browser.c 267 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443
  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 void form_reset_event(unsigned int form);
  228. static unsigned int s_len(const char *s);
  229. static int s_eq(const char *a, const char *b);
  230. static void form_key(int k);
  231. static void form_click(unsigned int node);
  232. static void style_for_node(unsigned int node, struct br_style *out);
  233. static int form_disabled(unsigned int node)
  234. {
  235. struct br_node *n = &doc.nodes[node];
  236. if (n->attr_flags & BR_ATTR_DISABLED)
  237. return 1;
  238. return br_find_attr(&doc, node, "disabled") != 0;
  239. }
  240. static int form_kind_of(unsigned int node)
  241. {
  242. const char *type = br_type(&doc, node);
  243. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  244. return FORM_TEXTAREA;
  245. if (doc.nodes[node].tag == BR_TAG_SELECT)
  246. return FORM_SELECT;
  247. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  248. if (s_eq(type, "reset"))
  249. return FORM_RESET;
  250. if (s_eq(type, "button"))
  251. return FORM_BUTTON;
  252. return FORM_SUBMIT;
  253. }
  254. if (s_eq(type, "password"))
  255. return FORM_PASSWORD;
  256. if (s_eq(type, "checkbox"))
  257. return FORM_CHECKBOX;
  258. if (s_eq(type, "radio"))
  259. return FORM_RADIO;
  260. if (s_eq(type, "submit"))
  261. return FORM_SUBMIT;
  262. if (s_eq(type, "reset"))
  263. return FORM_RESET;
  264. if (s_eq(type, "button"))
  265. return FORM_BUTTON;
  266. return FORM_TEXT;
  267. }
  268. static unsigned int form_option_count(unsigned int node)
  269. {
  270. unsigned int c, n = 0;
  271. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  272. if (doc.nodes[c].type == BR_NODE_ELEM &&
  273. doc.nodes[c].tag == BR_TAG_OPTION)
  274. n++;
  275. return n;
  276. }
  277. static unsigned int form_option_selected(unsigned int node)
  278. {
  279. unsigned int c, i = 0;
  280. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  281. if (doc.nodes[c].type != BR_NODE_ELEM ||
  282. doc.nodes[c].tag != BR_TAG_OPTION)
  283. continue;
  284. if (br_find_attr(&doc, c, "selected"))
  285. return i;
  286. i++;
  287. }
  288. return 0;
  289. }
  290. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  291. char *out, unsigned int cap)
  292. {
  293. unsigned int c, i = 0;
  294. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  295. if (doc.nodes[c].type != BR_NODE_ELEM ||
  296. doc.nodes[c].tag != BR_TAG_OPTION)
  297. continue;
  298. if (i == idx)
  299. return br_text_content(&doc, c, out, cap);
  300. i++;
  301. }
  302. return 0;
  303. }
  304. static struct form_state *form_get(unsigned int node, int create)
  305. {
  306. struct form_state *slot = 0;
  307. unsigned int i;
  308. for (i = 0; i < FORM_MAX; i++) {
  309. if (form_states[i].used) {
  310. if (form_states[i].node == node)
  311. return &form_states[i];
  312. } else if (!slot) {
  313. slot = &form_states[i];
  314. }
  315. }
  316. if (!create || !slot)
  317. return 0;
  318. slot->node = node;
  319. slot->len = 0;
  320. slot->caret = 0;
  321. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  322. slot->selected = form_option_selected(node);
  323. slot->used = 1;
  324. {
  325. unsigned int n = 0;
  326. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  327. n = br_text_content(&doc, node, slot->value,
  328. FORM_VALUE_MAX + 1);
  329. } else {
  330. const char *v = br_value(&doc, node);
  331. if (v) {
  332. n = s_len(v);
  333. if (n > FORM_VALUE_MAX)
  334. n = FORM_VALUE_MAX;
  335. for (unsigned int j = 0; j < n; j++)
  336. slot->value[j] = v[j];
  337. }
  338. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  339. n = br_text_content(&doc, node, slot->value,
  340. FORM_VALUE_MAX + 1);
  341. }
  342. if (n > FORM_VALUE_MAX)
  343. n = FORM_VALUE_MAX;
  344. slot->value[n] = '\0';
  345. slot->len = (unsigned char)n;
  346. slot->caret = (unsigned char)n;
  347. }
  348. return slot;
  349. }
  350. static void form_reset_state(void)
  351. {
  352. unsigned int i;
  353. for (i = 0; i < FORM_MAX; i++)
  354. form_states[i].used = 0;
  355. form_focus = 0;
  356. }
  357. static int form_is_control(unsigned int node)
  358. {
  359. unsigned int tag;
  360. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  361. return 0;
  362. tag = doc.nodes[node].tag;
  363. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  364. tag == BR_TAG_SELECT || tag == BR_TAG_BUTTON;
  365. }
  366. #define HIT_MAX 96
  367. static struct hit hits[HIT_MAX];
  368. static int nhits;
  369. static unsigned short block_h[BR_MAX_NODES];
  370. /* Measure-pass top of each block, in the same document coordinates as
  371. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  372. * paint, so it cannot drive the lazy background loader). */
  373. static unsigned short block_top[BR_MAX_NODES];
  374. static char li_marker[BR_MAX_NODES][12];
  375. /* one connection object; the browser fetches one resource at a time */
  376. /* ---- tiny strings ---- */
  377. static unsigned int s_len(const char *s)
  378. {
  379. unsigned int n = 0;
  380. while (s && s[n])
  381. n++;
  382. return n;
  383. }
  384. static void s_copy(char *d, const char *s, unsigned int cap)
  385. {
  386. unsigned int i = 0;
  387. if (!cap)
  388. return;
  389. while (s && s[i] && i + 1 < cap) {
  390. d[i] = s[i];
  391. i++;
  392. }
  393. d[i] = '\0';
  394. }
  395. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  396. {
  397. while (s && *s && *n + 1 < cap)
  398. d[(*n)++] = *s++;
  399. d[*n] = '\0';
  400. }
  401. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  402. unsigned int cap)
  403. {
  404. char tmp[12];
  405. unsigned int i = 0, j;
  406. do {
  407. tmp[i++] = (char)('0' + v % 10);
  408. v /= 10;
  409. } while (v && i < sizeof(tmp));
  410. for (j = 0; j < i && *n + 1 < cap; j++)
  411. d[(*n)++] = tmp[i - 1 - j];
  412. d[*n] = '\0';
  413. }
  414. static int s_eq(const char *a, const char *b)
  415. {
  416. while (*a && *b) {
  417. if (*a != *b)
  418. return 0;
  419. a++;
  420. b++;
  421. }
  422. return *a == *b;
  423. }
  424. static int starts_with(const char *s, const char *p)
  425. {
  426. unsigned int i = 0;
  427. while (p[i]) {
  428. if (s[i] != p[i])
  429. return 0;
  430. i++;
  431. }
  432. return 1;
  433. }
  434. static int contains_ci(const char *s, const char *p)
  435. {
  436. unsigned int i, j;
  437. for (i = 0; s[i]; i++) {
  438. for (j = 0; p[j]; j++) {
  439. char a = s[i + j];
  440. if (a >= 'A' && a <= 'Z')
  441. a = (char)(a - 'A' + 'a');
  442. if (a != p[j])
  443. break;
  444. }
  445. if (!p[j])
  446. return 1;
  447. }
  448. return 0;
  449. }
  450. static char *trim(char *s)
  451. {
  452. unsigned int n;
  453. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  454. s++;
  455. n = s_len(s);
  456. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  457. s[n - 1] == '\r' || s[n - 1] == '\n'))
  458. s[--n] = '\0';
  459. return s;
  460. }
  461. /* ---- per-process heap ---- */
  462. static int heap_start(void)
  463. {
  464. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  465. if (!image_io_buf)
  466. return -1;
  467. page_backbuf = (unsigned short *)malloc(
  468. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  469. pagebuf_w = page_backbuf ? ui.w : 0;
  470. pagebuf_h = page_backbuf ? ui.h : 0;
  471. page_cache_valid = 0;
  472. return 0;
  473. }
  474. static void heap_clear(void)
  475. {
  476. memset(font_faces, 0, sizeof(font_faces));
  477. ngui_font_detach(&ui);
  478. svg_cache_clear();
  479. decode_arena = 0; /* lives in the page heap too */
  480. decode_arena_size = 0;
  481. heap_reset();
  482. /* The document arenas live in that heap; drop the stale pointers so
  483. * the next br_parse_plain() allocates fresh ones. */
  484. doc.nodes = 0;
  485. doc.text = 0;
  486. doc.attrs = 0;
  487. image_io_buf = 0;
  488. page_backbuf = 0;
  489. pagebuf_w = pagebuf_h = 0;
  490. page_cache_valid = 0;
  491. }
  492. static void browser_rules_alloc(void)
  493. {
  494. struct br_rule *rules;
  495. rules = (struct br_rule *)malloc(
  496. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  497. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  498. }
  499. /* ---- status ---- */
  500. static void set_status(const char *s, int err, unsigned int ttl_ms)
  501. {
  502. s_copy(status_text, s, sizeof(status_text));
  503. status_error = err;
  504. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  505. ngui_invalidate(&ui);
  506. }
  507. /* ---- JavaScript ---- */
  508. static int resolve_link(const char *base, const char *href, char *out,
  509. unsigned int cap);
  510. static char js_last_status[BR_STATUS_MAX];
  511. static int js_last_error;
  512. static void js_host_status(const char *msg, int error)
  513. {
  514. s_copy(js_last_status, msg, sizeof(js_last_status));
  515. js_last_error = error;
  516. set_status(msg, error, 6000);
  517. }
  518. static void js_host_report(const char *msg)
  519. {
  520. u_puts("[js] ");
  521. u_puts(msg);
  522. u_putc('\n');
  523. s_copy(js_last_status, msg, sizeof(js_last_status));
  524. js_last_error = 1;
  525. set_status(msg, 1, 8000);
  526. }
  527. static void js_host_navigate(const char *url)
  528. {
  529. char resolved[BR_URL_MAX];
  530. if (!url || !url[0])
  531. return;
  532. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  533. return;
  534. s_copy(pending_url, resolved, sizeof(pending_url));
  535. pending_action |= ACT_NAV;
  536. cancel_fetch = 1;
  537. }
  538. static void js_host_changed(void)
  539. {
  540. /* Class/style/attribute mutations change computed styles, not just the
  541. * text: drop the per-node style cache before the next layout. */
  542. br_reset_styles(&doc);
  543. layout_valid = 0;
  544. /* Script-built content (Angular's ng-repeat cards) brings new images
  545. * and inline background styles: rescan once the main loop is idle. */
  546. preload_rescan = 1;
  547. ngui_invalidate(&ui);
  548. }
  549. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  550. {
  551. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  552. return 0;
  553. *x = layout_boxes[node].x - page_rect.x;
  554. *y = layout_boxes[node].y - page_rect.y;
  555. *w = layout_boxes[node].w;
  556. *h = layout_boxes[node].h;
  557. return 1;
  558. }
  559. static void form_copy_out(const char *s, char *buf, int cap)
  560. {
  561. int i = 0;
  562. if (!buf || cap <= 0)
  563. return;
  564. while (s && s[i] && i + 1 < cap) {
  565. buf[i] = s[i];
  566. i++;
  567. }
  568. buf[i] = '\0';
  569. }
  570. static int js_host_form_value(unsigned int node, char *buf, int cap)
  571. {
  572. struct form_state *fs;
  573. int kind;
  574. if (!form_is_control(node))
  575. return 0;
  576. kind = form_kind_of(node);
  577. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  578. return 0;
  579. if (kind == FORM_SELECT) {
  580. char opt[64] = "";
  581. unsigned int c, i = 0;
  582. fs = form_get(node, 1);
  583. if (!fs)
  584. return 0;
  585. form_option_text(node, fs->selected, opt, sizeof(opt));
  586. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  587. if (doc.nodes[c].type != BR_NODE_ELEM ||
  588. doc.nodes[c].tag != BR_TAG_OPTION)
  589. continue;
  590. if (i == fs->selected) {
  591. const char *v = br_value(&doc, c);
  592. if (v && v[0])
  593. form_copy_out(v, buf, cap);
  594. else
  595. form_copy_out(opt, buf, cap);
  596. return 1;
  597. }
  598. i++;
  599. }
  600. form_copy_out(opt, buf, cap);
  601. return 1;
  602. }
  603. fs = form_get(node, 1);
  604. if (!fs)
  605. return 0;
  606. form_copy_out(fs->value, buf, cap);
  607. return 1;
  608. }
  609. static int js_host_form_checked(unsigned int node)
  610. {
  611. struct form_state *fs;
  612. int kind;
  613. if (!form_is_control(node))
  614. return -1;
  615. kind = form_kind_of(node);
  616. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  617. return -1;
  618. fs = form_get(node, 1);
  619. return fs ? fs->checked : 0;
  620. }
  621. static int js_host_form_selected(unsigned int node)
  622. {
  623. struct form_state *fs;
  624. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  625. return -1;
  626. fs = form_get(node, 1);
  627. return fs ? fs->selected : 0;
  628. }
  629. static int js_host_form_set_value(unsigned int node, const char *value)
  630. {
  631. struct form_state *fs;
  632. unsigned int n;
  633. if (!form_is_control(node))
  634. return 0;
  635. fs = form_get(node, 1);
  636. if (!fs)
  637. return 0;
  638. n = s_len(value ? value : "");
  639. if (n > FORM_VALUE_MAX)
  640. n = FORM_VALUE_MAX;
  641. for (unsigned int i = 0; i < n; i++)
  642. fs->value[i] = value[i];
  643. fs->value[n] = '\0';
  644. fs->len = (unsigned char)n;
  645. fs->caret = (unsigned char)n;
  646. layout_valid = 0;
  647. ngui_invalidate(&ui);
  648. return 1;
  649. }
  650. static int js_host_form_set_checked(unsigned int node, int checked)
  651. {
  652. struct form_state *fs;
  653. int kind;
  654. if (!form_is_control(node))
  655. return 0;
  656. kind = form_kind_of(node);
  657. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  658. return 0;
  659. fs = form_get(node, 1);
  660. if (!fs)
  661. return 0;
  662. fs->checked = (unsigned char)(checked != 0);
  663. layout_valid = 0;
  664. ngui_invalidate(&ui);
  665. return 1;
  666. }
  667. static int js_host_form_set_selected(unsigned int node, int index)
  668. {
  669. struct form_state *fs;
  670. unsigned int n;
  671. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  672. return 0;
  673. fs = form_get(node, 1);
  674. if (!fs)
  675. return 0;
  676. n = form_option_count(node);
  677. if (index < 0)
  678. index = 0;
  679. if (n && (unsigned int)index >= n)
  680. index = (int)n - 1;
  681. fs->selected = (unsigned char)index;
  682. layout_valid = 0;
  683. ngui_invalidate(&ui);
  684. return 1;
  685. }
  686. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  687. {
  688. unsigned int i;
  689. int n = 0;
  690. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  691. doc.nodes[form].tag != BR_TAG_FORM)
  692. return 0;
  693. for (i = 0; i < doc.nnode && n < cap; i++) {
  694. struct br_node *nd = &doc.nodes[i];
  695. if (i == form || nd->type != BR_NODE_ELEM)
  696. continue;
  697. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  698. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  699. continue;
  700. if (!form_descendant(i, form))
  701. continue;
  702. out[n++] = i;
  703. }
  704. return n;
  705. }
  706. static int js_host_form_submit(unsigned int form)
  707. {
  708. form_submit_form(form, 0);
  709. return 1;
  710. }
  711. static int js_host_form_reset(unsigned int form)
  712. {
  713. form_reset_event(form);
  714. return 1;
  715. }
  716. static void css_computed_name(const char *p, char *out, int cap)
  717. {
  718. int n = 0;
  719. for (; p && *p && n + 2 < cap; p++) {
  720. char c = *p;
  721. if (c >= 'A' && c <= 'Z') {
  722. out[n++] = '-';
  723. c = (char)(c - 'A' + 'a');
  724. } else if (c == '_') {
  725. c = '-';
  726. } else if (c >= 'a' && c <= 'z') {
  727. /* keep */
  728. }
  729. out[n++] = c;
  730. }
  731. out[n] = '\0';
  732. if (!strcmp(out, "css-float"))
  733. strcpy(out, "float");
  734. }
  735. static void css_rgb(unsigned short c, char *buf, int cap)
  736. {
  737. int r = ((c >> 11) & 31) * 255 / 31;
  738. int g = ((c >> 5) & 63) * 255 / 63;
  739. int b = (c & 31) * 255 / 31;
  740. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  741. }
  742. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  743. int font_px)
  744. {
  745. if (unit == 4) {
  746. snprintf(buf, cap, "auto");
  747. } else if (unit == 0) {
  748. snprintf(buf, cap, "%dpx", raw);
  749. } else if (unit == 1) {
  750. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  751. } else if (unit == 2) {
  752. /* Chrome's getComputedStyle() reports used pixel values. */
  753. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  754. } else if (unit == 3) {
  755. snprintf(buf, cap, "%dpx",
  756. (int)br_root_font_px() * raw / 100);
  757. } else {
  758. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  759. raw / 100, raw % 100, px);
  760. }
  761. }
  762. static int js_host_computed(unsigned int node, const char *property,
  763. char *buf, int cap)
  764. {
  765. struct br_style st;
  766. char name[40];
  767. if (!buf || cap <= 0 || node >= doc.nnode || node == 0)
  768. return 0;
  769. buf[0] = '\0';
  770. css_computed_name(property, name, sizeof(name));
  771. style_for_node(node, &st);
  772. if (!strcmp(name, "display")) {
  773. const char *v = "inline";
  774. if (st.display == BR_DISPLAY_BLOCK)
  775. v = "block";
  776. else if (st.display == BR_DISPLAY_NONE)
  777. v = "none";
  778. else if (st.display == BR_DISPLAY_FLEX)
  779. v = "flex";
  780. else if (st.display == BR_DISPLAY_GRID)
  781. v = "grid";
  782. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  783. v = "inline-block";
  784. snprintf(buf, cap, "%s", v);
  785. } else if (!strcmp(name, "position")) {
  786. static const char *pos[] = {
  787. "static", "absolute", "fixed", "relative", "sticky"
  788. };
  789. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  790. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  791. int is_w = name[0] == 'w';
  792. int kind = is_w ? st.width_kind : st.height_kind;
  793. int val = is_w ? st.width : st.height;
  794. if (kind == 3) {
  795. if (is_w)
  796. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  797. st.width_calc_pct / 100,
  798. st.width_calc_pct % 100,
  799. st.width_calc_px);
  800. else
  801. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  802. st.height_calc_pct / 100,
  803. st.height_calc_pct % 100,
  804. st.height_calc_px);
  805. } else if (kind == 1) {
  806. snprintf(buf, cap, "%dpx", val);
  807. } else if (kind == 2) {
  808. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  809. } else {
  810. snprintf(buf, cap, "auto");
  811. }
  812. } else if (!strcmp(name, "color") ||
  813. !strcmp(name, "background-color")) {
  814. if (!strcmp(name, "background-color") && !st.has_bg)
  815. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  816. else
  817. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  818. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  819. int is_fill = name[0] == 'f';
  820. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  821. if (mode == BR_PAINT_COLOR)
  822. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  823. else if (mode == BR_PAINT_CURRENT)
  824. css_rgb(st.color, buf, cap);
  825. else if (mode == BR_PAINT_UNSET && is_fill)
  826. snprintf(buf, cap, "rgb(0, 0, 0)");
  827. else if (mode == BR_PAINT_URL)
  828. snprintf(buf, cap, "url()");
  829. else
  830. snprintf(buf, cap, "none");
  831. } else if (!strcmp(name, "font-size")) {
  832. snprintf(buf, cap, "%dpx", st.font_px);
  833. } else if (!strcmp(name, "font-weight")) {
  834. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  835. } else if (!strcmp(name, "font-style")) {
  836. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  837. } else if (!strcmp(name, "font-family")) {
  838. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  839. br_font_face_family(st.font_face)[0])
  840. snprintf(buf, cap, "%s",
  841. br_font_face_family(st.font_face));
  842. else
  843. snprintf(buf, cap, "%s",
  844. st.mono ? "monospace" : "sans-serif");
  845. } else if (!strcmp(name, "text-align")) {
  846. static const char *al[] = { "left", "center", "right", "justify" };
  847. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  848. } else if (!strcmp(name, "float")) {
  849. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  850. st.float_left == 2 ? "right" : "none");
  851. } else if (!strcmp(name, "clear")) {
  852. static const char *cl[] = { "none", "left", "right", "both" };
  853. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  854. } else if (!strcmp(name, "opacity")) {
  855. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  856. } else if (!strcmp(name, "visibility")) {
  857. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  858. } else if (!strcmp(name, "overflow")) {
  859. snprintf(buf, cap, "%s",
  860. st.overflow_hidden ? "hidden" : "visible");
  861. } else if (!strcmp(name, "white-space")) {
  862. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  863. } else if (!strcmp(name, "text-transform")) {
  864. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  865. } else if (!strcmp(name, "box-sizing")) {
  866. snprintf(buf, cap, "%s",
  867. st.box_sizing ? "border-box" : "content-box");
  868. } else if (!strcmp(name, "line-height")) {
  869. if (st.line_h_px)
  870. snprintf(buf, cap, "%dpx", st.line_h_px);
  871. else if (st.line_h_pct)
  872. snprintf(buf, cap, "%d%%", st.line_h_pct);
  873. else
  874. snprintf(buf, cap, "normal");
  875. } else if (!strcmp(name, "z-index")) {
  876. if (st.z_set)
  877. snprintf(buf, cap, "%d", st.z_index);
  878. else
  879. snprintf(buf, cap, "auto");
  880. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  881. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  882. int set = name[0] == 't' ? st.top_set :
  883. name[0] == 'l' ? st.left_set :
  884. name[0] == 'r' ? st.right_set : st.bottom_set;
  885. int v = name[0] == 't' ? st.top :
  886. name[0] == 'l' ? st.left :
  887. name[0] == 'r' ? st.right : st.bottom;
  888. if (set)
  889. snprintf(buf, cap, "%dpx", v);
  890. else
  891. snprintf(buf, cap, "auto");
  892. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  893. !strcmp(name, "margin-bottom") ||
  894. !strcmp(name, "margin-left") ||
  895. !strcmp(name, "padding-top") ||
  896. !strcmp(name, "padding-right") ||
  897. !strcmp(name, "padding-bottom") ||
  898. !strcmp(name, "padding-left")) {
  899. int is_pad = name[0] == 'p';
  900. int side = name[strlen(name) - 1] == 'p' ? 0 :
  901. name[strlen(name) - 1] == 't' ? 1 :
  902. name[strlen(name) - 1] == 'm' ? 2 : 3;
  903. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  904. if (!strcmp(name, "margin-right") ||
  905. !strcmp(name, "padding-right"))
  906. side = 1;
  907. else if (!strcmp(name, "margin-bottom") ||
  908. !strcmp(name, "padding-bottom"))
  909. side = 2;
  910. else if (!strcmp(name, "margin-left") ||
  911. !strcmp(name, "padding-left"))
  912. side = 3;
  913. else
  914. side = 0;
  915. side += is_pad ? 4 : 0;
  916. css_mp_value(buf, cap,
  917. side == 0 ? st.mt : side == 1 ? st.mr :
  918. side == 2 ? st.mb : side == 3 ? st.ml :
  919. side == 4 ? st.pt : side == 5 ? st.pr :
  920. side == 6 ? st.pb : st.pl,
  921. st.mp_unit[side], st.mp_calc_px[side],
  922. st.font_px);
  923. } else if (!strcmp(name, "border-top-width") ||
  924. !strcmp(name, "border-right-width") ||
  925. !strcmp(name, "border-bottom-width") ||
  926. !strcmp(name, "border-left-width")) {
  927. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  928. name[7] == 'b' ? 2 : 3;
  929. snprintf(buf, cap, "%dpx", st.border_w[side]);
  930. } else if (!strcmp(name, "border-top-color") ||
  931. !strcmp(name, "border-right-color") ||
  932. !strcmp(name, "border-bottom-color") ||
  933. !strcmp(name, "border-left-color")) {
  934. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  935. name[7] == 'b' ? 2 : 3;
  936. if (st.border_w[side] && !st.border_t[side])
  937. css_rgb(st.border_c[side], buf, cap);
  938. else
  939. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  940. } else if (!strcmp(name, "background-image")) {
  941. if (st.bg_image)
  942. snprintf(buf, cap, "url(\"%s\")",
  943. br_bg_image_url(st.bg_image - 1));
  944. else
  945. snprintf(buf, cap, "none");
  946. } else if (!strcmp(name, "background-repeat")) {
  947. static const char *rp[] = {
  948. "repeat", "no-repeat", "repeat-x", "repeat-y"
  949. };
  950. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  951. st.bg_repeat : 0]);
  952. } else if (!strcmp(name, "background-position")) {
  953. if (st.bg_pos_x_kind == 1)
  954. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  955. st.bg_pos_y);
  956. else
  957. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  958. st.bg_pos_y);
  959. } else if (!strcmp(name, "background-size")) {
  960. if (st.bg_size_kind == 3)
  961. snprintf(buf, cap, "cover");
  962. else if (st.bg_size_kind == 4)
  963. snprintf(buf, cap, "contain");
  964. else if (st.bg_size_kind == 1)
  965. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  966. st.bg_size_h);
  967. else if (st.bg_size_kind == 2)
  968. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  969. st.bg_size_h);
  970. else
  971. snprintf(buf, cap, "auto");
  972. } else if (!strcmp(name, "transform")) {
  973. char tmp[128];
  974. unsigned int n = 0;
  975. if (!st.transform_set) {
  976. snprintf(buf, cap, "none");
  977. } else {
  978. tmp[0] = '\0';
  979. if (st.tx || st.ty) {
  980. snprintf(tmp + n, sizeof(tmp) - n,
  981. "translate(%dpx, %dpx)", st.tx, st.ty);
  982. n = (unsigned int)strlen(tmp);
  983. }
  984. if (st.transform_scale) {
  985. snprintf(tmp + n, sizeof(tmp) - n,
  986. "%sscale(%d.%02d, %d.%02d)",
  987. n ? " " : "", st.scale_x / 100,
  988. st.scale_x % 100, st.scale_y / 100,
  989. st.scale_y % 100);
  990. n = (unsigned int)strlen(tmp);
  991. if (st.rotate_x100) {
  992. snprintf(tmp + n, sizeof(tmp) - n,
  993. " rotate(%d.%02ddeg)",
  994. st.rotate_x100 / 100,
  995. st.rotate_x100 % 100);
  996. }
  997. } else if (st.rotate_x100) {
  998. snprintf(tmp + n, sizeof(tmp) - n,
  999. "%srotate(%d.%02ddeg)",
  1000. n ? " " : "", st.rotate_x100 / 100,
  1001. st.rotate_x100 % 100);
  1002. }
  1003. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1004. }
  1005. } else {
  1006. return 0;
  1007. }
  1008. return buf[0] != '\0';
  1009. }
  1010. static int js_host_click(unsigned int node)
  1011. {
  1012. char url[BR_URL_MAX];
  1013. const char *href;
  1014. if (node >= doc.nnode)
  1015. return 0;
  1016. if (form_is_control(node)) {
  1017. form_click(node); /* dispatches its own click event */
  1018. return 1;
  1019. }
  1020. /* element.click() fires a bubbling, cancelable click before the
  1021. * default action, like a real click (delegated list handlers). */
  1022. if (!js_browser_event(node, "click", 1, 1))
  1023. return 1;
  1024. href = br_href(&doc, node);
  1025. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1026. return 0;
  1027. s_copy(pending_url, url, sizeof(pending_url));
  1028. pending_action |= ACT_NAV;
  1029. cancel_fetch = 1;
  1030. ngui_invalidate(&ui);
  1031. return 1;
  1032. }
  1033. static int fetch_script_text(const char *url, unsigned char **out,
  1034. unsigned int *outlen, char *err,
  1035. unsigned int errcap);
  1036. struct fetch_worker;
  1037. static struct fetch_worker *fetch_worker_alloc(void);
  1038. static void fetch_worker_release(struct fetch_worker *w);
  1039. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1040. unsigned int cap, const char *post,
  1041. unsigned int post_len, unsigned int node,
  1042. int bg, char *err, unsigned int errcap);
  1043. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1044. unsigned int errcap);
  1045. static int fetch_worker_read_body(struct fetch_worker *w,
  1046. unsigned char *plain,
  1047. unsigned int plaincap,
  1048. unsigned char *comp,
  1049. unsigned int compcap,
  1050. int *truncated, char *err,
  1051. unsigned int errcap);
  1052. static void fetch_workers_stop_all(void);
  1053. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1054. unsigned int cap, const char *method,
  1055. const char *ctype, const char *post,
  1056. unsigned int post_len, unsigned int node,
  1057. int bg, char *err, unsigned int errcap);
  1058. static int script_cache_has(const char *url);
  1059. static void script_cache_put(const char *url, const unsigned char *data,
  1060. unsigned int len);
  1061. static unsigned int script_cache_hash(const char *s);
  1062. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1063. unsigned int errcap);
  1064. static void fetch_workers_cancel_busy(void);
  1065. static void worker_wait_ui(void);
  1066. static int fetch_worker_status(const struct fetch_worker *w);
  1067. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1068. * module load: the wait must not pump input, or a click would dispatch DOM
  1069. * events into the middle of the running script. */
  1070. static int fetch_wait_passive;
  1071. static void script_error(const char *what, const char *url, const char *why)
  1072. {
  1073. char msg[192];
  1074. unsigned int n = 0;
  1075. s_append(msg, &n, what, sizeof(msg));
  1076. if (url && url[0]) {
  1077. s_append(msg, &n, " ", sizeof(msg));
  1078. s_append(msg, &n, url, sizeof(msg));
  1079. }
  1080. if (why && why[0]) {
  1081. s_append(msg, &n, ": ", sizeof(msg));
  1082. s_append(msg, &n, why, sizeof(msg));
  1083. }
  1084. js_host_report(msg);
  1085. }
  1086. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1087. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1088. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1089. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1090. #define JS_HTTP_POST_MAX (16u * 1024u)
  1091. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1092. static int js_worker_http(const char *method, const char *url,
  1093. const char *ctype, const char *body,
  1094. unsigned int body_len, struct js_http_resp *r,
  1095. char *err, int errcap);
  1096. static int js_host_http(const char *method, const char *url,
  1097. const char *ctype, const char *body,
  1098. unsigned int body_len, struct js_http_resp *r,
  1099. char *err, int errcap)
  1100. {
  1101. if (pending_action) {
  1102. s_copy(err, "page is navigating", (unsigned int)errcap);
  1103. return -1;
  1104. }
  1105. if (url[0] == '/') {
  1106. /* Local file: GET only. */
  1107. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1108. int rv;
  1109. if (!buf) {
  1110. s_copy(err, "out of memory", (unsigned int)errcap);
  1111. return -1;
  1112. }
  1113. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1114. (int)JS_HTTP_MAX);
  1115. r->status = rv < 0 ? 404 : 200;
  1116. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1117. buf[r->len] = '\0';
  1118. r->body = (char *)buf;
  1119. s_copy(r->url, url, sizeof(r->url));
  1120. if (contains_ci(url, ".json"))
  1121. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1122. return 0;
  1123. }
  1124. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1125. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1126. return -1;
  1127. }
  1128. if (body_len > JS_HTTP_POST_MAX) {
  1129. s_copy(err, "request body too large", (unsigned int)errcap);
  1130. return -1;
  1131. }
  1132. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1133. errcap);
  1134. }
  1135. /* Module source for the engine's loader: the boot script cache first, then
  1136. * one blocking fetch with input pumping disabled (the loader runs inside
  1137. * JavaScript). */
  1138. static char *js_host_load_script(const char *url, unsigned int *len)
  1139. {
  1140. unsigned char *data = 0;
  1141. char err[64];
  1142. int rv;
  1143. fetch_wait_passive++;
  1144. set_status("Loading module...", 0, 0);
  1145. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1146. fetch_wait_passive--;
  1147. if (rv != 0) {
  1148. script_error("Cannot load module", url,
  1149. rv == FETCH_ABORT ? "navigation" : err);
  1150. return 0;
  1151. }
  1152. return (char *)data;
  1153. }
  1154. /* Web Storage lives in /share, outside the page heap that every navigation
  1155. * resets: localStorage per origin for the boot, sessionStorage per origin
  1156. * and browser window. */
  1157. #define JS_ORIGIN_MAX 160
  1158. /* scheme://host[:port] of the page (a local page's whole path). */
  1159. static void js_page_origin(char *origin, unsigned int cap)
  1160. {
  1161. unsigned int i = 0, slashes = 0;
  1162. while (page_url[i] && i + 1 < cap) {
  1163. if (page_url[i] == '/' && ++slashes == 3)
  1164. break;
  1165. origin[i] = page_url[i];
  1166. i++;
  1167. }
  1168. origin[i] = '\0';
  1169. }
  1170. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1171. {
  1172. unsigned int n = 0;
  1173. s_append(out, &n, "/share/bls", cap);
  1174. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1175. }
  1176. static void js_storage_path(int kind, char *out, unsigned int cap)
  1177. {
  1178. char origin[JS_ORIGIN_MAX];
  1179. unsigned int n = 0;
  1180. js_page_origin(origin, sizeof(origin));
  1181. if (!kind) {
  1182. js_origin_path(origin, out, cap);
  1183. return;
  1184. }
  1185. s_append(out, &n, "/share/bss", cap);
  1186. if (kind) {
  1187. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1188. s_append(out, &n, "-", cap);
  1189. }
  1190. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1191. }
  1192. static void persist_mark_origin(const char *origin);
  1193. static int persist_store_lookup(const char *origin, char *out, int cap);
  1194. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1195. {
  1196. char path[48], origin[JS_ORIGIN_MAX];
  1197. int rv;
  1198. js_storage_path(kind, path, sizeof(path));
  1199. if (set) {
  1200. if (kind) {
  1201. if (!set[0] || !strcmp(set, "{}")) {
  1202. u_syscall1(SYS_UNLINK, (int)path);
  1203. return 0;
  1204. }
  1205. } else {
  1206. /* localStorage keeps an explicit "{}" rather than no
  1207. * file: a missing /share file means "not loaded from
  1208. * /data yet", and a cleared store must not come back
  1209. * from the disk copy before it is flushed. */
  1210. if (!set[0])
  1211. set = "{}";
  1212. js_page_origin(origin, sizeof(origin));
  1213. persist_mark_origin(origin);
  1214. }
  1215. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1216. (int)strlen(set)) < 0 ? -1 : 0;
  1217. }
  1218. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1219. if (rv < 0 && !kind) {
  1220. /* First use this boot: the persistent copy on /data. */
  1221. js_page_origin(origin, sizeof(origin));
  1222. rv = persist_store_lookup(origin, out, cap);
  1223. if (rv >= 0)
  1224. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1225. }
  1226. if (rv < 0)
  1227. return -1;
  1228. out[rv] = '\0';
  1229. return rv;
  1230. }
  1231. /* ---- persistence on /data ----
  1232. *
  1233. * /share is the working copy (RAM, shared by every helper and window); the
  1234. * installed disk's /data volume keeps the cookie jar and localStorage
  1235. * across reboots when it is mounted. The browser owns the disk copies: at
  1236. * start it restores the jar into /share, and its main loop writes back
  1237. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1238. * setItem updates costs one FAT write. The helpers only touch /share (they
  1239. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1240. * /data mount every disk access simply fails. Both files are plaintext
  1241. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1242. #define PERSIST_MS 3000u
  1243. #define SHARE_COOKIES "/share/bcookies"
  1244. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1245. #define DATA_STORE "/data/BSTORE.DAT"
  1246. #define DATA_STORE_MAGIC "NBLS1\n"
  1247. #define DATA_STORE_MAX (192u * 1024u)
  1248. #define PERSIST_DIRTY_MAX 8
  1249. static unsigned int persist_due;
  1250. static unsigned int cookie_sum_saved;
  1251. static int cookie_sum_valid;
  1252. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1253. static int persist_ndirty;
  1254. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1255. {
  1256. unsigned int h = 2166136261u, i;
  1257. for (i = 0; i < n; i++)
  1258. h = (h ^ p[i]) * 16777619u;
  1259. return h;
  1260. }
  1261. /* Called once at startup, before any helper runs. */
  1262. static void persist_restore(void)
  1263. {
  1264. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1265. int n;
  1266. if (!jar)
  1267. return;
  1268. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1269. (int)sizeof(struct uhttp_jar));
  1270. if (n != (int)sizeof(struct uhttp_jar)) {
  1271. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1272. (int)sizeof(struct uhttp_jar));
  1273. if (n == (int)sizeof(struct uhttp_jar)) {
  1274. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1275. (int)jar, n);
  1276. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1277. cookie_sum_valid = 1;
  1278. }
  1279. }
  1280. free(jar);
  1281. persist_due = u_ticks_ms() + PERSIST_MS;
  1282. }
  1283. static void persist_mark_origin(const char *origin)
  1284. {
  1285. int i;
  1286. for (i = 0; i < persist_ndirty; i++)
  1287. if (s_eq(persist_dirty[i], origin))
  1288. return;
  1289. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1290. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1291. }
  1292. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1293. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1294. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1295. unsigned int *o_off, unsigned int *o_len,
  1296. unsigned int *d_off, unsigned int *d_len,
  1297. unsigned int *rec_end)
  1298. {
  1299. unsigned int p = *pos, v = 0;
  1300. if (p >= len)
  1301. return 0;
  1302. *o_off = p;
  1303. while (p < len && buf[p] != '\n')
  1304. p++;
  1305. if (p >= len)
  1306. return 0;
  1307. *o_len = p - *o_off;
  1308. p++;
  1309. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1310. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1311. if (p >= len || buf[p] != '\n')
  1312. return 0;
  1313. p++;
  1314. if (v > len - p)
  1315. return 0;
  1316. *d_off = p;
  1317. *d_len = v;
  1318. p += v;
  1319. if (p < len && buf[p] == '\n')
  1320. p++;
  1321. *rec_end = p;
  1322. *pos = p;
  1323. return 1;
  1324. }
  1325. static int store_load(char **out)
  1326. {
  1327. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1328. int n;
  1329. *out = buf;
  1330. if (!buf)
  1331. return -1;
  1332. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1333. (int)DATA_STORE_MAX);
  1334. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1335. !starts_with(buf, DATA_STORE_MAGIC))
  1336. return 0;
  1337. return n;
  1338. }
  1339. static int persist_store_lookup(const char *origin, char *out, int cap)
  1340. {
  1341. char *buf;
  1342. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1343. unsigned int olen = s_len(origin);
  1344. int n = store_load(&buf), rv = -1;
  1345. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1346. &dl, &e)) {
  1347. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1348. if ((int)dl < cap) {
  1349. memcpy(out, buf + d, dl);
  1350. out[dl] = '\0';
  1351. rv = (int)dl;
  1352. }
  1353. break;
  1354. }
  1355. }
  1356. free(buf);
  1357. return rv;
  1358. }
  1359. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1360. static void persist_store_flush(void)
  1361. {
  1362. char *old, *nb, path[48];
  1363. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1364. int n = store_load(&old), i, w;
  1365. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1366. if (n < 0 || !nb) {
  1367. free(old);
  1368. free(nb);
  1369. return;
  1370. }
  1371. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1372. /* Untouched origins first, in their old order. */
  1373. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1374. &dl, &e)) {
  1375. int dirty = 0;
  1376. for (i = 0; i < persist_ndirty; i++)
  1377. if (s_len(persist_dirty[i]) == ol &&
  1378. !memcmp(persist_dirty[i], old + oo, ol))
  1379. dirty = 1;
  1380. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1381. continue;
  1382. memcpy(nb + nn, old + oo, e - oo);
  1383. nn += e - oo;
  1384. }
  1385. /* Then the changed ones (an emptied store is dropped). */
  1386. for (i = 0; i < persist_ndirty; i++) {
  1387. char num[12];
  1388. unsigned int k = 0;
  1389. js_origin_path(persist_dirty[i], path, sizeof(path));
  1390. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1391. (int)DATA_STORE_MAX);
  1392. if (w <= 2) /* missing or "{}" */
  1393. continue;
  1394. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1395. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1396. DATA_STORE_MAX) {
  1397. set_status("Saved site data is full; a site's "
  1398. "localStorage was not saved", 1, 6000);
  1399. continue;
  1400. }
  1401. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1402. nb[nn++] = '\n';
  1403. s_append(nb, &nn, num, DATA_STORE_MAX);
  1404. nb[nn++] = '\n';
  1405. memcpy(nb + nn, old, (unsigned int)w);
  1406. nn += (unsigned int)w;
  1407. nb[nn++] = '\n';
  1408. }
  1409. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1410. persist_ndirty = 0;
  1411. free(old);
  1412. free(nb);
  1413. }
  1414. static void persist_cookies_flush(void)
  1415. {
  1416. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1417. unsigned int sum;
  1418. int n;
  1419. if (!jar)
  1420. return;
  1421. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1422. (int)sizeof(struct uhttp_jar));
  1423. if (n == (int)sizeof(struct uhttp_jar)) {
  1424. sum = persist_sum(jar, (unsigned int)n);
  1425. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1426. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1427. (int)jar, n) >= 0) {
  1428. cookie_sum_saved = sum;
  1429. cookie_sum_valid = 1;
  1430. }
  1431. }
  1432. }
  1433. free(jar);
  1434. }
  1435. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1436. static void persist_tick(void)
  1437. {
  1438. unsigned int now = u_ticks_ms();
  1439. if ((int)(now - persist_due) < 0)
  1440. return;
  1441. persist_due = now + PERSIST_MS;
  1442. persist_cookies_flush();
  1443. if (persist_ndirty)
  1444. persist_store_flush();
  1445. }
  1446. /* <link rel="modulepreload">: download the page's module graph on all
  1447. * helpers at once into the boot script cache, before any script runs. The
  1448. * engine's module loader is sequential (one blocking fetch per import), so
  1449. * without this a Vite app with a dozen chunks pays every round trip in a
  1450. * row. Failures are ignored; the loader fetches what is missing. */
  1451. #define MODULE_PRELOAD_MAX 24
  1452. static void prefetch_module_preloads(void)
  1453. {
  1454. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1455. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1456. unsigned int count = 0, next = 0, done = 0, i;
  1457. char err[64];
  1458. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1459. struct br_node *nd = &doc.nodes[i];
  1460. const char *rel, *href;
  1461. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1462. continue;
  1463. rel = br_rel(&doc, i);
  1464. href = br_href(&doc, i);
  1465. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1466. continue;
  1467. if (resolve_link(page_url, href, urls[count],
  1468. sizeof(urls[count])) != 0 ||
  1469. urls[count][0] == '/' || script_cache_has(urls[count]))
  1470. continue;
  1471. slot[count++] = 0;
  1472. }
  1473. if (!count)
  1474. return;
  1475. set_status("Loading modules...", 0, 0);
  1476. while (done < count) {
  1477. struct fetch_worker *w;
  1478. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1479. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1480. 0, 0, 0, err,
  1481. sizeof(err)) != 0) {
  1482. fetch_worker_release(w);
  1483. done++;
  1484. } else {
  1485. slot[next] = w;
  1486. }
  1487. next++;
  1488. }
  1489. worker_wait_ui();
  1490. if (cancel_fetch || pending_action) {
  1491. fetch_workers_cancel_busy();
  1492. return;
  1493. }
  1494. for (i = 0; i < next; i++) {
  1495. unsigned char *body;
  1496. int rv, tr = 0;
  1497. if (!slot[i])
  1498. continue;
  1499. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1500. if (rv == 0)
  1501. continue;
  1502. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1503. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1504. if (body) {
  1505. rv = fetch_worker_read_body(slot[i], body,
  1506. BR_SCRIPT_MAX, image_io_buf,
  1507. BR_PAGE_COMP_MAX, &tr, err,
  1508. sizeof(err));
  1509. if (rv > 0 && !tr)
  1510. script_cache_put(urls[i], body,
  1511. (unsigned int)rv);
  1512. free(body);
  1513. }
  1514. fetch_worker_release(slot[i]);
  1515. slot[i] = 0;
  1516. done++;
  1517. }
  1518. u_sleep_ms(10);
  1519. }
  1520. }
  1521. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1522. * submitted to helper workers ahead of time, but scripts still execute in
  1523. * document order. */
  1524. #define SCRIPT_INLINE 0
  1525. #define SCRIPT_LOCAL 1
  1526. #define SCRIPT_REMOTE 2
  1527. #define SCRIPT_ERROR 3
  1528. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1529. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1530. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1531. static void script_submit_window(unsigned int *next, char *err,
  1532. unsigned int errcap)
  1533. {
  1534. while (*next < doc.nscripts) {
  1535. struct fetch_worker *w;
  1536. if (script_kind[*next] != SCRIPT_REMOTE) {
  1537. (*next)++;
  1538. continue;
  1539. }
  1540. w = fetch_worker_alloc();
  1541. if (!w)
  1542. return;
  1543. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1544. 0, 0, 0, 0, err, errcap) != 0) {
  1545. fetch_worker_release(w);
  1546. script_kind[*next] = SCRIPT_ERROR;
  1547. (*next)++;
  1548. continue;
  1549. }
  1550. script_slot[*next] = w;
  1551. (*next)++;
  1552. }
  1553. }
  1554. /* Run the page's scripts in document order. External bodies are prefetched
  1555. * in parallel so downloading script N+1 overlaps executing script N; inline
  1556. * bodies are copied because the engine needs NUL-terminated text. */
  1557. static void run_page_scripts(void)
  1558. {
  1559. struct js_browser_host host;
  1560. unsigned int i, next = 0;
  1561. char err[64], ferr[64];
  1562. if (!doc.nscripts)
  1563. return;
  1564. host.status = js_host_status;
  1565. host.report = js_host_report;
  1566. host.navigate = js_host_navigate;
  1567. host.changed = js_host_changed;
  1568. host.rect = js_host_rect;
  1569. host.form_value = js_host_form_value;
  1570. host.form_checked = js_host_form_checked;
  1571. host.form_selected = js_host_form_selected;
  1572. host.form_set_value = js_host_form_set_value;
  1573. host.form_set_checked = js_host_form_set_checked;
  1574. host.form_set_selected = js_host_form_set_selected;
  1575. host.form_elements = js_host_form_elements;
  1576. host.form_submit = js_host_form_submit;
  1577. host.form_reset = js_host_form_reset;
  1578. host.click = js_host_click;
  1579. host.computed = js_host_computed;
  1580. host.http = js_host_http;
  1581. host.load_script = js_host_load_script;
  1582. host.storage = js_host_storage;
  1583. host.page_url = page_url;
  1584. host.width = ui.w;
  1585. host.height = ui.h;
  1586. if (js_browser_start(&doc, &host) != 0) {
  1587. js_host_status("JavaScript: out of memory", 1);
  1588. return;
  1589. }
  1590. prefetch_module_preloads();
  1591. for (i = 0; i < doc.nscripts; i++) {
  1592. struct br_script *script = &doc.scripts[i];
  1593. const char *src_attr = script->src_off ?
  1594. doc.attrs + script->src_off : "";
  1595. script_slot[i] = 0;
  1596. if (!script->src_off) {
  1597. script_kind[i] = SCRIPT_INLINE;
  1598. continue;
  1599. }
  1600. if (!src_attr[0] ||
  1601. resolve_link(page_url, src_attr, script_urls[i],
  1602. sizeof(script_urls[i])) != 0) {
  1603. script_urls[i][0] = '\0';
  1604. script_kind[i] = SCRIPT_ERROR;
  1605. continue;
  1606. }
  1607. if (script_urls[i][0] == '/' ||
  1608. script_cache_has(script_urls[i]))
  1609. script_kind[i] = SCRIPT_LOCAL;
  1610. else
  1611. script_kind[i] = SCRIPT_REMOTE;
  1612. }
  1613. script_submit_window(&next, ferr, sizeof(ferr));
  1614. for (i = 0; i < doc.nscripts; i++) {
  1615. struct br_script *script = &doc.scripts[i];
  1616. if (script_kind[i] == SCRIPT_INLINE) {
  1617. unsigned int off = script->off;
  1618. unsigned int len = script->len;
  1619. unsigned int k;
  1620. char *src = (char *)malloc(len + 1);
  1621. if (!src) {
  1622. js_host_status("JavaScript: out of memory", 1);
  1623. break;
  1624. }
  1625. for (k = 0; k < len; k++)
  1626. src[k] = doc.script_src[off + k];
  1627. src[len] = '\0';
  1628. if (script->module) {
  1629. /* A distinct module name per inline module
  1630. * (QuickJS registers modules by name); the
  1631. * fragment keeps relative imports resolving
  1632. * against the page. */
  1633. char mname[BR_URL_MAX + 16];
  1634. unsigned int mn = 0;
  1635. s_append(mname, &mn, page_url, sizeof(mname));
  1636. s_append(mname, &mn, "#module", sizeof(mname));
  1637. s_append_dec(mname, &mn, i, sizeof(mname));
  1638. js_browser_run_module(src, mname);
  1639. } else {
  1640. js_browser_run(src, page_url);
  1641. }
  1642. free(src);
  1643. } else if (script->src_off) {
  1644. const char *src_attr = doc.attrs + script->src_off;
  1645. if (script_kind[i] == SCRIPT_ERROR) {
  1646. script_error("Cannot load script", src_attr,
  1647. script_urls[i][0] ?
  1648. "network busy" :
  1649. "unsupported URL");
  1650. continue;
  1651. }
  1652. if (script_kind[i] == SCRIPT_LOCAL) {
  1653. unsigned char *data = 0;
  1654. unsigned int len = 0;
  1655. int rv;
  1656. set_status("Loading script...", 0, 0);
  1657. rv = fetch_script_text(script_urls[i], &data,
  1658. &len, err, sizeof(err));
  1659. if (rv == FETCH_ABORT)
  1660. break;
  1661. if (rv != 0) {
  1662. script_error("Cannot load script",
  1663. script_urls[i], err);
  1664. continue;
  1665. }
  1666. if (script->module)
  1667. js_browser_run_module(
  1668. (const char *)data,
  1669. script_urls[i]);
  1670. else
  1671. js_browser_run((const char *)data,
  1672. script_urls[i]);
  1673. free(data);
  1674. } else {
  1675. struct fetch_worker *w = script_slot[i];
  1676. unsigned char *body = 0;
  1677. int tr = 0, rv;
  1678. if (!w) {
  1679. w = fetch_worker_alloc();
  1680. if (!w)
  1681. continue;
  1682. if (fetch_worker_submit(w,
  1683. script_urls[i],
  1684. BR_SCRIPT_MAX,
  1685. 0, 0, 0, 0, err,
  1686. sizeof(err)) != 0) {
  1687. fetch_worker_release(w);
  1688. script_kind[i] = SCRIPT_ERROR;
  1689. if (i == next)
  1690. next++;
  1691. continue;
  1692. }
  1693. script_slot[i] = w;
  1694. if (i == next)
  1695. next++;
  1696. }
  1697. set_status("Loading script...", 0, 0);
  1698. rv = fetch_worker_wait(w, err, sizeof(err));
  1699. if (rv == FETCH_ABORT) {
  1700. fetch_workers_stop_all();
  1701. break;
  1702. }
  1703. /* The body gets its own buffer (scripts are up
  1704. * to 2 MB); image_io_buf takes the gzip
  1705. * stream. */
  1706. body = rv == 0 ? (unsigned char *)malloc(
  1707. BR_SCRIPT_MAX + 1) : 0;
  1708. if (body)
  1709. rv = fetch_worker_read_body(w, body,
  1710. BR_SCRIPT_MAX, image_io_buf,
  1711. BR_PAGE_COMP_MAX, &tr, err,
  1712. sizeof(err));
  1713. else {
  1714. if (rv == 0)
  1715. s_copy(err, "out of memory",
  1716. sizeof(err));
  1717. rv = -1;
  1718. }
  1719. fetch_worker_release(w);
  1720. script_slot[i] = 0;
  1721. script_submit_window(&next, ferr, sizeof(ferr));
  1722. if (rv <= 0)
  1723. script_error("Cannot load script",
  1724. script_urls[i], err);
  1725. else if (tr || (unsigned int)rv >=
  1726. BR_SCRIPT_MAX)
  1727. script_error("Cannot load script",
  1728. script_urls[i],
  1729. "script is too large");
  1730. else {
  1731. body[rv] = '\0';
  1732. script_cache_put(script_urls[i], body,
  1733. (unsigned int)rv);
  1734. if (script->module)
  1735. js_browser_run_module(
  1736. (const char *)body,
  1737. script_urls[i]);
  1738. else
  1739. js_browser_run(
  1740. (const char *)body,
  1741. script_urls[i]);
  1742. }
  1743. free(body);
  1744. }
  1745. }
  1746. if (pending_action)
  1747. break;
  1748. }
  1749. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  1750. * load_home() stop it before the next navigation. */
  1751. if (doc.scripts_truncated && !js_last_error)
  1752. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  1753. 1);
  1754. }
  1755. /* ---- images ---- */
  1756. static void image_reset(void)
  1757. {
  1758. int i;
  1759. for (i = 0; i < BR_MAX_IMAGES; i++) {
  1760. images[i].state = 0;
  1761. images[i].native_w = images[i].native_h = 0;
  1762. images[i].err[0] = '\0';
  1763. }
  1764. image_count = 0;
  1765. image_pixels = 0;
  1766. preload_active = 0;
  1767. preload_pending = 0;
  1768. preload_wait = 0;
  1769. preload_node = 0;
  1770. preload_loaded = 0;
  1771. }
  1772. /* Decode into the shared arena, then copy/scale the result into a display
  1773. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  1774. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  1775. * pixels. Transparent edges are composited over white. */
  1776. /* One decode scratch arena per page, reused across images. Allocating and
  1777. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  1778. * each small display bitmap landed in the hole the previous arena left, so
  1779. * the next arena no longer fit and the heap ratcheted up until an app
  1780. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  1781. * still released right after their one image. */
  1782. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  1783. static unsigned char *decode_arena_get(unsigned int bytes)
  1784. {
  1785. if (decode_arena && decode_arena_size >= bytes)
  1786. return decode_arena;
  1787. free(decode_arena);
  1788. decode_arena = (unsigned char *)malloc(bytes);
  1789. decode_arena_size = decode_arena ? bytes : 0;
  1790. return decode_arena;
  1791. }
  1792. static void decode_arena_put(void)
  1793. {
  1794. if (decode_arena_size > DECODE_ARENA_KEEP) {
  1795. free(decode_arena);
  1796. decode_arena = 0;
  1797. decode_arena_size = 0;
  1798. }
  1799. }
  1800. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  1801. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  1802. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  1803. static int decode_image_data(const unsigned char *data, unsigned int len,
  1804. struct br_image *bi, int box_w, int box_h)
  1805. {
  1806. struct img_info info;
  1807. struct img_options opt;
  1808. struct img_mem mem;
  1809. struct img_image decoded;
  1810. unsigned char *arena;
  1811. unsigned int est, bytes, i;
  1812. unsigned short *px;
  1813. unsigned char *alpha = 0;
  1814. int dw, dh, r;
  1815. if (img_sniff(data, len, &info) != 0) {
  1816. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  1817. return -1;
  1818. }
  1819. est = img_estimate(&info);
  1820. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  1821. s_copy(bi->err, "image too large", sizeof(bi->err));
  1822. return -1;
  1823. }
  1824. arena = decode_arena_get(est);
  1825. if (!arena) {
  1826. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1827. return -1;
  1828. }
  1829. img_mem_init(&mem, arena, est);
  1830. opt.max_pixels = BR_IMG_PIX_MAX;
  1831. r = img_decode(data, len, &opt, &mem, &decoded);
  1832. if (r != 0) {
  1833. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  1834. goto fail;
  1835. }
  1836. if (decoded.w == 0 || decoded.h == 0) {
  1837. s_copy(bi->err, "empty image", sizeof(bi->err));
  1838. goto fail;
  1839. }
  1840. bi->native_w = (int)decoded.w;
  1841. bi->native_h = (int)decoded.h;
  1842. dw = (int)decoded.w;
  1843. dh = (int)decoded.h;
  1844. if (box_w > 0 && box_h > 0) {
  1845. /* cover: scale so both box sides are filled, never up */
  1846. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  1847. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  1848. unsigned int sc = sw > sh ? sw : sh;
  1849. if (sc < 0x10000u) {
  1850. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  1851. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  1852. }
  1853. }
  1854. if (dw > BR_IMG_LAYOUT_W) {
  1855. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  1856. dw = BR_IMG_LAYOUT_W;
  1857. }
  1858. if (dh < 1)
  1859. dh = 1;
  1860. if (dw < 1)
  1861. dw = 1;
  1862. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  1863. BR_IMG_PIXEL_BUDGET) {
  1864. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  1865. goto fail;
  1866. }
  1867. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  1868. px = (unsigned short *)malloc(bytes);
  1869. if (!px) {
  1870. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1871. goto fail;
  1872. }
  1873. /* Keep the alpha plane for the scaled image so transparent logos and
  1874. * icons composite over the page instead of the browser's dark theme
  1875. * background. Very large alpha images stay flattened to bound the
  1876. * heap use. */
  1877. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  1878. alpha = (unsigned char *)malloc((unsigned int)dw *
  1879. (unsigned int)dh);
  1880. if (alpha) {
  1881. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1882. alpha[i] = 255;
  1883. }
  1884. }
  1885. /* With an alpha plane the colour under transparent pixels only shows
  1886. * through partially covered edge pixels of the downscale: use white,
  1887. * as documented above, not the dark browser theme (which left a dark
  1888. * fringe around scaled app icons). */
  1889. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1890. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  1891. {
  1892. struct img_blit b;
  1893. b.dst = px;
  1894. b.dst_w = dw;
  1895. b.dst_h = dh;
  1896. b.clip_x = 0;
  1897. b.clip_y = 0;
  1898. b.clip_w = dw;
  1899. b.clip_h = dh;
  1900. b.x = 0;
  1901. b.y = 0;
  1902. b.scale = ((unsigned int)dw << 16) / decoded.w;
  1903. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  1904. b.bg2 = b.bg;
  1905. b.dst_a = alpha;
  1906. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  1907. img_draw(&decoded, &b);
  1908. }
  1909. bi->img.format = decoded.format;
  1910. bi->img.w = (unsigned int)dw;
  1911. bi->img.h = (unsigned int)dh;
  1912. bi->img.px = px;
  1913. bi->img.alpha = alpha;
  1914. bi->img.flags = 0;
  1915. bi->state = 1;
  1916. image_pixels += (unsigned int)dw * (unsigned int)dh;
  1917. decode_arena_put();
  1918. return 0;
  1919. fail:
  1920. decode_arena_put();
  1921. return -1;
  1922. }
  1923. /* ---- URL / local path handling ---- */
  1924. static int is_http(const char *s)
  1925. {
  1926. return starts_with(s, "http://") || starts_with(s, "https://");
  1927. }
  1928. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  1929. static int normalize_abs(const char *in, char *out, unsigned int cap)
  1930. {
  1931. char seg[64];
  1932. unsigned int i = 0, o = 1;
  1933. int depth = 0;
  1934. int trailing;
  1935. if (!in || in[0] != '/' || cap < 2)
  1936. return -1;
  1937. trailing = 0;
  1938. {
  1939. unsigned int n = s_len(in);
  1940. if (n > 1 && in[n - 1] == '/')
  1941. trailing = 1;
  1942. }
  1943. out[0] = '/';
  1944. while (in[i]) {
  1945. unsigned int n = 0;
  1946. while (in[i] == '/')
  1947. i++;
  1948. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  1949. if (n + 1 < sizeof(seg))
  1950. seg[n++] = in[i];
  1951. i++;
  1952. }
  1953. seg[n] = '\0';
  1954. if (n == 0)
  1955. break;
  1956. if (s_eq(seg, "."))
  1957. continue;
  1958. if (s_eq(seg, "..")) {
  1959. if (depth > 0) {
  1960. while (o > 1 && out[o - 1] != '/')
  1961. o--;
  1962. if (o > 1)
  1963. o--;
  1964. depth--;
  1965. }
  1966. continue;
  1967. }
  1968. if (o > 1) {
  1969. if (o + 1 >= cap)
  1970. return -1;
  1971. out[o++] = '/';
  1972. }
  1973. if (o + n + 1 >= cap)
  1974. return -1;
  1975. {
  1976. unsigned int j;
  1977. for (j = 0; j < n; j++)
  1978. out[o++] = seg[j];
  1979. }
  1980. depth++;
  1981. }
  1982. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  1983. if (o + 1 >= cap)
  1984. return -1;
  1985. out[o++] = '/';
  1986. }
  1987. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  1988. if (in[i] == '?' || in[i] == '#') {
  1989. while (in[i]) {
  1990. if (o + 1 >= cap)
  1991. return -1;
  1992. out[o++] = in[i++];
  1993. }
  1994. }
  1995. out[o] = '\0';
  1996. return 0;
  1997. }
  1998. static void make_abs_local(const char *in, char *out, unsigned int cap)
  1999. {
  2000. char joined[BR_URL_MAX];
  2001. if (!in || !in[0]) {
  2002. s_copy(out, cwd[0] ? cwd : "/", cap);
  2003. return;
  2004. }
  2005. if (in[0] == '/') {
  2006. if (normalize_abs(in, out, cap) != 0)
  2007. s_copy(out, in, cap);
  2008. return;
  2009. }
  2010. {
  2011. unsigned int n = 0;
  2012. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2013. s_append(joined, &n, "/", sizeof(joined));
  2014. s_append(joined, &n, in, sizeof(joined));
  2015. }
  2016. if (normalize_abs(joined, out, cap) != 0)
  2017. s_copy(out, joined, cap);
  2018. }
  2019. /* ---- canonical origin cache ---- *
  2020. *
  2021. * Sites commonly redirect http://host to https://host and then to
  2022. * https://www.host. Remember the final scheme/host of the last navigation so
  2023. * a bare domain typed again goes straight there instead of paying for two
  2024. * more connections and TLS handshakes. Only default-port requests are
  2025. * rewritten; explicit ports are left alone. */
  2026. #define ORIGIN_CACHE_MAX 8
  2027. #define ORIGIN_FILE "/share/borigins"
  2028. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2029. UHTTP_HOST_MAX + 2))
  2030. struct origin_cache_entry {
  2031. char host[UHTTP_HOST_MAX];
  2032. char origin[UHTTP_HOST_MAX + 16];
  2033. };
  2034. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2035. static int origin_count;
  2036. static char origin_buf[ORIGIN_BUF_SIZE];
  2037. static int default_port(const struct uhttp_url *u)
  2038. {
  2039. return u->secure ? u->port == 443 : u->port == 80;
  2040. }
  2041. static void url_origin(const struct uhttp_url *u, char *out,
  2042. unsigned int cap)
  2043. {
  2044. unsigned int n = 0;
  2045. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2046. s_append(out, &n, u->host, cap);
  2047. if (!default_port(u)) {
  2048. s_append(out, &n, ":", cap);
  2049. s_append_dec(out, &n, u->port, cap);
  2050. }
  2051. }
  2052. static void origin_cache_apply(char *url, unsigned int cap)
  2053. {
  2054. struct uhttp_url u;
  2055. char out[BR_URL_MAX];
  2056. unsigned int n = 0;
  2057. int i;
  2058. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2059. return;
  2060. for (i = 0; i < origin_count; i++) {
  2061. if (!s_eq(u.host, origins[i].host))
  2062. continue;
  2063. s_append(out, &n, origins[i].origin, sizeof(out));
  2064. s_append(out, &n, u.path, sizeof(out));
  2065. s_copy(url, out, cap);
  2066. return;
  2067. }
  2068. }
  2069. static void origin_cache_save(void)
  2070. {
  2071. unsigned int n = 0;
  2072. int i;
  2073. for (i = 0; i < origin_count; i++) {
  2074. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2075. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2076. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2077. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2078. }
  2079. if (n)
  2080. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2081. (int)origin_buf, (int)n);
  2082. }
  2083. static void origin_cache_load(void)
  2084. {
  2085. char *p;
  2086. int rn;
  2087. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2088. (int)(sizeof(origin_buf) - 1));
  2089. if (rn <= 0)
  2090. return;
  2091. origin_buf[rn] = '\0';
  2092. p = origin_buf;
  2093. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2094. char *line = p, *origin;
  2095. while (*p && *p != '\n')
  2096. p++;
  2097. if (*p)
  2098. *p++ = '\0';
  2099. if (!line[0])
  2100. continue;
  2101. origin = line;
  2102. while (*origin && *origin != ' ')
  2103. origin++;
  2104. if (!*origin)
  2105. continue;
  2106. *origin++ = '\0';
  2107. if (!line[0] || !is_http(origin))
  2108. continue;
  2109. {
  2110. struct uhttp_url uo;
  2111. if (uhttp_parse_url(origin, &uo) != 0 ||
  2112. !s_eq(uo.path, "/"))
  2113. continue;
  2114. }
  2115. s_copy(origins[origin_count].host, line,
  2116. sizeof(origins[origin_count].host));
  2117. s_copy(origins[origin_count].origin, origin,
  2118. sizeof(origins[origin_count].origin));
  2119. origin_count++;
  2120. }
  2121. }
  2122. static int host_is_www_of(const char *host, const char *base)
  2123. {
  2124. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2125. host[3] == '.' && s_eq(host + 4, base);
  2126. }
  2127. static void origin_cache_learn(const char *requested, const char *final)
  2128. {
  2129. struct uhttp_url from, to;
  2130. char origin[UHTTP_HOST_MAX + 16];
  2131. int i;
  2132. if (!is_http(requested) || !is_http(final))
  2133. return;
  2134. if (uhttp_parse_url(requested, &from) != 0 ||
  2135. uhttp_parse_url(final, &to) != 0)
  2136. return;
  2137. if (!default_port(&from))
  2138. return;
  2139. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2140. from.port == to.port)
  2141. return;
  2142. /* Only remember origin-level canonicalisation: the same path, and
  2143. * either the same host or its www./apex sibling. A path- or
  2144. * host-specific redirect (a shortener, a login page) must not poison
  2145. * every request to the typed host. */
  2146. if (!s_eq(from.path, to.path))
  2147. return;
  2148. if (!s_eq(from.host, to.host) &&
  2149. !host_is_www_of(to.host, from.host) &&
  2150. !host_is_www_of(from.host, to.host))
  2151. return;
  2152. url_origin(&to, origin, sizeof(origin));
  2153. for (i = 0; i < origin_count; i++) {
  2154. if (s_eq(origins[i].host, from.host)) {
  2155. if (!s_eq(origins[i].origin, origin)) {
  2156. s_copy(origins[i].origin, origin,
  2157. sizeof(origins[i].origin));
  2158. origin_cache_save();
  2159. }
  2160. return;
  2161. }
  2162. }
  2163. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2164. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2165. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2166. origin_cache_save();
  2167. }
  2168. static int path_dir(const char *path, char *out, unsigned int cap)
  2169. {
  2170. unsigned int i, last = 0;
  2171. for (i = 0; path[i]; i++)
  2172. if (path[i] == '/')
  2173. last = i;
  2174. if (last == 0) {
  2175. if (cap < 2)
  2176. return -1;
  2177. out[0] = '/';
  2178. out[1] = '\0';
  2179. return 0;
  2180. }
  2181. if (last + 1 >= cap)
  2182. return -1;
  2183. {
  2184. unsigned int j;
  2185. for (j = 0; j < last; j++)
  2186. out[j] = path[j];
  2187. out[last] = '\0';
  2188. }
  2189. return 0;
  2190. }
  2191. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2192. static int resolve_link(const char *base, const char *href, char *out,
  2193. unsigned int cap)
  2194. {
  2195. char joined[BR_URL_MAX];
  2196. if (!href || !href[0] || href[0] == '#')
  2197. return -1;
  2198. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2199. starts_with(href, "data:") || starts_with(href, "tel:"))
  2200. return -1;
  2201. if (starts_with(href, "about:")) {
  2202. s_copy(out, href, cap);
  2203. return 0;
  2204. }
  2205. if (is_http(href)) {
  2206. s_copy(out, href, cap);
  2207. return 0;
  2208. }
  2209. if (starts_with(href, "//")) {
  2210. if (is_http(base)) {
  2211. unsigned int n = 0;
  2212. s_append(out, &n, starts_with(base, "https:") ?
  2213. "https:" : "http:", cap);
  2214. s_append(out, &n, href, cap);
  2215. return 0;
  2216. }
  2217. return -1;
  2218. }
  2219. if (is_http(base)) {
  2220. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2221. }
  2222. /* local page */
  2223. if (href[0] == '/') {
  2224. if (normalize_abs(href, out, cap) != 0)
  2225. return -1;
  2226. return 0;
  2227. }
  2228. {
  2229. char dir[BR_URL_MAX];
  2230. unsigned int n = 0;
  2231. if (s_eq(base, "about:home"))
  2232. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2233. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2234. s_copy(dir, "/", sizeof(dir));
  2235. s_append(joined, &n, dir, sizeof(joined));
  2236. if (n == 0 || joined[n - 1] != '/')
  2237. s_append(joined, &n, "/", sizeof(joined));
  2238. s_append(joined, &n, href, sizeof(joined));
  2239. }
  2240. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2241. }
  2242. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2243. * rest instead of failing when a page or stylesheet is larger than the
  2244. * buffer. The stream is still walked to the end, so a normal page is
  2245. * verified; a truncated compressed input still returns whatever was decoded
  2246. * so far. */
  2247. struct trunc_buf {
  2248. unsigned char *dst;
  2249. unsigned int cap, pos;
  2250. int full;
  2251. };
  2252. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2253. {
  2254. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2255. if (len > m->cap - m->pos) {
  2256. unsigned int room = m->cap - m->pos;
  2257. if (room) {
  2258. unsigned int i;
  2259. for (i = 0; i < room; i++)
  2260. m->dst[m->pos + i] = data[i];
  2261. m->pos += room;
  2262. }
  2263. m->full = 1;
  2264. return 0;
  2265. }
  2266. {
  2267. unsigned int i;
  2268. for (i = 0; i < len; i++)
  2269. m->dst[m->pos + i] = data[i];
  2270. }
  2271. m->pos += len;
  2272. return 0;
  2273. }
  2274. static void worker_wait_ui(void);
  2275. static void inflate_ui_pump(void *ctx)
  2276. {
  2277. static unsigned int last;
  2278. unsigned int now = u_ticks_ms();
  2279. (void)ctx;
  2280. if ((int)(now - last) >= 50) {
  2281. last = now;
  2282. worker_wait_ui();
  2283. }
  2284. }
  2285. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2286. unsigned char *dst, unsigned int cap,
  2287. unsigned int *outlen, int gzip, int *truncated)
  2288. {
  2289. struct inflate_src in;
  2290. struct inflate_sink sink;
  2291. struct trunc_buf m;
  2292. unsigned int got = 0;
  2293. int r;
  2294. in.p = src;
  2295. in.len = len;
  2296. in.more = 0;
  2297. in.ctx = 0;
  2298. m.dst = dst;
  2299. m.cap = cap;
  2300. m.pos = 0;
  2301. m.full = 0;
  2302. sink.write = trunc_write;
  2303. sink.ctx = &m;
  2304. inflate_init(&image_inflate_ws, &in, &sink);
  2305. image_inflate_ws.progress = inflate_ui_pump;
  2306. image_inflate_ws.progress_ctx = 0;
  2307. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2308. inflate_zlib(&image_inflate_ws, &got);
  2309. *outlen = m.pos;
  2310. *truncated = m.full || r != 0;
  2311. if (r != 0 && m.pos == 0)
  2312. return -1;
  2313. return 0;
  2314. }
  2315. /* ---- headless fetch workers ------------------------------------------ *
  2316. *
  2317. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2318. * writes the raw response, a small metadata file and a done marker under
  2319. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2320. * or a multi-megabyte body never freezes the UI and images download in
  2321. * parallel.
  2322. */
  2323. struct fetch_meta {
  2324. int status;
  2325. int error;
  2326. int trunc;
  2327. unsigned int len;
  2328. unsigned int open_ms;
  2329. unsigned int first_ms;
  2330. unsigned int total_ms;
  2331. char encoding[16];
  2332. char ctype[64];
  2333. char final[BR_URL_MAX];
  2334. };
  2335. static void draw(unsigned int *action);
  2336. static void handle_keys(unsigned int *action);
  2337. static void handle_page_click(unsigned int *action);
  2338. #define FETCH_WORKERS 4
  2339. #define FETCH_PATH_MAX 32
  2340. /* One long-lived curl __serve helper per worker. Each worker has its own
  2341. * request/body/meta/done files under /share so several downloads can be in
  2342. * flight at once; the keep-alive connection stays in the helper process, so
  2343. * tls.c's per-process state remains valid. */
  2344. struct fetch_worker {
  2345. int pid;
  2346. int slot;
  2347. int busy;
  2348. int ready;
  2349. int image_job;
  2350. unsigned int seq;
  2351. unsigned int deadline;
  2352. int retried;
  2353. char req[FETCH_PATH_MAX];
  2354. char body[FETCH_PATH_MAX];
  2355. char meta[FETCH_PATH_MAX];
  2356. char done[FETCH_PATH_MAX];
  2357. char post[FETCH_PATH_MAX];
  2358. /* Optional preload job attached to this worker. */
  2359. unsigned int node;
  2360. int bg;
  2361. char url[BR_URL_MAX];
  2362. struct fetch_meta m;
  2363. };
  2364. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2365. static int fetch_tty = -2;
  2366. static void fetch_tty_drain(void);
  2367. static unsigned int fetch_session;
  2368. static unsigned int fetch_seq;
  2369. static struct fetch_meta fetch_meta;
  2370. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2371. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2372. static int fetch_last_error;
  2373. static unsigned int meta_uint(char **pp)
  2374. {
  2375. char *p = *pp;
  2376. unsigned int v = 0;
  2377. while (*p >= '0' && *p <= '9') {
  2378. v = v * 10 + (unsigned int)(*p - '0');
  2379. p++;
  2380. }
  2381. while (*p && *p != '\n')
  2382. p++;
  2383. if (*p == '\n')
  2384. p++;
  2385. *pp = p;
  2386. return v;
  2387. }
  2388. static void meta_str(char **pp, char *out, unsigned int cap)
  2389. {
  2390. char *p = *pp;
  2391. unsigned int n = 0;
  2392. while (*p && *p != '\n' && n + 1 < cap)
  2393. out[n++] = *p++;
  2394. out[n] = '\0';
  2395. while (*p && *p != '\n')
  2396. p++;
  2397. if (*p == '\n')
  2398. p++;
  2399. *pp = p;
  2400. }
  2401. static void worker_wait_ui(void)
  2402. {
  2403. unsigned int action = 0;
  2404. if (!ngui_begin(&ui))
  2405. return;
  2406. draw(&action);
  2407. handle_keys(&action);
  2408. handle_page_click(&action);
  2409. if (action & ACT_WAIT_NAV) {
  2410. pending_action |= action & ACT_WAIT_NAV;
  2411. if ((action & ACT_NAV) && click_url[0])
  2412. s_copy(pending_url, click_url, sizeof(pending_url));
  2413. click_url[0] = '\0';
  2414. cancel_fetch = 1;
  2415. }
  2416. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  2417. ngui_invalidate(&ui);
  2418. ngui_end(&ui);
  2419. }
  2420. static void fetch_path(char *out, unsigned int cap, const char *kind,
  2421. unsigned int session, int slot)
  2422. {
  2423. unsigned int n = 0;
  2424. s_append(out, &n, "/share/bf", cap);
  2425. s_append_dec(out, &n, session, cap);
  2426. s_append(out, &n, "_", cap);
  2427. s_append_dec(out, &n, (unsigned int)slot, cap);
  2428. s_append(out, &n, kind, cap);
  2429. }
  2430. static void fetch_pool_init(void)
  2431. {
  2432. static int ready;
  2433. int i;
  2434. if (ready)
  2435. return;
  2436. ready = 1;
  2437. fetch_session = ((unsigned int)u_getpid() << 16) ^
  2438. (u_ticks_ms() & 0xFFFFu);
  2439. if (!fetch_session)
  2440. fetch_session = 1;
  2441. for (i = 0; i < FETCH_WORKERS; i++) {
  2442. struct fetch_worker *w = &fetch_workers[i];
  2443. w->pid = -1;
  2444. w->slot = i;
  2445. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  2446. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  2447. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  2448. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  2449. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  2450. }
  2451. }
  2452. static void fetch_worker_stop(struct fetch_worker *w)
  2453. {
  2454. int i;
  2455. /* An abandoned image job leaves its node loadable again. */
  2456. if (w->busy && w->image_job && w->node < doc.nnode) {
  2457. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  2458. doc.nodes[w->node].bg_img_index = -1;
  2459. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  2460. doc.nodes[w->node].img_index = -1;
  2461. }
  2462. if (w->pid > 0) {
  2463. u_kill((unsigned int)w->pid);
  2464. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  2465. u_sleep_ms(5);
  2466. /* Let the reaper close the socket before we reuse the slot. */
  2467. u_sleep_ms(10);
  2468. }
  2469. w->pid = -1;
  2470. w->busy = 0;
  2471. w->ready = 0;
  2472. w->image_job = 0;
  2473. if (w->req[0]) {
  2474. u_syscall1(SYS_UNLINK, (int)w->done);
  2475. u_syscall1(SYS_UNLINK, (int)w->meta);
  2476. u_syscall1(SYS_UNLINK, (int)w->body);
  2477. u_syscall1(SYS_UNLINK, (int)w->post);
  2478. u_syscall1(SYS_UNLINK, (int)w->req);
  2479. }
  2480. }
  2481. static void fetch_workers_stop_all(void)
  2482. {
  2483. int i;
  2484. for (i = 0; i < FETCH_WORKERS; i++)
  2485. fetch_worker_stop(&fetch_workers[i]);
  2486. }
  2487. /* Abandon the transfers of the current page but keep idle helpers and their
  2488. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  2489. * because its response would otherwise land in a reused /share slot. */
  2490. static void fetch_workers_cancel_busy(void)
  2491. {
  2492. int i;
  2493. for (i = 0; i < FETCH_WORKERS; i++)
  2494. if (fetch_workers[i].busy)
  2495. fetch_worker_stop(&fetch_workers[i]);
  2496. }
  2497. static void fetch_workers_prepare_nav(const char *url)
  2498. {
  2499. int i;
  2500. (void)url;
  2501. for (i = 0; i < FETCH_WORKERS; i++) {
  2502. struct fetch_worker *w = &fetch_workers[i];
  2503. if (w->pid <= 0)
  2504. continue;
  2505. /* Only an in-flight transfer must be aborted. Idle helpers
  2506. * stay warm across origins: there are just FETCH_WORKERS of
  2507. * them, and uhttp_open drops the old connection when the
  2508. * next job is for another host. Killing and respawning all
  2509. * four on every navigation churned processes and sockets
  2510. * while images were still loading. */
  2511. if (w->busy)
  2512. fetch_worker_stop(w);
  2513. }
  2514. }
  2515. /* The browser is no longer the active window and no fetch is running: give
  2516. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  2517. static void fetch_workers_stop_if_unfocused(void)
  2518. {
  2519. int i;
  2520. fetch_tty_drain();
  2521. if (ui.focused || page_loading || preload_active)
  2522. return;
  2523. for (i = 0; i < FETCH_WORKERS; i++)
  2524. if (fetch_workers[i].pid > 0) {
  2525. fetch_workers_stop_all();
  2526. return;
  2527. }
  2528. }
  2529. /* The helpers (and this process, since u_tty_create() rebinds our own
  2530. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  2531. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  2532. * a dozen TLS connections every helper hung in its next log line, so the
  2533. * following cross-origin navigation sat at "Loading..." until it timed out.
  2534. * Drain and discard it from every wait/poll loop. */
  2535. static void fetch_tty_drain(void)
  2536. {
  2537. char sink[512];
  2538. int i;
  2539. if (fetch_tty <= 0)
  2540. return;
  2541. for (i = 0; i < 16; i++)
  2542. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  2543. break;
  2544. }
  2545. static int fetch_worker_start(struct fetch_worker *w, char *err,
  2546. unsigned int errcap)
  2547. {
  2548. char arg[40];
  2549. unsigned int n = 0;
  2550. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  2551. return 0;
  2552. w->pid = -1;
  2553. fetch_pool_init();
  2554. if (fetch_tty == -2) {
  2555. int t = u_tty_create();
  2556. fetch_tty = t > 0 ? t : 0;
  2557. }
  2558. s_append(arg, &n, "__serve ", sizeof(arg));
  2559. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  2560. s_append(arg, &n, " ", sizeof(arg));
  2561. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  2562. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  2563. if (w->pid <= 0) {
  2564. w->pid = -1;
  2565. s_copy(err, "cannot start network helper", errcap);
  2566. return -1;
  2567. }
  2568. return 0;
  2569. }
  2570. static struct fetch_worker *fetch_worker_alloc(void)
  2571. {
  2572. int i;
  2573. fetch_pool_init();
  2574. for (i = 0; i < FETCH_WORKERS; i++)
  2575. if (!fetch_workers[i].busy)
  2576. return &fetch_workers[i];
  2577. return 0;
  2578. }
  2579. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  2580. unsigned int cap, const char *method,
  2581. const char *ctype, const char *post,
  2582. unsigned int post_len, unsigned int node,
  2583. int bg, char *err, unsigned int errcap);
  2584. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  2585. unsigned int cap, const char *post,
  2586. unsigned int post_len, unsigned int node,
  2587. int bg, char *err, unsigned int errcap)
  2588. {
  2589. /* A body pointer with no bytes is still a POST: the classic request
  2590. * line would turn it into a GET. */
  2591. if (post && !post_len)
  2592. return fetch_worker_submit_req(w, url, cap, "POST",
  2593. "application/x-www-form-urlencoded", post, 0, node,
  2594. bg, err, errcap);
  2595. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  2596. node, bg, err, errcap);
  2597. }
  2598. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  2599. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  2600. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  2601. unsigned int cap, const char *method,
  2602. const char *ctype, const char *post,
  2603. unsigned int post_len, unsigned int node,
  2604. int bg, char *err, unsigned int errcap)
  2605. {
  2606. static char req[1024];
  2607. unsigned int n = 0;
  2608. fetch_seq++;
  2609. if (!fetch_seq)
  2610. fetch_seq = 1;
  2611. w->seq = fetch_seq;
  2612. w->ready = 0;
  2613. w->image_job = 0;
  2614. w->retried = 0;
  2615. w->m.error = 0;
  2616. w->node = node;
  2617. w->bg = bg;
  2618. s_copy(w->url, url, sizeof(w->url));
  2619. s_append_dec(req, &n, w->seq, sizeof(req));
  2620. s_append(req, &n, " ", sizeof(req));
  2621. s_append_dec(req, &n, cap, sizeof(req));
  2622. s_append(req, &n, " ", sizeof(req));
  2623. if (method) {
  2624. unsigned int k;
  2625. s_append(req, &n, "X ", sizeof(req));
  2626. s_append(req, &n, method, sizeof(req));
  2627. s_append(req, &n, " ", sizeof(req));
  2628. s_append_dec(req, &n, post_len, sizeof(req));
  2629. s_append(req, &n, " ", sizeof(req));
  2630. if (!ctype || !ctype[0])
  2631. s_append(req, &n, "-", sizeof(req));
  2632. /* One token on the request line: drop the spaces
  2633. * ("application/json; charset=utf-8" stays valid). */
  2634. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  2635. if (ctype[k] != ' ')
  2636. req[n++] = ctype[k];
  2637. req[n] = '\0';
  2638. s_append(req, &n, " ", sizeof(req));
  2639. } else if (post_len) {
  2640. s_append(req, &n, "POST ", sizeof(req));
  2641. s_append_dec(req, &n, post_len, sizeof(req));
  2642. s_append(req, &n, " ", sizeof(req));
  2643. }
  2644. s_append(req, &n, url, sizeof(req));
  2645. s_append(req, &n, "\n", sizeof(req));
  2646. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  2647. (int)post, (int)post_len) < 0) {
  2648. s_copy(err, "cannot queue form body", errcap);
  2649. return -1;
  2650. }
  2651. u_syscall1(SYS_UNLINK, (int)w->done);
  2652. u_syscall1(SYS_UNLINK, (int)w->meta);
  2653. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  2654. s_copy(err, "cannot queue network request", errcap);
  2655. return -1;
  2656. }
  2657. if (fetch_worker_start(w, err, errcap) != 0)
  2658. return -1;
  2659. w->busy = 1;
  2660. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  2661. return 0;
  2662. }
  2663. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  2664. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  2665. unsigned int errcap)
  2666. {
  2667. static char meta[1024];
  2668. char *p;
  2669. int rn, mseq;
  2670. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  2671. (int)(sizeof(meta) - 1));
  2672. if (rn <= 0) {
  2673. s_copy(err, "network helper failed", errcap);
  2674. return -1;
  2675. }
  2676. meta[rn] = '\0';
  2677. p = meta;
  2678. mseq = (int)meta_uint(&p);
  2679. if (mseq != (int)w->seq) {
  2680. s_copy(err, "stale network response", errcap);
  2681. return -1;
  2682. }
  2683. w->m.status = (int)meta_uint(&p);
  2684. w->m.error = (int)meta_uint(&p);
  2685. w->m.trunc = (int)meta_uint(&p);
  2686. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  2687. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  2688. meta_str(&p, w->m.final, sizeof(w->m.final));
  2689. w->m.len = meta_uint(&p);
  2690. w->m.open_ms = 0;
  2691. w->m.first_ms = 0;
  2692. w->m.total_ms = 0;
  2693. if (*p) {
  2694. w->m.open_ms = meta_uint(&p);
  2695. w->m.first_ms = meta_uint(&p);
  2696. w->m.total_ms = meta_uint(&p);
  2697. }
  2698. if (w->m.error) {
  2699. s_copy(err, uhttp_error_string(w->m.error), errcap);
  2700. return -1;
  2701. }
  2702. w->ready = 1;
  2703. return 0;
  2704. }
  2705. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  2706. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  2707. unsigned int errcap)
  2708. {
  2709. static char done[24];
  2710. char *p;
  2711. int rn, mseq;
  2712. fetch_tty_drain();
  2713. if (!w->busy)
  2714. return -1;
  2715. if (w->ready)
  2716. return 1;
  2717. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  2718. (int)(sizeof(done) - 1));
  2719. if (rn > 0) {
  2720. done[rn] = '\0';
  2721. p = done;
  2722. mseq = (int)meta_uint(&p);
  2723. if (mseq == (int)w->seq) {
  2724. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  2725. fetch_worker_stop(w);
  2726. return -1;
  2727. }
  2728. return 1;
  2729. }
  2730. }
  2731. if (!u_alive((unsigned int)w->pid)) {
  2732. w->pid = -1;
  2733. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  2734. w->retried = 1;
  2735. return 0;
  2736. }
  2737. s_copy(err, "network helper stopped", errcap);
  2738. fetch_worker_stop(w);
  2739. return -1;
  2740. }
  2741. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  2742. s_copy(err, "network request timed out", errcap);
  2743. fetch_worker_stop(w);
  2744. return -1;
  2745. }
  2746. return 0;
  2747. }
  2748. /* Copy the completed body, inflating it if the server ignored our identity
  2749. * request. Mirrors the old fetch_remote body path. */
  2750. static int fetch_worker_read_body(struct fetch_worker *w,
  2751. unsigned char *plain,
  2752. unsigned int plaincap,
  2753. unsigned char *comp,
  2754. unsigned int compcap,
  2755. int *truncated, char *err,
  2756. unsigned int errcap)
  2757. {
  2758. int rv, zr, was_trunc;
  2759. if (contains_ci(w->m.encoding, "gzip") ||
  2760. contains_ci(w->m.encoding, "deflate")) {
  2761. unsigned int comp_len = 0, plen = 0;
  2762. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  2763. (int)compcap);
  2764. if (rv < 0) {
  2765. s_copy(err, "empty response", errcap);
  2766. return -1;
  2767. }
  2768. comp_len = (unsigned int)rv;
  2769. if (comp_len < w->m.len) {
  2770. s_copy(err, "compressed response is too large", errcap);
  2771. return -1;
  2772. }
  2773. if (contains_ci(w->m.encoding, "deflate"))
  2774. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2775. &plen, 0, &was_trunc);
  2776. else
  2777. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2778. &plen, 1, &was_trunc);
  2779. if (zr != 0) {
  2780. s_copy(err, "compressed response is corrupt", errcap);
  2781. return -1;
  2782. }
  2783. *truncated = w->m.trunc || was_trunc;
  2784. return (int)plen;
  2785. }
  2786. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  2787. if (rv < 0) {
  2788. s_copy(err, "empty response", errcap);
  2789. return -1;
  2790. }
  2791. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  2792. return rv;
  2793. }
  2794. static void fetch_worker_release(struct fetch_worker *w)
  2795. {
  2796. u_syscall1(SYS_UNLINK, (int)w->done);
  2797. u_syscall1(SYS_UNLINK, (int)w->meta);
  2798. u_syscall1(SYS_UNLINK, (int)w->body);
  2799. u_syscall1(SYS_UNLINK, (int)w->post);
  2800. u_syscall1(SYS_UNLINK, (int)w->req);
  2801. w->busy = 0;
  2802. w->ready = 0;
  2803. w->image_job = 0;
  2804. }
  2805. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  2806. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  2807. unsigned int errcap)
  2808. {
  2809. for (;;) {
  2810. int rv;
  2811. if (!fetch_wait_passive)
  2812. worker_wait_ui();
  2813. if (cancel_fetch || pending_action) {
  2814. fetch_workers_cancel_busy();
  2815. return FETCH_ABORT;
  2816. }
  2817. rv = fetch_worker_poll(w, err, errcap);
  2818. if (rv != 0)
  2819. return rv == 1 ? 0 : -1;
  2820. u_sleep_ms(10);
  2821. }
  2822. }
  2823. static int fetch_remote(const char *url, unsigned int cap,
  2824. const char *post, unsigned int post_len,
  2825. unsigned char *plain, unsigned int plaincap,
  2826. unsigned char *comp, unsigned int compcap,
  2827. struct fetch_meta *m, int *truncated,
  2828. char *err, unsigned int errcap)
  2829. {
  2830. struct fetch_worker *w = fetch_worker_alloc();
  2831. int rv;
  2832. fetch_last_error = 0;
  2833. if (!w) {
  2834. s_copy(err, "network busy", errcap);
  2835. return -1;
  2836. }
  2837. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  2838. err, errcap) != 0) {
  2839. fetch_worker_release(w);
  2840. return -1;
  2841. }
  2842. rv = fetch_worker_wait(w, err, errcap);
  2843. if (rv == FETCH_ABORT) {
  2844. fetch_worker_release(w);
  2845. return FETCH_ABORT;
  2846. }
  2847. if (rv != 0) {
  2848. fetch_last_error = w->m.error;
  2849. fetch_worker_release(w);
  2850. return -1;
  2851. }
  2852. *m = w->m;
  2853. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  2854. truncated, err, errcap);
  2855. fetch_worker_release(w);
  2856. if (rv >= 0 && (cancel_fetch || pending_action))
  2857. return FETCH_ABORT;
  2858. return rv;
  2859. }
  2860. static int fetch_worker_status(const struct fetch_worker *w)
  2861. {
  2862. return w->m.status;
  2863. }
  2864. /* fetch()/XHR through a helper: one request, the status and body come back
  2865. * whatever the HTTP status (a 401 is an answer, not a network error). */
  2866. static int js_worker_http(const char *method, const char *url,
  2867. const char *ctype, const char *body,
  2868. unsigned int body_len, struct js_http_resp *r,
  2869. char *err, int errcap)
  2870. {
  2871. struct fetch_worker *w = fetch_worker_alloc();
  2872. unsigned char *plain;
  2873. int rv, tr = 0;
  2874. if (!w) {
  2875. s_copy(err, "network busy", (unsigned int)errcap);
  2876. return -1;
  2877. }
  2878. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  2879. body_len, 0, 0, err,
  2880. (unsigned int)errcap) != 0) {
  2881. fetch_worker_release(w);
  2882. return -1;
  2883. }
  2884. fetch_wait_passive++;
  2885. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  2886. fetch_wait_passive--;
  2887. if (rv != 0) {
  2888. if (rv == FETCH_ABORT)
  2889. s_copy(err, "page is navigating", (unsigned int)errcap);
  2890. fetch_worker_release(w);
  2891. return -1;
  2892. }
  2893. r->status = w->m.status;
  2894. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  2895. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  2896. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  2897. if (!plain) {
  2898. fetch_worker_release(w);
  2899. s_copy(err, "out of memory", (unsigned int)errcap);
  2900. return -1;
  2901. }
  2902. if (w->m.len == 0) {
  2903. rv = 0; /* 204, an empty 200: no body file */
  2904. } else {
  2905. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  2906. image_io_buf, BR_PAGE_COMP_MAX,
  2907. &tr, err, (unsigned int)errcap);
  2908. }
  2909. fetch_worker_release(w);
  2910. if (rv < 0) {
  2911. free(plain);
  2912. return -1;
  2913. }
  2914. plain[rv] = '\0';
  2915. r->body = (char *)plain;
  2916. r->len = (unsigned int)rv;
  2917. return 0;
  2918. }
  2919. /* ---- HTTP / file fetch ---- */
  2920. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  2921. unsigned int *outlen, int *is_local, char *ctype,
  2922. unsigned int ctcap, char *final, unsigned int finalcap,
  2923. char *err, unsigned int errcap, int *truncated,
  2924. const char *post, unsigned int post_len)
  2925. {
  2926. unsigned char *buf;
  2927. unsigned int len;
  2928. int tr = 0;
  2929. int rv;
  2930. *out = 0;
  2931. *outlen = 0;
  2932. *truncated = 0;
  2933. if (final && finalcap)
  2934. final[0] = '\0';
  2935. if (ctype && ctcap)
  2936. ctype[0] = '\0';
  2937. if (url[0] == '/') {
  2938. char pathbuf[BR_URL_MAX];
  2939. const char *open_url = url;
  2940. unsigned int i = 0;
  2941. /* A local form GET keeps ?query in the address bar but the
  2942. * file lookup uses the path alone, like a real browser. */
  2943. while (url[i] && url[i] != '?' && url[i] != '#')
  2944. i++;
  2945. if (url[i]) {
  2946. s_copy(pathbuf, url, i + 1);
  2947. open_url = pathbuf;
  2948. }
  2949. buf = (unsigned char *)malloc(cap);
  2950. if (!buf) {
  2951. s_copy(err, "out of memory", errcap);
  2952. return -1;
  2953. }
  2954. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  2955. if (rv < 0) {
  2956. free(buf);
  2957. s_copy(err, "file not found", errcap);
  2958. return -1;
  2959. }
  2960. *out = buf;
  2961. *outlen = (unsigned int)rv;
  2962. *is_local = 1;
  2963. if (ctype)
  2964. s_copy(ctype, "text/html", ctcap);
  2965. if (final)
  2966. s_copy(final, url, finalcap);
  2967. if ((unsigned int)rv == cap)
  2968. *truncated = 1;
  2969. return 0;
  2970. }
  2971. buf = (unsigned char *)malloc(cap);
  2972. if (!buf) {
  2973. s_copy(err, "out of memory", errcap);
  2974. return -1;
  2975. }
  2976. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  2977. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  2978. if (rv == FETCH_ABORT) {
  2979. free(buf);
  2980. return FETCH_ABORT;
  2981. }
  2982. if (rv < 0) {
  2983. free(buf);
  2984. return -1;
  2985. }
  2986. len = (unsigned int)rv;
  2987. if (len == 0) {
  2988. free(buf);
  2989. s_copy(err, "empty response", errcap);
  2990. return -1;
  2991. }
  2992. if (ctype)
  2993. s_copy(ctype, fetch_meta.ctype, ctcap);
  2994. if (final && fetch_meta.final[0])
  2995. s_copy(final, fetch_meta.final, finalcap);
  2996. *is_local = 0;
  2997. *out = buf;
  2998. *outlen = len;
  2999. *truncated = tr;
  3000. return 0;
  3001. }
  3002. /* Load every @font-face the parser registered. Local files go through
  3003. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  3004. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  3005. * to the built-in regular/bold/italic/mono set. */
  3006. static void load_font_faces(void)
  3007. {
  3008. unsigned int i;
  3009. memset(font_faces, 0, sizeof(font_faces));
  3010. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  3011. i <= BR_MAX_FACES; i++) {
  3012. const char *url = br_font_face_url((int)i);
  3013. const char *base = br_font_face_base((int)i);
  3014. char abs[BR_URL_MAX];
  3015. if (!url || !url[0])
  3016. continue;
  3017. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  3018. sizeof(abs)) != 0)
  3019. continue;
  3020. if (abs[0] == '/') {
  3021. font_faces[i - 1] = ufont_face_open_path(abs);
  3022. } else if (is_http(abs)) {
  3023. unsigned char *buf;
  3024. char err[64];
  3025. int rv, tr = 0;
  3026. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  3027. if (!buf)
  3028. continue;
  3029. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3030. UFONT_MAX_FILE, image_io_buf,
  3031. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  3032. err, sizeof(err));
  3033. if (rv > 0)
  3034. font_faces[i - 1] = ufont_face_open_mem(buf,
  3035. rv);
  3036. free(buf);
  3037. }
  3038. }
  3039. }
  3040. /* Remote scripts are cached under /share for the current boot, like the
  3041. * stylesheet cache, so reloads and later visits skip the network. */
  3042. static int script_cache_count;
  3043. static unsigned int script_cache_hash(const char *s)
  3044. {
  3045. unsigned int h = 2166136261u;
  3046. while (*s) {
  3047. h ^= (unsigned char)*s++;
  3048. h *= 16777619u;
  3049. }
  3050. return h;
  3051. }
  3052. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3053. {
  3054. unsigned int n = 0;
  3055. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3056. s_append_dec(out, &n, script_cache_hash(url), cap);
  3057. }
  3058. static void script_cache_clear(void)
  3059. {
  3060. struct sys_dirent d;
  3061. char path[96];
  3062. for (;;) {
  3063. int i, found = 0;
  3064. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3065. (int)&d) == 1; i++) {
  3066. unsigned int n = 0;
  3067. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3068. continue;
  3069. s_append(path, &n, "/share/", sizeof(path));
  3070. s_append(path, &n, d.name, sizeof(path));
  3071. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3072. return;
  3073. found = 1;
  3074. break;
  3075. }
  3076. if (!found)
  3077. break;
  3078. }
  3079. script_cache_count = 0;
  3080. }
  3081. static void script_cache_init(void)
  3082. {
  3083. struct sys_dirent d;
  3084. int i, count = 0;
  3085. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3086. (int)&d) == 1; i++)
  3087. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3088. count++;
  3089. if (count >= SCRIPT_CACHE_MAX) {
  3090. script_cache_clear();
  3091. return;
  3092. }
  3093. script_cache_count = count;
  3094. }
  3095. static int script_cache_get(const char *url, unsigned char **out,
  3096. unsigned int *outlen)
  3097. {
  3098. char path[96];
  3099. struct sys_stat st;
  3100. unsigned char *buf;
  3101. int rn;
  3102. script_cache_path(url, path, sizeof(path));
  3103. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3104. st.size >= SCRIPT_CACHE_FILE_MAX)
  3105. return 0;
  3106. buf = (unsigned char *)malloc(st.size + 1);
  3107. if (!buf)
  3108. return 0;
  3109. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3110. if (rn != (int)st.size) {
  3111. free(buf);
  3112. return 0;
  3113. }
  3114. buf[st.size] = '\0';
  3115. *out = buf;
  3116. *outlen = st.size;
  3117. return 1;
  3118. }
  3119. static void script_cache_put(const char *url, const unsigned char *data,
  3120. unsigned int len)
  3121. {
  3122. char path[96];
  3123. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3124. len >= SCRIPT_CACHE_FILE_MAX)
  3125. return;
  3126. script_cache_path(url, path, sizeof(path));
  3127. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3128. (int)len) >= 0)
  3129. script_cache_count++;
  3130. }
  3131. static int script_cache_has(const char *url)
  3132. {
  3133. char path[96];
  3134. struct sys_stat st;
  3135. script_cache_path(url, path, sizeof(path));
  3136. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3137. st.size < SCRIPT_CACHE_FILE_MAX;
  3138. }
  3139. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3140. static int fetch_script_text(const char *url, unsigned char **out,
  3141. unsigned int *outlen, char *err,
  3142. unsigned int errcap)
  3143. {
  3144. unsigned char *buf;
  3145. unsigned int len;
  3146. int local, truncated = 0;
  3147. char ctype[64], final[BR_URL_MAX];
  3148. int rv;
  3149. *out = 0;
  3150. *outlen = 0;
  3151. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3152. return 0;
  3153. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3154. sizeof(ctype), final, sizeof(final), err, errcap,
  3155. &truncated, 0, 0);
  3156. if (rv != 0)
  3157. return rv;
  3158. if (truncated || len >= BR_SCRIPT_MAX) {
  3159. free(buf);
  3160. s_copy(err, "script is too large", errcap);
  3161. return -1;
  3162. }
  3163. buf[len] = '\0';
  3164. if (!local)
  3165. script_cache_put(url, buf, len);
  3166. *out = buf;
  3167. *outlen = len;
  3168. return 0;
  3169. }
  3170. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  3171. * the heap, so images must not allocate their file body from it as well. */
  3172. static int fetch_image(const char *url, unsigned int cap,
  3173. unsigned char **out, unsigned int *outlen,
  3174. char *err, unsigned int errcap)
  3175. {
  3176. unsigned int len;
  3177. int tr = 0;
  3178. int rv;
  3179. *out = 0;
  3180. *outlen = 0;
  3181. if (cap > BR_IMG_FILE_MAX)
  3182. cap = BR_IMG_FILE_MAX;
  3183. if (url[0] == '/') {
  3184. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  3185. (int)cap);
  3186. if (rv < 0) {
  3187. s_copy(err, "file not found", errcap);
  3188. return -1;
  3189. }
  3190. *out = image_file_buf;
  3191. *outlen = (unsigned int)rv;
  3192. return 0;
  3193. }
  3194. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  3195. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  3196. if (rv == FETCH_ABORT)
  3197. return FETCH_ABORT;
  3198. if (rv < 0)
  3199. return -1;
  3200. len = (unsigned int)rv;
  3201. if (len == 0) {
  3202. s_copy(err, "empty image", errcap);
  3203. return -1;
  3204. }
  3205. *out = image_file_buf;
  3206. *outlen = len;
  3207. return 0;
  3208. }
  3209. /* Remote stylesheets are immutable enough for the current boot: keep
  3210. * successful responses under /share so a reload, a second visit or a fresh
  3211. * browser launch does not fetch the same five sheets over the network again.
  3212. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  3213. static int css_cache_count;
  3214. static unsigned int css_cache_hash(const char *s)
  3215. {
  3216. unsigned int h = 2166136261u;
  3217. while (*s) {
  3218. h ^= (unsigned char)*s++;
  3219. h *= 16777619u;
  3220. }
  3221. return h;
  3222. }
  3223. static void css_cache_path(const char *url, char *out, unsigned int cap)
  3224. {
  3225. unsigned int n = 0;
  3226. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  3227. s_append_dec(out, &n, css_cache_hash(url), cap);
  3228. }
  3229. static void css_cache_clear(void)
  3230. {
  3231. struct sys_dirent d;
  3232. char path[96];
  3233. for (;;) {
  3234. int i, found = 0;
  3235. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3236. (int)&d) == 1; i++) {
  3237. unsigned int n = 0;
  3238. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  3239. continue;
  3240. s_append(path, &n, "/share/", sizeof(path));
  3241. s_append(path, &n, d.name, sizeof(path));
  3242. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3243. return;
  3244. found = 1;
  3245. break;
  3246. }
  3247. if (!found)
  3248. break;
  3249. }
  3250. css_cache_count = 0;
  3251. }
  3252. static void css_cache_init(void)
  3253. {
  3254. struct sys_dirent d;
  3255. int i, count = 0;
  3256. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3257. (int)&d) == 1; i++)
  3258. if (starts_with(d.name, CSS_CACHE_PREFIX))
  3259. count++;
  3260. if (count >= CSS_CACHE_MAX) {
  3261. css_cache_clear();
  3262. return;
  3263. }
  3264. css_cache_count = count;
  3265. }
  3266. static int css_cache_get(const char *url, unsigned char **out,
  3267. unsigned int *outlen)
  3268. {
  3269. char path[96];
  3270. int rn;
  3271. css_cache_path(url, path, sizeof(path));
  3272. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  3273. (int)CSS_CACHE_FILE_MAX);
  3274. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  3275. return 0;
  3276. *out = image_io_buf;
  3277. *outlen = (unsigned int)rn;
  3278. return 1;
  3279. }
  3280. static void css_cache_put(const char *url, const unsigned char *data,
  3281. unsigned int len)
  3282. {
  3283. char path[96];
  3284. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  3285. len >= CSS_CACHE_FILE_MAX)
  3286. return;
  3287. css_cache_path(url, path, sizeof(path));
  3288. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3289. (int)len) >= 0)
  3290. css_cache_count++;
  3291. }
  3292. static int css_cache_has(const char *url)
  3293. {
  3294. char path[96];
  3295. struct sys_stat st;
  3296. css_cache_path(url, path, sizeof(path));
  3297. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3298. st.size < CSS_CACHE_FILE_MAX;
  3299. }
  3300. /* Read one stylesheet into the shared static buffer. CSS is parsed
  3301. * immediately, so it does not need the page heap; this leaves the heap for
  3302. * the 2 MB page body, the rules and the scaled image bitmaps. */
  3303. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  3304. char *err, unsigned int errcap)
  3305. {
  3306. unsigned int len;
  3307. int tr = 0;
  3308. int rv;
  3309. *out = 0;
  3310. *outlen = 0;
  3311. if (url[0] == '/') {
  3312. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  3313. (int)BR_CSS_MAX);
  3314. if (rv < 0) {
  3315. s_copy(err, "stylesheet not found", errcap);
  3316. return -1;
  3317. }
  3318. *out = image_io_buf;
  3319. *outlen = (unsigned int)rv;
  3320. return 0;
  3321. }
  3322. if (css_cache_get(url, out, outlen))
  3323. return 0;
  3324. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  3325. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  3326. &fetch_meta, &tr, err, errcap);
  3327. if (rv == FETCH_ABORT)
  3328. return FETCH_ABORT;
  3329. if (rv < 0)
  3330. return -1;
  3331. len = (unsigned int)rv;
  3332. if (len == 0) {
  3333. s_copy(err, "empty stylesheet", errcap);
  3334. return -1;
  3335. }
  3336. *out = image_io_buf;
  3337. *outlen = len;
  3338. css_cache_put(url, image_io_buf, len);
  3339. return 0;
  3340. }
  3341. static void redraw_now(void);
  3342. static char error_page[1024];
  3343. static void show_error(const char *title, const char *detail)
  3344. {
  3345. char *page = error_page;
  3346. unsigned int n = 0;
  3347. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  3348. s_append(page, &n, title, sizeof(error_page));
  3349. s_append(page, &n, "</h2><p>", sizeof(error_page));
  3350. {
  3351. const char *p = detail;
  3352. while (*p && n + 1 < sizeof(error_page)) {
  3353. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  3354. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  3355. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  3356. else page[n++] = *p;
  3357. p++;
  3358. }
  3359. }
  3360. page[n] = '\0';
  3361. s_append(page, &n, "</p><p>", sizeof(error_page));
  3362. s_append(page, &n, page_url, sizeof(error_page));
  3363. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  3364. sizeof(error_page));
  3365. br_parse(&doc, page, n);
  3366. layout_valid = 0;
  3367. preload_active = 0;
  3368. preload_pending = 0;
  3369. preload_wait = 0;
  3370. fetch_workers_cancel_busy();
  3371. s_copy(page_title, title, sizeof(page_title));
  3372. page_loading = 0;
  3373. set_status(title, 1, 0);
  3374. ngui_invalidate(&ui);
  3375. }
  3376. static int decode_direct_image(const unsigned char *data, unsigned int len,
  3377. unsigned int node)
  3378. {
  3379. if (image_count >= BR_MAX_IMAGES)
  3380. return -1;
  3381. if (decode_image_data(data, len, &images[0], 0, 0) != 0)
  3382. return -1;
  3383. doc.nodes[node].img_index = 0;
  3384. image_count = 1;
  3385. return 0;
  3386. }
  3387. static int ancestor_is(unsigned int node, unsigned int tag)
  3388. {
  3389. unsigned int p = doc.nodes[node].parent;
  3390. while (p) {
  3391. if (doc.nodes[p].tag == tag)
  3392. return 1;
  3393. p = doc.nodes[p].parent;
  3394. }
  3395. return 0;
  3396. }
  3397. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  3398. * parallel but parsed in document order, so the cascade is unchanged. */
  3399. static int load_stylesheets(void)
  3400. {
  3401. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  3402. static unsigned char remote[BR_MAX_SHEETS];
  3403. struct fetch_worker *slot[BR_MAX_SHEETS];
  3404. unsigned int i, n = 0, next = 0, k;
  3405. char err[64];
  3406. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  3407. struct br_node *nd = &doc.nodes[i];
  3408. const char *rel, *href;
  3409. char url[BR_URL_MAX];
  3410. int dup = 0;
  3411. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  3412. continue;
  3413. rel = br_rel(&doc, i);
  3414. if (!contains_ci(rel, "stylesheet"))
  3415. continue;
  3416. href = br_href(&doc, i);
  3417. if (!href[0])
  3418. continue;
  3419. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  3420. continue;
  3421. for (k = 0; k < n; k++)
  3422. if (s_eq(urls[k], url)) {
  3423. dup = 1;
  3424. break;
  3425. }
  3426. if (dup)
  3427. continue;
  3428. s_copy(urls[n], url, BR_URL_MAX);
  3429. remote[n] = url[0] != '/' && !css_cache_has(url);
  3430. n++;
  3431. }
  3432. for (i = 0; i < BR_MAX_SHEETS; i++)
  3433. slot[i] = 0;
  3434. /* Start as many remote sheets as there are free workers. */
  3435. for (; next < n; next++) {
  3436. struct fetch_worker *w;
  3437. if (!remote[next])
  3438. continue;
  3439. w = fetch_worker_alloc();
  3440. if (!w)
  3441. break;
  3442. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  3443. err, sizeof(err)) != 0) {
  3444. fetch_worker_release(w);
  3445. remote[next] = 0;
  3446. continue;
  3447. }
  3448. slot[next] = w;
  3449. }
  3450. for (i = 0; i < n; i++) {
  3451. unsigned char *data = 0;
  3452. unsigned int len = 0;
  3453. int rv;
  3454. if (!remote[i]) {
  3455. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  3456. if (rv == FETCH_ABORT) {
  3457. fetch_workers_stop_all();
  3458. return FETCH_ABORT;
  3459. }
  3460. if (rv != 0 || !len)
  3461. continue;
  3462. } else {
  3463. struct fetch_worker *w = slot[i];
  3464. int tr = 0;
  3465. if (!w) {
  3466. w = fetch_worker_alloc();
  3467. if (!w)
  3468. continue;
  3469. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  3470. 0, 0, 0, 0, err,
  3471. sizeof(err)) != 0) {
  3472. fetch_worker_release(w);
  3473. remote[i] = 0;
  3474. if (i == next)
  3475. next++;
  3476. continue;
  3477. }
  3478. slot[i] = w;
  3479. if (i == next)
  3480. next++;
  3481. }
  3482. rv = fetch_worker_wait(w, err, sizeof(err));
  3483. if (rv == FETCH_ABORT) {
  3484. fetch_workers_stop_all();
  3485. return FETCH_ABORT;
  3486. }
  3487. if (rv == 0)
  3488. rv = fetch_worker_read_body(w, image_io_buf,
  3489. BR_CSS_MAX,
  3490. image_io_buf + BR_CSS_MAX,
  3491. BR_CSS_COMP_MAX, &tr,
  3492. err, sizeof(err));
  3493. else
  3494. rv = -1;
  3495. fetch_worker_release(w);
  3496. slot[i] = 0;
  3497. /* Refill the worker window before parsing this sheet. */
  3498. for (; next < n; next++) {
  3499. struct fetch_worker *nw;
  3500. if (!remote[next])
  3501. continue;
  3502. nw = fetch_worker_alloc();
  3503. if (!nw)
  3504. break;
  3505. if (fetch_worker_submit(nw, urls[next],
  3506. BR_CSS_MAX, 0, 0, 0, 0,
  3507. err, sizeof(err)) != 0) {
  3508. fetch_worker_release(nw);
  3509. remote[next] = 0;
  3510. continue;
  3511. }
  3512. slot[next] = nw;
  3513. }
  3514. if (rv <= 0)
  3515. continue;
  3516. len = (unsigned int)rv;
  3517. data = image_io_buf;
  3518. css_cache_put(urls[i], data, len);
  3519. }
  3520. if (len) {
  3521. br_set_font_base(urls[i]);
  3522. br_parse_css_text(&doc, (const char *)data, len);
  3523. }
  3524. }
  3525. br_set_font_base(page_url);
  3526. br_parse_inline_css(&doc);
  3527. load_font_faces();
  3528. br_reset_styles(&doc);
  3529. layout_valid = 0;
  3530. return 0;
  3531. }
  3532. static void preload_begin(void)
  3533. {
  3534. preload_active = 1;
  3535. preload_pending = 0;
  3536. preload_wait = 1;
  3537. preload_max_jobs = FETCH_WORKERS;
  3538. preload_node = 0;
  3539. preload_loaded = 0;
  3540. preload_scroll = 0;
  3541. }
  3542. /* Styles are computed top-down during layout, but images inside a hidden
  3543. * menu/carousel are never visited and keep img_top == 0. Without this check
  3544. * the preloader walks the DOM in node order and spends the whole image
  3545. * budget on logos and off-canvas thumbnails the reader cannot see. */
  3546. static int node_hidden(unsigned int node)
  3547. {
  3548. unsigned int path[32], n = 0, p = node, i;
  3549. struct br_style st, parent;
  3550. while (p && n < sizeof(path) / sizeof(path[0])) {
  3551. path[n++] = p;
  3552. p = doc.nodes[p].parent;
  3553. }
  3554. parent = (struct br_style){0};
  3555. parent.font_px = 16;
  3556. parent.display = BR_DISPLAY_BLOCK;
  3557. for (i = n; i > 0; i--) {
  3558. br_style_for(&doc, path[i - 1], &parent, &st);
  3559. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  3560. st.opacity_hidden)
  3561. return 1;
  3562. parent = st;
  3563. }
  3564. return 0;
  3565. }
  3566. static struct br_style base_style(void);
  3567. static void style_for_node(unsigned int node, struct br_style *out)
  3568. {
  3569. unsigned int p = doc.nodes[node].parent;
  3570. struct br_style parent;
  3571. if (p) {
  3572. style_for_node(p, &parent);
  3573. br_style_for(&doc, node, &parent, out);
  3574. } else {
  3575. parent = base_style();
  3576. br_style_for(&doc, node, &parent, out);
  3577. }
  3578. }
  3579. /* ---- parallel image preloading ---- *
  3580. *
  3581. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  3582. * preload_step() only starts jobs and harvests completed ones; the browser
  3583. * main loop keeps drawing between calls, instead of blocking on one fetch.
  3584. */
  3585. static int preload_active_jobs(void)
  3586. {
  3587. int i, n = 0;
  3588. for (i = 0; i < FETCH_WORKERS; i++)
  3589. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  3590. n++;
  3591. return n;
  3592. }
  3593. static void preload_job_error(struct fetch_worker *w)
  3594. {
  3595. if (w->node < doc.nnode) {
  3596. if (w->bg)
  3597. doc.nodes[w->node].bg_img_index = -2;
  3598. else
  3599. doc.nodes[w->node].img_index = -2;
  3600. ngui_invalidate(&ui);
  3601. }
  3602. }
  3603. static void preload_decode(unsigned int node, int bg,
  3604. const unsigned char *data, unsigned int len)
  3605. {
  3606. if (image_count >= BR_MAX_IMAGES) {
  3607. if (bg)
  3608. doc.nodes[node].bg_img_index = -2;
  3609. else
  3610. doc.nodes[node].img_index = -2;
  3611. return;
  3612. }
  3613. if (decode_image_data(data, len, &images[image_count],
  3614. bg && node < BR_MAX_NODES &&
  3615. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  3616. bg && node < BR_MAX_NODES &&
  3617. layout_boxes[node].valid ? layout_boxes[node].h : 0) == 0) {
  3618. if (bg)
  3619. doc.nodes[node].bg_img_index = (short)image_count;
  3620. else
  3621. doc.nodes[node].img_index = (short)image_count;
  3622. image_count++;
  3623. preload_loaded++;
  3624. layout_valid = 0;
  3625. } else {
  3626. if (bg)
  3627. doc.nodes[node].bg_img_index = -2;
  3628. else
  3629. doc.nodes[node].img_index = -2;
  3630. }
  3631. ngui_invalidate(&ui);
  3632. }
  3633. /* Harvest one completed worker. Returns 1 when a job was finished. */
  3634. static int preload_finish_worker(struct fetch_worker *w)
  3635. {
  3636. char err[64];
  3637. int rv, tr = 0;
  3638. rv = fetch_worker_poll(w, err, sizeof(err));
  3639. if (rv < 0) {
  3640. preload_job_error(w);
  3641. fetch_worker_release(w);
  3642. return 1;
  3643. }
  3644. if (rv == 0)
  3645. return 0;
  3646. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  3647. image_comp_buf, BR_IMG_FILE_MAX,
  3648. &tr, err, sizeof(err));
  3649. if (rv >= 0)
  3650. preload_decode(w->node, w->bg, image_file_buf,
  3651. (unsigned int)rv);
  3652. else
  3653. preload_job_error(w);
  3654. fetch_worker_release(w);
  3655. return 1;
  3656. }
  3657. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  3658. * the number of jobs started. */
  3659. static int preload_fill_jobs(void)
  3660. {
  3661. int started = 0;
  3662. char err[64];
  3663. while (preload_active && preload_node < doc.nnode) {
  3664. unsigned int i = preload_node;
  3665. struct br_node *nd = &doc.nodes[i];
  3666. const char *src;
  3667. char url[BR_URL_MAX];
  3668. struct fetch_worker *w;
  3669. if (preload_active_jobs() >= preload_max_jobs)
  3670. break;
  3671. if (nd->type != BR_NODE_ELEM) {
  3672. preload_node++;
  3673. continue;
  3674. }
  3675. if (nd->tag != BR_TAG_IMG) {
  3676. if (nd->bg_img_index == -1) {
  3677. struct br_style bs;
  3678. style_for_node(i, &bs);
  3679. if (bs.display != BR_DISPLAY_NONE &&
  3680. !bs.vis_hidden && bs.bg_image) {
  3681. const char *bsrc =
  3682. br_bg_image_url(bs.bg_image - 1);
  3683. /* Lazy like <img>: a background box
  3684. * below the viewport (or not laid
  3685. * out yet) waits for the next scan. */
  3686. if (bsrc[0] &&
  3687. (!layout_boxes[i].valid ||
  3688. block_top[i] >
  3689. (unsigned int)(page_scroll.offset +
  3690. page_rect.h + 160))) {
  3691. preload_pending = 1;
  3692. preload_node++;
  3693. continue;
  3694. }
  3695. if (bsrc[0] &&
  3696. !contains_ci(bsrc, ".svg") &&
  3697. !starts_with(bsrc, "data:") &&
  3698. resolve_link(page_url, bsrc, url,
  3699. sizeof(url)) == 0) {
  3700. if (image_count +
  3701. preload_active_jobs() >=
  3702. BR_MAX_IMAGES) {
  3703. preload_node = doc.nnode;
  3704. break;
  3705. }
  3706. if (url[0] == '/') {
  3707. unsigned char *data = 0;
  3708. unsigned int len = 0;
  3709. preload_node = i + 1;
  3710. if (fetch_image(url,
  3711. BR_IMG_FILE_MAX,
  3712. &data, &len,
  3713. err,
  3714. sizeof(err)) == 0)
  3715. preload_decode(i, 1, data, len);
  3716. else
  3717. nd->bg_img_index = -2;
  3718. continue;
  3719. }
  3720. w = fetch_worker_alloc();
  3721. if (!w)
  3722. return started;
  3723. preload_node = i + 1;
  3724. if (fetch_worker_submit(w, url,
  3725. BR_IMG_FILE_MAX,
  3726. 0, 0, i, 1,
  3727. err,
  3728. sizeof(err)) != 0) {
  3729. nd->bg_img_index = -2;
  3730. fetch_worker_release(w);
  3731. continue;
  3732. }
  3733. w->image_job = 1;
  3734. w->deadline = u_ticks_ms() +
  3735. BR_IMG_JOB_TIMEOUT_MS;
  3736. /* in flight: rescans skip it */
  3737. nd->bg_img_index = -3;
  3738. started++;
  3739. continue;
  3740. }
  3741. }
  3742. nd->bg_img_index = -2;
  3743. }
  3744. preload_node++;
  3745. continue;
  3746. }
  3747. if (nd->img_index != -1) {
  3748. preload_node++;
  3749. continue;
  3750. }
  3751. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  3752. preload_node++;
  3753. continue;
  3754. }
  3755. src = br_src(&doc, i);
  3756. if (!src[0] || contains_ci(src, ".svg") ||
  3757. starts_with(src, "data:")) {
  3758. preload_node++;
  3759. continue;
  3760. }
  3761. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  3762. preload_node++;
  3763. continue;
  3764. }
  3765. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  3766. preload_node = doc.nnode;
  3767. break;
  3768. }
  3769. /* Do not stop at the first below-fold image: DOM order is
  3770. * not visual order, and a footer/ad image early in the DOM
  3771. * used to hide every later article image from the loader. */
  3772. if (img_top[i] >
  3773. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  3774. preload_pending = 1;
  3775. preload_node++;
  3776. continue;
  3777. }
  3778. if (url[0] == '/') {
  3779. unsigned char *data = 0;
  3780. unsigned int len = 0;
  3781. preload_node = i + 1;
  3782. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  3783. err, sizeof(err)) == 0)
  3784. preload_decode(i, 0, data, len);
  3785. else
  3786. nd->img_index = -2;
  3787. continue;
  3788. }
  3789. w = fetch_worker_alloc();
  3790. if (!w)
  3791. return started;
  3792. preload_node = i + 1;
  3793. {
  3794. char msg[64];
  3795. unsigned int n = 0;
  3796. s_append(msg, &n, "Loading images ", sizeof(msg));
  3797. s_append_dec(msg, &n,
  3798. (unsigned int)preload_loaded + 1,
  3799. sizeof(msg));
  3800. s_append(msg, &n, "...", sizeof(msg));
  3801. set_status(msg, 0, 0);
  3802. }
  3803. if (fetch_worker_submit(w, url, BR_IMG_FILE_MAX, 0, 0, i, 0,
  3804. err, sizeof(err)) != 0) {
  3805. nd->img_index = -2;
  3806. fetch_worker_release(w);
  3807. continue;
  3808. }
  3809. w->image_job = 1;
  3810. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  3811. nd->img_index = -3; /* in flight: rescans skip it */
  3812. started++;
  3813. }
  3814. return started;
  3815. }
  3816. static void preload_step(void)
  3817. {
  3818. int i;
  3819. if (!preload_active)
  3820. return;
  3821. if (cancel_fetch || pending_action) {
  3822. preload_active = 0;
  3823. preload_pending = 0;
  3824. fetch_workers_cancel_busy();
  3825. return;
  3826. }
  3827. preload_fill_jobs();
  3828. /* Decode at most one completed image per main-loop pass. A full-size
  3829. * JPEG decode blocks this single-threaded UI for a long time, and
  3830. * harvesting a batch back-to-back starved the TCP pump (and therefore
  3831. * every other image download) on slow CPUs: requests looked stuck
  3832. * while four decodes ran in a row. */
  3833. for (i = 0; i < FETCH_WORKERS; i++) {
  3834. if (!fetch_workers[i].busy)
  3835. continue;
  3836. if (preload_finish_worker(&fetch_workers[i]))
  3837. return;
  3838. }
  3839. if (preload_active && preload_node >= doc.nnode &&
  3840. preload_active_jobs() == 0) {
  3841. preload_active = 0;
  3842. if (preload_pending)
  3843. preload_scroll = page_scroll.offset;
  3844. else
  3845. preload_pending = 0;
  3846. /* Keep the now idle helpers and their connections; a later
  3847. * navigation reuses them. They exit after ten idle seconds,
  3848. * and losing window focus stops them at once. */
  3849. set_status(post_status_text, post_status_error, post_status_ttl);
  3850. ngui_invalidate(&ui);
  3851. }
  3852. }
  3853. /* Set by navigate() when it turned a typed bare host into https://; the next
  3854. * load_page() consumes it and may retry over http. */
  3855. static int nav_https_upgraded;
  3856. /* Errors that mean "https is not served here" rather than "the site is
  3857. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  3858. static int https_fallback_error(int e)
  3859. {
  3860. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  3861. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  3862. e == UHTTP_ERR_RESET;
  3863. }
  3864. static void history_push(const char *url)
  3865. {
  3866. if (!url || !url[0])
  3867. return;
  3868. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  3869. s_eq(history[hist_pos], url))
  3870. return;
  3871. if (hist_len > 0 && hist_pos + 1 < hist_len)
  3872. hist_len = hist_pos + 1;
  3873. if (hist_len < BR_HISTORY) {
  3874. s_copy(history[hist_len], url, BR_URL_MAX);
  3875. hist_pos = hist_len;
  3876. hist_len++;
  3877. } else {
  3878. int i;
  3879. for (i = 1; i < BR_HISTORY; i++)
  3880. s_copy(history[i - 1], history[i], BR_URL_MAX);
  3881. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  3882. hist_pos = BR_HISTORY - 1;
  3883. }
  3884. }
  3885. static void load_page(const char *url, int local, int push)
  3886. {
  3887. unsigned char *body = 0;
  3888. unsigned int len = 0;
  3889. int truncated = 0;
  3890. struct img_info image_info;
  3891. char ctype[64];
  3892. char final[BR_URL_MAX];
  3893. char err[80];
  3894. const char *detail = 0;
  3895. const char *post = pending_post_is ? pending_post : 0;
  3896. unsigned int post_len = pending_post_len;
  3897. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  3898. /* Phase timings for the status line: where a slow load spends it. */
  3899. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  3900. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  3901. int upgraded = nav_https_upgraded;
  3902. int retried = 0;
  3903. int rv;
  3904. nav_https_upgraded = 0;
  3905. final[0] = '\0';
  3906. pending_post_len = 0;
  3907. pending_post_is = 0;
  3908. cancel_fetch = 0;
  3909. preload_active = 0;
  3910. preload_pending = 0;
  3911. fetch_workers_prepare_nav(url);
  3912. js_browser_stop();
  3913. js_last_status[0] = '\0';
  3914. js_last_error = 0;
  3915. heap_clear();
  3916. image_reset();
  3917. form_reset_state();
  3918. layout_valid = 0;
  3919. page_scroll.offset = 0;
  3920. page_scroll.dragging = 0;
  3921. page_title[0] = '\0';
  3922. page_loading = 1;
  3923. page_is_local = local;
  3924. s_copy(page_url, url, sizeof(page_url));
  3925. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3926. url_in.len = s_len(url_in.text);
  3927. url_in.cursor = url_in.len;
  3928. url_in.scroll = 0;
  3929. ngui_set_focus(&ui, 0);
  3930. if (final[0])
  3931. final[0] = '\0';
  3932. if (push)
  3933. history_push(url);
  3934. set_status("Loading...", 0, 0);
  3935. ngui_invalidate(&ui);
  3936. /* heap_clear() detaches the fonts, so attach them again before the
  3937. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  3938. if (heap_start() != 0) {
  3939. show_error("Out of memory", "Cannot allocate the page buffer");
  3940. return;
  3941. }
  3942. br_parse_plain(&doc, "", 0); /* blank while loading */
  3943. ngui_font_attach(&ui);
  3944. redraw_now();
  3945. browser_rules_alloc();
  3946. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  3947. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  3948. &truncated, post, post_len);
  3949. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  3950. fetch_last_error == UHTTP_ERR_DNS) {
  3951. /* A busy previous page can leave the receiver ring full just
  3952. * long enough to lose a DNS reply. Tear the old helpers down
  3953. * and try once more before giving up. */
  3954. retried = 1;
  3955. fetch_workers_stop_all();
  3956. u_sleep_ms(500);
  3957. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  3958. sizeof(ctype), final, sizeof(final), err,
  3959. sizeof(err), &truncated, post, post_len);
  3960. }
  3961. if (rv == FETCH_ABORT)
  3962. return;
  3963. t_fetch = u_ticks_ms() - t_start;
  3964. /* Capture the page timing before CSS/script/image fetches overwrite the
  3965. * shared fetch_meta block. */
  3966. if (rv == 0 && !local) {
  3967. page_open_ms = fetch_meta.open_ms;
  3968. page_first_ms = fetch_meta.first_ms;
  3969. page_total_ms = fetch_meta.total_ms;
  3970. }
  3971. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  3972. https_fallback_error(fetch_last_error)) {
  3973. char http_url[BR_URL_MAX];
  3974. unsigned int n = 0;
  3975. s_append(http_url, &n, "http://", sizeof(http_url));
  3976. s_append(http_url, &n, url + 8, sizeof(http_url));
  3977. /* Replace the https entry instead of adding a second one. */
  3978. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  3979. s_eq(history[hist_pos], url))
  3980. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  3981. load_page(http_url, 0, 0);
  3982. return;
  3983. }
  3984. if (rv != 0) {
  3985. detail = err;
  3986. show_error("Cannot load this page", detail);
  3987. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3988. url_in.len = s_len(url_in.text);
  3989. url_in.cursor = url_in.len;
  3990. url_in.scroll = 0;
  3991. return;
  3992. }
  3993. if (!local)
  3994. origin_cache_learn(url, final[0] ? final : url);
  3995. page_is_local = local;
  3996. if (final[0]) {
  3997. s_copy(page_url, final, sizeof(page_url));
  3998. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3999. url_in.len = s_len(url_in.text);
  4000. url_in.cursor = url_in.len;
  4001. url_in.scroll = 0;
  4002. }
  4003. if (contains_ci(ctype, "text/plain")) {
  4004. br_parse_plain(&doc, (const char *)body, len);
  4005. } else if (contains_ci(ctype, "image/") ||
  4006. (!contains_ci(ctype, "text/html") &&
  4007. img_sniff(body, len, &image_info) == 0)) {
  4008. unsigned int node = br_parse_image_doc(&doc, page_url);
  4009. if (node)
  4010. decode_direct_image(body, len, node);
  4011. s_copy(page_title, "Image", sizeof(page_title));
  4012. } else {
  4013. br_set_viewport(ui.w);
  4014. t_mark = u_ticks_ms();
  4015. br_parse(&doc, (const char *)body, len);
  4016. t_parse = u_ticks_ms() - t_mark;
  4017. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  4018. sizeof(page_title));
  4019. t_mark = u_ticks_ms();
  4020. if (load_stylesheets() == FETCH_ABORT)
  4021. return;
  4022. t_css = u_ticks_ms() - t_mark;
  4023. if (pending_action)
  4024. return;
  4025. }
  4026. preload_begin();
  4027. page_loading = 0;
  4028. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4029. url_in.len = s_len(url_in.text);
  4030. url_in.cursor = url_in.len;
  4031. url_in.scroll = 0;
  4032. ngui_set_focus(&ui, 0);
  4033. /* Paint the parsed page before fetching/running scripts. A slow
  4034. * remote <script src> then does not hide the page behind the loading
  4035. * screen; the fetch helper pumps this UI while it waits. */
  4036. set_status("Loading scripts...", 0, 0);
  4037. t_mark = u_ticks_ms();
  4038. redraw_now();
  4039. t_paint = u_ticks_ms() - t_mark;
  4040. /* Start one image download before the scripts. The other workers
  4041. * fetch the external script bodies in parallel, and the remaining
  4042. * images start as soon as the script phase ends. */
  4043. preload_max_jobs = 1;
  4044. preload_fill_jobs();
  4045. preload_wait = 0;
  4046. t_mark = u_ticks_ms();
  4047. run_page_scripts();
  4048. t_js = u_ticks_ms() - t_mark;
  4049. preload_max_jobs = FETCH_WORKERS;
  4050. if (pending_action)
  4051. return;
  4052. post_status_text[0] = '\0';
  4053. post_status_error = 0;
  4054. post_status_ttl = 0;
  4055. if (js_last_status[0]) {
  4056. s_copy(post_status_text, js_last_status,
  4057. sizeof(post_status_text));
  4058. post_status_error = js_last_error;
  4059. post_status_ttl = 8000;
  4060. } else if (truncated) {
  4061. s_copy(post_status_text, "Page truncated at the buffer limit",
  4062. sizeof(post_status_text));
  4063. post_status_ttl = 6000;
  4064. } else if (doc.truncated) {
  4065. s_copy(post_status_text, "Page truncated by the parser",
  4066. sizeof(post_status_text));
  4067. post_status_ttl = 6000;
  4068. } else if (page_total_ms) {
  4069. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  4070. * paint 220, js 1750" -- the phases of this load. */
  4071. unsigned int n = 0;
  4072. static const char *const names[] = {
  4073. ", parse ", ", css ", ", paint ", ", js "
  4074. };
  4075. unsigned int vals[4];
  4076. int k;
  4077. vals[0] = t_parse;
  4078. vals[1] = t_css;
  4079. vals[2] = t_paint;
  4080. vals[3] = t_js;
  4081. (void)page_first_ms;
  4082. if (starts_with(page_url, "https://"))
  4083. s_append(post_status_text, &n,
  4084. "HTTPS (not verified), ",
  4085. sizeof(post_status_text));
  4086. s_append(post_status_text, &n, "Loaded in ",
  4087. sizeof(post_status_text));
  4088. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  4089. sizeof(post_status_text));
  4090. s_append(post_status_text, &n, " ms: page ",
  4091. sizeof(post_status_text));
  4092. s_append_dec(post_status_text, &n, t_fetch,
  4093. sizeof(post_status_text));
  4094. s_append(post_status_text, &n, " (headers ",
  4095. sizeof(post_status_text));
  4096. s_append_dec(post_status_text, &n, page_open_ms,
  4097. sizeof(post_status_text));
  4098. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  4099. for (k = 0; k < 4; k++) {
  4100. s_append(post_status_text, &n, names[k],
  4101. sizeof(post_status_text));
  4102. s_append_dec(post_status_text, &n, vals[k],
  4103. sizeof(post_status_text));
  4104. }
  4105. post_status_ttl = 12000;
  4106. } else if (starts_with(page_url, "https://")) {
  4107. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  4108. sizeof(post_status_text));
  4109. post_status_ttl = 6000;
  4110. }
  4111. set_status(post_status_text, post_status_error, post_status_ttl);
  4112. ngui_invalidate(&ui);
  4113. }
  4114. static void load_home(int push)
  4115. {
  4116. pending_post_len = 0;
  4117. pending_post_is = 0;
  4118. cancel_fetch = 0;
  4119. preload_active = 0;
  4120. preload_pending = 0;
  4121. js_browser_stop();
  4122. js_last_status[0] = '\0';
  4123. js_last_error = 0;
  4124. heap_clear();
  4125. image_reset();
  4126. form_reset_state();
  4127. layout_valid = 0;
  4128. page_scroll.offset = 0;
  4129. page_scroll.dragging = 0;
  4130. page_loading = 1;
  4131. page_is_local = 0;
  4132. s_copy(page_url, "about:home", sizeof(page_url));
  4133. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4134. url_in.len = s_len(url_in.text);
  4135. url_in.cursor = url_in.len;
  4136. url_in.scroll = 0;
  4137. ngui_set_focus(&ui, 0);
  4138. if (push)
  4139. history_push(page_url);
  4140. ngui_invalidate(&ui);
  4141. /* See load_page(): reattach the fonts before the first redraw. */
  4142. if (heap_start() != 0) {
  4143. show_error("Out of memory", "Cannot allocate the browser heap");
  4144. return;
  4145. }
  4146. br_parse_plain(&doc, "", 0);
  4147. ngui_font_attach(&ui);
  4148. redraw_now();
  4149. browser_rules_alloc();
  4150. {
  4151. static const char home[] =
  4152. "<html><head><title>NebOS Browser</title><style>"
  4153. "body { margin: 10px; color: #e4e6f0; }"
  4154. "h1 { color: #7fb0ff; }"
  4155. ".box { background-color: #262b3a; margin: 12px; "
  4156. "padding: 10px; }"
  4157. "a { color: #7fb0ff; }"
  4158. "pre { background-color: #32384a; }"
  4159. "</style></head><body>"
  4160. "<h1>NebOS Browser</h1>"
  4161. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  4162. "shared HTTP client and the image library.</p>"
  4163. "<div class=\"box\"><b>Try:</b>"
  4164. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  4165. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  4166. "<li><a href=\"/floppy1/JS.HTM\">/"
  4167. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  4168. "<li><a href=\"http://10.0.2.2:8000/\">"
  4169. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  4170. "<li><a href=\"https://example.com/\">"
  4171. "https://example.com/</a> (TLS, not verified)</li>"
  4172. "</ul></div>"
  4173. "<p>Type a URL in the bar above. Esc closes the "
  4174. "window, Ctrl+L focuses the address bar.</p>"
  4175. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  4176. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  4177. "</body></html>";
  4178. br_set_viewport(ui.w);
  4179. br_parse(&doc, home, sizeof(home) - 1);
  4180. br_parse_inline_css(&doc);
  4181. br_reset_styles(&doc);
  4182. s_copy(page_title, doc.title, sizeof(page_title));
  4183. }
  4184. post_status_text[0] = '\0';
  4185. post_status_error = 0;
  4186. post_status_ttl = 0;
  4187. page_loading = 0;
  4188. set_status("", 0, 0);
  4189. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4190. url_in.len = s_len(url_in.text);
  4191. url_in.cursor = url_in.len;
  4192. url_in.scroll = 0;
  4193. ngui_set_focus(&ui, 0);
  4194. ngui_invalidate(&ui);
  4195. }
  4196. /* Extensions the browser opens from the local filesystem. A dotted input
  4197. * with one of these still resolves relative to the cwd. */
  4198. static int local_file_ext(const char *s)
  4199. {
  4200. static const char *const exts[] = {
  4201. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  4202. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  4203. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  4204. "cfg", "conf", 0
  4205. };
  4206. unsigned int i = 0, start = 0, len = 0, e;
  4207. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  4208. s[i] != '#') {
  4209. if (s[i] == '.') {
  4210. start = i + 1;
  4211. len = 0;
  4212. } else if (start) {
  4213. len++;
  4214. }
  4215. i++;
  4216. }
  4217. if (!len)
  4218. return 0;
  4219. for (e = 0; exts[e]; e++) {
  4220. const char *x = exts[e];
  4221. unsigned int xn = s_len(x), k;
  4222. if (xn != len)
  4223. continue;
  4224. for (k = 0; k < len; k++) {
  4225. char a = s[start + k];
  4226. if (a >= 'A' && a <= 'Z')
  4227. a = (char)(a - 'A' + 'a');
  4228. if (a != x[k])
  4229. break;
  4230. }
  4231. if (k == len)
  4232. return 1;
  4233. }
  4234. return 0;
  4235. }
  4236. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  4237. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  4238. * Enter to the first network request. */
  4239. static int looks_like_host(const char *s)
  4240. {
  4241. unsigned int i = 0;
  4242. int dot = 0;
  4243. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  4244. s[i] != ':') {
  4245. char c = s[i];
  4246. if (c == '.') {
  4247. dot = 1;
  4248. } else if (!((c >= 'a' && c <= 'z') ||
  4249. (c >= 'A' && c <= 'Z') ||
  4250. (c >= '0' && c <= '9') ||
  4251. c == '-' || c == '_')) {
  4252. return 0;
  4253. }
  4254. i++;
  4255. }
  4256. return dot && i > 0 && !local_file_ext(s);
  4257. }
  4258. static void load_remote(const char *url, int push)
  4259. {
  4260. char canon[BR_URL_MAX];
  4261. s_copy(canon, url, sizeof(canon));
  4262. origin_cache_apply(canon, sizeof(canon));
  4263. load_page(canon, 0, push);
  4264. }
  4265. static void navigate(const char *input, int push)
  4266. {
  4267. char target[BR_URL_MAX];
  4268. char *t;
  4269. if (!input)
  4270. return;
  4271. s_copy(target, input, sizeof(target));
  4272. t = trim(target);
  4273. if (!t[0])
  4274. return;
  4275. if (s_eq(t, "about:home")) {
  4276. load_home(push);
  4277. return;
  4278. }
  4279. if (starts_with(t, "file://")) {
  4280. make_abs_local(t + 7, target, sizeof(target));
  4281. load_page(target, 1, push);
  4282. return;
  4283. }
  4284. if (is_http(t)) {
  4285. load_remote(t, push);
  4286. return;
  4287. }
  4288. if (t[0] == '/') {
  4289. make_abs_local(t, target, sizeof(target));
  4290. load_page(target, 1, push);
  4291. return;
  4292. }
  4293. if (!looks_like_host(t)) {
  4294. struct sys_stat st;
  4295. if (u_stat(t, &st) == 0 && !st.is_dir) {
  4296. make_abs_local(t, target, sizeof(target));
  4297. load_page(target, 1, push);
  4298. return;
  4299. }
  4300. }
  4301. {
  4302. /* A typed bare host tries https first: nearly every site
  4303. * redirects http -> https anyway, and that hop costs a whole
  4304. * extra connection. load_page() falls back to http when the
  4305. * https connection itself fails. */
  4306. char with_scheme[BR_URL_MAX];
  4307. unsigned int n = 0;
  4308. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  4309. s_append(with_scheme, &n, t, sizeof(with_scheme));
  4310. nav_https_upgraded = 1;
  4311. load_remote(with_scheme, push);
  4312. }
  4313. }
  4314. /* ---- layout ---- */
  4315. static struct ufont_face *style_face(const struct br_style *st)
  4316. {
  4317. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  4318. return font_faces[st->font_face - 1];
  4319. return 0;
  4320. }
  4321. static struct ufont_face *run_face(const struct lay_run *r)
  4322. {
  4323. if (r->font_face && r->font_face <= BR_MAX_FACES)
  4324. return font_faces[r->font_face - 1];
  4325. return 0;
  4326. }
  4327. static unsigned int face_text_width(struct ngui *gui,
  4328. const struct br_style *st,
  4329. const char *s, unsigned int n)
  4330. {
  4331. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  4332. st->bold, st->italic, st->mono);
  4333. }
  4334. static int face_line_height(struct ngui *gui, const struct br_style *st)
  4335. {
  4336. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  4337. st->mono);
  4338. }
  4339. static unsigned int run_text_width(struct ngui *gui,
  4340. const struct lay_run *r,
  4341. const char *s, unsigned int n)
  4342. {
  4343. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  4344. r->bold, r->italic, r->mono);
  4345. }
  4346. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  4347. {
  4348. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  4349. r->mono);
  4350. }
  4351. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  4352. {
  4353. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  4354. }
  4355. static struct br_style base_style(void)
  4356. {
  4357. struct br_style s = { 0 };
  4358. s.color = ui.theme.text;
  4359. s.bg = ui.theme.bg;
  4360. s.has_bg = 0;
  4361. for (int i = 0; i < 4; i++) {
  4362. s.border_c[i] = 0;
  4363. s.border_w[i] = 0;
  4364. s.border_s[i] = BR_BORDER_SOLID;
  4365. }
  4366. s.font_px = 16;
  4367. s.bold = 0;
  4368. s.italic = 0;
  4369. s.mono = 0;
  4370. s.underline = 0;
  4371. s.strike = 0;
  4372. s.overline = 0;
  4373. s.align = BR_ALIGN_LEFT;
  4374. s.display = BR_DISPLAY_BLOCK;
  4375. s.no_bullet = 0;
  4376. s.list_style = BR_LIST_AUTO;
  4377. s.uppercase = 0;
  4378. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  4379. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  4380. s.width = s.max_width = s.min_width = 0;
  4381. s.height = s.min_height = s.max_height = 0;
  4382. s.box_sizing = 0;
  4383. s.ml_auto = s.mr_auto = 0;
  4384. s.line_h_pct = 0;
  4385. s.line_h_px = 0;
  4386. s.mt = s.mb = s.ml = s.mr = 0;
  4387. s.pt = s.pb = s.pl = s.pr = 0;
  4388. return s;
  4389. }
  4390. /* Resolve a margin/padding raw value. Percentages use the containing
  4391. * block width for all four sides, as CSS specifies. */
  4392. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  4393. {
  4394. if (unit == 1)
  4395. return base * v / 10000;
  4396. if (unit == 2)
  4397. return st->font_px * v / 100;
  4398. if (unit == 3)
  4399. return (int)br_root_font_px() * v / 100;
  4400. if (unit == 4)
  4401. return 0;
  4402. return v;
  4403. }
  4404. static int mp_px(const struct br_style *st, int side, int base)
  4405. {
  4406. int raw;
  4407. switch (side) {
  4408. case 0: raw = st->mt; break;
  4409. case 1: raw = st->mr; break;
  4410. case 2: raw = st->mb; break;
  4411. case 3: raw = st->ml; break;
  4412. case 4: raw = st->pt; break;
  4413. case 5: raw = st->pr; break;
  4414. case 6: raw = st->pb; break;
  4415. default: raw = st->pl; break;
  4416. }
  4417. if (st->mp_unit[side] == 5)
  4418. return base * raw / 100 + st->mp_calc_px[side];
  4419. return css_mp_px(st, raw, st->mp_unit[side], base);
  4420. }
  4421. static int style_width_px(const struct br_style *st, int base)
  4422. {
  4423. if (st->width_kind == 1)
  4424. return st->width;
  4425. if (st->width_kind == 2)
  4426. return base * (int)st->width / 100;
  4427. if (st->width_kind == 3)
  4428. return base * st->width_calc_pct / 100 + st->width_calc_px;
  4429. return 0;
  4430. }
  4431. static int style_height_px(const struct br_style *st, int base)
  4432. {
  4433. if (st->height_kind == 1)
  4434. return st->height;
  4435. if (st->height_kind == 2)
  4436. return base * (int)st->height / 100;
  4437. if (st->height_kind == 3)
  4438. return base * st->height_calc_pct / 100 + st->height_calc_px;
  4439. return 0;
  4440. }
  4441. static int css_size(unsigned char kind, int val, int base)
  4442. {
  4443. if (kind == 1)
  4444. return val;
  4445. if (kind == 2)
  4446. return base * val / 100;
  4447. return -1;
  4448. }
  4449. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  4450. int thick, int horizontal, unsigned short color,
  4451. unsigned char style)
  4452. {
  4453. int pos;
  4454. if (len <= 0 || thick <= 0)
  4455. return;
  4456. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  4457. if (horizontal)
  4458. ngui_fill_rect(ui, (struct ngui_rect){
  4459. x, y, len, thick}, color);
  4460. else
  4461. ngui_fill_rect(ui, (struct ngui_rect){
  4462. x, y, thick, len}, color);
  4463. return;
  4464. }
  4465. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  4466. int seg = len - pos;
  4467. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  4468. seg = style == BR_BORDER_DASHED ? 4 : 2;
  4469. if (horizontal)
  4470. ngui_fill_rect(ui, (struct ngui_rect){
  4471. x + pos, y, seg, thick}, color);
  4472. else
  4473. ngui_fill_rect(ui, (struct ngui_rect){
  4474. x, y + pos, thick, seg}, color);
  4475. }
  4476. }
  4477. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  4478. const struct br_style *st)
  4479. {
  4480. int top = st->border_w[0], right = st->border_w[1];
  4481. int bottom = st->border_w[2], left = st->border_w[3];
  4482. if (r.w <= 0 || r.h <= 0)
  4483. return;
  4484. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  4485. int i;
  4486. for (i = 0; i < 4; i++)
  4487. if (st->border_w[i] && !st->border_t[i]) {
  4488. ngui_fill_rect(ui, r, st->border_c[i]);
  4489. break;
  4490. }
  4491. return;
  4492. }
  4493. if (top && !st->border_t[0])
  4494. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  4495. st->border_c[0], st->border_s[0]);
  4496. if (bottom && !st->border_t[2])
  4497. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  4498. st->border_c[2], st->border_s[2]);
  4499. if (left && !st->border_t[3])
  4500. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  4501. left, 0, st->border_c[3], st->border_s[3]);
  4502. if (right && !st->border_t[1])
  4503. draw_border_side(ui, r.x + r.w - right, r.y + top,
  4504. r.h - top - bottom, right, 0,
  4505. st->border_c[1], st->border_s[1]);
  4506. }
  4507. static void transform_origin(const struct br_style *st, int w, int h,
  4508. int *ox, int *oy)
  4509. {
  4510. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  4511. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  4512. }
  4513. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  4514. unsigned int a)
  4515. {
  4516. unsigned int dr, dg, db, sr, sg, sb;
  4517. if (a >= 255)
  4518. return s;
  4519. dr = (d >> 11) & 31;
  4520. dg = (d >> 5) & 63;
  4521. db = d & 31;
  4522. sr = (s >> 11) & 31;
  4523. sg = (s >> 5) & 63;
  4524. sb = s & 31;
  4525. dr = (dr * (255 - a) + sr * a) / 255;
  4526. dg = (dg * (255 - a) + sg * a) / 255;
  4527. db = (db * (255 - a) + sb * a) / 255;
  4528. return (unsigned short)((dr << 11) | (dg << 5) | db);
  4529. }
  4530. /* Paint a solid box through scale()/rotate() around transform-origin. This
  4531. * transforms the element's own background box; text and descendants keep
  4532. * their layout (documented approximation). */
  4533. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  4534. unsigned short color,
  4535. const struct br_style *st)
  4536. {
  4537. double sx = st->scale_x / 100.0;
  4538. double sy = st->scale_y / 100.0;
  4539. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  4540. double c = cos(th), sn = sin(th);
  4541. int ox, oy, minx, miny, maxx, maxy, x, y;
  4542. double ax, ay;
  4543. double px[4], py[4];
  4544. int cx1, cy1, cx2, cy2, i;
  4545. if (sx == 0)
  4546. sx = 0.01;
  4547. if (sy == 0)
  4548. sy = 0.01;
  4549. transform_origin(st, box.w, box.h, &ox, &oy);
  4550. ax = box.x + ox;
  4551. ay = box.y + oy;
  4552. px[0] = -ox; py[0] = -oy;
  4553. px[1] = box.w - ox; py[1] = -oy;
  4554. px[2] = box.w - ox; py[2] = box.h - oy;
  4555. px[3] = -ox; py[3] = box.h - oy;
  4556. minx = miny = 1000000;
  4557. maxx = maxy = -1000000;
  4558. for (i = 0; i < 4; i++) {
  4559. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  4560. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  4561. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  4562. if (dx < minx) minx = dx;
  4563. if (dx > maxx) maxx = dx;
  4564. if (dy < miny) miny = dy;
  4565. if (dy > maxy) maxy = dy;
  4566. }
  4567. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  4568. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  4569. cx2 = page_rect.x + page_rect.w - 12;
  4570. cy2 = page_rect.y + page_rect.h;
  4571. if (cx2 > gui->w) cx2 = gui->w;
  4572. if (cy2 > gui->h) cy2 = gui->h;
  4573. if (minx < cx1) minx = cx1;
  4574. if (miny < cy1) miny = cy1;
  4575. if (maxx > cx2 - 1) maxx = cx2 - 1;
  4576. if (maxy > cy2 - 1) maxy = cy2 - 1;
  4577. for (y = miny; y <= maxy; y++) {
  4578. for (x = minx; x <= maxx; x++) {
  4579. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  4580. double rx = dx * c + dy * sn;
  4581. double ry = -dx * sn + dy * c;
  4582. double bx = rx / sx + ox;
  4583. double by = ry / sy + oy;
  4584. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  4585. gui->px[y * gui->w + x] = color;
  4586. }
  4587. }
  4588. }
  4589. static void draw_image_transformed(struct ngui *gui,
  4590. const struct img_image *im,
  4591. int x, int y, int w, int h,
  4592. int sx100, int sy100, int rot100,
  4593. int origin_x, int origin_y,
  4594. int origin_x_kind, int origin_y_kind)
  4595. {
  4596. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  4597. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  4598. double c = cos(th), sn = sin(th);
  4599. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  4600. double ax, ay;
  4601. double bx[4], by[4];
  4602. int cx1, cy1, cx2, cy2;
  4603. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  4604. return;
  4605. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  4606. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  4607. ax = x + ox;
  4608. ay = y + oy;
  4609. bx[0] = -ox; by[0] = -oy;
  4610. bx[1] = w - ox; by[1] = -oy;
  4611. bx[2] = w - ox; by[2] = h - oy;
  4612. bx[3] = -ox; by[3] = h - oy;
  4613. minx = miny = 1000000;
  4614. maxx = maxy = -1000000;
  4615. for (i = 0; i < 4; i++) {
  4616. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  4617. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  4618. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  4619. if (dx < minx) minx = dx;
  4620. if (dx > maxx) maxx = dx;
  4621. if (dy < miny) miny = dy;
  4622. if (dy > maxy) maxy = dy;
  4623. }
  4624. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  4625. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  4626. cx2 = page_rect.x + page_rect.w - 12;
  4627. cy2 = page_rect.y + page_rect.h;
  4628. if (cx2 > gui->w) cx2 = gui->w;
  4629. if (cy2 > gui->h) cy2 = gui->h;
  4630. if (minx < cx1) minx = cx1;
  4631. if (miny < cy1) miny = cy1;
  4632. if (maxx > cx2 - 1) maxx = cx2 - 1;
  4633. if (maxy > cy2 - 1) maxy = cy2 - 1;
  4634. for (py = miny; py <= maxy; py++) {
  4635. for (px = minx; px <= maxx; px++) {
  4636. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  4637. double rx = dx * c + dy * sn;
  4638. double ry = -dx * sn + dy * c;
  4639. double fx = rx / sx + ox;
  4640. double fy = ry / sy + oy;
  4641. int ix, iy;
  4642. unsigned int si, a;
  4643. unsigned short src;
  4644. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  4645. continue;
  4646. ix = (int)(fx * (double)im->w / w);
  4647. iy = (int)(fy * (double)im->h / h);
  4648. if (ix < 0 || ix >= (int)im->w ||
  4649. iy < 0 || iy >= (int)im->h)
  4650. continue;
  4651. si = (unsigned int)iy * im->w + (unsigned int)ix;
  4652. src = im->px[si];
  4653. a = im->alpha ? im->alpha[si] : 255;
  4654. gui->px[py * gui->w + px] =
  4655. a >= 255 ? src :
  4656. blend_rgb565(gui->px[py * gui->w + px],
  4657. src, a);
  4658. }
  4659. }
  4660. }
  4661. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  4662. unsigned int node, const struct br_style *st);
  4663. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  4664. * first and every pixel outside a corner's arc is restored afterwards. */
  4665. #define BG_ROUND_MAX 64
  4666. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  4667. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  4668. unsigned int node, const struct br_style *st,
  4669. int rtl, int rtr, int rbr, int rbl)
  4670. {
  4671. struct ngui *ui = l->ui;
  4672. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  4673. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  4674. if (ui->nclip > 0)
  4675. clip = ui->clip[ui->nclip - 1];
  4676. for (c = 0; c < 4; c++) {
  4677. if (r[c] > BG_ROUND_MAX)
  4678. r[c] = BG_ROUND_MAX;
  4679. if (r[c] > box.w / 2)
  4680. r[c] = box.w / 2;
  4681. if (r[c] > box.h / 2)
  4682. r[c] = box.h / 2;
  4683. }
  4684. for (c = 0; c < 4; c++) {
  4685. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  4686. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  4687. for (dy = 0; dy < r[c]; dy++)
  4688. for (dx = 0; dx < r[c]; dx++) {
  4689. int px = ox + dx, py = oy + dy;
  4690. if (px >= clip.x && py >= clip.y &&
  4691. px < clip.x + clip.w && py < clip.y + clip.h)
  4692. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  4693. ui->px[py * ui->w + px];
  4694. }
  4695. }
  4696. draw_bg_image(l, box, node, st);
  4697. for (c = 0; c < 4; c++) {
  4698. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  4699. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  4700. /* arc centre, in corner-square coordinates */
  4701. int cx = (c == 1 || c == 2) ? 0 : r[c];
  4702. int cy = (c >= 2) ? 0 : r[c];
  4703. for (dy = 0; dy < r[c]; dy++)
  4704. for (dx = 0; dx < r[c]; dx++) {
  4705. int px = ox + dx, py = oy + dy;
  4706. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  4707. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  4708. continue;
  4709. if (px >= clip.x && py >= clip.y &&
  4710. px < clip.x + clip.w && py < clip.y + clip.h)
  4711. ui->px[py * ui->w + px] =
  4712. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  4713. }
  4714. }
  4715. }
  4716. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  4717. unsigned int node, const struct br_style *st)
  4718. {
  4719. struct br_image *bi;
  4720. struct img_blit b;
  4721. int tw, th, x, y, rep_x, rep_y, posx, posy;
  4722. unsigned int scale = 65536;
  4723. int legacy, tiles = 0, rows = 0;
  4724. int cx1, cy1, cx2, cy2;
  4725. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  4726. return;
  4727. if (doc.nodes[node].bg_img_index < 0 ||
  4728. doc.nodes[node].bg_img_index >= image_count)
  4729. return;
  4730. bi = &images[doc.nodes[node].bg_img_index];
  4731. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  4732. return;
  4733. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  4734. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  4735. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  4736. if (legacy) {
  4737. scale = ((unsigned int)box.w << 16) / bi->img.w;
  4738. tw = box.w;
  4739. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  4740. x = box.x;
  4741. y = box.y;
  4742. rep_x = rep_y = 0;
  4743. } else {
  4744. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  4745. unsigned int sx = ((unsigned int)box.w << 16) /
  4746. bi->img.w;
  4747. unsigned int sy = ((unsigned int)box.h << 16) /
  4748. bi->img.h;
  4749. scale = st->bg_size_kind == 3 ?
  4750. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  4751. } else if (st->bg_size_kind == 1 ||
  4752. st->bg_size_kind == 2) {
  4753. int w = st->bg_size_w;
  4754. int h = st->bg_size_h;
  4755. if (st->bg_size_kind == 2) {
  4756. if (w)
  4757. w = box.w * w / 100;
  4758. if (h)
  4759. h = box.h * h / 100;
  4760. }
  4761. if (w)
  4762. scale = ((unsigned int)w << 16) / bi->img.w;
  4763. else if (h)
  4764. scale = ((unsigned int)h << 16) / bi->img.h;
  4765. }
  4766. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  4767. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  4768. if (tw < 1)
  4769. tw = 1;
  4770. if (th < 1)
  4771. th = 1;
  4772. posx = st->bg_pos_x_kind == 1 ?
  4773. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  4774. posy = st->bg_pos_y_kind == 1 ?
  4775. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  4776. x = box.x + posx;
  4777. y = box.y + posy;
  4778. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  4779. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  4780. if (rep_x) {
  4781. int m = (x - box.x) % tw;
  4782. if (m > 0)
  4783. m -= tw;
  4784. x = box.x + m;
  4785. }
  4786. if (rep_y) {
  4787. int m = (y - box.y) % th;
  4788. if (m > 0)
  4789. m -= th;
  4790. y = box.y + m;
  4791. }
  4792. }
  4793. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  4794. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  4795. cx2 = box.x + box.w;
  4796. cy2 = box.y + box.h;
  4797. if (cx2 > page_rect.x + page_rect.w - 12)
  4798. cx2 = page_rect.x + page_rect.w - 12;
  4799. if (cy2 > page_rect.y + page_rect.h)
  4800. cy2 = page_rect.y + page_rect.h;
  4801. if (cx1 >= cx2 || cy1 >= cy2)
  4802. return;
  4803. b.dst = l->ui->px;
  4804. b.dst_w = l->ui->w;
  4805. b.dst_h = l->ui->h;
  4806. b.clip_x = cx1;
  4807. b.clip_y = cy1;
  4808. b.clip_w = cx2 - cx1;
  4809. b.clip_h = cy2 - cy1;
  4810. b.scale = scale;
  4811. b.bg = ui.theme.bg;
  4812. b.bg2 = ui.theme.bg;
  4813. b.flags = IMG_BLIT_OVER_DST;
  4814. {
  4815. int row_x = x;
  4816. for (;;) {
  4817. for (;;) {
  4818. b.x = x;
  4819. b.y = y;
  4820. img_draw(&bi->img, &b);
  4821. if (!rep_x || ++tiles > 512)
  4822. break;
  4823. x += tw;
  4824. if (x >= box.x + box.w)
  4825. break;
  4826. }
  4827. if (!rep_y || ++rows > 64)
  4828. break;
  4829. y += th;
  4830. if (y >= box.y + box.h)
  4831. break;
  4832. x = row_x;
  4833. }
  4834. }
  4835. }
  4836. static int run_width(const struct lay_run *r)
  4837. {
  4838. if (r->img >= 0)
  4839. return r->iw;
  4840. if (r->img == -2)
  4841. return r->iw;
  4842. return (int)r->w;
  4843. }
  4844. static void start_line(struct lay *l, const struct br_style *st)
  4845. {
  4846. (void)st;
  4847. if (l->nruns == 0) {
  4848. l->line_y = l->y;
  4849. l->line_h = 0;
  4850. }
  4851. l->line_left = l->left;
  4852. l->line_right = l->right;
  4853. if (l->float_active && l->line_y < l->float_bottom) {
  4854. if (l->float_left > l->line_left)
  4855. l->line_left = l->float_left;
  4856. if (l->float_right < l->line_right)
  4857. l->line_right = l->float_right;
  4858. }
  4859. if (l->line_right < l->line_left + 8)
  4860. l->line_right = l->line_left + 8;
  4861. l->line_x = l->line_left;
  4862. l->run_x = l->line_left;
  4863. }
  4864. static void flush_line(struct lay *l)
  4865. {
  4866. int total, x, i, vis;
  4867. if (!l->nruns && l->line_x == l->line_left) {
  4868. l->line_h = 0;
  4869. return;
  4870. }
  4871. total = l->line_x - l->line_left;
  4872. x = l->line_left;
  4873. vis = 1;
  4874. if (l->draw) {
  4875. int lh = l->line_h ? l->line_h : 16;
  4876. vis = l->line_y + lh >= page_rect.y &&
  4877. l->line_y <= page_rect.y + page_rect.h;
  4878. }
  4879. if (l->align == BR_ALIGN_CENTER)
  4880. x += (l->line_right - l->line_left - total) / 2;
  4881. else if (l->align == BR_ALIGN_RIGHT)
  4882. x = l->line_right - total;
  4883. if (x < l->line_left)
  4884. x = l->line_left;
  4885. for (i = 0; i < l->nruns; i++) {
  4886. struct lay_run *r = &l->runs[i];
  4887. int w = run_width(r);
  4888. int ry = l->line_y + r->dy;
  4889. x += r->gap;
  4890. if (l->draw && vis) {
  4891. if (r->form) {
  4892. unsigned int node = r->form - 1;
  4893. struct form_state *fs = form_get(node, 1);
  4894. int hh = r->ih ? r->ih : 20;
  4895. int focused = form_focus == node;
  4896. int disabled = r->form_disabled;
  4897. unsigned short bg = l->ui->theme.panel_alt;
  4898. unsigned short fg = disabled ? 0x8410 : r->color;
  4899. struct ngui_rect box = {x, ry, w, hh};
  4900. if (r->form_kind == FORM_CHECKBOX ||
  4901. r->form_kind == FORM_RADIO) {
  4902. ngui_fill_rect(l->ui, box, bg);
  4903. ngui_frame(l->ui, box,
  4904. focused ? l->ui->theme.accent :
  4905. l->ui->theme.border);
  4906. if (fs && fs->checked) {
  4907. struct ngui_rect dot = {
  4908. x + 4, ry + 4,
  4909. w > 8 ? w - 8 : 1,
  4910. hh > 8 ? hh - 8 : 1
  4911. };
  4912. if (r->form_kind == FORM_RADIO)
  4913. ngui_fill_round_rect(
  4914. l->ui, dot, 4,
  4915. 4, 4, 4,
  4916. l->ui->theme.accent);
  4917. else
  4918. ngui_fill_rect(l->ui,
  4919. dot,
  4920. l->ui->theme.accent);
  4921. }
  4922. } else {
  4923. int editable =
  4924. r->form_kind == FORM_TEXT ||
  4925. r->form_kind == FORM_PASSWORD ||
  4926. r->form_kind == FORM_TEXTAREA;
  4927. int scroll = 0;
  4928. /* Editable fields draw the live value
  4929. * (r->lit is a short copy). */
  4930. static char shown[FORM_VALUE_MAX + 1];
  4931. const char *txt = r->lit;
  4932. unsigned int tl = s_len(r->lit);
  4933. if (editable && fs && fs->len) {
  4934. unsigned int k;
  4935. if (r->form_kind == FORM_PASSWORD) {
  4936. for (k = 0; k < fs->len; k++)
  4937. shown[k] = '*';
  4938. shown[k] = '\0';
  4939. txt = shown;
  4940. } else {
  4941. txt = fs->value;
  4942. }
  4943. tl = fs->len;
  4944. }
  4945. /* The box is drawn in theme colours, so
  4946. * the text is too: the page's CSS colour
  4947. * (dark on a light page) would vanish on
  4948. * the dark field. */
  4949. if (!disabled)
  4950. fg = editable && fs && !fs->len ?
  4951. l->ui->theme.text_dim :
  4952. l->ui->theme.text;
  4953. ngui_fill_rect(l->ui, box, bg);
  4954. ngui_frame(l->ui, box,
  4955. focused ? l->ui->theme.accent :
  4956. l->ui->theme.border);
  4957. /* A value wider than the field shows its
  4958. * tail (where typing happens). */
  4959. if (editable && w > 12) {
  4960. int tw = (int)run_text_width(l->ui,
  4961. r, txt, tl);
  4962. if (tw > w - 12)
  4963. scroll = tw - (w - 12);
  4964. }
  4965. ngui_push_clip(l->ui, (struct ngui_rect){
  4966. x + 1, ry + 1,
  4967. w > 2 ? w - 2 : 1,
  4968. hh > 2 ? hh - 2 : 1 });
  4969. ngui_text_px_face(l->ui, run_face(r),
  4970. x + 6 - scroll,
  4971. ry + (hh - r->font_px) / 2 - 1,
  4972. txt, tl, fg, r->font_px,
  4973. r->bold, r->italic, r->mono);
  4974. if (focused && fs && editable) {
  4975. int cw = 0;
  4976. if (fs->len && fs->caret)
  4977. cw = (int)run_text_width(
  4978. l->ui, r, txt,
  4979. fs->caret < fs->len ?
  4980. fs->caret : fs->len);
  4981. ngui_fill_rect(l->ui,
  4982. (struct ngui_rect){
  4983. x + 6 + cw - scroll,
  4984. ry + 4, 1,
  4985. hh > 8 ? hh - 8 : 1
  4986. },
  4987. l->ui->theme.accent);
  4988. }
  4989. ngui_pop_clip(l->ui);
  4990. if (r->form_kind == FORM_SELECT) {
  4991. ngui_text_px(l->ui, x + w - 12,
  4992. ry + 2, "v", 1, fg,
  4993. r->font_px, 0, 0, 0);
  4994. }
  4995. }
  4996. } else if (r->img == -2) {
  4997. int hh = r->ih ? r->ih : 20;
  4998. ngui_fill_rect(l->ui,
  4999. (struct ngui_rect){x, ry, w, hh},
  5000. l->ui->theme.panel_alt);
  5001. ngui_frame(l->ui,
  5002. (struct ngui_rect){x, ry, w, hh},
  5003. l->ui->theme.border);
  5004. ngui_text_px_face(l->ui, run_face(r),
  5005. x + 6, ry + 2, r->lit,
  5006. s_len(r->lit), r->color,
  5007. r->font_px, r->bold, r->italic,
  5008. r->mono);
  5009. } else if (r->img >= 0) {
  5010. struct br_image *bi = &images[r->img];
  5011. if (bi->state == 1 && r->transform_scale) {
  5012. draw_image_transformed(l->ui, &bi->img,
  5013. x, ry, r->iw, r->ih,
  5014. r->scale_x, r->scale_y,
  5015. r->rotate_x100, r->origin_x,
  5016. r->origin_y, r->origin_x_kind,
  5017. r->origin_y_kind);
  5018. } else if (bi->state == 1) {
  5019. struct img_blit b;
  5020. b.dst = l->ui->px;
  5021. b.dst_w = l->ui->w;
  5022. b.dst_h = l->ui->h;
  5023. b.clip_x = page_rect.x;
  5024. b.clip_y = page_rect.y;
  5025. b.clip_w = page_rect.w - 12;
  5026. b.clip_h = page_rect.h;
  5027. b.x = x;
  5028. b.y = ry;
  5029. b.scale = ((unsigned int)r->iw << 16) /
  5030. bi->img.w;
  5031. b.bg = ui.theme.bg;
  5032. b.bg2 = ui.theme.bg;
  5033. b.flags = IMG_BLIT_OVER_DST;
  5034. img_draw(&bi->img, &b);
  5035. }
  5036. } else {
  5037. const char *s = r->has_lit ? r->lit :
  5038. doc.text + r->off;
  5039. unsigned int n = r->has_lit ? s_len(r->lit) :
  5040. r->len;
  5041. ngui_text_px_face(l->ui, run_face(r), x, ry,
  5042. s, n, r->color, r->font_px,
  5043. r->bold, r->italic, r->mono);
  5044. if (r->underline)
  5045. ngui_fill_rect(l->ui,
  5046. (struct ngui_rect){x,
  5047. ry + run_ascent(l->ui, r) + 2,
  5048. w, 1}, r->color);
  5049. if (r->strike)
  5050. ngui_fill_rect(l->ui,
  5051. (struct ngui_rect){x,
  5052. ry + run_ascent(l->ui, r) -
  5053. (r->font_px > 3 ?
  5054. r->font_px / 3 : 1),
  5055. w, 1}, r->color);
  5056. if (r->overline)
  5057. ngui_fill_rect(l->ui,
  5058. (struct ngui_rect){x, ry,
  5059. w, 1}, r->color);
  5060. }
  5061. if (r->form || r->href) {
  5062. if (nhits < HIT_MAX) {
  5063. struct hit *h = &hits[nhits];
  5064. unsigned int target = r->form ?
  5065. r->form - 1 : r->href;
  5066. int hh = (r->form || r->img >= 0) ?
  5067. r->ih :
  5068. run_line_height(l->ui, r);
  5069. int merge = nhits > 0 &&
  5070. hits[nhits - 1].node == target &&
  5071. hits[nhits - 1].y == ry &&
  5072. hits[nhits - 1].h == hh &&
  5073. x <= hits[nhits - 1].x +
  5074. hits[nhits - 1].w + 2;
  5075. if (merge) {
  5076. struct hit *p = &hits[nhits - 1];
  5077. int end = x + w;
  5078. if (end > p->x + p->w)
  5079. p->w = end - p->x;
  5080. } else {
  5081. h->x = x;
  5082. h->y = ry;
  5083. h->w = w;
  5084. h->h = hh;
  5085. h->node = (unsigned short)target;
  5086. nhits++;
  5087. }
  5088. }
  5089. }
  5090. }
  5091. x += w;
  5092. }
  5093. l->y += l->line_h + 2;
  5094. if (l->float_active && l->y >= l->float_bottom)
  5095. l->float_active = 0;
  5096. l->nruns = 0;
  5097. l->line_x = l->left;
  5098. l->run_x = l->left;
  5099. l->line_left = l->left;
  5100. l->line_right = l->right;
  5101. l->line_h = 0;
  5102. l->space_pending = 0;
  5103. }
  5104. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  5105. const struct br_style *st, unsigned short href,
  5106. const char *lit)
  5107. {
  5108. unsigned int n = lit ? s_len(lit) : len;
  5109. const char *tp = lit ? lit : doc.text + off;
  5110. int w = (int)face_text_width(l->ui, st, tp, n);
  5111. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  5112. flush_line(l);
  5113. if (l->nruns == 0) {
  5114. l->line_y = l->y;
  5115. l->line_h = 0;
  5116. start_line(l, st);
  5117. }
  5118. {
  5119. struct lay_run *r = &l->runs[l->nruns++];
  5120. int gap = l->line_x - l->run_x;
  5121. if (gap < 0)
  5122. gap = 0;
  5123. r->gap = (unsigned short)gap;
  5124. r->off = off;
  5125. r->len = len;
  5126. r->color = st->color;
  5127. r->href = href;
  5128. r->dy = 0;
  5129. r->has_lit = 0;
  5130. r->form = 0;
  5131. r->form_kind = 0;
  5132. r->form_disabled = 0;
  5133. r->lit[0] = '\0';
  5134. if (lit && lit[0]) {
  5135. unsigned int i;
  5136. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  5137. r->lit[i] = lit[i];
  5138. r->lit[i] = '\0';
  5139. r->has_lit = 1;
  5140. }
  5141. r->img = -1;
  5142. r->iw = r->ih = 0;
  5143. r->font_px = st->font_px;
  5144. r->bold = st->bold;
  5145. r->italic = st->italic;
  5146. r->mono = st->mono;
  5147. r->font_face = st->font_face;
  5148. /* A control with its own background is a button, not body copy;
  5149. * an inherited link underline would strike through the fill. */
  5150. r->underline = st->underline && !st->has_bg;
  5151. r->strike = st->strike && !st->has_bg;
  5152. r->overline = st->overline && !st->has_bg;
  5153. r->w = (unsigned short)w;
  5154. if (r->has_lit)
  5155. r->w = (unsigned short)run_text_width(
  5156. l->ui, r, r->lit, s_len(r->lit));
  5157. w = r->w;
  5158. }
  5159. l->line_x += w;
  5160. l->run_x = l->line_x;
  5161. {
  5162. int lh = face_line_height(l->ui, st);
  5163. if (st->line_h_px)
  5164. lh = st->line_h_px;
  5165. else if (st->line_h_pct)
  5166. lh = st->font_px * st->line_h_pct / 100;
  5167. if (lh < face_line_height(l->ui, st))
  5168. lh = face_line_height(l->ui, st);
  5169. if (l->line_h < lh)
  5170. l->line_h = lh;
  5171. }
  5172. }
  5173. static void add_image_run(struct lay *l, unsigned int node,
  5174. const struct br_style *st, unsigned short href)
  5175. {
  5176. struct br_image *bi = 0;
  5177. int idx = doc.nodes[node].img_index;
  5178. int dw, dh, maxw;
  5179. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  5180. bi = &images[idx];
  5181. if (l->nruns == 0)
  5182. start_line(l, st);
  5183. if (l->space_pending &&
  5184. (l->nruns > 0 || l->line_x > l->line_left)) {
  5185. int sp = (int)face_text_width(l->ui, st, " ", 1);
  5186. if (l->line_x + sp <= l->line_right)
  5187. l->line_x += sp;
  5188. }
  5189. l->space_pending = 0;
  5190. if (!bi) {
  5191. const char *alt = br_alt(&doc, node);
  5192. struct br_style gs = *st;
  5193. char tmp[96];
  5194. unsigned int n = 0;
  5195. int w;
  5196. gs.color = BR_GRAY;
  5197. gs.underline = 0;
  5198. s_append(tmp, &n, "[", sizeof(tmp));
  5199. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  5200. s_append(tmp, &n, "]", sizeof(tmp));
  5201. w = (int)face_text_width(l->ui, &gs, tmp, n);
  5202. if (l->line_x + w > l->line_right &&
  5203. (l->nruns > 0 || l->line_x > l->line_left))
  5204. flush_line(l);
  5205. add_run(l, 0, 0, &gs, href, tmp);
  5206. if (!l->draw) {
  5207. int t = l->line_y < 0 ? 0 : l->line_y;
  5208. int hh = face_line_height(l->ui, &gs);
  5209. if (t > 65535)
  5210. t = 65535;
  5211. if (hh > 65535)
  5212. hh = 65535;
  5213. img_top[node] = (unsigned short)t;
  5214. img_h[node] = (unsigned short)hh;
  5215. }
  5216. return;
  5217. }
  5218. maxw = l->line_right - l->line_left;
  5219. if (maxw < 8)
  5220. maxw = 8;
  5221. {
  5222. int iw = bi->native_w, ih = bi->native_h;
  5223. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  5224. if (iw <= 0 || ih <= 0) {
  5225. iw = (int)bi->img.w;
  5226. ih = (int)bi->img.h;
  5227. }
  5228. dw = iw;
  5229. dh = ih;
  5230. if (doc.nodes[node].width_attr) {
  5231. int want = doc.nodes[node].width_attr;
  5232. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  5233. have_w = 1;
  5234. }
  5235. if (doc.nodes[node].height_attr) {
  5236. int want = doc.nodes[node].height_attr;
  5237. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  5238. have_h = 1;
  5239. }
  5240. if (have_w && !have_h)
  5241. dh = ih ? ih * dw / iw : 0;
  5242. if (have_h && !have_w)
  5243. dw = iw ? iw * dh / ih : 0;
  5244. if (st->width_kind) {
  5245. css_w = 1;
  5246. if (st->width_kind == 3)
  5247. dw = maxw * st->width_calc_pct / 100 +
  5248. st->width_calc_px;
  5249. else
  5250. dw = st->width_kind == 2 ?
  5251. maxw * (int)st->width / 100 :
  5252. (int)st->width;
  5253. }
  5254. if (st->height_kind) {
  5255. css_h = 1;
  5256. if (st->height_kind == 3)
  5257. dh = maxw * st->height_calc_pct / 100 +
  5258. st->height_calc_px;
  5259. else
  5260. dh = st->height_kind == 2 ?
  5261. maxw * (int)st->height / 100 :
  5262. (int)st->height;
  5263. }
  5264. if (css_w && !css_h)
  5265. dh = ih ? ih * dw / iw : 0;
  5266. if (css_h && !css_w)
  5267. dw = iw ? iw * dh / ih : 0;
  5268. if (st->max_width_kind) {
  5269. int mw = st->max_width_kind == 3 ?
  5270. maxw * st->max_width_calc_pct / 100 +
  5271. st->max_width_calc_px :
  5272. st->max_width_kind == 2 ?
  5273. maxw * (int)st->max_width / 100 :
  5274. (int)st->max_width;
  5275. if (mw > 0 && dw > mw) {
  5276. dh = iw ? ih * mw / iw : 0;
  5277. dw = mw;
  5278. }
  5279. }
  5280. }
  5281. if (dw < 8)
  5282. dw = 8;
  5283. if (dh < 8)
  5284. dh = 8;
  5285. if (dw > maxw) {
  5286. dh = dw ? dh * maxw / dw : dh;
  5287. dw = maxw;
  5288. }
  5289. if (!l->draw) {
  5290. int t = l->line_y < 0 ? 0 : l->line_y;
  5291. if (t > 65535)
  5292. t = 65535;
  5293. if (dh > 65535)
  5294. dh = 65535;
  5295. img_top[node] = (unsigned short)t;
  5296. img_h[node] = (unsigned short)dh;
  5297. }
  5298. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  5299. l->line_x > l->line_left))
  5300. flush_line(l);
  5301. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  5302. flush_line(l);
  5303. if (l->nruns == 0) {
  5304. l->line_y = l->y;
  5305. l->line_h = 0;
  5306. start_line(l, st);
  5307. }
  5308. {
  5309. struct lay_run *r = &l->runs[l->nruns++];
  5310. int gap = l->line_x - l->run_x;
  5311. if (gap < 0)
  5312. gap = 0;
  5313. r->gap = (unsigned short)gap;
  5314. r->off = 0;
  5315. r->len = 0;
  5316. r->color = 0;
  5317. r->href = href;
  5318. r->form = 0;
  5319. r->form_kind = 0;
  5320. r->form_disabled = 0;
  5321. /* Inline replaced elements honour their vertical margins; this
  5322. * is how Bootstrap's negative logo margins centre the wordmark. */
  5323. {
  5324. int idy = mp_px(st, 0, l->right - l->left);
  5325. if (idy < -2048)
  5326. idy = -2048;
  5327. if (idy > 2048)
  5328. idy = 2048;
  5329. r->dy = (signed short)idy;
  5330. }
  5331. r->has_lit = 0;
  5332. r->lit[0] = '\0';
  5333. r->img = (short)idx;
  5334. r->iw = (unsigned short)dw;
  5335. r->ih = (unsigned short)dh;
  5336. r->w = (unsigned short)dw;
  5337. r->font_px = st->font_px;
  5338. r->bold = st->bold;
  5339. r->italic = st->italic;
  5340. r->mono = st->mono;
  5341. r->font_face = st->font_face;
  5342. r->transform_scale = st->transform_scale;
  5343. r->scale_x = st->scale_x;
  5344. r->scale_y = st->scale_y;
  5345. r->rotate_x100 = st->rotate_x100;
  5346. r->origin_x = st->origin_x;
  5347. r->origin_y = st->origin_y;
  5348. r->origin_x_kind = st->origin_x_kind;
  5349. r->origin_y_kind = st->origin_y_kind;
  5350. r->underline = 0;
  5351. }
  5352. if (node < BR_MAX_NODES) {
  5353. layout_boxes[node].x = l->line_x;
  5354. layout_boxes[node].y = l->line_y +
  5355. mp_px(st, 0, l->right - l->left);
  5356. layout_boxes[node].w = dw;
  5357. layout_boxes[node].h = dh;
  5358. layout_boxes[node].valid = 1;
  5359. }
  5360. l->line_x += dw;
  5361. l->run_x = l->line_x;
  5362. if (l->line_h < dh)
  5363. l->line_h = dh;
  5364. }
  5365. static int text_width(struct lay *l, const char *s, unsigned int n,
  5366. const struct br_style *st)
  5367. {
  5368. return (int)face_text_width(l->ui, st, s, n);
  5369. }
  5370. /* Longest prefix that fits in maxw, at least one byte. */
  5371. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  5372. const struct br_style *st, int maxw)
  5373. {
  5374. unsigned int take = 0;
  5375. while (take < n) {
  5376. if (text_width(l, s, take + 1, st) > maxw)
  5377. break;
  5378. take++;
  5379. }
  5380. return take ? take : 1;
  5381. }
  5382. static void emit_word(struct lay *l, const char *s, unsigned int start,
  5383. unsigned int n, unsigned int base,
  5384. const struct br_style *st, unsigned short href)
  5385. {
  5386. int avail;
  5387. int w = text_width(l, s + start, n, st);
  5388. unsigned int off = start;
  5389. if (l->nruns == 0)
  5390. start_line(l, st);
  5391. avail = l->line_right - l->line_left;
  5392. if (st->nowrap) {
  5393. if (n)
  5394. add_run(l, base + start,
  5395. (unsigned short)n, st, href, 0);
  5396. return;
  5397. }
  5398. /* A padded/bordered one-word button can be a few pixels wider than
  5399. * the content box; keep it on one line instead of splitting it. */
  5400. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  5401. add_run(l, base + start,
  5402. (unsigned short)n, st, href, 0);
  5403. return;
  5404. }
  5405. if (l->line_x + w > l->line_right &&
  5406. (l->nruns > 0 || l->line_x > l->line_left)) {
  5407. flush_line(l);
  5408. start_line(l, st);
  5409. avail = l->line_right - l->line_left;
  5410. }
  5411. if (w <= avail) {
  5412. if (n)
  5413. add_run(l, base + start,
  5414. (unsigned short)n, st, href, 0);
  5415. return;
  5416. }
  5417. while (n > 0) {
  5418. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  5419. add_run(l, base + off,
  5420. (unsigned short)take, st, href, 0);
  5421. off += take;
  5422. n -= take;
  5423. if (n) {
  5424. flush_line(l);
  5425. start_line(l, st);
  5426. avail = l->line_right - l->line_left;
  5427. }
  5428. }
  5429. }
  5430. static void emit_text(struct lay *l, const char *s, unsigned int len,
  5431. const struct br_style *st, unsigned short href, int pre)
  5432. {
  5433. unsigned int i = 0;
  5434. unsigned int base;
  5435. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  5436. if (!s || !len)
  5437. return;
  5438. if (space_w <= 0)
  5439. space_w = 8;
  5440. if (l->nruns == 0)
  5441. start_line(l, st);
  5442. base = (unsigned int)(s - doc.text);
  5443. if (st->uppercase) {
  5444. char *p = (char *)s;
  5445. unsigned int j;
  5446. for (j = 0; j < len; j++)
  5447. if (p[j] >= 'a' && p[j] <= 'z')
  5448. p[j] = (char)(p[j] - 'a' + 'A');
  5449. }
  5450. if (pre) {
  5451. while (i < len) {
  5452. unsigned int start;
  5453. if (s[i] == '\n') {
  5454. flush_line(l);
  5455. start_line(l, st);
  5456. i++;
  5457. continue;
  5458. }
  5459. if (s[i] == ' ') {
  5460. if (l->line_x + space_w > l->line_right &&
  5461. (l->nruns > 0 || l->line_x > l->line_left)) {
  5462. flush_line(l);
  5463. start_line(l, st);
  5464. } else {
  5465. l->line_x += space_w;
  5466. }
  5467. i++;
  5468. continue;
  5469. }
  5470. start = i;
  5471. while (i < len && s[i] != ' ' && s[i] != '\n')
  5472. i++;
  5473. emit_word(l, s, start, i - start, base, st, href);
  5474. }
  5475. return;
  5476. }
  5477. while (i < len) {
  5478. unsigned int start, n;
  5479. if (s[i] == ' ') {
  5480. l->space_pending = 1;
  5481. i++;
  5482. continue;
  5483. }
  5484. start = i;
  5485. while (i < len && s[i] != ' ')
  5486. i++;
  5487. n = i - start;
  5488. if (l->space_pending &&
  5489. (l->nruns > 0 || l->line_x > l->line_left)) {
  5490. if (st->nowrap ||
  5491. l->line_x + space_w <= l->line_right)
  5492. l->line_x += space_w;
  5493. }
  5494. l->space_pending = 0;
  5495. emit_word(l, s, start, n, base, st, href);
  5496. }
  5497. }
  5498. static int list_index(unsigned int parent, unsigned int node)
  5499. {
  5500. unsigned int n = 0, i;
  5501. for (i = doc.nodes[parent].first; i && i != node;
  5502. i = doc.nodes[i].next)
  5503. if (doc.nodes[i].tag == BR_TAG_LI)
  5504. n++;
  5505. return (int)n + 1;
  5506. }
  5507. static void list_roman(char *m, unsigned int *n, int v, int upper,
  5508. unsigned int cap)
  5509. {
  5510. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  5511. 50, 40, 10, 9, 5, 4, 1 };
  5512. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  5513. "l", "xl", "x", "ix", "v", "iv", "i" };
  5514. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  5515. "L", "XL", "X", "IX", "V", "IV", "I" };
  5516. unsigned int i;
  5517. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  5518. while (v >= val[i] && *n + 1 < cap) {
  5519. const char *s = upper ? up[i] : lo[i];
  5520. while (*s && *n + 1 < cap)
  5521. m[(*n)++] = *s++;
  5522. v -= val[i];
  5523. }
  5524. }
  5525. }
  5526. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  5527. {
  5528. unsigned int n = 0;
  5529. if (style == BR_LIST_DISC) {
  5530. m[n++] = '-';
  5531. } else if (style == BR_LIST_CIRCLE) {
  5532. m[n++] = 'o';
  5533. } else if (style == BR_LIST_SQUARE) {
  5534. m[n++] = '+';
  5535. } else if (style == BR_LIST_LOWER_ALPHA ||
  5536. style == BR_LIST_UPPER_ALPHA) {
  5537. if (idx >= 1 && idx <= 26)
  5538. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  5539. 'A' : 'a') + idx - 1);
  5540. else
  5541. m[n++] = '?';
  5542. m[n++] = '.';
  5543. } else if (style == BR_LIST_LOWER_ROMAN ||
  5544. style == BR_LIST_UPPER_ROMAN) {
  5545. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  5546. if (n + 1 < cap)
  5547. m[n++] = '.';
  5548. } else {
  5549. s_append_dec(m, &n, (unsigned int)idx, cap);
  5550. if (n + 1 < cap)
  5551. m[n++] = '.';
  5552. }
  5553. m[n] = '\0';
  5554. }
  5555. /* Set by the layout when the control is stretched to its line: a flex item
  5556. * (its box width was assigned by the flex row) or a child of a flex column,
  5557. * whose default align-items: stretch makes inputs full width. */
  5558. static int form_fill_line;
  5559. static void add_form_run(struct lay *l, unsigned int node,
  5560. const struct br_style *st, unsigned short href)
  5561. {
  5562. struct form_state *fs = form_get(node, 1);
  5563. char shown[FORM_VALUE_MAX + 1];
  5564. char opt[64];
  5565. const char *text = "";
  5566. struct lay_run *r;
  5567. int kind = form_kind_of(node);
  5568. int disabled = form_disabled(node);
  5569. int tw, w = 120, h = 20, i;
  5570. if (!fs)
  5571. return;
  5572. if (l->nruns == 0)
  5573. start_line(l, st);
  5574. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  5575. text = "";
  5576. w = 16;
  5577. h = 16;
  5578. } else if (kind == FORM_SELECT) {
  5579. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  5580. s_copy(opt, "Select", sizeof(opt));
  5581. text = opt;
  5582. w = 120;
  5583. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  5584. kind == FORM_RESET) {
  5585. if (fs->len)
  5586. text = fs->value;
  5587. else
  5588. text = kind == FORM_SUBMIT ? "Submit" :
  5589. kind == FORM_RESET ? "Reset" : "Button";
  5590. } else if (kind == FORM_PASSWORD) {
  5591. for (i = 0; i < fs->len; i++)
  5592. shown[i] = '*';
  5593. shown[fs->len] = '\0';
  5594. text = fs->len ? shown : br_placeholder(&doc, node);
  5595. } else {
  5596. if (fs->len)
  5597. text = fs->value;
  5598. else
  5599. text = br_placeholder(&doc, node);
  5600. if (kind == FORM_TEXTAREA) {
  5601. w = 180;
  5602. h = 40;
  5603. }
  5604. }
  5605. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  5606. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  5607. w = tw + 18;
  5608. if (w < 64)
  5609. w = 64;
  5610. h = 22;
  5611. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD) {
  5612. int line_w = l->line_right - l->line_left;
  5613. if (st->width_kind == 1)
  5614. w = st->width;
  5615. else if (st->width_kind == 2)
  5616. w = css_size(st->width_kind, st->width, line_w);
  5617. else if (form_fill_line || st->display == BR_DISPLAY_BLOCK)
  5618. w = line_w - (l->line_x - l->line_left);
  5619. else
  5620. w = 120;
  5621. /* Taller fields for large text (min-height/padding on login
  5622. * pages): keep the box around the glyphs. */
  5623. if (st->font_px + 8 > h)
  5624. h = st->font_px + 8;
  5625. } else if (kind == FORM_SELECT) {
  5626. w = st->width_kind == 1 ? st->width : 120;
  5627. }
  5628. if (w > l->line_right - l->line_left)
  5629. w = l->line_right - l->line_left;
  5630. if (w < 8)
  5631. w = 8;
  5632. if (l->line_x + w > l->line_right &&
  5633. (l->nruns > 0 || l->line_x > l->line_left))
  5634. flush_line(l);
  5635. if (l->nruns >= 96)
  5636. return;
  5637. if (l->nruns == 0) {
  5638. l->line_y = l->y;
  5639. l->line_h = 0;
  5640. start_line(l, st);
  5641. }
  5642. r = &l->runs[l->nruns++];
  5643. r->gap = (unsigned short)(l->line_x - l->run_x);
  5644. r->off = r->len = 0;
  5645. r->color = st->color;
  5646. r->href = href;
  5647. r->dy = 0;
  5648. r->has_lit = 1;
  5649. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  5650. r->lit[i] = text[i];
  5651. r->lit[i] = '\0';
  5652. r->img = -2;
  5653. r->iw = (unsigned short)w;
  5654. r->ih = (unsigned short)h;
  5655. r->w = (unsigned short)w;
  5656. r->font_px = st->font_px;
  5657. r->bold = st->bold;
  5658. r->italic = st->italic;
  5659. r->mono = st->mono;
  5660. r->font_face = st->font_face;
  5661. r->underline = 0;
  5662. r->form = node + 1;
  5663. r->form_kind = (unsigned char)kind;
  5664. r->form_disabled = (unsigned char)disabled;
  5665. if (node < BR_MAX_NODES) {
  5666. layout_boxes[node].x = l->line_x;
  5667. layout_boxes[node].y = l->line_y;
  5668. layout_boxes[node].w = w;
  5669. layout_boxes[node].h = h;
  5670. layout_boxes[node].valid = 1;
  5671. }
  5672. l->line_x += w;
  5673. l->run_x = l->line_x;
  5674. if (l->line_h < h)
  5675. l->line_h = h;
  5676. }
  5677. /* A poster wrapper is absolutely positioned over the media slot; the
  5678. * measured height of its picture is normally added back to the flow. When a
  5679. * loading-skeleton sibling already reserves that slot, adding both doubles
  5680. * the media height and pushes the article text a full screen down. */
  5681. static int has_skeleton_sibling(unsigned int node)
  5682. {
  5683. unsigned int p = doc.nodes[node].parent, c;
  5684. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  5685. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  5686. continue;
  5687. if (doc.nodes[c].class_off &&
  5688. contains_ci(doc.attrs + doc.nodes[c].class_off,
  5689. "skeleton"))
  5690. return 1;
  5691. }
  5692. return 0;
  5693. }
  5694. static void layout_children(struct lay *l, unsigned int parent,
  5695. const struct br_style *pst, int depth,
  5696. unsigned short link);
  5697. static void layout_flex_children(struct lay *l, unsigned int parent,
  5698. const struct br_style *pst, int depth,
  5699. unsigned short link);
  5700. static void layout_grid_children(struct lay *l, unsigned int parent,
  5701. const struct br_style *pst, int depth,
  5702. unsigned short link);
  5703. static void layout_grid_auto(struct lay *l, unsigned int parent,
  5704. const struct br_style *pst, int depth,
  5705. unsigned short link);
  5706. static int flex_item_width(struct lay *l, unsigned int n,
  5707. const struct br_style *cs, int avail);
  5708. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  5709. const struct br_style *pst, int depth,
  5710. unsigned short link);
  5711. static void layout_table_row(struct lay *l, unsigned int row,
  5712. const struct br_style *pst, int depth,
  5713. unsigned short link);
  5714. static int table_has_rowspan(unsigned int table);
  5715. static void layout_table(struct lay *l, unsigned int table,
  5716. const struct br_style *st, int depth,
  5717. unsigned short link);
  5718. /* A flex container whose items are only inline spans is usually just a
  5719. * heading/icon pair. Our flex row positions such items without emitting
  5720. * their inline text in some deep page contexts; normal inline flow renders
  5721. * the same content correctly. */
  5722. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  5723. {
  5724. unsigned int c;
  5725. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  5726. struct br_node *nd = &doc.nodes[c];
  5727. struct br_style cs;
  5728. if (nd->type == BR_NODE_TEXT)
  5729. continue;
  5730. br_style_for(&doc, c, pst, &cs);
  5731. if (cs.display == BR_DISPLAY_NONE)
  5732. continue;
  5733. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  5734. cs.width_kind || cs.has_bg ||
  5735. cs.border_w[0] || cs.border_w[1] ||
  5736. cs.border_w[2] || cs.border_w[3] ||
  5737. nd->tag == BR_TAG_IMG)
  5738. return 1;
  5739. }
  5740. return 0;
  5741. }
  5742. static int css_radius(const struct br_style *st, int corner,
  5743. int w, int h)
  5744. {
  5745. int r = st->radius[corner];
  5746. if (r <= 0)
  5747. return 0;
  5748. if (r > w / 2)
  5749. r = w / 2;
  5750. if (r > h / 2)
  5751. r = h / 2;
  5752. return r;
  5753. }
  5754. /* ---- inline SVG ----
  5755. *
  5756. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  5757. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  5758. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  5759. * opacity and solid paint; a gradient paints the average of its stops) and
  5760. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  5761. #define SVG_CACHE_MAX 48
  5762. #define SVG_CACHE_PIXELS (640 * 1024)
  5763. #define SVG_MAX_POINTS 24576
  5764. struct svg_cache_ent {
  5765. unsigned int node;
  5766. int w, h;
  5767. unsigned short *px;
  5768. unsigned char *a;
  5769. unsigned int stamp;
  5770. };
  5771. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  5772. static unsigned int svg_cache_pixels, svg_cache_clock;
  5773. static struct svgr svg_geom;
  5774. static void *svg_geom_buf;
  5775. /* Current viewport in user units: percentage lengths resolve against it
  5776. * (the viewBox size, not the device pixels). */
  5777. static double svg_vp_w = 300, svg_vp_h = 150;
  5778. /* The layers live in the page heap: forget them before heap_reset(). */
  5779. static void svg_cache_clear(void)
  5780. {
  5781. memset(svg_cache, 0, sizeof(svg_cache));
  5782. svg_cache_pixels = 0;
  5783. svg_geom_buf = 0;
  5784. }
  5785. static int svg_name_is(const char *a, const char *b)
  5786. {
  5787. while (*a && *b) {
  5788. char x = *a, y = *b;
  5789. if (x >= 'A' && x <= 'Z')
  5790. x = (char)(x - 'A' + 'a');
  5791. if (x != y)
  5792. return 0;
  5793. a++;
  5794. b++;
  5795. }
  5796. return *a == *b;
  5797. }
  5798. static const char *svg_elem_name(unsigned int node)
  5799. {
  5800. const struct br_node *nd = &doc.nodes[node];
  5801. if (nd->name_off)
  5802. return doc.attrs + nd->name_off;
  5803. return br_tag_name(nd->tag);
  5804. }
  5805. /* A numeric attribute; a percentage resolves against `base`. */
  5806. static double svg_attr_num(unsigned int node, const char *name, double def,
  5807. double base)
  5808. {
  5809. const char *v = br_find_attr(&doc, node, name);
  5810. const char *p = v;
  5811. int ok = 0;
  5812. double x;
  5813. if (!v)
  5814. return def;
  5815. x = svgr_num(&p, &ok);
  5816. if (!ok)
  5817. return def;
  5818. if (*p == '%')
  5819. x = x * base / 100.0;
  5820. return x;
  5821. }
  5822. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  5823. static int svg_viewbox4(unsigned int node, double vb[4])
  5824. {
  5825. const char *v = br_find_attr(&doc, node, "viewbox");
  5826. const char *p = v;
  5827. int i, ok = 1;
  5828. if (!v)
  5829. return 0;
  5830. for (i = 0; i < 4 && ok; i++)
  5831. vb[i] = svgr_num(&p, &ok);
  5832. return ok && vb[2] > 0 && vb[3] > 0;
  5833. }
  5834. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  5835. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  5836. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  5837. double w, double h, double m[6])
  5838. {
  5839. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  5840. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  5841. int ax = 1, ay = 1;
  5842. if (par && contains_ci(par, "none")) {
  5843. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  5844. m[4] = -vb[0] * sx;
  5845. m[5] = -vb[1] * sy;
  5846. return;
  5847. }
  5848. if (par) {
  5849. if (contains_ci(par, "xmin"))
  5850. ax = 0;
  5851. else if (contains_ci(par, "xmax"))
  5852. ax = 2;
  5853. if (contains_ci(par, "ymin"))
  5854. ay = 0;
  5855. else if (contains_ci(par, "ymax"))
  5856. ay = 2;
  5857. }
  5858. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  5859. (sx < sy ? sx : sy);
  5860. tx = (w - vb[2] * s) * ax / 2.0;
  5861. ty = (h - vb[3] * s) * ay / 2.0;
  5862. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  5863. m[4] = tx - vb[0] * s;
  5864. m[5] = ty - vb[1] * s;
  5865. }
  5866. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  5867. * the paint attribute, then average the gradient's stops. */
  5868. static int svg_url_paint(unsigned int node, const char *attr,
  5869. unsigned short *color, unsigned int *alpha)
  5870. {
  5871. const char *v = 0, *h;
  5872. char id[64];
  5873. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  5874. for (k = 0; node && k < 32 && !v; k++) {
  5875. v = br_find_attr(&doc, node, attr);
  5876. if (!v) {
  5877. const char *style = br_find_attr(&doc, node, "style");
  5878. if (style && contains_ci(style, "url(#"))
  5879. v = strstr(style, "url(#");
  5880. }
  5881. if (v && !contains_ci(v, "url("))
  5882. v = 0;
  5883. node = doc.nodes[node].parent;
  5884. }
  5885. if (!v || !(h = strstr(v, "#")))
  5886. return 0;
  5887. h++;
  5888. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  5889. id[n++] = *h++;
  5890. id[n] = '\0';
  5891. g = br_find_id(&doc, id);
  5892. /* Follow href chains (a gradient that only references another one's
  5893. * stops), at most a few hops. */
  5894. for (k = 0; g && k < 4; k++) {
  5895. unsigned int gi = g - 1;
  5896. const char *ref;
  5897. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  5898. const char *nm, *sc, *so;
  5899. unsigned short col = 0;
  5900. double op = 1;
  5901. if (doc.nodes[c].type != BR_NODE_ELEM)
  5902. continue;
  5903. nm = svg_elem_name(c);
  5904. if (!svg_name_is(nm, "stop"))
  5905. continue;
  5906. sc = br_find_attr(&doc, c, "stop-color");
  5907. so = br_find_attr(&doc, c, "stop-opacity");
  5908. {
  5909. const char *st = br_find_attr(&doc, c, "style");
  5910. const char *q;
  5911. if (st && (q = strstr(st, "stop-color:")) != 0)
  5912. sc = q + 11;
  5913. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  5914. so = q + 13;
  5915. }
  5916. if (sc) {
  5917. unsigned int L = 0;
  5918. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  5919. L++;
  5920. if (!br_parse_color(sc, L, &col))
  5921. col = 0;
  5922. }
  5923. if (so) {
  5924. const char *p = so;
  5925. int ok = 0;
  5926. double x = svgr_num(&p, &ok);
  5927. if (ok)
  5928. op = x < 0 ? 0 : x > 1 ? 1 : x;
  5929. }
  5930. sr += (col >> 11) & 31;
  5931. sg += (col >> 5) & 63;
  5932. sb += col & 31;
  5933. sa += (unsigned int)(op * 255);
  5934. cnt++;
  5935. }
  5936. if (cnt)
  5937. break;
  5938. ref = br_find_attr(&doc, gi, "href");
  5939. if (!ref)
  5940. ref = br_find_attr(&doc, gi, "xlink:href");
  5941. if (!ref || ref[0] != '#')
  5942. break;
  5943. g = br_find_id(&doc, ref + 1);
  5944. }
  5945. if (!cnt)
  5946. return 0;
  5947. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  5948. (sb / cnt));
  5949. *alpha = sa / cnt;
  5950. return 1;
  5951. }
  5952. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  5953. unsigned short *color, unsigned int *alpha)
  5954. {
  5955. int mode = fill ? st->fill_mode : st->stroke_mode;
  5956. const char *op = br_find_attr(&doc, node,
  5957. fill ? "fill-opacity" : "stroke-opacity");
  5958. *alpha = 255;
  5959. switch (mode) {
  5960. case BR_PAINT_UNSET:
  5961. if (!fill)
  5962. return 0;
  5963. *color = 0;
  5964. break;
  5965. case BR_PAINT_COLOR:
  5966. *color = fill ? st->fill : st->stroke;
  5967. break;
  5968. case BR_PAINT_CURRENT:
  5969. *color = st->color;
  5970. break;
  5971. case BR_PAINT_URL:
  5972. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  5973. alpha))
  5974. return 0;
  5975. break;
  5976. default:
  5977. return 0;
  5978. }
  5979. if (op) {
  5980. const char *p = op;
  5981. int ok = 0;
  5982. double x = svgr_num(&p, &ok);
  5983. if (ok)
  5984. *alpha = (unsigned int)(*alpha *
  5985. (x < 0 ? 0 : x > 1 ? 1 : x));
  5986. }
  5987. return *alpha > 0;
  5988. }
  5989. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  5990. const double m[6], const struct br_style *pst,
  5991. unsigned int alpha, int depth);
  5992. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  5993. const double m[6], const struct br_style *st,
  5994. unsigned int alpha, int depth)
  5995. {
  5996. unsigned int c;
  5997. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  5998. if (doc.nodes[c].type == BR_NODE_ELEM)
  5999. svg_draw_node(L, c, m, st, alpha, depth + 1);
  6000. }
  6001. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  6002. const double pm[6], const struct br_style *pst,
  6003. unsigned int alpha, int depth)
  6004. {
  6005. struct br_style st;
  6006. const char *nm = svg_elem_name(node);
  6007. const char *tf;
  6008. double m[6];
  6009. unsigned short color;
  6010. unsigned int pa;
  6011. int shape = 0, fillable = 1;
  6012. if (depth > 24 || !nm)
  6013. return;
  6014. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  6015. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  6016. svg_name_is(nm, "lineargradient") ||
  6017. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  6018. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  6019. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  6020. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  6021. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  6022. svg_name_is(nm, "foreignobject"))
  6023. return;
  6024. br_style_for(&doc, node, pst, &st);
  6025. if (st.display == BR_DISPLAY_NONE)
  6026. return;
  6027. memcpy(m, pm, sizeof(m));
  6028. tf = br_find_attr(&doc, node, "transform");
  6029. if (tf)
  6030. svgr_transform(m, tf);
  6031. {
  6032. const char *op = br_find_attr(&doc, node, "opacity");
  6033. if (op) {
  6034. const char *p = op;
  6035. int ok = 0;
  6036. double x = svgr_num(&p, &ok);
  6037. if (ok)
  6038. alpha = (unsigned int)(alpha *
  6039. (x < 0 ? 0 :
  6040. x > 1 ? 1 : x));
  6041. }
  6042. }
  6043. if (!alpha)
  6044. return;
  6045. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  6046. svg_name_is(nm, "switch")) {
  6047. svg_draw_children(L, node, m, &st, alpha, depth);
  6048. return;
  6049. }
  6050. if (svg_name_is(nm, "svg")) {
  6051. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  6052. y = svg_attr_num(node, "y", 0, 0);
  6053. double t[6] = { 1, 0, 0, 1, 0, 0 };
  6054. t[4] = x;
  6055. t[5] = y;
  6056. svgr_mat_mul(m, m, t);
  6057. double ow = svg_vp_w, oh = svg_vp_h;
  6058. if (svg_viewbox4(node, vb)) {
  6059. double w = svg_attr_num(node, "width", vb[2], ow);
  6060. double h = svg_attr_num(node, "height", vb[3], oh);
  6061. double vm[6];
  6062. svg_viewport_matrix(node, vb, w, h, vm);
  6063. svgr_mat_mul(m, m, vm);
  6064. svg_vp_w = vb[2];
  6065. svg_vp_h = vb[3];
  6066. }
  6067. svg_draw_children(L, node, m, &st, alpha, depth);
  6068. svg_vp_w = ow;
  6069. svg_vp_h = oh;
  6070. return;
  6071. }
  6072. if (svg_name_is(nm, "use")) {
  6073. const char *ref = br_find_attr(&doc, node, "href");
  6074. unsigned int tgt;
  6075. double t[6] = { 1, 0, 0, 1, 0, 0 };
  6076. if (!ref)
  6077. ref = br_find_attr(&doc, node, "xlink:href");
  6078. if (!ref || ref[0] != '#')
  6079. return;
  6080. tgt = br_find_id(&doc, ref + 1);
  6081. if (!tgt || tgt - 1 == node)
  6082. return;
  6083. tgt--;
  6084. t[4] = svg_attr_num(node, "x", 0, 0);
  6085. t[5] = svg_attr_num(node, "y", 0, 0);
  6086. svgr_mat_mul(m, m, t);
  6087. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  6088. double vb[4];
  6089. double ow = svg_vp_w, oh = svg_vp_h;
  6090. if (svg_viewbox4(tgt, vb)) {
  6091. double w = svg_attr_num(node, "width", vb[2],
  6092. ow);
  6093. double h = svg_attr_num(node, "height", vb[3],
  6094. oh);
  6095. double vm[6];
  6096. svg_viewport_matrix(tgt, vb, w, h, vm);
  6097. svgr_mat_mul(m, m, vm);
  6098. svg_vp_w = vb[2];
  6099. svg_vp_h = vb[3];
  6100. }
  6101. svg_draw_children(L, tgt, m, &st, alpha, depth);
  6102. svg_vp_w = ow;
  6103. svg_vp_h = oh;
  6104. } else {
  6105. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  6106. }
  6107. return;
  6108. }
  6109. svgr_reset(&svg_geom, m);
  6110. if (svg_name_is(nm, "path")) {
  6111. const char *d = br_find_attr(&doc, node, "d");
  6112. if (d) {
  6113. svgr_path(&svg_geom, d);
  6114. shape = 1;
  6115. }
  6116. } else if (svg_name_is(nm, "rect")) {
  6117. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  6118. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  6119. double rx = svg_attr_num(node, "rx", -1, w);
  6120. double ry = svg_attr_num(node, "ry", -1, h);
  6121. if (rx < 0)
  6122. rx = ry < 0 ? 0 : ry;
  6123. if (ry < 0)
  6124. ry = rx;
  6125. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  6126. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  6127. shape = 1;
  6128. } else if (svg_name_is(nm, "circle")) {
  6129. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  6130. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  6131. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  6132. shape = 1;
  6133. } else if (svg_name_is(nm, "ellipse")) {
  6134. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  6135. svg_attr_num(node, "cy", 0, svg_vp_h),
  6136. svg_attr_num(node, "rx", 0, svg_vp_w),
  6137. svg_attr_num(node, "ry", 0, svg_vp_h));
  6138. shape = 1;
  6139. } else if (svg_name_is(nm, "line")) {
  6140. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  6141. svg_attr_num(node, "y1", 0, svg_vp_h));
  6142. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  6143. svg_attr_num(node, "y2", 0, svg_vp_h));
  6144. shape = 1;
  6145. fillable = 0;
  6146. } else if (svg_name_is(nm, "polyline") ||
  6147. svg_name_is(nm, "polygon")) {
  6148. const char *pts = br_find_attr(&doc, node, "points");
  6149. if (pts) {
  6150. svgr_points(&svg_geom, pts,
  6151. svg_name_is(nm, "polygon"));
  6152. shape = 1;
  6153. }
  6154. }
  6155. if (!shape)
  6156. return;
  6157. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  6158. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  6159. st.fill_evenodd);
  6160. if (svg_paint(node, &st, 0, &color, &pa)) {
  6161. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  6162. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  6163. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  6164. }
  6165. }
  6166. /* <text> elements: drawn straight onto the page every frame (the glyph
  6167. * renderer targets the ngui canvas, not a layer). x/y map through the
  6168. * accumulated transform; the font size scales with it. */
  6169. static void svg_draw_text(struct ngui *ui, unsigned int node,
  6170. const double pm[6], const struct br_style *pst,
  6171. int ox, int oy, int depth)
  6172. {
  6173. unsigned int c;
  6174. if (depth > 24)
  6175. return;
  6176. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  6177. struct br_style st;
  6178. const char *nm, *tf;
  6179. double m[6];
  6180. if (doc.nodes[c].type != BR_NODE_ELEM)
  6181. continue;
  6182. nm = svg_elem_name(c);
  6183. if (!nm || svg_name_is(nm, "defs") ||
  6184. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  6185. svg_name_is(nm, "clippath"))
  6186. continue;
  6187. br_style_for(&doc, c, pst, &st);
  6188. if (st.display == BR_DISPLAY_NONE)
  6189. continue;
  6190. memcpy(m, pm, sizeof(m));
  6191. tf = br_find_attr(&doc, c, "transform");
  6192. if (tf)
  6193. svgr_transform(m, tf);
  6194. if (svg_name_is(nm, "text")) {
  6195. unsigned int t = doc.nodes[c].first;
  6196. const char *s;
  6197. unsigned int n, tw;
  6198. double x = svg_attr_num(c, "x", 0, 0),
  6199. y = svg_attr_num(c, "y", 0, 0);
  6200. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  6201. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  6202. int tx, ty, anchor;
  6203. unsigned short col;
  6204. unsigned int pa;
  6205. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  6206. continue;
  6207. if (px < 6)
  6208. px = 6;
  6209. if (px > 72)
  6210. px = 72;
  6211. if (!svg_paint(c, &st, 1, &col, &pa))
  6212. continue;
  6213. s = doc.text + doc.nodes[t].text_off;
  6214. n = doc.nodes[t].text_len;
  6215. st.font_px = (unsigned char)px;
  6216. tw = face_text_width(ui, &st, s, n);
  6217. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  6218. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  6219. ngui_text_ascent_face(ui, style_face(&st), px,
  6220. st.mono);
  6221. anchor = st.align;
  6222. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  6223. anchor = BR_ALIGN_CENTER;
  6224. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  6225. anchor = BR_ALIGN_RIGHT;
  6226. if (anchor == BR_ALIGN_CENTER)
  6227. tx -= (int)tw / 2;
  6228. else if (anchor == BR_ALIGN_RIGHT)
  6229. tx -= (int)tw;
  6230. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  6231. col, px, st.bold, st.italic,
  6232. st.mono);
  6233. } else {
  6234. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  6235. }
  6236. }
  6237. }
  6238. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  6239. {
  6240. double vb[4];
  6241. if (svg_viewbox4(node, vb)) {
  6242. svg_viewport_matrix(node, vb, w, h, m);
  6243. } else {
  6244. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  6245. }
  6246. }
  6247. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  6248. const struct br_style *st)
  6249. {
  6250. struct svg_cache_ent *e = 0;
  6251. struct svgr_layer L;
  6252. double m[6];
  6253. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  6254. svg_cache_clock++;
  6255. for (i = 0; i < SVG_CACHE_MAX; i++)
  6256. if (svg_cache[i].px && svg_cache[i].node == node &&
  6257. svg_cache[i].w == w && svg_cache[i].h == h) {
  6258. svg_cache[i].stamp = svg_cache_clock;
  6259. return &svg_cache[i];
  6260. }
  6261. if (need > SVG_CACHE_PIXELS)
  6262. return 0;
  6263. /* Evict least recently used layers until this one fits. */
  6264. for (;;) {
  6265. struct svg_cache_ent *lru = 0, *free_slot = 0;
  6266. for (i = 0; i < SVG_CACHE_MAX; i++) {
  6267. if (!svg_cache[i].px) {
  6268. if (!free_slot)
  6269. free_slot = &svg_cache[i];
  6270. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  6271. lru = &svg_cache[i];
  6272. }
  6273. }
  6274. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  6275. e = free_slot;
  6276. break;
  6277. }
  6278. if (!lru)
  6279. return 0;
  6280. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  6281. free(lru->px);
  6282. free(lru->a);
  6283. memset(lru, 0, sizeof(*lru));
  6284. }
  6285. if (!svg_geom_buf) {
  6286. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  6287. if (!svg_geom_buf)
  6288. return 0;
  6289. }
  6290. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  6291. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  6292. e->a = (unsigned char *)calloc(need, 1);
  6293. if (!e->px || !e->a) {
  6294. free(e->px);
  6295. free(e->a);
  6296. memset(e, 0, sizeof(*e));
  6297. return 0;
  6298. }
  6299. e->node = node;
  6300. e->w = w;
  6301. e->h = h;
  6302. e->stamp = svg_cache_clock;
  6303. svg_cache_pixels += need;
  6304. L.px = e->px;
  6305. L.a = e->a;
  6306. L.w = w;
  6307. L.h = h;
  6308. svg_root_matrix(node, w, h, m);
  6309. {
  6310. double vb[4];
  6311. if (svg_viewbox4(node, vb)) {
  6312. svg_vp_w = vb[2];
  6313. svg_vp_h = vb[3];
  6314. } else {
  6315. svg_vp_w = w;
  6316. svg_vp_h = h;
  6317. }
  6318. }
  6319. svg_draw_children(&L, node, m, st, 255, 0);
  6320. return e;
  6321. }
  6322. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  6323. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  6324. int *out_w, int *out_h)
  6325. {
  6326. double vb[4];
  6327. int has_vb = svg_viewbox4(node, vb);
  6328. double aw = svg_attr_num(node, "width", -1, cw);
  6329. double ah = svg_attr_num(node, "height", -1, 0);
  6330. int w, h;
  6331. if (st->width_kind)
  6332. w = cw;
  6333. else if (aw > 0)
  6334. w = (int)(aw + 0.5);
  6335. else if (st->height_kind == 1 && has_vb)
  6336. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  6337. else if (ah > 0 && has_vb)
  6338. w = (int)(ah * vb[2] / vb[3] + 0.5);
  6339. else if (has_vb)
  6340. w = cw;
  6341. else
  6342. w = 300;
  6343. if (st->max_width_kind == 1 && w > st->max_width)
  6344. w = st->max_width;
  6345. if (w > cw && cw > 0 && !(aw > 0))
  6346. w = cw;
  6347. if (w < 1)
  6348. w = 1;
  6349. if (w > 2000)
  6350. w = 2000;
  6351. if (st->height_kind == 1)
  6352. h = st->height;
  6353. else if (ah > 0)
  6354. h = (int)(ah + 0.5);
  6355. else if (has_vb)
  6356. h = (int)(w * vb[3] / vb[2] + 0.5);
  6357. else
  6358. h = 150;
  6359. if (h < 1)
  6360. h = 1;
  6361. if (h > 1400)
  6362. h = 1400;
  6363. *out_w = w;
  6364. *out_h = h;
  6365. }
  6366. static void svg_paint_box(struct ngui *ui, unsigned int node,
  6367. const struct br_style *st, int x, int y, int w, int h)
  6368. {
  6369. struct svg_cache_ent *e;
  6370. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  6371. int cx0, cy0, cx1, cy1, px, py;
  6372. double m[6];
  6373. if (ui->nclip > 0)
  6374. clip = ui->clip[ui->nclip - 1];
  6375. cx0 = r.x > clip.x ? r.x : clip.x;
  6376. cy0 = r.y > clip.y ? r.y : clip.y;
  6377. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  6378. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  6379. if (cx0 >= cx1 || cy0 >= cy1)
  6380. return;
  6381. e = svg_layer(node, w, h, st);
  6382. if (e) {
  6383. for (py = cy0; py < cy1; py++) {
  6384. unsigned int srow = (unsigned int)(py - y) *
  6385. (unsigned int)w;
  6386. unsigned short *dst = ui->px + py * ui->w;
  6387. for (px = cx0; px < cx1; px++) {
  6388. unsigned int si = srow + (unsigned int)(px - x);
  6389. unsigned int a = e->a[si];
  6390. if (!a)
  6391. continue;
  6392. dst[px] = a >= 255 ? e->px[si] :
  6393. blend_rgb565(dst[px], e->px[si], a);
  6394. }
  6395. }
  6396. }
  6397. svg_root_matrix(node, w, h, m);
  6398. ngui_push_clip(ui, r);
  6399. svg_draw_text(ui, node, m, st, x, y, 0);
  6400. ngui_pop_clip(ui);
  6401. }
  6402. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  6403. * keep using add_image_run(); this covers the CSS `position:absolute;
  6404. * width:100%` poster pattern used by news sites. */
  6405. static void image_block_size(unsigned int node, const struct br_style *st,
  6406. int cbw, int *out_w, int *out_h)
  6407. {
  6408. struct br_node *nd = &doc.nodes[node];
  6409. int idx = nd->img_index;
  6410. int iw = 0, ih = 0, w, h;
  6411. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  6412. iw = (int)images[idx].img.w;
  6413. ih = (int)images[idx].img.h;
  6414. if (iw <= 0 || ih <= 0) {
  6415. iw = (int)images[idx].native_w;
  6416. ih = (int)images[idx].native_h;
  6417. }
  6418. }
  6419. if (st->width_kind)
  6420. w = style_width_px(st, cbw);
  6421. else if (nd->width_attr)
  6422. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  6423. (int)nd->width_attr;
  6424. else if (iw)
  6425. w = iw;
  6426. else
  6427. w = 64;
  6428. if (w < 8)
  6429. w = 8;
  6430. if (cbw > 0 && w > cbw)
  6431. w = cbw;
  6432. if (st->height_kind)
  6433. h = style_height_px(st, cbw);
  6434. else if (nd->height_attr)
  6435. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  6436. (int)nd->height_attr;
  6437. else if (iw && ih)
  6438. h = w * ih / iw;
  6439. else
  6440. h = 64;
  6441. if (h < 8)
  6442. h = 8;
  6443. *out_w = w;
  6444. *out_h = h;
  6445. }
  6446. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  6447. int dw, int dh)
  6448. {
  6449. int idx = doc.nodes[node].img_index;
  6450. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  6451. struct img_blit b;
  6452. b.dst = l->ui->px;
  6453. b.dst_w = l->ui->w;
  6454. b.dst_h = l->ui->h;
  6455. b.clip_x = page_rect.x;
  6456. b.clip_y = page_rect.y;
  6457. b.clip_w = page_rect.w - 12;
  6458. b.clip_h = page_rect.h;
  6459. b.x = x;
  6460. b.y = y;
  6461. b.scale = ((unsigned int)dw << 16) / images[idx].img.w;
  6462. b.bg = ui.theme.bg;
  6463. b.bg2 = ui.theme.bg;
  6464. b.flags = IMG_BLIT_OVER_DST;
  6465. img_draw(&images[idx].img, &b);
  6466. } else if (l->draw) {
  6467. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  6468. 0xD69A);
  6469. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  6470. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  6471. }
  6472. }
  6473. static void layout_block(struct lay *l, unsigned int node,
  6474. const struct br_style *st, int depth,
  6475. unsigned short link)
  6476. {
  6477. int old_left = l->left, old_right = l->right, old_align = l->align;
  6478. int saved_parent_top = l->parent_top;
  6479. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  6480. int saved_cb_top = l->cb_top;
  6481. int top, l0, r0;
  6482. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  6483. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  6484. int deco_w, deco_h, content_w, content_h, box_h;
  6485. int img_dh = 0;
  6486. int definite_w = 0;
  6487. int normal_top = 0;
  6488. int rel_dx = 0, rel_dy = 0;
  6489. int clip_pushed = 0;
  6490. struct ngui_rect clip_rect;
  6491. /* A DOM level costs about two depth units (layout_block ->
  6492. * layout_children), so 48 covers a ~24-level page. Real news pages
  6493. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  6494. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  6495. return;
  6496. flow_y = l->y;
  6497. flow_left = l->left;
  6498. flow_right = l->right;
  6499. positioned = st->pos == 1 || st->pos == 2;
  6500. relative = st->pos == 3;
  6501. sticky = st->pos == 4;
  6502. shifted = relative || sticky || st->transform_set;
  6503. if (positioned) {
  6504. int def_w = st->width_kind == 1 ? st->width : -1;
  6505. if (st->pos == 2) {
  6506. int avail_w = page_rect.w - 12;
  6507. if (st->right_set && def_w >= 0)
  6508. l->left = page_rect.x + avail_w - st->right -
  6509. def_w;
  6510. else
  6511. l->left = page_rect.x +
  6512. (st->left_set ? st->left : 0);
  6513. l->right = def_w >= 0 ? l->left + def_w :
  6514. page_rect.x + avail_w;
  6515. if (st->bottom_set && st->height_kind)
  6516. l->y = page_rect.y + page_rect.h -
  6517. st->bottom -
  6518. style_height_px(st, page_rect.w);
  6519. else
  6520. l->y = page_rect.y +
  6521. (st->top_set ? st->top : 0);
  6522. } else {
  6523. int left = flow_left + (st->left_set ? st->left : 0);
  6524. unsigned int parent = doc.nodes[node].parent;
  6525. if (st->right_set && def_w >= 0)
  6526. left = flow_right - st->right - def_w;
  6527. l->left = left;
  6528. l->right = def_w >= 0 ? left + def_w :
  6529. flow_right +
  6530. (st->left_set ? st->left : 0);
  6531. l->y = flow_y + (st->top_set ? st->top : 0);
  6532. if (st->bottom_set && st->height_kind &&
  6533. parent < BR_MAX_NODES && block_h[parent] > 0)
  6534. l->y = flow_y + block_h[parent] - st->bottom -
  6535. style_height_px(st, old_right - old_left);
  6536. }
  6537. old_left = l->left;
  6538. old_right = l->right;
  6539. } else if (relative) {
  6540. rel_dx = st->left_set ? st->left :
  6541. (st->right_set ? -st->right : 0);
  6542. rel_dy = st->top_set ? st->top :
  6543. (st->bottom_set ? -st->bottom : 0);
  6544. }
  6545. if (st->transform_set) {
  6546. rel_dx += st->tx;
  6547. rel_dy += st->ty;
  6548. }
  6549. if (doc.nodes[node].tag == BR_TAG_INPUT ||
  6550. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  6551. doc.nodes[node].tag == BR_TAG_SELECT ||
  6552. doc.nodes[node].tag == BR_TAG_BUTTON) {
  6553. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  6554. s_eq(br_type(&doc, node), "hidden"))
  6555. return;
  6556. /* Reached as a block-level box (a flex item): the control
  6557. * fills the box the caller assigned, and its line is flushed
  6558. * here; flex layout resets the run list for the next item, so
  6559. * a queued run would never be drawn. */
  6560. form_fill_line = 1;
  6561. add_form_run(l, node, st, link);
  6562. form_fill_line = 0;
  6563. flush_line(l);
  6564. return;
  6565. }
  6566. flush_line(l);
  6567. cbw = old_right - old_left;
  6568. if (cbw < 8)
  6569. cbw = 8;
  6570. l->y += mp_px(st, 0, cbw);
  6571. top = l->y;
  6572. ml = mp_px(st, 3, cbw);
  6573. mr = mp_px(st, 1, cbw);
  6574. bl = st->border_w[3];
  6575. br = st->border_w[1];
  6576. pl = mp_px(st, 7, cbw);
  6577. pr = mp_px(st, 5, cbw);
  6578. bt = st->border_w[0];
  6579. bb = st->border_w[2];
  6580. pt = mp_px(st, 4, cbw);
  6581. pb = mp_px(st, 6, cbw);
  6582. deco_w = bl + br + pl + pr;
  6583. deco_h = bt + bb + pt + pb;
  6584. if (st->width_kind) {
  6585. int w;
  6586. if (st->width_kind == 3)
  6587. w = cbw * st->width_calc_pct / 100 +
  6588. st->width_calc_px;
  6589. else
  6590. w = css_size(st->width_kind, st->width, cbw);
  6591. if (w < 0)
  6592. w = 0;
  6593. content_w = st->box_sizing ? w - deco_w : w;
  6594. definite_w = 1;
  6595. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  6596. doc.nodes[node].tag == BR_TAG_TD ||
  6597. doc.nodes[node].tag == BR_TAG_TH) &&
  6598. doc.nodes[node].width_attr) {
  6599. /* Legacy table/cell width attributes: percentages resolve
  6600. * against the containing block, bare numbers are pixels. */
  6601. int w = doc.nodes[node].width_pct ?
  6602. cbw * doc.nodes[node].width_attr / 100 :
  6603. doc.nodes[node].width_attr;
  6604. if (w < 0)
  6605. w = 0;
  6606. content_w = st->box_sizing ? w - deco_w : w;
  6607. definite_w = 1;
  6608. } else {
  6609. content_w = cbw - ml - mr - deco_w;
  6610. }
  6611. if (content_w < 0)
  6612. content_w = 0;
  6613. if (st->max_width_kind) {
  6614. int mw = st->max_width_kind == 3 ?
  6615. cbw * st->max_width_calc_pct / 100 +
  6616. st->max_width_calc_px :
  6617. css_size(st->max_width_kind, st->max_width, cbw);
  6618. int max_box = st->box_sizing ? mw : mw + deco_w;
  6619. if (content_w + deco_w > max_box)
  6620. content_w = max_box - deco_w;
  6621. }
  6622. if (st->min_width_kind) {
  6623. int mw = st->min_width_kind == 3 ?
  6624. cbw * st->min_width_calc_pct / 100 +
  6625. st->min_width_calc_px :
  6626. css_size(st->min_width_kind, st->min_width, cbw);
  6627. int min_box = st->box_sizing ? mw : mw + deco_w;
  6628. if (content_w + deco_w < min_box) {
  6629. content_w = min_box - deco_w;
  6630. definite_w = 1;
  6631. }
  6632. }
  6633. if (content_w < 8)
  6634. content_w = 8;
  6635. if (definite_w) {
  6636. int free_w = cbw - ml - mr - deco_w - content_w;
  6637. if (free_w < 0)
  6638. free_w = 0;
  6639. if (st->ml_auto && st->mr_auto) {
  6640. ml = free_w / 2;
  6641. mr = free_w - ml;
  6642. } else if (st->ml_auto) {
  6643. ml = free_w;
  6644. } else if (st->mr_auto) {
  6645. mr = free_w;
  6646. }
  6647. }
  6648. if (doc.nodes[node].tag == BR_TAG_IMG) {
  6649. int iw, ih;
  6650. image_block_size(node, st, cbw, &iw, &ih);
  6651. content_w = iw;
  6652. img_dh = ih;
  6653. }
  6654. l0 = old_left + ml;
  6655. r0 = l0 + deco_w + content_w;
  6656. if (r0 < l0 + 8)
  6657. r0 = l0 + 8;
  6658. normal_top = top;
  6659. if (sticky) {
  6660. if (st->top_set) {
  6661. int stick = page_rect.y + 4 + st->top;
  6662. if (normal_top < stick)
  6663. rel_dy += stick - normal_top;
  6664. } else if (st->bottom_set && block_h[node]) {
  6665. int stick = page_rect.y + page_rect.h - st->bottom -
  6666. block_h[node];
  6667. if (normal_top > stick)
  6668. rel_dy += stick - normal_top;
  6669. }
  6670. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  6671. block_h[doc.nodes[node].parent]) {
  6672. unsigned int p = doc.nodes[node].parent;
  6673. int ptop = l->parent_top;
  6674. int pbottom = ptop + block_h[p];
  6675. int eh = block_h[node];
  6676. int moved_top = normal_top + rel_dy;
  6677. int moved_bottom = moved_top + eh;
  6678. if (moved_bottom > pbottom)
  6679. rel_dy -= moved_bottom - pbottom;
  6680. moved_top = normal_top + rel_dy;
  6681. if (moved_top < ptop)
  6682. rel_dy += ptop - moved_top;
  6683. }
  6684. }
  6685. if (shifted && l->draw) {
  6686. top += rel_dy;
  6687. l0 += rel_dx;
  6688. r0 += rel_dx;
  6689. }
  6690. l->parent_top = top;
  6691. if (st->pos != 0) {
  6692. /* Positioned boxes establish the containing block for their
  6693. * absolutely positioned descendants. */
  6694. l->cb_left = l0;
  6695. l->cb_right = r0;
  6696. l->cb_top = top;
  6697. }
  6698. if (l->draw && block_h[node] &&
  6699. top < page_rect.y + page_rect.h &&
  6700. top + block_h[node] > page_rect.y) {
  6701. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  6702. int rtl = css_radius(st, 0, box.w, box.h);
  6703. int rtr = css_radius(st, 1, box.w, box.h);
  6704. int rbr = css_radius(st, 2, box.w, box.h);
  6705. int rbl = css_radius(st, 3, box.w, box.h);
  6706. if (st->transform_scale) {
  6707. if (st->has_bg)
  6708. fill_transformed_rect(l->ui, box, st->bg, st);
  6709. } else if (rtl || rtr || rbr || rbl) {
  6710. if (st->has_bg) {
  6711. int bw = st->border_w[0];
  6712. if (bw > 0 && !st->border_t[0] &&
  6713. st->border_c[0] != st->bg &&
  6714. box.w > bw * 2 && box.h > bw * 2) {
  6715. struct ngui_rect inner = {
  6716. box.x + bw, box.y + bw,
  6717. box.w - bw * 2, box.h - bw * 2
  6718. };
  6719. int itl = rtl > bw ? rtl - bw : 0;
  6720. int itr = rtr > bw ? rtr - bw : 0;
  6721. int ibr = rbr > bw ? rbr - bw : 0;
  6722. int ibl = rbl > bw ? rbl - bw : 0;
  6723. ngui_fill_round_rect(l->ui, box, rtl,
  6724. rtr, rbr, rbl,
  6725. st->border_c[0]);
  6726. ngui_fill_round_rect(l->ui, inner,
  6727. itl, itr, ibr,
  6728. ibl, st->bg);
  6729. } else {
  6730. ngui_fill_round_rect(l->ui, box, rtl,
  6731. rtr, rbr, rbl,
  6732. st->bg);
  6733. }
  6734. } else if (st->border_w[0] && !st->border_t[0]) {
  6735. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  6736. rbl, st->border_w[0],
  6737. st->border_c[0]);
  6738. }
  6739. /* Rounded boxes paint their background image too
  6740. * (app icons are rounded squares), kept inside the
  6741. * corner arcs. */
  6742. if (st->bg_image)
  6743. draw_bg_image_round(l, box, node, st, rtl, rtr,
  6744. rbr, rbl);
  6745. } else {
  6746. if (st->has_bg)
  6747. ngui_fill_rect(l->ui, box, st->bg);
  6748. if (st->bg_image)
  6749. draw_bg_image(l, box, node, st);
  6750. if (st->border_w[0] || st->border_w[1] ||
  6751. st->border_w[2] || st->border_w[3])
  6752. draw_border_box(l->ui, box, st);
  6753. }
  6754. }
  6755. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  6756. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  6757. content_w, img_dh);
  6758. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  6759. l->ui && l->ui->nclip < 4) {
  6760. clip_rect.x = l0 + bl;
  6761. clip_rect.y = top + bt;
  6762. clip_rect.w = (r0 - l0) - bl - br;
  6763. clip_rect.h = (int)block_h[node] - bt - bb;
  6764. if (clip_rect.w > 0 && clip_rect.h > 0) {
  6765. ngui_push_clip(l->ui, clip_rect);
  6766. clip_pushed = 1;
  6767. }
  6768. }
  6769. l->left = l0 + bl + pl;
  6770. l->right = l->left + content_w;
  6771. if (l->right < l->left + 8)
  6772. l->right = l->left + 8;
  6773. l->align = st->align;
  6774. l->line_left = l->left;
  6775. l->line_right = l->right;
  6776. l->y = top + bt + pt;
  6777. if (doc.nodes[node].tag == BR_TAG_HR) {
  6778. if (l->draw)
  6779. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  6780. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  6781. l->y += 8;
  6782. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  6783. int vw = l->right - l->left;
  6784. int vh;
  6785. if (doc.nodes[node].width_pct)
  6786. vw = vw * doc.nodes[node].width_attr / 100;
  6787. else if (doc.nodes[node].width_attr)
  6788. vw = doc.nodes[node].width_attr;
  6789. if (vw > l->right - l->left)
  6790. vw = l->right - l->left;
  6791. if (vw < 8)
  6792. vw = 8;
  6793. vh = vw * 9 / 16;
  6794. if (vh > 240)
  6795. vh = 240;
  6796. if (vh < 80)
  6797. vh = 80;
  6798. if (l->draw) {
  6799. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  6800. vw, vh}, 0xD69A);
  6801. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  6802. vw, vh}, 0x8410);
  6803. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  6804. 0x4208);
  6805. }
  6806. l->y += vh + 4;
  6807. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  6808. int dw, dh, cw = l->right - l->left;
  6809. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  6810. if (l->draw && l->y < page_rect.y + page_rect.h &&
  6811. l->y + dh > page_rect.y)
  6812. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  6813. l->y += dh;
  6814. } else {
  6815. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  6816. !st->no_bullet) {
  6817. char *m = li_marker[node];
  6818. if (!m[0]) {
  6819. unsigned int parent = doc.nodes[node].parent;
  6820. int style = st->list_style;
  6821. int idx = parent ? list_index(parent, node) : 1;
  6822. if (style == BR_LIST_AUTO)
  6823. style = (parent &&
  6824. doc.nodes[parent].tag ==
  6825. BR_TAG_OL) ?
  6826. BR_LIST_DECIMAL : BR_LIST_DISC;
  6827. list_marker_text(m, sizeof(li_marker[node]),
  6828. style, idx);
  6829. }
  6830. if (l->draw && m[0]) {
  6831. int mw = (int)ngui_text_width_ui(l->ui, m);
  6832. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  6833. st->color);
  6834. }
  6835. }
  6836. if (doc.nodes[node].tag == BR_TAG_TR)
  6837. layout_table_row(l, node, st, depth + 1, link);
  6838. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  6839. table_has_rowspan(node))
  6840. layout_table(l, node, st, depth + 1, link);
  6841. else if (st->grid_auto)
  6842. layout_grid_auto(l, node, st, depth + 1, link);
  6843. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  6844. st->grid_gap > 0)
  6845. layout_grid_children(l, node, st, depth + 1, link);
  6846. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  6847. flex_wants_row(node, st))
  6848. layout_flex_children(l, node, st, depth + 1, link);
  6849. else
  6850. layout_children(l, node, st, depth + 1, link);
  6851. }
  6852. flush_line(l);
  6853. if (clip_pushed)
  6854. ngui_pop_clip(l->ui);
  6855. if (l->float_active) {
  6856. if (l->y < l->float_bottom)
  6857. l->y = l->float_bottom;
  6858. l->float_active = 0;
  6859. }
  6860. if (doc.nodes[node].tag == BR_TAG_IMG) {
  6861. content_h = img_dh;
  6862. } else if (st->height_kind &&
  6863. !((doc.nodes[node].tag == BR_TAG_HTML ||
  6864. doc.nodes[node].tag == BR_TAG_BODY) &&
  6865. st->height_kind == 2)) {
  6866. content_h = style_height_px(st, cbw);
  6867. if (st->box_sizing)
  6868. content_h -= deco_h;
  6869. } else {
  6870. /* Percentage heights on html/body resolve against the
  6871. * viewport, but their content still defines the document
  6872. * scroll height. Treating them as auto avoids collapsing
  6873. * the measured page to the containing block width. */
  6874. content_h = l->y - (top + bt + pt);
  6875. }
  6876. if (content_h < 0)
  6877. content_h = 0;
  6878. if (st->max_height_kind) {
  6879. int mh = st->max_height_kind == 3 ?
  6880. cbw * st->max_height_calc_pct / 100 +
  6881. st->max_height_calc_px :
  6882. css_size(st->max_height_kind, st->max_height, cbw);
  6883. int max_box = st->box_sizing ? mh : mh + deco_h;
  6884. if (content_h + deco_h > max_box)
  6885. content_h = max_box - deco_h;
  6886. }
  6887. if (st->min_height_kind &&
  6888. !((doc.nodes[node].tag == BR_TAG_HTML ||
  6889. doc.nodes[node].tag == BR_TAG_BODY) &&
  6890. st->min_height_kind == 2)) {
  6891. int mh = st->min_height_kind == 3 ?
  6892. cbw * st->min_height_calc_pct / 100 +
  6893. st->min_height_calc_px :
  6894. css_size(st->min_height_kind, st->min_height, cbw);
  6895. int min_box = st->box_sizing ? mh : mh + deco_h;
  6896. if (content_h + deco_h < min_box)
  6897. content_h = min_box - deco_h;
  6898. }
  6899. if (content_h < 0)
  6900. content_h = 0;
  6901. box_h = deco_h + content_h;
  6902. if (box_h < 0)
  6903. box_h = 0;
  6904. l->y = (shifted ? normal_top : top) + box_h;
  6905. if (node < BR_MAX_NODES) {
  6906. layout_boxes[node].x = l0;
  6907. layout_boxes[node].y = top;
  6908. layout_boxes[node].w = r0 - l0;
  6909. layout_boxes[node].h = box_h;
  6910. layout_boxes[node].valid = r0 > l0;
  6911. }
  6912. l->left = old_left;
  6913. l->right = old_right;
  6914. l->align = old_align;
  6915. l->y += mp_px(st, 2, cbw);
  6916. if (!l->draw) {
  6917. if (box_h > 65535)
  6918. box_h = 65535;
  6919. block_h[node] = (unsigned short)box_h;
  6920. block_top[node] = (unsigned short)(top < 0 ? 0 :
  6921. top > 65535 ? 65535 : top);
  6922. }
  6923. if (positioned) {
  6924. l->y = flow_y;
  6925. l->left = flow_left;
  6926. l->right = flow_right;
  6927. }
  6928. l->parent_top = saved_parent_top;
  6929. l->cb_left = saved_cb_left;
  6930. l->cb_right = saved_cb_right;
  6931. l->cb_top = saved_cb_top;
  6932. }
  6933. static int text_node_blank(const struct br_node *nd)
  6934. {
  6935. const char *t = doc.text + nd->text_off;
  6936. unsigned int i;
  6937. for (i = 0; i < nd->text_len; i++)
  6938. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  6939. t[i] != '\r')
  6940. return 0;
  6941. return 1;
  6942. }
  6943. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  6944. * text/image widths in the subtree, plus padding and margins. This keeps
  6945. * Bootstrap's floated nav items on one line instead of giving each the whole
  6946. * row. */
  6947. static int text_space(char c)
  6948. {
  6949. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  6950. }
  6951. static int intrinsic_width(struct ngui *ui, unsigned int node,
  6952. const struct br_style *pst, int depth, int base)
  6953. {
  6954. unsigned int c;
  6955. int line_w = 0, max_w = 0;
  6956. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  6957. if (depth > 32)
  6958. return 0;
  6959. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  6960. struct br_node *nd = &doc.nodes[c];
  6961. struct br_style cs;
  6962. if (nd->type == BR_NODE_TEXT) {
  6963. const char *t = doc.text + nd->text_off;
  6964. unsigned int tn = nd->text_len;
  6965. if (doc.nodes[node].tag == BR_TAG_PRE) {
  6966. line_w += (int)face_text_width(ui, pst, t, tn);
  6967. } else {
  6968. unsigned int ti = 0;
  6969. int first = 1;
  6970. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  6971. int sp = (int)face_text_width(ui, pst, " ", 1);
  6972. while (ti < tn) {
  6973. unsigned int ts;
  6974. while (ti < tn && text_space(t[ti]))
  6975. ti++;
  6976. ts = ti;
  6977. while (ti < tn && !text_space(t[ti]))
  6978. ti++;
  6979. if (ti == ts)
  6980. break;
  6981. if (!first || lead)
  6982. line_w += sp;
  6983. lead = 0;
  6984. line_w += (int)face_text_width(ui, pst,
  6985. t + ts, ti - ts);
  6986. first = 0;
  6987. }
  6988. }
  6989. continue;
  6990. }
  6991. br_style_for(&doc, c, pst, &cs);
  6992. if (cs.display == BR_DISPLAY_NONE)
  6993. continue;
  6994. if (nd->tag == BR_TAG_BR) {
  6995. if (line_w > max_w)
  6996. max_w = line_w;
  6997. line_w = 0;
  6998. continue;
  6999. }
  7000. if (nd->tag == BR_TAG_IMG) {
  7001. /* Measure the image as layout will draw it: a CSS or
  7002. * attribute height keeps the intrinsic aspect ratio, and
  7003. * a CSS width overrides the native pixel width. Bootstrap
  7004. * sizes the Cloudron logo with height:40px only. */
  7005. int idx = nd->img_index;
  7006. int iw = 0, ih = 0;
  7007. if (idx >= 0 && idx < image_count &&
  7008. images[idx].state == 1) {
  7009. iw = (int)images[idx].native_w;
  7010. ih = (int)images[idx].native_h;
  7011. if (iw <= 0 || ih <= 0) {
  7012. iw = (int)images[idx].img.w;
  7013. ih = (int)images[idx].img.h;
  7014. }
  7015. }
  7016. if (cs.width_kind) {
  7017. int ww = style_width_px(&cs, base);
  7018. line_w += ww > 0 ? ww : 64;
  7019. } else if (nd->width_attr) {
  7020. line_w += nd->width_attr;
  7021. } else if (nd->height_attr && iw && ih) {
  7022. line_w += iw * (int)nd->height_attr / ih;
  7023. } else if (cs.height_kind && iw && ih) {
  7024. int hh = style_height_px(&cs, base);
  7025. line_w += hh > 0 ? iw * hh / ih : iw;
  7026. } else if (iw) {
  7027. line_w += iw;
  7028. } else {
  7029. line_w += 64;
  7030. }
  7031. continue;
  7032. }
  7033. {
  7034. int cw = mp_px(&cs, 7, base) +
  7035. mp_px(&cs, 5, base) +
  7036. mp_px(&cs, 3, base) +
  7037. mp_px(&cs, 1, base) +
  7038. cs.border_w[1] + cs.border_w[3];
  7039. /* width/height do not apply to non-replaced inline
  7040. * boxes. The tagesschau home label is an inline span
  7041. * with width:1px for the mobile icon-only header; using
  7042. * that width made the whole subnav collapse to a
  7043. * one-character column. */
  7044. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  7045. cw += cs.width_kind == 1 ? cs.width :
  7046. style_width_px(&cs, base);
  7047. else
  7048. cw += intrinsic_width(ui, c, &cs, depth + 1,
  7049. base);
  7050. if (flex_row || cs.float_left ||
  7051. cs.display == BR_DISPLAY_INLINE ||
  7052. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  7053. line_w += cw;
  7054. } else {
  7055. if (line_w > max_w)
  7056. max_w = line_w;
  7057. line_w = 0;
  7058. if (cw > max_w)
  7059. max_w = cw;
  7060. }
  7061. }
  7062. if (line_w > 4096 || max_w > 4096)
  7063. break;
  7064. }
  7065. return line_w > max_w ? line_w : max_w;
  7066. }
  7067. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  7068. * the main user: .row > .col-md-* with float:left and a percentage width.
  7069. * Each column is laid out with its own left/right edge and the row advances
  7070. * to the tallest column. Returns the first child not consumed. */
  7071. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  7072. const struct br_style *pst, int depth,
  7073. unsigned short link)
  7074. {
  7075. unsigned int n = first;
  7076. int row_left = l->left, row_right = l->right;
  7077. int row_top, row_bottom, xl, xr, any = 0;
  7078. int fl_left = row_left, fl_right = row_right, fl_bottom;
  7079. flush_line(l);
  7080. row_top = l->y;
  7081. row_bottom = l->y;
  7082. fl_bottom = row_top;
  7083. xl = row_left;
  7084. xr = row_right;
  7085. while (n) {
  7086. struct br_node *nd = &doc.nodes[n];
  7087. struct br_style cs;
  7088. unsigned short lk = link;
  7089. int colw, right;
  7090. if (nd->type == BR_NODE_TEXT) {
  7091. if (text_node_blank(nd)) {
  7092. n = nd->next;
  7093. continue;
  7094. }
  7095. break;
  7096. }
  7097. br_style_for(&doc, n, pst, &cs);
  7098. if (cs.display == BR_DISPLAY_NONE) {
  7099. n = nd->next;
  7100. continue;
  7101. }
  7102. /* A float blockifies its box: Bootstrap floats inline
  7103. * anchors too (the navbar brand and its text links), and
  7104. * their padding must be honoured. */
  7105. if (!cs.float_left)
  7106. break;
  7107. if (nd->tag == BR_TAG_A && nd->href_off)
  7108. lk = (unsigned short)n;
  7109. right = cs.float_left == 2;
  7110. if (cs.width_kind == 2 || cs.width_kind == 3) {
  7111. colw = style_width_px(&cs, row_right - row_left);
  7112. } else if (cs.width_kind == 1) {
  7113. colw = (int)cs.width;
  7114. } else {
  7115. int base = row_right - row_left;
  7116. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  7117. mp_px(&cs, 7, base) +
  7118. mp_px(&cs, 5, base) +
  7119. mp_px(&cs, 3, base) +
  7120. mp_px(&cs, 1, base);
  7121. if (colw < 8)
  7122. colw = 8;
  7123. }
  7124. if (colw < 8)
  7125. colw = 8;
  7126. if (colw > row_right - row_left)
  7127. colw = row_right - row_left;
  7128. /* The float column width is already resolved. */
  7129. cs.width_kind = 0;
  7130. cs.max_width_kind = 0;
  7131. if (right) {
  7132. if (any && xr - colw < xl) {
  7133. row_top = row_bottom;
  7134. row_bottom = row_top;
  7135. xl = row_left;
  7136. xr = row_right;
  7137. }
  7138. if (xr - colw < xl)
  7139. colw = xr - xl;
  7140. if (colw < 8)
  7141. colw = 8;
  7142. l->left = xr - colw;
  7143. if (l->left < row_left)
  7144. l->left = row_left;
  7145. l->right = xr;
  7146. xr = l->left;
  7147. if (xr < fl_right)
  7148. fl_right = xr;
  7149. } else {
  7150. if (any && xl + colw > xr) {
  7151. row_top = row_bottom;
  7152. row_bottom = row_top;
  7153. xl = row_left;
  7154. xr = row_right;
  7155. }
  7156. l->left = xl;
  7157. l->right = xl + colw;
  7158. xl += colw;
  7159. if (xl > fl_left)
  7160. fl_left = xl;
  7161. }
  7162. if (l->right < l->left + 8)
  7163. l->right = l->left + 8;
  7164. l->y = row_top;
  7165. l->line_x = l->left;
  7166. l->run_x = l->left;
  7167. l->line_y = l->y;
  7168. l->line_h = 0;
  7169. l->nruns = 0;
  7170. l->space_pending = 0;
  7171. l->align = cs.align;
  7172. layout_block(l, n, &cs, depth + 1, lk);
  7173. if (l->y > row_bottom)
  7174. row_bottom = l->y;
  7175. if (l->y > fl_bottom)
  7176. fl_bottom = l->y;
  7177. any = 1;
  7178. n = nd->next;
  7179. }
  7180. l->left = row_left;
  7181. l->right = row_right;
  7182. if (n && any) {
  7183. struct br_node *nd = &doc.nodes[n];
  7184. int inline_next = 0;
  7185. if (nd->type == BR_NODE_TEXT) {
  7186. inline_next = 1;
  7187. } else if (nd->type == BR_NODE_ELEM) {
  7188. struct br_style cs;
  7189. br_style_for(&doc, n, pst, &cs);
  7190. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  7191. cs.display != BR_DISPLAY_NONE &&
  7192. !br_tag_is_block(nd->tag);
  7193. }
  7194. if (inline_next) {
  7195. if (l->float_active) {
  7196. if (l->float_left > fl_left)
  7197. fl_left = l->float_left;
  7198. if (l->float_right < fl_right)
  7199. fl_right = l->float_right;
  7200. if (l->float_bottom > fl_bottom)
  7201. fl_bottom = l->float_bottom;
  7202. }
  7203. l->float_active = 1;
  7204. l->float_left = fl_left;
  7205. l->float_right = fl_right;
  7206. l->float_bottom = fl_bottom;
  7207. l->y = row_top;
  7208. } else {
  7209. l->float_active = 0;
  7210. l->y = row_bottom;
  7211. }
  7212. } else {
  7213. l->float_active = 0;
  7214. l->y = row_bottom;
  7215. }
  7216. l->line_x = l->left;
  7217. l->run_x = l->left;
  7218. l->line_left = l->left;
  7219. l->line_right = l->right;
  7220. l->line_y = l->y;
  7221. l->line_h = 0;
  7222. l->nruns = 0;
  7223. l->space_pending = 0;
  7224. return n;
  7225. }
  7226. static int flex_item_width(struct lay *l, unsigned int n,
  7227. const struct br_style *cs, int avail)
  7228. {
  7229. struct br_node *nd = &doc.nodes[n];
  7230. (void)l;
  7231. int w;
  7232. if (cs->width_kind == 2 || cs->width_kind == 3)
  7233. w = style_width_px(cs, avail);
  7234. else if (cs->width_kind == 1)
  7235. w = (int)cs->width;
  7236. else if (nd->tag == BR_TAG_IMG) {
  7237. int idx = nd->img_index;
  7238. if (idx >= 0 && idx < image_count &&
  7239. images[idx].state == 1)
  7240. w = (int)images[idx].img.w;
  7241. else if (nd->width_attr)
  7242. w = (int)nd->width_attr;
  7243. else
  7244. w = 64;
  7245. } else {
  7246. w = intrinsic_width(l->ui, n, cs, 0, avail);
  7247. }
  7248. /* Explicit widths are content-box sizes; the flex item's outer width
  7249. * must include padding, borders and margins. */
  7250. w += mp_px(cs, 7, avail);
  7251. w += mp_px(cs, 5, avail);
  7252. w += mp_px(cs, 3, avail);
  7253. w += mp_px(cs, 1, avail);
  7254. w += cs->border_w[1] + cs->border_w[3];
  7255. if (w < 24)
  7256. w = 24;
  7257. if (w > avail)
  7258. w = avail;
  7259. return w;
  7260. }
  7261. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  7262. * on one line, not one full-width block each. Place intrinsic widths from
  7263. * left to right and wrap when the row is full. */
  7264. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  7265. const struct br_style *pst, int depth,
  7266. unsigned short link)
  7267. {
  7268. unsigned int n = first;
  7269. int row_left = l->left, row_right = l->right;
  7270. int avail = row_right - row_left;
  7271. int x = row_left, y = l->y, row_h = 0, any = 0;
  7272. flush_line(l);
  7273. y = l->y;
  7274. while (n) {
  7275. struct br_node *nd = &doc.nodes[n];
  7276. struct br_style cs;
  7277. unsigned short lk = link;
  7278. int colw, h;
  7279. if (nd->type == BR_NODE_TEXT) {
  7280. if (!text_node_blank(nd))
  7281. break;
  7282. if (any)
  7283. x += 4;
  7284. n = nd->next;
  7285. continue;
  7286. }
  7287. br_style_for(&doc, n, pst, &cs);
  7288. if (cs.display == BR_DISPLAY_NONE) {
  7289. n = nd->next;
  7290. continue;
  7291. }
  7292. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  7293. break;
  7294. if (nd->tag == BR_TAG_A && nd->href_off)
  7295. lk = (unsigned short)n;
  7296. colw = flex_item_width(l, n, &cs, avail);
  7297. /* A few pixels of slack keep a single long token (boot.S)
  7298. * from wrapping at the exact content width. */
  7299. colw += 8;
  7300. if (colw > avail)
  7301. colw = avail;
  7302. cs.width_kind = 0;
  7303. cs.max_width_kind = 0;
  7304. if (any && x + colw > row_right) {
  7305. y += row_h + 2;
  7306. x = row_left;
  7307. row_h = 0;
  7308. any = 0;
  7309. }
  7310. if (any && x > row_left)
  7311. x += 4;
  7312. l->left = x;
  7313. l->right = x + colw;
  7314. if (l->right < l->left + 8)
  7315. l->right = l->left + 8;
  7316. l->y = y;
  7317. l->line_x = l->left;
  7318. l->run_x = l->left;
  7319. l->line_y = l->y;
  7320. l->line_h = 0;
  7321. l->nruns = 0;
  7322. l->space_pending = 0;
  7323. l->align = cs.align;
  7324. layout_block(l, n, &cs, depth + 1, lk);
  7325. h = l->y - y;
  7326. if (h > row_h)
  7327. row_h = h;
  7328. x += colw;
  7329. any = 1;
  7330. n = nd->next;
  7331. }
  7332. if (any)
  7333. y += row_h;
  7334. l->left = row_left;
  7335. l->right = row_right;
  7336. l->y = y;
  7337. l->line_x = l->left;
  7338. l->run_x = l->left;
  7339. l->line_y = l->y;
  7340. l->line_h = 0;
  7341. l->nruns = 0;
  7342. l->space_pending = 0;
  7343. return n;
  7344. }
  7345. struct flex_item {
  7346. unsigned int node;
  7347. unsigned short link;
  7348. int w;
  7349. };
  7350. static void layout_flex_children(struct lay *l, unsigned int parent,
  7351. const struct br_style *pst, int depth,
  7352. unsigned short link)
  7353. {
  7354. struct flex_item it[32];
  7355. unsigned int c;
  7356. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  7357. int row_left = l->left, row_right = l->right;
  7358. int avail = row_right - row_left;
  7359. int idx, row_top;
  7360. if (avail < 160 || depth > 48) {
  7361. layout_children(l, parent, pst, depth, link);
  7362. return;
  7363. }
  7364. /* If direct text is not just whitespace, normal block flow handles it
  7365. * better than pretending it is a flex item. */
  7366. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7367. struct br_node *nd = &doc.nodes[c];
  7368. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7369. layout_children(l, parent, pst, depth, link);
  7370. return;
  7371. }
  7372. }
  7373. for (c = doc.nodes[parent].first;
  7374. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  7375. c = doc.nodes[c].next) {
  7376. struct br_node *nd = &doc.nodes[c];
  7377. struct br_style cs;
  7378. if (nd->type == BR_NODE_TEXT)
  7379. continue;
  7380. br_style_for(&doc, c, pst, &cs);
  7381. if (cs.display == BR_DISPLAY_NONE)
  7382. continue;
  7383. it[nitem].node = c;
  7384. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  7385. (unsigned short)c : link;
  7386. it[nitem].w = 0;
  7387. if (cs.flex_grow && !cs.width_kind)
  7388. grow_count++;
  7389. else
  7390. fixed += flex_item_width(l, c, &cs, avail);
  7391. nitem++;
  7392. }
  7393. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  7394. if (grow_w < 96)
  7395. grow_w = 96;
  7396. for (idx = 0; idx < nitem; idx++) {
  7397. struct br_style cs;
  7398. br_style_for(&doc, it[idx].node, pst, &cs);
  7399. if (cs.flex_grow && !cs.width_kind)
  7400. it[idx].w = grow_w;
  7401. else
  7402. it[idx].w = flex_item_width(l, it[idx].node, &cs, avail);
  7403. if (it[idx].w > avail)
  7404. it[idx].w = avail;
  7405. if (it[idx].w < 8)
  7406. it[idx].w = 8;
  7407. }
  7408. row_top = l->y;
  7409. idx = 0;
  7410. while (idx < nitem) {
  7411. int start = idx, count = 0, row_w = 0;
  7412. int free_w, x, extra = 0, row_h = 0, k;
  7413. while (idx < nitem) {
  7414. int add = it[idx].w + (count ? gap : 0);
  7415. /* CSS default is nowrap; only flex-wrap: wrap (1)
  7416. * starts a new row. */
  7417. if (count && pst->flex_wrap == 1 &&
  7418. row_w + add > avail)
  7419. break;
  7420. row_w += add;
  7421. count++;
  7422. idx++;
  7423. }
  7424. if (!count) {
  7425. count = 1;
  7426. row_w = it[start].w;
  7427. idx = start + 1;
  7428. }
  7429. free_w = avail - row_w;
  7430. if (free_w < 0)
  7431. free_w = 0;
  7432. x = row_left;
  7433. if (pst->justify == 1) {
  7434. x += free_w / 2;
  7435. } else if (pst->justify == 2) {
  7436. x += free_w;
  7437. } else if (pst->justify == 3) {
  7438. extra = count > 1 ? free_w / (count - 1) : 0;
  7439. } else if (pst->justify == 4) {
  7440. extra = count ? free_w / count : 0;
  7441. x += extra / 2;
  7442. } else if (pst->justify == 5) {
  7443. extra = count ? free_w / (count + 1) : 0;
  7444. x += extra;
  7445. }
  7446. for (k = 0; k < count; k++) {
  7447. int node = (int)it[start + k].node;
  7448. int h = block_h[node];
  7449. if (h > row_h)
  7450. row_h = h;
  7451. }
  7452. if (pst->height_kind) {
  7453. int hh = style_height_px(pst, avail);
  7454. if (hh > row_h)
  7455. row_h = hh;
  7456. }
  7457. for (k = 0; k < count; k++) {
  7458. struct br_style cs;
  7459. int node = (int)it[start + k].node;
  7460. int yoff = 0;
  7461. br_style_for(&doc, node, pst, &cs);
  7462. cs.width_kind = 0;
  7463. cs.max_width_kind = 0;
  7464. if (l->draw && pst->align_items &&
  7465. row_h > block_h[node]) {
  7466. if (pst->align_items == 1)
  7467. yoff = (row_h - block_h[node]) / 2;
  7468. else if (pst->align_items == 2)
  7469. yoff = row_h - block_h[node];
  7470. }
  7471. l->left = x;
  7472. l->right = x + it[start + k].w;
  7473. if (l->right < l->left + 8)
  7474. l->right = l->left + 8;
  7475. l->y = row_top + yoff;
  7476. l->line_x = l->left;
  7477. l->run_x = l->left;
  7478. l->line_y = l->y;
  7479. l->line_h = 0;
  7480. l->nruns = 0;
  7481. l->space_pending = 0;
  7482. l->align = cs.align;
  7483. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  7484. if (!l->draw) {
  7485. int h = l->y - row_top;
  7486. if (h > row_h)
  7487. row_h = h;
  7488. }
  7489. x += it[start + k].w;
  7490. if (k + 1 < count)
  7491. x += gap + extra;
  7492. }
  7493. row_top += row_h;
  7494. }
  7495. l->left = row_left;
  7496. l->right = row_right;
  7497. l->y = row_top;
  7498. l->line_x = l->left;
  7499. l->run_x = l->left;
  7500. l->line_y = l->y;
  7501. l->line_h = 0;
  7502. l->nruns = 0;
  7503. l->space_pending = 0;
  7504. }
  7505. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  7506. * plus the grid-area hints used by site shells (site notice/footer full
  7507. * width, column-start left, page-content right). Anything more elaborate
  7508. * falls back to normal block flow. */
  7509. static int grid_track_width(unsigned char kind, unsigned short val,
  7510. int avail, int other)
  7511. {
  7512. if (kind == 2)
  7513. return avail * (int)val / 100;
  7514. if (kind == 1)
  7515. return val;
  7516. return other;
  7517. }
  7518. static void layout_grid_children(struct lay *l, unsigned int parent,
  7519. const struct br_style *pst, int depth,
  7520. unsigned short link)
  7521. {
  7522. unsigned int n;
  7523. int row_left = l->left, row_right = l->right;
  7524. int avail = row_right - row_left;
  7525. int gap = pst->grid_gap;
  7526. int track_total = avail - gap;
  7527. int col0, col1, x0, x1;
  7528. int row_y, row_bottom, have_left = 0, have_right = 0;
  7529. unsigned int c;
  7530. if (avail < 32 || depth > 48)
  7531. return;
  7532. if (track_total < 16)
  7533. track_total = 16;
  7534. col0 = grid_track_width((unsigned char)(pst->width_kind),
  7535. pst->width, track_total, 0);
  7536. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  7537. pst->max_width, track_total, 0);
  7538. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  7539. int w0 = pst->width ? pst->width : 1;
  7540. int w1 = pst->max_width ? pst->max_width : 1;
  7541. col0 = track_total * w0 / (w0 + w1);
  7542. col1 = track_total - col0;
  7543. } else if (pst->width_kind == 3) {
  7544. col0 = track_total - col1;
  7545. if (col0 < 24)
  7546. col0 = 24;
  7547. } else if (pst->max_width_kind == 3) {
  7548. col1 = track_total - col0;
  7549. if (col1 < 24)
  7550. col1 = 24;
  7551. }
  7552. if (col0 < 24)
  7553. col0 = 24;
  7554. if (col1 < 24)
  7555. col1 = 24;
  7556. if (col0 + col1 > track_total) {
  7557. col1 = track_total - col0;
  7558. if (col1 < 24)
  7559. col1 = 24;
  7560. }
  7561. x0 = row_left;
  7562. x1 = row_left + col0 + gap;
  7563. /* Direct text makes a grid ambiguous; use block flow instead. */
  7564. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7565. struct br_node *nd = &doc.nodes[c];
  7566. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7567. layout_children(l, parent, pst, depth, link);
  7568. return;
  7569. }
  7570. }
  7571. row_y = row_bottom = l->y;
  7572. n = doc.nodes[parent].first;
  7573. while (n) {
  7574. struct br_node *nd = &doc.nodes[n];
  7575. struct br_style cs;
  7576. unsigned short lk = link;
  7577. int slot, x, w;
  7578. if (nd->type == BR_NODE_TEXT) {
  7579. n = nd->next;
  7580. continue;
  7581. }
  7582. br_style_for(&doc, n, pst, &cs);
  7583. if (cs.display == BR_DISPLAY_NONE) {
  7584. n = nd->next;
  7585. continue;
  7586. }
  7587. if (nd->tag == BR_TAG_A && nd->href_off)
  7588. lk = (unsigned short)n;
  7589. slot = cs.grid_slot;
  7590. if (!slot) {
  7591. if (!have_left)
  7592. slot = 2;
  7593. else if (!have_right)
  7594. slot = 3;
  7595. else
  7596. slot = 2;
  7597. }
  7598. if (slot == 1) {
  7599. if (have_left || have_right) {
  7600. row_y = row_bottom;
  7601. have_left = have_right = 0;
  7602. }
  7603. x = row_left;
  7604. w = avail;
  7605. } else if (slot == 2) {
  7606. if (have_left) {
  7607. row_y = row_bottom;
  7608. have_left = have_right = 0;
  7609. }
  7610. x = x0;
  7611. w = col0;
  7612. have_left = 1;
  7613. } else {
  7614. if (have_right) {
  7615. row_y = row_bottom;
  7616. have_left = have_right = 0;
  7617. }
  7618. x = x1;
  7619. w = col1;
  7620. have_right = 1;
  7621. }
  7622. cs.width_kind = 0;
  7623. cs.max_width_kind = 0;
  7624. l->left = x;
  7625. l->right = x + w;
  7626. if (l->right < l->left + 8)
  7627. l->right = l->left + 8;
  7628. l->y = row_y;
  7629. l->line_x = l->left;
  7630. l->run_x = l->left;
  7631. l->line_y = l->y;
  7632. l->line_h = 0;
  7633. l->nruns = 0;
  7634. l->space_pending = 0;
  7635. l->align = cs.align;
  7636. layout_block(l, n, &cs, depth + 1, lk);
  7637. if (l->y > row_bottom)
  7638. row_bottom = l->y;
  7639. n = nd->next;
  7640. }
  7641. l->left = row_left;
  7642. l->right = row_right;
  7643. l->y = row_bottom;
  7644. l->line_x = l->left;
  7645. l->run_x = l->left;
  7646. l->line_y = l->y;
  7647. l->line_h = 0;
  7648. l->nruns = 0;
  7649. l->space_pending = 0;
  7650. }
  7651. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  7652. * capped at four. Used by the project docs' card grids. */
  7653. static void layout_grid_auto(struct lay *l, unsigned int parent,
  7654. const struct br_style *pst, int depth,
  7655. unsigned short link)
  7656. {
  7657. unsigned int n, c;
  7658. int row_left = l->left, row_right = l->right;
  7659. int avail = row_right - row_left;
  7660. int gap = pst->grid_gap;
  7661. int minw = pst->width_kind == 1 ? pst->width : 200;
  7662. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  7663. if (avail < 32 || depth > 48) {
  7664. layout_children(l, parent, pst, depth, link);
  7665. return;
  7666. }
  7667. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7668. struct br_node *nd = &doc.nodes[c];
  7669. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7670. layout_children(l, parent, pst, depth, link);
  7671. return;
  7672. }
  7673. }
  7674. if (minw < 80)
  7675. minw = 80;
  7676. ncols = (avail + gap) / (minw + gap);
  7677. if (ncols < 1)
  7678. ncols = 1;
  7679. if (ncols > 4)
  7680. ncols = 4;
  7681. colw = (avail - gap * (ncols - 1)) / ncols;
  7682. if (colw < 24)
  7683. colw = 24;
  7684. x = row_left;
  7685. n = doc.nodes[parent].first;
  7686. while (n) {
  7687. struct br_node *nd = &doc.nodes[n];
  7688. struct br_style cs;
  7689. unsigned short lk = link;
  7690. int h;
  7691. if (nd->type == BR_NODE_TEXT) {
  7692. n = nd->next;
  7693. continue;
  7694. }
  7695. br_style_for(&doc, n, pst, &cs);
  7696. if (cs.display == BR_DISPLAY_NONE) {
  7697. n = nd->next;
  7698. continue;
  7699. }
  7700. if (nd->tag == BR_TAG_A && nd->href_off)
  7701. lk = (unsigned short)n;
  7702. cs.width_kind = 0;
  7703. cs.max_width_kind = 0;
  7704. l->left = x;
  7705. l->right = x + colw;
  7706. if (l->right < l->left + 8)
  7707. l->right = l->left + 8;
  7708. l->y = y;
  7709. l->line_x = l->left;
  7710. l->run_x = l->left;
  7711. l->line_y = l->y;
  7712. l->line_h = 0;
  7713. l->nruns = 0;
  7714. l->space_pending = 0;
  7715. l->align = cs.align;
  7716. layout_block(l, n, &cs, depth + 1, lk);
  7717. h = l->y - y;
  7718. if (h > row_h)
  7719. row_h = h;
  7720. col++;
  7721. n = nd->next;
  7722. if (col == ncols) {
  7723. y += row_h + gap;
  7724. x = row_left;
  7725. row_h = 0;
  7726. col = 0;
  7727. } else {
  7728. x += colw + gap;
  7729. }
  7730. }
  7731. if (col)
  7732. y += row_h;
  7733. else if (y > start_y)
  7734. y -= gap;
  7735. l->left = row_left;
  7736. l->right = row_right;
  7737. l->y = y;
  7738. l->line_x = l->left;
  7739. l->run_x = l->left;
  7740. l->line_y = l->y;
  7741. l->line_h = 0;
  7742. l->nruns = 0;
  7743. l->space_pending = 0;
  7744. }
  7745. /* Column widths are the widest cell in each column across every row, so all
  7746. * rows line up. The table model is still deliberately basic: no colspan,
  7747. * border-collapse or percentage columns. */
  7748. static void table_columns(struct lay *l, unsigned int table,
  7749. const struct br_style *pst, int avail,
  7750. int *raw, int maxcols, int *out_cols,
  7751. int *out_total)
  7752. {
  7753. unsigned int r, c;
  7754. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  7755. int fixed[12];
  7756. for (c = 0; c < (unsigned int)maxcols; c++) {
  7757. raw[c] = 0;
  7758. fixed[c] = 0;
  7759. }
  7760. /* Intrinsic widths of single-column cells. */
  7761. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7762. struct br_node *rn = &doc.nodes[r];
  7763. int col = 0;
  7764. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7765. continue;
  7766. for (c = rn->first; c; c = doc.nodes[c].next) {
  7767. struct br_node *cn = &doc.nodes[c];
  7768. struct br_style cs;
  7769. int w, span;
  7770. if (cn->type != BR_NODE_ELEM ||
  7771. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  7772. continue;
  7773. span = cn->colspan ? cn->colspan : 1;
  7774. br_style_for(&doc, c, pst, &cs);
  7775. if (cs.display == BR_DISPLAY_NONE)
  7776. continue;
  7777. if (col + span > maxcols)
  7778. span = maxcols - col;
  7779. if (span < 1)
  7780. break;
  7781. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  7782. mp_px(&cs, 7, avail) +
  7783. mp_px(&cs, 5, avail) +
  7784. mp_px(&cs, 3, avail) +
  7785. mp_px(&cs, 1, avail) +
  7786. cs.border_w[0] + cs.border_w[1] +
  7787. cs.border_w[2] + cs.border_w[3];
  7788. if (w < 24)
  7789. w = 24;
  7790. if (span == 1) {
  7791. if (w > raw[col])
  7792. raw[col] = w;
  7793. }
  7794. if (col + span > cols)
  7795. cols = col + span;
  7796. col += span;
  7797. }
  7798. }
  7799. /* A colspan cell only has to be as wide as the sum of its columns. */
  7800. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7801. struct br_node *rn = &doc.nodes[r];
  7802. int col = 0;
  7803. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7804. continue;
  7805. for (c = rn->first; c; c = doc.nodes[c].next) {
  7806. struct br_node *cn = &doc.nodes[c];
  7807. struct br_style cs;
  7808. int span, w, sum, i;
  7809. if (cn->type != BR_NODE_ELEM ||
  7810. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  7811. continue;
  7812. span = cn->colspan ? cn->colspan : 1;
  7813. if (col + span > maxcols)
  7814. span = maxcols - col;
  7815. if (span < 1)
  7816. break;
  7817. if (span > 1) {
  7818. br_style_for(&doc, c, pst, &cs);
  7819. if (cs.display != BR_DISPLAY_NONE) {
  7820. w = intrinsic_width(l->ui, c, &cs,
  7821. 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. sum = 0;
  7829. for (i = 0; i < span; i++)
  7830. sum += raw[col + i];
  7831. if (w > sum)
  7832. raw[col + span - 1] += w - sum;
  7833. }
  7834. }
  7835. col += span;
  7836. }
  7837. }
  7838. /* Explicit and percentage widths override intrinsic widths. */
  7839. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7840. struct br_node *rn = &doc.nodes[r];
  7841. int col = 0;
  7842. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7843. continue;
  7844. for (c = rn->first; c; c = doc.nodes[c].next) {
  7845. struct br_node *cn = &doc.nodes[c];
  7846. struct br_style cs;
  7847. int span;
  7848. if (cn->type != BR_NODE_ELEM ||
  7849. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  7850. continue;
  7851. span = cn->colspan ? cn->colspan : 1;
  7852. if (col + span > maxcols)
  7853. span = maxcols - col;
  7854. if (span < 1)
  7855. break;
  7856. if (span == 1) {
  7857. br_style_for(&doc, c, pst, &cs);
  7858. if (cs.display != BR_DISPLAY_NONE) {
  7859. if (cs.width_kind == 1) {
  7860. raw[col] = cs.width;
  7861. fixed[col] = 1;
  7862. } else if (cs.width_kind == 2 ||
  7863. cs.width_kind == 3) {
  7864. raw[col] = style_width_px(&cs,
  7865. avail);
  7866. fixed[col] = 1;
  7867. }
  7868. }
  7869. }
  7870. col += span;
  7871. }
  7872. }
  7873. for (c = 0; c < (unsigned int)cols; c++) {
  7874. if (raw[c] < 8)
  7875. raw[c] = 8;
  7876. total += raw[c];
  7877. if (fixed[c])
  7878. fixed_sum += raw[c];
  7879. else {
  7880. free_raw += raw[c];
  7881. free_cols++;
  7882. }
  7883. }
  7884. if (fixed_sum > 0 && fixed_sum < avail) {
  7885. int free_avail = avail - fixed_sum;
  7886. int i;
  7887. if (free_raw > 0) {
  7888. for (i = 0; i < cols; i++)
  7889. if (!fixed[i])
  7890. raw[i] = free_avail * raw[i] /
  7891. free_raw;
  7892. } else if (free_cols > 0) {
  7893. for (i = 0; i < cols; i++)
  7894. if (!fixed[i])
  7895. raw[i] = free_avail / free_cols;
  7896. }
  7897. total = 0;
  7898. for (i = 0; i < cols; i++)
  7899. total += raw[i];
  7900. } else if (total < avail && total > 0) {
  7901. int i;
  7902. for (i = 0; i < cols; i++)
  7903. raw[i] = raw[i] * avail / total;
  7904. total = 0;
  7905. for (i = 0; i < cols; i++)
  7906. total += raw[i];
  7907. }
  7908. *out_cols = cols;
  7909. *out_total = total;
  7910. }
  7911. static void layout_table_row(struct lay *l, unsigned int row,
  7912. const struct br_style *pst, int depth,
  7913. unsigned short link)
  7914. {
  7915. unsigned int n, cell[12];
  7916. int raw[12], colstart[12], colspan[12];
  7917. int prefix[13];
  7918. int ncell = 0, total = 0, cols = 0, col = 0;
  7919. int row_left = l->left, row_right = l->right;
  7920. int avail = row_right - row_left;
  7921. int y = l->y, bottom = l->y;
  7922. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  7923. struct br_node *nd = &doc.nodes[n];
  7924. struct br_style cs;
  7925. int span;
  7926. if (nd->type == BR_NODE_TEXT) {
  7927. if (text_node_blank(nd))
  7928. continue;
  7929. layout_children(l, row, pst, depth, link);
  7930. return;
  7931. }
  7932. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  7933. layout_children(l, row, pst, depth, link);
  7934. return;
  7935. }
  7936. br_style_for(&doc, n, pst, &cs);
  7937. if (cs.display == BR_DISPLAY_NONE)
  7938. continue;
  7939. if (ncell >= 12) {
  7940. layout_children(l, row, pst, depth, link);
  7941. return;
  7942. }
  7943. span = nd->colspan ? nd->colspan : 1;
  7944. if (span > 12 - col)
  7945. span = 12 - col;
  7946. if (span < 1)
  7947. continue;
  7948. cell[ncell] = n;
  7949. colstart[ncell] = col;
  7950. colspan[ncell] = span;
  7951. col += span;
  7952. ncell++;
  7953. }
  7954. if (ncell < 1 || avail < 32) {
  7955. layout_children(l, row, pst, depth, link);
  7956. return;
  7957. }
  7958. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  7959. &total);
  7960. if (cols < 2 || total <= 0) {
  7961. int c;
  7962. total = 0;
  7963. for (c = 0; c < ncell; c++) {
  7964. struct br_style cs;
  7965. br_style_for(&doc, cell[c], pst, &cs);
  7966. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  7967. avail) +
  7968. mp_px(&cs, 7, avail) +
  7969. mp_px(&cs, 5, avail) +
  7970. mp_px(&cs, 3, avail) +
  7971. mp_px(&cs, 1, avail);
  7972. if (raw[c] < 24)
  7973. raw[c] = 24;
  7974. total += raw[c];
  7975. }
  7976. /* A one-column table still has to fill its own width; the
  7977. * intrinsic fallback above otherwise leaves the cell at its
  7978. * text width (HN's outer table and nested story table). */
  7979. if (total > 0 && total < avail) {
  7980. int c;
  7981. for (c = 0; c < ncell; c++)
  7982. raw[c] = raw[c] * avail / total;
  7983. total = avail;
  7984. }
  7985. }
  7986. prefix[0] = row_left;
  7987. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  7988. prefix[n + 1] = prefix[n] + raw[n];
  7989. for (n = 0; n < (unsigned int)ncell; n++) {
  7990. struct br_style cs;
  7991. int start = colstart[n];
  7992. int end = start + colspan[n];
  7993. int w;
  7994. if (end > cols)
  7995. end = cols;
  7996. if (start >= cols)
  7997. continue;
  7998. w = prefix[end] - prefix[start];
  7999. br_style_for(&doc, cell[n], pst, &cs);
  8000. /* The column width already reflects the cell's width property. */
  8001. cs.width_kind = 0;
  8002. cs.max_width_kind = 0;
  8003. if (w < 24)
  8004. w = 24;
  8005. if (w < 8)
  8006. w = 8;
  8007. l->left = prefix[start];
  8008. l->right = l->left + w;
  8009. l->y = y;
  8010. l->line_x = l->left;
  8011. l->run_x = l->left;
  8012. l->line_y = l->y;
  8013. l->line_h = 0;
  8014. l->nruns = 0;
  8015. l->space_pending = 0;
  8016. l->align = cs.align;
  8017. layout_block(l, cell[n], &cs, depth + 1, link);
  8018. if (l->y > bottom)
  8019. bottom = l->y;
  8020. }
  8021. l->left = row_left;
  8022. l->right = row_right;
  8023. l->y = bottom;
  8024. l->line_x = l->left;
  8025. l->run_x = l->left;
  8026. l->line_y = l->y;
  8027. l->line_h = 0;
  8028. l->nruns = 0;
  8029. l->space_pending = 0;
  8030. }
  8031. #define TBL_MAX_ROWS 32
  8032. #define TBL_MAX_COLS 12
  8033. #define TBL_MAX_CELLS 128
  8034. struct tbl_cell {
  8035. unsigned int node;
  8036. unsigned char row, col, rowspan, colspan;
  8037. int height;
  8038. };
  8039. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  8040. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  8041. static int table_active;
  8042. static int table_has_rowspan(unsigned int table)
  8043. {
  8044. unsigned int r, c;
  8045. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  8046. struct br_node *rn = &doc.nodes[r];
  8047. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  8048. continue;
  8049. for (c = rn->first; c; c = doc.nodes[c].next) {
  8050. struct br_node *cn = &doc.nodes[c];
  8051. if (cn->type == BR_NODE_ELEM &&
  8052. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  8053. cn->rowspan > 1)
  8054. return 1;
  8055. }
  8056. }
  8057. return 0;
  8058. }
  8059. static void table_cell_style(unsigned int row, unsigned int cell,
  8060. const struct br_style *st, struct br_style *out)
  8061. {
  8062. struct br_style trs;
  8063. br_style_for(&doc, row, st, &trs);
  8064. br_style_for(&doc, cell, &trs, out);
  8065. }
  8066. /* Tables that use rowspan need row heights before anything is painted. This
  8067. * path builds a small occupancy grid, measures the natural cell heights, then
  8068. * lays every cell out at its row/column position. Tables without rowspan
  8069. * keep the lighter per-row path in layout_table_row(). */
  8070. static void layout_table(struct lay *l, unsigned int table,
  8071. const struct br_style *st, int depth,
  8072. unsigned short link)
  8073. {
  8074. unsigned int rows[TBL_MAX_ROWS];
  8075. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  8076. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  8077. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  8078. int free_raw = 0, free_cols = 0;
  8079. int table_left = l->left, table_right = l->right;
  8080. int top = l->y, avail = table_right - table_left;
  8081. unsigned int r, c;
  8082. int i, rr, cc;
  8083. if (depth > 48 || table_active) {
  8084. layout_children(l, table, st, depth, link);
  8085. return;
  8086. }
  8087. table_active = 1;
  8088. for (r = doc.nodes[table].first;
  8089. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  8090. struct br_node *rn = &doc.nodes[r];
  8091. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  8092. rows[nrows++] = r;
  8093. }
  8094. if (!nrows) {
  8095. table_active = 0;
  8096. layout_children(l, table, st, depth, link);
  8097. return;
  8098. }
  8099. for (rr = 0; rr < nrows; rr++)
  8100. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  8101. tbl_at[rr][cc] = 0;
  8102. for (rr = 0; rr < nrows; rr++) {
  8103. int col = 0;
  8104. for (c = doc.nodes[rows[rr]].first; c;
  8105. c = doc.nodes[c].next) {
  8106. struct br_node *cn = &doc.nodes[c];
  8107. struct br_style cs;
  8108. int rs, csn;
  8109. if (cn->type != BR_NODE_ELEM ||
  8110. (cn->tag != BR_TAG_TD &&
  8111. cn->tag != BR_TAG_TH))
  8112. continue;
  8113. table_cell_style(rows[rr], c, st, &cs);
  8114. if (cs.display == BR_DISPLAY_NONE)
  8115. continue;
  8116. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  8117. col++;
  8118. if (col >= TBL_MAX_COLS)
  8119. break;
  8120. rs = cn->rowspan ? cn->rowspan : 1;
  8121. csn = cn->colspan ? cn->colspan : 1;
  8122. if (rr + rs > nrows)
  8123. rs = nrows - rr;
  8124. if (col + csn > TBL_MAX_COLS)
  8125. csn = TBL_MAX_COLS - col;
  8126. if (rs < 1 || csn < 1)
  8127. continue;
  8128. if (ncells >= TBL_MAX_CELLS)
  8129. break;
  8130. tbl_cells[ncells].node = c;
  8131. tbl_cells[ncells].row = (unsigned char)rr;
  8132. tbl_cells[ncells].col = (unsigned char)col;
  8133. tbl_cells[ncells].rowspan = (unsigned char)rs;
  8134. tbl_cells[ncells].colspan = (unsigned char)csn;
  8135. tbl_cells[ncells].height = 0;
  8136. for (i = rr; i < rr + rs; i++)
  8137. for (int j = col; j < col + csn; j++)
  8138. tbl_at[i][j] =
  8139. (unsigned short)(ncells + 1);
  8140. ncells++;
  8141. col += csn;
  8142. if (col > cols)
  8143. cols = col;
  8144. }
  8145. }
  8146. if (!ncells || cols < 1) {
  8147. table_active = 0;
  8148. layout_children(l, table, st, depth, link);
  8149. return;
  8150. }
  8151. for (i = 0; i < cols; i++) {
  8152. raw[i] = 0;
  8153. fixed[i] = 0;
  8154. }
  8155. /* Intrinsic widths of single-column cells. */
  8156. for (i = 0; i < ncells; i++) {
  8157. struct br_style cs;
  8158. int w;
  8159. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8160. st, &cs);
  8161. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  8162. mp_px(&cs, 7, avail) +
  8163. mp_px(&cs, 5, avail) +
  8164. mp_px(&cs, 3, avail) +
  8165. mp_px(&cs, 1, avail) +
  8166. cs.border_w[0] + cs.border_w[1] +
  8167. cs.border_w[2] + cs.border_w[3];
  8168. if (w < 24)
  8169. w = 24;
  8170. if (tbl_cells[i].colspan == 1) {
  8171. int col = tbl_cells[i].col;
  8172. if (w > raw[col])
  8173. raw[col] = w;
  8174. }
  8175. }
  8176. /* A spanning cell only needs the sum of its columns to be large
  8177. * enough; put the deficit in the last column. */
  8178. for (i = 0; i < ncells; i++) {
  8179. struct br_style cs;
  8180. int w, sum, col, span;
  8181. if (tbl_cells[i].colspan < 2)
  8182. continue;
  8183. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8184. st, &cs);
  8185. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  8186. mp_px(&cs, 7, avail) +
  8187. mp_px(&cs, 5, avail) +
  8188. mp_px(&cs, 3, avail) +
  8189. mp_px(&cs, 1, avail) +
  8190. cs.border_w[0] + cs.border_w[1] +
  8191. cs.border_w[2] + cs.border_w[3];
  8192. col = tbl_cells[i].col;
  8193. span = tbl_cells[i].colspan;
  8194. sum = 0;
  8195. for (int j = 0; j < span; j++)
  8196. sum += raw[col + j];
  8197. if (w > sum)
  8198. raw[col + span - 1] += w - sum;
  8199. }
  8200. /* Explicit/percentage widths, as in table_columns(). */
  8201. for (i = 0; i < ncells; i++) {
  8202. struct br_style cs;
  8203. int col;
  8204. if (tbl_cells[i].colspan != 1)
  8205. continue;
  8206. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8207. st, &cs);
  8208. col = tbl_cells[i].col;
  8209. if (cs.width_kind == 1) {
  8210. raw[col] = cs.width;
  8211. fixed[col] = 1;
  8212. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  8213. raw[col] = style_width_px(&cs, avail);
  8214. fixed[col] = 1;
  8215. }
  8216. }
  8217. for (i = 0; i < cols; i++) {
  8218. if (raw[i] < 8)
  8219. raw[i] = 8;
  8220. total += raw[i];
  8221. if (fixed[i])
  8222. fixed_sum += raw[i];
  8223. else {
  8224. free_raw += raw[i];
  8225. free_cols++;
  8226. }
  8227. }
  8228. if (fixed_sum > 0 && fixed_sum < avail) {
  8229. int free_avail = avail - fixed_sum;
  8230. if (free_raw > 0) {
  8231. for (i = 0; i < cols; i++)
  8232. if (!fixed[i])
  8233. raw[i] = free_avail * raw[i] /
  8234. free_raw;
  8235. } else if (free_cols > 0) {
  8236. for (i = 0; i < cols; i++)
  8237. if (!fixed[i])
  8238. raw[i] = free_avail / free_cols;
  8239. }
  8240. } else if (total < avail && total > 0) {
  8241. for (i = 0; i < cols; i++)
  8242. raw[i] = raw[i] * avail / total;
  8243. }
  8244. prefix[0] = table_left;
  8245. for (i = 0; i < cols; i++)
  8246. prefix[i + 1] = prefix[i] + raw[i];
  8247. /* Measure natural cell heights with the column widths. */
  8248. for (i = 0; i < ncells; i++) {
  8249. struct br_style cs;
  8250. int col = tbl_cells[i].col;
  8251. int span = tbl_cells[i].colspan;
  8252. int w = prefix[col + span] - prefix[col];
  8253. int sl = l->left, sr = l->right, sy = l->y;
  8254. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  8255. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  8256. int sal = l->align, sdraw = l->draw;
  8257. struct ngui *sui = l->ui;
  8258. if (w < 8)
  8259. w = 8;
  8260. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8261. st, &cs);
  8262. cs.width_kind = 0;
  8263. cs.max_width_kind = 0;
  8264. l->draw = 0;
  8265. l->ui = 0;
  8266. l->left = prefix[col];
  8267. l->right = l->left + w;
  8268. l->y = 0;
  8269. l->line_x = l->left;
  8270. l->run_x = l->left;
  8271. l->line_y = 0;
  8272. l->line_h = 0;
  8273. l->nruns = 0;
  8274. l->space_pending = 0;
  8275. l->align = cs.align;
  8276. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  8277. tbl_cells[i].height = block_h[tbl_cells[i].node];
  8278. l->left = sl;
  8279. l->right = sr;
  8280. l->y = sy;
  8281. l->line_x = slx;
  8282. l->run_x = srx;
  8283. l->line_y = sly;
  8284. l->line_h = slh;
  8285. l->nruns = snr;
  8286. l->space_pending = ssp;
  8287. l->align = sal;
  8288. l->draw = sdraw;
  8289. l->ui = sui;
  8290. }
  8291. for (i = 0; i < nrows; i++)
  8292. rowh[i] = 0;
  8293. for (i = 0; i < ncells; i++) {
  8294. int row = tbl_cells[i].row;
  8295. if (tbl_cells[i].rowspan == 1) {
  8296. if (tbl_cells[i].height > rowh[row])
  8297. rowh[row] = tbl_cells[i].height;
  8298. }
  8299. }
  8300. for (i = 0; i < ncells; i++) {
  8301. int row = tbl_cells[i].row;
  8302. int span = tbl_cells[i].rowspan;
  8303. int sum = 0;
  8304. if (span < 2)
  8305. continue;
  8306. for (int j = 0; j < span; j++)
  8307. sum += rowh[row + j];
  8308. if (sum < tbl_cells[i].height)
  8309. rowh[row + span - 1] +=
  8310. tbl_cells[i].height - sum;
  8311. }
  8312. for (i = 0; i < nrows; i++)
  8313. if (rowh[i] < 8)
  8314. rowh[i] = 8;
  8315. rowy[0] = top;
  8316. for (i = 1; i < nrows; i++)
  8317. rowy[i] = rowy[i - 1] + rowh[i - 1];
  8318. if (!l->draw) {
  8319. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  8320. table_active = 0;
  8321. return;
  8322. }
  8323. for (i = 0; i < ncells; i++) {
  8324. struct br_style cs;
  8325. int col = tbl_cells[i].col;
  8326. int span = tbl_cells[i].colspan;
  8327. int row = tbl_cells[i].row;
  8328. int rspan = tbl_cells[i].rowspan;
  8329. int w = prefix[col + span] - prefix[col];
  8330. int h = 0;
  8331. int sl = l->left, sr = l->right, sy = l->y;
  8332. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  8333. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  8334. int sal = l->align;
  8335. int deco;
  8336. for (int j = 0; j < rspan; j++)
  8337. h += rowh[row + j];
  8338. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  8339. cs.width_kind = 0;
  8340. cs.max_width_kind = 0;
  8341. cs.box_sizing = 0;
  8342. deco = mp_px(&cs, 4, avail) +
  8343. mp_px(&cs, 6, avail) +
  8344. cs.border_w[0] + cs.border_w[2];
  8345. cs.height_kind = 1;
  8346. cs.height = h > deco ? h - deco : 0;
  8347. /* The block painter reads block_h[] from the measure pass; make
  8348. * the table cell fill its row/rowspan, not just its content. */
  8349. if (h > 0 && h < 65536)
  8350. block_h[tbl_cells[i].node] = (unsigned short)h;
  8351. l->left = prefix[col];
  8352. l->right = l->left + w;
  8353. l->y = rowy[row];
  8354. l->line_x = l->left;
  8355. l->run_x = l->left;
  8356. l->line_y = l->y;
  8357. l->line_h = 0;
  8358. l->nruns = 0;
  8359. l->space_pending = 0;
  8360. l->align = cs.align;
  8361. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  8362. l->left = sl;
  8363. l->right = sr;
  8364. l->y = sy;
  8365. l->line_x = slx;
  8366. l->run_x = srx;
  8367. l->line_y = sly;
  8368. l->line_h = slh;
  8369. l->nruns = snr;
  8370. l->space_pending = ssp;
  8371. l->align = sal;
  8372. }
  8373. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  8374. table_active = 0;
  8375. }
  8376. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  8377. * flow so they sit above it, like CSS painting order. Their flow origin is
  8378. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  8379. struct br_deferred {
  8380. unsigned int node;
  8381. int flow_y, flow_left, flow_right;
  8382. unsigned short link;
  8383. signed short z_index;
  8384. unsigned char z_set;
  8385. unsigned int order;
  8386. };
  8387. /* Positioned boxes painted after the flow. News front pages have one or two
  8388. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  8389. * old 16 entries the rest fell back into the flow, so a hero image landed
  8390. * below its padding-top aspect box instead of on top of it. */
  8391. #define BR_MAX_DEFERRED 256
  8392. static struct br_deferred deferred[BR_MAX_DEFERRED];
  8393. static int ndeferred;
  8394. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  8395. * element's line. A block-level pseudo-element gets its own line; its box
  8396. * (margins, padding, background) is not drawn. */
  8397. static void emit_pseudo(struct lay *l, unsigned int node,
  8398. const struct br_style *st, int pe, unsigned short link)
  8399. {
  8400. char buf[160];
  8401. struct br_style ps;
  8402. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  8403. unsigned int i = 0;
  8404. int block, space_w;
  8405. if (!n)
  8406. return;
  8407. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  8408. if (block)
  8409. flush_line(l);
  8410. if (ps.uppercase)
  8411. for (i = 0; i < n; i++)
  8412. if (buf[i] >= 'a' && buf[i] <= 'z')
  8413. buf[i] = (char)(buf[i] - 'a' + 'A');
  8414. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  8415. if (space_w <= 0)
  8416. space_w = 8;
  8417. i = 0;
  8418. while (i < n) {
  8419. char word[28];
  8420. unsigned int k = 0;
  8421. int w;
  8422. if (buf[i] == ' ') {
  8423. l->space_pending = 1;
  8424. i++;
  8425. continue;
  8426. }
  8427. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  8428. word[k++] = buf[i++];
  8429. word[k] = '\0';
  8430. if (l->space_pending &&
  8431. (l->nruns > 0 || l->line_x > l->line_left) &&
  8432. l->line_x + space_w <= l->line_right)
  8433. l->line_x += space_w;
  8434. l->space_pending = 0;
  8435. w = (int)face_text_width(l->ui, &ps, word, k);
  8436. if (l->line_x + w > l->line_right &&
  8437. (l->nruns > 0 || l->line_x > l->line_left))
  8438. flush_line(l);
  8439. add_run(l, 0, 0, &ps, link, word);
  8440. }
  8441. if (block)
  8442. flush_line(l);
  8443. }
  8444. static void layout_children(struct lay *l, unsigned int parent,
  8445. const struct br_style *pst, int depth,
  8446. unsigned short link)
  8447. {
  8448. unsigned int n;
  8449. if (depth > 48)
  8450. return;
  8451. emit_pseudo(l, parent, pst, 1, link);
  8452. n = doc.nodes[parent].first;
  8453. while (n) {
  8454. struct br_node *nd = &doc.nodes[n];
  8455. struct br_style cs;
  8456. unsigned short lk = link;
  8457. if (nd->type == BR_NODE_TEXT) {
  8458. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  8459. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  8460. n = nd->next;
  8461. continue;
  8462. }
  8463. br_style_for(&doc, n, pst, &cs);
  8464. if (cs.display == BR_DISPLAY_NONE) {
  8465. n = nd->next;
  8466. continue;
  8467. }
  8468. if (cs.clear && l->float_active) {
  8469. flush_line(l);
  8470. if (l->y < l->float_bottom)
  8471. l->y = l->float_bottom;
  8472. l->float_active = 0;
  8473. l->line_x = l->left;
  8474. l->run_x = l->left;
  8475. l->line_left = l->left;
  8476. l->line_right = l->right;
  8477. l->line_y = l->y;
  8478. l->line_h = 0;
  8479. l->nruns = 0;
  8480. l->space_pending = 0;
  8481. }
  8482. if (nd->tag == BR_TAG_A && nd->href_off)
  8483. lk = (unsigned short)n;
  8484. if (cs.pos == 1 || cs.pos == 2 ||
  8485. (cs.pos == 3 && cs.z_set)) {
  8486. if (cs.pos == 3 && l->draw &&
  8487. ndeferred < BR_MAX_DEFERRED) {
  8488. /* Relative z-index: measure and advance the flow
  8489. * without painting, then paint it in the
  8490. * deferred (stacked) pass. */
  8491. int fy = l->y, fl = l->left, fr = l->right;
  8492. int save_draw = l->draw;
  8493. l->draw = 0;
  8494. layout_block(l, n, &cs, depth + 1, lk);
  8495. l->draw = save_draw;
  8496. deferred[ndeferred].node = n;
  8497. deferred[ndeferred].flow_y = fy;
  8498. deferred[ndeferred].flow_left = fl;
  8499. deferred[ndeferred].flow_right = fr;
  8500. deferred[ndeferred].link = lk;
  8501. deferred[ndeferred].z_index = cs.z_index;
  8502. deferred[ndeferred].z_set = cs.z_set;
  8503. deferred[ndeferred].order = (unsigned int)ndeferred;
  8504. ndeferred++;
  8505. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  8506. deferred[ndeferred].node = n;
  8507. deferred[ndeferred].flow_y =
  8508. cs.pos == 1 ? l->cb_top : l->y;
  8509. deferred[ndeferred].flow_left =
  8510. cs.pos == 1 ? l->cb_left : l->left;
  8511. deferred[ndeferred].flow_right =
  8512. cs.pos == 1 ? l->cb_right : l->right;
  8513. deferred[ndeferred].link = lk;
  8514. deferred[ndeferred].z_index = cs.z_index;
  8515. deferred[ndeferred].z_set = cs.z_set;
  8516. deferred[ndeferred].order = (unsigned int)ndeferred;
  8517. ndeferred++;
  8518. } else if (l->draw && cs.pos == 1) {
  8519. /* Deferred list full: paint in place, but still
  8520. * against the containing block, not the flow. */
  8521. int fy = l->y, fl = l->left, fr = l->right;
  8522. l->y = l->cb_top;
  8523. l->left = l->cb_left;
  8524. l->right = l->cb_right;
  8525. layout_block(l, n, &cs, depth + 1, lk);
  8526. l->y = fy;
  8527. l->left = fl;
  8528. l->right = fr;
  8529. } else {
  8530. layout_block(l, n, &cs, depth + 1, lk);
  8531. }
  8532. if (cs.pos == 1 && block_h[n] &&
  8533. doc.nodes[n].class_off) {
  8534. const char *cl = doc.attrs +
  8535. doc.nodes[n].class_off;
  8536. if ((contains_ci(cl, "poster-wrapper") ||
  8537. contains_ci(cl, "ts-picture")) &&
  8538. !has_skeleton_sibling(n))
  8539. l->y += block_h[n];
  8540. }
  8541. n = nd->next;
  8542. continue;
  8543. }
  8544. if (nd->tag == BR_TAG_BR) {
  8545. flush_line(l);
  8546. n = nd->next;
  8547. continue;
  8548. }
  8549. if (nd->tag == BR_TAG_HR) {
  8550. flush_line(l);
  8551. if (l->draw)
  8552. ngui_fill_rect(l->ui,
  8553. (struct ngui_rect){l->left, l->y + 2,
  8554. l->right - l->left, 1}, BR_GRAY);
  8555. l->y += 8;
  8556. n = nd->next;
  8557. continue;
  8558. }
  8559. if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  8560. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) {
  8561. if (!(nd->tag == BR_TAG_INPUT &&
  8562. s_eq(br_type(&doc, n), "hidden"))) {
  8563. form_fill_line = pst->display ==
  8564. BR_DISPLAY_FLEX &&
  8565. pst->flex_col;
  8566. add_form_run(l, n, &cs, lk);
  8567. form_fill_line = 0;
  8568. }
  8569. n = nd->next;
  8570. continue;
  8571. }
  8572. if (nd->tag == BR_TAG_IMG) {
  8573. add_image_run(l, n, &cs, lk);
  8574. n = nd->next;
  8575. continue;
  8576. }
  8577. if (nd->tag == BR_TAG_VIDEO) {
  8578. layout_block(l, n, &cs, depth + 1, lk);
  8579. n = nd->next;
  8580. continue;
  8581. }
  8582. if (cs.float_left) {
  8583. n = layout_float_group(l, n, pst, depth, lk);
  8584. continue;
  8585. }
  8586. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8587. n = layout_inline_blocks(l, n, pst, depth, link);
  8588. continue;
  8589. }
  8590. /* A flex container is block-level like any block box even when
  8591. * the element is an inline tag such as <a> (a link card with
  8592. * display:flex is common on news sites). Without the block box
  8593. * its children were laid out in the parent flow with a 0x0 box
  8594. * of their own. */
  8595. /* inline-flex around inline content only ("| mehr" link
  8596. * tails, icon+label pills) stays in the text line. */
  8597. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  8598. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  8599. !flex_wants_row(n, &cs)) {
  8600. layout_children(l, n, &cs, depth + 1, lk);
  8601. } else if (cs.display == BR_DISPLAY_BLOCK ||
  8602. cs.display == BR_DISPLAY_FLEX ||
  8603. br_tag_is_block(nd->tag))
  8604. layout_block(l, n, &cs, depth + 1, lk);
  8605. else {
  8606. layout_children(l, n, &cs, depth + 1, lk);
  8607. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  8608. l->space_pending = 1;
  8609. }
  8610. n = nd->next;
  8611. }
  8612. emit_pseudo(l, parent, pst, 2, link);
  8613. }
  8614. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  8615. * runs and a recursive page can otherwise overflow the stack. */
  8616. static struct lay layout_state;
  8617. static int measure_page(int left, int right)
  8618. {
  8619. struct lay *l = &layout_state;
  8620. struct br_style base = base_style();
  8621. unsigned int i;
  8622. for (i = 0; i < BR_MAX_NODES; i++) {
  8623. block_h[i] = 0;
  8624. img_top[i] = 0;
  8625. block_top[i] = 0;
  8626. img_h[i] = 0;
  8627. layout_boxes[i].valid = 0;
  8628. }
  8629. memset(li_marker, 0, sizeof(li_marker));
  8630. l->draw = 0;
  8631. l->ui = &ui;
  8632. l->left = left;
  8633. l->right = right;
  8634. l->y = 0;
  8635. l->line_x = left;
  8636. l->run_x = left;
  8637. l->line_left = left;
  8638. l->line_right = right;
  8639. l->line_y = 0;
  8640. l->line_h = 0;
  8641. l->align = BR_ALIGN_LEFT;
  8642. l->float_active = 0;
  8643. l->parent_top = 0;
  8644. l->cb_left = left;
  8645. l->cb_right = right;
  8646. l->cb_top = 0;
  8647. l->depth = 0;
  8648. l->nruns = 0;
  8649. l->space_pending = 0;
  8650. layout_children(l, doc.root, &base, 0, 0);
  8651. return l->y + 8;
  8652. }
  8653. static int deferred_cmp(const struct br_deferred *a,
  8654. const struct br_deferred *b)
  8655. {
  8656. int az = a->z_set ? a->z_index : 0;
  8657. int bz = b->z_set ? b->z_index : 0;
  8658. if (az != bz)
  8659. return az < bz ? -1 : 1;
  8660. if (a->order != b->order)
  8661. return a->order < b->order ? -1 : 1;
  8662. return 0;
  8663. }
  8664. static void sort_deferred(void)
  8665. {
  8666. int i;
  8667. for (i = 1; i < ndeferred; i++) {
  8668. struct br_deferred key = deferred[i];
  8669. int j = i;
  8670. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  8671. deferred[j] = deferred[j - 1];
  8672. j--;
  8673. }
  8674. deferred[j] = key;
  8675. }
  8676. }
  8677. static void render_page(int left, int right, int y0)
  8678. {
  8679. struct lay *l = &layout_state;
  8680. struct br_style base = base_style();
  8681. l->draw = 1;
  8682. l->ui = &ui;
  8683. l->left = left;
  8684. l->right = right;
  8685. l->y = y0;
  8686. l->line_x = left;
  8687. l->run_x = left;
  8688. l->line_left = left;
  8689. l->line_right = right;
  8690. l->line_y = y0;
  8691. l->line_h = 0;
  8692. l->align = BR_ALIGN_LEFT;
  8693. l->float_active = 0;
  8694. l->parent_top = 0;
  8695. l->cb_left = left;
  8696. l->cb_right = right;
  8697. l->cb_top = y0;
  8698. l->depth = 0;
  8699. l->nruns = 0;
  8700. l->space_pending = 0;
  8701. nhits = 0;
  8702. ndeferred = 0;
  8703. layout_children(l, doc.root, &base, 0, 0);
  8704. sort_deferred();
  8705. {
  8706. int i;
  8707. for (i = 0; i < ndeferred; i++) {
  8708. struct br_style st;
  8709. br_style_for(&doc, deferred[i].node, &base, &st);
  8710. if (st.display == BR_DISPLAY_NONE)
  8711. continue;
  8712. l->draw = 1;
  8713. l->left = deferred[i].flow_left;
  8714. l->right = deferred[i].flow_right;
  8715. l->y = deferred[i].flow_y;
  8716. l->line_x = l->left;
  8717. l->run_x = l->left;
  8718. l->line_y = l->y;
  8719. l->line_h = 0;
  8720. l->nruns = 0;
  8721. l->space_pending = 0;
  8722. l->align = st.align;
  8723. if (st.pos == 2 && block_h[deferred[i].node]) {
  8724. struct ngui_rect clip;
  8725. int ch = block_h[deferred[i].node] + 24;
  8726. clip.x = page_rect.x;
  8727. clip.y = page_rect.y;
  8728. clip.w = page_rect.w - 12;
  8729. if (ch > page_rect.h)
  8730. ch = page_rect.h;
  8731. clip.h = ch;
  8732. ngui_push_clip(&ui, clip);
  8733. if (st.has_bg)
  8734. ngui_fill_rect(&ui, clip, st.bg);
  8735. layout_block(l, deferred[i].node, &st, 0,
  8736. deferred[i].link);
  8737. ngui_pop_clip(&ui);
  8738. } else {
  8739. layout_block(l, deferred[i].node, &st, 0,
  8740. deferred[i].link);
  8741. }
  8742. }
  8743. }
  8744. }
  8745. /* ---- UI ---- */
  8746. static int find_hit(int x, int y)
  8747. {
  8748. int i;
  8749. for (i = nhits - 1; i >= 0; i--) {
  8750. struct hit *h = &hits[i];
  8751. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  8752. y < h->y + h->h)
  8753. return (int)h->node;
  8754. }
  8755. return 0;
  8756. }
  8757. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  8758. {
  8759. int x = r.x + 4, y = r.y + 4, h = 22;
  8760. int compact = r.w < 560;
  8761. int go_w = r.w < 420 ? 32 : 42;
  8762. int in_x, in_w, res;
  8763. ngui_fill_rect(&ui, r, ui.theme.panel);
  8764. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  8765. ui.theme.border);
  8766. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  8767. NGUI_ICON_CHEVRON_LEFT))
  8768. *action |= ACT_BACK;
  8769. x += 32;
  8770. if (!compact) {
  8771. if (ngui_icon_button(&ui, ID_FORWARD,
  8772. (struct ngui_rect){x, y, 28, h},
  8773. NGUI_ICON_CHEVRON_RIGHT))
  8774. *action |= ACT_FORWARD;
  8775. x += 32;
  8776. }
  8777. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  8778. NGUI_ICON_REFRESH))
  8779. *action |= ACT_RELOAD;
  8780. x += 32;
  8781. if (!compact) {
  8782. if (ngui_icon_button(&ui, ID_HOME,
  8783. (struct ngui_rect){x, y, 28, h},
  8784. NGUI_ICON_HOME))
  8785. *action |= ACT_HOME;
  8786. x += 32;
  8787. }
  8788. in_x = x + 2;
  8789. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  8790. if (in_w < 60)
  8791. in_w = 60;
  8792. res = ngui_text_input(&ui, ID_URL,
  8793. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  8794. if (res & NGUI_INPUT_SUBMIT)
  8795. *action |= ACT_NAV;
  8796. if (res & NGUI_INPUT_CANCEL)
  8797. ngui_set_focus(&ui, 0);
  8798. if (ngui_button(&ui, ID_GO,
  8799. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  8800. "Go"))
  8801. *action |= ACT_NAV;
  8802. }
  8803. static int page_hover_node(void)
  8804. {
  8805. if (!ui.inside)
  8806. return 0;
  8807. if (ui.mouse_x < page_rect.x ||
  8808. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  8809. ui.mouse_y < page_rect.y ||
  8810. ui.mouse_y >= page_rect.y + page_rect.h)
  8811. return 0;
  8812. return find_hit(ui.mouse_x, ui.mouse_y);
  8813. }
  8814. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  8815. {
  8816. int x, y, w = page.w, h = page.h;
  8817. if (!src || w <= 0 || h <= 0)
  8818. return;
  8819. for (y = 0; y < h; y++) {
  8820. unsigned short *s = src + (page.y + y) * sw + page.x;
  8821. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  8822. for (x = 0; x + 1 < w; x += 2) {
  8823. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  8824. }
  8825. if (x < w)
  8826. d[x] = s[x];
  8827. }
  8828. }
  8829. static void draw_page(struct ngui_rect page)
  8830. {
  8831. int left, right, ch;
  8832. int old_panel, old_dim;
  8833. unsigned short *saved_px;
  8834. unsigned short page_bg = ui.theme.bg;
  8835. int saved_w, saved_h, use_buf;
  8836. page_rect = page;
  8837. {
  8838. unsigned int root = doc.nnode > 1 ?
  8839. br_find_tag(&doc, BR_TAG_HTML) : 0;
  8840. unsigned int body = doc.nnode > 1 ?
  8841. br_find_tag(&doc, BR_TAG_BODY) : 0;
  8842. struct br_style bs;
  8843. if (root) {
  8844. style_for_node(root - 1, &bs);
  8845. if (bs.has_bg)
  8846. page_bg = bs.bg;
  8847. }
  8848. if (body) {
  8849. style_for_node(body - 1, &bs);
  8850. if (bs.has_bg)
  8851. page_bg = bs.bg;
  8852. }
  8853. }
  8854. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  8855. page_cache_valid && layout_valid &&
  8856. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  8857. !(ui.scroll_y &&
  8858. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  8859. page_scroll.offset == page_cache_scroll &&
  8860. page_cache_nnode == doc.nnode &&
  8861. page_cache_x == page.x && page_cache_y == page.y &&
  8862. page_cache_w == page.w && page_cache_h == page.h) {
  8863. blit_page(page, page_backbuf, pagebuf_w);
  8864. return;
  8865. }
  8866. ngui_fill_rect(&ui, page, page_bg);
  8867. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  8868. const char *s = page_loading ? "Loading..." : "No page";
  8869. int w = (int)ngui_text_width_ui(&ui, s);
  8870. ngui_text(&ui, page.x + (page.w - w) / 2,
  8871. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  8872. page_scroll.content_h = 0;
  8873. page_scroll.view_h = page.h;
  8874. page_cache_valid = 0;
  8875. return;
  8876. }
  8877. if (page.w < 40 || page.h < 40) {
  8878. page_cache_valid = 0;
  8879. return;
  8880. }
  8881. saved_px = ui.px;
  8882. saved_w = ui.w;
  8883. saved_h = ui.h;
  8884. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  8885. if (use_buf) {
  8886. ui.px = page_backbuf;
  8887. ui.w = pagebuf_w;
  8888. ui.h = pagebuf_h;
  8889. ngui_fill_rect(&ui, page, page_bg);
  8890. }
  8891. left = page.x + 8;
  8892. right = page.x + page.w - 16;
  8893. if (!layout_valid || left != layout_left || right != layout_right ||
  8894. layout_nnode != doc.nnode) {
  8895. layout_content_h = measure_page(left, right);
  8896. layout_valid = 1;
  8897. layout_left = left;
  8898. layout_right = right;
  8899. layout_nnode = doc.nnode;
  8900. }
  8901. ch = layout_content_h;
  8902. page_scroll.content_h = ch;
  8903. page_scroll.view_h = page.h;
  8904. ngui_scroll_begin(&ui, page, &page_scroll);
  8905. ngui_scroll_wheel(&ui, page, &page_scroll);
  8906. render_page(left, right, page.y + 4 - page_scroll.offset);
  8907. old_panel = ui.theme.panel_alt;
  8908. old_dim = ui.theme.text_dim;
  8909. ui.theme.panel_alt = 0xC618;
  8910. ui.theme.text_dim = 0x8410;
  8911. ngui_scroll_end(&ui, page, &page_scroll);
  8912. ui.theme.panel_alt = old_panel;
  8913. ui.theme.text_dim = old_dim;
  8914. if (use_buf) {
  8915. ui.px = saved_px;
  8916. ui.w = saved_w;
  8917. ui.h = saved_h;
  8918. blit_page(page, page_backbuf, pagebuf_w);
  8919. page_cache_valid = 1;
  8920. page_cache_scroll = page_scroll.offset;
  8921. page_cache_nnode = doc.nnode;
  8922. page_cache_x = page.x;
  8923. page_cache_y = page.y;
  8924. page_cache_w = page.w;
  8925. page_cache_h = page.h;
  8926. } else {
  8927. page_cache_valid = 0;
  8928. }
  8929. }
  8930. static void draw_status(struct ngui_rect r)
  8931. {
  8932. char msg[BR_URL_MAX + 32];
  8933. unsigned int n = 0;
  8934. int hover = page_hover_node();
  8935. unsigned short color;
  8936. const char *kind;
  8937. ngui_fill_rect(&ui, r, ui.theme.panel);
  8938. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  8939. ui.theme.border);
  8940. if (hover) {
  8941. const char *href = br_href(&doc, (unsigned int)hover);
  8942. char url[BR_URL_MAX];
  8943. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  8944. s_append(msg, &n, "Link: ", sizeof(msg));
  8945. s_append(msg, &n, url, sizeof(msg));
  8946. } else {
  8947. s_copy(msg, "Link", sizeof(msg));
  8948. }
  8949. color = ui.theme.accent;
  8950. } else if (status_text[0]) {
  8951. s_copy(msg, status_text, sizeof(msg));
  8952. color = status_error ? ui.theme.error : ui.theme.text;
  8953. } else if (page_title[0]) {
  8954. s_copy(msg, page_title, sizeof(msg));
  8955. color = ui.theme.text;
  8956. } else {
  8957. s_copy(msg, "Ready", sizeof(msg));
  8958. color = ui.theme.text_dim;
  8959. }
  8960. kind = s_eq(page_url, "about:home") ? "HOME" :
  8961. page_is_local ? "FILE" :
  8962. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  8963. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  8964. {
  8965. int kw = (int)ngui_text_width_ui(&ui, kind);
  8966. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  8967. ui.theme.text_dim);
  8968. }
  8969. }
  8970. static void draw(unsigned int *action)
  8971. {
  8972. struct ngui_rect r = {0, 0, ui.w, ui.h};
  8973. struct ngui_rect toolbar, status, page;
  8974. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  8975. status = ngui_cut_bottom(&r, BR_STATUS_H);
  8976. page = r;
  8977. draw_toolbar(toolbar, action);
  8978. draw_page(page);
  8979. draw_status(status);
  8980. }
  8981. static void redraw_now(void)
  8982. {
  8983. unsigned int action = 0;
  8984. ngui_begin(&ui);
  8985. draw(&action);
  8986. ngui_end(&ui);
  8987. }
  8988. static void handle_keys(unsigned int *action)
  8989. {
  8990. int k, scrolled = 0;
  8991. if (form_focus >= doc.nnode)
  8992. form_focus = 0;
  8993. if (form_focus && !ngui_focus(&ui)) {
  8994. while ((k = ngui_key(&ui)) != 0)
  8995. form_key(k);
  8996. return;
  8997. }
  8998. /* Batch queued page keys: a slow full-page render must not make a
  8999. * held Page Down advance only once every few frames. */
  9000. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  9001. scrolled++;
  9002. if (scrolled)
  9003. ngui_invalidate(&ui);
  9004. if (ngui_focus(&ui))
  9005. return;
  9006. while ((k = ngui_key(&ui)) != 0) {
  9007. switch (k) {
  9008. case NGUI_KEY_ESC:
  9009. *action |= ACT_CLOSE;
  9010. break;
  9011. case NGUI_KEY_TAB:
  9012. case 0x0C: /* Ctrl+L */
  9013. ngui_set_focus(&ui, ID_URL);
  9014. break;
  9015. case 0x12: /* Ctrl+R */
  9016. *action |= ACT_RELOAD;
  9017. break;
  9018. case NGUI_KEY_BACKSPACE:
  9019. *action |= ACT_BACK;
  9020. break;
  9021. case NGUI_KEY_UP:
  9022. ngui_scroll_to(&page_scroll,
  9023. page_scroll.offset - 24);
  9024. ngui_invalidate(&ui);
  9025. break;
  9026. case NGUI_KEY_DOWN:
  9027. ngui_scroll_to(&page_scroll,
  9028. page_scroll.offset + 24);
  9029. ngui_invalidate(&ui);
  9030. break;
  9031. case NGUI_KEY_HOME:
  9032. ngui_scroll_to(&page_scroll, 0);
  9033. ngui_invalidate(&ui);
  9034. break;
  9035. case NGUI_KEY_END:
  9036. ngui_scroll_to(&page_scroll,
  9037. page_scroll.content_h -
  9038. page_scroll.view_h);
  9039. ngui_invalidate(&ui);
  9040. break;
  9041. default:
  9042. break;
  9043. }
  9044. }
  9045. }
  9046. static unsigned int form_ancestor(unsigned int node)
  9047. {
  9048. unsigned int p = node;
  9049. while (p && p < doc.nnode) {
  9050. if (doc.nodes[p].tag == BR_TAG_FORM &&
  9051. doc.nodes[p].type == BR_NODE_ELEM)
  9052. return p;
  9053. p = doc.nodes[p].parent;
  9054. }
  9055. return 0;
  9056. }
  9057. static int form_descendant(unsigned int node, unsigned int form)
  9058. {
  9059. unsigned int p = node;
  9060. while (p && p < doc.nnode) {
  9061. if (p == form)
  9062. return 1;
  9063. p = doc.nodes[p].parent;
  9064. }
  9065. return 0;
  9066. }
  9067. static void form_reset_form(unsigned int form)
  9068. {
  9069. unsigned int i;
  9070. for (i = 0; i < FORM_MAX; i++)
  9071. if (form_states[i].used &&
  9072. form_descendant(form_states[i].node, form))
  9073. form_states[i].used = 0;
  9074. form_focus = 0;
  9075. }
  9076. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  9077. const char *s)
  9078. {
  9079. static const char hex[] = "0123456789ABCDEF";
  9080. while (s && *s && *n + 1 < cap) {
  9081. unsigned char c = (unsigned char)*s++;
  9082. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  9083. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  9084. c == '.' || c == '~') {
  9085. dst[(*n)++] = (char)c;
  9086. } else if (c == ' ') {
  9087. dst[(*n)++] = '+';
  9088. } else if (*n + 3 < cap) {
  9089. dst[(*n)++] = '%';
  9090. dst[(*n)++] = hex[c >> 4];
  9091. dst[(*n)++] = hex[c & 15];
  9092. }
  9093. }
  9094. dst[*n] = '\0';
  9095. }
  9096. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  9097. const char *name, const char *value, int *first)
  9098. {
  9099. if (!name || !name[0])
  9100. return;
  9101. if (!*first && *n + 1 < cap)
  9102. dst[(*n)++] = '&';
  9103. *first = 0;
  9104. form_url_append(dst, n, cap, name);
  9105. if (*n + 1 < cap)
  9106. dst[(*n)++] = '=';
  9107. form_url_append(dst, n, cap, value ? value : "");
  9108. dst[*n] = '\0';
  9109. }
  9110. static int form_submit_form(unsigned int node, int fire_event)
  9111. {
  9112. unsigned int form = form_ancestor(node);
  9113. char action[BR_URL_MAX], query[2048];
  9114. unsigned int qn = 0, i;
  9115. int first = 1, is_post = 0;
  9116. const char *a, *method;
  9117. if (!form)
  9118. return 0;
  9119. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  9120. return 0;
  9121. method = br_find_attr(&doc, form, "method");
  9122. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  9123. is_post = 1;
  9124. a = br_find_attr(&doc, form, "action");
  9125. if (a && a[0]) {
  9126. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  9127. return 0;
  9128. } else {
  9129. s_copy(action, page_url, sizeof(action));
  9130. }
  9131. query[0] = '\0';
  9132. for (i = 0; i < doc.nnode; i++) {
  9133. struct br_node *nd = &doc.nodes[i];
  9134. struct form_state *fs;
  9135. const char *name;
  9136. const char *value = "";
  9137. if (nd->type != BR_NODE_ELEM || i == form ||
  9138. !form_descendant(i, form))
  9139. continue;
  9140. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  9141. nd->tag != BR_TAG_SELECT)
  9142. continue;
  9143. if (form_disabled(i))
  9144. continue;
  9145. name = br_find_attr(&doc, i, "name");
  9146. if (!name || !name[0])
  9147. continue;
  9148. fs = form_get(i, 1);
  9149. if (!fs)
  9150. continue;
  9151. if (nd->tag == BR_TAG_SELECT) {
  9152. char opt[64];
  9153. if (!form_option_text(i, fs->selected, opt,
  9154. sizeof(opt)))
  9155. s_copy(opt, "", sizeof(opt));
  9156. value = opt;
  9157. {
  9158. unsigned int c, oi = 0;
  9159. for (c = nd->first; c;
  9160. c = doc.nodes[c].next) {
  9161. if (doc.nodes[c].type != BR_NODE_ELEM ||
  9162. doc.nodes[c].tag != BR_TAG_OPTION)
  9163. continue;
  9164. if (oi == fs->selected) {
  9165. const char *v =
  9166. br_value(&doc, c);
  9167. if (v && v[0])
  9168. value = v;
  9169. break;
  9170. }
  9171. oi++;
  9172. }
  9173. }
  9174. } else if (nd->tag == BR_TAG_INPUT) {
  9175. int kind = form_kind_of(i);
  9176. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  9177. if (!fs->checked)
  9178. continue;
  9179. value = br_value(&doc, i);
  9180. if (!value || !value[0])
  9181. value = "on";
  9182. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  9183. kind == FORM_BUTTON) {
  9184. if (i != node)
  9185. continue;
  9186. value = fs->value;
  9187. } else {
  9188. value = fs->value;
  9189. }
  9190. } else {
  9191. value = fs->value;
  9192. }
  9193. form_add_param(query, &qn, sizeof(query), name, value, &first);
  9194. }
  9195. if (is_post) {
  9196. if (action[0] == '/') {
  9197. set_status("POST forms need an HTTP action URL", 1, 4000);
  9198. ngui_invalidate(&ui);
  9199. return 0;
  9200. }
  9201. if (qn >= sizeof(pending_post))
  9202. qn = sizeof(pending_post) - 1;
  9203. if (qn)
  9204. memcpy(pending_post, query, qn);
  9205. pending_post[qn] = '\0';
  9206. pending_post_len = qn;
  9207. pending_post_is = 1;
  9208. } else {
  9209. pending_post_len = 0;
  9210. pending_post_is = 0;
  9211. if (qn) {
  9212. unsigned int an = s_len(action);
  9213. if (an + qn + 2 < sizeof(action)) {
  9214. action[an++] = strchr(action, '?') ? '&' : '?';
  9215. action[an] = '\0';
  9216. s_copy(action + an, query,
  9217. sizeof(action) - an);
  9218. }
  9219. }
  9220. }
  9221. s_copy(pending_url, action, sizeof(pending_url));
  9222. pending_action |= ACT_NAV;
  9223. cancel_fetch = 1;
  9224. ngui_invalidate(&ui);
  9225. return 1;
  9226. }
  9227. static void form_reset_event(unsigned int form)
  9228. {
  9229. if (form && !js_browser_event(form, "reset", 1, 1))
  9230. return;
  9231. if (form)
  9232. form_reset_form(form);
  9233. else
  9234. form_reset_state();
  9235. form_dirty = 0;
  9236. layout_valid = 0;
  9237. ngui_invalidate(&ui);
  9238. }
  9239. static void form_blur(void)
  9240. {
  9241. unsigned int node = form_focus;
  9242. form_focus = 0;
  9243. if (node && form_dirty) {
  9244. form_dirty = 0;
  9245. js_browser_event(node, "change", 1, 0);
  9246. }
  9247. }
  9248. static void form_click(unsigned int node)
  9249. {
  9250. struct form_state *fs;
  9251. int kind, changed = 0;
  9252. if (!form_is_control(node) || form_disabled(node))
  9253. return;
  9254. if (form_focus != node)
  9255. form_blur();
  9256. if (!js_browser_event(node, "click", 1, 1))
  9257. return;
  9258. fs = form_get(node, 1);
  9259. if (!fs)
  9260. return;
  9261. kind = form_kind_of(node);
  9262. form_focus = node;
  9263. form_dirty = 0;
  9264. if (kind == FORM_CHECKBOX) {
  9265. fs->checked = !fs->checked;
  9266. changed = 1;
  9267. } else if (kind == FORM_RADIO) {
  9268. const char *name = br_find_attr(&doc, node, "name");
  9269. unsigned int i;
  9270. fs->checked = 1;
  9271. changed = 1;
  9272. if (name) {
  9273. for (i = 0; i < FORM_MAX; i++) {
  9274. struct form_state *o = &form_states[i];
  9275. if (!o->used || o->node == node)
  9276. continue;
  9277. if (form_kind_of(o->node) == FORM_RADIO) {
  9278. const char *on = br_find_attr(&doc,
  9279. o->node,
  9280. "name");
  9281. if (on && s_eq(on, name))
  9282. o->checked = 0;
  9283. }
  9284. }
  9285. }
  9286. } else if (kind == FORM_SELECT) {
  9287. unsigned int n = form_option_count(node);
  9288. if (n) {
  9289. fs->selected = (unsigned char)
  9290. ((fs->selected + 1) % n);
  9291. changed = 1;
  9292. }
  9293. } else if (kind == FORM_SUBMIT) {
  9294. form_submit_form(node, 1);
  9295. return;
  9296. } else if (kind == FORM_RESET) {
  9297. form_reset_event(form_ancestor(node));
  9298. return;
  9299. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  9300. kind == FORM_TEXTAREA) {
  9301. fs->caret = fs->len;
  9302. }
  9303. if (changed) {
  9304. js_browser_event(node, "input", 1, 0);
  9305. js_browser_event(node, "change", 1, 0);
  9306. }
  9307. layout_valid = 0;
  9308. ngui_invalidate(&ui);
  9309. }
  9310. static void form_focus_next(void)
  9311. {
  9312. unsigned int start = form_focus ? form_focus + 1 : 0;
  9313. unsigned int i;
  9314. form_blur();
  9315. for (i = start; i < doc.nnode; i++) {
  9316. if (form_is_control(i) && !form_disabled(i) &&
  9317. !s_eq(br_type(&doc, i), "hidden")) {
  9318. form_focus = i;
  9319. layout_valid = 0;
  9320. ngui_invalidate(&ui);
  9321. return;
  9322. }
  9323. }
  9324. form_focus = 0;
  9325. layout_valid = 0;
  9326. ngui_invalidate(&ui);
  9327. }
  9328. static void form_key(int k)
  9329. {
  9330. struct form_state *fs;
  9331. int kind;
  9332. if (!form_focus || form_focus >= doc.nnode) {
  9333. form_focus = 0;
  9334. return;
  9335. }
  9336. fs = form_get(form_focus, 1);
  9337. if (!fs || form_disabled(form_focus))
  9338. return;
  9339. kind = form_kind_of(form_focus);
  9340. if (kind == FORM_SELECT) {
  9341. unsigned int n = form_option_count(form_focus);
  9342. int changed = 0;
  9343. if (k == NGUI_KEY_UP && n) {
  9344. fs->selected = (unsigned char)
  9345. ((fs->selected + n - 1) % n);
  9346. changed = 1;
  9347. } else if (k == NGUI_KEY_DOWN && n) {
  9348. fs->selected = (unsigned char)
  9349. ((fs->selected + 1) % n);
  9350. changed = 1;
  9351. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  9352. form_blur();
  9353. layout_valid = 0;
  9354. ngui_invalidate(&ui);
  9355. return;
  9356. } else {
  9357. return;
  9358. }
  9359. if (changed) {
  9360. js_browser_event(form_focus, "input", 1, 0);
  9361. js_browser_event(form_focus, "change", 1, 0);
  9362. }
  9363. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  9364. if (k == ' ') {
  9365. form_click(form_focus);
  9366. return;
  9367. }
  9368. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  9369. form_blur();
  9370. layout_valid = 0;
  9371. ngui_invalidate(&ui);
  9372. }
  9373. return;
  9374. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  9375. kind == FORM_RESET) {
  9376. if (k == NGUI_KEY_ESC) {
  9377. form_blur();
  9378. layout_valid = 0;
  9379. ngui_invalidate(&ui);
  9380. } else if (k == '\r' || k == '\n' || k == ' ') {
  9381. form_click(form_focus);
  9382. }
  9383. return;
  9384. } else if (k == NGUI_KEY_TAB) {
  9385. form_focus_next();
  9386. return;
  9387. } else if (k == NGUI_KEY_ESC) {
  9388. form_blur();
  9389. layout_valid = 0;
  9390. ngui_invalidate(&ui);
  9391. return;
  9392. } else if (k == '\r' || k == '\n') {
  9393. unsigned int node = form_focus;
  9394. form_blur();
  9395. if (form_ancestor(node))
  9396. form_submit_form(node, 1);
  9397. layout_valid = 0;
  9398. ngui_invalidate(&ui);
  9399. return;
  9400. } else if (k == NGUI_KEY_BACKSPACE) {
  9401. if (fs->caret) {
  9402. unsigned int i = --fs->caret;
  9403. for (; i < fs->len; i++)
  9404. fs->value[i] = fs->value[i + 1];
  9405. if (fs->len)
  9406. fs->len--;
  9407. form_dirty = 1;
  9408. js_browser_event(form_focus, "input", 1, 0);
  9409. }
  9410. } else if (k == NGUI_KEY_DELETE) {
  9411. if (fs->caret < fs->len) {
  9412. unsigned int i;
  9413. for (i = fs->caret; i < fs->len; i++)
  9414. fs->value[i] = fs->value[i + 1];
  9415. fs->len--;
  9416. form_dirty = 1;
  9417. js_browser_event(form_focus, "input", 1, 0);
  9418. }
  9419. } else if (k == NGUI_KEY_LEFT) {
  9420. if (fs->caret)
  9421. fs->caret--;
  9422. } else if (k == NGUI_KEY_RIGHT) {
  9423. if (fs->caret < fs->len)
  9424. fs->caret++;
  9425. } else if (k == NGUI_KEY_HOME) {
  9426. fs->caret = 0;
  9427. } else if (k == NGUI_KEY_END) {
  9428. fs->caret = fs->len;
  9429. } else if (k >= 32 && k < 127) {
  9430. if (fs->len < FORM_VALUE_MAX) {
  9431. unsigned int i;
  9432. for (i = fs->len; i > fs->caret; i--)
  9433. fs->value[i] = fs->value[i - 1];
  9434. fs->value[fs->caret++] = (char)k;
  9435. fs->len++;
  9436. form_dirty = 1;
  9437. js_browser_event(form_focus, "input", 1, 0);
  9438. }
  9439. } else {
  9440. return;
  9441. }
  9442. fs->value[fs->len] = '\0';
  9443. layout_valid = 0;
  9444. ngui_invalidate(&ui);
  9445. }
  9446. /* The innermost laid-out box under a screen point: the smallest valid box
  9447. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  9448. * Used to deliver clicks to elements that are neither links nor controls
  9449. * (a Vue <div role="button">, a card with a click listener). */
  9450. static unsigned int find_box_hit(int x, int y)
  9451. {
  9452. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  9453. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  9454. const struct br_layout_box *b = &layout_boxes[i];
  9455. unsigned int area;
  9456. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  9457. x < b->x || y < b->y || x >= b->x + b->w ||
  9458. y >= b->y + b->h)
  9459. continue;
  9460. area = (unsigned int)b->w * (unsigned int)b->h;
  9461. if (area <= best_area) {
  9462. best = i;
  9463. best_area = area;
  9464. }
  9465. }
  9466. return best;
  9467. }
  9468. static void handle_page_click(unsigned int *action)
  9469. {
  9470. int node;
  9471. char url[BR_URL_MAX];
  9472. if (!ui.pressed)
  9473. return;
  9474. if (ui.press_x < page_rect.x ||
  9475. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  9476. ui.press_y < page_rect.y ||
  9477. ui.press_y >= page_rect.y + page_rect.h)
  9478. return;
  9479. node = find_hit(ui.press_x, ui.press_y);
  9480. if (!node) {
  9481. unsigned int box;
  9482. if (!js_browser_active())
  9483. return;
  9484. box = find_box_hit(ui.press_x, ui.press_y);
  9485. if (box) {
  9486. form_blur();
  9487. js_browser_event(box, "click", 1, 1);
  9488. }
  9489. return;
  9490. }
  9491. if (form_is_control((unsigned int)node)) {
  9492. form_click((unsigned int)node);
  9493. return;
  9494. }
  9495. form_blur();
  9496. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  9497. return;
  9498. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  9499. sizeof(url)) != 0)
  9500. return;
  9501. s_copy(click_url, url, sizeof(click_url));
  9502. *action |= ACT_NAV;
  9503. }
  9504. void _start(const char *arg)
  9505. {
  9506. struct win_info wi;
  9507. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  9508. u_win_create(960, 640, "Browser", &wi) != 0 &&
  9509. u_win_create(780, 540, "Browser", &wi) != 0) {
  9510. u_puts("browser: no graphics window\n");
  9511. u_exit(1);
  9512. }
  9513. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  9514. url_in.placeholder = "http://...";
  9515. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  9516. ui.theme.accent);
  9517. br_set_viewport(wi.width);
  9518. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  9519. s_copy(cwd, "/", sizeof(cwd));
  9520. heap_clear();
  9521. origin_cache_load();
  9522. css_cache_init();
  9523. script_cache_init();
  9524. persist_restore();
  9525. page_scroll.offset = 0;
  9526. page_scroll.content_h = 0;
  9527. if (arg && arg[0]) {
  9528. navigate(arg, 1);
  9529. } else {
  9530. load_home(1);
  9531. /* Start ready to type: keep the home page, but leave the address
  9532. * bar empty instead of showing "about:home". */
  9533. ngui_input_set(&url_in, "");
  9534. ngui_set_focus(&ui, ID_URL);
  9535. }
  9536. for (;;) {
  9537. unsigned int action = 0;
  9538. unsigned int now;
  9539. click_url[0] = '\0';
  9540. if (pending_action) {
  9541. action |= pending_action & ACT_WAIT_NAV;
  9542. if (pending_url[0])
  9543. s_copy(click_url, pending_url, sizeof(click_url));
  9544. pending_action = 0;
  9545. pending_url[0] = '\0';
  9546. cancel_fetch = 0;
  9547. } else if (preload_active) {
  9548. if (preload_wait)
  9549. preload_wait = 0;
  9550. else
  9551. preload_step();
  9552. } else if ((preload_pending &&
  9553. page_scroll.offset != preload_scroll) ||
  9554. (preload_rescan && layout_valid)) {
  9555. preload_scroll = page_scroll.offset;
  9556. preload_rescan = 0;
  9557. preload_pending = 0;
  9558. preload_node = 0;
  9559. preload_active = 1;
  9560. }
  9561. js_browser_tick();
  9562. persist_tick();
  9563. if (pending_action)
  9564. continue;
  9565. now = u_ticks_ms();
  9566. if (status_until && (int)(now - status_until) >= 0) {
  9567. status_text[0] = '\0';
  9568. status_until = 0;
  9569. status_error = 0;
  9570. ngui_invalidate(&ui);
  9571. }
  9572. if (!ngui_begin(&ui)) {
  9573. /* A queued navigation (e.g. Enter in the URL bar during
  9574. * a slow fetch) must be handled even when this frame
  9575. * needs no redraw. */
  9576. if (!action) {
  9577. fetch_workers_stop_if_unfocused();
  9578. u_sleep_ms(10);
  9579. continue;
  9580. }
  9581. } else {
  9582. draw(&action);
  9583. handle_keys(&action);
  9584. handle_page_click(&action);
  9585. ngui_end(&ui);
  9586. }
  9587. if (action & ACT_NAV) {
  9588. if (click_url[0]) {
  9589. navigate(click_url, 1);
  9590. click_url[0] = '\0';
  9591. } else {
  9592. navigate(url_in.text, 1);
  9593. }
  9594. }
  9595. if (action & ACT_BACK) {
  9596. if (hist_pos > 0) {
  9597. hist_pos--;
  9598. navigate(history[hist_pos], 0);
  9599. }
  9600. }
  9601. if (action & ACT_FORWARD) {
  9602. if (hist_pos + 1 < hist_len) {
  9603. hist_pos++;
  9604. navigate(history[hist_pos], 0);
  9605. }
  9606. }
  9607. if (action & ACT_RELOAD) {
  9608. if (s_eq(page_url, "about:home"))
  9609. load_home(0);
  9610. else
  9611. navigate(page_url, 0);
  9612. }
  9613. if (action & ACT_HOME)
  9614. load_home(1);
  9615. if (action & ACT_CLOSE)
  9616. quit = 1;
  9617. if (quit)
  9618. break;
  9619. if (pending_action)
  9620. continue;
  9621. fetch_workers_stop_if_unfocused();
  9622. u_sleep_ms(10);
  9623. }
  9624. fetch_workers_stop_all();
  9625. u_win_close();
  9626. u_exit(0);
  9627. }