browser.c 269 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527
  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 (512u * 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_ARENA_MAX (24u * 1024u * 1024u)
  43. #define BR_IMG_LAYOUT_W 1000
  44. /* An image job may hold a fetch helper this long. The page/script
  45. * deadline (UHTTP_TOTAL_TIMEOUT_MS) is minutes; one unreachable image host
  46. * must not starve the other images of all four helpers that long. */
  47. #define BR_IMG_JOB_TIMEOUT_MS 30000u
  48. #define BR_CSS_MAX (832u * 1024u)
  49. #define BR_CSS_COMP_MAX (192u * 1024u)
  50. /* Scripts and ES modules: Vite bundles reach ~1.7 MB (the Cloudron
  51. * dashboard's main chunk); the helper's FETCH_MAX is the same 2 MB. */
  52. #define BR_SCRIPT_MAX (2u * 1024u * 1024u)
  53. #define FETCH_ABORT (-2)
  54. /* Session cache for remote stylesheets (per launch; cleared at startup). */
  55. #define CSS_CACHE_MAX 16
  56. #define CSS_CACHE_FILE_MAX (256u * 1024u)
  57. #define CSS_CACHE_PREFIX "bcss-"
  58. #define SCRIPT_CACHE_MAX 24
  59. #define SCRIPT_CACHE_FILE_MAX BR_SCRIPT_MAX
  60. #define SCRIPT_CACHE_PREFIX "bjs-"
  61. #define BR_MAX_SHEETS 6
  62. #define BR_HISTORY 16
  63. #define BR_URL_MAX 512
  64. #define BR_STATUS_MAX 200
  65. #define BR_IMG_RGB565(r, g, b) \
  66. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  67. #define BR_GRAY 0x8410
  68. enum {
  69. ID_URL = 1,
  70. ID_GO,
  71. ID_BACK,
  72. ID_FORWARD,
  73. ID_RELOAD,
  74. ID_HOME
  75. };
  76. #define ACT_NAV (1u << 0)
  77. #define ACT_BACK (1u << 1)
  78. #define ACT_FORWARD (1u << 2)
  79. #define ACT_RELOAD (1u << 3)
  80. #define ACT_HOME (1u << 4)
  81. #define ACT_CLOSE (1u << 5)
  82. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  83. ACT_HOME | ACT_CLOSE)
  84. struct br_image {
  85. int state; /* 0 empty, 1 ready */
  86. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  87. int native_w, native_h;
  88. char err[32];
  89. };
  90. static struct ngui ui;
  91. static struct ngui_input url_in;
  92. static struct ngui_scroll page_scroll;
  93. static struct br_doc doc;
  94. static struct br_image images[BR_MAX_IMAGES];
  95. static int image_count;
  96. static unsigned int image_pixels;
  97. /* Painted border boxes, in page/screen coordinates (layout starts at
  98. * page_rect.y + 4 - scroll). getBoundingClientRect() subtracts page_rect. */
  99. struct br_layout_box {
  100. int x, y;
  101. int w, h;
  102. unsigned char valid;
  103. };
  104. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  105. /* Images are loaded one per main-loop iteration so the parsed page stays
  106. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  107. static int preload_active;
  108. static int preload_max_jobs;
  109. static int preload_pending;
  110. static int preload_wait;
  111. static unsigned int preload_node;
  112. static int preload_loaded;
  113. static int preload_scroll;
  114. static int preload_rescan;
  115. static char post_status_text[BR_STATUS_MAX];
  116. static int post_status_error;
  117. static unsigned int post_status_ttl;
  118. /* Content-relative position/height of each <img>, recorded by the measure
  119. * pass so image loading can be deferred until it is near the viewport. */
  120. static unsigned short img_top[BR_MAX_NODES];
  121. static unsigned short img_h[BR_MAX_NODES];
  122. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  123. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  124. * body. Decode arenas are allocated per image instead of living here. */
  125. static unsigned char *image_io_buf;
  126. static struct ufont_face *font_faces[BR_MAX_FACES];
  127. #define image_file_buf (image_io_buf)
  128. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  129. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  130. static struct inflate image_inflate_ws;
  131. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  132. #error "CSS scratch must fit in image_io_buf"
  133. #endif
  134. static char page_url[BR_URL_MAX];
  135. static char page_title[BR_TITLE_MAX];
  136. static char cwd[64];
  137. static int page_is_local;
  138. static int page_loading;
  139. static char status_text[BR_STATUS_MAX];
  140. static unsigned int status_until;
  141. static int status_error;
  142. static char history[BR_HISTORY][BR_URL_MAX];
  143. static int hist_len, hist_pos;
  144. static char click_url[BR_URL_MAX];
  145. static char pending_url[BR_URL_MAX];
  146. #define BR_POST_MAX 4096
  147. static char pending_post[BR_POST_MAX];
  148. static unsigned int pending_post_len;
  149. /* The pending navigation is a POST even when its body is empty (a form
  150. * without fields, e.g. the OIDC consent auto-submit). */
  151. static int pending_post_is;
  152. static unsigned int pending_action;
  153. static int cancel_fetch;
  154. static int quit;
  155. static struct ngui_rect page_rect;
  156. static unsigned short *page_backbuf;
  157. static int pagebuf_w, pagebuf_h;
  158. static int page_cache_valid;
  159. static int page_cache_scroll;
  160. static unsigned int page_cache_nnode;
  161. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  162. static int layout_valid, layout_left, layout_right;
  163. static unsigned int layout_nnode;
  164. static int layout_content_h;
  165. /* layout output */
  166. struct lay_run {
  167. unsigned int off;
  168. unsigned short len;
  169. unsigned short gap;
  170. unsigned short color;
  171. unsigned short href;
  172. char lit[28];
  173. short img;
  174. signed short dy; /* inline image vertical offset */
  175. unsigned short iw, ih;
  176. unsigned short w;
  177. unsigned char font_px, bold, italic, mono, underline, strike;
  178. unsigned char overline, font_face;
  179. unsigned char transform_scale;
  180. unsigned char origin_x_kind, origin_y_kind;
  181. signed short scale_x, scale_y, rotate_x100;
  182. signed short origin_x, origin_y;
  183. unsigned char has_lit;
  184. unsigned int form; /* node + 1, 0 = not a control */
  185. unsigned char form_kind;
  186. unsigned char form_disabled;
  187. };
  188. struct lay {
  189. int draw;
  190. struct ngui *ui;
  191. int left, right;
  192. int y;
  193. int line_x, line_y, line_h;
  194. int line_left, line_right;
  195. int parent_top;
  196. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  197. int run_x;
  198. int align;
  199. int depth;
  200. int space_pending;
  201. unsigned char float_active;
  202. int float_left, float_right, float_bottom;
  203. struct lay_run runs[96];
  204. int nruns;
  205. };
  206. struct hit {
  207. int x, y, w, h;
  208. unsigned short node;
  209. };
  210. /* Live form state; the DOM attributes stay the initial/default value. */
  211. #define FORM_MAX 64
  212. #define FORM_VALUE_MAX 63
  213. enum {
  214. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  215. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  216. };
  217. struct form_state {
  218. unsigned int node;
  219. char value[FORM_VALUE_MAX + 1];
  220. unsigned char len, caret, checked, selected, used;
  221. };
  222. static struct form_state form_states[FORM_MAX];
  223. static unsigned int form_focus;
  224. static unsigned int form_dirty;
  225. static int form_descendant(unsigned int node, unsigned int form);
  226. static int form_submit_form(unsigned int node, int fire_event);
  227. static int link_fragment_nav(unsigned int node);
  228. static void history_push(const char *url);
  229. static void form_reset_event(unsigned int form);
  230. static unsigned int s_len(const char *s);
  231. static int s_eq(const char *a, const char *b);
  232. static void form_key(int k);
  233. static void form_click(unsigned int node);
  234. static void style_for_node(unsigned int node, struct br_style *out);
  235. static int form_disabled(unsigned int node)
  236. {
  237. struct br_node *n = &doc.nodes[node];
  238. if (n->attr_flags & BR_ATTR_DISABLED)
  239. return 1;
  240. return br_find_attr(&doc, node, "disabled") != 0;
  241. }
  242. static int form_kind_of(unsigned int node)
  243. {
  244. const char *type = br_type(&doc, node);
  245. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  246. return FORM_TEXTAREA;
  247. if (doc.nodes[node].tag == BR_TAG_SELECT)
  248. return FORM_SELECT;
  249. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  250. if (s_eq(type, "reset"))
  251. return FORM_RESET;
  252. if (s_eq(type, "button"))
  253. return FORM_BUTTON;
  254. return FORM_SUBMIT;
  255. }
  256. if (s_eq(type, "password"))
  257. return FORM_PASSWORD;
  258. if (s_eq(type, "checkbox"))
  259. return FORM_CHECKBOX;
  260. if (s_eq(type, "radio"))
  261. return FORM_RADIO;
  262. if (s_eq(type, "submit"))
  263. return FORM_SUBMIT;
  264. if (s_eq(type, "reset"))
  265. return FORM_RESET;
  266. if (s_eq(type, "button"))
  267. return FORM_BUTTON;
  268. return FORM_TEXT;
  269. }
  270. static unsigned int form_option_count(unsigned int node)
  271. {
  272. unsigned int c, n = 0;
  273. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  274. if (doc.nodes[c].type == BR_NODE_ELEM &&
  275. doc.nodes[c].tag == BR_TAG_OPTION)
  276. n++;
  277. return n;
  278. }
  279. static unsigned int form_option_selected(unsigned int node)
  280. {
  281. unsigned int c, i = 0;
  282. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  283. if (doc.nodes[c].type != BR_NODE_ELEM ||
  284. doc.nodes[c].tag != BR_TAG_OPTION)
  285. continue;
  286. if (br_find_attr(&doc, c, "selected"))
  287. return i;
  288. i++;
  289. }
  290. return 0;
  291. }
  292. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  293. char *out, unsigned int cap)
  294. {
  295. unsigned int c, i = 0;
  296. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  297. if (doc.nodes[c].type != BR_NODE_ELEM ||
  298. doc.nodes[c].tag != BR_TAG_OPTION)
  299. continue;
  300. if (i == idx)
  301. return br_text_content(&doc, c, out, cap);
  302. i++;
  303. }
  304. return 0;
  305. }
  306. static struct form_state *form_get(unsigned int node, int create)
  307. {
  308. struct form_state *slot = 0;
  309. unsigned int i;
  310. for (i = 0; i < FORM_MAX; i++) {
  311. if (form_states[i].used) {
  312. if (form_states[i].node == node)
  313. return &form_states[i];
  314. } else if (!slot) {
  315. slot = &form_states[i];
  316. }
  317. }
  318. if (!create || !slot)
  319. return 0;
  320. slot->node = node;
  321. slot->len = 0;
  322. slot->caret = 0;
  323. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  324. slot->selected = form_option_selected(node);
  325. slot->used = 1;
  326. {
  327. unsigned int n = 0;
  328. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  329. n = br_text_content(&doc, node, slot->value,
  330. FORM_VALUE_MAX + 1);
  331. } else {
  332. const char *v = br_value(&doc, node);
  333. if (v) {
  334. n = s_len(v);
  335. if (n > FORM_VALUE_MAX)
  336. n = FORM_VALUE_MAX;
  337. for (unsigned int j = 0; j < n; j++)
  338. slot->value[j] = v[j];
  339. }
  340. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  341. n = br_text_content(&doc, node, slot->value,
  342. FORM_VALUE_MAX + 1);
  343. }
  344. if (n > FORM_VALUE_MAX)
  345. n = FORM_VALUE_MAX;
  346. slot->value[n] = '\0';
  347. slot->len = (unsigned char)n;
  348. slot->caret = (unsigned char)n;
  349. }
  350. return slot;
  351. }
  352. static void form_reset_state(void)
  353. {
  354. unsigned int i;
  355. for (i = 0; i < FORM_MAX; i++)
  356. form_states[i].used = 0;
  357. form_focus = 0;
  358. }
  359. static int form_is_control(unsigned int node)
  360. {
  361. unsigned int tag;
  362. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  363. return 0;
  364. tag = doc.nodes[node].tag;
  365. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  366. tag == BR_TAG_SELECT || tag == BR_TAG_BUTTON;
  367. }
  368. #define HIT_MAX 96
  369. static struct hit hits[HIT_MAX];
  370. static int nhits;
  371. static unsigned short block_h[BR_MAX_NODES];
  372. /* Measure-pass top of each block, in the same document coordinates as
  373. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  374. * paint, so it cannot drive the lazy background loader). */
  375. static unsigned short block_top[BR_MAX_NODES];
  376. static char li_marker[BR_MAX_NODES][12];
  377. /* one connection object; the browser fetches one resource at a time */
  378. /* ---- tiny strings ---- */
  379. static unsigned int s_len(const char *s)
  380. {
  381. unsigned int n = 0;
  382. while (s && s[n])
  383. n++;
  384. return n;
  385. }
  386. static void s_copy(char *d, const char *s, unsigned int cap)
  387. {
  388. unsigned int i = 0;
  389. if (!cap)
  390. return;
  391. while (s && s[i] && i + 1 < cap) {
  392. d[i] = s[i];
  393. i++;
  394. }
  395. d[i] = '\0';
  396. }
  397. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  398. {
  399. while (s && *s && *n + 1 < cap)
  400. d[(*n)++] = *s++;
  401. d[*n] = '\0';
  402. }
  403. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  404. unsigned int cap)
  405. {
  406. char tmp[12];
  407. unsigned int i = 0, j;
  408. do {
  409. tmp[i++] = (char)('0' + v % 10);
  410. v /= 10;
  411. } while (v && i < sizeof(tmp));
  412. for (j = 0; j < i && *n + 1 < cap; j++)
  413. d[(*n)++] = tmp[i - 1 - j];
  414. d[*n] = '\0';
  415. }
  416. static int s_eq(const char *a, const char *b)
  417. {
  418. while (*a && *b) {
  419. if (*a != *b)
  420. return 0;
  421. a++;
  422. b++;
  423. }
  424. return *a == *b;
  425. }
  426. static int starts_with(const char *s, const char *p)
  427. {
  428. unsigned int i = 0;
  429. while (p[i]) {
  430. if (s[i] != p[i])
  431. return 0;
  432. i++;
  433. }
  434. return 1;
  435. }
  436. static int contains_ci(const char *s, const char *p)
  437. {
  438. unsigned int i, j;
  439. for (i = 0; s[i]; i++) {
  440. for (j = 0; p[j]; j++) {
  441. char a = s[i + j];
  442. if (a >= 'A' && a <= 'Z')
  443. a = (char)(a - 'A' + 'a');
  444. if (a != p[j])
  445. break;
  446. }
  447. if (!p[j])
  448. return 1;
  449. }
  450. return 0;
  451. }
  452. static char *trim(char *s)
  453. {
  454. unsigned int n;
  455. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  456. s++;
  457. n = s_len(s);
  458. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  459. s[n - 1] == '\r' || s[n - 1] == '\n'))
  460. s[--n] = '\0';
  461. return s;
  462. }
  463. /* ---- per-process heap ---- */
  464. static int heap_start(void)
  465. {
  466. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  467. if (!image_io_buf)
  468. return -1;
  469. page_backbuf = (unsigned short *)malloc(
  470. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  471. pagebuf_w = page_backbuf ? ui.w : 0;
  472. pagebuf_h = page_backbuf ? ui.h : 0;
  473. page_cache_valid = 0;
  474. return 0;
  475. }
  476. static void heap_clear(void)
  477. {
  478. memset(font_faces, 0, sizeof(font_faces));
  479. ngui_font_detach(&ui);
  480. svg_cache_clear();
  481. decode_arena = 0; /* lives in the page heap too */
  482. decode_arena_size = 0;
  483. heap_reset();
  484. /* The document arenas live in that heap; drop the stale pointers so
  485. * the next br_parse_plain() allocates fresh ones. */
  486. doc.nodes = 0;
  487. doc.text = 0;
  488. doc.attrs = 0;
  489. image_io_buf = 0;
  490. page_backbuf = 0;
  491. pagebuf_w = pagebuf_h = 0;
  492. page_cache_valid = 0;
  493. }
  494. static void browser_rules_alloc(void)
  495. {
  496. struct br_rule *rules;
  497. rules = (struct br_rule *)malloc(
  498. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  499. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  500. }
  501. /* ---- status ---- */
  502. static void set_status(const char *s, int err, unsigned int ttl_ms)
  503. {
  504. s_copy(status_text, s, sizeof(status_text));
  505. status_error = err;
  506. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  507. ngui_invalidate(&ui);
  508. }
  509. /* ---- JavaScript ---- */
  510. static int resolve_link(const char *base, const char *href, char *out,
  511. unsigned int cap);
  512. static char js_last_status[BR_STATUS_MAX];
  513. static int js_last_error;
  514. static void js_host_status(const char *msg, int error)
  515. {
  516. s_copy(js_last_status, msg, sizeof(js_last_status));
  517. js_last_error = error;
  518. set_status(msg, error, 6000);
  519. }
  520. static void js_host_report(const char *msg)
  521. {
  522. u_puts("[js] ");
  523. u_puts(msg);
  524. u_putc('\n');
  525. s_copy(js_last_status, msg, sizeof(js_last_status));
  526. js_last_error = 1;
  527. set_status(msg, 1, 8000);
  528. }
  529. static void js_host_navigate(const char *url)
  530. {
  531. char resolved[BR_URL_MAX];
  532. if (!url || !url[0])
  533. return;
  534. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  535. return;
  536. s_copy(pending_url, resolved, sizeof(pending_url));
  537. pending_action |= ACT_NAV;
  538. cancel_fetch = 1;
  539. }
  540. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  541. * back/forward between fragments): the page URL, address bar and history
  542. * follow, nothing is reloaded. `push` adds a history entry. */
  543. static int page_set_fragment(const char *url, int push)
  544. {
  545. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  546. return -1;
  547. s_copy(page_url, url, sizeof(page_url));
  548. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  549. url_in.len = s_len(url_in.text);
  550. url_in.cursor = url_in.len;
  551. url_in.scroll = 0;
  552. if (push)
  553. history_push(page_url);
  554. ngui_invalidate(&ui);
  555. return 0;
  556. }
  557. static int js_host_set_hash(const char *url)
  558. {
  559. return page_set_fragment(url, 1);
  560. }
  561. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  562. * the page, so a hash router can react). */
  563. static int same_doc_fragment(const char *url)
  564. {
  565. unsigned int a = 0, b = 0;
  566. if (!js_browser_active() || !url)
  567. return 0;
  568. while (url[a] && url[a] != '#')
  569. a++;
  570. while (page_url[b] && page_url[b] != '#')
  571. b++;
  572. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  573. !s_eq(url, page_url);
  574. }
  575. static void js_host_changed(void)
  576. {
  577. /* Class/style/attribute mutations change computed styles, not just the
  578. * text: drop the per-node style cache before the next layout. */
  579. br_reset_styles(&doc);
  580. layout_valid = 0;
  581. /* Script-built content (Angular's ng-repeat cards) brings new images
  582. * and inline background styles: rescan once the main loop is idle. */
  583. preload_rescan = 1;
  584. ngui_invalidate(&ui);
  585. }
  586. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  587. {
  588. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  589. return 0;
  590. *x = layout_boxes[node].x - page_rect.x;
  591. *y = layout_boxes[node].y - page_rect.y;
  592. *w = layout_boxes[node].w;
  593. *h = layout_boxes[node].h;
  594. return 1;
  595. }
  596. static void form_copy_out(const char *s, char *buf, int cap)
  597. {
  598. int i = 0;
  599. if (!buf || cap <= 0)
  600. return;
  601. while (s && s[i] && i + 1 < cap) {
  602. buf[i] = s[i];
  603. i++;
  604. }
  605. buf[i] = '\0';
  606. }
  607. static int js_host_form_value(unsigned int node, char *buf, int cap)
  608. {
  609. struct form_state *fs;
  610. int kind;
  611. if (!form_is_control(node))
  612. return 0;
  613. kind = form_kind_of(node);
  614. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  615. return 0;
  616. if (kind == FORM_SELECT) {
  617. char opt[64] = "";
  618. unsigned int c, i = 0;
  619. fs = form_get(node, 1);
  620. if (!fs)
  621. return 0;
  622. form_option_text(node, fs->selected, opt, sizeof(opt));
  623. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  624. if (doc.nodes[c].type != BR_NODE_ELEM ||
  625. doc.nodes[c].tag != BR_TAG_OPTION)
  626. continue;
  627. if (i == fs->selected) {
  628. const char *v = br_value(&doc, c);
  629. if (v && v[0])
  630. form_copy_out(v, buf, cap);
  631. else
  632. form_copy_out(opt, buf, cap);
  633. return 1;
  634. }
  635. i++;
  636. }
  637. form_copy_out(opt, buf, cap);
  638. return 1;
  639. }
  640. fs = form_get(node, 1);
  641. if (!fs)
  642. return 0;
  643. form_copy_out(fs->value, buf, cap);
  644. return 1;
  645. }
  646. static int js_host_form_checked(unsigned int node)
  647. {
  648. struct form_state *fs;
  649. int kind;
  650. if (!form_is_control(node))
  651. return -1;
  652. kind = form_kind_of(node);
  653. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  654. return -1;
  655. fs = form_get(node, 1);
  656. return fs ? fs->checked : 0;
  657. }
  658. static int js_host_form_selected(unsigned int node)
  659. {
  660. struct form_state *fs;
  661. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  662. return -1;
  663. fs = form_get(node, 1);
  664. return fs ? fs->selected : 0;
  665. }
  666. static int js_host_form_set_value(unsigned int node, const char *value)
  667. {
  668. struct form_state *fs;
  669. unsigned int n;
  670. if (!form_is_control(node))
  671. return 0;
  672. fs = form_get(node, 1);
  673. if (!fs)
  674. return 0;
  675. n = s_len(value ? value : "");
  676. if (n > FORM_VALUE_MAX)
  677. n = FORM_VALUE_MAX;
  678. for (unsigned int i = 0; i < n; i++)
  679. fs->value[i] = value[i];
  680. fs->value[n] = '\0';
  681. fs->len = (unsigned char)n;
  682. fs->caret = (unsigned char)n;
  683. layout_valid = 0;
  684. ngui_invalidate(&ui);
  685. return 1;
  686. }
  687. static int js_host_form_set_checked(unsigned int node, int checked)
  688. {
  689. struct form_state *fs;
  690. int kind;
  691. if (!form_is_control(node))
  692. return 0;
  693. kind = form_kind_of(node);
  694. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  695. return 0;
  696. fs = form_get(node, 1);
  697. if (!fs)
  698. return 0;
  699. fs->checked = (unsigned char)(checked != 0);
  700. layout_valid = 0;
  701. ngui_invalidate(&ui);
  702. return 1;
  703. }
  704. static int js_host_form_set_selected(unsigned int node, int index)
  705. {
  706. struct form_state *fs;
  707. unsigned int n;
  708. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  709. return 0;
  710. fs = form_get(node, 1);
  711. if (!fs)
  712. return 0;
  713. n = form_option_count(node);
  714. if (index < 0)
  715. index = 0;
  716. if (n && (unsigned int)index >= n)
  717. index = (int)n - 1;
  718. fs->selected = (unsigned char)index;
  719. layout_valid = 0;
  720. ngui_invalidate(&ui);
  721. return 1;
  722. }
  723. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  724. {
  725. unsigned int i;
  726. int n = 0;
  727. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  728. doc.nodes[form].tag != BR_TAG_FORM)
  729. return 0;
  730. for (i = 0; i < doc.nnode && n < cap; i++) {
  731. struct br_node *nd = &doc.nodes[i];
  732. if (i == form || nd->type != BR_NODE_ELEM)
  733. continue;
  734. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  735. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  736. continue;
  737. if (!form_descendant(i, form))
  738. continue;
  739. out[n++] = i;
  740. }
  741. return n;
  742. }
  743. static int js_host_form_submit(unsigned int form)
  744. {
  745. form_submit_form(form, 0);
  746. return 1;
  747. }
  748. static int js_host_form_reset(unsigned int form)
  749. {
  750. form_reset_event(form);
  751. return 1;
  752. }
  753. static void css_computed_name(const char *p, char *out, int cap)
  754. {
  755. int n = 0;
  756. for (; p && *p && n + 2 < cap; p++) {
  757. char c = *p;
  758. if (c >= 'A' && c <= 'Z') {
  759. out[n++] = '-';
  760. c = (char)(c - 'A' + 'a');
  761. } else if (c == '_') {
  762. c = '-';
  763. } else if (c >= 'a' && c <= 'z') {
  764. /* keep */
  765. }
  766. out[n++] = c;
  767. }
  768. out[n] = '\0';
  769. if (!strcmp(out, "css-float"))
  770. strcpy(out, "float");
  771. }
  772. static void css_rgb(unsigned short c, char *buf, int cap)
  773. {
  774. int r = ((c >> 11) & 31) * 255 / 31;
  775. int g = ((c >> 5) & 63) * 255 / 63;
  776. int b = (c & 31) * 255 / 31;
  777. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  778. }
  779. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  780. int font_px)
  781. {
  782. if (unit == 4) {
  783. snprintf(buf, cap, "auto");
  784. } else if (unit == 0) {
  785. snprintf(buf, cap, "%dpx", raw);
  786. } else if (unit == 1) {
  787. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  788. } else if (unit == 2) {
  789. /* Chrome's getComputedStyle() reports used pixel values. */
  790. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  791. } else if (unit == 3) {
  792. snprintf(buf, cap, "%dpx",
  793. (int)br_root_font_px() * raw / 100);
  794. } else {
  795. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  796. raw / 100, raw % 100, px);
  797. }
  798. }
  799. static int js_host_computed(unsigned int node, const char *property,
  800. char *buf, int cap)
  801. {
  802. struct br_style st;
  803. char name[40];
  804. if (!buf || cap <= 0 || node >= doc.nnode || node == 0)
  805. return 0;
  806. buf[0] = '\0';
  807. css_computed_name(property, name, sizeof(name));
  808. style_for_node(node, &st);
  809. if (!strcmp(name, "display")) {
  810. const char *v = "inline";
  811. if (st.display == BR_DISPLAY_BLOCK)
  812. v = "block";
  813. else if (st.display == BR_DISPLAY_NONE)
  814. v = "none";
  815. else if (st.display == BR_DISPLAY_FLEX)
  816. v = "flex";
  817. else if (st.display == BR_DISPLAY_GRID)
  818. v = "grid";
  819. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  820. v = "inline-block";
  821. snprintf(buf, cap, "%s", v);
  822. } else if (!strcmp(name, "position")) {
  823. static const char *pos[] = {
  824. "static", "absolute", "fixed", "relative", "sticky"
  825. };
  826. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  827. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  828. int is_w = name[0] == 'w';
  829. int kind = is_w ? st.width_kind : st.height_kind;
  830. int val = is_w ? st.width : st.height;
  831. if (kind == 3) {
  832. if (is_w)
  833. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  834. st.width_calc_pct / 100,
  835. st.width_calc_pct % 100,
  836. st.width_calc_px);
  837. else
  838. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  839. st.height_calc_pct / 100,
  840. st.height_calc_pct % 100,
  841. st.height_calc_px);
  842. } else if (kind == 1) {
  843. snprintf(buf, cap, "%dpx", val);
  844. } else if (kind == 2) {
  845. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  846. } else {
  847. snprintf(buf, cap, "auto");
  848. }
  849. } else if (!strcmp(name, "color") ||
  850. !strcmp(name, "background-color")) {
  851. if (!strcmp(name, "background-color") && !st.has_bg)
  852. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  853. else
  854. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  855. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  856. int is_fill = name[0] == 'f';
  857. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  858. if (mode == BR_PAINT_COLOR)
  859. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  860. else if (mode == BR_PAINT_CURRENT)
  861. css_rgb(st.color, buf, cap);
  862. else if (mode == BR_PAINT_UNSET && is_fill)
  863. snprintf(buf, cap, "rgb(0, 0, 0)");
  864. else if (mode == BR_PAINT_URL)
  865. snprintf(buf, cap, "url()");
  866. else
  867. snprintf(buf, cap, "none");
  868. } else if (!strcmp(name, "font-size")) {
  869. snprintf(buf, cap, "%dpx", st.font_px);
  870. } else if (!strcmp(name, "font-weight")) {
  871. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  872. } else if (!strcmp(name, "font-style")) {
  873. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  874. } else if (!strcmp(name, "font-family")) {
  875. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  876. br_font_face_family(st.font_face)[0])
  877. snprintf(buf, cap, "%s",
  878. br_font_face_family(st.font_face));
  879. else
  880. snprintf(buf, cap, "%s",
  881. st.mono ? "monospace" : "sans-serif");
  882. } else if (!strcmp(name, "text-align")) {
  883. static const char *al[] = { "left", "center", "right", "justify" };
  884. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  885. } else if (!strcmp(name, "float")) {
  886. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  887. st.float_left == 2 ? "right" : "none");
  888. } else if (!strcmp(name, "clear")) {
  889. static const char *cl[] = { "none", "left", "right", "both" };
  890. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  891. } else if (!strcmp(name, "opacity")) {
  892. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  893. } else if (!strcmp(name, "visibility")) {
  894. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  895. } else if (!strcmp(name, "overflow")) {
  896. snprintf(buf, cap, "%s",
  897. st.overflow_hidden ? "hidden" : "visible");
  898. } else if (!strcmp(name, "white-space")) {
  899. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  900. } else if (!strcmp(name, "text-transform")) {
  901. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  902. } else if (!strcmp(name, "box-sizing")) {
  903. snprintf(buf, cap, "%s",
  904. st.box_sizing ? "border-box" : "content-box");
  905. } else if (!strcmp(name, "line-height")) {
  906. if (st.line_h_px)
  907. snprintf(buf, cap, "%dpx", st.line_h_px);
  908. else if (st.line_h_pct)
  909. snprintf(buf, cap, "%d%%", st.line_h_pct);
  910. else
  911. snprintf(buf, cap, "normal");
  912. } else if (!strcmp(name, "z-index")) {
  913. if (st.z_set)
  914. snprintf(buf, cap, "%d", st.z_index);
  915. else
  916. snprintf(buf, cap, "auto");
  917. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  918. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  919. int set = name[0] == 't' ? st.top_set :
  920. name[0] == 'l' ? st.left_set :
  921. name[0] == 'r' ? st.right_set : st.bottom_set;
  922. int v = name[0] == 't' ? st.top :
  923. name[0] == 'l' ? st.left :
  924. name[0] == 'r' ? st.right : st.bottom;
  925. if (set)
  926. snprintf(buf, cap, "%dpx", v);
  927. else
  928. snprintf(buf, cap, "auto");
  929. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  930. !strcmp(name, "margin-bottom") ||
  931. !strcmp(name, "margin-left") ||
  932. !strcmp(name, "padding-top") ||
  933. !strcmp(name, "padding-right") ||
  934. !strcmp(name, "padding-bottom") ||
  935. !strcmp(name, "padding-left")) {
  936. int is_pad = name[0] == 'p';
  937. int side = name[strlen(name) - 1] == 'p' ? 0 :
  938. name[strlen(name) - 1] == 't' ? 1 :
  939. name[strlen(name) - 1] == 'm' ? 2 : 3;
  940. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  941. if (!strcmp(name, "margin-right") ||
  942. !strcmp(name, "padding-right"))
  943. side = 1;
  944. else if (!strcmp(name, "margin-bottom") ||
  945. !strcmp(name, "padding-bottom"))
  946. side = 2;
  947. else if (!strcmp(name, "margin-left") ||
  948. !strcmp(name, "padding-left"))
  949. side = 3;
  950. else
  951. side = 0;
  952. side += is_pad ? 4 : 0;
  953. css_mp_value(buf, cap,
  954. side == 0 ? st.mt : side == 1 ? st.mr :
  955. side == 2 ? st.mb : side == 3 ? st.ml :
  956. side == 4 ? st.pt : side == 5 ? st.pr :
  957. side == 6 ? st.pb : st.pl,
  958. st.mp_unit[side], st.mp_calc_px[side],
  959. st.font_px);
  960. } else if (!strcmp(name, "border-top-width") ||
  961. !strcmp(name, "border-right-width") ||
  962. !strcmp(name, "border-bottom-width") ||
  963. !strcmp(name, "border-left-width")) {
  964. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  965. name[7] == 'b' ? 2 : 3;
  966. snprintf(buf, cap, "%dpx", st.border_w[side]);
  967. } else if (!strcmp(name, "border-top-color") ||
  968. !strcmp(name, "border-right-color") ||
  969. !strcmp(name, "border-bottom-color") ||
  970. !strcmp(name, "border-left-color")) {
  971. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  972. name[7] == 'b' ? 2 : 3;
  973. if (st.border_w[side] && !st.border_t[side])
  974. css_rgb(st.border_c[side], buf, cap);
  975. else
  976. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  977. } else if (!strcmp(name, "background-image")) {
  978. if (st.bg_image)
  979. snprintf(buf, cap, "url(\"%s\")",
  980. br_bg_image_url(st.bg_image - 1));
  981. else
  982. snprintf(buf, cap, "none");
  983. } else if (!strcmp(name, "background-repeat")) {
  984. static const char *rp[] = {
  985. "repeat", "no-repeat", "repeat-x", "repeat-y"
  986. };
  987. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  988. st.bg_repeat : 0]);
  989. } else if (!strcmp(name, "background-position")) {
  990. if (st.bg_pos_x_kind == 1)
  991. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  992. st.bg_pos_y);
  993. else
  994. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  995. st.bg_pos_y);
  996. } else if (!strcmp(name, "background-size")) {
  997. if (st.bg_size_kind == 3)
  998. snprintf(buf, cap, "cover");
  999. else if (st.bg_size_kind == 4)
  1000. snprintf(buf, cap, "contain");
  1001. else if (st.bg_size_kind == 1)
  1002. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1003. st.bg_size_h);
  1004. else if (st.bg_size_kind == 2)
  1005. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1006. st.bg_size_h);
  1007. else
  1008. snprintf(buf, cap, "auto");
  1009. } else if (!strcmp(name, "transform")) {
  1010. char tmp[128];
  1011. unsigned int n = 0;
  1012. if (!st.transform_set) {
  1013. snprintf(buf, cap, "none");
  1014. } else {
  1015. tmp[0] = '\0';
  1016. if (st.tx || st.ty) {
  1017. snprintf(tmp + n, sizeof(tmp) - n,
  1018. "translate(%dpx, %dpx)", st.tx, st.ty);
  1019. n = (unsigned int)strlen(tmp);
  1020. }
  1021. if (st.transform_scale) {
  1022. snprintf(tmp + n, sizeof(tmp) - n,
  1023. "%sscale(%d.%02d, %d.%02d)",
  1024. n ? " " : "", st.scale_x / 100,
  1025. st.scale_x % 100, st.scale_y / 100,
  1026. st.scale_y % 100);
  1027. n = (unsigned int)strlen(tmp);
  1028. if (st.rotate_x100) {
  1029. snprintf(tmp + n, sizeof(tmp) - n,
  1030. " rotate(%d.%02ddeg)",
  1031. st.rotate_x100 / 100,
  1032. st.rotate_x100 % 100);
  1033. }
  1034. } else if (st.rotate_x100) {
  1035. snprintf(tmp + n, sizeof(tmp) - n,
  1036. "%srotate(%d.%02ddeg)",
  1037. n ? " " : "", st.rotate_x100 / 100,
  1038. st.rotate_x100 % 100);
  1039. }
  1040. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1041. }
  1042. } else {
  1043. return 0;
  1044. }
  1045. return buf[0] != '\0';
  1046. }
  1047. static int js_host_click(unsigned int node)
  1048. {
  1049. char url[BR_URL_MAX];
  1050. const char *href;
  1051. if (node >= doc.nnode)
  1052. return 0;
  1053. if (form_is_control(node)) {
  1054. form_click(node); /* dispatches its own click event */
  1055. return 1;
  1056. }
  1057. /* element.click() fires a bubbling, cancelable click before the
  1058. * default action, like a real click (delegated list handlers). */
  1059. if (!js_browser_event(node, "click", 1, 1))
  1060. return 1;
  1061. if (link_fragment_nav(node))
  1062. return 1;
  1063. href = br_href(&doc, node);
  1064. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1065. return 0;
  1066. s_copy(pending_url, url, sizeof(pending_url));
  1067. pending_action |= ACT_NAV;
  1068. cancel_fetch = 1;
  1069. ngui_invalidate(&ui);
  1070. return 1;
  1071. }
  1072. static int fetch_script_text(const char *url, unsigned char **out,
  1073. unsigned int *outlen, char *err,
  1074. unsigned int errcap);
  1075. struct fetch_worker;
  1076. static struct fetch_worker *fetch_worker_alloc(void);
  1077. static void fetch_worker_release(struct fetch_worker *w);
  1078. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1079. unsigned int cap, const char *post,
  1080. unsigned int post_len, unsigned int node,
  1081. int bg, char *err, unsigned int errcap);
  1082. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1083. unsigned int errcap);
  1084. static int fetch_worker_read_body(struct fetch_worker *w,
  1085. unsigned char *plain,
  1086. unsigned int plaincap,
  1087. unsigned char *comp,
  1088. unsigned int compcap,
  1089. int *truncated, char *err,
  1090. unsigned int errcap);
  1091. static void fetch_workers_stop_all(void);
  1092. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1093. unsigned int cap, const char *method,
  1094. const char *ctype, const char *post,
  1095. unsigned int post_len, unsigned int node,
  1096. int bg, char *err, unsigned int errcap);
  1097. static int script_cache_has(const char *url);
  1098. static void script_cache_put(const char *url, const unsigned char *data,
  1099. unsigned int len);
  1100. static unsigned int script_cache_hash(const char *s);
  1101. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1102. unsigned int errcap);
  1103. static void fetch_workers_cancel_busy(void);
  1104. static void worker_wait_ui(void);
  1105. static int fetch_worker_status(const struct fetch_worker *w);
  1106. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1107. * module load: the wait must not pump input, or a click would dispatch DOM
  1108. * events into the middle of the running script. */
  1109. static int fetch_wait_passive;
  1110. static void script_error(const char *what, const char *url, const char *why)
  1111. {
  1112. char msg[192];
  1113. unsigned int n = 0;
  1114. s_append(msg, &n, what, sizeof(msg));
  1115. if (url && url[0]) {
  1116. s_append(msg, &n, " ", sizeof(msg));
  1117. s_append(msg, &n, url, sizeof(msg));
  1118. }
  1119. if (why && why[0]) {
  1120. s_append(msg, &n, ": ", sizeof(msg));
  1121. s_append(msg, &n, why, sizeof(msg));
  1122. }
  1123. js_host_report(msg);
  1124. }
  1125. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1126. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1127. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1128. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1129. #define JS_HTTP_POST_MAX (16u * 1024u)
  1130. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1131. static int js_worker_http(const char *method, const char *url,
  1132. const char *ctype, const char *body,
  1133. unsigned int body_len, struct js_http_resp *r,
  1134. char *err, int errcap);
  1135. static int js_host_http(const char *method, const char *url,
  1136. const char *ctype, const char *body,
  1137. unsigned int body_len, struct js_http_resp *r,
  1138. char *err, int errcap)
  1139. {
  1140. if (pending_action) {
  1141. s_copy(err, "page is navigating", (unsigned int)errcap);
  1142. return -1;
  1143. }
  1144. if (url[0] == '/') {
  1145. /* Local file: GET only. */
  1146. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1147. int rv;
  1148. if (!buf) {
  1149. s_copy(err, "out of memory", (unsigned int)errcap);
  1150. return -1;
  1151. }
  1152. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1153. (int)JS_HTTP_MAX);
  1154. r->status = rv < 0 ? 404 : 200;
  1155. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1156. buf[r->len] = '\0';
  1157. r->body = (char *)buf;
  1158. s_copy(r->url, url, sizeof(r->url));
  1159. if (contains_ci(url, ".json"))
  1160. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1161. return 0;
  1162. }
  1163. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1164. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1165. return -1;
  1166. }
  1167. if (body_len > JS_HTTP_POST_MAX) {
  1168. s_copy(err, "request body too large", (unsigned int)errcap);
  1169. return -1;
  1170. }
  1171. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1172. errcap);
  1173. }
  1174. /* Module source for the engine's loader: the boot script cache first, then
  1175. * one blocking fetch with input pumping disabled (the loader runs inside
  1176. * JavaScript). */
  1177. static char *js_host_load_script(const char *url, unsigned int *len)
  1178. {
  1179. unsigned char *data = 0;
  1180. char err[64];
  1181. int rv;
  1182. fetch_wait_passive++;
  1183. set_status("Loading module...", 0, 0);
  1184. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1185. fetch_wait_passive--;
  1186. if (rv != 0) {
  1187. script_error("Cannot load module", url,
  1188. rv == FETCH_ABORT ? "navigation" : err);
  1189. return 0;
  1190. }
  1191. return (char *)data;
  1192. }
  1193. /* Web Storage lives in /share, outside the page heap that every navigation
  1194. * resets: localStorage per origin for the boot, sessionStorage per origin
  1195. * and browser window. */
  1196. #define JS_ORIGIN_MAX 160
  1197. /* scheme://host[:port] of the page (a local page's whole path). */
  1198. static void js_page_origin(char *origin, unsigned int cap)
  1199. {
  1200. unsigned int i = 0, slashes = 0;
  1201. while (page_url[i] && i + 1 < cap) {
  1202. if (page_url[i] == '/' && ++slashes == 3)
  1203. break;
  1204. origin[i] = page_url[i];
  1205. i++;
  1206. }
  1207. origin[i] = '\0';
  1208. }
  1209. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1210. {
  1211. unsigned int n = 0;
  1212. s_append(out, &n, "/share/bls", cap);
  1213. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1214. }
  1215. static void js_storage_path(int kind, char *out, unsigned int cap)
  1216. {
  1217. char origin[JS_ORIGIN_MAX];
  1218. unsigned int n = 0;
  1219. js_page_origin(origin, sizeof(origin));
  1220. if (!kind) {
  1221. js_origin_path(origin, out, cap);
  1222. return;
  1223. }
  1224. s_append(out, &n, "/share/bss", cap);
  1225. if (kind) {
  1226. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1227. s_append(out, &n, "-", cap);
  1228. }
  1229. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1230. }
  1231. static void persist_mark_origin(const char *origin);
  1232. static int persist_store_lookup(const char *origin, char *out, int cap);
  1233. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1234. {
  1235. char path[48], origin[JS_ORIGIN_MAX];
  1236. int rv;
  1237. js_storage_path(kind, path, sizeof(path));
  1238. if (set) {
  1239. if (kind) {
  1240. if (!set[0] || !strcmp(set, "{}")) {
  1241. u_syscall1(SYS_UNLINK, (int)path);
  1242. return 0;
  1243. }
  1244. } else {
  1245. /* localStorage keeps an explicit "{}" rather than no
  1246. * file: a missing /share file means "not loaded from
  1247. * /data yet", and a cleared store must not come back
  1248. * from the disk copy before it is flushed. */
  1249. if (!set[0])
  1250. set = "{}";
  1251. js_page_origin(origin, sizeof(origin));
  1252. persist_mark_origin(origin);
  1253. }
  1254. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1255. (int)strlen(set)) < 0 ? -1 : 0;
  1256. }
  1257. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1258. if (rv < 0 && !kind) {
  1259. /* First use this boot: the persistent copy on /data. */
  1260. js_page_origin(origin, sizeof(origin));
  1261. rv = persist_store_lookup(origin, out, cap);
  1262. if (rv >= 0)
  1263. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1264. }
  1265. if (rv < 0)
  1266. return -1;
  1267. out[rv] = '\0';
  1268. return rv;
  1269. }
  1270. /* ---- persistence on /data ----
  1271. *
  1272. * /share is the working copy (RAM, shared by every helper and window); the
  1273. * installed disk's /data volume keeps the cookie jar and localStorage
  1274. * across reboots when it is mounted. The browser owns the disk copies: at
  1275. * start it restores the jar into /share, and its main loop writes back
  1276. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1277. * setItem updates costs one FAT write. The helpers only touch /share (they
  1278. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1279. * /data mount every disk access simply fails. Both files are plaintext
  1280. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1281. #define PERSIST_MS 3000u
  1282. #define SHARE_COOKIES "/share/bcookies"
  1283. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1284. #define DATA_STORE "/data/BSTORE.DAT"
  1285. #define DATA_STORE_MAGIC "NBLS1\n"
  1286. #define DATA_STORE_MAX (192u * 1024u)
  1287. #define PERSIST_DIRTY_MAX 8
  1288. static unsigned int persist_due;
  1289. static unsigned int cookie_sum_saved;
  1290. static int cookie_sum_valid;
  1291. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1292. static int persist_ndirty;
  1293. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1294. {
  1295. unsigned int h = 2166136261u, i;
  1296. for (i = 0; i < n; i++)
  1297. h = (h ^ p[i]) * 16777619u;
  1298. return h;
  1299. }
  1300. /* Called once at startup, before any helper runs. */
  1301. static void persist_restore(void)
  1302. {
  1303. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1304. int n;
  1305. if (!jar)
  1306. return;
  1307. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1308. (int)sizeof(struct uhttp_jar));
  1309. if (n != (int)sizeof(struct uhttp_jar)) {
  1310. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1311. (int)sizeof(struct uhttp_jar));
  1312. if (n == (int)sizeof(struct uhttp_jar)) {
  1313. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1314. (int)jar, n);
  1315. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1316. cookie_sum_valid = 1;
  1317. }
  1318. }
  1319. free(jar);
  1320. persist_due = u_ticks_ms() + PERSIST_MS;
  1321. }
  1322. static void persist_mark_origin(const char *origin)
  1323. {
  1324. int i;
  1325. for (i = 0; i < persist_ndirty; i++)
  1326. if (s_eq(persist_dirty[i], origin))
  1327. return;
  1328. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1329. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1330. }
  1331. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1332. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1333. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1334. unsigned int *o_off, unsigned int *o_len,
  1335. unsigned int *d_off, unsigned int *d_len,
  1336. unsigned int *rec_end)
  1337. {
  1338. unsigned int p = *pos, v = 0;
  1339. if (p >= len)
  1340. return 0;
  1341. *o_off = p;
  1342. while (p < len && buf[p] != '\n')
  1343. p++;
  1344. if (p >= len)
  1345. return 0;
  1346. *o_len = p - *o_off;
  1347. p++;
  1348. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1349. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1350. if (p >= len || buf[p] != '\n')
  1351. return 0;
  1352. p++;
  1353. if (v > len - p)
  1354. return 0;
  1355. *d_off = p;
  1356. *d_len = v;
  1357. p += v;
  1358. if (p < len && buf[p] == '\n')
  1359. p++;
  1360. *rec_end = p;
  1361. *pos = p;
  1362. return 1;
  1363. }
  1364. static int store_load(char **out)
  1365. {
  1366. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1367. int n;
  1368. *out = buf;
  1369. if (!buf)
  1370. return -1;
  1371. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1372. (int)DATA_STORE_MAX);
  1373. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1374. !starts_with(buf, DATA_STORE_MAGIC))
  1375. return 0;
  1376. return n;
  1377. }
  1378. static int persist_store_lookup(const char *origin, char *out, int cap)
  1379. {
  1380. char *buf;
  1381. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1382. unsigned int olen = s_len(origin);
  1383. int n = store_load(&buf), rv = -1;
  1384. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1385. &dl, &e)) {
  1386. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1387. if ((int)dl < cap) {
  1388. memcpy(out, buf + d, dl);
  1389. out[dl] = '\0';
  1390. rv = (int)dl;
  1391. }
  1392. break;
  1393. }
  1394. }
  1395. free(buf);
  1396. return rv;
  1397. }
  1398. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1399. static void persist_store_flush(void)
  1400. {
  1401. char *old, *nb, path[48];
  1402. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1403. int n = store_load(&old), i, w;
  1404. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1405. if (n < 0 || !nb) {
  1406. free(old);
  1407. free(nb);
  1408. return;
  1409. }
  1410. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1411. /* Untouched origins first, in their old order. */
  1412. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1413. &dl, &e)) {
  1414. int dirty = 0;
  1415. for (i = 0; i < persist_ndirty; i++)
  1416. if (s_len(persist_dirty[i]) == ol &&
  1417. !memcmp(persist_dirty[i], old + oo, ol))
  1418. dirty = 1;
  1419. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1420. continue;
  1421. memcpy(nb + nn, old + oo, e - oo);
  1422. nn += e - oo;
  1423. }
  1424. /* Then the changed ones (an emptied store is dropped). */
  1425. for (i = 0; i < persist_ndirty; i++) {
  1426. char num[12];
  1427. unsigned int k = 0;
  1428. js_origin_path(persist_dirty[i], path, sizeof(path));
  1429. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1430. (int)DATA_STORE_MAX);
  1431. if (w <= 2) /* missing or "{}" */
  1432. continue;
  1433. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1434. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1435. DATA_STORE_MAX) {
  1436. set_status("Saved site data is full; a site's "
  1437. "localStorage was not saved", 1, 6000);
  1438. continue;
  1439. }
  1440. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1441. nb[nn++] = '\n';
  1442. s_append(nb, &nn, num, DATA_STORE_MAX);
  1443. nb[nn++] = '\n';
  1444. memcpy(nb + nn, old, (unsigned int)w);
  1445. nn += (unsigned int)w;
  1446. nb[nn++] = '\n';
  1447. }
  1448. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1449. persist_ndirty = 0;
  1450. free(old);
  1451. free(nb);
  1452. }
  1453. static void persist_cookies_flush(void)
  1454. {
  1455. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1456. unsigned int sum;
  1457. int n;
  1458. if (!jar)
  1459. return;
  1460. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1461. (int)sizeof(struct uhttp_jar));
  1462. if (n == (int)sizeof(struct uhttp_jar)) {
  1463. sum = persist_sum(jar, (unsigned int)n);
  1464. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1465. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1466. (int)jar, n) >= 0) {
  1467. cookie_sum_saved = sum;
  1468. cookie_sum_valid = 1;
  1469. }
  1470. }
  1471. }
  1472. free(jar);
  1473. }
  1474. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1475. static void persist_tick(void)
  1476. {
  1477. unsigned int now = u_ticks_ms();
  1478. if ((int)(now - persist_due) < 0)
  1479. return;
  1480. persist_due = now + PERSIST_MS;
  1481. persist_cookies_flush();
  1482. if (persist_ndirty)
  1483. persist_store_flush();
  1484. }
  1485. /* <link rel="modulepreload">: download the page's module graph on all
  1486. * helpers at once into the boot script cache, before any script runs. The
  1487. * engine's module loader is sequential (one blocking fetch per import), so
  1488. * without this a Vite app with a dozen chunks pays every round trip in a
  1489. * row. Failures are ignored; the loader fetches what is missing. */
  1490. #define MODULE_PRELOAD_MAX 24
  1491. static void prefetch_module_preloads(void)
  1492. {
  1493. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1494. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1495. unsigned int count = 0, next = 0, done = 0, i;
  1496. char err[64];
  1497. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1498. struct br_node *nd = &doc.nodes[i];
  1499. const char *rel, *href;
  1500. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1501. continue;
  1502. rel = br_rel(&doc, i);
  1503. href = br_href(&doc, i);
  1504. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1505. continue;
  1506. if (resolve_link(page_url, href, urls[count],
  1507. sizeof(urls[count])) != 0 ||
  1508. urls[count][0] == '/' || script_cache_has(urls[count]))
  1509. continue;
  1510. slot[count++] = 0;
  1511. }
  1512. if (!count)
  1513. return;
  1514. set_status("Loading modules...", 0, 0);
  1515. while (done < count) {
  1516. struct fetch_worker *w;
  1517. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1518. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1519. 0, 0, 0, err,
  1520. sizeof(err)) != 0) {
  1521. fetch_worker_release(w);
  1522. done++;
  1523. } else {
  1524. slot[next] = w;
  1525. }
  1526. next++;
  1527. }
  1528. worker_wait_ui();
  1529. if (cancel_fetch || pending_action) {
  1530. fetch_workers_cancel_busy();
  1531. return;
  1532. }
  1533. for (i = 0; i < next; i++) {
  1534. unsigned char *body;
  1535. int rv, tr = 0;
  1536. if (!slot[i])
  1537. continue;
  1538. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1539. if (rv == 0)
  1540. continue;
  1541. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1542. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1543. if (body) {
  1544. rv = fetch_worker_read_body(slot[i], body,
  1545. BR_SCRIPT_MAX, image_io_buf,
  1546. BR_PAGE_COMP_MAX, &tr, err,
  1547. sizeof(err));
  1548. if (rv > 0 && !tr)
  1549. script_cache_put(urls[i], body,
  1550. (unsigned int)rv);
  1551. free(body);
  1552. }
  1553. fetch_worker_release(slot[i]);
  1554. slot[i] = 0;
  1555. done++;
  1556. }
  1557. u_sleep_ms(10);
  1558. }
  1559. }
  1560. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1561. * submitted to helper workers ahead of time, but scripts still execute in
  1562. * document order. */
  1563. #define SCRIPT_INLINE 0
  1564. #define SCRIPT_LOCAL 1
  1565. #define SCRIPT_REMOTE 2
  1566. #define SCRIPT_ERROR 3
  1567. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1568. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1569. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1570. static void script_submit_window(unsigned int *next, char *err,
  1571. unsigned int errcap)
  1572. {
  1573. while (*next < doc.nscripts) {
  1574. struct fetch_worker *w;
  1575. if (script_kind[*next] != SCRIPT_REMOTE) {
  1576. (*next)++;
  1577. continue;
  1578. }
  1579. w = fetch_worker_alloc();
  1580. if (!w)
  1581. return;
  1582. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1583. 0, 0, 0, 0, err, errcap) != 0) {
  1584. fetch_worker_release(w);
  1585. script_kind[*next] = SCRIPT_ERROR;
  1586. (*next)++;
  1587. continue;
  1588. }
  1589. script_slot[*next] = w;
  1590. (*next)++;
  1591. }
  1592. }
  1593. /* Run the page's scripts in document order. External bodies are prefetched
  1594. * in parallel so downloading script N+1 overlaps executing script N; inline
  1595. * bodies are copied because the engine needs NUL-terminated text. */
  1596. static void run_page_scripts(void)
  1597. {
  1598. struct js_browser_host host;
  1599. unsigned int i, next = 0;
  1600. char err[64], ferr[64];
  1601. if (!doc.nscripts)
  1602. return;
  1603. host.status = js_host_status;
  1604. host.report = js_host_report;
  1605. host.navigate = js_host_navigate;
  1606. host.changed = js_host_changed;
  1607. host.rect = js_host_rect;
  1608. host.form_value = js_host_form_value;
  1609. host.form_checked = js_host_form_checked;
  1610. host.form_selected = js_host_form_selected;
  1611. host.form_set_value = js_host_form_set_value;
  1612. host.form_set_checked = js_host_form_set_checked;
  1613. host.form_set_selected = js_host_form_set_selected;
  1614. host.form_elements = js_host_form_elements;
  1615. host.form_submit = js_host_form_submit;
  1616. host.form_reset = js_host_form_reset;
  1617. host.click = js_host_click;
  1618. host.computed = js_host_computed;
  1619. host.http = js_host_http;
  1620. host.load_script = js_host_load_script;
  1621. host.storage = js_host_storage;
  1622. host.set_hash = js_host_set_hash;
  1623. host.page_url = page_url;
  1624. host.width = ui.w;
  1625. host.height = ui.h;
  1626. if (js_browser_start(&doc, &host) != 0) {
  1627. js_host_status("JavaScript: out of memory", 1);
  1628. return;
  1629. }
  1630. prefetch_module_preloads();
  1631. for (i = 0; i < doc.nscripts; i++) {
  1632. struct br_script *script = &doc.scripts[i];
  1633. const char *src_attr = script->src_off ?
  1634. doc.attrs + script->src_off : "";
  1635. script_slot[i] = 0;
  1636. if (!script->src_off) {
  1637. script_kind[i] = SCRIPT_INLINE;
  1638. continue;
  1639. }
  1640. if (!src_attr[0] ||
  1641. resolve_link(page_url, src_attr, script_urls[i],
  1642. sizeof(script_urls[i])) != 0) {
  1643. script_urls[i][0] = '\0';
  1644. script_kind[i] = SCRIPT_ERROR;
  1645. continue;
  1646. }
  1647. if (script_urls[i][0] == '/' ||
  1648. script_cache_has(script_urls[i]))
  1649. script_kind[i] = SCRIPT_LOCAL;
  1650. else
  1651. script_kind[i] = SCRIPT_REMOTE;
  1652. }
  1653. script_submit_window(&next, ferr, sizeof(ferr));
  1654. for (i = 0; i < doc.nscripts; i++) {
  1655. struct br_script *script = &doc.scripts[i];
  1656. if (script_kind[i] == SCRIPT_INLINE) {
  1657. unsigned int off = script->off;
  1658. unsigned int len = script->len;
  1659. unsigned int k;
  1660. char *src = (char *)malloc(len + 1);
  1661. if (!src) {
  1662. js_host_status("JavaScript: out of memory", 1);
  1663. break;
  1664. }
  1665. for (k = 0; k < len; k++)
  1666. src[k] = doc.script_src[off + k];
  1667. src[len] = '\0';
  1668. if (script->module) {
  1669. /* A distinct module name per inline module
  1670. * (QuickJS registers modules by name); the
  1671. * fragment keeps relative imports resolving
  1672. * against the page. */
  1673. char mname[BR_URL_MAX + 16];
  1674. unsigned int mn = 0;
  1675. s_append(mname, &mn, page_url, sizeof(mname));
  1676. s_append(mname, &mn, "#module", sizeof(mname));
  1677. s_append_dec(mname, &mn, i, sizeof(mname));
  1678. js_browser_run_module(src, mname);
  1679. } else {
  1680. js_browser_run(src, page_url);
  1681. }
  1682. free(src);
  1683. } else if (script->src_off) {
  1684. const char *src_attr = doc.attrs + script->src_off;
  1685. if (script_kind[i] == SCRIPT_ERROR) {
  1686. script_error("Cannot load script", src_attr,
  1687. script_urls[i][0] ?
  1688. "network busy" :
  1689. "unsupported URL");
  1690. continue;
  1691. }
  1692. if (script_kind[i] == SCRIPT_LOCAL) {
  1693. unsigned char *data = 0;
  1694. unsigned int len = 0;
  1695. int rv;
  1696. set_status("Loading script...", 0, 0);
  1697. rv = fetch_script_text(script_urls[i], &data,
  1698. &len, err, sizeof(err));
  1699. if (rv == FETCH_ABORT)
  1700. break;
  1701. if (rv != 0) {
  1702. script_error("Cannot load script",
  1703. script_urls[i], err);
  1704. continue;
  1705. }
  1706. if (script->module)
  1707. js_browser_run_module(
  1708. (const char *)data,
  1709. script_urls[i]);
  1710. else
  1711. js_browser_run((const char *)data,
  1712. script_urls[i]);
  1713. free(data);
  1714. } else {
  1715. struct fetch_worker *w = script_slot[i];
  1716. unsigned char *body = 0;
  1717. int tr = 0, rv;
  1718. if (!w) {
  1719. w = fetch_worker_alloc();
  1720. if (!w)
  1721. continue;
  1722. if (fetch_worker_submit(w,
  1723. script_urls[i],
  1724. BR_SCRIPT_MAX,
  1725. 0, 0, 0, 0, err,
  1726. sizeof(err)) != 0) {
  1727. fetch_worker_release(w);
  1728. script_kind[i] = SCRIPT_ERROR;
  1729. if (i == next)
  1730. next++;
  1731. continue;
  1732. }
  1733. script_slot[i] = w;
  1734. if (i == next)
  1735. next++;
  1736. }
  1737. set_status("Loading script...", 0, 0);
  1738. rv = fetch_worker_wait(w, err, sizeof(err));
  1739. if (rv == FETCH_ABORT) {
  1740. fetch_workers_stop_all();
  1741. break;
  1742. }
  1743. /* The body gets its own buffer (scripts are up
  1744. * to 2 MB); image_io_buf takes the gzip
  1745. * stream. */
  1746. body = rv == 0 ? (unsigned char *)malloc(
  1747. BR_SCRIPT_MAX + 1) : 0;
  1748. if (body)
  1749. rv = fetch_worker_read_body(w, body,
  1750. BR_SCRIPT_MAX, image_io_buf,
  1751. BR_PAGE_COMP_MAX, &tr, err,
  1752. sizeof(err));
  1753. else {
  1754. if (rv == 0)
  1755. s_copy(err, "out of memory",
  1756. sizeof(err));
  1757. rv = -1;
  1758. }
  1759. fetch_worker_release(w);
  1760. script_slot[i] = 0;
  1761. script_submit_window(&next, ferr, sizeof(ferr));
  1762. if (rv <= 0)
  1763. script_error("Cannot load script",
  1764. script_urls[i], err);
  1765. else if (tr || (unsigned int)rv >=
  1766. BR_SCRIPT_MAX)
  1767. script_error("Cannot load script",
  1768. script_urls[i],
  1769. "script is too large");
  1770. else {
  1771. body[rv] = '\0';
  1772. script_cache_put(script_urls[i], body,
  1773. (unsigned int)rv);
  1774. if (script->module)
  1775. js_browser_run_module(
  1776. (const char *)body,
  1777. script_urls[i]);
  1778. else
  1779. js_browser_run(
  1780. (const char *)body,
  1781. script_urls[i]);
  1782. }
  1783. free(body);
  1784. }
  1785. }
  1786. if (pending_action)
  1787. break;
  1788. }
  1789. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  1790. * load_home() stop it before the next navigation. */
  1791. if (doc.scripts_truncated && !js_last_error)
  1792. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  1793. 1);
  1794. }
  1795. /* ---- images ---- */
  1796. static void image_reset(void)
  1797. {
  1798. int i;
  1799. for (i = 0; i < BR_MAX_IMAGES; i++) {
  1800. images[i].state = 0;
  1801. images[i].native_w = images[i].native_h = 0;
  1802. images[i].err[0] = '\0';
  1803. }
  1804. image_count = 0;
  1805. image_pixels = 0;
  1806. preload_active = 0;
  1807. preload_pending = 0;
  1808. preload_wait = 0;
  1809. preload_node = 0;
  1810. preload_loaded = 0;
  1811. }
  1812. /* Decode into the shared arena, then copy/scale the result into a display
  1813. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  1814. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  1815. * pixels. Transparent edges are composited over white. */
  1816. /* One decode scratch arena per page, reused across images. Allocating and
  1817. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  1818. * each small display bitmap landed in the hole the previous arena left, so
  1819. * the next arena no longer fit and the heap ratcheted up until an app
  1820. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  1821. * still released right after their one image. */
  1822. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  1823. static unsigned char *decode_arena_get(unsigned int bytes)
  1824. {
  1825. if (decode_arena && decode_arena_size >= bytes)
  1826. return decode_arena;
  1827. free(decode_arena);
  1828. decode_arena = (unsigned char *)malloc(bytes);
  1829. decode_arena_size = decode_arena ? bytes : 0;
  1830. return decode_arena;
  1831. }
  1832. static void decode_arena_put(void)
  1833. {
  1834. if (decode_arena_size > DECODE_ARENA_KEEP) {
  1835. free(decode_arena);
  1836. decode_arena = 0;
  1837. decode_arena_size = 0;
  1838. }
  1839. }
  1840. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  1841. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  1842. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  1843. static int decode_image_data(const unsigned char *data, unsigned int len,
  1844. struct br_image *bi, int box_w, int box_h)
  1845. {
  1846. struct img_info info;
  1847. struct img_options opt;
  1848. struct img_mem mem;
  1849. struct img_image decoded;
  1850. unsigned char *arena;
  1851. unsigned int est, bytes, i;
  1852. unsigned short *px;
  1853. unsigned char *alpha = 0;
  1854. int dw, dh, r;
  1855. if (img_sniff(data, len, &info) != 0) {
  1856. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  1857. return -1;
  1858. }
  1859. est = img_estimate(&info);
  1860. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  1861. s_copy(bi->err, "image too large", sizeof(bi->err));
  1862. return -1;
  1863. }
  1864. arena = decode_arena_get(est);
  1865. if (!arena) {
  1866. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1867. return -1;
  1868. }
  1869. img_mem_init(&mem, arena, est);
  1870. opt.max_pixels = BR_IMG_PIX_MAX;
  1871. r = img_decode(data, len, &opt, &mem, &decoded);
  1872. if (r != 0) {
  1873. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  1874. goto fail;
  1875. }
  1876. if (decoded.w == 0 || decoded.h == 0) {
  1877. s_copy(bi->err, "empty image", sizeof(bi->err));
  1878. goto fail;
  1879. }
  1880. bi->native_w = (int)decoded.w;
  1881. bi->native_h = (int)decoded.h;
  1882. dw = (int)decoded.w;
  1883. dh = (int)decoded.h;
  1884. if (box_w > 0 && box_h > 0) {
  1885. /* cover: scale so both box sides are filled, never up */
  1886. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  1887. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  1888. unsigned int sc = sw > sh ? sw : sh;
  1889. if (sc < 0x10000u) {
  1890. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  1891. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  1892. }
  1893. }
  1894. if (dw > BR_IMG_LAYOUT_W) {
  1895. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  1896. dw = BR_IMG_LAYOUT_W;
  1897. }
  1898. if (dh < 1)
  1899. dh = 1;
  1900. if (dw < 1)
  1901. dw = 1;
  1902. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  1903. BR_IMG_PIXEL_BUDGET) {
  1904. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  1905. goto fail;
  1906. }
  1907. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  1908. px = (unsigned short *)malloc(bytes);
  1909. if (!px) {
  1910. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1911. goto fail;
  1912. }
  1913. /* Keep the alpha plane for the scaled image so transparent logos and
  1914. * icons composite over the page instead of the browser's dark theme
  1915. * background. Very large alpha images stay flattened to bound the
  1916. * heap use. */
  1917. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  1918. alpha = (unsigned char *)malloc((unsigned int)dw *
  1919. (unsigned int)dh);
  1920. if (alpha) {
  1921. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1922. alpha[i] = 255;
  1923. }
  1924. }
  1925. /* With an alpha plane the colour under transparent pixels only shows
  1926. * through partially covered edge pixels of the downscale: use white,
  1927. * as documented above, not the dark browser theme (which left a dark
  1928. * fringe around scaled app icons). */
  1929. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1930. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  1931. {
  1932. struct img_blit b;
  1933. b.dst = px;
  1934. b.dst_w = dw;
  1935. b.dst_h = dh;
  1936. b.clip_x = 0;
  1937. b.clip_y = 0;
  1938. b.clip_w = dw;
  1939. b.clip_h = dh;
  1940. b.x = 0;
  1941. b.y = 0;
  1942. b.scale = ((unsigned int)dw << 16) / decoded.w;
  1943. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  1944. b.bg2 = b.bg;
  1945. b.dst_a = alpha;
  1946. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  1947. img_draw(&decoded, &b);
  1948. }
  1949. bi->img.format = decoded.format;
  1950. bi->img.w = (unsigned int)dw;
  1951. bi->img.h = (unsigned int)dh;
  1952. bi->img.px = px;
  1953. bi->img.alpha = alpha;
  1954. bi->img.flags = 0;
  1955. bi->state = 1;
  1956. image_pixels += (unsigned int)dw * (unsigned int)dh;
  1957. decode_arena_put();
  1958. return 0;
  1959. fail:
  1960. decode_arena_put();
  1961. return -1;
  1962. }
  1963. /* ---- URL / local path handling ---- */
  1964. static int is_http(const char *s)
  1965. {
  1966. return starts_with(s, "http://") || starts_with(s, "https://");
  1967. }
  1968. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  1969. static int normalize_abs(const char *in, char *out, unsigned int cap)
  1970. {
  1971. char seg[64];
  1972. unsigned int i = 0, o = 1;
  1973. int depth = 0;
  1974. int trailing;
  1975. if (!in || in[0] != '/' || cap < 2)
  1976. return -1;
  1977. trailing = 0;
  1978. {
  1979. unsigned int n = s_len(in);
  1980. if (n > 1 && in[n - 1] == '/')
  1981. trailing = 1;
  1982. }
  1983. out[0] = '/';
  1984. while (in[i]) {
  1985. unsigned int n = 0;
  1986. while (in[i] == '/')
  1987. i++;
  1988. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  1989. if (n + 1 < sizeof(seg))
  1990. seg[n++] = in[i];
  1991. i++;
  1992. }
  1993. seg[n] = '\0';
  1994. if (n == 0)
  1995. break;
  1996. if (s_eq(seg, "."))
  1997. continue;
  1998. if (s_eq(seg, "..")) {
  1999. if (depth > 0) {
  2000. while (o > 1 && out[o - 1] != '/')
  2001. o--;
  2002. if (o > 1)
  2003. o--;
  2004. depth--;
  2005. }
  2006. continue;
  2007. }
  2008. if (o > 1) {
  2009. if (o + 1 >= cap)
  2010. return -1;
  2011. out[o++] = '/';
  2012. }
  2013. if (o + n + 1 >= cap)
  2014. return -1;
  2015. {
  2016. unsigned int j;
  2017. for (j = 0; j < n; j++)
  2018. out[o++] = seg[j];
  2019. }
  2020. depth++;
  2021. }
  2022. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2023. if (o + 1 >= cap)
  2024. return -1;
  2025. out[o++] = '/';
  2026. }
  2027. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2028. if (in[i] == '?' || in[i] == '#') {
  2029. while (in[i]) {
  2030. if (o + 1 >= cap)
  2031. return -1;
  2032. out[o++] = in[i++];
  2033. }
  2034. }
  2035. out[o] = '\0';
  2036. return 0;
  2037. }
  2038. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2039. {
  2040. char joined[BR_URL_MAX];
  2041. if (!in || !in[0]) {
  2042. s_copy(out, cwd[0] ? cwd : "/", cap);
  2043. return;
  2044. }
  2045. if (in[0] == '/') {
  2046. if (normalize_abs(in, out, cap) != 0)
  2047. s_copy(out, in, cap);
  2048. return;
  2049. }
  2050. {
  2051. unsigned int n = 0;
  2052. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2053. s_append(joined, &n, "/", sizeof(joined));
  2054. s_append(joined, &n, in, sizeof(joined));
  2055. }
  2056. if (normalize_abs(joined, out, cap) != 0)
  2057. s_copy(out, joined, cap);
  2058. }
  2059. /* ---- canonical origin cache ---- *
  2060. *
  2061. * Sites commonly redirect http://host to https://host and then to
  2062. * https://www.host. Remember the final scheme/host of the last navigation so
  2063. * a bare domain typed again goes straight there instead of paying for two
  2064. * more connections and TLS handshakes. Only default-port requests are
  2065. * rewritten; explicit ports are left alone. */
  2066. #define ORIGIN_CACHE_MAX 8
  2067. #define ORIGIN_FILE "/share/borigins"
  2068. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2069. UHTTP_HOST_MAX + 2))
  2070. struct origin_cache_entry {
  2071. char host[UHTTP_HOST_MAX];
  2072. char origin[UHTTP_HOST_MAX + 16];
  2073. };
  2074. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2075. static int origin_count;
  2076. static char origin_buf[ORIGIN_BUF_SIZE];
  2077. static int default_port(const struct uhttp_url *u)
  2078. {
  2079. return u->secure ? u->port == 443 : u->port == 80;
  2080. }
  2081. static void url_origin(const struct uhttp_url *u, char *out,
  2082. unsigned int cap)
  2083. {
  2084. unsigned int n = 0;
  2085. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2086. s_append(out, &n, u->host, cap);
  2087. if (!default_port(u)) {
  2088. s_append(out, &n, ":", cap);
  2089. s_append_dec(out, &n, u->port, cap);
  2090. }
  2091. }
  2092. static void origin_cache_apply(char *url, unsigned int cap)
  2093. {
  2094. struct uhttp_url u;
  2095. char out[BR_URL_MAX];
  2096. unsigned int n = 0;
  2097. int i;
  2098. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2099. return;
  2100. for (i = 0; i < origin_count; i++) {
  2101. if (!s_eq(u.host, origins[i].host))
  2102. continue;
  2103. s_append(out, &n, origins[i].origin, sizeof(out));
  2104. s_append(out, &n, u.path, sizeof(out));
  2105. s_copy(url, out, cap);
  2106. return;
  2107. }
  2108. }
  2109. static void origin_cache_save(void)
  2110. {
  2111. unsigned int n = 0;
  2112. int i;
  2113. for (i = 0; i < origin_count; i++) {
  2114. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2115. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2116. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2117. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2118. }
  2119. if (n)
  2120. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2121. (int)origin_buf, (int)n);
  2122. }
  2123. static void origin_cache_load(void)
  2124. {
  2125. char *p;
  2126. int rn;
  2127. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2128. (int)(sizeof(origin_buf) - 1));
  2129. if (rn <= 0)
  2130. return;
  2131. origin_buf[rn] = '\0';
  2132. p = origin_buf;
  2133. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2134. char *line = p, *origin;
  2135. while (*p && *p != '\n')
  2136. p++;
  2137. if (*p)
  2138. *p++ = '\0';
  2139. if (!line[0])
  2140. continue;
  2141. origin = line;
  2142. while (*origin && *origin != ' ')
  2143. origin++;
  2144. if (!*origin)
  2145. continue;
  2146. *origin++ = '\0';
  2147. if (!line[0] || !is_http(origin))
  2148. continue;
  2149. {
  2150. struct uhttp_url uo;
  2151. if (uhttp_parse_url(origin, &uo) != 0 ||
  2152. !s_eq(uo.path, "/"))
  2153. continue;
  2154. }
  2155. s_copy(origins[origin_count].host, line,
  2156. sizeof(origins[origin_count].host));
  2157. s_copy(origins[origin_count].origin, origin,
  2158. sizeof(origins[origin_count].origin));
  2159. origin_count++;
  2160. }
  2161. }
  2162. static int host_is_www_of(const char *host, const char *base)
  2163. {
  2164. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2165. host[3] == '.' && s_eq(host + 4, base);
  2166. }
  2167. static void origin_cache_learn(const char *requested, const char *final)
  2168. {
  2169. struct uhttp_url from, to;
  2170. char origin[UHTTP_HOST_MAX + 16];
  2171. int i;
  2172. if (!is_http(requested) || !is_http(final))
  2173. return;
  2174. if (uhttp_parse_url(requested, &from) != 0 ||
  2175. uhttp_parse_url(final, &to) != 0)
  2176. return;
  2177. if (!default_port(&from))
  2178. return;
  2179. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2180. from.port == to.port)
  2181. return;
  2182. /* Only remember origin-level canonicalisation: the same path, and
  2183. * either the same host or its www./apex sibling. A path- or
  2184. * host-specific redirect (a shortener, a login page) must not poison
  2185. * every request to the typed host. */
  2186. if (!s_eq(from.path, to.path))
  2187. return;
  2188. if (!s_eq(from.host, to.host) &&
  2189. !host_is_www_of(to.host, from.host) &&
  2190. !host_is_www_of(from.host, to.host))
  2191. return;
  2192. url_origin(&to, origin, sizeof(origin));
  2193. for (i = 0; i < origin_count; i++) {
  2194. if (s_eq(origins[i].host, from.host)) {
  2195. if (!s_eq(origins[i].origin, origin)) {
  2196. s_copy(origins[i].origin, origin,
  2197. sizeof(origins[i].origin));
  2198. origin_cache_save();
  2199. }
  2200. return;
  2201. }
  2202. }
  2203. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2204. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2205. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2206. origin_cache_save();
  2207. }
  2208. static int path_dir(const char *path, char *out, unsigned int cap)
  2209. {
  2210. unsigned int i, last = 0;
  2211. for (i = 0; path[i]; i++)
  2212. if (path[i] == '/')
  2213. last = i;
  2214. if (last == 0) {
  2215. if (cap < 2)
  2216. return -1;
  2217. out[0] = '/';
  2218. out[1] = '\0';
  2219. return 0;
  2220. }
  2221. if (last + 1 >= cap)
  2222. return -1;
  2223. {
  2224. unsigned int j;
  2225. for (j = 0; j < last; j++)
  2226. out[j] = path[j];
  2227. out[last] = '\0';
  2228. }
  2229. return 0;
  2230. }
  2231. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2232. static int resolve_link(const char *base, const char *href, char *out,
  2233. unsigned int cap)
  2234. {
  2235. char joined[BR_URL_MAX];
  2236. if (!href || !href[0] || href[0] == '#')
  2237. return -1;
  2238. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2239. starts_with(href, "data:") || starts_with(href, "tel:"))
  2240. return -1;
  2241. if (starts_with(href, "about:")) {
  2242. s_copy(out, href, cap);
  2243. return 0;
  2244. }
  2245. if (is_http(href)) {
  2246. s_copy(out, href, cap);
  2247. return 0;
  2248. }
  2249. if (starts_with(href, "//")) {
  2250. if (is_http(base)) {
  2251. unsigned int n = 0;
  2252. s_append(out, &n, starts_with(base, "https:") ?
  2253. "https:" : "http:", cap);
  2254. s_append(out, &n, href, cap);
  2255. return 0;
  2256. }
  2257. return -1;
  2258. }
  2259. if (is_http(base)) {
  2260. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2261. }
  2262. /* local page */
  2263. if (href[0] == '/') {
  2264. if (normalize_abs(href, out, cap) != 0)
  2265. return -1;
  2266. return 0;
  2267. }
  2268. {
  2269. char dir[BR_URL_MAX];
  2270. unsigned int n = 0;
  2271. if (s_eq(base, "about:home"))
  2272. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2273. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2274. s_copy(dir, "/", sizeof(dir));
  2275. s_append(joined, &n, dir, sizeof(joined));
  2276. if (n == 0 || joined[n - 1] != '/')
  2277. s_append(joined, &n, "/", sizeof(joined));
  2278. s_append(joined, &n, href, sizeof(joined));
  2279. }
  2280. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2281. }
  2282. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2283. * rest instead of failing when a page or stylesheet is larger than the
  2284. * buffer. The stream is still walked to the end, so a normal page is
  2285. * verified; a truncated compressed input still returns whatever was decoded
  2286. * so far. */
  2287. struct trunc_buf {
  2288. unsigned char *dst;
  2289. unsigned int cap, pos;
  2290. int full;
  2291. };
  2292. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2293. {
  2294. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2295. if (len > m->cap - m->pos) {
  2296. unsigned int room = m->cap - m->pos;
  2297. if (room) {
  2298. unsigned int i;
  2299. for (i = 0; i < room; i++)
  2300. m->dst[m->pos + i] = data[i];
  2301. m->pos += room;
  2302. }
  2303. m->full = 1;
  2304. return 0;
  2305. }
  2306. {
  2307. unsigned int i;
  2308. for (i = 0; i < len; i++)
  2309. m->dst[m->pos + i] = data[i];
  2310. }
  2311. m->pos += len;
  2312. return 0;
  2313. }
  2314. static void worker_wait_ui(void);
  2315. static void inflate_ui_pump(void *ctx)
  2316. {
  2317. static unsigned int last;
  2318. unsigned int now = u_ticks_ms();
  2319. (void)ctx;
  2320. if ((int)(now - last) >= 50) {
  2321. last = now;
  2322. worker_wait_ui();
  2323. }
  2324. }
  2325. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2326. unsigned char *dst, unsigned int cap,
  2327. unsigned int *outlen, int gzip, int *truncated)
  2328. {
  2329. struct inflate_src in;
  2330. struct inflate_sink sink;
  2331. struct trunc_buf m;
  2332. unsigned int got = 0;
  2333. int r;
  2334. in.p = src;
  2335. in.len = len;
  2336. in.more = 0;
  2337. in.ctx = 0;
  2338. m.dst = dst;
  2339. m.cap = cap;
  2340. m.pos = 0;
  2341. m.full = 0;
  2342. sink.write = trunc_write;
  2343. sink.ctx = &m;
  2344. inflate_init(&image_inflate_ws, &in, &sink);
  2345. image_inflate_ws.progress = inflate_ui_pump;
  2346. image_inflate_ws.progress_ctx = 0;
  2347. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2348. inflate_zlib(&image_inflate_ws, &got);
  2349. *outlen = m.pos;
  2350. *truncated = m.full || r != 0;
  2351. if (r != 0 && m.pos == 0)
  2352. return -1;
  2353. return 0;
  2354. }
  2355. /* ---- headless fetch workers ------------------------------------------ *
  2356. *
  2357. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2358. * writes the raw response, a small metadata file and a done marker under
  2359. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2360. * or a multi-megabyte body never freezes the UI and images download in
  2361. * parallel.
  2362. */
  2363. struct fetch_meta {
  2364. int status;
  2365. int error;
  2366. int trunc;
  2367. unsigned int len;
  2368. unsigned int open_ms;
  2369. unsigned int first_ms;
  2370. unsigned int total_ms;
  2371. char encoding[16];
  2372. char ctype[64];
  2373. char final[BR_URL_MAX];
  2374. };
  2375. static void draw(unsigned int *action);
  2376. static void handle_keys(unsigned int *action);
  2377. static void handle_page_click(unsigned int *action);
  2378. #define FETCH_WORKERS 4
  2379. #define FETCH_PATH_MAX 32
  2380. /* One long-lived curl __serve helper per worker. Each worker has its own
  2381. * request/body/meta/done files under /share so several downloads can be in
  2382. * flight at once; the keep-alive connection stays in the helper process, so
  2383. * tls.c's per-process state remains valid. */
  2384. struct fetch_worker {
  2385. int pid;
  2386. int slot;
  2387. int busy;
  2388. int ready;
  2389. int image_job;
  2390. unsigned int seq;
  2391. unsigned int deadline;
  2392. int retried;
  2393. char req[FETCH_PATH_MAX];
  2394. char body[FETCH_PATH_MAX];
  2395. char meta[FETCH_PATH_MAX];
  2396. char done[FETCH_PATH_MAX];
  2397. char post[FETCH_PATH_MAX];
  2398. /* Optional preload job attached to this worker. */
  2399. unsigned int node;
  2400. int bg;
  2401. char url[BR_URL_MAX];
  2402. struct fetch_meta m;
  2403. };
  2404. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2405. static int fetch_tty = -2;
  2406. static void fetch_tty_drain(void);
  2407. static unsigned int fetch_session;
  2408. static unsigned int fetch_seq;
  2409. static struct fetch_meta fetch_meta;
  2410. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2411. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2412. static int fetch_last_error;
  2413. static unsigned int meta_uint(char **pp)
  2414. {
  2415. char *p = *pp;
  2416. unsigned int v = 0;
  2417. while (*p >= '0' && *p <= '9') {
  2418. v = v * 10 + (unsigned int)(*p - '0');
  2419. p++;
  2420. }
  2421. while (*p && *p != '\n')
  2422. p++;
  2423. if (*p == '\n')
  2424. p++;
  2425. *pp = p;
  2426. return v;
  2427. }
  2428. static void meta_str(char **pp, char *out, unsigned int cap)
  2429. {
  2430. char *p = *pp;
  2431. unsigned int n = 0;
  2432. while (*p && *p != '\n' && n + 1 < cap)
  2433. out[n++] = *p++;
  2434. out[n] = '\0';
  2435. while (*p && *p != '\n')
  2436. p++;
  2437. if (*p == '\n')
  2438. p++;
  2439. *pp = p;
  2440. }
  2441. static void worker_wait_ui(void)
  2442. {
  2443. unsigned int action = 0;
  2444. if (!ngui_begin(&ui))
  2445. return;
  2446. draw(&action);
  2447. handle_keys(&action);
  2448. handle_page_click(&action);
  2449. if (action & ACT_WAIT_NAV) {
  2450. pending_action |= action & ACT_WAIT_NAV;
  2451. if ((action & ACT_NAV) && click_url[0])
  2452. s_copy(pending_url, click_url, sizeof(pending_url));
  2453. click_url[0] = '\0';
  2454. cancel_fetch = 1;
  2455. }
  2456. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  2457. ngui_invalidate(&ui);
  2458. ngui_end(&ui);
  2459. }
  2460. static void fetch_path(char *out, unsigned int cap, const char *kind,
  2461. unsigned int session, int slot)
  2462. {
  2463. unsigned int n = 0;
  2464. s_append(out, &n, "/share/bf", cap);
  2465. s_append_dec(out, &n, session, cap);
  2466. s_append(out, &n, "_", cap);
  2467. s_append_dec(out, &n, (unsigned int)slot, cap);
  2468. s_append(out, &n, kind, cap);
  2469. }
  2470. static void fetch_pool_init(void)
  2471. {
  2472. static int ready;
  2473. int i;
  2474. if (ready)
  2475. return;
  2476. ready = 1;
  2477. fetch_session = ((unsigned int)u_getpid() << 16) ^
  2478. (u_ticks_ms() & 0xFFFFu);
  2479. if (!fetch_session)
  2480. fetch_session = 1;
  2481. for (i = 0; i < FETCH_WORKERS; i++) {
  2482. struct fetch_worker *w = &fetch_workers[i];
  2483. w->pid = -1;
  2484. w->slot = i;
  2485. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  2486. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  2487. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  2488. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  2489. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  2490. }
  2491. }
  2492. static void fetch_worker_stop(struct fetch_worker *w)
  2493. {
  2494. int i;
  2495. /* An abandoned image job leaves its node loadable again. */
  2496. if (w->busy && w->image_job && w->node < doc.nnode) {
  2497. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  2498. doc.nodes[w->node].bg_img_index = -1;
  2499. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  2500. doc.nodes[w->node].img_index = -1;
  2501. }
  2502. if (w->pid > 0) {
  2503. u_kill((unsigned int)w->pid);
  2504. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  2505. u_sleep_ms(5);
  2506. /* Let the reaper close the socket before we reuse the slot. */
  2507. u_sleep_ms(10);
  2508. }
  2509. w->pid = -1;
  2510. w->busy = 0;
  2511. w->ready = 0;
  2512. w->image_job = 0;
  2513. if (w->req[0]) {
  2514. u_syscall1(SYS_UNLINK, (int)w->done);
  2515. u_syscall1(SYS_UNLINK, (int)w->meta);
  2516. u_syscall1(SYS_UNLINK, (int)w->body);
  2517. u_syscall1(SYS_UNLINK, (int)w->post);
  2518. u_syscall1(SYS_UNLINK, (int)w->req);
  2519. }
  2520. }
  2521. static void fetch_workers_stop_all(void)
  2522. {
  2523. int i;
  2524. for (i = 0; i < FETCH_WORKERS; i++)
  2525. fetch_worker_stop(&fetch_workers[i]);
  2526. }
  2527. /* Abandon the transfers of the current page but keep idle helpers and their
  2528. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  2529. * because its response would otherwise land in a reused /share slot. */
  2530. static void fetch_workers_cancel_busy(void)
  2531. {
  2532. int i;
  2533. for (i = 0; i < FETCH_WORKERS; i++)
  2534. if (fetch_workers[i].busy)
  2535. fetch_worker_stop(&fetch_workers[i]);
  2536. }
  2537. static void fetch_workers_prepare_nav(const char *url)
  2538. {
  2539. int i;
  2540. (void)url;
  2541. for (i = 0; i < FETCH_WORKERS; i++) {
  2542. struct fetch_worker *w = &fetch_workers[i];
  2543. if (w->pid <= 0)
  2544. continue;
  2545. /* Only an in-flight transfer must be aborted. Idle helpers
  2546. * stay warm across origins: there are just FETCH_WORKERS of
  2547. * them, and uhttp_open drops the old connection when the
  2548. * next job is for another host. Killing and respawning all
  2549. * four on every navigation churned processes and sockets
  2550. * while images were still loading. */
  2551. if (w->busy)
  2552. fetch_worker_stop(w);
  2553. }
  2554. }
  2555. /* The browser is no longer the active window and no fetch is running: give
  2556. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  2557. static void fetch_workers_stop_if_unfocused(void)
  2558. {
  2559. int i;
  2560. fetch_tty_drain();
  2561. if (ui.focused || page_loading || preload_active)
  2562. return;
  2563. for (i = 0; i < FETCH_WORKERS; i++)
  2564. if (fetch_workers[i].pid > 0) {
  2565. fetch_workers_stop_all();
  2566. return;
  2567. }
  2568. }
  2569. /* The helpers (and this process, since u_tty_create() rebinds our own
  2570. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  2571. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  2572. * a dozen TLS connections every helper hung in its next log line, so the
  2573. * following cross-origin navigation sat at "Loading..." until it timed out.
  2574. * Drain and discard it from every wait/poll loop. */
  2575. static void fetch_tty_drain(void)
  2576. {
  2577. char sink[512];
  2578. int i;
  2579. if (fetch_tty <= 0)
  2580. return;
  2581. for (i = 0; i < 16; i++)
  2582. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  2583. break;
  2584. }
  2585. static int fetch_worker_start(struct fetch_worker *w, char *err,
  2586. unsigned int errcap)
  2587. {
  2588. char arg[40];
  2589. unsigned int n = 0;
  2590. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  2591. return 0;
  2592. w->pid = -1;
  2593. fetch_pool_init();
  2594. if (fetch_tty == -2) {
  2595. int t = u_tty_create();
  2596. fetch_tty = t > 0 ? t : 0;
  2597. }
  2598. s_append(arg, &n, "__serve ", sizeof(arg));
  2599. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  2600. s_append(arg, &n, " ", sizeof(arg));
  2601. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  2602. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  2603. if (w->pid <= 0) {
  2604. w->pid = -1;
  2605. s_copy(err, "cannot start network helper", errcap);
  2606. return -1;
  2607. }
  2608. return 0;
  2609. }
  2610. static struct fetch_worker *fetch_worker_alloc(void)
  2611. {
  2612. int i;
  2613. fetch_pool_init();
  2614. for (i = 0; i < FETCH_WORKERS; i++)
  2615. if (!fetch_workers[i].busy)
  2616. return &fetch_workers[i];
  2617. return 0;
  2618. }
  2619. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  2620. unsigned int cap, const char *method,
  2621. const char *ctype, const char *post,
  2622. unsigned int post_len, unsigned int node,
  2623. int bg, char *err, unsigned int errcap);
  2624. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  2625. unsigned int cap, const char *post,
  2626. unsigned int post_len, unsigned int node,
  2627. int bg, char *err, unsigned int errcap)
  2628. {
  2629. /* A body pointer with no bytes is still a POST: the classic request
  2630. * line would turn it into a GET. */
  2631. if (post && !post_len)
  2632. return fetch_worker_submit_req(w, url, cap, "POST",
  2633. "application/x-www-form-urlencoded", post, 0, node,
  2634. bg, err, errcap);
  2635. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  2636. node, bg, err, errcap);
  2637. }
  2638. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  2639. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  2640. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  2641. unsigned int cap, const char *method,
  2642. const char *ctype, const char *post,
  2643. unsigned int post_len, unsigned int node,
  2644. int bg, char *err, unsigned int errcap)
  2645. {
  2646. static char req[1024];
  2647. unsigned int n = 0;
  2648. fetch_seq++;
  2649. if (!fetch_seq)
  2650. fetch_seq = 1;
  2651. w->seq = fetch_seq;
  2652. w->ready = 0;
  2653. w->image_job = 0;
  2654. w->retried = 0;
  2655. w->m.error = 0;
  2656. w->node = node;
  2657. w->bg = bg;
  2658. s_copy(w->url, url, sizeof(w->url));
  2659. s_append_dec(req, &n, w->seq, sizeof(req));
  2660. s_append(req, &n, " ", sizeof(req));
  2661. s_append_dec(req, &n, cap, sizeof(req));
  2662. s_append(req, &n, " ", sizeof(req));
  2663. if (method) {
  2664. unsigned int k;
  2665. s_append(req, &n, "X ", sizeof(req));
  2666. s_append(req, &n, method, sizeof(req));
  2667. s_append(req, &n, " ", sizeof(req));
  2668. s_append_dec(req, &n, post_len, sizeof(req));
  2669. s_append(req, &n, " ", sizeof(req));
  2670. if (!ctype || !ctype[0])
  2671. s_append(req, &n, "-", sizeof(req));
  2672. /* One token on the request line: drop the spaces
  2673. * ("application/json; charset=utf-8" stays valid). */
  2674. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  2675. if (ctype[k] != ' ')
  2676. req[n++] = ctype[k];
  2677. req[n] = '\0';
  2678. s_append(req, &n, " ", sizeof(req));
  2679. } else if (post_len) {
  2680. s_append(req, &n, "POST ", sizeof(req));
  2681. s_append_dec(req, &n, post_len, sizeof(req));
  2682. s_append(req, &n, " ", sizeof(req));
  2683. }
  2684. s_append(req, &n, url, sizeof(req));
  2685. s_append(req, &n, "\n", sizeof(req));
  2686. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  2687. (int)post, (int)post_len) < 0) {
  2688. s_copy(err, "cannot queue form body", errcap);
  2689. return -1;
  2690. }
  2691. u_syscall1(SYS_UNLINK, (int)w->done);
  2692. u_syscall1(SYS_UNLINK, (int)w->meta);
  2693. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  2694. s_copy(err, "cannot queue network request", errcap);
  2695. return -1;
  2696. }
  2697. if (fetch_worker_start(w, err, errcap) != 0)
  2698. return -1;
  2699. w->busy = 1;
  2700. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  2701. return 0;
  2702. }
  2703. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  2704. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  2705. unsigned int errcap)
  2706. {
  2707. static char meta[1024];
  2708. char *p;
  2709. int rn, mseq;
  2710. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  2711. (int)(sizeof(meta) - 1));
  2712. if (rn <= 0) {
  2713. s_copy(err, "network helper failed", errcap);
  2714. return -1;
  2715. }
  2716. meta[rn] = '\0';
  2717. p = meta;
  2718. mseq = (int)meta_uint(&p);
  2719. if (mseq != (int)w->seq) {
  2720. s_copy(err, "stale network response", errcap);
  2721. return -1;
  2722. }
  2723. w->m.status = (int)meta_uint(&p);
  2724. w->m.error = (int)meta_uint(&p);
  2725. w->m.trunc = (int)meta_uint(&p);
  2726. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  2727. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  2728. meta_str(&p, w->m.final, sizeof(w->m.final));
  2729. w->m.len = meta_uint(&p);
  2730. w->m.open_ms = 0;
  2731. w->m.first_ms = 0;
  2732. w->m.total_ms = 0;
  2733. if (*p) {
  2734. w->m.open_ms = meta_uint(&p);
  2735. w->m.first_ms = meta_uint(&p);
  2736. w->m.total_ms = meta_uint(&p);
  2737. }
  2738. if (w->m.error) {
  2739. s_copy(err, uhttp_error_string(w->m.error), errcap);
  2740. return -1;
  2741. }
  2742. w->ready = 1;
  2743. return 0;
  2744. }
  2745. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  2746. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  2747. unsigned int errcap)
  2748. {
  2749. static char done[24];
  2750. char *p;
  2751. int rn, mseq;
  2752. fetch_tty_drain();
  2753. if (!w->busy)
  2754. return -1;
  2755. if (w->ready)
  2756. return 1;
  2757. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  2758. (int)(sizeof(done) - 1));
  2759. if (rn > 0) {
  2760. done[rn] = '\0';
  2761. p = done;
  2762. mseq = (int)meta_uint(&p);
  2763. if (mseq == (int)w->seq) {
  2764. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  2765. fetch_worker_stop(w);
  2766. return -1;
  2767. }
  2768. return 1;
  2769. }
  2770. }
  2771. if (!u_alive((unsigned int)w->pid)) {
  2772. w->pid = -1;
  2773. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  2774. w->retried = 1;
  2775. return 0;
  2776. }
  2777. s_copy(err, "network helper stopped", errcap);
  2778. fetch_worker_stop(w);
  2779. return -1;
  2780. }
  2781. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  2782. s_copy(err, "network request timed out", errcap);
  2783. fetch_worker_stop(w);
  2784. return -1;
  2785. }
  2786. return 0;
  2787. }
  2788. /* Copy the completed body, inflating it if the server ignored our identity
  2789. * request. Mirrors the old fetch_remote body path. */
  2790. static int fetch_worker_read_body(struct fetch_worker *w,
  2791. unsigned char *plain,
  2792. unsigned int plaincap,
  2793. unsigned char *comp,
  2794. unsigned int compcap,
  2795. int *truncated, char *err,
  2796. unsigned int errcap)
  2797. {
  2798. int rv, zr, was_trunc;
  2799. if (contains_ci(w->m.encoding, "gzip") ||
  2800. contains_ci(w->m.encoding, "deflate")) {
  2801. unsigned int comp_len = 0, plen = 0;
  2802. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  2803. (int)compcap);
  2804. if (rv < 0) {
  2805. s_copy(err, "empty response", errcap);
  2806. return -1;
  2807. }
  2808. comp_len = (unsigned int)rv;
  2809. if (comp_len < w->m.len) {
  2810. s_copy(err, "compressed response is too large", errcap);
  2811. return -1;
  2812. }
  2813. if (contains_ci(w->m.encoding, "deflate"))
  2814. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2815. &plen, 0, &was_trunc);
  2816. else
  2817. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2818. &plen, 1, &was_trunc);
  2819. if (zr != 0) {
  2820. s_copy(err, "compressed response is corrupt", errcap);
  2821. return -1;
  2822. }
  2823. *truncated = w->m.trunc || was_trunc;
  2824. return (int)plen;
  2825. }
  2826. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  2827. if (rv < 0) {
  2828. s_copy(err, "empty response", errcap);
  2829. return -1;
  2830. }
  2831. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  2832. return rv;
  2833. }
  2834. static void fetch_worker_release(struct fetch_worker *w)
  2835. {
  2836. u_syscall1(SYS_UNLINK, (int)w->done);
  2837. u_syscall1(SYS_UNLINK, (int)w->meta);
  2838. u_syscall1(SYS_UNLINK, (int)w->body);
  2839. u_syscall1(SYS_UNLINK, (int)w->post);
  2840. u_syscall1(SYS_UNLINK, (int)w->req);
  2841. w->busy = 0;
  2842. w->ready = 0;
  2843. w->image_job = 0;
  2844. }
  2845. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  2846. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  2847. unsigned int errcap)
  2848. {
  2849. for (;;) {
  2850. int rv;
  2851. if (!fetch_wait_passive)
  2852. worker_wait_ui();
  2853. if (cancel_fetch || pending_action) {
  2854. fetch_workers_cancel_busy();
  2855. return FETCH_ABORT;
  2856. }
  2857. rv = fetch_worker_poll(w, err, errcap);
  2858. if (rv != 0)
  2859. return rv == 1 ? 0 : -1;
  2860. u_sleep_ms(10);
  2861. }
  2862. }
  2863. static int fetch_remote(const char *url, unsigned int cap,
  2864. const char *post, unsigned int post_len,
  2865. unsigned char *plain, unsigned int plaincap,
  2866. unsigned char *comp, unsigned int compcap,
  2867. struct fetch_meta *m, int *truncated,
  2868. char *err, unsigned int errcap)
  2869. {
  2870. struct fetch_worker *w = fetch_worker_alloc();
  2871. int rv;
  2872. fetch_last_error = 0;
  2873. if (!w) {
  2874. s_copy(err, "network busy", errcap);
  2875. return -1;
  2876. }
  2877. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  2878. err, errcap) != 0) {
  2879. fetch_worker_release(w);
  2880. return -1;
  2881. }
  2882. rv = fetch_worker_wait(w, err, errcap);
  2883. if (rv == FETCH_ABORT) {
  2884. fetch_worker_release(w);
  2885. return FETCH_ABORT;
  2886. }
  2887. if (rv != 0) {
  2888. fetch_last_error = w->m.error;
  2889. fetch_worker_release(w);
  2890. return -1;
  2891. }
  2892. *m = w->m;
  2893. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  2894. truncated, err, errcap);
  2895. fetch_worker_release(w);
  2896. if (rv >= 0 && (cancel_fetch || pending_action))
  2897. return FETCH_ABORT;
  2898. return rv;
  2899. }
  2900. static int fetch_worker_status(const struct fetch_worker *w)
  2901. {
  2902. return w->m.status;
  2903. }
  2904. /* fetch()/XHR through a helper: one request, the status and body come back
  2905. * whatever the HTTP status (a 401 is an answer, not a network error). */
  2906. static int js_worker_http(const char *method, const char *url,
  2907. const char *ctype, const char *body,
  2908. unsigned int body_len, struct js_http_resp *r,
  2909. char *err, int errcap)
  2910. {
  2911. struct fetch_worker *w = fetch_worker_alloc();
  2912. unsigned char *plain;
  2913. int rv, tr = 0;
  2914. if (!w) {
  2915. s_copy(err, "network busy", (unsigned int)errcap);
  2916. return -1;
  2917. }
  2918. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  2919. body_len, 0, 0, err,
  2920. (unsigned int)errcap) != 0) {
  2921. fetch_worker_release(w);
  2922. return -1;
  2923. }
  2924. fetch_wait_passive++;
  2925. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  2926. fetch_wait_passive--;
  2927. if (rv != 0) {
  2928. if (rv == FETCH_ABORT)
  2929. s_copy(err, "page is navigating", (unsigned int)errcap);
  2930. fetch_worker_release(w);
  2931. return -1;
  2932. }
  2933. r->status = w->m.status;
  2934. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  2935. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  2936. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  2937. if (!plain) {
  2938. fetch_worker_release(w);
  2939. s_copy(err, "out of memory", (unsigned int)errcap);
  2940. return -1;
  2941. }
  2942. if (w->m.len == 0) {
  2943. rv = 0; /* 204, an empty 200: no body file */
  2944. } else {
  2945. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  2946. image_io_buf, BR_PAGE_COMP_MAX,
  2947. &tr, err, (unsigned int)errcap);
  2948. }
  2949. fetch_worker_release(w);
  2950. if (rv < 0) {
  2951. free(plain);
  2952. return -1;
  2953. }
  2954. plain[rv] = '\0';
  2955. r->body = (char *)plain;
  2956. r->len = (unsigned int)rv;
  2957. return 0;
  2958. }
  2959. /* ---- HTTP / file fetch ---- */
  2960. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  2961. unsigned int *outlen, int *is_local, char *ctype,
  2962. unsigned int ctcap, char *final, unsigned int finalcap,
  2963. char *err, unsigned int errcap, int *truncated,
  2964. const char *post, unsigned int post_len)
  2965. {
  2966. unsigned char *buf;
  2967. unsigned int len;
  2968. int tr = 0;
  2969. int rv;
  2970. *out = 0;
  2971. *outlen = 0;
  2972. *truncated = 0;
  2973. if (final && finalcap)
  2974. final[0] = '\0';
  2975. if (ctype && ctcap)
  2976. ctype[0] = '\0';
  2977. if (url[0] == '/') {
  2978. char pathbuf[BR_URL_MAX];
  2979. const char *open_url = url;
  2980. unsigned int i = 0;
  2981. /* A local form GET keeps ?query in the address bar but the
  2982. * file lookup uses the path alone, like a real browser. */
  2983. while (url[i] && url[i] != '?' && url[i] != '#')
  2984. i++;
  2985. if (url[i]) {
  2986. s_copy(pathbuf, url, i + 1);
  2987. open_url = pathbuf;
  2988. }
  2989. buf = (unsigned char *)malloc(cap);
  2990. if (!buf) {
  2991. s_copy(err, "out of memory", errcap);
  2992. return -1;
  2993. }
  2994. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  2995. if (rv < 0) {
  2996. free(buf);
  2997. s_copy(err, "file not found", errcap);
  2998. return -1;
  2999. }
  3000. *out = buf;
  3001. *outlen = (unsigned int)rv;
  3002. *is_local = 1;
  3003. if (ctype)
  3004. s_copy(ctype, "text/html", ctcap);
  3005. if (final)
  3006. s_copy(final, url, finalcap);
  3007. if ((unsigned int)rv == cap)
  3008. *truncated = 1;
  3009. return 0;
  3010. }
  3011. buf = (unsigned char *)malloc(cap);
  3012. if (!buf) {
  3013. s_copy(err, "out of memory", errcap);
  3014. return -1;
  3015. }
  3016. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3017. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3018. if (rv == FETCH_ABORT) {
  3019. free(buf);
  3020. return FETCH_ABORT;
  3021. }
  3022. if (rv < 0) {
  3023. free(buf);
  3024. return -1;
  3025. }
  3026. len = (unsigned int)rv;
  3027. if (len == 0) {
  3028. free(buf);
  3029. s_copy(err, "empty response", errcap);
  3030. return -1;
  3031. }
  3032. if (ctype)
  3033. s_copy(ctype, fetch_meta.ctype, ctcap);
  3034. if (final && fetch_meta.final[0])
  3035. s_copy(final, fetch_meta.final, finalcap);
  3036. *is_local = 0;
  3037. *out = buf;
  3038. *outlen = len;
  3039. *truncated = tr;
  3040. return 0;
  3041. }
  3042. /* Load every @font-face the parser registered. Local files go through
  3043. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  3044. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  3045. * to the built-in regular/bold/italic/mono set. */
  3046. static void load_font_faces(void)
  3047. {
  3048. unsigned int i;
  3049. memset(font_faces, 0, sizeof(font_faces));
  3050. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  3051. i <= BR_MAX_FACES; i++) {
  3052. const char *url = br_font_face_url((int)i);
  3053. const char *base = br_font_face_base((int)i);
  3054. char abs[BR_URL_MAX];
  3055. if (!url || !url[0])
  3056. continue;
  3057. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  3058. sizeof(abs)) != 0)
  3059. continue;
  3060. if (abs[0] == '/') {
  3061. font_faces[i - 1] = ufont_face_open_path(abs);
  3062. } else if (is_http(abs)) {
  3063. unsigned char *buf;
  3064. char err[64];
  3065. int rv, tr = 0;
  3066. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  3067. if (!buf)
  3068. continue;
  3069. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3070. UFONT_MAX_FILE, image_io_buf,
  3071. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  3072. err, sizeof(err));
  3073. if (rv > 0)
  3074. font_faces[i - 1] = ufont_face_open_mem(buf,
  3075. rv);
  3076. free(buf);
  3077. }
  3078. }
  3079. }
  3080. /* Remote scripts are cached under /share for the current boot, like the
  3081. * stylesheet cache, so reloads and later visits skip the network. */
  3082. static int script_cache_count;
  3083. static unsigned int script_cache_hash(const char *s)
  3084. {
  3085. unsigned int h = 2166136261u;
  3086. while (*s) {
  3087. h ^= (unsigned char)*s++;
  3088. h *= 16777619u;
  3089. }
  3090. return h;
  3091. }
  3092. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3093. {
  3094. unsigned int n = 0;
  3095. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3096. s_append_dec(out, &n, script_cache_hash(url), cap);
  3097. }
  3098. static void script_cache_clear(void)
  3099. {
  3100. struct sys_dirent d;
  3101. char path[96];
  3102. for (;;) {
  3103. int i, found = 0;
  3104. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3105. (int)&d) == 1; i++) {
  3106. unsigned int n = 0;
  3107. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3108. continue;
  3109. s_append(path, &n, "/share/", sizeof(path));
  3110. s_append(path, &n, d.name, sizeof(path));
  3111. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3112. return;
  3113. found = 1;
  3114. break;
  3115. }
  3116. if (!found)
  3117. break;
  3118. }
  3119. script_cache_count = 0;
  3120. }
  3121. static void script_cache_init(void)
  3122. {
  3123. struct sys_dirent d;
  3124. int i, count = 0;
  3125. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3126. (int)&d) == 1; i++)
  3127. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3128. count++;
  3129. if (count >= SCRIPT_CACHE_MAX) {
  3130. script_cache_clear();
  3131. return;
  3132. }
  3133. script_cache_count = count;
  3134. }
  3135. static int script_cache_get(const char *url, unsigned char **out,
  3136. unsigned int *outlen)
  3137. {
  3138. char path[96];
  3139. struct sys_stat st;
  3140. unsigned char *buf;
  3141. int rn;
  3142. script_cache_path(url, path, sizeof(path));
  3143. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3144. st.size >= SCRIPT_CACHE_FILE_MAX)
  3145. return 0;
  3146. buf = (unsigned char *)malloc(st.size + 1);
  3147. if (!buf)
  3148. return 0;
  3149. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3150. if (rn != (int)st.size) {
  3151. free(buf);
  3152. return 0;
  3153. }
  3154. buf[st.size] = '\0';
  3155. *out = buf;
  3156. *outlen = st.size;
  3157. return 1;
  3158. }
  3159. static void script_cache_put(const char *url, const unsigned char *data,
  3160. unsigned int len)
  3161. {
  3162. char path[96];
  3163. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3164. len >= SCRIPT_CACHE_FILE_MAX)
  3165. return;
  3166. script_cache_path(url, path, sizeof(path));
  3167. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3168. (int)len) >= 0)
  3169. script_cache_count++;
  3170. }
  3171. static int script_cache_has(const char *url)
  3172. {
  3173. char path[96];
  3174. struct sys_stat st;
  3175. script_cache_path(url, path, sizeof(path));
  3176. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3177. st.size < SCRIPT_CACHE_FILE_MAX;
  3178. }
  3179. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3180. static int fetch_script_text(const char *url, unsigned char **out,
  3181. unsigned int *outlen, char *err,
  3182. unsigned int errcap)
  3183. {
  3184. unsigned char *buf;
  3185. unsigned int len;
  3186. int local, truncated = 0;
  3187. char ctype[64], final[BR_URL_MAX];
  3188. int rv;
  3189. *out = 0;
  3190. *outlen = 0;
  3191. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3192. return 0;
  3193. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3194. sizeof(ctype), final, sizeof(final), err, errcap,
  3195. &truncated, 0, 0);
  3196. if (rv != 0)
  3197. return rv;
  3198. if (truncated || len >= BR_SCRIPT_MAX) {
  3199. free(buf);
  3200. s_copy(err, "script is too large", errcap);
  3201. return -1;
  3202. }
  3203. buf[len] = '\0';
  3204. if (!local)
  3205. script_cache_put(url, buf, len);
  3206. *out = buf;
  3207. *outlen = len;
  3208. return 0;
  3209. }
  3210. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  3211. * the heap, so images must not allocate their file body from it as well. */
  3212. static int fetch_image(const char *url, unsigned int cap,
  3213. unsigned char **out, unsigned int *outlen,
  3214. char *err, unsigned int errcap)
  3215. {
  3216. unsigned int len;
  3217. int tr = 0;
  3218. int rv;
  3219. *out = 0;
  3220. *outlen = 0;
  3221. if (cap > BR_IMG_FILE_MAX)
  3222. cap = BR_IMG_FILE_MAX;
  3223. if (url[0] == '/') {
  3224. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  3225. (int)cap);
  3226. if (rv < 0) {
  3227. s_copy(err, "file not found", errcap);
  3228. return -1;
  3229. }
  3230. *out = image_file_buf;
  3231. *outlen = (unsigned int)rv;
  3232. return 0;
  3233. }
  3234. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  3235. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  3236. if (rv == FETCH_ABORT)
  3237. return FETCH_ABORT;
  3238. if (rv < 0)
  3239. return -1;
  3240. len = (unsigned int)rv;
  3241. if (len == 0) {
  3242. s_copy(err, "empty image", errcap);
  3243. return -1;
  3244. }
  3245. *out = image_file_buf;
  3246. *outlen = len;
  3247. return 0;
  3248. }
  3249. /* Remote stylesheets are immutable enough for the current boot: keep
  3250. * successful responses under /share so a reload, a second visit or a fresh
  3251. * browser launch does not fetch the same five sheets over the network again.
  3252. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  3253. static int css_cache_count;
  3254. static unsigned int css_cache_hash(const char *s)
  3255. {
  3256. unsigned int h = 2166136261u;
  3257. while (*s) {
  3258. h ^= (unsigned char)*s++;
  3259. h *= 16777619u;
  3260. }
  3261. return h;
  3262. }
  3263. static void css_cache_path(const char *url, char *out, unsigned int cap)
  3264. {
  3265. unsigned int n = 0;
  3266. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  3267. s_append_dec(out, &n, css_cache_hash(url), cap);
  3268. }
  3269. static void css_cache_clear(void)
  3270. {
  3271. struct sys_dirent d;
  3272. char path[96];
  3273. for (;;) {
  3274. int i, found = 0;
  3275. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3276. (int)&d) == 1; i++) {
  3277. unsigned int n = 0;
  3278. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  3279. continue;
  3280. s_append(path, &n, "/share/", sizeof(path));
  3281. s_append(path, &n, d.name, sizeof(path));
  3282. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3283. return;
  3284. found = 1;
  3285. break;
  3286. }
  3287. if (!found)
  3288. break;
  3289. }
  3290. css_cache_count = 0;
  3291. }
  3292. static void css_cache_init(void)
  3293. {
  3294. struct sys_dirent d;
  3295. int i, count = 0;
  3296. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3297. (int)&d) == 1; i++)
  3298. if (starts_with(d.name, CSS_CACHE_PREFIX))
  3299. count++;
  3300. if (count >= CSS_CACHE_MAX) {
  3301. css_cache_clear();
  3302. return;
  3303. }
  3304. css_cache_count = count;
  3305. }
  3306. static int css_cache_get(const char *url, unsigned char **out,
  3307. unsigned int *outlen)
  3308. {
  3309. char path[96];
  3310. int rn;
  3311. css_cache_path(url, path, sizeof(path));
  3312. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  3313. (int)CSS_CACHE_FILE_MAX);
  3314. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  3315. return 0;
  3316. *out = image_io_buf;
  3317. *outlen = (unsigned int)rn;
  3318. return 1;
  3319. }
  3320. static void css_cache_put(const char *url, const unsigned char *data,
  3321. unsigned int len)
  3322. {
  3323. char path[96];
  3324. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  3325. len >= CSS_CACHE_FILE_MAX)
  3326. return;
  3327. css_cache_path(url, path, sizeof(path));
  3328. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3329. (int)len) >= 0)
  3330. css_cache_count++;
  3331. }
  3332. static int css_cache_has(const char *url)
  3333. {
  3334. char path[96];
  3335. struct sys_stat st;
  3336. css_cache_path(url, path, sizeof(path));
  3337. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3338. st.size < CSS_CACHE_FILE_MAX;
  3339. }
  3340. /* Read one stylesheet into the shared static buffer. CSS is parsed
  3341. * immediately, so it does not need the page heap; this leaves the heap for
  3342. * the 2 MB page body, the rules and the scaled image bitmaps. */
  3343. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  3344. char *err, unsigned int errcap)
  3345. {
  3346. unsigned int len;
  3347. int tr = 0;
  3348. int rv;
  3349. *out = 0;
  3350. *outlen = 0;
  3351. if (url[0] == '/') {
  3352. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  3353. (int)BR_CSS_MAX);
  3354. if (rv < 0) {
  3355. s_copy(err, "stylesheet not found", errcap);
  3356. return -1;
  3357. }
  3358. *out = image_io_buf;
  3359. *outlen = (unsigned int)rv;
  3360. return 0;
  3361. }
  3362. if (css_cache_get(url, out, outlen))
  3363. return 0;
  3364. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  3365. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  3366. &fetch_meta, &tr, err, errcap);
  3367. if (rv == FETCH_ABORT)
  3368. return FETCH_ABORT;
  3369. if (rv < 0)
  3370. return -1;
  3371. len = (unsigned int)rv;
  3372. if (len == 0) {
  3373. s_copy(err, "empty stylesheet", errcap);
  3374. return -1;
  3375. }
  3376. *out = image_io_buf;
  3377. *outlen = len;
  3378. css_cache_put(url, image_io_buf, len);
  3379. return 0;
  3380. }
  3381. static void redraw_now(void);
  3382. static char error_page[1024];
  3383. static void show_error(const char *title, const char *detail)
  3384. {
  3385. char *page = error_page;
  3386. unsigned int n = 0;
  3387. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  3388. s_append(page, &n, title, sizeof(error_page));
  3389. s_append(page, &n, "</h2><p>", sizeof(error_page));
  3390. {
  3391. const char *p = detail;
  3392. while (*p && n + 1 < sizeof(error_page)) {
  3393. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  3394. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  3395. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  3396. else page[n++] = *p;
  3397. p++;
  3398. }
  3399. }
  3400. page[n] = '\0';
  3401. s_append(page, &n, "</p><p>", sizeof(error_page));
  3402. s_append(page, &n, page_url, sizeof(error_page));
  3403. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  3404. sizeof(error_page));
  3405. br_parse(&doc, page, n);
  3406. layout_valid = 0;
  3407. preload_active = 0;
  3408. preload_pending = 0;
  3409. preload_wait = 0;
  3410. fetch_workers_cancel_busy();
  3411. s_copy(page_title, title, sizeof(page_title));
  3412. page_loading = 0;
  3413. set_status(title, 1, 0);
  3414. ngui_invalidate(&ui);
  3415. }
  3416. static int decode_direct_image(const unsigned char *data, unsigned int len,
  3417. unsigned int node)
  3418. {
  3419. if (image_count >= BR_MAX_IMAGES)
  3420. return -1;
  3421. if (decode_image_data(data, len, &images[0], 0, 0) != 0)
  3422. return -1;
  3423. doc.nodes[node].img_index = 0;
  3424. image_count = 1;
  3425. return 0;
  3426. }
  3427. static int ancestor_is(unsigned int node, unsigned int tag)
  3428. {
  3429. unsigned int p = doc.nodes[node].parent;
  3430. while (p) {
  3431. if (doc.nodes[p].tag == tag)
  3432. return 1;
  3433. p = doc.nodes[p].parent;
  3434. }
  3435. return 0;
  3436. }
  3437. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  3438. * parallel but parsed in document order, so the cascade is unchanged. */
  3439. static int load_stylesheets(void)
  3440. {
  3441. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  3442. static unsigned char remote[BR_MAX_SHEETS];
  3443. struct fetch_worker *slot[BR_MAX_SHEETS];
  3444. unsigned int i, n = 0, next = 0, k;
  3445. char err[64];
  3446. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  3447. struct br_node *nd = &doc.nodes[i];
  3448. const char *rel, *href;
  3449. char url[BR_URL_MAX];
  3450. int dup = 0;
  3451. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  3452. continue;
  3453. rel = br_rel(&doc, i);
  3454. if (!contains_ci(rel, "stylesheet"))
  3455. continue;
  3456. href = br_href(&doc, i);
  3457. if (!href[0])
  3458. continue;
  3459. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  3460. continue;
  3461. for (k = 0; k < n; k++)
  3462. if (s_eq(urls[k], url)) {
  3463. dup = 1;
  3464. break;
  3465. }
  3466. if (dup)
  3467. continue;
  3468. s_copy(urls[n], url, BR_URL_MAX);
  3469. remote[n] = url[0] != '/' && !css_cache_has(url);
  3470. n++;
  3471. }
  3472. for (i = 0; i < BR_MAX_SHEETS; i++)
  3473. slot[i] = 0;
  3474. /* Start as many remote sheets as there are free workers. */
  3475. for (; next < n; next++) {
  3476. struct fetch_worker *w;
  3477. if (!remote[next])
  3478. continue;
  3479. w = fetch_worker_alloc();
  3480. if (!w)
  3481. break;
  3482. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  3483. err, sizeof(err)) != 0) {
  3484. fetch_worker_release(w);
  3485. remote[next] = 0;
  3486. continue;
  3487. }
  3488. slot[next] = w;
  3489. }
  3490. for (i = 0; i < n; i++) {
  3491. unsigned char *data = 0;
  3492. unsigned int len = 0;
  3493. int rv;
  3494. if (!remote[i]) {
  3495. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  3496. if (rv == FETCH_ABORT) {
  3497. fetch_workers_stop_all();
  3498. return FETCH_ABORT;
  3499. }
  3500. if (rv != 0 || !len)
  3501. continue;
  3502. } else {
  3503. struct fetch_worker *w = slot[i];
  3504. int tr = 0;
  3505. if (!w) {
  3506. w = fetch_worker_alloc();
  3507. if (!w)
  3508. continue;
  3509. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  3510. 0, 0, 0, 0, err,
  3511. sizeof(err)) != 0) {
  3512. fetch_worker_release(w);
  3513. remote[i] = 0;
  3514. if (i == next)
  3515. next++;
  3516. continue;
  3517. }
  3518. slot[i] = w;
  3519. if (i == next)
  3520. next++;
  3521. }
  3522. rv = fetch_worker_wait(w, err, sizeof(err));
  3523. if (rv == FETCH_ABORT) {
  3524. fetch_workers_stop_all();
  3525. return FETCH_ABORT;
  3526. }
  3527. if (rv == 0)
  3528. rv = fetch_worker_read_body(w, image_io_buf,
  3529. BR_CSS_MAX,
  3530. image_io_buf + BR_CSS_MAX,
  3531. BR_CSS_COMP_MAX, &tr,
  3532. err, sizeof(err));
  3533. else
  3534. rv = -1;
  3535. fetch_worker_release(w);
  3536. slot[i] = 0;
  3537. /* Refill the worker window before parsing this sheet. */
  3538. for (; next < n; next++) {
  3539. struct fetch_worker *nw;
  3540. if (!remote[next])
  3541. continue;
  3542. nw = fetch_worker_alloc();
  3543. if (!nw)
  3544. break;
  3545. if (fetch_worker_submit(nw, urls[next],
  3546. BR_CSS_MAX, 0, 0, 0, 0,
  3547. err, sizeof(err)) != 0) {
  3548. fetch_worker_release(nw);
  3549. remote[next] = 0;
  3550. continue;
  3551. }
  3552. slot[next] = nw;
  3553. }
  3554. if (rv <= 0)
  3555. continue;
  3556. len = (unsigned int)rv;
  3557. data = image_io_buf;
  3558. css_cache_put(urls[i], data, len);
  3559. }
  3560. if (len) {
  3561. br_set_font_base(urls[i]);
  3562. br_parse_css_text(&doc, (const char *)data, len);
  3563. }
  3564. }
  3565. br_set_font_base(page_url);
  3566. br_parse_inline_css(&doc);
  3567. load_font_faces();
  3568. br_reset_styles(&doc);
  3569. layout_valid = 0;
  3570. return 0;
  3571. }
  3572. static void preload_begin(void)
  3573. {
  3574. preload_active = 1;
  3575. preload_pending = 0;
  3576. preload_wait = 1;
  3577. preload_max_jobs = FETCH_WORKERS;
  3578. preload_node = 0;
  3579. preload_loaded = 0;
  3580. preload_scroll = 0;
  3581. }
  3582. /* Styles are computed top-down during layout, but images inside a hidden
  3583. * menu/carousel are never visited and keep img_top == 0. Without this check
  3584. * the preloader walks the DOM in node order and spends the whole image
  3585. * budget on logos and off-canvas thumbnails the reader cannot see. */
  3586. static int node_hidden(unsigned int node)
  3587. {
  3588. unsigned int path[32], n = 0, p = node, i;
  3589. struct br_style st, parent;
  3590. while (p && n < sizeof(path) / sizeof(path[0])) {
  3591. path[n++] = p;
  3592. p = doc.nodes[p].parent;
  3593. }
  3594. parent = (struct br_style){0};
  3595. parent.font_px = 16;
  3596. parent.display = BR_DISPLAY_BLOCK;
  3597. for (i = n; i > 0; i--) {
  3598. br_style_for(&doc, path[i - 1], &parent, &st);
  3599. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  3600. st.opacity_hidden)
  3601. return 1;
  3602. parent = st;
  3603. }
  3604. return 0;
  3605. }
  3606. static struct br_style base_style(void);
  3607. static void style_for_node(unsigned int node, struct br_style *out)
  3608. {
  3609. unsigned int p = doc.nodes[node].parent;
  3610. struct br_style parent;
  3611. if (p) {
  3612. style_for_node(p, &parent);
  3613. br_style_for(&doc, node, &parent, out);
  3614. } else {
  3615. parent = base_style();
  3616. br_style_for(&doc, node, &parent, out);
  3617. }
  3618. }
  3619. /* ---- parallel image preloading ---- *
  3620. *
  3621. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  3622. * preload_step() only starts jobs and harvests completed ones; the browser
  3623. * main loop keeps drawing between calls, instead of blocking on one fetch.
  3624. */
  3625. static int preload_active_jobs(void)
  3626. {
  3627. int i, n = 0;
  3628. for (i = 0; i < FETCH_WORKERS; i++)
  3629. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  3630. n++;
  3631. return n;
  3632. }
  3633. static void preload_job_error(struct fetch_worker *w)
  3634. {
  3635. if (w->node < doc.nnode) {
  3636. if (w->bg)
  3637. doc.nodes[w->node].bg_img_index = -2;
  3638. else
  3639. doc.nodes[w->node].img_index = -2;
  3640. ngui_invalidate(&ui);
  3641. }
  3642. }
  3643. static void preload_decode(unsigned int node, int bg,
  3644. const unsigned char *data, unsigned int len)
  3645. {
  3646. if (image_count >= BR_MAX_IMAGES) {
  3647. if (bg)
  3648. doc.nodes[node].bg_img_index = -2;
  3649. else
  3650. doc.nodes[node].img_index = -2;
  3651. return;
  3652. }
  3653. if (decode_image_data(data, len, &images[image_count],
  3654. bg && node < BR_MAX_NODES &&
  3655. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  3656. bg && node < BR_MAX_NODES &&
  3657. layout_boxes[node].valid ? layout_boxes[node].h : 0) == 0) {
  3658. if (bg)
  3659. doc.nodes[node].bg_img_index = (short)image_count;
  3660. else
  3661. doc.nodes[node].img_index = (short)image_count;
  3662. image_count++;
  3663. preload_loaded++;
  3664. layout_valid = 0;
  3665. } else {
  3666. if (bg)
  3667. doc.nodes[node].bg_img_index = -2;
  3668. else
  3669. doc.nodes[node].img_index = -2;
  3670. }
  3671. ngui_invalidate(&ui);
  3672. }
  3673. /* Harvest one completed worker. Returns 1 when a job was finished. */
  3674. static int preload_finish_worker(struct fetch_worker *w)
  3675. {
  3676. char err[64];
  3677. int rv, tr = 0;
  3678. rv = fetch_worker_poll(w, err, sizeof(err));
  3679. if (rv < 0) {
  3680. preload_job_error(w);
  3681. fetch_worker_release(w);
  3682. return 1;
  3683. }
  3684. if (rv == 0)
  3685. return 0;
  3686. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  3687. image_comp_buf, BR_IMG_FILE_MAX,
  3688. &tr, err, sizeof(err));
  3689. if (rv >= 0)
  3690. preload_decode(w->node, w->bg, image_file_buf,
  3691. (unsigned int)rv);
  3692. else
  3693. preload_job_error(w);
  3694. fetch_worker_release(w);
  3695. return 1;
  3696. }
  3697. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  3698. * the number of jobs started. */
  3699. static int preload_fill_jobs(void)
  3700. {
  3701. int started = 0;
  3702. char err[64];
  3703. while (preload_active && preload_node < doc.nnode) {
  3704. unsigned int i = preload_node;
  3705. struct br_node *nd = &doc.nodes[i];
  3706. const char *src;
  3707. char url[BR_URL_MAX];
  3708. struct fetch_worker *w;
  3709. if (preload_active_jobs() >= preload_max_jobs)
  3710. break;
  3711. if (nd->type != BR_NODE_ELEM) {
  3712. preload_node++;
  3713. continue;
  3714. }
  3715. if (nd->tag != BR_TAG_IMG) {
  3716. if (nd->bg_img_index == -1) {
  3717. struct br_style bs;
  3718. style_for_node(i, &bs);
  3719. if (bs.display != BR_DISPLAY_NONE &&
  3720. !bs.vis_hidden && bs.bg_image) {
  3721. const char *bsrc =
  3722. br_bg_image_url(bs.bg_image - 1);
  3723. /* Lazy like <img>: a background box
  3724. * below the viewport (or not laid
  3725. * out yet) waits for the next scan. */
  3726. if (bsrc[0] &&
  3727. (!layout_boxes[i].valid ||
  3728. block_top[i] >
  3729. (unsigned int)(page_scroll.offset +
  3730. page_rect.h + 160))) {
  3731. preload_pending = 1;
  3732. preload_node++;
  3733. continue;
  3734. }
  3735. if (bsrc[0] &&
  3736. !contains_ci(bsrc, ".svg") &&
  3737. !starts_with(bsrc, "data:") &&
  3738. resolve_link(page_url, bsrc, url,
  3739. sizeof(url)) == 0) {
  3740. if (image_count +
  3741. preload_active_jobs() >=
  3742. BR_MAX_IMAGES) {
  3743. preload_node = doc.nnode;
  3744. break;
  3745. }
  3746. if (url[0] == '/') {
  3747. unsigned char *data = 0;
  3748. unsigned int len = 0;
  3749. preload_node = i + 1;
  3750. if (fetch_image(url,
  3751. BR_IMG_FILE_MAX,
  3752. &data, &len,
  3753. err,
  3754. sizeof(err)) == 0)
  3755. preload_decode(i, 1, data, len);
  3756. else
  3757. nd->bg_img_index = -2;
  3758. continue;
  3759. }
  3760. w = fetch_worker_alloc();
  3761. if (!w)
  3762. return started;
  3763. preload_node = i + 1;
  3764. if (fetch_worker_submit(w, url,
  3765. BR_IMG_FILE_MAX,
  3766. 0, 0, i, 1,
  3767. err,
  3768. sizeof(err)) != 0) {
  3769. nd->bg_img_index = -2;
  3770. fetch_worker_release(w);
  3771. continue;
  3772. }
  3773. w->image_job = 1;
  3774. w->deadline = u_ticks_ms() +
  3775. BR_IMG_JOB_TIMEOUT_MS;
  3776. /* in flight: rescans skip it */
  3777. nd->bg_img_index = -3;
  3778. started++;
  3779. continue;
  3780. }
  3781. }
  3782. nd->bg_img_index = -2;
  3783. }
  3784. preload_node++;
  3785. continue;
  3786. }
  3787. if (nd->img_index != -1) {
  3788. preload_node++;
  3789. continue;
  3790. }
  3791. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  3792. preload_node++;
  3793. continue;
  3794. }
  3795. src = br_src(&doc, i);
  3796. if (!src[0] || contains_ci(src, ".svg") ||
  3797. starts_with(src, "data:")) {
  3798. preload_node++;
  3799. continue;
  3800. }
  3801. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  3802. preload_node++;
  3803. continue;
  3804. }
  3805. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  3806. preload_node = doc.nnode;
  3807. break;
  3808. }
  3809. /* Do not stop at the first below-fold image: DOM order is
  3810. * not visual order, and a footer/ad image early in the DOM
  3811. * used to hide every later article image from the loader. */
  3812. if (img_top[i] >
  3813. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  3814. preload_pending = 1;
  3815. preload_node++;
  3816. continue;
  3817. }
  3818. if (url[0] == '/') {
  3819. unsigned char *data = 0;
  3820. unsigned int len = 0;
  3821. preload_node = i + 1;
  3822. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  3823. err, sizeof(err)) == 0)
  3824. preload_decode(i, 0, data, len);
  3825. else
  3826. nd->img_index = -2;
  3827. continue;
  3828. }
  3829. w = fetch_worker_alloc();
  3830. if (!w)
  3831. return started;
  3832. preload_node = i + 1;
  3833. {
  3834. char msg[64];
  3835. unsigned int n = 0;
  3836. s_append(msg, &n, "Loading images ", sizeof(msg));
  3837. s_append_dec(msg, &n,
  3838. (unsigned int)preload_loaded + 1,
  3839. sizeof(msg));
  3840. s_append(msg, &n, "...", sizeof(msg));
  3841. set_status(msg, 0, 0);
  3842. }
  3843. if (fetch_worker_submit(w, url, BR_IMG_FILE_MAX, 0, 0, i, 0,
  3844. err, sizeof(err)) != 0) {
  3845. nd->img_index = -2;
  3846. fetch_worker_release(w);
  3847. continue;
  3848. }
  3849. w->image_job = 1;
  3850. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  3851. nd->img_index = -3; /* in flight: rescans skip it */
  3852. started++;
  3853. }
  3854. return started;
  3855. }
  3856. static void preload_step(void)
  3857. {
  3858. int i;
  3859. if (!preload_active)
  3860. return;
  3861. if (cancel_fetch || pending_action) {
  3862. preload_active = 0;
  3863. preload_pending = 0;
  3864. fetch_workers_cancel_busy();
  3865. return;
  3866. }
  3867. preload_fill_jobs();
  3868. /* Decode at most one completed image per main-loop pass. A full-size
  3869. * JPEG decode blocks this single-threaded UI for a long time, and
  3870. * harvesting a batch back-to-back starved the TCP pump (and therefore
  3871. * every other image download) on slow CPUs: requests looked stuck
  3872. * while four decodes ran in a row. */
  3873. for (i = 0; i < FETCH_WORKERS; i++) {
  3874. if (!fetch_workers[i].busy)
  3875. continue;
  3876. if (preload_finish_worker(&fetch_workers[i]))
  3877. return;
  3878. }
  3879. if (preload_active && preload_node >= doc.nnode &&
  3880. preload_active_jobs() == 0) {
  3881. preload_active = 0;
  3882. if (preload_pending)
  3883. preload_scroll = page_scroll.offset;
  3884. else
  3885. preload_pending = 0;
  3886. /* Keep the now idle helpers and their connections; a later
  3887. * navigation reuses them. They exit after ten idle seconds,
  3888. * and losing window focus stops them at once. */
  3889. set_status(post_status_text, post_status_error, post_status_ttl);
  3890. ngui_invalidate(&ui);
  3891. }
  3892. }
  3893. /* Set by navigate() when it turned a typed bare host into https://; the next
  3894. * load_page() consumes it and may retry over http. */
  3895. static int nav_https_upgraded;
  3896. /* Errors that mean "https is not served here" rather than "the site is
  3897. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  3898. static int https_fallback_error(int e)
  3899. {
  3900. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  3901. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  3902. e == UHTTP_ERR_RESET;
  3903. }
  3904. static void history_push(const char *url)
  3905. {
  3906. if (!url || !url[0])
  3907. return;
  3908. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  3909. s_eq(history[hist_pos], url))
  3910. return;
  3911. if (hist_len > 0 && hist_pos + 1 < hist_len)
  3912. hist_len = hist_pos + 1;
  3913. if (hist_len < BR_HISTORY) {
  3914. s_copy(history[hist_len], url, BR_URL_MAX);
  3915. hist_pos = hist_len;
  3916. hist_len++;
  3917. } else {
  3918. int i;
  3919. for (i = 1; i < BR_HISTORY; i++)
  3920. s_copy(history[i - 1], history[i], BR_URL_MAX);
  3921. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  3922. hist_pos = BR_HISTORY - 1;
  3923. }
  3924. }
  3925. static void load_page(const char *url, int local, int push)
  3926. {
  3927. unsigned char *body = 0;
  3928. unsigned int len = 0;
  3929. int truncated = 0;
  3930. struct img_info image_info;
  3931. char ctype[64];
  3932. char final[BR_URL_MAX];
  3933. char err[80];
  3934. const char *detail = 0;
  3935. const char *post = pending_post_is ? pending_post : 0;
  3936. unsigned int post_len = pending_post_len;
  3937. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  3938. /* Phase timings for the status line: where a slow load spends it. */
  3939. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  3940. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  3941. int upgraded = nav_https_upgraded;
  3942. int retried = 0;
  3943. int rv;
  3944. nav_https_upgraded = 0;
  3945. final[0] = '\0';
  3946. pending_post_len = 0;
  3947. pending_post_is = 0;
  3948. cancel_fetch = 0;
  3949. preload_active = 0;
  3950. preload_pending = 0;
  3951. fetch_workers_prepare_nav(url);
  3952. js_browser_stop();
  3953. js_last_status[0] = '\0';
  3954. js_last_error = 0;
  3955. heap_clear();
  3956. image_reset();
  3957. form_reset_state();
  3958. layout_valid = 0;
  3959. page_scroll.offset = 0;
  3960. page_scroll.dragging = 0;
  3961. page_title[0] = '\0';
  3962. page_loading = 1;
  3963. page_is_local = local;
  3964. s_copy(page_url, url, sizeof(page_url));
  3965. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3966. url_in.len = s_len(url_in.text);
  3967. url_in.cursor = url_in.len;
  3968. url_in.scroll = 0;
  3969. ngui_set_focus(&ui, 0);
  3970. if (final[0])
  3971. final[0] = '\0';
  3972. if (push)
  3973. history_push(url);
  3974. set_status("Loading...", 0, 0);
  3975. ngui_invalidate(&ui);
  3976. /* heap_clear() detaches the fonts, so attach them again before the
  3977. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  3978. if (heap_start() != 0) {
  3979. show_error("Out of memory", "Cannot allocate the page buffer");
  3980. return;
  3981. }
  3982. br_parse_plain(&doc, "", 0); /* blank while loading */
  3983. ngui_font_attach(&ui);
  3984. redraw_now();
  3985. browser_rules_alloc();
  3986. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  3987. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  3988. &truncated, post, post_len);
  3989. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  3990. fetch_last_error == UHTTP_ERR_DNS) {
  3991. /* A busy previous page can leave the receiver ring full just
  3992. * long enough to lose a DNS reply. Tear the old helpers down
  3993. * and try once more before giving up. */
  3994. retried = 1;
  3995. fetch_workers_stop_all();
  3996. u_sleep_ms(500);
  3997. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  3998. sizeof(ctype), final, sizeof(final), err,
  3999. sizeof(err), &truncated, post, post_len);
  4000. }
  4001. if (rv == FETCH_ABORT)
  4002. return;
  4003. t_fetch = u_ticks_ms() - t_start;
  4004. /* Capture the page timing before CSS/script/image fetches overwrite the
  4005. * shared fetch_meta block. */
  4006. if (rv == 0 && !local) {
  4007. page_open_ms = fetch_meta.open_ms;
  4008. page_first_ms = fetch_meta.first_ms;
  4009. page_total_ms = fetch_meta.total_ms;
  4010. }
  4011. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  4012. https_fallback_error(fetch_last_error)) {
  4013. char http_url[BR_URL_MAX];
  4014. unsigned int n = 0;
  4015. s_append(http_url, &n, "http://", sizeof(http_url));
  4016. s_append(http_url, &n, url + 8, sizeof(http_url));
  4017. /* Replace the https entry instead of adding a second one. */
  4018. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  4019. s_eq(history[hist_pos], url))
  4020. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  4021. load_page(http_url, 0, 0);
  4022. return;
  4023. }
  4024. if (rv != 0) {
  4025. detail = err;
  4026. show_error("Cannot load this page", detail);
  4027. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4028. url_in.len = s_len(url_in.text);
  4029. url_in.cursor = url_in.len;
  4030. url_in.scroll = 0;
  4031. return;
  4032. }
  4033. if (!local)
  4034. origin_cache_learn(url, final[0] ? final : url);
  4035. page_is_local = local;
  4036. if (final[0]) {
  4037. s_copy(page_url, final, sizeof(page_url));
  4038. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4039. url_in.len = s_len(url_in.text);
  4040. url_in.cursor = url_in.len;
  4041. url_in.scroll = 0;
  4042. }
  4043. if (contains_ci(ctype, "text/plain")) {
  4044. br_parse_plain(&doc, (const char *)body, len);
  4045. } else if (contains_ci(ctype, "image/") ||
  4046. (!contains_ci(ctype, "text/html") &&
  4047. img_sniff(body, len, &image_info) == 0)) {
  4048. unsigned int node = br_parse_image_doc(&doc, page_url);
  4049. if (node)
  4050. decode_direct_image(body, len, node);
  4051. s_copy(page_title, "Image", sizeof(page_title));
  4052. } else {
  4053. br_set_viewport(ui.w);
  4054. t_mark = u_ticks_ms();
  4055. br_parse(&doc, (const char *)body, len);
  4056. t_parse = u_ticks_ms() - t_mark;
  4057. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  4058. sizeof(page_title));
  4059. t_mark = u_ticks_ms();
  4060. if (load_stylesheets() == FETCH_ABORT)
  4061. return;
  4062. t_css = u_ticks_ms() - t_mark;
  4063. if (pending_action)
  4064. return;
  4065. }
  4066. preload_begin();
  4067. page_loading = 0;
  4068. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4069. url_in.len = s_len(url_in.text);
  4070. url_in.cursor = url_in.len;
  4071. url_in.scroll = 0;
  4072. ngui_set_focus(&ui, 0);
  4073. /* Paint the parsed page before fetching/running scripts. A slow
  4074. * remote <script src> then does not hide the page behind the loading
  4075. * screen; the fetch helper pumps this UI while it waits. */
  4076. set_status("Loading scripts...", 0, 0);
  4077. t_mark = u_ticks_ms();
  4078. redraw_now();
  4079. t_paint = u_ticks_ms() - t_mark;
  4080. /* Start one image download before the scripts. The other workers
  4081. * fetch the external script bodies in parallel, and the remaining
  4082. * images start as soon as the script phase ends. */
  4083. preload_max_jobs = 1;
  4084. preload_fill_jobs();
  4085. preload_wait = 0;
  4086. t_mark = u_ticks_ms();
  4087. run_page_scripts();
  4088. t_js = u_ticks_ms() - t_mark;
  4089. preload_max_jobs = FETCH_WORKERS;
  4090. if (pending_action)
  4091. return;
  4092. post_status_text[0] = '\0';
  4093. post_status_error = 0;
  4094. post_status_ttl = 0;
  4095. if (js_last_status[0]) {
  4096. s_copy(post_status_text, js_last_status,
  4097. sizeof(post_status_text));
  4098. post_status_error = js_last_error;
  4099. post_status_ttl = 8000;
  4100. } else if (truncated) {
  4101. s_copy(post_status_text, "Page truncated at the buffer limit",
  4102. sizeof(post_status_text));
  4103. post_status_ttl = 6000;
  4104. } else if (doc.truncated) {
  4105. s_copy(post_status_text, "Page truncated by the parser",
  4106. sizeof(post_status_text));
  4107. post_status_ttl = 6000;
  4108. } else if (page_total_ms) {
  4109. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  4110. * paint 220, js 1750" -- the phases of this load. */
  4111. unsigned int n = 0;
  4112. static const char *const names[] = {
  4113. ", parse ", ", css ", ", paint ", ", js "
  4114. };
  4115. unsigned int vals[4];
  4116. int k;
  4117. vals[0] = t_parse;
  4118. vals[1] = t_css;
  4119. vals[2] = t_paint;
  4120. vals[3] = t_js;
  4121. (void)page_first_ms;
  4122. if (starts_with(page_url, "https://"))
  4123. s_append(post_status_text, &n,
  4124. "HTTPS (not verified), ",
  4125. sizeof(post_status_text));
  4126. s_append(post_status_text, &n, "Loaded in ",
  4127. sizeof(post_status_text));
  4128. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  4129. sizeof(post_status_text));
  4130. s_append(post_status_text, &n, " ms: page ",
  4131. sizeof(post_status_text));
  4132. s_append_dec(post_status_text, &n, t_fetch,
  4133. sizeof(post_status_text));
  4134. s_append(post_status_text, &n, " (headers ",
  4135. sizeof(post_status_text));
  4136. s_append_dec(post_status_text, &n, page_open_ms,
  4137. sizeof(post_status_text));
  4138. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  4139. for (k = 0; k < 4; k++) {
  4140. s_append(post_status_text, &n, names[k],
  4141. sizeof(post_status_text));
  4142. s_append_dec(post_status_text, &n, vals[k],
  4143. sizeof(post_status_text));
  4144. }
  4145. post_status_ttl = 12000;
  4146. } else if (starts_with(page_url, "https://")) {
  4147. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  4148. sizeof(post_status_text));
  4149. post_status_ttl = 6000;
  4150. }
  4151. set_status(post_status_text, post_status_error, post_status_ttl);
  4152. ngui_invalidate(&ui);
  4153. }
  4154. static void load_home(int push)
  4155. {
  4156. pending_post_len = 0;
  4157. pending_post_is = 0;
  4158. cancel_fetch = 0;
  4159. preload_active = 0;
  4160. preload_pending = 0;
  4161. js_browser_stop();
  4162. js_last_status[0] = '\0';
  4163. js_last_error = 0;
  4164. heap_clear();
  4165. image_reset();
  4166. form_reset_state();
  4167. layout_valid = 0;
  4168. page_scroll.offset = 0;
  4169. page_scroll.dragging = 0;
  4170. page_loading = 1;
  4171. page_is_local = 0;
  4172. s_copy(page_url, "about:home", sizeof(page_url));
  4173. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4174. url_in.len = s_len(url_in.text);
  4175. url_in.cursor = url_in.len;
  4176. url_in.scroll = 0;
  4177. ngui_set_focus(&ui, 0);
  4178. if (push)
  4179. history_push(page_url);
  4180. ngui_invalidate(&ui);
  4181. /* See load_page(): reattach the fonts before the first redraw. */
  4182. if (heap_start() != 0) {
  4183. show_error("Out of memory", "Cannot allocate the browser heap");
  4184. return;
  4185. }
  4186. br_parse_plain(&doc, "", 0);
  4187. ngui_font_attach(&ui);
  4188. redraw_now();
  4189. browser_rules_alloc();
  4190. {
  4191. static const char home[] =
  4192. "<html><head><title>NebOS Browser</title><style>"
  4193. "body { margin: 10px; color: #e4e6f0; }"
  4194. "h1 { color: #7fb0ff; }"
  4195. ".box { background-color: #262b3a; margin: 12px; "
  4196. "padding: 10px; }"
  4197. "a { color: #7fb0ff; }"
  4198. "pre { background-color: #32384a; }"
  4199. "</style></head><body>"
  4200. "<h1>NebOS Browser</h1>"
  4201. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  4202. "shared HTTP client and the image library.</p>"
  4203. "<div class=\"box\"><b>Try:</b>"
  4204. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  4205. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  4206. "<li><a href=\"/floppy1/JS.HTM\">/"
  4207. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  4208. "<li><a href=\"http://10.0.2.2:8000/\">"
  4209. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  4210. "<li><a href=\"https://example.com/\">"
  4211. "https://example.com/</a> (TLS, not verified)</li>"
  4212. "</ul></div>"
  4213. "<p>Type a URL in the bar above. Esc closes the "
  4214. "window, Ctrl+L focuses the address bar.</p>"
  4215. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  4216. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  4217. "</body></html>";
  4218. br_set_viewport(ui.w);
  4219. br_parse(&doc, home, sizeof(home) - 1);
  4220. br_parse_inline_css(&doc);
  4221. br_reset_styles(&doc);
  4222. s_copy(page_title, doc.title, sizeof(page_title));
  4223. }
  4224. post_status_text[0] = '\0';
  4225. post_status_error = 0;
  4226. post_status_ttl = 0;
  4227. page_loading = 0;
  4228. set_status("", 0, 0);
  4229. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4230. url_in.len = s_len(url_in.text);
  4231. url_in.cursor = url_in.len;
  4232. url_in.scroll = 0;
  4233. ngui_set_focus(&ui, 0);
  4234. ngui_invalidate(&ui);
  4235. }
  4236. /* Extensions the browser opens from the local filesystem. A dotted input
  4237. * with one of these still resolves relative to the cwd. */
  4238. static int local_file_ext(const char *s)
  4239. {
  4240. static const char *const exts[] = {
  4241. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  4242. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  4243. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  4244. "cfg", "conf", 0
  4245. };
  4246. unsigned int i = 0, start = 0, len = 0, e;
  4247. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  4248. s[i] != '#') {
  4249. if (s[i] == '.') {
  4250. start = i + 1;
  4251. len = 0;
  4252. } else if (start) {
  4253. len++;
  4254. }
  4255. i++;
  4256. }
  4257. if (!len)
  4258. return 0;
  4259. for (e = 0; exts[e]; e++) {
  4260. const char *x = exts[e];
  4261. unsigned int xn = s_len(x), k;
  4262. if (xn != len)
  4263. continue;
  4264. for (k = 0; k < len; k++) {
  4265. char a = s[start + k];
  4266. if (a >= 'A' && a <= 'Z')
  4267. a = (char)(a - 'A' + 'a');
  4268. if (a != x[k])
  4269. break;
  4270. }
  4271. if (k == len)
  4272. return 1;
  4273. }
  4274. return 0;
  4275. }
  4276. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  4277. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  4278. * Enter to the first network request. */
  4279. static int looks_like_host(const char *s)
  4280. {
  4281. unsigned int i = 0;
  4282. int dot = 0;
  4283. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  4284. s[i] != ':') {
  4285. char c = s[i];
  4286. if (c == '.') {
  4287. dot = 1;
  4288. } else if (!((c >= 'a' && c <= 'z') ||
  4289. (c >= 'A' && c <= 'Z') ||
  4290. (c >= '0' && c <= '9') ||
  4291. c == '-' || c == '_')) {
  4292. return 0;
  4293. }
  4294. i++;
  4295. }
  4296. return dot && i > 0 && !local_file_ext(s);
  4297. }
  4298. static void load_remote(const char *url, int push)
  4299. {
  4300. char canon[BR_URL_MAX];
  4301. s_copy(canon, url, sizeof(canon));
  4302. origin_cache_apply(canon, sizeof(canon));
  4303. load_page(canon, 0, push);
  4304. }
  4305. static void navigate(const char *input, int push)
  4306. {
  4307. char target[BR_URL_MAX];
  4308. char *t;
  4309. if (!input)
  4310. return;
  4311. s_copy(target, input, sizeof(target));
  4312. t = trim(target);
  4313. if (!t[0])
  4314. return;
  4315. if (s_eq(t, "about:home")) {
  4316. load_home(push);
  4317. return;
  4318. }
  4319. if (starts_with(t, "file://")) {
  4320. make_abs_local(t + 7, target, sizeof(target));
  4321. load_page(target, 1, push);
  4322. return;
  4323. }
  4324. if (is_http(t)) {
  4325. load_remote(t, push);
  4326. return;
  4327. }
  4328. if (t[0] == '/') {
  4329. make_abs_local(t, target, sizeof(target));
  4330. load_page(target, 1, push);
  4331. return;
  4332. }
  4333. if (!looks_like_host(t)) {
  4334. struct sys_stat st;
  4335. if (u_stat(t, &st) == 0 && !st.is_dir) {
  4336. make_abs_local(t, target, sizeof(target));
  4337. load_page(target, 1, push);
  4338. return;
  4339. }
  4340. }
  4341. {
  4342. /* A typed bare host tries https first: nearly every site
  4343. * redirects http -> https anyway, and that hop costs a whole
  4344. * extra connection. load_page() falls back to http when the
  4345. * https connection itself fails. */
  4346. char with_scheme[BR_URL_MAX];
  4347. unsigned int n = 0;
  4348. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  4349. s_append(with_scheme, &n, t, sizeof(with_scheme));
  4350. nav_https_upgraded = 1;
  4351. load_remote(with_scheme, push);
  4352. }
  4353. }
  4354. /* ---- layout ---- */
  4355. static struct ufont_face *style_face(const struct br_style *st)
  4356. {
  4357. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  4358. return font_faces[st->font_face - 1];
  4359. return 0;
  4360. }
  4361. static struct ufont_face *run_face(const struct lay_run *r)
  4362. {
  4363. if (r->font_face && r->font_face <= BR_MAX_FACES)
  4364. return font_faces[r->font_face - 1];
  4365. return 0;
  4366. }
  4367. static unsigned int face_text_width(struct ngui *gui,
  4368. const struct br_style *st,
  4369. const char *s, unsigned int n)
  4370. {
  4371. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  4372. st->bold, st->italic, st->mono);
  4373. }
  4374. static int face_line_height(struct ngui *gui, const struct br_style *st)
  4375. {
  4376. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  4377. st->mono);
  4378. }
  4379. static unsigned int run_text_width(struct ngui *gui,
  4380. const struct lay_run *r,
  4381. const char *s, unsigned int n)
  4382. {
  4383. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  4384. r->bold, r->italic, r->mono);
  4385. }
  4386. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  4387. {
  4388. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  4389. r->mono);
  4390. }
  4391. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  4392. {
  4393. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  4394. }
  4395. static struct br_style base_style(void)
  4396. {
  4397. struct br_style s = { 0 };
  4398. s.color = ui.theme.text;
  4399. s.bg = ui.theme.bg;
  4400. s.has_bg = 0;
  4401. for (int i = 0; i < 4; i++) {
  4402. s.border_c[i] = 0;
  4403. s.border_w[i] = 0;
  4404. s.border_s[i] = BR_BORDER_SOLID;
  4405. }
  4406. s.font_px = 16;
  4407. s.bold = 0;
  4408. s.italic = 0;
  4409. s.mono = 0;
  4410. s.underline = 0;
  4411. s.strike = 0;
  4412. s.overline = 0;
  4413. s.align = BR_ALIGN_LEFT;
  4414. s.display = BR_DISPLAY_BLOCK;
  4415. s.no_bullet = 0;
  4416. s.list_style = BR_LIST_AUTO;
  4417. s.uppercase = 0;
  4418. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  4419. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  4420. s.width = s.max_width = s.min_width = 0;
  4421. s.height = s.min_height = s.max_height = 0;
  4422. s.box_sizing = 0;
  4423. s.ml_auto = s.mr_auto = 0;
  4424. s.line_h_pct = 0;
  4425. s.line_h_px = 0;
  4426. s.mt = s.mb = s.ml = s.mr = 0;
  4427. s.pt = s.pb = s.pl = s.pr = 0;
  4428. return s;
  4429. }
  4430. /* Resolve a margin/padding raw value. Percentages use the containing
  4431. * block width for all four sides, as CSS specifies. */
  4432. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  4433. {
  4434. if (unit == 1)
  4435. return base * v / 10000;
  4436. if (unit == 2)
  4437. return st->font_px * v / 100;
  4438. if (unit == 3)
  4439. return (int)br_root_font_px() * v / 100;
  4440. if (unit == 4)
  4441. return 0;
  4442. return v;
  4443. }
  4444. static int mp_px(const struct br_style *st, int side, int base)
  4445. {
  4446. int raw;
  4447. switch (side) {
  4448. case 0: raw = st->mt; break;
  4449. case 1: raw = st->mr; break;
  4450. case 2: raw = st->mb; break;
  4451. case 3: raw = st->ml; break;
  4452. case 4: raw = st->pt; break;
  4453. case 5: raw = st->pr; break;
  4454. case 6: raw = st->pb; break;
  4455. default: raw = st->pl; break;
  4456. }
  4457. if (st->mp_unit[side] == 5)
  4458. return base * raw / 100 + st->mp_calc_px[side];
  4459. return css_mp_px(st, raw, st->mp_unit[side], base);
  4460. }
  4461. static int style_width_px(const struct br_style *st, int base)
  4462. {
  4463. if (st->width_kind == 1)
  4464. return st->width;
  4465. if (st->width_kind == 2)
  4466. return base * (int)st->width / 100;
  4467. if (st->width_kind == 3)
  4468. return base * st->width_calc_pct / 100 + st->width_calc_px;
  4469. return 0;
  4470. }
  4471. static int style_height_px(const struct br_style *st, int base)
  4472. {
  4473. if (st->height_kind == 1)
  4474. return st->height;
  4475. if (st->height_kind == 2)
  4476. return base * (int)st->height / 100;
  4477. if (st->height_kind == 3)
  4478. return base * st->height_calc_pct / 100 + st->height_calc_px;
  4479. return 0;
  4480. }
  4481. static int css_size(unsigned char kind, int val, int base)
  4482. {
  4483. if (kind == 1)
  4484. return val;
  4485. if (kind == 2)
  4486. return base * val / 100;
  4487. return -1;
  4488. }
  4489. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  4490. int thick, int horizontal, unsigned short color,
  4491. unsigned char style)
  4492. {
  4493. int pos;
  4494. if (len <= 0 || thick <= 0)
  4495. return;
  4496. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  4497. if (horizontal)
  4498. ngui_fill_rect(ui, (struct ngui_rect){
  4499. x, y, len, thick}, color);
  4500. else
  4501. ngui_fill_rect(ui, (struct ngui_rect){
  4502. x, y, thick, len}, color);
  4503. return;
  4504. }
  4505. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  4506. int seg = len - pos;
  4507. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  4508. seg = style == BR_BORDER_DASHED ? 4 : 2;
  4509. if (horizontal)
  4510. ngui_fill_rect(ui, (struct ngui_rect){
  4511. x + pos, y, seg, thick}, color);
  4512. else
  4513. ngui_fill_rect(ui, (struct ngui_rect){
  4514. x, y + pos, thick, seg}, color);
  4515. }
  4516. }
  4517. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  4518. const struct br_style *st)
  4519. {
  4520. int top = st->border_w[0], right = st->border_w[1];
  4521. int bottom = st->border_w[2], left = st->border_w[3];
  4522. if (r.w <= 0 || r.h <= 0)
  4523. return;
  4524. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  4525. int i;
  4526. for (i = 0; i < 4; i++)
  4527. if (st->border_w[i] && !st->border_t[i]) {
  4528. ngui_fill_rect(ui, r, st->border_c[i]);
  4529. break;
  4530. }
  4531. return;
  4532. }
  4533. if (top && !st->border_t[0])
  4534. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  4535. st->border_c[0], st->border_s[0]);
  4536. if (bottom && !st->border_t[2])
  4537. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  4538. st->border_c[2], st->border_s[2]);
  4539. if (left && !st->border_t[3])
  4540. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  4541. left, 0, st->border_c[3], st->border_s[3]);
  4542. if (right && !st->border_t[1])
  4543. draw_border_side(ui, r.x + r.w - right, r.y + top,
  4544. r.h - top - bottom, right, 0,
  4545. st->border_c[1], st->border_s[1]);
  4546. }
  4547. static void transform_origin(const struct br_style *st, int w, int h,
  4548. int *ox, int *oy)
  4549. {
  4550. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  4551. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  4552. }
  4553. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  4554. unsigned int a)
  4555. {
  4556. unsigned int dr, dg, db, sr, sg, sb;
  4557. if (a >= 255)
  4558. return s;
  4559. dr = (d >> 11) & 31;
  4560. dg = (d >> 5) & 63;
  4561. db = d & 31;
  4562. sr = (s >> 11) & 31;
  4563. sg = (s >> 5) & 63;
  4564. sb = s & 31;
  4565. dr = (dr * (255 - a) + sr * a) / 255;
  4566. dg = (dg * (255 - a) + sg * a) / 255;
  4567. db = (db * (255 - a) + sb * a) / 255;
  4568. return (unsigned short)((dr << 11) | (dg << 5) | db);
  4569. }
  4570. /* Paint a solid box through scale()/rotate() around transform-origin. This
  4571. * transforms the element's own background box; text and descendants keep
  4572. * their layout (documented approximation). */
  4573. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  4574. unsigned short color,
  4575. const struct br_style *st)
  4576. {
  4577. double sx = st->scale_x / 100.0;
  4578. double sy = st->scale_y / 100.0;
  4579. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  4580. double c = cos(th), sn = sin(th);
  4581. int ox, oy, minx, miny, maxx, maxy, x, y;
  4582. double ax, ay;
  4583. double px[4], py[4];
  4584. int cx1, cy1, cx2, cy2, i;
  4585. if (sx == 0)
  4586. sx = 0.01;
  4587. if (sy == 0)
  4588. sy = 0.01;
  4589. transform_origin(st, box.w, box.h, &ox, &oy);
  4590. ax = box.x + ox;
  4591. ay = box.y + oy;
  4592. px[0] = -ox; py[0] = -oy;
  4593. px[1] = box.w - ox; py[1] = -oy;
  4594. px[2] = box.w - ox; py[2] = box.h - oy;
  4595. px[3] = -ox; py[3] = box.h - oy;
  4596. minx = miny = 1000000;
  4597. maxx = maxy = -1000000;
  4598. for (i = 0; i < 4; i++) {
  4599. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  4600. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  4601. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  4602. if (dx < minx) minx = dx;
  4603. if (dx > maxx) maxx = dx;
  4604. if (dy < miny) miny = dy;
  4605. if (dy > maxy) maxy = dy;
  4606. }
  4607. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  4608. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  4609. cx2 = page_rect.x + page_rect.w - 12;
  4610. cy2 = page_rect.y + page_rect.h;
  4611. if (cx2 > gui->w) cx2 = gui->w;
  4612. if (cy2 > gui->h) cy2 = gui->h;
  4613. if (minx < cx1) minx = cx1;
  4614. if (miny < cy1) miny = cy1;
  4615. if (maxx > cx2 - 1) maxx = cx2 - 1;
  4616. if (maxy > cy2 - 1) maxy = cy2 - 1;
  4617. for (y = miny; y <= maxy; y++) {
  4618. for (x = minx; x <= maxx; x++) {
  4619. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  4620. double rx = dx * c + dy * sn;
  4621. double ry = -dx * sn + dy * c;
  4622. double bx = rx / sx + ox;
  4623. double by = ry / sy + oy;
  4624. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  4625. gui->px[y * gui->w + x] = color;
  4626. }
  4627. }
  4628. }
  4629. static void draw_image_transformed(struct ngui *gui,
  4630. const struct img_image *im,
  4631. int x, int y, int w, int h,
  4632. int sx100, int sy100, int rot100,
  4633. int origin_x, int origin_y,
  4634. int origin_x_kind, int origin_y_kind)
  4635. {
  4636. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  4637. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  4638. double c = cos(th), sn = sin(th);
  4639. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  4640. double ax, ay;
  4641. double bx[4], by[4];
  4642. int cx1, cy1, cx2, cy2;
  4643. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  4644. return;
  4645. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  4646. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  4647. ax = x + ox;
  4648. ay = y + oy;
  4649. bx[0] = -ox; by[0] = -oy;
  4650. bx[1] = w - ox; by[1] = -oy;
  4651. bx[2] = w - ox; by[2] = h - oy;
  4652. bx[3] = -ox; by[3] = h - oy;
  4653. minx = miny = 1000000;
  4654. maxx = maxy = -1000000;
  4655. for (i = 0; i < 4; i++) {
  4656. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  4657. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  4658. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  4659. if (dx < minx) minx = dx;
  4660. if (dx > maxx) maxx = dx;
  4661. if (dy < miny) miny = dy;
  4662. if (dy > maxy) maxy = dy;
  4663. }
  4664. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  4665. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  4666. cx2 = page_rect.x + page_rect.w - 12;
  4667. cy2 = page_rect.y + page_rect.h;
  4668. if (cx2 > gui->w) cx2 = gui->w;
  4669. if (cy2 > gui->h) cy2 = gui->h;
  4670. if (minx < cx1) minx = cx1;
  4671. if (miny < cy1) miny = cy1;
  4672. if (maxx > cx2 - 1) maxx = cx2 - 1;
  4673. if (maxy > cy2 - 1) maxy = cy2 - 1;
  4674. for (py = miny; py <= maxy; py++) {
  4675. for (px = minx; px <= maxx; px++) {
  4676. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  4677. double rx = dx * c + dy * sn;
  4678. double ry = -dx * sn + dy * c;
  4679. double fx = rx / sx + ox;
  4680. double fy = ry / sy + oy;
  4681. int ix, iy;
  4682. unsigned int si, a;
  4683. unsigned short src;
  4684. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  4685. continue;
  4686. ix = (int)(fx * (double)im->w / w);
  4687. iy = (int)(fy * (double)im->h / h);
  4688. if (ix < 0 || ix >= (int)im->w ||
  4689. iy < 0 || iy >= (int)im->h)
  4690. continue;
  4691. si = (unsigned int)iy * im->w + (unsigned int)ix;
  4692. src = im->px[si];
  4693. a = im->alpha ? im->alpha[si] : 255;
  4694. gui->px[py * gui->w + px] =
  4695. a >= 255 ? src :
  4696. blend_rgb565(gui->px[py * gui->w + px],
  4697. src, a);
  4698. }
  4699. }
  4700. }
  4701. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  4702. unsigned int node, const struct br_style *st);
  4703. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  4704. * first and every pixel outside a corner's arc is restored afterwards. */
  4705. #define BG_ROUND_MAX 64
  4706. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  4707. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  4708. unsigned int node, const struct br_style *st,
  4709. int rtl, int rtr, int rbr, int rbl)
  4710. {
  4711. struct ngui *ui = l->ui;
  4712. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  4713. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  4714. if (ui->nclip > 0)
  4715. clip = ui->clip[ui->nclip - 1];
  4716. for (c = 0; c < 4; c++) {
  4717. if (r[c] > BG_ROUND_MAX)
  4718. r[c] = BG_ROUND_MAX;
  4719. if (r[c] > box.w / 2)
  4720. r[c] = box.w / 2;
  4721. if (r[c] > box.h / 2)
  4722. r[c] = box.h / 2;
  4723. }
  4724. for (c = 0; c < 4; c++) {
  4725. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  4726. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  4727. for (dy = 0; dy < r[c]; dy++)
  4728. for (dx = 0; dx < r[c]; dx++) {
  4729. int px = ox + dx, py = oy + dy;
  4730. if (px >= clip.x && py >= clip.y &&
  4731. px < clip.x + clip.w && py < clip.y + clip.h)
  4732. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  4733. ui->px[py * ui->w + px];
  4734. }
  4735. }
  4736. draw_bg_image(l, box, node, st);
  4737. for (c = 0; c < 4; c++) {
  4738. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  4739. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  4740. /* arc centre, in corner-square coordinates */
  4741. int cx = (c == 1 || c == 2) ? 0 : r[c];
  4742. int cy = (c >= 2) ? 0 : r[c];
  4743. for (dy = 0; dy < r[c]; dy++)
  4744. for (dx = 0; dx < r[c]; dx++) {
  4745. int px = ox + dx, py = oy + dy;
  4746. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  4747. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  4748. continue;
  4749. if (px >= clip.x && py >= clip.y &&
  4750. px < clip.x + clip.w && py < clip.y + clip.h)
  4751. ui->px[py * ui->w + px] =
  4752. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  4753. }
  4754. }
  4755. }
  4756. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  4757. unsigned int node, const struct br_style *st)
  4758. {
  4759. struct br_image *bi;
  4760. struct img_blit b;
  4761. int tw, th, x, y, rep_x, rep_y, posx, posy;
  4762. unsigned int scale = 65536;
  4763. int legacy, tiles = 0, rows = 0;
  4764. int cx1, cy1, cx2, cy2;
  4765. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  4766. return;
  4767. if (doc.nodes[node].bg_img_index < 0 ||
  4768. doc.nodes[node].bg_img_index >= image_count)
  4769. return;
  4770. bi = &images[doc.nodes[node].bg_img_index];
  4771. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  4772. return;
  4773. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  4774. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  4775. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  4776. if (legacy) {
  4777. scale = ((unsigned int)box.w << 16) / bi->img.w;
  4778. tw = box.w;
  4779. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  4780. x = box.x;
  4781. y = box.y;
  4782. rep_x = rep_y = 0;
  4783. } else {
  4784. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  4785. unsigned int sx = ((unsigned int)box.w << 16) /
  4786. bi->img.w;
  4787. unsigned int sy = ((unsigned int)box.h << 16) /
  4788. bi->img.h;
  4789. scale = st->bg_size_kind == 3 ?
  4790. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  4791. } else if (st->bg_size_kind == 1 ||
  4792. st->bg_size_kind == 2) {
  4793. int w = st->bg_size_w;
  4794. int h = st->bg_size_h;
  4795. if (st->bg_size_kind == 2) {
  4796. if (w)
  4797. w = box.w * w / 100;
  4798. if (h)
  4799. h = box.h * h / 100;
  4800. }
  4801. if (w)
  4802. scale = ((unsigned int)w << 16) / bi->img.w;
  4803. else if (h)
  4804. scale = ((unsigned int)h << 16) / bi->img.h;
  4805. }
  4806. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  4807. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  4808. if (tw < 1)
  4809. tw = 1;
  4810. if (th < 1)
  4811. th = 1;
  4812. posx = st->bg_pos_x_kind == 1 ?
  4813. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  4814. posy = st->bg_pos_y_kind == 1 ?
  4815. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  4816. x = box.x + posx;
  4817. y = box.y + posy;
  4818. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  4819. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  4820. if (rep_x) {
  4821. int m = (x - box.x) % tw;
  4822. if (m > 0)
  4823. m -= tw;
  4824. x = box.x + m;
  4825. }
  4826. if (rep_y) {
  4827. int m = (y - box.y) % th;
  4828. if (m > 0)
  4829. m -= th;
  4830. y = box.y + m;
  4831. }
  4832. }
  4833. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  4834. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  4835. cx2 = box.x + box.w;
  4836. cy2 = box.y + box.h;
  4837. if (cx2 > page_rect.x + page_rect.w - 12)
  4838. cx2 = page_rect.x + page_rect.w - 12;
  4839. if (cy2 > page_rect.y + page_rect.h)
  4840. cy2 = page_rect.y + page_rect.h;
  4841. if (cx1 >= cx2 || cy1 >= cy2)
  4842. return;
  4843. b.dst = l->ui->px;
  4844. b.dst_w = l->ui->w;
  4845. b.dst_h = l->ui->h;
  4846. b.clip_x = cx1;
  4847. b.clip_y = cy1;
  4848. b.clip_w = cx2 - cx1;
  4849. b.clip_h = cy2 - cy1;
  4850. b.scale = scale;
  4851. b.bg = ui.theme.bg;
  4852. b.bg2 = ui.theme.bg;
  4853. b.flags = IMG_BLIT_OVER_DST;
  4854. {
  4855. int row_x = x;
  4856. for (;;) {
  4857. for (;;) {
  4858. b.x = x;
  4859. b.y = y;
  4860. img_draw(&bi->img, &b);
  4861. if (!rep_x || ++tiles > 512)
  4862. break;
  4863. x += tw;
  4864. if (x >= box.x + box.w)
  4865. break;
  4866. }
  4867. if (!rep_y || ++rows > 64)
  4868. break;
  4869. y += th;
  4870. if (y >= box.y + box.h)
  4871. break;
  4872. x = row_x;
  4873. }
  4874. }
  4875. }
  4876. static int run_width(const struct lay_run *r)
  4877. {
  4878. if (r->img >= 0)
  4879. return r->iw;
  4880. if (r->img == -2)
  4881. return r->iw;
  4882. return (int)r->w;
  4883. }
  4884. static void start_line(struct lay *l, const struct br_style *st)
  4885. {
  4886. (void)st;
  4887. if (l->nruns == 0) {
  4888. l->line_y = l->y;
  4889. l->line_h = 0;
  4890. }
  4891. l->line_left = l->left;
  4892. l->line_right = l->right;
  4893. if (l->float_active && l->line_y < l->float_bottom) {
  4894. if (l->float_left > l->line_left)
  4895. l->line_left = l->float_left;
  4896. if (l->float_right < l->line_right)
  4897. l->line_right = l->float_right;
  4898. }
  4899. if (l->line_right < l->line_left + 8)
  4900. l->line_right = l->line_left + 8;
  4901. l->line_x = l->line_left;
  4902. l->run_x = l->line_left;
  4903. }
  4904. static void flush_line(struct lay *l)
  4905. {
  4906. int total, x, i, vis;
  4907. if (!l->nruns && l->line_x == l->line_left) {
  4908. l->line_h = 0;
  4909. return;
  4910. }
  4911. total = l->line_x - l->line_left;
  4912. x = l->line_left;
  4913. vis = 1;
  4914. if (l->draw) {
  4915. int lh = l->line_h ? l->line_h : 16;
  4916. vis = l->line_y + lh >= page_rect.y &&
  4917. l->line_y <= page_rect.y + page_rect.h;
  4918. }
  4919. if (l->align == BR_ALIGN_CENTER)
  4920. x += (l->line_right - l->line_left - total) / 2;
  4921. else if (l->align == BR_ALIGN_RIGHT)
  4922. x = l->line_right - total;
  4923. if (x < l->line_left)
  4924. x = l->line_left;
  4925. for (i = 0; i < l->nruns; i++) {
  4926. struct lay_run *r = &l->runs[i];
  4927. int w = run_width(r);
  4928. int ry = l->line_y + r->dy;
  4929. x += r->gap;
  4930. if (l->draw && vis) {
  4931. if (r->form) {
  4932. unsigned int node = r->form - 1;
  4933. struct form_state *fs = form_get(node, 1);
  4934. int hh = r->ih ? r->ih : 20;
  4935. int focused = form_focus == node;
  4936. int disabled = r->form_disabled;
  4937. unsigned short bg = l->ui->theme.panel_alt;
  4938. unsigned short fg = disabled ? 0x8410 : r->color;
  4939. struct ngui_rect box = {x, ry, w, hh};
  4940. if (r->form_kind == FORM_CHECKBOX ||
  4941. r->form_kind == FORM_RADIO) {
  4942. ngui_fill_rect(l->ui, box, bg);
  4943. ngui_frame(l->ui, box,
  4944. focused ? l->ui->theme.accent :
  4945. l->ui->theme.border);
  4946. if (fs && fs->checked) {
  4947. struct ngui_rect dot = {
  4948. x + 4, ry + 4,
  4949. w > 8 ? w - 8 : 1,
  4950. hh > 8 ? hh - 8 : 1
  4951. };
  4952. if (r->form_kind == FORM_RADIO)
  4953. ngui_fill_round_rect(
  4954. l->ui, dot, 4,
  4955. 4, 4, 4,
  4956. l->ui->theme.accent);
  4957. else
  4958. ngui_fill_rect(l->ui,
  4959. dot,
  4960. l->ui->theme.accent);
  4961. }
  4962. } else {
  4963. int editable =
  4964. r->form_kind == FORM_TEXT ||
  4965. r->form_kind == FORM_PASSWORD ||
  4966. r->form_kind == FORM_TEXTAREA;
  4967. int scroll = 0;
  4968. /* Editable fields draw the live value
  4969. * (r->lit is a short copy). */
  4970. static char shown[FORM_VALUE_MAX + 1];
  4971. const char *txt = r->lit;
  4972. unsigned int tl = s_len(r->lit);
  4973. if (editable && fs && fs->len) {
  4974. unsigned int k;
  4975. if (r->form_kind == FORM_PASSWORD) {
  4976. for (k = 0; k < fs->len; k++)
  4977. shown[k] = '*';
  4978. shown[k] = '\0';
  4979. txt = shown;
  4980. } else {
  4981. txt = fs->value;
  4982. }
  4983. tl = fs->len;
  4984. }
  4985. /* The box is drawn in theme colours, so
  4986. * the text is too: the page's CSS colour
  4987. * (dark on a light page) would vanish on
  4988. * the dark field. */
  4989. if (!disabled)
  4990. fg = editable && fs && !fs->len ?
  4991. l->ui->theme.text_dim :
  4992. l->ui->theme.text;
  4993. ngui_fill_rect(l->ui, box, bg);
  4994. ngui_frame(l->ui, box,
  4995. focused ? l->ui->theme.accent :
  4996. l->ui->theme.border);
  4997. /* A value wider than the field shows its
  4998. * tail (where typing happens). */
  4999. if (editable && w > 12) {
  5000. int tw = (int)run_text_width(l->ui,
  5001. r, txt, tl);
  5002. if (tw > w - 12)
  5003. scroll = tw - (w - 12);
  5004. }
  5005. ngui_push_clip(l->ui, (struct ngui_rect){
  5006. x + 1, ry + 1,
  5007. w > 2 ? w - 2 : 1,
  5008. hh > 2 ? hh - 2 : 1 });
  5009. ngui_text_px_face(l->ui, run_face(r),
  5010. x + 6 - scroll,
  5011. ry + (hh - r->font_px) / 2 - 1,
  5012. txt, tl, fg, r->font_px,
  5013. r->bold, r->italic, r->mono);
  5014. if (focused && fs && editable) {
  5015. int cw = 0;
  5016. if (fs->len && fs->caret)
  5017. cw = (int)run_text_width(
  5018. l->ui, r, txt,
  5019. fs->caret < fs->len ?
  5020. fs->caret : fs->len);
  5021. ngui_fill_rect(l->ui,
  5022. (struct ngui_rect){
  5023. x + 6 + cw - scroll,
  5024. ry + 4, 1,
  5025. hh > 8 ? hh - 8 : 1
  5026. },
  5027. l->ui->theme.accent);
  5028. }
  5029. ngui_pop_clip(l->ui);
  5030. if (r->form_kind == FORM_SELECT) {
  5031. ngui_text_px(l->ui, x + w - 12,
  5032. ry + 2, "v", 1, fg,
  5033. r->font_px, 0, 0, 0);
  5034. }
  5035. }
  5036. } else if (r->img == -2) {
  5037. int hh = r->ih ? r->ih : 20;
  5038. ngui_fill_rect(l->ui,
  5039. (struct ngui_rect){x, ry, w, hh},
  5040. l->ui->theme.panel_alt);
  5041. ngui_frame(l->ui,
  5042. (struct ngui_rect){x, ry, w, hh},
  5043. l->ui->theme.border);
  5044. ngui_text_px_face(l->ui, run_face(r),
  5045. x + 6, ry + 2, r->lit,
  5046. s_len(r->lit), r->color,
  5047. r->font_px, r->bold, r->italic,
  5048. r->mono);
  5049. } else if (r->img >= 0) {
  5050. struct br_image *bi = &images[r->img];
  5051. if (bi->state == 1 && r->transform_scale) {
  5052. draw_image_transformed(l->ui, &bi->img,
  5053. x, ry, r->iw, r->ih,
  5054. r->scale_x, r->scale_y,
  5055. r->rotate_x100, r->origin_x,
  5056. r->origin_y, r->origin_x_kind,
  5057. r->origin_y_kind);
  5058. } else if (bi->state == 1) {
  5059. struct img_blit b;
  5060. b.dst = l->ui->px;
  5061. b.dst_w = l->ui->w;
  5062. b.dst_h = l->ui->h;
  5063. b.clip_x = page_rect.x;
  5064. b.clip_y = page_rect.y;
  5065. b.clip_w = page_rect.w - 12;
  5066. b.clip_h = page_rect.h;
  5067. b.x = x;
  5068. b.y = ry;
  5069. b.scale = ((unsigned int)r->iw << 16) /
  5070. bi->img.w;
  5071. b.bg = ui.theme.bg;
  5072. b.bg2 = ui.theme.bg;
  5073. b.flags = IMG_BLIT_OVER_DST;
  5074. img_draw(&bi->img, &b);
  5075. }
  5076. } else {
  5077. const char *s = r->has_lit ? r->lit :
  5078. doc.text + r->off;
  5079. unsigned int n = r->has_lit ? s_len(r->lit) :
  5080. r->len;
  5081. ngui_text_px_face(l->ui, run_face(r), x, ry,
  5082. s, n, r->color, r->font_px,
  5083. r->bold, r->italic, r->mono);
  5084. if (r->underline)
  5085. ngui_fill_rect(l->ui,
  5086. (struct ngui_rect){x,
  5087. ry + run_ascent(l->ui, r) + 2,
  5088. w, 1}, r->color);
  5089. if (r->strike)
  5090. ngui_fill_rect(l->ui,
  5091. (struct ngui_rect){x,
  5092. ry + run_ascent(l->ui, r) -
  5093. (r->font_px > 3 ?
  5094. r->font_px / 3 : 1),
  5095. w, 1}, r->color);
  5096. if (r->overline)
  5097. ngui_fill_rect(l->ui,
  5098. (struct ngui_rect){x, ry,
  5099. w, 1}, r->color);
  5100. }
  5101. if (r->form || r->href) {
  5102. if (nhits < HIT_MAX) {
  5103. struct hit *h = &hits[nhits];
  5104. unsigned int target = r->form ?
  5105. r->form - 1 : r->href;
  5106. int hh = (r->form || r->img >= 0) ?
  5107. r->ih :
  5108. run_line_height(l->ui, r);
  5109. int merge = nhits > 0 &&
  5110. hits[nhits - 1].node == target &&
  5111. hits[nhits - 1].y == ry &&
  5112. hits[nhits - 1].h == hh &&
  5113. x <= hits[nhits - 1].x +
  5114. hits[nhits - 1].w + 2;
  5115. if (merge) {
  5116. struct hit *p = &hits[nhits - 1];
  5117. int end = x + w;
  5118. if (end > p->x + p->w)
  5119. p->w = end - p->x;
  5120. } else {
  5121. h->x = x;
  5122. h->y = ry;
  5123. h->w = w;
  5124. h->h = hh;
  5125. h->node = (unsigned short)target;
  5126. nhits++;
  5127. }
  5128. }
  5129. }
  5130. }
  5131. x += w;
  5132. }
  5133. l->y += l->line_h + 2;
  5134. if (l->float_active && l->y >= l->float_bottom)
  5135. l->float_active = 0;
  5136. l->nruns = 0;
  5137. l->line_x = l->left;
  5138. l->run_x = l->left;
  5139. l->line_left = l->left;
  5140. l->line_right = l->right;
  5141. l->line_h = 0;
  5142. l->space_pending = 0;
  5143. }
  5144. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  5145. const struct br_style *st, unsigned short href,
  5146. const char *lit)
  5147. {
  5148. unsigned int n = lit ? s_len(lit) : len;
  5149. const char *tp = lit ? lit : doc.text + off;
  5150. int w = (int)face_text_width(l->ui, st, tp, n);
  5151. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  5152. flush_line(l);
  5153. if (l->nruns == 0) {
  5154. l->line_y = l->y;
  5155. l->line_h = 0;
  5156. start_line(l, st);
  5157. }
  5158. {
  5159. struct lay_run *r = &l->runs[l->nruns++];
  5160. int gap = l->line_x - l->run_x;
  5161. if (gap < 0)
  5162. gap = 0;
  5163. r->gap = (unsigned short)gap;
  5164. r->off = off;
  5165. r->len = len;
  5166. r->color = st->color;
  5167. r->href = href;
  5168. r->dy = 0;
  5169. r->has_lit = 0;
  5170. r->form = 0;
  5171. r->form_kind = 0;
  5172. r->form_disabled = 0;
  5173. r->lit[0] = '\0';
  5174. if (lit && lit[0]) {
  5175. unsigned int i;
  5176. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  5177. r->lit[i] = lit[i];
  5178. r->lit[i] = '\0';
  5179. r->has_lit = 1;
  5180. }
  5181. r->img = -1;
  5182. r->iw = r->ih = 0;
  5183. r->font_px = st->font_px;
  5184. r->bold = st->bold;
  5185. r->italic = st->italic;
  5186. r->mono = st->mono;
  5187. r->font_face = st->font_face;
  5188. /* A control with its own background is a button, not body copy;
  5189. * an inherited link underline would strike through the fill. */
  5190. r->underline = st->underline && !st->has_bg;
  5191. r->strike = st->strike && !st->has_bg;
  5192. r->overline = st->overline && !st->has_bg;
  5193. r->w = (unsigned short)w;
  5194. if (r->has_lit)
  5195. r->w = (unsigned short)run_text_width(
  5196. l->ui, r, r->lit, s_len(r->lit));
  5197. w = r->w;
  5198. }
  5199. l->line_x += w;
  5200. l->run_x = l->line_x;
  5201. {
  5202. int lh = face_line_height(l->ui, st);
  5203. if (st->line_h_px)
  5204. lh = st->line_h_px;
  5205. else if (st->line_h_pct)
  5206. lh = st->font_px * st->line_h_pct / 100;
  5207. if (lh < face_line_height(l->ui, st))
  5208. lh = face_line_height(l->ui, st);
  5209. if (l->line_h < lh)
  5210. l->line_h = lh;
  5211. }
  5212. }
  5213. static void add_image_run(struct lay *l, unsigned int node,
  5214. const struct br_style *st, unsigned short href)
  5215. {
  5216. struct br_image *bi = 0;
  5217. int idx = doc.nodes[node].img_index;
  5218. int dw, dh, maxw;
  5219. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  5220. bi = &images[idx];
  5221. if (l->nruns == 0)
  5222. start_line(l, st);
  5223. if (l->space_pending &&
  5224. (l->nruns > 0 || l->line_x > l->line_left)) {
  5225. int sp = (int)face_text_width(l->ui, st, " ", 1);
  5226. if (l->line_x + sp <= l->line_right)
  5227. l->line_x += sp;
  5228. }
  5229. l->space_pending = 0;
  5230. if (!bi) {
  5231. const char *alt = br_alt(&doc, node);
  5232. struct br_style gs = *st;
  5233. char tmp[96];
  5234. unsigned int n = 0;
  5235. int w;
  5236. gs.color = BR_GRAY;
  5237. gs.underline = 0;
  5238. s_append(tmp, &n, "[", sizeof(tmp));
  5239. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  5240. s_append(tmp, &n, "]", sizeof(tmp));
  5241. w = (int)face_text_width(l->ui, &gs, tmp, n);
  5242. if (l->line_x + w > l->line_right &&
  5243. (l->nruns > 0 || l->line_x > l->line_left))
  5244. flush_line(l);
  5245. add_run(l, 0, 0, &gs, href, tmp);
  5246. if (!l->draw) {
  5247. int t = l->line_y < 0 ? 0 : l->line_y;
  5248. int hh = face_line_height(l->ui, &gs);
  5249. if (t > 65535)
  5250. t = 65535;
  5251. if (hh > 65535)
  5252. hh = 65535;
  5253. img_top[node] = (unsigned short)t;
  5254. img_h[node] = (unsigned short)hh;
  5255. }
  5256. return;
  5257. }
  5258. maxw = l->line_right - l->line_left;
  5259. if (maxw < 8)
  5260. maxw = 8;
  5261. {
  5262. int iw = bi->native_w, ih = bi->native_h;
  5263. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  5264. if (iw <= 0 || ih <= 0) {
  5265. iw = (int)bi->img.w;
  5266. ih = (int)bi->img.h;
  5267. }
  5268. dw = iw;
  5269. dh = ih;
  5270. if (doc.nodes[node].width_attr) {
  5271. int want = doc.nodes[node].width_attr;
  5272. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  5273. have_w = 1;
  5274. }
  5275. if (doc.nodes[node].height_attr) {
  5276. int want = doc.nodes[node].height_attr;
  5277. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  5278. have_h = 1;
  5279. }
  5280. if (have_w && !have_h)
  5281. dh = ih ? ih * dw / iw : 0;
  5282. if (have_h && !have_w)
  5283. dw = iw ? iw * dh / ih : 0;
  5284. if (st->width_kind) {
  5285. css_w = 1;
  5286. if (st->width_kind == 3)
  5287. dw = maxw * st->width_calc_pct / 100 +
  5288. st->width_calc_px;
  5289. else
  5290. dw = st->width_kind == 2 ?
  5291. maxw * (int)st->width / 100 :
  5292. (int)st->width;
  5293. }
  5294. if (st->height_kind) {
  5295. css_h = 1;
  5296. if (st->height_kind == 3)
  5297. dh = maxw * st->height_calc_pct / 100 +
  5298. st->height_calc_px;
  5299. else
  5300. dh = st->height_kind == 2 ?
  5301. maxw * (int)st->height / 100 :
  5302. (int)st->height;
  5303. }
  5304. if (css_w && !css_h)
  5305. dh = ih ? ih * dw / iw : 0;
  5306. if (css_h && !css_w)
  5307. dw = iw ? iw * dh / ih : 0;
  5308. if (st->max_width_kind) {
  5309. int mw = st->max_width_kind == 3 ?
  5310. maxw * st->max_width_calc_pct / 100 +
  5311. st->max_width_calc_px :
  5312. st->max_width_kind == 2 ?
  5313. maxw * (int)st->max_width / 100 :
  5314. (int)st->max_width;
  5315. if (mw > 0 && dw > mw) {
  5316. dh = iw ? ih * mw / iw : 0;
  5317. dw = mw;
  5318. }
  5319. }
  5320. }
  5321. if (dw < 8)
  5322. dw = 8;
  5323. if (dh < 8)
  5324. dh = 8;
  5325. if (dw > maxw) {
  5326. dh = dw ? dh * maxw / dw : dh;
  5327. dw = maxw;
  5328. }
  5329. if (!l->draw) {
  5330. int t = l->line_y < 0 ? 0 : l->line_y;
  5331. if (t > 65535)
  5332. t = 65535;
  5333. if (dh > 65535)
  5334. dh = 65535;
  5335. img_top[node] = (unsigned short)t;
  5336. img_h[node] = (unsigned short)dh;
  5337. }
  5338. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  5339. l->line_x > l->line_left))
  5340. flush_line(l);
  5341. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  5342. flush_line(l);
  5343. if (l->nruns == 0) {
  5344. l->line_y = l->y;
  5345. l->line_h = 0;
  5346. start_line(l, st);
  5347. }
  5348. {
  5349. struct lay_run *r = &l->runs[l->nruns++];
  5350. int gap = l->line_x - l->run_x;
  5351. if (gap < 0)
  5352. gap = 0;
  5353. r->gap = (unsigned short)gap;
  5354. r->off = 0;
  5355. r->len = 0;
  5356. r->color = 0;
  5357. r->href = href;
  5358. r->form = 0;
  5359. r->form_kind = 0;
  5360. r->form_disabled = 0;
  5361. /* Inline replaced elements honour their vertical margins; this
  5362. * is how Bootstrap's negative logo margins centre the wordmark. */
  5363. {
  5364. int idy = mp_px(st, 0, l->right - l->left);
  5365. if (idy < -2048)
  5366. idy = -2048;
  5367. if (idy > 2048)
  5368. idy = 2048;
  5369. r->dy = (signed short)idy;
  5370. }
  5371. r->has_lit = 0;
  5372. r->lit[0] = '\0';
  5373. r->img = (short)idx;
  5374. r->iw = (unsigned short)dw;
  5375. r->ih = (unsigned short)dh;
  5376. r->w = (unsigned short)dw;
  5377. r->font_px = st->font_px;
  5378. r->bold = st->bold;
  5379. r->italic = st->italic;
  5380. r->mono = st->mono;
  5381. r->font_face = st->font_face;
  5382. r->transform_scale = st->transform_scale;
  5383. r->scale_x = st->scale_x;
  5384. r->scale_y = st->scale_y;
  5385. r->rotate_x100 = st->rotate_x100;
  5386. r->origin_x = st->origin_x;
  5387. r->origin_y = st->origin_y;
  5388. r->origin_x_kind = st->origin_x_kind;
  5389. r->origin_y_kind = st->origin_y_kind;
  5390. r->underline = 0;
  5391. }
  5392. if (node < BR_MAX_NODES) {
  5393. layout_boxes[node].x = l->line_x;
  5394. layout_boxes[node].y = l->line_y +
  5395. mp_px(st, 0, l->right - l->left);
  5396. layout_boxes[node].w = dw;
  5397. layout_boxes[node].h = dh;
  5398. layout_boxes[node].valid = 1;
  5399. }
  5400. l->line_x += dw;
  5401. l->run_x = l->line_x;
  5402. if (l->line_h < dh)
  5403. l->line_h = dh;
  5404. }
  5405. static int text_width(struct lay *l, const char *s, unsigned int n,
  5406. const struct br_style *st)
  5407. {
  5408. return (int)face_text_width(l->ui, st, s, n);
  5409. }
  5410. /* Longest prefix that fits in maxw, at least one byte. */
  5411. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  5412. const struct br_style *st, int maxw)
  5413. {
  5414. unsigned int take = 0;
  5415. while (take < n) {
  5416. if (text_width(l, s, take + 1, st) > maxw)
  5417. break;
  5418. take++;
  5419. }
  5420. return take ? take : 1;
  5421. }
  5422. static void emit_word(struct lay *l, const char *s, unsigned int start,
  5423. unsigned int n, unsigned int base,
  5424. const struct br_style *st, unsigned short href)
  5425. {
  5426. int avail;
  5427. int w = text_width(l, s + start, n, st);
  5428. unsigned int off = start;
  5429. if (l->nruns == 0)
  5430. start_line(l, st);
  5431. avail = l->line_right - l->line_left;
  5432. if (st->nowrap) {
  5433. if (n)
  5434. add_run(l, base + start,
  5435. (unsigned short)n, st, href, 0);
  5436. return;
  5437. }
  5438. /* A padded/bordered one-word button can be a few pixels wider than
  5439. * the content box; keep it on one line instead of splitting it. */
  5440. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  5441. add_run(l, base + start,
  5442. (unsigned short)n, st, href, 0);
  5443. return;
  5444. }
  5445. if (l->line_x + w > l->line_right &&
  5446. (l->nruns > 0 || l->line_x > l->line_left)) {
  5447. flush_line(l);
  5448. start_line(l, st);
  5449. avail = l->line_right - l->line_left;
  5450. }
  5451. if (w <= avail) {
  5452. if (n)
  5453. add_run(l, base + start,
  5454. (unsigned short)n, st, href, 0);
  5455. return;
  5456. }
  5457. while (n > 0) {
  5458. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  5459. add_run(l, base + off,
  5460. (unsigned short)take, st, href, 0);
  5461. off += take;
  5462. n -= take;
  5463. if (n) {
  5464. flush_line(l);
  5465. start_line(l, st);
  5466. avail = l->line_right - l->line_left;
  5467. }
  5468. }
  5469. }
  5470. static void emit_text(struct lay *l, const char *s, unsigned int len,
  5471. const struct br_style *st, unsigned short href, int pre)
  5472. {
  5473. unsigned int i = 0;
  5474. unsigned int base;
  5475. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  5476. if (!s || !len)
  5477. return;
  5478. if (space_w <= 0)
  5479. space_w = 8;
  5480. if (l->nruns == 0)
  5481. start_line(l, st);
  5482. base = (unsigned int)(s - doc.text);
  5483. if (st->uppercase) {
  5484. char *p = (char *)s;
  5485. unsigned int j;
  5486. for (j = 0; j < len; j++)
  5487. if (p[j] >= 'a' && p[j] <= 'z')
  5488. p[j] = (char)(p[j] - 'a' + 'A');
  5489. }
  5490. if (pre) {
  5491. while (i < len) {
  5492. unsigned int start;
  5493. if (s[i] == '\n') {
  5494. flush_line(l);
  5495. start_line(l, st);
  5496. i++;
  5497. continue;
  5498. }
  5499. if (s[i] == ' ') {
  5500. if (l->line_x + space_w > l->line_right &&
  5501. (l->nruns > 0 || l->line_x > l->line_left)) {
  5502. flush_line(l);
  5503. start_line(l, st);
  5504. } else {
  5505. l->line_x += space_w;
  5506. }
  5507. i++;
  5508. continue;
  5509. }
  5510. start = i;
  5511. while (i < len && s[i] != ' ' && s[i] != '\n')
  5512. i++;
  5513. emit_word(l, s, start, i - start, base, st, href);
  5514. }
  5515. return;
  5516. }
  5517. while (i < len) {
  5518. unsigned int start, n;
  5519. if (s[i] == ' ') {
  5520. l->space_pending = 1;
  5521. i++;
  5522. continue;
  5523. }
  5524. start = i;
  5525. while (i < len && s[i] != ' ')
  5526. i++;
  5527. n = i - start;
  5528. if (l->space_pending &&
  5529. (l->nruns > 0 || l->line_x > l->line_left)) {
  5530. if (st->nowrap ||
  5531. l->line_x + space_w <= l->line_right)
  5532. l->line_x += space_w;
  5533. }
  5534. l->space_pending = 0;
  5535. emit_word(l, s, start, n, base, st, href);
  5536. }
  5537. }
  5538. static int list_index(unsigned int parent, unsigned int node)
  5539. {
  5540. unsigned int n = 0, i;
  5541. for (i = doc.nodes[parent].first; i && i != node;
  5542. i = doc.nodes[i].next)
  5543. if (doc.nodes[i].tag == BR_TAG_LI)
  5544. n++;
  5545. return (int)n + 1;
  5546. }
  5547. static void list_roman(char *m, unsigned int *n, int v, int upper,
  5548. unsigned int cap)
  5549. {
  5550. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  5551. 50, 40, 10, 9, 5, 4, 1 };
  5552. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  5553. "l", "xl", "x", "ix", "v", "iv", "i" };
  5554. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  5555. "L", "XL", "X", "IX", "V", "IV", "I" };
  5556. unsigned int i;
  5557. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  5558. while (v >= val[i] && *n + 1 < cap) {
  5559. const char *s = upper ? up[i] : lo[i];
  5560. while (*s && *n + 1 < cap)
  5561. m[(*n)++] = *s++;
  5562. v -= val[i];
  5563. }
  5564. }
  5565. }
  5566. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  5567. {
  5568. unsigned int n = 0;
  5569. if (style == BR_LIST_DISC) {
  5570. m[n++] = '-';
  5571. } else if (style == BR_LIST_CIRCLE) {
  5572. m[n++] = 'o';
  5573. } else if (style == BR_LIST_SQUARE) {
  5574. m[n++] = '+';
  5575. } else if (style == BR_LIST_LOWER_ALPHA ||
  5576. style == BR_LIST_UPPER_ALPHA) {
  5577. if (idx >= 1 && idx <= 26)
  5578. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  5579. 'A' : 'a') + idx - 1);
  5580. else
  5581. m[n++] = '?';
  5582. m[n++] = '.';
  5583. } else if (style == BR_LIST_LOWER_ROMAN ||
  5584. style == BR_LIST_UPPER_ROMAN) {
  5585. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  5586. if (n + 1 < cap)
  5587. m[n++] = '.';
  5588. } else {
  5589. s_append_dec(m, &n, (unsigned int)idx, cap);
  5590. if (n + 1 < cap)
  5591. m[n++] = '.';
  5592. }
  5593. m[n] = '\0';
  5594. }
  5595. /* Set by the layout when the control is stretched to its line: a flex item
  5596. * (its box width was assigned by the flex row) or a child of a flex column,
  5597. * whose default align-items: stretch makes inputs full width. */
  5598. static int form_fill_line;
  5599. static void add_form_run(struct lay *l, unsigned int node,
  5600. const struct br_style *st, unsigned short href)
  5601. {
  5602. struct form_state *fs = form_get(node, 1);
  5603. char shown[FORM_VALUE_MAX + 1];
  5604. char opt[64];
  5605. const char *text = "";
  5606. struct lay_run *r;
  5607. int kind = form_kind_of(node);
  5608. int disabled = form_disabled(node);
  5609. int tw, w = 120, h = 20, i;
  5610. if (!fs)
  5611. return;
  5612. if (l->nruns == 0)
  5613. start_line(l, st);
  5614. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  5615. text = "";
  5616. w = 16;
  5617. h = 16;
  5618. } else if (kind == FORM_SELECT) {
  5619. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  5620. s_copy(opt, "Select", sizeof(opt));
  5621. text = opt;
  5622. w = 120;
  5623. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  5624. kind == FORM_RESET) {
  5625. if (fs->len)
  5626. text = fs->value;
  5627. else
  5628. text = kind == FORM_SUBMIT ? "Submit" :
  5629. kind == FORM_RESET ? "Reset" : "Button";
  5630. } else if (kind == FORM_PASSWORD) {
  5631. for (i = 0; i < fs->len; i++)
  5632. shown[i] = '*';
  5633. shown[fs->len] = '\0';
  5634. text = fs->len ? shown : br_placeholder(&doc, node);
  5635. } else {
  5636. if (fs->len)
  5637. text = fs->value;
  5638. else
  5639. text = br_placeholder(&doc, node);
  5640. if (kind == FORM_TEXTAREA) {
  5641. w = 180;
  5642. h = 40;
  5643. }
  5644. }
  5645. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  5646. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  5647. w = tw + 18;
  5648. if (w < 64)
  5649. w = 64;
  5650. h = 22;
  5651. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD) {
  5652. int line_w = l->line_right - l->line_left;
  5653. if (st->width_kind == 1)
  5654. w = st->width;
  5655. else if (st->width_kind == 2)
  5656. w = css_size(st->width_kind, st->width, line_w);
  5657. else if (form_fill_line || st->display == BR_DISPLAY_BLOCK)
  5658. w = line_w - (l->line_x - l->line_left);
  5659. else
  5660. w = 120;
  5661. /* Taller fields for large text (min-height/padding on login
  5662. * pages): keep the box around the glyphs. */
  5663. if (st->font_px + 8 > h)
  5664. h = st->font_px + 8;
  5665. } else if (kind == FORM_SELECT) {
  5666. w = st->width_kind == 1 ? st->width : 120;
  5667. }
  5668. if (w > l->line_right - l->line_left)
  5669. w = l->line_right - l->line_left;
  5670. if (w < 8)
  5671. w = 8;
  5672. if (l->line_x + w > l->line_right &&
  5673. (l->nruns > 0 || l->line_x > l->line_left))
  5674. flush_line(l);
  5675. if (l->nruns >= 96)
  5676. return;
  5677. if (l->nruns == 0) {
  5678. l->line_y = l->y;
  5679. l->line_h = 0;
  5680. start_line(l, st);
  5681. }
  5682. r = &l->runs[l->nruns++];
  5683. r->gap = (unsigned short)(l->line_x - l->run_x);
  5684. r->off = r->len = 0;
  5685. r->color = st->color;
  5686. r->href = href;
  5687. r->dy = 0;
  5688. r->has_lit = 1;
  5689. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  5690. r->lit[i] = text[i];
  5691. r->lit[i] = '\0';
  5692. r->img = -2;
  5693. r->iw = (unsigned short)w;
  5694. r->ih = (unsigned short)h;
  5695. r->w = (unsigned short)w;
  5696. r->font_px = st->font_px;
  5697. r->bold = st->bold;
  5698. r->italic = st->italic;
  5699. r->mono = st->mono;
  5700. r->font_face = st->font_face;
  5701. r->underline = 0;
  5702. r->form = node + 1;
  5703. r->form_kind = (unsigned char)kind;
  5704. r->form_disabled = (unsigned char)disabled;
  5705. if (node < BR_MAX_NODES) {
  5706. layout_boxes[node].x = l->line_x;
  5707. layout_boxes[node].y = l->line_y;
  5708. layout_boxes[node].w = w;
  5709. layout_boxes[node].h = h;
  5710. layout_boxes[node].valid = 1;
  5711. }
  5712. l->line_x += w;
  5713. l->run_x = l->line_x;
  5714. if (l->line_h < h)
  5715. l->line_h = h;
  5716. }
  5717. /* A poster wrapper is absolutely positioned over the media slot; the
  5718. * measured height of its picture is normally added back to the flow. When a
  5719. * loading-skeleton sibling already reserves that slot, adding both doubles
  5720. * the media height and pushes the article text a full screen down. */
  5721. static int has_skeleton_sibling(unsigned int node)
  5722. {
  5723. unsigned int p = doc.nodes[node].parent, c;
  5724. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  5725. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  5726. continue;
  5727. if (doc.nodes[c].class_off &&
  5728. contains_ci(doc.attrs + doc.nodes[c].class_off,
  5729. "skeleton"))
  5730. return 1;
  5731. }
  5732. return 0;
  5733. }
  5734. static void layout_children(struct lay *l, unsigned int parent,
  5735. const struct br_style *pst, int depth,
  5736. unsigned short link);
  5737. static void layout_flex_children(struct lay *l, unsigned int parent,
  5738. const struct br_style *pst, int depth,
  5739. unsigned short link);
  5740. static void layout_grid_children(struct lay *l, unsigned int parent,
  5741. const struct br_style *pst, int depth,
  5742. unsigned short link);
  5743. static void layout_grid_auto(struct lay *l, unsigned int parent,
  5744. const struct br_style *pst, int depth,
  5745. unsigned short link);
  5746. static int flex_item_width(struct lay *l, unsigned int n,
  5747. const struct br_style *cs, int avail);
  5748. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  5749. const struct br_style *pst, int depth,
  5750. unsigned short link);
  5751. static void layout_table_row(struct lay *l, unsigned int row,
  5752. const struct br_style *pst, int depth,
  5753. unsigned short link);
  5754. static int table_has_rowspan(unsigned int table);
  5755. static void layout_table(struct lay *l, unsigned int table,
  5756. const struct br_style *st, int depth,
  5757. unsigned short link);
  5758. /* A flex container whose items are only inline spans is usually just a
  5759. * heading/icon pair. Our flex row positions such items without emitting
  5760. * their inline text in some deep page contexts; normal inline flow renders
  5761. * the same content correctly. */
  5762. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  5763. {
  5764. unsigned int c;
  5765. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  5766. struct br_node *nd = &doc.nodes[c];
  5767. struct br_style cs;
  5768. if (nd->type == BR_NODE_TEXT)
  5769. continue;
  5770. br_style_for(&doc, c, pst, &cs);
  5771. if (cs.display == BR_DISPLAY_NONE)
  5772. continue;
  5773. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  5774. cs.width_kind || cs.has_bg ||
  5775. cs.border_w[0] || cs.border_w[1] ||
  5776. cs.border_w[2] || cs.border_w[3] ||
  5777. nd->tag == BR_TAG_IMG)
  5778. return 1;
  5779. }
  5780. return 0;
  5781. }
  5782. static int css_radius(const struct br_style *st, int corner,
  5783. int w, int h)
  5784. {
  5785. int r = st->radius[corner];
  5786. if (r <= 0)
  5787. return 0;
  5788. if (r > w / 2)
  5789. r = w / 2;
  5790. if (r > h / 2)
  5791. r = h / 2;
  5792. return r;
  5793. }
  5794. /* ---- inline SVG ----
  5795. *
  5796. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  5797. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  5798. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  5799. * opacity and solid paint; a gradient paints the average of its stops) and
  5800. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  5801. #define SVG_CACHE_MAX 48
  5802. #define SVG_CACHE_PIXELS (640 * 1024)
  5803. #define SVG_MAX_POINTS 24576
  5804. struct svg_cache_ent {
  5805. unsigned int node;
  5806. int w, h;
  5807. unsigned short *px;
  5808. unsigned char *a;
  5809. unsigned int stamp;
  5810. };
  5811. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  5812. static unsigned int svg_cache_pixels, svg_cache_clock;
  5813. static struct svgr svg_geom;
  5814. static void *svg_geom_buf;
  5815. /* Current viewport in user units: percentage lengths resolve against it
  5816. * (the viewBox size, not the device pixels). */
  5817. static double svg_vp_w = 300, svg_vp_h = 150;
  5818. /* The layers live in the page heap: forget them before heap_reset(). */
  5819. static void svg_cache_clear(void)
  5820. {
  5821. memset(svg_cache, 0, sizeof(svg_cache));
  5822. svg_cache_pixels = 0;
  5823. svg_geom_buf = 0;
  5824. }
  5825. static int svg_name_is(const char *a, const char *b)
  5826. {
  5827. while (*a && *b) {
  5828. char x = *a, y = *b;
  5829. if (x >= 'A' && x <= 'Z')
  5830. x = (char)(x - 'A' + 'a');
  5831. if (x != y)
  5832. return 0;
  5833. a++;
  5834. b++;
  5835. }
  5836. return *a == *b;
  5837. }
  5838. static const char *svg_elem_name(unsigned int node)
  5839. {
  5840. const struct br_node *nd = &doc.nodes[node];
  5841. if (nd->name_off)
  5842. return doc.attrs + nd->name_off;
  5843. return br_tag_name(nd->tag);
  5844. }
  5845. /* A numeric attribute; a percentage resolves against `base`. */
  5846. static double svg_attr_num(unsigned int node, const char *name, double def,
  5847. double base)
  5848. {
  5849. const char *v = br_find_attr(&doc, node, name);
  5850. const char *p = v;
  5851. int ok = 0;
  5852. double x;
  5853. if (!v)
  5854. return def;
  5855. x = svgr_num(&p, &ok);
  5856. if (!ok)
  5857. return def;
  5858. if (*p == '%')
  5859. x = x * base / 100.0;
  5860. return x;
  5861. }
  5862. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  5863. static int svg_viewbox4(unsigned int node, double vb[4])
  5864. {
  5865. const char *v = br_find_attr(&doc, node, "viewbox");
  5866. const char *p = v;
  5867. int i, ok = 1;
  5868. if (!v)
  5869. return 0;
  5870. for (i = 0; i < 4 && ok; i++)
  5871. vb[i] = svgr_num(&p, &ok);
  5872. return ok && vb[2] > 0 && vb[3] > 0;
  5873. }
  5874. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  5875. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  5876. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  5877. double w, double h, double m[6])
  5878. {
  5879. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  5880. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  5881. int ax = 1, ay = 1;
  5882. if (par && contains_ci(par, "none")) {
  5883. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  5884. m[4] = -vb[0] * sx;
  5885. m[5] = -vb[1] * sy;
  5886. return;
  5887. }
  5888. if (par) {
  5889. if (contains_ci(par, "xmin"))
  5890. ax = 0;
  5891. else if (contains_ci(par, "xmax"))
  5892. ax = 2;
  5893. if (contains_ci(par, "ymin"))
  5894. ay = 0;
  5895. else if (contains_ci(par, "ymax"))
  5896. ay = 2;
  5897. }
  5898. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  5899. (sx < sy ? sx : sy);
  5900. tx = (w - vb[2] * s) * ax / 2.0;
  5901. ty = (h - vb[3] * s) * ay / 2.0;
  5902. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  5903. m[4] = tx - vb[0] * s;
  5904. m[5] = ty - vb[1] * s;
  5905. }
  5906. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  5907. * the paint attribute, then average the gradient's stops. */
  5908. static int svg_url_paint(unsigned int node, const char *attr,
  5909. unsigned short *color, unsigned int *alpha)
  5910. {
  5911. const char *v = 0, *h;
  5912. char id[64];
  5913. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  5914. for (k = 0; node && k < 32 && !v; k++) {
  5915. v = br_find_attr(&doc, node, attr);
  5916. if (!v) {
  5917. const char *style = br_find_attr(&doc, node, "style");
  5918. if (style && contains_ci(style, "url(#"))
  5919. v = strstr(style, "url(#");
  5920. }
  5921. if (v && !contains_ci(v, "url("))
  5922. v = 0;
  5923. node = doc.nodes[node].parent;
  5924. }
  5925. if (!v || !(h = strstr(v, "#")))
  5926. return 0;
  5927. h++;
  5928. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  5929. id[n++] = *h++;
  5930. id[n] = '\0';
  5931. g = br_find_id(&doc, id);
  5932. /* Follow href chains (a gradient that only references another one's
  5933. * stops), at most a few hops. */
  5934. for (k = 0; g && k < 4; k++) {
  5935. unsigned int gi = g - 1;
  5936. const char *ref;
  5937. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  5938. const char *nm, *sc, *so;
  5939. unsigned short col = 0;
  5940. double op = 1;
  5941. if (doc.nodes[c].type != BR_NODE_ELEM)
  5942. continue;
  5943. nm = svg_elem_name(c);
  5944. if (!svg_name_is(nm, "stop"))
  5945. continue;
  5946. sc = br_find_attr(&doc, c, "stop-color");
  5947. so = br_find_attr(&doc, c, "stop-opacity");
  5948. {
  5949. const char *st = br_find_attr(&doc, c, "style");
  5950. const char *q;
  5951. if (st && (q = strstr(st, "stop-color:")) != 0)
  5952. sc = q + 11;
  5953. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  5954. so = q + 13;
  5955. }
  5956. if (sc) {
  5957. unsigned int L = 0;
  5958. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  5959. L++;
  5960. if (!br_parse_color(sc, L, &col))
  5961. col = 0;
  5962. }
  5963. if (so) {
  5964. const char *p = so;
  5965. int ok = 0;
  5966. double x = svgr_num(&p, &ok);
  5967. if (ok)
  5968. op = x < 0 ? 0 : x > 1 ? 1 : x;
  5969. }
  5970. sr += (col >> 11) & 31;
  5971. sg += (col >> 5) & 63;
  5972. sb += col & 31;
  5973. sa += (unsigned int)(op * 255);
  5974. cnt++;
  5975. }
  5976. if (cnt)
  5977. break;
  5978. ref = br_find_attr(&doc, gi, "href");
  5979. if (!ref)
  5980. ref = br_find_attr(&doc, gi, "xlink:href");
  5981. if (!ref || ref[0] != '#')
  5982. break;
  5983. g = br_find_id(&doc, ref + 1);
  5984. }
  5985. if (!cnt)
  5986. return 0;
  5987. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  5988. (sb / cnt));
  5989. *alpha = sa / cnt;
  5990. return 1;
  5991. }
  5992. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  5993. unsigned short *color, unsigned int *alpha)
  5994. {
  5995. int mode = fill ? st->fill_mode : st->stroke_mode;
  5996. const char *op = br_find_attr(&doc, node,
  5997. fill ? "fill-opacity" : "stroke-opacity");
  5998. *alpha = 255;
  5999. switch (mode) {
  6000. case BR_PAINT_UNSET:
  6001. if (!fill)
  6002. return 0;
  6003. *color = 0;
  6004. break;
  6005. case BR_PAINT_COLOR:
  6006. *color = fill ? st->fill : st->stroke;
  6007. break;
  6008. case BR_PAINT_CURRENT:
  6009. *color = st->color;
  6010. break;
  6011. case BR_PAINT_URL:
  6012. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  6013. alpha))
  6014. return 0;
  6015. break;
  6016. default:
  6017. return 0;
  6018. }
  6019. if (op) {
  6020. const char *p = op;
  6021. int ok = 0;
  6022. double x = svgr_num(&p, &ok);
  6023. if (ok)
  6024. *alpha = (unsigned int)(*alpha *
  6025. (x < 0 ? 0 : x > 1 ? 1 : x));
  6026. }
  6027. return *alpha > 0;
  6028. }
  6029. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  6030. const double m[6], const struct br_style *pst,
  6031. unsigned int alpha, int depth);
  6032. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  6033. const double m[6], const struct br_style *st,
  6034. unsigned int alpha, int depth)
  6035. {
  6036. unsigned int c;
  6037. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  6038. if (doc.nodes[c].type == BR_NODE_ELEM)
  6039. svg_draw_node(L, c, m, st, alpha, depth + 1);
  6040. }
  6041. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  6042. const double pm[6], const struct br_style *pst,
  6043. unsigned int alpha, int depth)
  6044. {
  6045. struct br_style st;
  6046. const char *nm = svg_elem_name(node);
  6047. const char *tf;
  6048. double m[6];
  6049. unsigned short color;
  6050. unsigned int pa;
  6051. int shape = 0, fillable = 1;
  6052. if (depth > 24 || !nm)
  6053. return;
  6054. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  6055. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  6056. svg_name_is(nm, "lineargradient") ||
  6057. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  6058. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  6059. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  6060. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  6061. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  6062. svg_name_is(nm, "foreignobject"))
  6063. return;
  6064. br_style_for(&doc, node, pst, &st);
  6065. if (st.display == BR_DISPLAY_NONE)
  6066. return;
  6067. memcpy(m, pm, sizeof(m));
  6068. tf = br_find_attr(&doc, node, "transform");
  6069. if (tf)
  6070. svgr_transform(m, tf);
  6071. {
  6072. const char *op = br_find_attr(&doc, node, "opacity");
  6073. if (op) {
  6074. const char *p = op;
  6075. int ok = 0;
  6076. double x = svgr_num(&p, &ok);
  6077. if (ok)
  6078. alpha = (unsigned int)(alpha *
  6079. (x < 0 ? 0 :
  6080. x > 1 ? 1 : x));
  6081. }
  6082. }
  6083. if (!alpha)
  6084. return;
  6085. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  6086. svg_name_is(nm, "switch")) {
  6087. svg_draw_children(L, node, m, &st, alpha, depth);
  6088. return;
  6089. }
  6090. if (svg_name_is(nm, "svg")) {
  6091. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  6092. y = svg_attr_num(node, "y", 0, 0);
  6093. double t[6] = { 1, 0, 0, 1, 0, 0 };
  6094. t[4] = x;
  6095. t[5] = y;
  6096. svgr_mat_mul(m, m, t);
  6097. double ow = svg_vp_w, oh = svg_vp_h;
  6098. if (svg_viewbox4(node, vb)) {
  6099. double w = svg_attr_num(node, "width", vb[2], ow);
  6100. double h = svg_attr_num(node, "height", vb[3], oh);
  6101. double vm[6];
  6102. svg_viewport_matrix(node, vb, w, h, vm);
  6103. svgr_mat_mul(m, m, vm);
  6104. svg_vp_w = vb[2];
  6105. svg_vp_h = vb[3];
  6106. }
  6107. svg_draw_children(L, node, m, &st, alpha, depth);
  6108. svg_vp_w = ow;
  6109. svg_vp_h = oh;
  6110. return;
  6111. }
  6112. if (svg_name_is(nm, "use")) {
  6113. const char *ref = br_find_attr(&doc, node, "href");
  6114. unsigned int tgt;
  6115. double t[6] = { 1, 0, 0, 1, 0, 0 };
  6116. if (!ref)
  6117. ref = br_find_attr(&doc, node, "xlink:href");
  6118. if (!ref || ref[0] != '#')
  6119. return;
  6120. tgt = br_find_id(&doc, ref + 1);
  6121. if (!tgt || tgt - 1 == node)
  6122. return;
  6123. tgt--;
  6124. t[4] = svg_attr_num(node, "x", 0, 0);
  6125. t[5] = svg_attr_num(node, "y", 0, 0);
  6126. svgr_mat_mul(m, m, t);
  6127. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  6128. double vb[4];
  6129. double ow = svg_vp_w, oh = svg_vp_h;
  6130. if (svg_viewbox4(tgt, vb)) {
  6131. double w = svg_attr_num(node, "width", vb[2],
  6132. ow);
  6133. double h = svg_attr_num(node, "height", vb[3],
  6134. oh);
  6135. double vm[6];
  6136. svg_viewport_matrix(tgt, vb, w, h, vm);
  6137. svgr_mat_mul(m, m, vm);
  6138. svg_vp_w = vb[2];
  6139. svg_vp_h = vb[3];
  6140. }
  6141. svg_draw_children(L, tgt, m, &st, alpha, depth);
  6142. svg_vp_w = ow;
  6143. svg_vp_h = oh;
  6144. } else {
  6145. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  6146. }
  6147. return;
  6148. }
  6149. svgr_reset(&svg_geom, m);
  6150. if (svg_name_is(nm, "path")) {
  6151. const char *d = br_find_attr(&doc, node, "d");
  6152. if (d) {
  6153. svgr_path(&svg_geom, d);
  6154. shape = 1;
  6155. }
  6156. } else if (svg_name_is(nm, "rect")) {
  6157. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  6158. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  6159. double rx = svg_attr_num(node, "rx", -1, w);
  6160. double ry = svg_attr_num(node, "ry", -1, h);
  6161. if (rx < 0)
  6162. rx = ry < 0 ? 0 : ry;
  6163. if (ry < 0)
  6164. ry = rx;
  6165. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  6166. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  6167. shape = 1;
  6168. } else if (svg_name_is(nm, "circle")) {
  6169. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  6170. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  6171. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  6172. shape = 1;
  6173. } else if (svg_name_is(nm, "ellipse")) {
  6174. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  6175. svg_attr_num(node, "cy", 0, svg_vp_h),
  6176. svg_attr_num(node, "rx", 0, svg_vp_w),
  6177. svg_attr_num(node, "ry", 0, svg_vp_h));
  6178. shape = 1;
  6179. } else if (svg_name_is(nm, "line")) {
  6180. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  6181. svg_attr_num(node, "y1", 0, svg_vp_h));
  6182. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  6183. svg_attr_num(node, "y2", 0, svg_vp_h));
  6184. shape = 1;
  6185. fillable = 0;
  6186. } else if (svg_name_is(nm, "polyline") ||
  6187. svg_name_is(nm, "polygon")) {
  6188. const char *pts = br_find_attr(&doc, node, "points");
  6189. if (pts) {
  6190. svgr_points(&svg_geom, pts,
  6191. svg_name_is(nm, "polygon"));
  6192. shape = 1;
  6193. }
  6194. }
  6195. if (!shape)
  6196. return;
  6197. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  6198. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  6199. st.fill_evenodd);
  6200. if (svg_paint(node, &st, 0, &color, &pa)) {
  6201. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  6202. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  6203. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  6204. }
  6205. }
  6206. /* <text> elements: drawn straight onto the page every frame (the glyph
  6207. * renderer targets the ngui canvas, not a layer). x/y map through the
  6208. * accumulated transform; the font size scales with it. */
  6209. static void svg_draw_text(struct ngui *ui, unsigned int node,
  6210. const double pm[6], const struct br_style *pst,
  6211. int ox, int oy, int depth)
  6212. {
  6213. unsigned int c;
  6214. if (depth > 24)
  6215. return;
  6216. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  6217. struct br_style st;
  6218. const char *nm, *tf;
  6219. double m[6];
  6220. if (doc.nodes[c].type != BR_NODE_ELEM)
  6221. continue;
  6222. nm = svg_elem_name(c);
  6223. if (!nm || svg_name_is(nm, "defs") ||
  6224. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  6225. svg_name_is(nm, "clippath"))
  6226. continue;
  6227. br_style_for(&doc, c, pst, &st);
  6228. if (st.display == BR_DISPLAY_NONE)
  6229. continue;
  6230. memcpy(m, pm, sizeof(m));
  6231. tf = br_find_attr(&doc, c, "transform");
  6232. if (tf)
  6233. svgr_transform(m, tf);
  6234. if (svg_name_is(nm, "text")) {
  6235. unsigned int t = doc.nodes[c].first;
  6236. const char *s;
  6237. unsigned int n, tw;
  6238. double x = svg_attr_num(c, "x", 0, 0),
  6239. y = svg_attr_num(c, "y", 0, 0);
  6240. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  6241. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  6242. int tx, ty, anchor;
  6243. unsigned short col;
  6244. unsigned int pa;
  6245. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  6246. continue;
  6247. if (px < 6)
  6248. px = 6;
  6249. if (px > 72)
  6250. px = 72;
  6251. if (!svg_paint(c, &st, 1, &col, &pa))
  6252. continue;
  6253. s = doc.text + doc.nodes[t].text_off;
  6254. n = doc.nodes[t].text_len;
  6255. st.font_px = (unsigned char)px;
  6256. tw = face_text_width(ui, &st, s, n);
  6257. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  6258. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  6259. ngui_text_ascent_face(ui, style_face(&st), px,
  6260. st.mono);
  6261. anchor = st.align;
  6262. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  6263. anchor = BR_ALIGN_CENTER;
  6264. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  6265. anchor = BR_ALIGN_RIGHT;
  6266. if (anchor == BR_ALIGN_CENTER)
  6267. tx -= (int)tw / 2;
  6268. else if (anchor == BR_ALIGN_RIGHT)
  6269. tx -= (int)tw;
  6270. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  6271. col, px, st.bold, st.italic,
  6272. st.mono);
  6273. } else {
  6274. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  6275. }
  6276. }
  6277. }
  6278. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  6279. {
  6280. double vb[4];
  6281. if (svg_viewbox4(node, vb)) {
  6282. svg_viewport_matrix(node, vb, w, h, m);
  6283. } else {
  6284. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  6285. }
  6286. }
  6287. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  6288. const struct br_style *st)
  6289. {
  6290. struct svg_cache_ent *e = 0;
  6291. struct svgr_layer L;
  6292. double m[6];
  6293. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  6294. svg_cache_clock++;
  6295. for (i = 0; i < SVG_CACHE_MAX; i++)
  6296. if (svg_cache[i].px && svg_cache[i].node == node &&
  6297. svg_cache[i].w == w && svg_cache[i].h == h) {
  6298. svg_cache[i].stamp = svg_cache_clock;
  6299. return &svg_cache[i];
  6300. }
  6301. if (need > SVG_CACHE_PIXELS)
  6302. return 0;
  6303. /* Evict least recently used layers until this one fits. */
  6304. for (;;) {
  6305. struct svg_cache_ent *lru = 0, *free_slot = 0;
  6306. for (i = 0; i < SVG_CACHE_MAX; i++) {
  6307. if (!svg_cache[i].px) {
  6308. if (!free_slot)
  6309. free_slot = &svg_cache[i];
  6310. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  6311. lru = &svg_cache[i];
  6312. }
  6313. }
  6314. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  6315. e = free_slot;
  6316. break;
  6317. }
  6318. if (!lru)
  6319. return 0;
  6320. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  6321. free(lru->px);
  6322. free(lru->a);
  6323. memset(lru, 0, sizeof(*lru));
  6324. }
  6325. if (!svg_geom_buf) {
  6326. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  6327. if (!svg_geom_buf)
  6328. return 0;
  6329. }
  6330. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  6331. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  6332. e->a = (unsigned char *)calloc(need, 1);
  6333. if (!e->px || !e->a) {
  6334. free(e->px);
  6335. free(e->a);
  6336. memset(e, 0, sizeof(*e));
  6337. return 0;
  6338. }
  6339. e->node = node;
  6340. e->w = w;
  6341. e->h = h;
  6342. e->stamp = svg_cache_clock;
  6343. svg_cache_pixels += need;
  6344. L.px = e->px;
  6345. L.a = e->a;
  6346. L.w = w;
  6347. L.h = h;
  6348. svg_root_matrix(node, w, h, m);
  6349. {
  6350. double vb[4];
  6351. if (svg_viewbox4(node, vb)) {
  6352. svg_vp_w = vb[2];
  6353. svg_vp_h = vb[3];
  6354. } else {
  6355. svg_vp_w = w;
  6356. svg_vp_h = h;
  6357. }
  6358. }
  6359. svg_draw_children(&L, node, m, st, 255, 0);
  6360. return e;
  6361. }
  6362. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  6363. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  6364. int *out_w, int *out_h)
  6365. {
  6366. double vb[4];
  6367. int has_vb = svg_viewbox4(node, vb);
  6368. double aw = svg_attr_num(node, "width", -1, cw);
  6369. double ah = svg_attr_num(node, "height", -1, 0);
  6370. int w, h;
  6371. if (st->width_kind)
  6372. w = cw;
  6373. else if (aw > 0)
  6374. w = (int)(aw + 0.5);
  6375. else if (st->height_kind == 1 && has_vb)
  6376. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  6377. else if (ah > 0 && has_vb)
  6378. w = (int)(ah * vb[2] / vb[3] + 0.5);
  6379. else if (has_vb)
  6380. w = cw;
  6381. else
  6382. w = 300;
  6383. if (st->max_width_kind == 1 && w > st->max_width)
  6384. w = st->max_width;
  6385. if (w > cw && cw > 0 && !(aw > 0))
  6386. w = cw;
  6387. if (w < 1)
  6388. w = 1;
  6389. if (w > 2000)
  6390. w = 2000;
  6391. if (st->height_kind == 1)
  6392. h = st->height;
  6393. else if (ah > 0)
  6394. h = (int)(ah + 0.5);
  6395. else if (has_vb)
  6396. h = (int)(w * vb[3] / vb[2] + 0.5);
  6397. else
  6398. h = 150;
  6399. if (h < 1)
  6400. h = 1;
  6401. if (h > 1400)
  6402. h = 1400;
  6403. *out_w = w;
  6404. *out_h = h;
  6405. }
  6406. static void svg_paint_box(struct ngui *ui, unsigned int node,
  6407. const struct br_style *st, int x, int y, int w, int h)
  6408. {
  6409. struct svg_cache_ent *e;
  6410. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  6411. int cx0, cy0, cx1, cy1, px, py;
  6412. double m[6];
  6413. if (ui->nclip > 0)
  6414. clip = ui->clip[ui->nclip - 1];
  6415. cx0 = r.x > clip.x ? r.x : clip.x;
  6416. cy0 = r.y > clip.y ? r.y : clip.y;
  6417. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  6418. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  6419. if (cx0 >= cx1 || cy0 >= cy1)
  6420. return;
  6421. e = svg_layer(node, w, h, st);
  6422. if (e) {
  6423. for (py = cy0; py < cy1; py++) {
  6424. unsigned int srow = (unsigned int)(py - y) *
  6425. (unsigned int)w;
  6426. unsigned short *dst = ui->px + py * ui->w;
  6427. for (px = cx0; px < cx1; px++) {
  6428. unsigned int si = srow + (unsigned int)(px - x);
  6429. unsigned int a = e->a[si];
  6430. if (!a)
  6431. continue;
  6432. dst[px] = a >= 255 ? e->px[si] :
  6433. blend_rgb565(dst[px], e->px[si], a);
  6434. }
  6435. }
  6436. }
  6437. svg_root_matrix(node, w, h, m);
  6438. ngui_push_clip(ui, r);
  6439. svg_draw_text(ui, node, m, st, x, y, 0);
  6440. ngui_pop_clip(ui);
  6441. }
  6442. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  6443. * keep using add_image_run(); this covers the CSS `position:absolute;
  6444. * width:100%` poster pattern used by news sites. */
  6445. static void image_block_size(unsigned int node, const struct br_style *st,
  6446. int cbw, int *out_w, int *out_h)
  6447. {
  6448. struct br_node *nd = &doc.nodes[node];
  6449. int idx = nd->img_index;
  6450. int iw = 0, ih = 0, w, h;
  6451. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  6452. iw = (int)images[idx].img.w;
  6453. ih = (int)images[idx].img.h;
  6454. if (iw <= 0 || ih <= 0) {
  6455. iw = (int)images[idx].native_w;
  6456. ih = (int)images[idx].native_h;
  6457. }
  6458. }
  6459. if (st->width_kind)
  6460. w = style_width_px(st, cbw);
  6461. else if (nd->width_attr)
  6462. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  6463. (int)nd->width_attr;
  6464. else if (iw)
  6465. w = iw;
  6466. else
  6467. w = 64;
  6468. if (w < 8)
  6469. w = 8;
  6470. if (cbw > 0 && w > cbw)
  6471. w = cbw;
  6472. if (st->height_kind)
  6473. h = style_height_px(st, cbw);
  6474. else if (nd->height_attr)
  6475. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  6476. (int)nd->height_attr;
  6477. else if (iw && ih)
  6478. h = w * ih / iw;
  6479. else
  6480. h = 64;
  6481. if (h < 8)
  6482. h = 8;
  6483. *out_w = w;
  6484. *out_h = h;
  6485. }
  6486. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  6487. int dw, int dh)
  6488. {
  6489. int idx = doc.nodes[node].img_index;
  6490. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  6491. struct img_blit b;
  6492. b.dst = l->ui->px;
  6493. b.dst_w = l->ui->w;
  6494. b.dst_h = l->ui->h;
  6495. b.clip_x = page_rect.x;
  6496. b.clip_y = page_rect.y;
  6497. b.clip_w = page_rect.w - 12;
  6498. b.clip_h = page_rect.h;
  6499. b.x = x;
  6500. b.y = y;
  6501. b.scale = ((unsigned int)dw << 16) / images[idx].img.w;
  6502. b.bg = ui.theme.bg;
  6503. b.bg2 = ui.theme.bg;
  6504. b.flags = IMG_BLIT_OVER_DST;
  6505. img_draw(&images[idx].img, &b);
  6506. } else if (l->draw) {
  6507. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  6508. 0xD69A);
  6509. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  6510. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  6511. }
  6512. }
  6513. static void layout_block(struct lay *l, unsigned int node,
  6514. const struct br_style *st, int depth,
  6515. unsigned short link)
  6516. {
  6517. int old_left = l->left, old_right = l->right, old_align = l->align;
  6518. int saved_parent_top = l->parent_top;
  6519. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  6520. int saved_cb_top = l->cb_top;
  6521. int top, l0, r0;
  6522. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  6523. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  6524. int deco_w, deco_h, content_w, content_h, box_h;
  6525. int img_dh = 0;
  6526. int definite_w = 0;
  6527. int normal_top = 0;
  6528. int rel_dx = 0, rel_dy = 0;
  6529. int clip_pushed = 0;
  6530. struct ngui_rect clip_rect;
  6531. /* A DOM level costs about two depth units (layout_block ->
  6532. * layout_children), so 48 covers a ~24-level page. Real news pages
  6533. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  6534. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  6535. return;
  6536. flow_y = l->y;
  6537. flow_left = l->left;
  6538. flow_right = l->right;
  6539. positioned = st->pos == 1 || st->pos == 2;
  6540. relative = st->pos == 3;
  6541. sticky = st->pos == 4;
  6542. shifted = relative || sticky || st->transform_set;
  6543. if (positioned) {
  6544. int def_w = st->width_kind == 1 ? st->width : -1;
  6545. if (st->pos == 2) {
  6546. int avail_w = page_rect.w - 12;
  6547. if (st->right_set && def_w >= 0)
  6548. l->left = page_rect.x + avail_w - st->right -
  6549. def_w;
  6550. else
  6551. l->left = page_rect.x +
  6552. (st->left_set ? st->left : 0);
  6553. l->right = def_w >= 0 ? l->left + def_w :
  6554. page_rect.x + avail_w;
  6555. if (st->bottom_set && st->height_kind)
  6556. l->y = page_rect.y + page_rect.h -
  6557. st->bottom -
  6558. style_height_px(st, page_rect.w);
  6559. else
  6560. l->y = page_rect.y +
  6561. (st->top_set ? st->top : 0);
  6562. } else {
  6563. int left = flow_left + (st->left_set ? st->left : 0);
  6564. unsigned int parent = doc.nodes[node].parent;
  6565. if (st->right_set && def_w >= 0)
  6566. left = flow_right - st->right - def_w;
  6567. l->left = left;
  6568. l->right = def_w >= 0 ? left + def_w :
  6569. flow_right +
  6570. (st->left_set ? st->left : 0);
  6571. l->y = flow_y + (st->top_set ? st->top : 0);
  6572. if (st->bottom_set && st->height_kind &&
  6573. parent < BR_MAX_NODES && block_h[parent] > 0)
  6574. l->y = flow_y + block_h[parent] - st->bottom -
  6575. style_height_px(st, old_right - old_left);
  6576. }
  6577. old_left = l->left;
  6578. old_right = l->right;
  6579. } else if (relative) {
  6580. rel_dx = st->left_set ? st->left :
  6581. (st->right_set ? -st->right : 0);
  6582. rel_dy = st->top_set ? st->top :
  6583. (st->bottom_set ? -st->bottom : 0);
  6584. }
  6585. if (st->transform_set) {
  6586. rel_dx += st->tx;
  6587. rel_dy += st->ty;
  6588. }
  6589. if (doc.nodes[node].tag == BR_TAG_INPUT ||
  6590. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  6591. doc.nodes[node].tag == BR_TAG_SELECT ||
  6592. doc.nodes[node].tag == BR_TAG_BUTTON) {
  6593. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  6594. s_eq(br_type(&doc, node), "hidden"))
  6595. return;
  6596. /* Reached as a block-level box (a flex item): the control
  6597. * fills the box the caller assigned, and its line is flushed
  6598. * here; flex layout resets the run list for the next item, so
  6599. * a queued run would never be drawn. */
  6600. form_fill_line = 1;
  6601. add_form_run(l, node, st, link);
  6602. form_fill_line = 0;
  6603. flush_line(l);
  6604. return;
  6605. }
  6606. flush_line(l);
  6607. cbw = old_right - old_left;
  6608. if (cbw < 8)
  6609. cbw = 8;
  6610. l->y += mp_px(st, 0, cbw);
  6611. top = l->y;
  6612. ml = mp_px(st, 3, cbw);
  6613. mr = mp_px(st, 1, cbw);
  6614. bl = st->border_w[3];
  6615. br = st->border_w[1];
  6616. pl = mp_px(st, 7, cbw);
  6617. pr = mp_px(st, 5, cbw);
  6618. bt = st->border_w[0];
  6619. bb = st->border_w[2];
  6620. pt = mp_px(st, 4, cbw);
  6621. pb = mp_px(st, 6, cbw);
  6622. deco_w = bl + br + pl + pr;
  6623. deco_h = bt + bb + pt + pb;
  6624. if (st->width_kind) {
  6625. int w;
  6626. if (st->width_kind == 3)
  6627. w = cbw * st->width_calc_pct / 100 +
  6628. st->width_calc_px;
  6629. else
  6630. w = css_size(st->width_kind, st->width, cbw);
  6631. if (w < 0)
  6632. w = 0;
  6633. content_w = st->box_sizing ? w - deco_w : w;
  6634. definite_w = 1;
  6635. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  6636. doc.nodes[node].tag == BR_TAG_TD ||
  6637. doc.nodes[node].tag == BR_TAG_TH) &&
  6638. doc.nodes[node].width_attr) {
  6639. /* Legacy table/cell width attributes: percentages resolve
  6640. * against the containing block, bare numbers are pixels. */
  6641. int w = doc.nodes[node].width_pct ?
  6642. cbw * doc.nodes[node].width_attr / 100 :
  6643. doc.nodes[node].width_attr;
  6644. if (w < 0)
  6645. w = 0;
  6646. content_w = st->box_sizing ? w - deco_w : w;
  6647. definite_w = 1;
  6648. } else {
  6649. content_w = cbw - ml - mr - deco_w;
  6650. }
  6651. if (content_w < 0)
  6652. content_w = 0;
  6653. if (st->max_width_kind) {
  6654. int mw = st->max_width_kind == 3 ?
  6655. cbw * st->max_width_calc_pct / 100 +
  6656. st->max_width_calc_px :
  6657. css_size(st->max_width_kind, st->max_width, cbw);
  6658. int max_box = st->box_sizing ? mw : mw + deco_w;
  6659. if (content_w + deco_w > max_box)
  6660. content_w = max_box - deco_w;
  6661. }
  6662. if (st->min_width_kind) {
  6663. int mw = st->min_width_kind == 3 ?
  6664. cbw * st->min_width_calc_pct / 100 +
  6665. st->min_width_calc_px :
  6666. css_size(st->min_width_kind, st->min_width, cbw);
  6667. int min_box = st->box_sizing ? mw : mw + deco_w;
  6668. if (content_w + deco_w < min_box) {
  6669. content_w = min_box - deco_w;
  6670. definite_w = 1;
  6671. }
  6672. }
  6673. if (content_w < 8)
  6674. content_w = 8;
  6675. if (definite_w) {
  6676. int free_w = cbw - ml - mr - deco_w - content_w;
  6677. if (free_w < 0)
  6678. free_w = 0;
  6679. if (st->ml_auto && st->mr_auto) {
  6680. ml = free_w / 2;
  6681. mr = free_w - ml;
  6682. } else if (st->ml_auto) {
  6683. ml = free_w;
  6684. } else if (st->mr_auto) {
  6685. mr = free_w;
  6686. }
  6687. }
  6688. if (doc.nodes[node].tag == BR_TAG_IMG) {
  6689. int iw, ih;
  6690. image_block_size(node, st, cbw, &iw, &ih);
  6691. content_w = iw;
  6692. img_dh = ih;
  6693. }
  6694. l0 = old_left + ml;
  6695. r0 = l0 + deco_w + content_w;
  6696. if (r0 < l0 + 8)
  6697. r0 = l0 + 8;
  6698. normal_top = top;
  6699. if (sticky) {
  6700. if (st->top_set) {
  6701. int stick = page_rect.y + 4 + st->top;
  6702. if (normal_top < stick)
  6703. rel_dy += stick - normal_top;
  6704. } else if (st->bottom_set && block_h[node]) {
  6705. int stick = page_rect.y + page_rect.h - st->bottom -
  6706. block_h[node];
  6707. if (normal_top > stick)
  6708. rel_dy += stick - normal_top;
  6709. }
  6710. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  6711. block_h[doc.nodes[node].parent]) {
  6712. unsigned int p = doc.nodes[node].parent;
  6713. int ptop = l->parent_top;
  6714. int pbottom = ptop + block_h[p];
  6715. int eh = block_h[node];
  6716. int moved_top = normal_top + rel_dy;
  6717. int moved_bottom = moved_top + eh;
  6718. if (moved_bottom > pbottom)
  6719. rel_dy -= moved_bottom - pbottom;
  6720. moved_top = normal_top + rel_dy;
  6721. if (moved_top < ptop)
  6722. rel_dy += ptop - moved_top;
  6723. }
  6724. }
  6725. if (shifted && l->draw) {
  6726. top += rel_dy;
  6727. l0 += rel_dx;
  6728. r0 += rel_dx;
  6729. }
  6730. l->parent_top = top;
  6731. if (st->pos != 0) {
  6732. /* Positioned boxes establish the containing block for their
  6733. * absolutely positioned descendants. */
  6734. l->cb_left = l0;
  6735. l->cb_right = r0;
  6736. l->cb_top = top;
  6737. }
  6738. if (l->draw && block_h[node] &&
  6739. top < page_rect.y + page_rect.h &&
  6740. top + block_h[node] > page_rect.y) {
  6741. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  6742. int rtl = css_radius(st, 0, box.w, box.h);
  6743. int rtr = css_radius(st, 1, box.w, box.h);
  6744. int rbr = css_radius(st, 2, box.w, box.h);
  6745. int rbl = css_radius(st, 3, box.w, box.h);
  6746. if (st->transform_scale) {
  6747. if (st->has_bg)
  6748. fill_transformed_rect(l->ui, box, st->bg, st);
  6749. } else if (rtl || rtr || rbr || rbl) {
  6750. if (st->has_bg) {
  6751. int bw = st->border_w[0];
  6752. if (bw > 0 && !st->border_t[0] &&
  6753. st->border_c[0] != st->bg &&
  6754. box.w > bw * 2 && box.h > bw * 2) {
  6755. struct ngui_rect inner = {
  6756. box.x + bw, box.y + bw,
  6757. box.w - bw * 2, box.h - bw * 2
  6758. };
  6759. int itl = rtl > bw ? rtl - bw : 0;
  6760. int itr = rtr > bw ? rtr - bw : 0;
  6761. int ibr = rbr > bw ? rbr - bw : 0;
  6762. int ibl = rbl > bw ? rbl - bw : 0;
  6763. ngui_fill_round_rect(l->ui, box, rtl,
  6764. rtr, rbr, rbl,
  6765. st->border_c[0]);
  6766. ngui_fill_round_rect(l->ui, inner,
  6767. itl, itr, ibr,
  6768. ibl, st->bg);
  6769. } else {
  6770. ngui_fill_round_rect(l->ui, box, rtl,
  6771. rtr, rbr, rbl,
  6772. st->bg);
  6773. }
  6774. } else if (st->border_w[0] && !st->border_t[0]) {
  6775. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  6776. rbl, st->border_w[0],
  6777. st->border_c[0]);
  6778. }
  6779. /* Rounded boxes paint their background image too
  6780. * (app icons are rounded squares), kept inside the
  6781. * corner arcs. */
  6782. if (st->bg_image)
  6783. draw_bg_image_round(l, box, node, st, rtl, rtr,
  6784. rbr, rbl);
  6785. } else {
  6786. if (st->has_bg)
  6787. ngui_fill_rect(l->ui, box, st->bg);
  6788. if (st->bg_image)
  6789. draw_bg_image(l, box, node, st);
  6790. if (st->border_w[0] || st->border_w[1] ||
  6791. st->border_w[2] || st->border_w[3])
  6792. draw_border_box(l->ui, box, st);
  6793. }
  6794. }
  6795. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  6796. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  6797. content_w, img_dh);
  6798. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  6799. l->ui && l->ui->nclip < 4) {
  6800. clip_rect.x = l0 + bl;
  6801. clip_rect.y = top + bt;
  6802. clip_rect.w = (r0 - l0) - bl - br;
  6803. clip_rect.h = (int)block_h[node] - bt - bb;
  6804. if (clip_rect.w > 0 && clip_rect.h > 0) {
  6805. ngui_push_clip(l->ui, clip_rect);
  6806. clip_pushed = 1;
  6807. }
  6808. }
  6809. l->left = l0 + bl + pl;
  6810. l->right = l->left + content_w;
  6811. if (l->right < l->left + 8)
  6812. l->right = l->left + 8;
  6813. l->align = st->align;
  6814. l->line_left = l->left;
  6815. l->line_right = l->right;
  6816. l->y = top + bt + pt;
  6817. if (doc.nodes[node].tag == BR_TAG_HR) {
  6818. if (l->draw)
  6819. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  6820. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  6821. l->y += 8;
  6822. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  6823. int vw = l->right - l->left;
  6824. int vh;
  6825. if (doc.nodes[node].width_pct)
  6826. vw = vw * doc.nodes[node].width_attr / 100;
  6827. else if (doc.nodes[node].width_attr)
  6828. vw = doc.nodes[node].width_attr;
  6829. if (vw > l->right - l->left)
  6830. vw = l->right - l->left;
  6831. if (vw < 8)
  6832. vw = 8;
  6833. vh = vw * 9 / 16;
  6834. if (vh > 240)
  6835. vh = 240;
  6836. if (vh < 80)
  6837. vh = 80;
  6838. if (l->draw) {
  6839. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  6840. vw, vh}, 0xD69A);
  6841. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  6842. vw, vh}, 0x8410);
  6843. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  6844. 0x4208);
  6845. }
  6846. l->y += vh + 4;
  6847. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  6848. int dw, dh, cw = l->right - l->left;
  6849. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  6850. if (l->draw && l->y < page_rect.y + page_rect.h &&
  6851. l->y + dh > page_rect.y)
  6852. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  6853. l->y += dh;
  6854. } else {
  6855. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  6856. !st->no_bullet) {
  6857. char *m = li_marker[node];
  6858. if (!m[0]) {
  6859. unsigned int parent = doc.nodes[node].parent;
  6860. int style = st->list_style;
  6861. int idx = parent ? list_index(parent, node) : 1;
  6862. if (style == BR_LIST_AUTO)
  6863. style = (parent &&
  6864. doc.nodes[parent].tag ==
  6865. BR_TAG_OL) ?
  6866. BR_LIST_DECIMAL : BR_LIST_DISC;
  6867. list_marker_text(m, sizeof(li_marker[node]),
  6868. style, idx);
  6869. }
  6870. if (l->draw && m[0]) {
  6871. int mw = (int)ngui_text_width_ui(l->ui, m);
  6872. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  6873. st->color);
  6874. }
  6875. }
  6876. if (doc.nodes[node].tag == BR_TAG_TR)
  6877. layout_table_row(l, node, st, depth + 1, link);
  6878. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  6879. table_has_rowspan(node))
  6880. layout_table(l, node, st, depth + 1, link);
  6881. else if (st->grid_auto)
  6882. layout_grid_auto(l, node, st, depth + 1, link);
  6883. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  6884. st->grid_gap > 0)
  6885. layout_grid_children(l, node, st, depth + 1, link);
  6886. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  6887. flex_wants_row(node, st))
  6888. layout_flex_children(l, node, st, depth + 1, link);
  6889. else
  6890. layout_children(l, node, st, depth + 1, link);
  6891. }
  6892. flush_line(l);
  6893. if (clip_pushed)
  6894. ngui_pop_clip(l->ui);
  6895. if (l->float_active) {
  6896. if (l->y < l->float_bottom)
  6897. l->y = l->float_bottom;
  6898. l->float_active = 0;
  6899. }
  6900. if (doc.nodes[node].tag == BR_TAG_IMG) {
  6901. content_h = img_dh;
  6902. } else if (st->height_kind &&
  6903. !((doc.nodes[node].tag == BR_TAG_HTML ||
  6904. doc.nodes[node].tag == BR_TAG_BODY) &&
  6905. st->height_kind == 2)) {
  6906. content_h = style_height_px(st, cbw);
  6907. if (st->box_sizing)
  6908. content_h -= deco_h;
  6909. } else {
  6910. /* Percentage heights on html/body resolve against the
  6911. * viewport, but their content still defines the document
  6912. * scroll height. Treating them as auto avoids collapsing
  6913. * the measured page to the containing block width. */
  6914. content_h = l->y - (top + bt + pt);
  6915. }
  6916. if (content_h < 0)
  6917. content_h = 0;
  6918. if (st->max_height_kind) {
  6919. int mh = st->max_height_kind == 3 ?
  6920. cbw * st->max_height_calc_pct / 100 +
  6921. st->max_height_calc_px :
  6922. css_size(st->max_height_kind, st->max_height, cbw);
  6923. int max_box = st->box_sizing ? mh : mh + deco_h;
  6924. if (content_h + deco_h > max_box)
  6925. content_h = max_box - deco_h;
  6926. }
  6927. if (st->min_height_kind &&
  6928. !((doc.nodes[node].tag == BR_TAG_HTML ||
  6929. doc.nodes[node].tag == BR_TAG_BODY) &&
  6930. st->min_height_kind == 2)) {
  6931. int mh = st->min_height_kind == 3 ?
  6932. cbw * st->min_height_calc_pct / 100 +
  6933. st->min_height_calc_px :
  6934. css_size(st->min_height_kind, st->min_height, cbw);
  6935. int min_box = st->box_sizing ? mh : mh + deco_h;
  6936. if (content_h + deco_h < min_box)
  6937. content_h = min_box - deco_h;
  6938. }
  6939. if (content_h < 0)
  6940. content_h = 0;
  6941. box_h = deco_h + content_h;
  6942. if (box_h < 0)
  6943. box_h = 0;
  6944. l->y = (shifted ? normal_top : top) + box_h;
  6945. if (node < BR_MAX_NODES) {
  6946. layout_boxes[node].x = l0;
  6947. layout_boxes[node].y = top;
  6948. layout_boxes[node].w = r0 - l0;
  6949. layout_boxes[node].h = box_h;
  6950. layout_boxes[node].valid = r0 > l0;
  6951. }
  6952. l->left = old_left;
  6953. l->right = old_right;
  6954. l->align = old_align;
  6955. l->y += mp_px(st, 2, cbw);
  6956. if (!l->draw) {
  6957. if (box_h > 65535)
  6958. box_h = 65535;
  6959. block_h[node] = (unsigned short)box_h;
  6960. block_top[node] = (unsigned short)(top < 0 ? 0 :
  6961. top > 65535 ? 65535 : top);
  6962. }
  6963. if (positioned) {
  6964. l->y = flow_y;
  6965. l->left = flow_left;
  6966. l->right = flow_right;
  6967. }
  6968. l->parent_top = saved_parent_top;
  6969. l->cb_left = saved_cb_left;
  6970. l->cb_right = saved_cb_right;
  6971. l->cb_top = saved_cb_top;
  6972. }
  6973. static int text_node_blank(const struct br_node *nd)
  6974. {
  6975. const char *t = doc.text + nd->text_off;
  6976. unsigned int i;
  6977. for (i = 0; i < nd->text_len; i++)
  6978. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  6979. t[i] != '\r')
  6980. return 0;
  6981. return 1;
  6982. }
  6983. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  6984. * text/image widths in the subtree, plus padding and margins. This keeps
  6985. * Bootstrap's floated nav items on one line instead of giving each the whole
  6986. * row. */
  6987. static int text_space(char c)
  6988. {
  6989. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  6990. }
  6991. static int intrinsic_width(struct ngui *ui, unsigned int node,
  6992. const struct br_style *pst, int depth, int base)
  6993. {
  6994. unsigned int c;
  6995. int line_w = 0, max_w = 0;
  6996. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  6997. if (depth > 32)
  6998. return 0;
  6999. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7000. struct br_node *nd = &doc.nodes[c];
  7001. struct br_style cs;
  7002. if (nd->type == BR_NODE_TEXT) {
  7003. const char *t = doc.text + nd->text_off;
  7004. unsigned int tn = nd->text_len;
  7005. if (doc.nodes[node].tag == BR_TAG_PRE) {
  7006. line_w += (int)face_text_width(ui, pst, t, tn);
  7007. } else {
  7008. unsigned int ti = 0;
  7009. int first = 1;
  7010. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  7011. int sp = (int)face_text_width(ui, pst, " ", 1);
  7012. while (ti < tn) {
  7013. unsigned int ts;
  7014. while (ti < tn && text_space(t[ti]))
  7015. ti++;
  7016. ts = ti;
  7017. while (ti < tn && !text_space(t[ti]))
  7018. ti++;
  7019. if (ti == ts)
  7020. break;
  7021. if (!first || lead)
  7022. line_w += sp;
  7023. lead = 0;
  7024. line_w += (int)face_text_width(ui, pst,
  7025. t + ts, ti - ts);
  7026. first = 0;
  7027. }
  7028. }
  7029. continue;
  7030. }
  7031. br_style_for(&doc, c, pst, &cs);
  7032. if (cs.display == BR_DISPLAY_NONE)
  7033. continue;
  7034. if (nd->tag == BR_TAG_BR) {
  7035. if (line_w > max_w)
  7036. max_w = line_w;
  7037. line_w = 0;
  7038. continue;
  7039. }
  7040. if (nd->tag == BR_TAG_IMG) {
  7041. /* Measure the image as layout will draw it: a CSS or
  7042. * attribute height keeps the intrinsic aspect ratio, and
  7043. * a CSS width overrides the native pixel width. Bootstrap
  7044. * sizes the Cloudron logo with height:40px only. */
  7045. int idx = nd->img_index;
  7046. int iw = 0, ih = 0;
  7047. if (idx >= 0 && idx < image_count &&
  7048. images[idx].state == 1) {
  7049. iw = (int)images[idx].native_w;
  7050. ih = (int)images[idx].native_h;
  7051. if (iw <= 0 || ih <= 0) {
  7052. iw = (int)images[idx].img.w;
  7053. ih = (int)images[idx].img.h;
  7054. }
  7055. }
  7056. if (cs.width_kind) {
  7057. int ww = style_width_px(&cs, base);
  7058. line_w += ww > 0 ? ww : 64;
  7059. } else if (nd->width_attr) {
  7060. line_w += nd->width_attr;
  7061. } else if (nd->height_attr && iw && ih) {
  7062. line_w += iw * (int)nd->height_attr / ih;
  7063. } else if (cs.height_kind && iw && ih) {
  7064. int hh = style_height_px(&cs, base);
  7065. line_w += hh > 0 ? iw * hh / ih : iw;
  7066. } else if (iw) {
  7067. line_w += iw;
  7068. } else {
  7069. line_w += 64;
  7070. }
  7071. continue;
  7072. }
  7073. {
  7074. int cw = mp_px(&cs, 7, base) +
  7075. mp_px(&cs, 5, base) +
  7076. mp_px(&cs, 3, base) +
  7077. mp_px(&cs, 1, base) +
  7078. cs.border_w[1] + cs.border_w[3];
  7079. /* width/height do not apply to non-replaced inline
  7080. * boxes. The tagesschau home label is an inline span
  7081. * with width:1px for the mobile icon-only header; using
  7082. * that width made the whole subnav collapse to a
  7083. * one-character column. */
  7084. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  7085. cw += cs.width_kind == 1 ? cs.width :
  7086. style_width_px(&cs, base);
  7087. else
  7088. cw += intrinsic_width(ui, c, &cs, depth + 1,
  7089. base);
  7090. if (flex_row || cs.float_left ||
  7091. cs.display == BR_DISPLAY_INLINE ||
  7092. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  7093. line_w += cw;
  7094. } else {
  7095. if (line_w > max_w)
  7096. max_w = line_w;
  7097. line_w = 0;
  7098. if (cw > max_w)
  7099. max_w = cw;
  7100. }
  7101. }
  7102. if (line_w > 4096 || max_w > 4096)
  7103. break;
  7104. }
  7105. return line_w > max_w ? line_w : max_w;
  7106. }
  7107. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  7108. * the main user: .row > .col-md-* with float:left and a percentage width.
  7109. * Each column is laid out with its own left/right edge and the row advances
  7110. * to the tallest column. Returns the first child not consumed. */
  7111. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  7112. const struct br_style *pst, int depth,
  7113. unsigned short link)
  7114. {
  7115. unsigned int n = first;
  7116. int row_left = l->left, row_right = l->right;
  7117. int row_top, row_bottom, xl, xr, any = 0;
  7118. int fl_left = row_left, fl_right = row_right, fl_bottom;
  7119. flush_line(l);
  7120. row_top = l->y;
  7121. row_bottom = l->y;
  7122. fl_bottom = row_top;
  7123. xl = row_left;
  7124. xr = row_right;
  7125. while (n) {
  7126. struct br_node *nd = &doc.nodes[n];
  7127. struct br_style cs;
  7128. unsigned short lk = link;
  7129. int colw, right;
  7130. if (nd->type == BR_NODE_TEXT) {
  7131. if (text_node_blank(nd)) {
  7132. n = nd->next;
  7133. continue;
  7134. }
  7135. break;
  7136. }
  7137. br_style_for(&doc, n, pst, &cs);
  7138. if (cs.display == BR_DISPLAY_NONE) {
  7139. n = nd->next;
  7140. continue;
  7141. }
  7142. /* A float blockifies its box: Bootstrap floats inline
  7143. * anchors too (the navbar brand and its text links), and
  7144. * their padding must be honoured. */
  7145. if (!cs.float_left)
  7146. break;
  7147. if (nd->tag == BR_TAG_A && nd->href_off)
  7148. lk = (unsigned short)n;
  7149. right = cs.float_left == 2;
  7150. if (cs.width_kind == 2 || cs.width_kind == 3) {
  7151. colw = style_width_px(&cs, row_right - row_left);
  7152. } else if (cs.width_kind == 1) {
  7153. colw = (int)cs.width;
  7154. } else {
  7155. int base = row_right - row_left;
  7156. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  7157. mp_px(&cs, 7, base) +
  7158. mp_px(&cs, 5, base) +
  7159. mp_px(&cs, 3, base) +
  7160. mp_px(&cs, 1, base);
  7161. if (colw < 8)
  7162. colw = 8;
  7163. }
  7164. if (colw < 8)
  7165. colw = 8;
  7166. if (colw > row_right - row_left)
  7167. colw = row_right - row_left;
  7168. /* The float column width is already resolved. */
  7169. cs.width_kind = 0;
  7170. cs.max_width_kind = 0;
  7171. if (right) {
  7172. if (any && xr - colw < xl) {
  7173. row_top = row_bottom;
  7174. row_bottom = row_top;
  7175. xl = row_left;
  7176. xr = row_right;
  7177. }
  7178. if (xr - colw < xl)
  7179. colw = xr - xl;
  7180. if (colw < 8)
  7181. colw = 8;
  7182. l->left = xr - colw;
  7183. if (l->left < row_left)
  7184. l->left = row_left;
  7185. l->right = xr;
  7186. xr = l->left;
  7187. if (xr < fl_right)
  7188. fl_right = xr;
  7189. } else {
  7190. if (any && xl + colw > xr) {
  7191. row_top = row_bottom;
  7192. row_bottom = row_top;
  7193. xl = row_left;
  7194. xr = row_right;
  7195. }
  7196. l->left = xl;
  7197. l->right = xl + colw;
  7198. xl += colw;
  7199. if (xl > fl_left)
  7200. fl_left = xl;
  7201. }
  7202. if (l->right < l->left + 8)
  7203. l->right = l->left + 8;
  7204. l->y = row_top;
  7205. l->line_x = l->left;
  7206. l->run_x = l->left;
  7207. l->line_y = l->y;
  7208. l->line_h = 0;
  7209. l->nruns = 0;
  7210. l->space_pending = 0;
  7211. l->align = cs.align;
  7212. layout_block(l, n, &cs, depth + 1, lk);
  7213. if (l->y > row_bottom)
  7214. row_bottom = l->y;
  7215. if (l->y > fl_bottom)
  7216. fl_bottom = l->y;
  7217. any = 1;
  7218. n = nd->next;
  7219. }
  7220. l->left = row_left;
  7221. l->right = row_right;
  7222. if (n && any) {
  7223. struct br_node *nd = &doc.nodes[n];
  7224. int inline_next = 0;
  7225. if (nd->type == BR_NODE_TEXT) {
  7226. inline_next = 1;
  7227. } else if (nd->type == BR_NODE_ELEM) {
  7228. struct br_style cs;
  7229. br_style_for(&doc, n, pst, &cs);
  7230. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  7231. cs.display != BR_DISPLAY_NONE &&
  7232. !br_tag_is_block(nd->tag);
  7233. }
  7234. if (inline_next) {
  7235. if (l->float_active) {
  7236. if (l->float_left > fl_left)
  7237. fl_left = l->float_left;
  7238. if (l->float_right < fl_right)
  7239. fl_right = l->float_right;
  7240. if (l->float_bottom > fl_bottom)
  7241. fl_bottom = l->float_bottom;
  7242. }
  7243. l->float_active = 1;
  7244. l->float_left = fl_left;
  7245. l->float_right = fl_right;
  7246. l->float_bottom = fl_bottom;
  7247. l->y = row_top;
  7248. } else {
  7249. l->float_active = 0;
  7250. l->y = row_bottom;
  7251. }
  7252. } else {
  7253. l->float_active = 0;
  7254. l->y = row_bottom;
  7255. }
  7256. l->line_x = l->left;
  7257. l->run_x = l->left;
  7258. l->line_left = l->left;
  7259. l->line_right = l->right;
  7260. l->line_y = l->y;
  7261. l->line_h = 0;
  7262. l->nruns = 0;
  7263. l->space_pending = 0;
  7264. return n;
  7265. }
  7266. static int flex_item_width(struct lay *l, unsigned int n,
  7267. const struct br_style *cs, int avail)
  7268. {
  7269. struct br_node *nd = &doc.nodes[n];
  7270. (void)l;
  7271. int w;
  7272. if (cs->width_kind == 2 || cs->width_kind == 3)
  7273. w = style_width_px(cs, avail);
  7274. else if (cs->width_kind == 1)
  7275. w = (int)cs->width;
  7276. else if (nd->tag == BR_TAG_IMG) {
  7277. int idx = nd->img_index;
  7278. if (idx >= 0 && idx < image_count &&
  7279. images[idx].state == 1)
  7280. w = (int)images[idx].img.w;
  7281. else if (nd->width_attr)
  7282. w = (int)nd->width_attr;
  7283. else
  7284. w = 64;
  7285. } else {
  7286. w = intrinsic_width(l->ui, n, cs, 0, avail);
  7287. }
  7288. /* Explicit widths are content-box sizes; the flex item's outer width
  7289. * must include padding, borders and margins. */
  7290. w += mp_px(cs, 7, avail);
  7291. w += mp_px(cs, 5, avail);
  7292. w += mp_px(cs, 3, avail);
  7293. w += mp_px(cs, 1, avail);
  7294. w += cs->border_w[1] + cs->border_w[3];
  7295. if (w < 24)
  7296. w = 24;
  7297. if (w > avail)
  7298. w = avail;
  7299. return w;
  7300. }
  7301. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  7302. * on one line, not one full-width block each. Place intrinsic widths from
  7303. * left to right and wrap when the row is full. */
  7304. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  7305. const struct br_style *pst, int depth,
  7306. unsigned short link)
  7307. {
  7308. unsigned int n = first;
  7309. int row_left = l->left, row_right = l->right;
  7310. int avail = row_right - row_left;
  7311. int x = row_left, y = l->y, row_h = 0, any = 0;
  7312. flush_line(l);
  7313. y = l->y;
  7314. while (n) {
  7315. struct br_node *nd = &doc.nodes[n];
  7316. struct br_style cs;
  7317. unsigned short lk = link;
  7318. int colw, h;
  7319. if (nd->type == BR_NODE_TEXT) {
  7320. if (!text_node_blank(nd))
  7321. break;
  7322. if (any)
  7323. x += 4;
  7324. n = nd->next;
  7325. continue;
  7326. }
  7327. br_style_for(&doc, n, pst, &cs);
  7328. if (cs.display == BR_DISPLAY_NONE) {
  7329. n = nd->next;
  7330. continue;
  7331. }
  7332. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  7333. break;
  7334. if (nd->tag == BR_TAG_A && nd->href_off)
  7335. lk = (unsigned short)n;
  7336. colw = flex_item_width(l, n, &cs, avail);
  7337. /* A few pixels of slack keep a single long token (boot.S)
  7338. * from wrapping at the exact content width. */
  7339. colw += 8;
  7340. if (colw > avail)
  7341. colw = avail;
  7342. cs.width_kind = 0;
  7343. cs.max_width_kind = 0;
  7344. if (any && x + colw > row_right) {
  7345. y += row_h + 2;
  7346. x = row_left;
  7347. row_h = 0;
  7348. any = 0;
  7349. }
  7350. if (any && x > row_left)
  7351. x += 4;
  7352. l->left = x;
  7353. l->right = x + colw;
  7354. if (l->right < l->left + 8)
  7355. l->right = l->left + 8;
  7356. l->y = y;
  7357. l->line_x = l->left;
  7358. l->run_x = l->left;
  7359. l->line_y = l->y;
  7360. l->line_h = 0;
  7361. l->nruns = 0;
  7362. l->space_pending = 0;
  7363. l->align = cs.align;
  7364. layout_block(l, n, &cs, depth + 1, lk);
  7365. h = l->y - y;
  7366. if (h > row_h)
  7367. row_h = h;
  7368. x += colw;
  7369. any = 1;
  7370. n = nd->next;
  7371. }
  7372. if (any)
  7373. y += row_h;
  7374. l->left = row_left;
  7375. l->right = row_right;
  7376. l->y = y;
  7377. l->line_x = l->left;
  7378. l->run_x = l->left;
  7379. l->line_y = l->y;
  7380. l->line_h = 0;
  7381. l->nruns = 0;
  7382. l->space_pending = 0;
  7383. return n;
  7384. }
  7385. struct flex_item {
  7386. unsigned int node;
  7387. unsigned short link;
  7388. int w;
  7389. };
  7390. static void layout_flex_children(struct lay *l, unsigned int parent,
  7391. const struct br_style *pst, int depth,
  7392. unsigned short link)
  7393. {
  7394. struct flex_item it[32];
  7395. unsigned int c;
  7396. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  7397. int row_left = l->left, row_right = l->right;
  7398. int avail = row_right - row_left;
  7399. int idx, row_top;
  7400. if (avail < 160 || depth > 48) {
  7401. layout_children(l, parent, pst, depth, link);
  7402. return;
  7403. }
  7404. /* If direct text is not just whitespace, normal block flow handles it
  7405. * better than pretending it is a flex item. */
  7406. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7407. struct br_node *nd = &doc.nodes[c];
  7408. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7409. layout_children(l, parent, pst, depth, link);
  7410. return;
  7411. }
  7412. }
  7413. for (c = doc.nodes[parent].first;
  7414. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  7415. c = doc.nodes[c].next) {
  7416. struct br_node *nd = &doc.nodes[c];
  7417. struct br_style cs;
  7418. if (nd->type == BR_NODE_TEXT)
  7419. continue;
  7420. br_style_for(&doc, c, pst, &cs);
  7421. if (cs.display == BR_DISPLAY_NONE)
  7422. continue;
  7423. it[nitem].node = c;
  7424. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  7425. (unsigned short)c : link;
  7426. it[nitem].w = 0;
  7427. if (cs.flex_grow && !cs.width_kind)
  7428. grow_count++;
  7429. else
  7430. fixed += flex_item_width(l, c, &cs, avail);
  7431. nitem++;
  7432. }
  7433. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  7434. if (grow_w < 96)
  7435. grow_w = 96;
  7436. for (idx = 0; idx < nitem; idx++) {
  7437. struct br_style cs;
  7438. br_style_for(&doc, it[idx].node, pst, &cs);
  7439. if (cs.flex_grow && !cs.width_kind)
  7440. it[idx].w = grow_w;
  7441. else
  7442. it[idx].w = flex_item_width(l, it[idx].node, &cs, avail);
  7443. if (it[idx].w > avail)
  7444. it[idx].w = avail;
  7445. if (it[idx].w < 8)
  7446. it[idx].w = 8;
  7447. }
  7448. row_top = l->y;
  7449. idx = 0;
  7450. while (idx < nitem) {
  7451. int start = idx, count = 0, row_w = 0;
  7452. int free_w, x, extra = 0, row_h = 0, k;
  7453. while (idx < nitem) {
  7454. int add = it[idx].w + (count ? gap : 0);
  7455. /* CSS default is nowrap; only flex-wrap: wrap (1)
  7456. * starts a new row. */
  7457. if (count && pst->flex_wrap == 1 &&
  7458. row_w + add > avail)
  7459. break;
  7460. row_w += add;
  7461. count++;
  7462. idx++;
  7463. }
  7464. if (!count) {
  7465. count = 1;
  7466. row_w = it[start].w;
  7467. idx = start + 1;
  7468. }
  7469. free_w = avail - row_w;
  7470. if (free_w < 0)
  7471. free_w = 0;
  7472. x = row_left;
  7473. if (pst->justify == 1) {
  7474. x += free_w / 2;
  7475. } else if (pst->justify == 2) {
  7476. x += free_w;
  7477. } else if (pst->justify == 3) {
  7478. extra = count > 1 ? free_w / (count - 1) : 0;
  7479. } else if (pst->justify == 4) {
  7480. extra = count ? free_w / count : 0;
  7481. x += extra / 2;
  7482. } else if (pst->justify == 5) {
  7483. extra = count ? free_w / (count + 1) : 0;
  7484. x += extra;
  7485. }
  7486. for (k = 0; k < count; k++) {
  7487. int node = (int)it[start + k].node;
  7488. int h = block_h[node];
  7489. if (h > row_h)
  7490. row_h = h;
  7491. }
  7492. if (pst->height_kind) {
  7493. int hh = style_height_px(pst, avail);
  7494. if (hh > row_h)
  7495. row_h = hh;
  7496. }
  7497. for (k = 0; k < count; k++) {
  7498. struct br_style cs;
  7499. int node = (int)it[start + k].node;
  7500. int yoff = 0;
  7501. br_style_for(&doc, node, pst, &cs);
  7502. cs.width_kind = 0;
  7503. cs.max_width_kind = 0;
  7504. if (l->draw && pst->align_items &&
  7505. row_h > block_h[node]) {
  7506. if (pst->align_items == 1)
  7507. yoff = (row_h - block_h[node]) / 2;
  7508. else if (pst->align_items == 2)
  7509. yoff = row_h - block_h[node];
  7510. }
  7511. l->left = x;
  7512. l->right = x + it[start + k].w;
  7513. if (l->right < l->left + 8)
  7514. l->right = l->left + 8;
  7515. l->y = row_top + yoff;
  7516. l->line_x = l->left;
  7517. l->run_x = l->left;
  7518. l->line_y = l->y;
  7519. l->line_h = 0;
  7520. l->nruns = 0;
  7521. l->space_pending = 0;
  7522. l->align = cs.align;
  7523. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  7524. if (!l->draw) {
  7525. int h = l->y - row_top;
  7526. if (h > row_h)
  7527. row_h = h;
  7528. }
  7529. x += it[start + k].w;
  7530. if (k + 1 < count)
  7531. x += gap + extra;
  7532. }
  7533. row_top += row_h;
  7534. }
  7535. l->left = row_left;
  7536. l->right = row_right;
  7537. l->y = row_top;
  7538. l->line_x = l->left;
  7539. l->run_x = l->left;
  7540. l->line_y = l->y;
  7541. l->line_h = 0;
  7542. l->nruns = 0;
  7543. l->space_pending = 0;
  7544. }
  7545. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  7546. * plus the grid-area hints used by site shells (site notice/footer full
  7547. * width, column-start left, page-content right). Anything more elaborate
  7548. * falls back to normal block flow. */
  7549. static int grid_track_width(unsigned char kind, unsigned short val,
  7550. int avail, int other)
  7551. {
  7552. if (kind == 2)
  7553. return avail * (int)val / 100;
  7554. if (kind == 1)
  7555. return val;
  7556. return other;
  7557. }
  7558. static void layout_grid_children(struct lay *l, unsigned int parent,
  7559. const struct br_style *pst, int depth,
  7560. unsigned short link)
  7561. {
  7562. unsigned int n;
  7563. int row_left = l->left, row_right = l->right;
  7564. int avail = row_right - row_left;
  7565. int gap = pst->grid_gap;
  7566. int track_total = avail - gap;
  7567. int col0, col1, x0, x1;
  7568. int row_y, row_bottom, have_left = 0, have_right = 0;
  7569. unsigned int c;
  7570. if (avail < 32 || depth > 48)
  7571. return;
  7572. if (track_total < 16)
  7573. track_total = 16;
  7574. col0 = grid_track_width((unsigned char)(pst->width_kind),
  7575. pst->width, track_total, 0);
  7576. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  7577. pst->max_width, track_total, 0);
  7578. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  7579. int w0 = pst->width ? pst->width : 1;
  7580. int w1 = pst->max_width ? pst->max_width : 1;
  7581. col0 = track_total * w0 / (w0 + w1);
  7582. col1 = track_total - col0;
  7583. } else if (pst->width_kind == 3) {
  7584. col0 = track_total - col1;
  7585. if (col0 < 24)
  7586. col0 = 24;
  7587. } else if (pst->max_width_kind == 3) {
  7588. col1 = track_total - col0;
  7589. if (col1 < 24)
  7590. col1 = 24;
  7591. }
  7592. if (col0 < 24)
  7593. col0 = 24;
  7594. if (col1 < 24)
  7595. col1 = 24;
  7596. if (col0 + col1 > track_total) {
  7597. col1 = track_total - col0;
  7598. if (col1 < 24)
  7599. col1 = 24;
  7600. }
  7601. x0 = row_left;
  7602. x1 = row_left + col0 + gap;
  7603. /* Direct text makes a grid ambiguous; use block flow instead. */
  7604. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7605. struct br_node *nd = &doc.nodes[c];
  7606. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7607. layout_children(l, parent, pst, depth, link);
  7608. return;
  7609. }
  7610. }
  7611. row_y = row_bottom = l->y;
  7612. n = doc.nodes[parent].first;
  7613. while (n) {
  7614. struct br_node *nd = &doc.nodes[n];
  7615. struct br_style cs;
  7616. unsigned short lk = link;
  7617. int slot, x, w;
  7618. if (nd->type == BR_NODE_TEXT) {
  7619. n = nd->next;
  7620. continue;
  7621. }
  7622. br_style_for(&doc, n, pst, &cs);
  7623. if (cs.display == BR_DISPLAY_NONE) {
  7624. n = nd->next;
  7625. continue;
  7626. }
  7627. if (nd->tag == BR_TAG_A && nd->href_off)
  7628. lk = (unsigned short)n;
  7629. slot = cs.grid_slot;
  7630. if (!slot) {
  7631. if (!have_left)
  7632. slot = 2;
  7633. else if (!have_right)
  7634. slot = 3;
  7635. else
  7636. slot = 2;
  7637. }
  7638. if (slot == 1) {
  7639. if (have_left || have_right) {
  7640. row_y = row_bottom;
  7641. have_left = have_right = 0;
  7642. }
  7643. x = row_left;
  7644. w = avail;
  7645. } else if (slot == 2) {
  7646. if (have_left) {
  7647. row_y = row_bottom;
  7648. have_left = have_right = 0;
  7649. }
  7650. x = x0;
  7651. w = col0;
  7652. have_left = 1;
  7653. } else {
  7654. if (have_right) {
  7655. row_y = row_bottom;
  7656. have_left = have_right = 0;
  7657. }
  7658. x = x1;
  7659. w = col1;
  7660. have_right = 1;
  7661. }
  7662. cs.width_kind = 0;
  7663. cs.max_width_kind = 0;
  7664. l->left = x;
  7665. l->right = x + w;
  7666. if (l->right < l->left + 8)
  7667. l->right = l->left + 8;
  7668. l->y = row_y;
  7669. l->line_x = l->left;
  7670. l->run_x = l->left;
  7671. l->line_y = l->y;
  7672. l->line_h = 0;
  7673. l->nruns = 0;
  7674. l->space_pending = 0;
  7675. l->align = cs.align;
  7676. layout_block(l, n, &cs, depth + 1, lk);
  7677. if (l->y > row_bottom)
  7678. row_bottom = l->y;
  7679. n = nd->next;
  7680. }
  7681. l->left = row_left;
  7682. l->right = row_right;
  7683. l->y = row_bottom;
  7684. l->line_x = l->left;
  7685. l->run_x = l->left;
  7686. l->line_y = l->y;
  7687. l->line_h = 0;
  7688. l->nruns = 0;
  7689. l->space_pending = 0;
  7690. }
  7691. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  7692. * capped at four. Used by the project docs' card grids. */
  7693. static void layout_grid_auto(struct lay *l, unsigned int parent,
  7694. const struct br_style *pst, int depth,
  7695. unsigned short link)
  7696. {
  7697. unsigned int n, c;
  7698. int row_left = l->left, row_right = l->right;
  7699. int avail = row_right - row_left;
  7700. int gap = pst->grid_gap;
  7701. int minw = pst->width_kind == 1 ? pst->width : 200;
  7702. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  7703. if (avail < 32 || depth > 48) {
  7704. layout_children(l, parent, pst, depth, link);
  7705. return;
  7706. }
  7707. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7708. struct br_node *nd = &doc.nodes[c];
  7709. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7710. layout_children(l, parent, pst, depth, link);
  7711. return;
  7712. }
  7713. }
  7714. if (minw < 80)
  7715. minw = 80;
  7716. ncols = (avail + gap) / (minw + gap);
  7717. if (ncols < 1)
  7718. ncols = 1;
  7719. if (ncols > 4)
  7720. ncols = 4;
  7721. colw = (avail - gap * (ncols - 1)) / ncols;
  7722. if (colw < 24)
  7723. colw = 24;
  7724. x = row_left;
  7725. n = doc.nodes[parent].first;
  7726. while (n) {
  7727. struct br_node *nd = &doc.nodes[n];
  7728. struct br_style cs;
  7729. unsigned short lk = link;
  7730. int h;
  7731. if (nd->type == BR_NODE_TEXT) {
  7732. n = nd->next;
  7733. continue;
  7734. }
  7735. br_style_for(&doc, n, pst, &cs);
  7736. if (cs.display == BR_DISPLAY_NONE) {
  7737. n = nd->next;
  7738. continue;
  7739. }
  7740. if (nd->tag == BR_TAG_A && nd->href_off)
  7741. lk = (unsigned short)n;
  7742. cs.width_kind = 0;
  7743. cs.max_width_kind = 0;
  7744. l->left = x;
  7745. l->right = x + colw;
  7746. if (l->right < l->left + 8)
  7747. l->right = l->left + 8;
  7748. l->y = y;
  7749. l->line_x = l->left;
  7750. l->run_x = l->left;
  7751. l->line_y = l->y;
  7752. l->line_h = 0;
  7753. l->nruns = 0;
  7754. l->space_pending = 0;
  7755. l->align = cs.align;
  7756. layout_block(l, n, &cs, depth + 1, lk);
  7757. h = l->y - y;
  7758. if (h > row_h)
  7759. row_h = h;
  7760. col++;
  7761. n = nd->next;
  7762. if (col == ncols) {
  7763. y += row_h + gap;
  7764. x = row_left;
  7765. row_h = 0;
  7766. col = 0;
  7767. } else {
  7768. x += colw + gap;
  7769. }
  7770. }
  7771. if (col)
  7772. y += row_h;
  7773. else if (y > start_y)
  7774. y -= gap;
  7775. l->left = row_left;
  7776. l->right = row_right;
  7777. l->y = y;
  7778. l->line_x = l->left;
  7779. l->run_x = l->left;
  7780. l->line_y = l->y;
  7781. l->line_h = 0;
  7782. l->nruns = 0;
  7783. l->space_pending = 0;
  7784. }
  7785. /* Column widths are the widest cell in each column across every row, so all
  7786. * rows line up. The table model is still deliberately basic: no colspan,
  7787. * border-collapse or percentage columns. */
  7788. static void table_columns(struct lay *l, unsigned int table,
  7789. const struct br_style *pst, int avail,
  7790. int *raw, int maxcols, int *out_cols,
  7791. int *out_total)
  7792. {
  7793. unsigned int r, c;
  7794. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  7795. int fixed[12];
  7796. for (c = 0; c < (unsigned int)maxcols; c++) {
  7797. raw[c] = 0;
  7798. fixed[c] = 0;
  7799. }
  7800. /* Intrinsic widths of single-column cells. */
  7801. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7802. struct br_node *rn = &doc.nodes[r];
  7803. int col = 0;
  7804. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7805. continue;
  7806. for (c = rn->first; c; c = doc.nodes[c].next) {
  7807. struct br_node *cn = &doc.nodes[c];
  7808. struct br_style cs;
  7809. int w, span;
  7810. if (cn->type != BR_NODE_ELEM ||
  7811. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  7812. continue;
  7813. span = cn->colspan ? cn->colspan : 1;
  7814. br_style_for(&doc, c, pst, &cs);
  7815. if (cs.display == BR_DISPLAY_NONE)
  7816. continue;
  7817. if (col + span > maxcols)
  7818. span = maxcols - col;
  7819. if (span < 1)
  7820. break;
  7821. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  7822. mp_px(&cs, 7, avail) +
  7823. mp_px(&cs, 5, avail) +
  7824. mp_px(&cs, 3, avail) +
  7825. mp_px(&cs, 1, avail) +
  7826. cs.border_w[0] + cs.border_w[1] +
  7827. cs.border_w[2] + cs.border_w[3];
  7828. if (w < 24)
  7829. w = 24;
  7830. if (span == 1) {
  7831. if (w > raw[col])
  7832. raw[col] = w;
  7833. }
  7834. if (col + span > cols)
  7835. cols = col + span;
  7836. col += span;
  7837. }
  7838. }
  7839. /* A colspan cell only has to be as wide as the sum of its columns. */
  7840. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7841. struct br_node *rn = &doc.nodes[r];
  7842. int col = 0;
  7843. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7844. continue;
  7845. for (c = rn->first; c; c = doc.nodes[c].next) {
  7846. struct br_node *cn = &doc.nodes[c];
  7847. struct br_style cs;
  7848. int span, w, sum, i;
  7849. if (cn->type != BR_NODE_ELEM ||
  7850. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  7851. continue;
  7852. span = cn->colspan ? cn->colspan : 1;
  7853. if (col + span > maxcols)
  7854. span = maxcols - col;
  7855. if (span < 1)
  7856. break;
  7857. if (span > 1) {
  7858. br_style_for(&doc, c, pst, &cs);
  7859. if (cs.display != BR_DISPLAY_NONE) {
  7860. w = intrinsic_width(l->ui, c, &cs,
  7861. 0, avail) +
  7862. mp_px(&cs, 7, avail) +
  7863. mp_px(&cs, 5, avail) +
  7864. mp_px(&cs, 3, avail) +
  7865. mp_px(&cs, 1, avail) +
  7866. cs.border_w[0] + cs.border_w[1] +
  7867. cs.border_w[2] + cs.border_w[3];
  7868. sum = 0;
  7869. for (i = 0; i < span; i++)
  7870. sum += raw[col + i];
  7871. if (w > sum)
  7872. raw[col + span - 1] += w - sum;
  7873. }
  7874. }
  7875. col += span;
  7876. }
  7877. }
  7878. /* Explicit and percentage widths override intrinsic widths. */
  7879. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7880. struct br_node *rn = &doc.nodes[r];
  7881. int col = 0;
  7882. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7883. continue;
  7884. for (c = rn->first; c; c = doc.nodes[c].next) {
  7885. struct br_node *cn = &doc.nodes[c];
  7886. struct br_style cs;
  7887. int span;
  7888. if (cn->type != BR_NODE_ELEM ||
  7889. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  7890. continue;
  7891. span = cn->colspan ? cn->colspan : 1;
  7892. if (col + span > maxcols)
  7893. span = maxcols - col;
  7894. if (span < 1)
  7895. break;
  7896. if (span == 1) {
  7897. br_style_for(&doc, c, pst, &cs);
  7898. if (cs.display != BR_DISPLAY_NONE) {
  7899. if (cs.width_kind == 1) {
  7900. raw[col] = cs.width;
  7901. fixed[col] = 1;
  7902. } else if (cs.width_kind == 2 ||
  7903. cs.width_kind == 3) {
  7904. raw[col] = style_width_px(&cs,
  7905. avail);
  7906. fixed[col] = 1;
  7907. }
  7908. }
  7909. }
  7910. col += span;
  7911. }
  7912. }
  7913. for (c = 0; c < (unsigned int)cols; c++) {
  7914. if (raw[c] < 8)
  7915. raw[c] = 8;
  7916. total += raw[c];
  7917. if (fixed[c])
  7918. fixed_sum += raw[c];
  7919. else {
  7920. free_raw += raw[c];
  7921. free_cols++;
  7922. }
  7923. }
  7924. if (fixed_sum > 0 && fixed_sum < avail) {
  7925. int free_avail = avail - fixed_sum;
  7926. int i;
  7927. if (free_raw > 0) {
  7928. for (i = 0; i < cols; i++)
  7929. if (!fixed[i])
  7930. raw[i] = free_avail * raw[i] /
  7931. free_raw;
  7932. } else if (free_cols > 0) {
  7933. for (i = 0; i < cols; i++)
  7934. if (!fixed[i])
  7935. raw[i] = free_avail / free_cols;
  7936. }
  7937. total = 0;
  7938. for (i = 0; i < cols; i++)
  7939. total += raw[i];
  7940. } else if (total < avail && total > 0) {
  7941. int i;
  7942. for (i = 0; i < cols; i++)
  7943. raw[i] = raw[i] * avail / total;
  7944. total = 0;
  7945. for (i = 0; i < cols; i++)
  7946. total += raw[i];
  7947. }
  7948. *out_cols = cols;
  7949. *out_total = total;
  7950. }
  7951. static void layout_table_row(struct lay *l, unsigned int row,
  7952. const struct br_style *pst, int depth,
  7953. unsigned short link)
  7954. {
  7955. unsigned int n, cell[12];
  7956. int raw[12], colstart[12], colspan[12];
  7957. int prefix[13];
  7958. int ncell = 0, total = 0, cols = 0, col = 0;
  7959. int row_left = l->left, row_right = l->right;
  7960. int avail = row_right - row_left;
  7961. int y = l->y, bottom = l->y;
  7962. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  7963. struct br_node *nd = &doc.nodes[n];
  7964. struct br_style cs;
  7965. int span;
  7966. if (nd->type == BR_NODE_TEXT) {
  7967. if (text_node_blank(nd))
  7968. continue;
  7969. layout_children(l, row, pst, depth, link);
  7970. return;
  7971. }
  7972. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  7973. layout_children(l, row, pst, depth, link);
  7974. return;
  7975. }
  7976. br_style_for(&doc, n, pst, &cs);
  7977. if (cs.display == BR_DISPLAY_NONE)
  7978. continue;
  7979. if (ncell >= 12) {
  7980. layout_children(l, row, pst, depth, link);
  7981. return;
  7982. }
  7983. span = nd->colspan ? nd->colspan : 1;
  7984. if (span > 12 - col)
  7985. span = 12 - col;
  7986. if (span < 1)
  7987. continue;
  7988. cell[ncell] = n;
  7989. colstart[ncell] = col;
  7990. colspan[ncell] = span;
  7991. col += span;
  7992. ncell++;
  7993. }
  7994. if (ncell < 1 || avail < 32) {
  7995. layout_children(l, row, pst, depth, link);
  7996. return;
  7997. }
  7998. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  7999. &total);
  8000. if (cols < 2 || total <= 0) {
  8001. int c;
  8002. total = 0;
  8003. for (c = 0; c < ncell; c++) {
  8004. struct br_style cs;
  8005. br_style_for(&doc, cell[c], pst, &cs);
  8006. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  8007. avail) +
  8008. mp_px(&cs, 7, avail) +
  8009. mp_px(&cs, 5, avail) +
  8010. mp_px(&cs, 3, avail) +
  8011. mp_px(&cs, 1, avail);
  8012. if (raw[c] < 24)
  8013. raw[c] = 24;
  8014. total += raw[c];
  8015. }
  8016. /* A one-column table still has to fill its own width; the
  8017. * intrinsic fallback above otherwise leaves the cell at its
  8018. * text width (HN's outer table and nested story table). */
  8019. if (total > 0 && total < avail) {
  8020. int c;
  8021. for (c = 0; c < ncell; c++)
  8022. raw[c] = raw[c] * avail / total;
  8023. total = avail;
  8024. }
  8025. }
  8026. prefix[0] = row_left;
  8027. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  8028. prefix[n + 1] = prefix[n] + raw[n];
  8029. for (n = 0; n < (unsigned int)ncell; n++) {
  8030. struct br_style cs;
  8031. int start = colstart[n];
  8032. int end = start + colspan[n];
  8033. int w;
  8034. if (end > cols)
  8035. end = cols;
  8036. if (start >= cols)
  8037. continue;
  8038. w = prefix[end] - prefix[start];
  8039. br_style_for(&doc, cell[n], pst, &cs);
  8040. /* The column width already reflects the cell's width property. */
  8041. cs.width_kind = 0;
  8042. cs.max_width_kind = 0;
  8043. if (w < 24)
  8044. w = 24;
  8045. if (w < 8)
  8046. w = 8;
  8047. l->left = prefix[start];
  8048. l->right = l->left + w;
  8049. l->y = y;
  8050. l->line_x = l->left;
  8051. l->run_x = l->left;
  8052. l->line_y = l->y;
  8053. l->line_h = 0;
  8054. l->nruns = 0;
  8055. l->space_pending = 0;
  8056. l->align = cs.align;
  8057. layout_block(l, cell[n], &cs, depth + 1, link);
  8058. if (l->y > bottom)
  8059. bottom = l->y;
  8060. }
  8061. l->left = row_left;
  8062. l->right = row_right;
  8063. l->y = bottom;
  8064. l->line_x = l->left;
  8065. l->run_x = l->left;
  8066. l->line_y = l->y;
  8067. l->line_h = 0;
  8068. l->nruns = 0;
  8069. l->space_pending = 0;
  8070. }
  8071. #define TBL_MAX_ROWS 32
  8072. #define TBL_MAX_COLS 12
  8073. #define TBL_MAX_CELLS 128
  8074. struct tbl_cell {
  8075. unsigned int node;
  8076. unsigned char row, col, rowspan, colspan;
  8077. int height;
  8078. };
  8079. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  8080. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  8081. static int table_active;
  8082. static int table_has_rowspan(unsigned int table)
  8083. {
  8084. unsigned int r, c;
  8085. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  8086. struct br_node *rn = &doc.nodes[r];
  8087. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  8088. continue;
  8089. for (c = rn->first; c; c = doc.nodes[c].next) {
  8090. struct br_node *cn = &doc.nodes[c];
  8091. if (cn->type == BR_NODE_ELEM &&
  8092. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  8093. cn->rowspan > 1)
  8094. return 1;
  8095. }
  8096. }
  8097. return 0;
  8098. }
  8099. static void table_cell_style(unsigned int row, unsigned int cell,
  8100. const struct br_style *st, struct br_style *out)
  8101. {
  8102. struct br_style trs;
  8103. br_style_for(&doc, row, st, &trs);
  8104. br_style_for(&doc, cell, &trs, out);
  8105. }
  8106. /* Tables that use rowspan need row heights before anything is painted. This
  8107. * path builds a small occupancy grid, measures the natural cell heights, then
  8108. * lays every cell out at its row/column position. Tables without rowspan
  8109. * keep the lighter per-row path in layout_table_row(). */
  8110. static void layout_table(struct lay *l, unsigned int table,
  8111. const struct br_style *st, int depth,
  8112. unsigned short link)
  8113. {
  8114. unsigned int rows[TBL_MAX_ROWS];
  8115. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  8116. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  8117. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  8118. int free_raw = 0, free_cols = 0;
  8119. int table_left = l->left, table_right = l->right;
  8120. int top = l->y, avail = table_right - table_left;
  8121. unsigned int r, c;
  8122. int i, rr, cc;
  8123. if (depth > 48 || table_active) {
  8124. layout_children(l, table, st, depth, link);
  8125. return;
  8126. }
  8127. table_active = 1;
  8128. for (r = doc.nodes[table].first;
  8129. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  8130. struct br_node *rn = &doc.nodes[r];
  8131. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  8132. rows[nrows++] = r;
  8133. }
  8134. if (!nrows) {
  8135. table_active = 0;
  8136. layout_children(l, table, st, depth, link);
  8137. return;
  8138. }
  8139. for (rr = 0; rr < nrows; rr++)
  8140. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  8141. tbl_at[rr][cc] = 0;
  8142. for (rr = 0; rr < nrows; rr++) {
  8143. int col = 0;
  8144. for (c = doc.nodes[rows[rr]].first; c;
  8145. c = doc.nodes[c].next) {
  8146. struct br_node *cn = &doc.nodes[c];
  8147. struct br_style cs;
  8148. int rs, csn;
  8149. if (cn->type != BR_NODE_ELEM ||
  8150. (cn->tag != BR_TAG_TD &&
  8151. cn->tag != BR_TAG_TH))
  8152. continue;
  8153. table_cell_style(rows[rr], c, st, &cs);
  8154. if (cs.display == BR_DISPLAY_NONE)
  8155. continue;
  8156. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  8157. col++;
  8158. if (col >= TBL_MAX_COLS)
  8159. break;
  8160. rs = cn->rowspan ? cn->rowspan : 1;
  8161. csn = cn->colspan ? cn->colspan : 1;
  8162. if (rr + rs > nrows)
  8163. rs = nrows - rr;
  8164. if (col + csn > TBL_MAX_COLS)
  8165. csn = TBL_MAX_COLS - col;
  8166. if (rs < 1 || csn < 1)
  8167. continue;
  8168. if (ncells >= TBL_MAX_CELLS)
  8169. break;
  8170. tbl_cells[ncells].node = c;
  8171. tbl_cells[ncells].row = (unsigned char)rr;
  8172. tbl_cells[ncells].col = (unsigned char)col;
  8173. tbl_cells[ncells].rowspan = (unsigned char)rs;
  8174. tbl_cells[ncells].colspan = (unsigned char)csn;
  8175. tbl_cells[ncells].height = 0;
  8176. for (i = rr; i < rr + rs; i++)
  8177. for (int j = col; j < col + csn; j++)
  8178. tbl_at[i][j] =
  8179. (unsigned short)(ncells + 1);
  8180. ncells++;
  8181. col += csn;
  8182. if (col > cols)
  8183. cols = col;
  8184. }
  8185. }
  8186. if (!ncells || cols < 1) {
  8187. table_active = 0;
  8188. layout_children(l, table, st, depth, link);
  8189. return;
  8190. }
  8191. for (i = 0; i < cols; i++) {
  8192. raw[i] = 0;
  8193. fixed[i] = 0;
  8194. }
  8195. /* Intrinsic widths of single-column cells. */
  8196. for (i = 0; i < ncells; i++) {
  8197. struct br_style cs;
  8198. int w;
  8199. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8200. st, &cs);
  8201. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  8202. mp_px(&cs, 7, avail) +
  8203. mp_px(&cs, 5, avail) +
  8204. mp_px(&cs, 3, avail) +
  8205. mp_px(&cs, 1, avail) +
  8206. cs.border_w[0] + cs.border_w[1] +
  8207. cs.border_w[2] + cs.border_w[3];
  8208. if (w < 24)
  8209. w = 24;
  8210. if (tbl_cells[i].colspan == 1) {
  8211. int col = tbl_cells[i].col;
  8212. if (w > raw[col])
  8213. raw[col] = w;
  8214. }
  8215. }
  8216. /* A spanning cell only needs the sum of its columns to be large
  8217. * enough; put the deficit in the last column. */
  8218. for (i = 0; i < ncells; i++) {
  8219. struct br_style cs;
  8220. int w, sum, col, span;
  8221. if (tbl_cells[i].colspan < 2)
  8222. continue;
  8223. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8224. st, &cs);
  8225. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  8226. mp_px(&cs, 7, avail) +
  8227. mp_px(&cs, 5, avail) +
  8228. mp_px(&cs, 3, avail) +
  8229. mp_px(&cs, 1, avail) +
  8230. cs.border_w[0] + cs.border_w[1] +
  8231. cs.border_w[2] + cs.border_w[3];
  8232. col = tbl_cells[i].col;
  8233. span = tbl_cells[i].colspan;
  8234. sum = 0;
  8235. for (int j = 0; j < span; j++)
  8236. sum += raw[col + j];
  8237. if (w > sum)
  8238. raw[col + span - 1] += w - sum;
  8239. }
  8240. /* Explicit/percentage widths, as in table_columns(). */
  8241. for (i = 0; i < ncells; i++) {
  8242. struct br_style cs;
  8243. int col;
  8244. if (tbl_cells[i].colspan != 1)
  8245. continue;
  8246. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8247. st, &cs);
  8248. col = tbl_cells[i].col;
  8249. if (cs.width_kind == 1) {
  8250. raw[col] = cs.width;
  8251. fixed[col] = 1;
  8252. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  8253. raw[col] = style_width_px(&cs, avail);
  8254. fixed[col] = 1;
  8255. }
  8256. }
  8257. for (i = 0; i < cols; i++) {
  8258. if (raw[i] < 8)
  8259. raw[i] = 8;
  8260. total += raw[i];
  8261. if (fixed[i])
  8262. fixed_sum += raw[i];
  8263. else {
  8264. free_raw += raw[i];
  8265. free_cols++;
  8266. }
  8267. }
  8268. if (fixed_sum > 0 && fixed_sum < avail) {
  8269. int free_avail = avail - fixed_sum;
  8270. if (free_raw > 0) {
  8271. for (i = 0; i < cols; i++)
  8272. if (!fixed[i])
  8273. raw[i] = free_avail * raw[i] /
  8274. free_raw;
  8275. } else if (free_cols > 0) {
  8276. for (i = 0; i < cols; i++)
  8277. if (!fixed[i])
  8278. raw[i] = free_avail / free_cols;
  8279. }
  8280. } else if (total < avail && total > 0) {
  8281. for (i = 0; i < cols; i++)
  8282. raw[i] = raw[i] * avail / total;
  8283. }
  8284. prefix[0] = table_left;
  8285. for (i = 0; i < cols; i++)
  8286. prefix[i + 1] = prefix[i] + raw[i];
  8287. /* Measure natural cell heights with the column widths. */
  8288. for (i = 0; i < ncells; i++) {
  8289. struct br_style cs;
  8290. int col = tbl_cells[i].col;
  8291. int span = tbl_cells[i].colspan;
  8292. int w = prefix[col + span] - prefix[col];
  8293. int sl = l->left, sr = l->right, sy = l->y;
  8294. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  8295. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  8296. int sal = l->align, sdraw = l->draw;
  8297. struct ngui *sui = l->ui;
  8298. if (w < 8)
  8299. w = 8;
  8300. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8301. st, &cs);
  8302. cs.width_kind = 0;
  8303. cs.max_width_kind = 0;
  8304. l->draw = 0;
  8305. l->ui = 0;
  8306. l->left = prefix[col];
  8307. l->right = l->left + w;
  8308. l->y = 0;
  8309. l->line_x = l->left;
  8310. l->run_x = l->left;
  8311. l->line_y = 0;
  8312. l->line_h = 0;
  8313. l->nruns = 0;
  8314. l->space_pending = 0;
  8315. l->align = cs.align;
  8316. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  8317. tbl_cells[i].height = block_h[tbl_cells[i].node];
  8318. l->left = sl;
  8319. l->right = sr;
  8320. l->y = sy;
  8321. l->line_x = slx;
  8322. l->run_x = srx;
  8323. l->line_y = sly;
  8324. l->line_h = slh;
  8325. l->nruns = snr;
  8326. l->space_pending = ssp;
  8327. l->align = sal;
  8328. l->draw = sdraw;
  8329. l->ui = sui;
  8330. }
  8331. for (i = 0; i < nrows; i++)
  8332. rowh[i] = 0;
  8333. for (i = 0; i < ncells; i++) {
  8334. int row = tbl_cells[i].row;
  8335. if (tbl_cells[i].rowspan == 1) {
  8336. if (tbl_cells[i].height > rowh[row])
  8337. rowh[row] = tbl_cells[i].height;
  8338. }
  8339. }
  8340. for (i = 0; i < ncells; i++) {
  8341. int row = tbl_cells[i].row;
  8342. int span = tbl_cells[i].rowspan;
  8343. int sum = 0;
  8344. if (span < 2)
  8345. continue;
  8346. for (int j = 0; j < span; j++)
  8347. sum += rowh[row + j];
  8348. if (sum < tbl_cells[i].height)
  8349. rowh[row + span - 1] +=
  8350. tbl_cells[i].height - sum;
  8351. }
  8352. for (i = 0; i < nrows; i++)
  8353. if (rowh[i] < 8)
  8354. rowh[i] = 8;
  8355. rowy[0] = top;
  8356. for (i = 1; i < nrows; i++)
  8357. rowy[i] = rowy[i - 1] + rowh[i - 1];
  8358. if (!l->draw) {
  8359. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  8360. table_active = 0;
  8361. return;
  8362. }
  8363. for (i = 0; i < ncells; i++) {
  8364. struct br_style cs;
  8365. int col = tbl_cells[i].col;
  8366. int span = tbl_cells[i].colspan;
  8367. int row = tbl_cells[i].row;
  8368. int rspan = tbl_cells[i].rowspan;
  8369. int w = prefix[col + span] - prefix[col];
  8370. int h = 0;
  8371. int sl = l->left, sr = l->right, sy = l->y;
  8372. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  8373. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  8374. int sal = l->align;
  8375. int deco;
  8376. for (int j = 0; j < rspan; j++)
  8377. h += rowh[row + j];
  8378. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  8379. cs.width_kind = 0;
  8380. cs.max_width_kind = 0;
  8381. cs.box_sizing = 0;
  8382. deco = mp_px(&cs, 4, avail) +
  8383. mp_px(&cs, 6, avail) +
  8384. cs.border_w[0] + cs.border_w[2];
  8385. cs.height_kind = 1;
  8386. cs.height = h > deco ? h - deco : 0;
  8387. /* The block painter reads block_h[] from the measure pass; make
  8388. * the table cell fill its row/rowspan, not just its content. */
  8389. if (h > 0 && h < 65536)
  8390. block_h[tbl_cells[i].node] = (unsigned short)h;
  8391. l->left = prefix[col];
  8392. l->right = l->left + w;
  8393. l->y = rowy[row];
  8394. l->line_x = l->left;
  8395. l->run_x = l->left;
  8396. l->line_y = l->y;
  8397. l->line_h = 0;
  8398. l->nruns = 0;
  8399. l->space_pending = 0;
  8400. l->align = cs.align;
  8401. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  8402. l->left = sl;
  8403. l->right = sr;
  8404. l->y = sy;
  8405. l->line_x = slx;
  8406. l->run_x = srx;
  8407. l->line_y = sly;
  8408. l->line_h = slh;
  8409. l->nruns = snr;
  8410. l->space_pending = ssp;
  8411. l->align = sal;
  8412. }
  8413. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  8414. table_active = 0;
  8415. }
  8416. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  8417. * flow so they sit above it, like CSS painting order. Their flow origin is
  8418. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  8419. struct br_deferred {
  8420. unsigned int node;
  8421. int flow_y, flow_left, flow_right;
  8422. unsigned short link;
  8423. signed short z_index;
  8424. unsigned char z_set;
  8425. unsigned int order;
  8426. };
  8427. /* Positioned boxes painted after the flow. News front pages have one or two
  8428. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  8429. * old 16 entries the rest fell back into the flow, so a hero image landed
  8430. * below its padding-top aspect box instead of on top of it. */
  8431. #define BR_MAX_DEFERRED 256
  8432. static struct br_deferred deferred[BR_MAX_DEFERRED];
  8433. static int ndeferred;
  8434. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  8435. * element's line. A block-level pseudo-element gets its own line; its box
  8436. * (margins, padding, background) is not drawn. */
  8437. static void emit_pseudo(struct lay *l, unsigned int node,
  8438. const struct br_style *st, int pe, unsigned short link)
  8439. {
  8440. char buf[160];
  8441. struct br_style ps;
  8442. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  8443. unsigned int i = 0;
  8444. int block, space_w;
  8445. if (!n)
  8446. return;
  8447. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  8448. if (block)
  8449. flush_line(l);
  8450. if (ps.uppercase)
  8451. for (i = 0; i < n; i++)
  8452. if (buf[i] >= 'a' && buf[i] <= 'z')
  8453. buf[i] = (char)(buf[i] - 'a' + 'A');
  8454. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  8455. if (space_w <= 0)
  8456. space_w = 8;
  8457. i = 0;
  8458. while (i < n) {
  8459. char word[28];
  8460. unsigned int k = 0;
  8461. int w;
  8462. if (buf[i] == ' ') {
  8463. l->space_pending = 1;
  8464. i++;
  8465. continue;
  8466. }
  8467. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  8468. word[k++] = buf[i++];
  8469. word[k] = '\0';
  8470. if (l->space_pending &&
  8471. (l->nruns > 0 || l->line_x > l->line_left) &&
  8472. l->line_x + space_w <= l->line_right)
  8473. l->line_x += space_w;
  8474. l->space_pending = 0;
  8475. w = (int)face_text_width(l->ui, &ps, word, k);
  8476. if (l->line_x + w > l->line_right &&
  8477. (l->nruns > 0 || l->line_x > l->line_left))
  8478. flush_line(l);
  8479. add_run(l, 0, 0, &ps, link, word);
  8480. }
  8481. if (block)
  8482. flush_line(l);
  8483. }
  8484. static void layout_children(struct lay *l, unsigned int parent,
  8485. const struct br_style *pst, int depth,
  8486. unsigned short link)
  8487. {
  8488. unsigned int n;
  8489. if (depth > 48)
  8490. return;
  8491. emit_pseudo(l, parent, pst, 1, link);
  8492. n = doc.nodes[parent].first;
  8493. while (n) {
  8494. struct br_node *nd = &doc.nodes[n];
  8495. struct br_style cs;
  8496. unsigned short lk = link;
  8497. if (nd->type == BR_NODE_TEXT) {
  8498. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  8499. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  8500. n = nd->next;
  8501. continue;
  8502. }
  8503. br_style_for(&doc, n, pst, &cs);
  8504. if (cs.display == BR_DISPLAY_NONE) {
  8505. n = nd->next;
  8506. continue;
  8507. }
  8508. if (cs.clear && l->float_active) {
  8509. flush_line(l);
  8510. if (l->y < l->float_bottom)
  8511. l->y = l->float_bottom;
  8512. l->float_active = 0;
  8513. l->line_x = l->left;
  8514. l->run_x = l->left;
  8515. l->line_left = l->left;
  8516. l->line_right = l->right;
  8517. l->line_y = l->y;
  8518. l->line_h = 0;
  8519. l->nruns = 0;
  8520. l->space_pending = 0;
  8521. }
  8522. if (nd->tag == BR_TAG_A && nd->href_off)
  8523. lk = (unsigned short)n;
  8524. if (cs.pos == 1 || cs.pos == 2 ||
  8525. (cs.pos == 3 && cs.z_set)) {
  8526. if (cs.pos == 3 && l->draw &&
  8527. ndeferred < BR_MAX_DEFERRED) {
  8528. /* Relative z-index: measure and advance the flow
  8529. * without painting, then paint it in the
  8530. * deferred (stacked) pass. */
  8531. int fy = l->y, fl = l->left, fr = l->right;
  8532. int save_draw = l->draw;
  8533. l->draw = 0;
  8534. layout_block(l, n, &cs, depth + 1, lk);
  8535. l->draw = save_draw;
  8536. deferred[ndeferred].node = n;
  8537. deferred[ndeferred].flow_y = fy;
  8538. deferred[ndeferred].flow_left = fl;
  8539. deferred[ndeferred].flow_right = fr;
  8540. deferred[ndeferred].link = lk;
  8541. deferred[ndeferred].z_index = cs.z_index;
  8542. deferred[ndeferred].z_set = cs.z_set;
  8543. deferred[ndeferred].order = (unsigned int)ndeferred;
  8544. ndeferred++;
  8545. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  8546. deferred[ndeferred].node = n;
  8547. deferred[ndeferred].flow_y =
  8548. cs.pos == 1 ? l->cb_top : l->y;
  8549. deferred[ndeferred].flow_left =
  8550. cs.pos == 1 ? l->cb_left : l->left;
  8551. deferred[ndeferred].flow_right =
  8552. cs.pos == 1 ? l->cb_right : l->right;
  8553. deferred[ndeferred].link = lk;
  8554. deferred[ndeferred].z_index = cs.z_index;
  8555. deferred[ndeferred].z_set = cs.z_set;
  8556. deferred[ndeferred].order = (unsigned int)ndeferred;
  8557. ndeferred++;
  8558. } else if (l->draw && cs.pos == 1) {
  8559. /* Deferred list full: paint in place, but still
  8560. * against the containing block, not the flow. */
  8561. int fy = l->y, fl = l->left, fr = l->right;
  8562. l->y = l->cb_top;
  8563. l->left = l->cb_left;
  8564. l->right = l->cb_right;
  8565. layout_block(l, n, &cs, depth + 1, lk);
  8566. l->y = fy;
  8567. l->left = fl;
  8568. l->right = fr;
  8569. } else {
  8570. layout_block(l, n, &cs, depth + 1, lk);
  8571. }
  8572. if (cs.pos == 1 && block_h[n] &&
  8573. doc.nodes[n].class_off) {
  8574. const char *cl = doc.attrs +
  8575. doc.nodes[n].class_off;
  8576. if ((contains_ci(cl, "poster-wrapper") ||
  8577. contains_ci(cl, "ts-picture")) &&
  8578. !has_skeleton_sibling(n))
  8579. l->y += block_h[n];
  8580. }
  8581. n = nd->next;
  8582. continue;
  8583. }
  8584. if (nd->tag == BR_TAG_BR) {
  8585. flush_line(l);
  8586. n = nd->next;
  8587. continue;
  8588. }
  8589. if (nd->tag == BR_TAG_HR) {
  8590. flush_line(l);
  8591. if (l->draw)
  8592. ngui_fill_rect(l->ui,
  8593. (struct ngui_rect){l->left, l->y + 2,
  8594. l->right - l->left, 1}, BR_GRAY);
  8595. l->y += 8;
  8596. n = nd->next;
  8597. continue;
  8598. }
  8599. if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  8600. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) {
  8601. if (!(nd->tag == BR_TAG_INPUT &&
  8602. s_eq(br_type(&doc, n), "hidden"))) {
  8603. form_fill_line = pst->display ==
  8604. BR_DISPLAY_FLEX &&
  8605. pst->flex_col;
  8606. add_form_run(l, n, &cs, lk);
  8607. form_fill_line = 0;
  8608. }
  8609. n = nd->next;
  8610. continue;
  8611. }
  8612. if (nd->tag == BR_TAG_IMG) {
  8613. add_image_run(l, n, &cs, lk);
  8614. n = nd->next;
  8615. continue;
  8616. }
  8617. if (nd->tag == BR_TAG_VIDEO) {
  8618. layout_block(l, n, &cs, depth + 1, lk);
  8619. n = nd->next;
  8620. continue;
  8621. }
  8622. if (cs.float_left) {
  8623. n = layout_float_group(l, n, pst, depth, lk);
  8624. continue;
  8625. }
  8626. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8627. n = layout_inline_blocks(l, n, pst, depth, link);
  8628. continue;
  8629. }
  8630. /* A flex container is block-level like any block box even when
  8631. * the element is an inline tag such as <a> (a link card with
  8632. * display:flex is common on news sites). Without the block box
  8633. * its children were laid out in the parent flow with a 0x0 box
  8634. * of their own. */
  8635. /* inline-flex around inline content only ("| mehr" link
  8636. * tails, icon+label pills) stays in the text line. */
  8637. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  8638. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  8639. !flex_wants_row(n, &cs)) {
  8640. layout_children(l, n, &cs, depth + 1, lk);
  8641. } else if (cs.display == BR_DISPLAY_BLOCK ||
  8642. cs.display == BR_DISPLAY_FLEX ||
  8643. br_tag_is_block(nd->tag))
  8644. layout_block(l, n, &cs, depth + 1, lk);
  8645. else {
  8646. layout_children(l, n, &cs, depth + 1, lk);
  8647. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  8648. l->space_pending = 1;
  8649. }
  8650. n = nd->next;
  8651. }
  8652. emit_pseudo(l, parent, pst, 2, link);
  8653. }
  8654. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  8655. * runs and a recursive page can otherwise overflow the stack. */
  8656. static struct lay layout_state;
  8657. static int measure_page(int left, int right)
  8658. {
  8659. struct lay *l = &layout_state;
  8660. struct br_style base = base_style();
  8661. unsigned int i;
  8662. for (i = 0; i < BR_MAX_NODES; i++) {
  8663. block_h[i] = 0;
  8664. img_top[i] = 0;
  8665. block_top[i] = 0;
  8666. img_h[i] = 0;
  8667. layout_boxes[i].valid = 0;
  8668. }
  8669. memset(li_marker, 0, sizeof(li_marker));
  8670. l->draw = 0;
  8671. l->ui = &ui;
  8672. l->left = left;
  8673. l->right = right;
  8674. l->y = 0;
  8675. l->line_x = left;
  8676. l->run_x = left;
  8677. l->line_left = left;
  8678. l->line_right = right;
  8679. l->line_y = 0;
  8680. l->line_h = 0;
  8681. l->align = BR_ALIGN_LEFT;
  8682. l->float_active = 0;
  8683. l->parent_top = 0;
  8684. l->cb_left = left;
  8685. l->cb_right = right;
  8686. l->cb_top = 0;
  8687. l->depth = 0;
  8688. l->nruns = 0;
  8689. l->space_pending = 0;
  8690. layout_children(l, doc.root, &base, 0, 0);
  8691. return l->y + 8;
  8692. }
  8693. static int deferred_cmp(const struct br_deferred *a,
  8694. const struct br_deferred *b)
  8695. {
  8696. int az = a->z_set ? a->z_index : 0;
  8697. int bz = b->z_set ? b->z_index : 0;
  8698. if (az != bz)
  8699. return az < bz ? -1 : 1;
  8700. if (a->order != b->order)
  8701. return a->order < b->order ? -1 : 1;
  8702. return 0;
  8703. }
  8704. static void sort_deferred(void)
  8705. {
  8706. int i;
  8707. for (i = 1; i < ndeferred; i++) {
  8708. struct br_deferred key = deferred[i];
  8709. int j = i;
  8710. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  8711. deferred[j] = deferred[j - 1];
  8712. j--;
  8713. }
  8714. deferred[j] = key;
  8715. }
  8716. }
  8717. static void render_page(int left, int right, int y0)
  8718. {
  8719. struct lay *l = &layout_state;
  8720. struct br_style base = base_style();
  8721. l->draw = 1;
  8722. l->ui = &ui;
  8723. l->left = left;
  8724. l->right = right;
  8725. l->y = y0;
  8726. l->line_x = left;
  8727. l->run_x = left;
  8728. l->line_left = left;
  8729. l->line_right = right;
  8730. l->line_y = y0;
  8731. l->line_h = 0;
  8732. l->align = BR_ALIGN_LEFT;
  8733. l->float_active = 0;
  8734. l->parent_top = 0;
  8735. l->cb_left = left;
  8736. l->cb_right = right;
  8737. l->cb_top = y0;
  8738. l->depth = 0;
  8739. l->nruns = 0;
  8740. l->space_pending = 0;
  8741. nhits = 0;
  8742. ndeferred = 0;
  8743. layout_children(l, doc.root, &base, 0, 0);
  8744. sort_deferred();
  8745. {
  8746. int i;
  8747. for (i = 0; i < ndeferred; i++) {
  8748. struct br_style st;
  8749. br_style_for(&doc, deferred[i].node, &base, &st);
  8750. if (st.display == BR_DISPLAY_NONE)
  8751. continue;
  8752. l->draw = 1;
  8753. l->left = deferred[i].flow_left;
  8754. l->right = deferred[i].flow_right;
  8755. l->y = deferred[i].flow_y;
  8756. l->line_x = l->left;
  8757. l->run_x = l->left;
  8758. l->line_y = l->y;
  8759. l->line_h = 0;
  8760. l->nruns = 0;
  8761. l->space_pending = 0;
  8762. l->align = st.align;
  8763. if (st.pos == 2 && block_h[deferred[i].node]) {
  8764. struct ngui_rect clip;
  8765. int ch = block_h[deferred[i].node] + 24;
  8766. clip.x = page_rect.x;
  8767. clip.y = page_rect.y;
  8768. clip.w = page_rect.w - 12;
  8769. if (ch > page_rect.h)
  8770. ch = page_rect.h;
  8771. clip.h = ch;
  8772. ngui_push_clip(&ui, clip);
  8773. if (st.has_bg)
  8774. ngui_fill_rect(&ui, clip, st.bg);
  8775. layout_block(l, deferred[i].node, &st, 0,
  8776. deferred[i].link);
  8777. ngui_pop_clip(&ui);
  8778. } else {
  8779. layout_block(l, deferred[i].node, &st, 0,
  8780. deferred[i].link);
  8781. }
  8782. }
  8783. }
  8784. }
  8785. /* ---- UI ---- */
  8786. static int find_hit(int x, int y)
  8787. {
  8788. int i;
  8789. for (i = nhits - 1; i >= 0; i--) {
  8790. struct hit *h = &hits[i];
  8791. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  8792. y < h->y + h->h)
  8793. return (int)h->node;
  8794. }
  8795. return 0;
  8796. }
  8797. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  8798. {
  8799. int x = r.x + 4, y = r.y + 4, h = 22;
  8800. int compact = r.w < 560;
  8801. int go_w = r.w < 420 ? 32 : 42;
  8802. int in_x, in_w, res;
  8803. ngui_fill_rect(&ui, r, ui.theme.panel);
  8804. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  8805. ui.theme.border);
  8806. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  8807. NGUI_ICON_CHEVRON_LEFT))
  8808. *action |= ACT_BACK;
  8809. x += 32;
  8810. if (!compact) {
  8811. if (ngui_icon_button(&ui, ID_FORWARD,
  8812. (struct ngui_rect){x, y, 28, h},
  8813. NGUI_ICON_CHEVRON_RIGHT))
  8814. *action |= ACT_FORWARD;
  8815. x += 32;
  8816. }
  8817. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  8818. NGUI_ICON_REFRESH))
  8819. *action |= ACT_RELOAD;
  8820. x += 32;
  8821. if (!compact) {
  8822. if (ngui_icon_button(&ui, ID_HOME,
  8823. (struct ngui_rect){x, y, 28, h},
  8824. NGUI_ICON_HOME))
  8825. *action |= ACT_HOME;
  8826. x += 32;
  8827. }
  8828. in_x = x + 2;
  8829. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  8830. if (in_w < 60)
  8831. in_w = 60;
  8832. res = ngui_text_input(&ui, ID_URL,
  8833. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  8834. if (res & NGUI_INPUT_SUBMIT)
  8835. *action |= ACT_NAV;
  8836. if (res & NGUI_INPUT_CANCEL)
  8837. ngui_set_focus(&ui, 0);
  8838. if (ngui_button(&ui, ID_GO,
  8839. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  8840. "Go"))
  8841. *action |= ACT_NAV;
  8842. }
  8843. static int page_hover_node(void)
  8844. {
  8845. if (!ui.inside)
  8846. return 0;
  8847. if (ui.mouse_x < page_rect.x ||
  8848. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  8849. ui.mouse_y < page_rect.y ||
  8850. ui.mouse_y >= page_rect.y + page_rect.h)
  8851. return 0;
  8852. return find_hit(ui.mouse_x, ui.mouse_y);
  8853. }
  8854. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  8855. {
  8856. int x, y, w = page.w, h = page.h;
  8857. if (!src || w <= 0 || h <= 0)
  8858. return;
  8859. for (y = 0; y < h; y++) {
  8860. unsigned short *s = src + (page.y + y) * sw + page.x;
  8861. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  8862. for (x = 0; x + 1 < w; x += 2) {
  8863. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  8864. }
  8865. if (x < w)
  8866. d[x] = s[x];
  8867. }
  8868. }
  8869. static void draw_page(struct ngui_rect page)
  8870. {
  8871. int left, right, ch;
  8872. int old_panel, old_dim;
  8873. unsigned short *saved_px;
  8874. unsigned short page_bg = ui.theme.bg;
  8875. int saved_w, saved_h, use_buf;
  8876. page_rect = page;
  8877. {
  8878. unsigned int root = doc.nnode > 1 ?
  8879. br_find_tag(&doc, BR_TAG_HTML) : 0;
  8880. unsigned int body = doc.nnode > 1 ?
  8881. br_find_tag(&doc, BR_TAG_BODY) : 0;
  8882. struct br_style bs;
  8883. if (root) {
  8884. style_for_node(root - 1, &bs);
  8885. if (bs.has_bg)
  8886. page_bg = bs.bg;
  8887. }
  8888. if (body) {
  8889. style_for_node(body - 1, &bs);
  8890. if (bs.has_bg)
  8891. page_bg = bs.bg;
  8892. }
  8893. }
  8894. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  8895. page_cache_valid && layout_valid &&
  8896. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  8897. !(ui.scroll_y &&
  8898. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  8899. page_scroll.offset == page_cache_scroll &&
  8900. page_cache_nnode == doc.nnode &&
  8901. page_cache_x == page.x && page_cache_y == page.y &&
  8902. page_cache_w == page.w && page_cache_h == page.h) {
  8903. blit_page(page, page_backbuf, pagebuf_w);
  8904. return;
  8905. }
  8906. ngui_fill_rect(&ui, page, page_bg);
  8907. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  8908. const char *s = page_loading ? "Loading..." : "No page";
  8909. int w = (int)ngui_text_width_ui(&ui, s);
  8910. ngui_text(&ui, page.x + (page.w - w) / 2,
  8911. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  8912. page_scroll.content_h = 0;
  8913. page_scroll.view_h = page.h;
  8914. page_cache_valid = 0;
  8915. return;
  8916. }
  8917. if (page.w < 40 || page.h < 40) {
  8918. page_cache_valid = 0;
  8919. return;
  8920. }
  8921. saved_px = ui.px;
  8922. saved_w = ui.w;
  8923. saved_h = ui.h;
  8924. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  8925. if (use_buf) {
  8926. ui.px = page_backbuf;
  8927. ui.w = pagebuf_w;
  8928. ui.h = pagebuf_h;
  8929. ngui_fill_rect(&ui, page, page_bg);
  8930. }
  8931. left = page.x + 8;
  8932. right = page.x + page.w - 16;
  8933. if (!layout_valid || left != layout_left || right != layout_right ||
  8934. layout_nnode != doc.nnode) {
  8935. layout_content_h = measure_page(left, right);
  8936. layout_valid = 1;
  8937. layout_left = left;
  8938. layout_right = right;
  8939. layout_nnode = doc.nnode;
  8940. }
  8941. ch = layout_content_h;
  8942. page_scroll.content_h = ch;
  8943. page_scroll.view_h = page.h;
  8944. ngui_scroll_begin(&ui, page, &page_scroll);
  8945. ngui_scroll_wheel(&ui, page, &page_scroll);
  8946. render_page(left, right, page.y + 4 - page_scroll.offset);
  8947. old_panel = ui.theme.panel_alt;
  8948. old_dim = ui.theme.text_dim;
  8949. ui.theme.panel_alt = 0xC618;
  8950. ui.theme.text_dim = 0x8410;
  8951. ngui_scroll_end(&ui, page, &page_scroll);
  8952. ui.theme.panel_alt = old_panel;
  8953. ui.theme.text_dim = old_dim;
  8954. if (use_buf) {
  8955. ui.px = saved_px;
  8956. ui.w = saved_w;
  8957. ui.h = saved_h;
  8958. blit_page(page, page_backbuf, pagebuf_w);
  8959. page_cache_valid = 1;
  8960. page_cache_scroll = page_scroll.offset;
  8961. page_cache_nnode = doc.nnode;
  8962. page_cache_x = page.x;
  8963. page_cache_y = page.y;
  8964. page_cache_w = page.w;
  8965. page_cache_h = page.h;
  8966. } else {
  8967. page_cache_valid = 0;
  8968. }
  8969. }
  8970. static void draw_status(struct ngui_rect r)
  8971. {
  8972. char msg[BR_URL_MAX + 32];
  8973. unsigned int n = 0;
  8974. int hover = page_hover_node();
  8975. unsigned short color;
  8976. const char *kind;
  8977. ngui_fill_rect(&ui, r, ui.theme.panel);
  8978. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  8979. ui.theme.border);
  8980. if (hover) {
  8981. const char *href = br_href(&doc, (unsigned int)hover);
  8982. char url[BR_URL_MAX];
  8983. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  8984. s_append(msg, &n, "Link: ", sizeof(msg));
  8985. s_append(msg, &n, url, sizeof(msg));
  8986. } else {
  8987. s_copy(msg, "Link", sizeof(msg));
  8988. }
  8989. color = ui.theme.accent;
  8990. } else if (status_text[0]) {
  8991. s_copy(msg, status_text, sizeof(msg));
  8992. color = status_error ? ui.theme.error : ui.theme.text;
  8993. } else if (page_title[0]) {
  8994. s_copy(msg, page_title, sizeof(msg));
  8995. color = ui.theme.text;
  8996. } else {
  8997. s_copy(msg, "Ready", sizeof(msg));
  8998. color = ui.theme.text_dim;
  8999. }
  9000. kind = s_eq(page_url, "about:home") ? "HOME" :
  9001. page_is_local ? "FILE" :
  9002. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  9003. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  9004. {
  9005. int kw = (int)ngui_text_width_ui(&ui, kind);
  9006. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  9007. ui.theme.text_dim);
  9008. }
  9009. }
  9010. static void draw(unsigned int *action)
  9011. {
  9012. struct ngui_rect r = {0, 0, ui.w, ui.h};
  9013. struct ngui_rect toolbar, status, page;
  9014. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  9015. status = ngui_cut_bottom(&r, BR_STATUS_H);
  9016. page = r;
  9017. draw_toolbar(toolbar, action);
  9018. draw_page(page);
  9019. draw_status(status);
  9020. }
  9021. static void redraw_now(void)
  9022. {
  9023. unsigned int action = 0;
  9024. ngui_begin(&ui);
  9025. draw(&action);
  9026. ngui_end(&ui);
  9027. }
  9028. static void handle_keys(unsigned int *action)
  9029. {
  9030. int k, scrolled = 0;
  9031. if (form_focus >= doc.nnode)
  9032. form_focus = 0;
  9033. if (form_focus && !ngui_focus(&ui)) {
  9034. while ((k = ngui_key(&ui)) != 0)
  9035. form_key(k);
  9036. return;
  9037. }
  9038. /* Batch queued page keys: a slow full-page render must not make a
  9039. * held Page Down advance only once every few frames. */
  9040. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  9041. scrolled++;
  9042. if (scrolled)
  9043. ngui_invalidate(&ui);
  9044. if (ngui_focus(&ui))
  9045. return;
  9046. while ((k = ngui_key(&ui)) != 0) {
  9047. switch (k) {
  9048. case NGUI_KEY_ESC:
  9049. *action |= ACT_CLOSE;
  9050. break;
  9051. case NGUI_KEY_TAB:
  9052. case 0x0C: /* Ctrl+L */
  9053. ngui_set_focus(&ui, ID_URL);
  9054. break;
  9055. case 0x12: /* Ctrl+R */
  9056. *action |= ACT_RELOAD;
  9057. break;
  9058. case NGUI_KEY_BACKSPACE:
  9059. *action |= ACT_BACK;
  9060. break;
  9061. case NGUI_KEY_UP:
  9062. ngui_scroll_to(&page_scroll,
  9063. page_scroll.offset - 24);
  9064. ngui_invalidate(&ui);
  9065. break;
  9066. case NGUI_KEY_DOWN:
  9067. ngui_scroll_to(&page_scroll,
  9068. page_scroll.offset + 24);
  9069. ngui_invalidate(&ui);
  9070. break;
  9071. case NGUI_KEY_HOME:
  9072. ngui_scroll_to(&page_scroll, 0);
  9073. ngui_invalidate(&ui);
  9074. break;
  9075. case NGUI_KEY_END:
  9076. ngui_scroll_to(&page_scroll,
  9077. page_scroll.content_h -
  9078. page_scroll.view_h);
  9079. ngui_invalidate(&ui);
  9080. break;
  9081. default:
  9082. break;
  9083. }
  9084. }
  9085. }
  9086. static unsigned int form_ancestor(unsigned int node)
  9087. {
  9088. unsigned int p = node;
  9089. while (p && p < doc.nnode) {
  9090. if (doc.nodes[p].tag == BR_TAG_FORM &&
  9091. doc.nodes[p].type == BR_NODE_ELEM)
  9092. return p;
  9093. p = doc.nodes[p].parent;
  9094. }
  9095. return 0;
  9096. }
  9097. static int form_descendant(unsigned int node, unsigned int form)
  9098. {
  9099. unsigned int p = node;
  9100. while (p && p < doc.nnode) {
  9101. if (p == form)
  9102. return 1;
  9103. p = doc.nodes[p].parent;
  9104. }
  9105. return 0;
  9106. }
  9107. static void form_reset_form(unsigned int form)
  9108. {
  9109. unsigned int i;
  9110. for (i = 0; i < FORM_MAX; i++)
  9111. if (form_states[i].used &&
  9112. form_descendant(form_states[i].node, form))
  9113. form_states[i].used = 0;
  9114. form_focus = 0;
  9115. }
  9116. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  9117. const char *s)
  9118. {
  9119. static const char hex[] = "0123456789ABCDEF";
  9120. while (s && *s && *n + 1 < cap) {
  9121. unsigned char c = (unsigned char)*s++;
  9122. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  9123. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  9124. c == '.' || c == '~') {
  9125. dst[(*n)++] = (char)c;
  9126. } else if (c == ' ') {
  9127. dst[(*n)++] = '+';
  9128. } else if (*n + 3 < cap) {
  9129. dst[(*n)++] = '%';
  9130. dst[(*n)++] = hex[c >> 4];
  9131. dst[(*n)++] = hex[c & 15];
  9132. }
  9133. }
  9134. dst[*n] = '\0';
  9135. }
  9136. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  9137. const char *name, const char *value, int *first)
  9138. {
  9139. if (!name || !name[0])
  9140. return;
  9141. if (!*first && *n + 1 < cap)
  9142. dst[(*n)++] = '&';
  9143. *first = 0;
  9144. form_url_append(dst, n, cap, name);
  9145. if (*n + 1 < cap)
  9146. dst[(*n)++] = '=';
  9147. form_url_append(dst, n, cap, value ? value : "");
  9148. dst[*n] = '\0';
  9149. }
  9150. static int form_submit_form(unsigned int node, int fire_event)
  9151. {
  9152. unsigned int form = form_ancestor(node);
  9153. char action[BR_URL_MAX], query[2048];
  9154. unsigned int qn = 0, i;
  9155. int first = 1, is_post = 0;
  9156. const char *a, *method;
  9157. if (!form)
  9158. return 0;
  9159. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  9160. return 0;
  9161. method = br_find_attr(&doc, form, "method");
  9162. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  9163. is_post = 1;
  9164. a = br_find_attr(&doc, form, "action");
  9165. if (a && a[0]) {
  9166. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  9167. return 0;
  9168. } else {
  9169. s_copy(action, page_url, sizeof(action));
  9170. }
  9171. query[0] = '\0';
  9172. for (i = 0; i < doc.nnode; i++) {
  9173. struct br_node *nd = &doc.nodes[i];
  9174. struct form_state *fs;
  9175. const char *name;
  9176. const char *value = "";
  9177. if (nd->type != BR_NODE_ELEM || i == form ||
  9178. !form_descendant(i, form))
  9179. continue;
  9180. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  9181. nd->tag != BR_TAG_SELECT)
  9182. continue;
  9183. if (form_disabled(i))
  9184. continue;
  9185. name = br_find_attr(&doc, i, "name");
  9186. if (!name || !name[0])
  9187. continue;
  9188. fs = form_get(i, 1);
  9189. if (!fs)
  9190. continue;
  9191. if (nd->tag == BR_TAG_SELECT) {
  9192. char opt[64];
  9193. if (!form_option_text(i, fs->selected, opt,
  9194. sizeof(opt)))
  9195. s_copy(opt, "", sizeof(opt));
  9196. value = opt;
  9197. {
  9198. unsigned int c, oi = 0;
  9199. for (c = nd->first; c;
  9200. c = doc.nodes[c].next) {
  9201. if (doc.nodes[c].type != BR_NODE_ELEM ||
  9202. doc.nodes[c].tag != BR_TAG_OPTION)
  9203. continue;
  9204. if (oi == fs->selected) {
  9205. const char *v =
  9206. br_value(&doc, c);
  9207. if (v && v[0])
  9208. value = v;
  9209. break;
  9210. }
  9211. oi++;
  9212. }
  9213. }
  9214. } else if (nd->tag == BR_TAG_INPUT) {
  9215. int kind = form_kind_of(i);
  9216. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  9217. if (!fs->checked)
  9218. continue;
  9219. value = br_value(&doc, i);
  9220. if (!value || !value[0])
  9221. value = "on";
  9222. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  9223. kind == FORM_BUTTON) {
  9224. if (i != node)
  9225. continue;
  9226. value = fs->value;
  9227. } else {
  9228. value = fs->value;
  9229. }
  9230. } else {
  9231. value = fs->value;
  9232. }
  9233. form_add_param(query, &qn, sizeof(query), name, value, &first);
  9234. }
  9235. if (is_post) {
  9236. if (action[0] == '/') {
  9237. set_status("POST forms need an HTTP action URL", 1, 4000);
  9238. ngui_invalidate(&ui);
  9239. return 0;
  9240. }
  9241. if (qn >= sizeof(pending_post))
  9242. qn = sizeof(pending_post) - 1;
  9243. if (qn)
  9244. memcpy(pending_post, query, qn);
  9245. pending_post[qn] = '\0';
  9246. pending_post_len = qn;
  9247. pending_post_is = 1;
  9248. } else {
  9249. pending_post_len = 0;
  9250. pending_post_is = 0;
  9251. if (qn) {
  9252. unsigned int an = s_len(action);
  9253. if (an + qn + 2 < sizeof(action)) {
  9254. action[an++] = strchr(action, '?') ? '&' : '?';
  9255. action[an] = '\0';
  9256. s_copy(action + an, query,
  9257. sizeof(action) - an);
  9258. }
  9259. }
  9260. }
  9261. s_copy(pending_url, action, sizeof(pending_url));
  9262. pending_action |= ACT_NAV;
  9263. cancel_fetch = 1;
  9264. ngui_invalidate(&ui);
  9265. return 1;
  9266. }
  9267. static void form_reset_event(unsigned int form)
  9268. {
  9269. if (form && !js_browser_event(form, "reset", 1, 1))
  9270. return;
  9271. if (form)
  9272. form_reset_form(form);
  9273. else
  9274. form_reset_state();
  9275. form_dirty = 0;
  9276. layout_valid = 0;
  9277. ngui_invalidate(&ui);
  9278. }
  9279. static void form_blur(void)
  9280. {
  9281. unsigned int node = form_focus;
  9282. form_focus = 0;
  9283. if (node && form_dirty) {
  9284. form_dirty = 0;
  9285. js_browser_event(node, "change", 1, 0);
  9286. }
  9287. }
  9288. static void form_click(unsigned int node)
  9289. {
  9290. struct form_state *fs;
  9291. int kind, changed = 0;
  9292. if (!form_is_control(node) || form_disabled(node))
  9293. return;
  9294. if (form_focus != node)
  9295. form_blur();
  9296. if (!js_browser_event(node, "click", 1, 1))
  9297. return;
  9298. fs = form_get(node, 1);
  9299. if (!fs)
  9300. return;
  9301. kind = form_kind_of(node);
  9302. form_focus = node;
  9303. form_dirty = 0;
  9304. if (kind == FORM_CHECKBOX) {
  9305. fs->checked = !fs->checked;
  9306. changed = 1;
  9307. } else if (kind == FORM_RADIO) {
  9308. const char *name = br_find_attr(&doc, node, "name");
  9309. unsigned int i;
  9310. fs->checked = 1;
  9311. changed = 1;
  9312. if (name) {
  9313. for (i = 0; i < FORM_MAX; i++) {
  9314. struct form_state *o = &form_states[i];
  9315. if (!o->used || o->node == node)
  9316. continue;
  9317. if (form_kind_of(o->node) == FORM_RADIO) {
  9318. const char *on = br_find_attr(&doc,
  9319. o->node,
  9320. "name");
  9321. if (on && s_eq(on, name))
  9322. o->checked = 0;
  9323. }
  9324. }
  9325. }
  9326. } else if (kind == FORM_SELECT) {
  9327. unsigned int n = form_option_count(node);
  9328. if (n) {
  9329. fs->selected = (unsigned char)
  9330. ((fs->selected + 1) % n);
  9331. changed = 1;
  9332. }
  9333. } else if (kind == FORM_SUBMIT) {
  9334. form_submit_form(node, 1);
  9335. return;
  9336. } else if (kind == FORM_RESET) {
  9337. form_reset_event(form_ancestor(node));
  9338. return;
  9339. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  9340. kind == FORM_TEXTAREA) {
  9341. fs->caret = fs->len;
  9342. }
  9343. if (changed) {
  9344. js_browser_event(node, "input", 1, 0);
  9345. js_browser_event(node, "change", 1, 0);
  9346. }
  9347. layout_valid = 0;
  9348. ngui_invalidate(&ui);
  9349. }
  9350. static void form_focus_next(void)
  9351. {
  9352. unsigned int start = form_focus ? form_focus + 1 : 0;
  9353. unsigned int i;
  9354. form_blur();
  9355. for (i = start; i < doc.nnode; i++) {
  9356. if (form_is_control(i) && !form_disabled(i) &&
  9357. !s_eq(br_type(&doc, i), "hidden")) {
  9358. form_focus = i;
  9359. layout_valid = 0;
  9360. ngui_invalidate(&ui);
  9361. return;
  9362. }
  9363. }
  9364. form_focus = 0;
  9365. layout_valid = 0;
  9366. ngui_invalidate(&ui);
  9367. }
  9368. static void form_key(int k)
  9369. {
  9370. struct form_state *fs;
  9371. int kind;
  9372. if (!form_focus || form_focus >= doc.nnode) {
  9373. form_focus = 0;
  9374. return;
  9375. }
  9376. fs = form_get(form_focus, 1);
  9377. if (!fs || form_disabled(form_focus))
  9378. return;
  9379. kind = form_kind_of(form_focus);
  9380. if (kind == FORM_SELECT) {
  9381. unsigned int n = form_option_count(form_focus);
  9382. int changed = 0;
  9383. if (k == NGUI_KEY_UP && n) {
  9384. fs->selected = (unsigned char)
  9385. ((fs->selected + n - 1) % n);
  9386. changed = 1;
  9387. } else if (k == NGUI_KEY_DOWN && n) {
  9388. fs->selected = (unsigned char)
  9389. ((fs->selected + 1) % n);
  9390. changed = 1;
  9391. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  9392. form_blur();
  9393. layout_valid = 0;
  9394. ngui_invalidate(&ui);
  9395. return;
  9396. } else {
  9397. return;
  9398. }
  9399. if (changed) {
  9400. js_browser_event(form_focus, "input", 1, 0);
  9401. js_browser_event(form_focus, "change", 1, 0);
  9402. }
  9403. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  9404. if (k == ' ') {
  9405. form_click(form_focus);
  9406. return;
  9407. }
  9408. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  9409. form_blur();
  9410. layout_valid = 0;
  9411. ngui_invalidate(&ui);
  9412. }
  9413. return;
  9414. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  9415. kind == FORM_RESET) {
  9416. if (k == NGUI_KEY_ESC) {
  9417. form_blur();
  9418. layout_valid = 0;
  9419. ngui_invalidate(&ui);
  9420. } else if (k == '\r' || k == '\n' || k == ' ') {
  9421. form_click(form_focus);
  9422. }
  9423. return;
  9424. } else if (k == NGUI_KEY_TAB) {
  9425. form_focus_next();
  9426. return;
  9427. } else if (k == NGUI_KEY_ESC) {
  9428. form_blur();
  9429. layout_valid = 0;
  9430. ngui_invalidate(&ui);
  9431. return;
  9432. } else if (k == '\r' || k == '\n') {
  9433. unsigned int node = form_focus;
  9434. form_blur();
  9435. if (form_ancestor(node))
  9436. form_submit_form(node, 1);
  9437. layout_valid = 0;
  9438. ngui_invalidate(&ui);
  9439. return;
  9440. } else if (k == NGUI_KEY_BACKSPACE) {
  9441. if (fs->caret) {
  9442. unsigned int i = --fs->caret;
  9443. for (; i < fs->len; i++)
  9444. fs->value[i] = fs->value[i + 1];
  9445. if (fs->len)
  9446. fs->len--;
  9447. form_dirty = 1;
  9448. js_browser_event(form_focus, "input", 1, 0);
  9449. }
  9450. } else if (k == NGUI_KEY_DELETE) {
  9451. if (fs->caret < fs->len) {
  9452. unsigned int i;
  9453. for (i = fs->caret; i < fs->len; i++)
  9454. fs->value[i] = fs->value[i + 1];
  9455. fs->len--;
  9456. form_dirty = 1;
  9457. js_browser_event(form_focus, "input", 1, 0);
  9458. }
  9459. } else if (k == NGUI_KEY_LEFT) {
  9460. if (fs->caret)
  9461. fs->caret--;
  9462. } else if (k == NGUI_KEY_RIGHT) {
  9463. if (fs->caret < fs->len)
  9464. fs->caret++;
  9465. } else if (k == NGUI_KEY_HOME) {
  9466. fs->caret = 0;
  9467. } else if (k == NGUI_KEY_END) {
  9468. fs->caret = fs->len;
  9469. } else if (k >= 32 && k < 127) {
  9470. if (fs->len < FORM_VALUE_MAX) {
  9471. unsigned int i;
  9472. for (i = fs->len; i > fs->caret; i--)
  9473. fs->value[i] = fs->value[i - 1];
  9474. fs->value[fs->caret++] = (char)k;
  9475. fs->len++;
  9476. form_dirty = 1;
  9477. js_browser_event(form_focus, "input", 1, 0);
  9478. }
  9479. } else {
  9480. return;
  9481. }
  9482. fs->value[fs->len] = '\0';
  9483. layout_valid = 0;
  9484. ngui_invalidate(&ui);
  9485. }
  9486. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  9487. * a same-document navigation: update the URL and fire hashchange. Returns
  9488. * 1 when handled. */
  9489. static int link_fragment_nav(unsigned int node)
  9490. {
  9491. const char *href = br_href(&doc, node);
  9492. char url[BR_URL_MAX];
  9493. unsigned int n = 0;
  9494. if (!href || !href[0] || !js_browser_active())
  9495. return 0;
  9496. if (href[0] == '#') {
  9497. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  9498. url[n] = page_url[n];
  9499. n++;
  9500. }
  9501. url[n] = '\0';
  9502. s_append(url, &n, href, sizeof(url));
  9503. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  9504. return 0;
  9505. }
  9506. if (!same_doc_fragment(url))
  9507. return href[0] == '#';
  9508. page_set_fragment(url, 1);
  9509. js_browser_hashchange();
  9510. return 1;
  9511. }
  9512. /* The innermost laid-out box under a screen point: the smallest valid box
  9513. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  9514. * Used to deliver clicks to elements that are neither links nor controls
  9515. * (a Vue <div role="button">, a card with a click listener). */
  9516. static unsigned int find_box_hit(int x, int y)
  9517. {
  9518. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  9519. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  9520. const struct br_layout_box *b = &layout_boxes[i];
  9521. unsigned int area;
  9522. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  9523. x < b->x || y < b->y || x >= b->x + b->w ||
  9524. y >= b->y + b->h)
  9525. continue;
  9526. area = (unsigned int)b->w * (unsigned int)b->h;
  9527. if (area <= best_area) {
  9528. best = i;
  9529. best_area = area;
  9530. }
  9531. }
  9532. return best;
  9533. }
  9534. static void handle_page_click(unsigned int *action)
  9535. {
  9536. int node;
  9537. char url[BR_URL_MAX];
  9538. if (!ui.pressed)
  9539. return;
  9540. if (ui.press_x < page_rect.x ||
  9541. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  9542. ui.press_y < page_rect.y ||
  9543. ui.press_y >= page_rect.y + page_rect.h)
  9544. return;
  9545. node = find_hit(ui.press_x, ui.press_y);
  9546. if (!node) {
  9547. unsigned int box;
  9548. if (!js_browser_active())
  9549. return;
  9550. box = find_box_hit(ui.press_x, ui.press_y);
  9551. if (box) {
  9552. form_blur();
  9553. js_browser_event(box, "click", 1, 1);
  9554. }
  9555. return;
  9556. }
  9557. if (form_is_control((unsigned int)node)) {
  9558. form_click((unsigned int)node);
  9559. return;
  9560. }
  9561. form_blur();
  9562. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  9563. return;
  9564. if (link_fragment_nav((unsigned int)node))
  9565. return;
  9566. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  9567. sizeof(url)) != 0)
  9568. return;
  9569. s_copy(click_url, url, sizeof(click_url));
  9570. *action |= ACT_NAV;
  9571. }
  9572. void _start(const char *arg)
  9573. {
  9574. struct win_info wi;
  9575. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  9576. u_win_create(960, 640, "Browser", &wi) != 0 &&
  9577. u_win_create(780, 540, "Browser", &wi) != 0) {
  9578. u_puts("browser: no graphics window\n");
  9579. u_exit(1);
  9580. }
  9581. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  9582. url_in.placeholder = "http://...";
  9583. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  9584. ui.theme.accent);
  9585. br_set_viewport(wi.width);
  9586. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  9587. s_copy(cwd, "/", sizeof(cwd));
  9588. heap_clear();
  9589. origin_cache_load();
  9590. css_cache_init();
  9591. script_cache_init();
  9592. persist_restore();
  9593. page_scroll.offset = 0;
  9594. page_scroll.content_h = 0;
  9595. if (arg && arg[0]) {
  9596. navigate(arg, 1);
  9597. } else {
  9598. load_home(1);
  9599. /* Start ready to type: keep the home page, but leave the address
  9600. * bar empty instead of showing "about:home". */
  9601. ngui_input_set(&url_in, "");
  9602. ngui_set_focus(&ui, ID_URL);
  9603. }
  9604. for (;;) {
  9605. unsigned int action = 0;
  9606. unsigned int now;
  9607. click_url[0] = '\0';
  9608. if (pending_action) {
  9609. action |= pending_action & ACT_WAIT_NAV;
  9610. if (pending_url[0])
  9611. s_copy(click_url, pending_url, sizeof(click_url));
  9612. pending_action = 0;
  9613. pending_url[0] = '\0';
  9614. cancel_fetch = 0;
  9615. } else if (preload_active) {
  9616. if (preload_wait)
  9617. preload_wait = 0;
  9618. else
  9619. preload_step();
  9620. } else if ((preload_pending &&
  9621. page_scroll.offset != preload_scroll) ||
  9622. (preload_rescan && layout_valid)) {
  9623. preload_scroll = page_scroll.offset;
  9624. preload_rescan = 0;
  9625. preload_pending = 0;
  9626. preload_node = 0;
  9627. preload_active = 1;
  9628. }
  9629. js_browser_tick();
  9630. persist_tick();
  9631. if (pending_action)
  9632. continue;
  9633. now = u_ticks_ms();
  9634. if (status_until && (int)(now - status_until) >= 0) {
  9635. status_text[0] = '\0';
  9636. status_until = 0;
  9637. status_error = 0;
  9638. ngui_invalidate(&ui);
  9639. }
  9640. if (!ngui_begin(&ui)) {
  9641. /* A queued navigation (e.g. Enter in the URL bar during
  9642. * a slow fetch) must be handled even when this frame
  9643. * needs no redraw. */
  9644. if (!action) {
  9645. fetch_workers_stop_if_unfocused();
  9646. u_sleep_ms(10);
  9647. continue;
  9648. }
  9649. } else {
  9650. draw(&action);
  9651. handle_keys(&action);
  9652. handle_page_click(&action);
  9653. ngui_end(&ui);
  9654. }
  9655. if (action & ACT_NAV) {
  9656. if (click_url[0]) {
  9657. navigate(click_url, 1);
  9658. click_url[0] = '\0';
  9659. } else {
  9660. navigate(url_in.text, 1);
  9661. }
  9662. }
  9663. if (action & ACT_BACK) {
  9664. if (hist_pos > 0) {
  9665. hist_pos--;
  9666. if (same_doc_fragment(history[hist_pos])) {
  9667. page_set_fragment(history[hist_pos], 0);
  9668. js_browser_hashchange();
  9669. } else {
  9670. navigate(history[hist_pos], 0);
  9671. }
  9672. }
  9673. }
  9674. if (action & ACT_FORWARD) {
  9675. if (hist_pos + 1 < hist_len) {
  9676. hist_pos++;
  9677. if (same_doc_fragment(history[hist_pos])) {
  9678. page_set_fragment(history[hist_pos], 0);
  9679. js_browser_hashchange();
  9680. } else {
  9681. navigate(history[hist_pos], 0);
  9682. }
  9683. }
  9684. }
  9685. if (action & ACT_RELOAD) {
  9686. if (s_eq(page_url, "about:home"))
  9687. load_home(0);
  9688. else
  9689. navigate(page_url, 0);
  9690. }
  9691. if (action & ACT_HOME)
  9692. load_home(1);
  9693. if (action & ACT_CLOSE)
  9694. quit = 1;
  9695. if (quit)
  9696. break;
  9697. if (pending_action)
  9698. continue;
  9699. fetch_workers_stop_if_unfocused();
  9700. u_sleep_ms(10);
  9701. }
  9702. fetch_workers_stop_all();
  9703. u_win_close();
  9704. u_exit(0);
  9705. }