browser.c 245 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687
  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 "img.h"
  22. #include "inflate.h"
  23. #include "ufont.h"
  24. #include "svg_raster.h"
  25. static void svg_cache_clear(void);
  26. static unsigned char *decode_arena; /* see decode_arena_get() */
  27. static unsigned int decode_arena_size;
  28. /* Start wide enough for the desktop nav; smaller screens fall back to
  29. * 960x640 and 780x540, which still fit a 1024x768 panel. */
  30. #define BR_W 1100
  31. #define BR_H 700
  32. #define BR_TOOLBAR_H 30
  33. #define BR_STATUS_H 18
  34. #define BR_PAGE_MAX (2u * 1024u * 1024u)
  35. #define BR_IMG_FILE_MAX (512u * 1024u)
  36. #define BR_IMG_PIX_MAX (8u * 1024u * 1024u)
  37. #define BR_MAX_IMAGES 256
  38. /* Decoded display bitmaps share the page heap: cap their total pixels
  39. * (RGB565 plus an optional alpha plane) instead of their count. */
  40. #define BR_IMG_PIXEL_BUDGET (4u * 1024u * 1024u)
  41. #define BR_IMG_ARENA_MAX (24u * 1024u * 1024u)
  42. #define BR_IMG_LAYOUT_W 1000
  43. /* An image job may hold a fetch helper this long. The page/script
  44. * deadline (UHTTP_TOTAL_TIMEOUT_MS) is minutes; one unreachable image host
  45. * must not starve the other images of all four helpers that long. */
  46. #define BR_IMG_JOB_TIMEOUT_MS 30000u
  47. #define BR_CSS_MAX (832u * 1024u)
  48. #define BR_CSS_COMP_MAX (192u * 1024u)
  49. #define BR_SCRIPT_MAX (512u * 1024u)
  50. #define FETCH_ABORT (-2)
  51. /* Session cache for remote stylesheets (per launch; cleared at startup). */
  52. #define CSS_CACHE_MAX 16
  53. #define CSS_CACHE_FILE_MAX (256u * 1024u)
  54. #define CSS_CACHE_PREFIX "bcss-"
  55. #define SCRIPT_CACHE_MAX 16
  56. #define SCRIPT_CACHE_FILE_MAX (512u * 1024u)
  57. #define SCRIPT_CACHE_PREFIX "bjs-"
  58. #define BR_MAX_SHEETS 6
  59. #define BR_HISTORY 16
  60. #define BR_URL_MAX 512
  61. #define BR_STATUS_MAX 200
  62. #define BR_IMG_RGB565(r, g, b) \
  63. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  64. #define BR_GRAY 0x8410
  65. enum {
  66. ID_URL = 1,
  67. ID_GO,
  68. ID_BACK,
  69. ID_FORWARD,
  70. ID_RELOAD,
  71. ID_HOME
  72. };
  73. #define ACT_NAV (1u << 0)
  74. #define ACT_BACK (1u << 1)
  75. #define ACT_FORWARD (1u << 2)
  76. #define ACT_RELOAD (1u << 3)
  77. #define ACT_HOME (1u << 4)
  78. #define ACT_CLOSE (1u << 5)
  79. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  80. ACT_HOME | ACT_CLOSE)
  81. struct br_image {
  82. int state; /* 0 empty, 1 ready */
  83. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  84. int native_w, native_h;
  85. char err[32];
  86. };
  87. static struct ngui ui;
  88. static struct ngui_input url_in;
  89. static struct ngui_scroll page_scroll;
  90. static struct br_doc doc;
  91. static struct br_image images[BR_MAX_IMAGES];
  92. static int image_count;
  93. static unsigned int image_pixels;
  94. /* Painted border boxes, in page/screen coordinates (layout starts at
  95. * page_rect.y + 4 - scroll). getBoundingClientRect() subtracts page_rect. */
  96. struct br_layout_box {
  97. int x, y;
  98. int w, h;
  99. unsigned char valid;
  100. };
  101. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  102. /* Images are loaded one per main-loop iteration so the parsed page stays
  103. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  104. static int preload_active;
  105. static int preload_max_jobs;
  106. static int preload_pending;
  107. static int preload_wait;
  108. static unsigned int preload_node;
  109. static int preload_loaded;
  110. static int preload_scroll;
  111. static int preload_rescan;
  112. static char post_status_text[BR_STATUS_MAX];
  113. static int post_status_error;
  114. static unsigned int post_status_ttl;
  115. /* Content-relative position/height of each <img>, recorded by the measure
  116. * pass so image loading can be deferred until it is near the viewport. */
  117. static unsigned short img_top[BR_MAX_NODES];
  118. static unsigned short img_h[BR_MAX_NODES];
  119. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  120. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  121. * body. Decode arenas are allocated per image instead of living here. */
  122. static unsigned char *image_io_buf;
  123. static struct ufont_face *font_faces[BR_MAX_FACES];
  124. #define image_file_buf (image_io_buf)
  125. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  126. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  127. static struct inflate image_inflate_ws;
  128. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  129. #error "CSS scratch must fit in image_io_buf"
  130. #endif
  131. static char page_url[BR_URL_MAX];
  132. static char page_title[BR_TITLE_MAX];
  133. static char cwd[64];
  134. static int page_is_local;
  135. static int page_loading;
  136. static char status_text[BR_STATUS_MAX];
  137. static unsigned int status_until;
  138. static int status_error;
  139. static char history[BR_HISTORY][BR_URL_MAX];
  140. static int hist_len, hist_pos;
  141. static char click_url[BR_URL_MAX];
  142. static char pending_url[BR_URL_MAX];
  143. #define BR_POST_MAX 4096
  144. static char pending_post[BR_POST_MAX];
  145. static unsigned int pending_post_len;
  146. static unsigned int pending_action;
  147. static int cancel_fetch;
  148. static int quit;
  149. static struct ngui_rect page_rect;
  150. static unsigned short *page_backbuf;
  151. static int pagebuf_w, pagebuf_h;
  152. static int page_cache_valid;
  153. static int page_cache_scroll;
  154. static unsigned int page_cache_nnode;
  155. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  156. static int layout_valid, layout_left, layout_right;
  157. static unsigned int layout_nnode;
  158. static int layout_content_h;
  159. /* layout output */
  160. struct lay_run {
  161. unsigned int off;
  162. unsigned short len;
  163. unsigned short gap;
  164. unsigned short color;
  165. unsigned short href;
  166. char lit[28];
  167. short img;
  168. signed short dy; /* inline image vertical offset */
  169. unsigned short iw, ih;
  170. unsigned short w;
  171. unsigned char font_px, bold, italic, mono, underline, strike;
  172. unsigned char overline, font_face;
  173. unsigned char transform_scale;
  174. unsigned char origin_x_kind, origin_y_kind;
  175. signed short scale_x, scale_y, rotate_x100;
  176. signed short origin_x, origin_y;
  177. unsigned char has_lit;
  178. unsigned int form; /* node + 1, 0 = not a control */
  179. unsigned char form_kind;
  180. unsigned char form_disabled;
  181. };
  182. struct lay {
  183. int draw;
  184. struct ngui *ui;
  185. int left, right;
  186. int y;
  187. int line_x, line_y, line_h;
  188. int line_left, line_right;
  189. int parent_top;
  190. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  191. int run_x;
  192. int align;
  193. int depth;
  194. int space_pending;
  195. unsigned char float_active;
  196. int float_left, float_right, float_bottom;
  197. struct lay_run runs[96];
  198. int nruns;
  199. };
  200. struct hit {
  201. int x, y, w, h;
  202. unsigned short node;
  203. };
  204. /* Live form state; the DOM attributes stay the initial/default value. */
  205. #define FORM_MAX 64
  206. #define FORM_VALUE_MAX 63
  207. enum {
  208. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  209. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  210. };
  211. struct form_state {
  212. unsigned int node;
  213. char value[FORM_VALUE_MAX + 1];
  214. unsigned char len, caret, checked, selected, used;
  215. };
  216. static struct form_state form_states[FORM_MAX];
  217. static unsigned int form_focus;
  218. static unsigned int form_dirty;
  219. static int form_descendant(unsigned int node, unsigned int form);
  220. static int form_submit_form(unsigned int node, int fire_event);
  221. static void form_reset_event(unsigned int form);
  222. static unsigned int s_len(const char *s);
  223. static int s_eq(const char *a, const char *b);
  224. static void form_key(int k);
  225. static void form_click(unsigned int node);
  226. static void style_for_node(unsigned int node, struct br_style *out);
  227. static int form_disabled(unsigned int node)
  228. {
  229. struct br_node *n = &doc.nodes[node];
  230. if (n->attr_flags & BR_ATTR_DISABLED)
  231. return 1;
  232. return br_find_attr(&doc, node, "disabled") != 0;
  233. }
  234. static int form_kind_of(unsigned int node)
  235. {
  236. const char *type = br_type(&doc, node);
  237. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  238. return FORM_TEXTAREA;
  239. if (doc.nodes[node].tag == BR_TAG_SELECT)
  240. return FORM_SELECT;
  241. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  242. if (s_eq(type, "reset"))
  243. return FORM_RESET;
  244. if (s_eq(type, "button"))
  245. return FORM_BUTTON;
  246. return FORM_SUBMIT;
  247. }
  248. if (s_eq(type, "password"))
  249. return FORM_PASSWORD;
  250. if (s_eq(type, "checkbox"))
  251. return FORM_CHECKBOX;
  252. if (s_eq(type, "radio"))
  253. return FORM_RADIO;
  254. if (s_eq(type, "submit"))
  255. return FORM_SUBMIT;
  256. if (s_eq(type, "reset"))
  257. return FORM_RESET;
  258. if (s_eq(type, "button"))
  259. return FORM_BUTTON;
  260. return FORM_TEXT;
  261. }
  262. static unsigned int form_option_count(unsigned int node)
  263. {
  264. unsigned int c, n = 0;
  265. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  266. if (doc.nodes[c].type == BR_NODE_ELEM &&
  267. doc.nodes[c].tag == BR_TAG_OPTION)
  268. n++;
  269. return n;
  270. }
  271. static unsigned int form_option_selected(unsigned int node)
  272. {
  273. unsigned int c, i = 0;
  274. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  275. if (doc.nodes[c].type != BR_NODE_ELEM ||
  276. doc.nodes[c].tag != BR_TAG_OPTION)
  277. continue;
  278. if (br_find_attr(&doc, c, "selected"))
  279. return i;
  280. i++;
  281. }
  282. return 0;
  283. }
  284. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  285. char *out, unsigned int cap)
  286. {
  287. unsigned int c, i = 0;
  288. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  289. if (doc.nodes[c].type != BR_NODE_ELEM ||
  290. doc.nodes[c].tag != BR_TAG_OPTION)
  291. continue;
  292. if (i == idx)
  293. return br_text_content(&doc, c, out, cap);
  294. i++;
  295. }
  296. return 0;
  297. }
  298. static struct form_state *form_get(unsigned int node, int create)
  299. {
  300. struct form_state *slot = 0;
  301. unsigned int i;
  302. for (i = 0; i < FORM_MAX; i++) {
  303. if (form_states[i].used) {
  304. if (form_states[i].node == node)
  305. return &form_states[i];
  306. } else if (!slot) {
  307. slot = &form_states[i];
  308. }
  309. }
  310. if (!create || !slot)
  311. return 0;
  312. slot->node = node;
  313. slot->len = 0;
  314. slot->caret = 0;
  315. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  316. slot->selected = form_option_selected(node);
  317. slot->used = 1;
  318. {
  319. unsigned int n = 0;
  320. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  321. n = br_text_content(&doc, node, slot->value,
  322. FORM_VALUE_MAX + 1);
  323. } else {
  324. const char *v = br_value(&doc, node);
  325. if (v) {
  326. n = s_len(v);
  327. if (n > FORM_VALUE_MAX)
  328. n = FORM_VALUE_MAX;
  329. for (unsigned int j = 0; j < n; j++)
  330. slot->value[j] = v[j];
  331. }
  332. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  333. n = br_text_content(&doc, node, slot->value,
  334. FORM_VALUE_MAX + 1);
  335. }
  336. if (n > FORM_VALUE_MAX)
  337. n = FORM_VALUE_MAX;
  338. slot->value[n] = '\0';
  339. slot->len = (unsigned char)n;
  340. slot->caret = (unsigned char)n;
  341. }
  342. return slot;
  343. }
  344. static void form_reset_state(void)
  345. {
  346. unsigned int i;
  347. for (i = 0; i < FORM_MAX; i++)
  348. form_states[i].used = 0;
  349. form_focus = 0;
  350. }
  351. static int form_is_control(unsigned int node)
  352. {
  353. unsigned int tag;
  354. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  355. return 0;
  356. tag = doc.nodes[node].tag;
  357. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  358. tag == BR_TAG_SELECT || tag == BR_TAG_BUTTON;
  359. }
  360. #define HIT_MAX 96
  361. static struct hit hits[HIT_MAX];
  362. static int nhits;
  363. static unsigned short block_h[BR_MAX_NODES];
  364. /* Measure-pass top of each block, in the same document coordinates as
  365. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  366. * paint, so it cannot drive the lazy background loader). */
  367. static unsigned short block_top[BR_MAX_NODES];
  368. static char li_marker[BR_MAX_NODES][12];
  369. /* one connection object; the browser fetches one resource at a time */
  370. /* ---- tiny strings ---- */
  371. static unsigned int s_len(const char *s)
  372. {
  373. unsigned int n = 0;
  374. while (s && s[n])
  375. n++;
  376. return n;
  377. }
  378. static void s_copy(char *d, const char *s, unsigned int cap)
  379. {
  380. unsigned int i = 0;
  381. if (!cap)
  382. return;
  383. while (s && s[i] && i + 1 < cap) {
  384. d[i] = s[i];
  385. i++;
  386. }
  387. d[i] = '\0';
  388. }
  389. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  390. {
  391. while (s && *s && *n + 1 < cap)
  392. d[(*n)++] = *s++;
  393. d[*n] = '\0';
  394. }
  395. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  396. unsigned int cap)
  397. {
  398. char tmp[12];
  399. unsigned int i = 0, j;
  400. do {
  401. tmp[i++] = (char)('0' + v % 10);
  402. v /= 10;
  403. } while (v && i < sizeof(tmp));
  404. for (j = 0; j < i && *n + 1 < cap; j++)
  405. d[(*n)++] = tmp[i - 1 - j];
  406. d[*n] = '\0';
  407. }
  408. static int s_eq(const char *a, const char *b)
  409. {
  410. while (*a && *b) {
  411. if (*a != *b)
  412. return 0;
  413. a++;
  414. b++;
  415. }
  416. return *a == *b;
  417. }
  418. static int starts_with(const char *s, const char *p)
  419. {
  420. unsigned int i = 0;
  421. while (p[i]) {
  422. if (s[i] != p[i])
  423. return 0;
  424. i++;
  425. }
  426. return 1;
  427. }
  428. static int contains_ci(const char *s, const char *p)
  429. {
  430. unsigned int i, j;
  431. for (i = 0; s[i]; i++) {
  432. for (j = 0; p[j]; j++) {
  433. char a = s[i + j];
  434. if (a >= 'A' && a <= 'Z')
  435. a = (char)(a - 'A' + 'a');
  436. if (a != p[j])
  437. break;
  438. }
  439. if (!p[j])
  440. return 1;
  441. }
  442. return 0;
  443. }
  444. static char *trim(char *s)
  445. {
  446. unsigned int n;
  447. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  448. s++;
  449. n = s_len(s);
  450. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  451. s[n - 1] == '\r' || s[n - 1] == '\n'))
  452. s[--n] = '\0';
  453. return s;
  454. }
  455. /* ---- per-process heap ---- */
  456. static int heap_start(void)
  457. {
  458. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  459. if (!image_io_buf)
  460. return -1;
  461. page_backbuf = (unsigned short *)malloc(
  462. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  463. pagebuf_w = page_backbuf ? ui.w : 0;
  464. pagebuf_h = page_backbuf ? ui.h : 0;
  465. page_cache_valid = 0;
  466. return 0;
  467. }
  468. static void heap_clear(void)
  469. {
  470. memset(font_faces, 0, sizeof(font_faces));
  471. ngui_font_detach(&ui);
  472. svg_cache_clear();
  473. decode_arena = 0; /* lives in the page heap too */
  474. decode_arena_size = 0;
  475. heap_reset();
  476. /* The document arenas live in that heap; drop the stale pointers so
  477. * the next br_parse_plain() allocates fresh ones. */
  478. doc.nodes = 0;
  479. doc.text = 0;
  480. doc.attrs = 0;
  481. image_io_buf = 0;
  482. page_backbuf = 0;
  483. pagebuf_w = pagebuf_h = 0;
  484. page_cache_valid = 0;
  485. }
  486. static void browser_rules_alloc(void)
  487. {
  488. struct br_rule *rules;
  489. rules = (struct br_rule *)malloc(
  490. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  491. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  492. }
  493. /* ---- status ---- */
  494. static void set_status(const char *s, int err, unsigned int ttl_ms)
  495. {
  496. s_copy(status_text, s, sizeof(status_text));
  497. status_error = err;
  498. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  499. ngui_invalidate(&ui);
  500. }
  501. /* ---- JavaScript ---- */
  502. static int resolve_link(const char *base, const char *href, char *out,
  503. unsigned int cap);
  504. static char js_last_status[BR_STATUS_MAX];
  505. static int js_last_error;
  506. static void js_host_status(const char *msg, int error)
  507. {
  508. s_copy(js_last_status, msg, sizeof(js_last_status));
  509. js_last_error = error;
  510. set_status(msg, error, 6000);
  511. }
  512. static void js_host_report(const char *msg)
  513. {
  514. u_puts("[js] ");
  515. u_puts(msg);
  516. u_putc('\n');
  517. s_copy(js_last_status, msg, sizeof(js_last_status));
  518. js_last_error = 1;
  519. set_status(msg, 1, 8000);
  520. }
  521. static void js_host_navigate(const char *url)
  522. {
  523. char resolved[BR_URL_MAX];
  524. if (!url || !url[0])
  525. return;
  526. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  527. return;
  528. s_copy(pending_url, resolved, sizeof(pending_url));
  529. pending_action |= ACT_NAV;
  530. cancel_fetch = 1;
  531. }
  532. static void js_host_changed(void)
  533. {
  534. /* Class/style/attribute mutations change computed styles, not just the
  535. * text: drop the per-node style cache before the next layout. */
  536. br_reset_styles(&doc);
  537. layout_valid = 0;
  538. /* Script-built content (Angular's ng-repeat cards) brings new images
  539. * and inline background styles: rescan once the main loop is idle. */
  540. preload_rescan = 1;
  541. ngui_invalidate(&ui);
  542. }
  543. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  544. {
  545. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  546. return 0;
  547. *x = layout_boxes[node].x - page_rect.x;
  548. *y = layout_boxes[node].y - page_rect.y;
  549. *w = layout_boxes[node].w;
  550. *h = layout_boxes[node].h;
  551. return 1;
  552. }
  553. static void form_copy_out(const char *s, char *buf, int cap)
  554. {
  555. int i = 0;
  556. if (!buf || cap <= 0)
  557. return;
  558. while (s && s[i] && i + 1 < cap) {
  559. buf[i] = s[i];
  560. i++;
  561. }
  562. buf[i] = '\0';
  563. }
  564. static int js_host_form_value(unsigned int node, char *buf, int cap)
  565. {
  566. struct form_state *fs;
  567. int kind;
  568. if (!form_is_control(node))
  569. return 0;
  570. kind = form_kind_of(node);
  571. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  572. return 0;
  573. if (kind == FORM_SELECT) {
  574. char opt[64] = "";
  575. unsigned int c, i = 0;
  576. fs = form_get(node, 1);
  577. if (!fs)
  578. return 0;
  579. form_option_text(node, fs->selected, opt, sizeof(opt));
  580. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  581. if (doc.nodes[c].type != BR_NODE_ELEM ||
  582. doc.nodes[c].tag != BR_TAG_OPTION)
  583. continue;
  584. if (i == fs->selected) {
  585. const char *v = br_value(&doc, c);
  586. if (v && v[0])
  587. form_copy_out(v, buf, cap);
  588. else
  589. form_copy_out(opt, buf, cap);
  590. return 1;
  591. }
  592. i++;
  593. }
  594. form_copy_out(opt, buf, cap);
  595. return 1;
  596. }
  597. fs = form_get(node, 1);
  598. if (!fs)
  599. return 0;
  600. form_copy_out(fs->value, buf, cap);
  601. return 1;
  602. }
  603. static int js_host_form_checked(unsigned int node)
  604. {
  605. struct form_state *fs;
  606. int kind;
  607. if (!form_is_control(node))
  608. return -1;
  609. kind = form_kind_of(node);
  610. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  611. return -1;
  612. fs = form_get(node, 1);
  613. return fs ? fs->checked : 0;
  614. }
  615. static int js_host_form_selected(unsigned int node)
  616. {
  617. struct form_state *fs;
  618. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  619. return -1;
  620. fs = form_get(node, 1);
  621. return fs ? fs->selected : 0;
  622. }
  623. static int js_host_form_set_value(unsigned int node, const char *value)
  624. {
  625. struct form_state *fs;
  626. unsigned int n;
  627. if (!form_is_control(node))
  628. return 0;
  629. fs = form_get(node, 1);
  630. if (!fs)
  631. return 0;
  632. n = s_len(value ? value : "");
  633. if (n > FORM_VALUE_MAX)
  634. n = FORM_VALUE_MAX;
  635. for (unsigned int i = 0; i < n; i++)
  636. fs->value[i] = value[i];
  637. fs->value[n] = '\0';
  638. fs->len = (unsigned char)n;
  639. fs->caret = (unsigned char)n;
  640. layout_valid = 0;
  641. ngui_invalidate(&ui);
  642. return 1;
  643. }
  644. static int js_host_form_set_checked(unsigned int node, int checked)
  645. {
  646. struct form_state *fs;
  647. int kind;
  648. if (!form_is_control(node))
  649. return 0;
  650. kind = form_kind_of(node);
  651. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  652. return 0;
  653. fs = form_get(node, 1);
  654. if (!fs)
  655. return 0;
  656. fs->checked = (unsigned char)(checked != 0);
  657. layout_valid = 0;
  658. ngui_invalidate(&ui);
  659. return 1;
  660. }
  661. static int js_host_form_set_selected(unsigned int node, int index)
  662. {
  663. struct form_state *fs;
  664. unsigned int n;
  665. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  666. return 0;
  667. fs = form_get(node, 1);
  668. if (!fs)
  669. return 0;
  670. n = form_option_count(node);
  671. if (index < 0)
  672. index = 0;
  673. if (n && (unsigned int)index >= n)
  674. index = (int)n - 1;
  675. fs->selected = (unsigned char)index;
  676. layout_valid = 0;
  677. ngui_invalidate(&ui);
  678. return 1;
  679. }
  680. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  681. {
  682. unsigned int i;
  683. int n = 0;
  684. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  685. doc.nodes[form].tag != BR_TAG_FORM)
  686. return 0;
  687. for (i = 0; i < doc.nnode && n < cap; i++) {
  688. struct br_node *nd = &doc.nodes[i];
  689. if (i == form || nd->type != BR_NODE_ELEM)
  690. continue;
  691. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  692. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  693. continue;
  694. if (!form_descendant(i, form))
  695. continue;
  696. out[n++] = i;
  697. }
  698. return n;
  699. }
  700. static int js_host_form_submit(unsigned int form)
  701. {
  702. form_submit_form(form, 0);
  703. return 1;
  704. }
  705. static int js_host_form_reset(unsigned int form)
  706. {
  707. form_reset_event(form);
  708. return 1;
  709. }
  710. static void css_computed_name(const char *p, char *out, int cap)
  711. {
  712. int n = 0;
  713. for (; p && *p && n + 2 < cap; p++) {
  714. char c = *p;
  715. if (c >= 'A' && c <= 'Z') {
  716. out[n++] = '-';
  717. c = (char)(c - 'A' + 'a');
  718. } else if (c == '_') {
  719. c = '-';
  720. } else if (c >= 'a' && c <= 'z') {
  721. /* keep */
  722. }
  723. out[n++] = c;
  724. }
  725. out[n] = '\0';
  726. if (!strcmp(out, "css-float"))
  727. strcpy(out, "float");
  728. }
  729. static void css_rgb(unsigned short c, char *buf, int cap)
  730. {
  731. int r = ((c >> 11) & 31) * 255 / 31;
  732. int g = ((c >> 5) & 63) * 255 / 63;
  733. int b = (c & 31) * 255 / 31;
  734. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  735. }
  736. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  737. int font_px)
  738. {
  739. if (unit == 4) {
  740. snprintf(buf, cap, "auto");
  741. } else if (unit == 0) {
  742. snprintf(buf, cap, "%dpx", raw);
  743. } else if (unit == 1) {
  744. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  745. } else if (unit == 2) {
  746. /* Chrome's getComputedStyle() reports used pixel values. */
  747. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  748. } else if (unit == 3) {
  749. snprintf(buf, cap, "%dpx",
  750. (int)br_root_font_px() * raw / 100);
  751. } else {
  752. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  753. raw / 100, raw % 100, px);
  754. }
  755. }
  756. static int js_host_computed(unsigned int node, const char *property,
  757. char *buf, int cap)
  758. {
  759. struct br_style st;
  760. char name[40];
  761. if (!buf || cap <= 0 || node >= doc.nnode || node == 0)
  762. return 0;
  763. buf[0] = '\0';
  764. css_computed_name(property, name, sizeof(name));
  765. style_for_node(node, &st);
  766. if (!strcmp(name, "display")) {
  767. const char *v = "inline";
  768. if (st.display == BR_DISPLAY_BLOCK)
  769. v = "block";
  770. else if (st.display == BR_DISPLAY_NONE)
  771. v = "none";
  772. else if (st.display == BR_DISPLAY_FLEX)
  773. v = "flex";
  774. else if (st.display == BR_DISPLAY_GRID)
  775. v = "grid";
  776. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  777. v = "inline-block";
  778. snprintf(buf, cap, "%s", v);
  779. } else if (!strcmp(name, "position")) {
  780. static const char *pos[] = {
  781. "static", "absolute", "fixed", "relative", "sticky"
  782. };
  783. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  784. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  785. int is_w = name[0] == 'w';
  786. int kind = is_w ? st.width_kind : st.height_kind;
  787. int val = is_w ? st.width : st.height;
  788. if (kind == 3) {
  789. if (is_w)
  790. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  791. st.width_calc_pct / 100,
  792. st.width_calc_pct % 100,
  793. st.width_calc_px);
  794. else
  795. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  796. st.height_calc_pct / 100,
  797. st.height_calc_pct % 100,
  798. st.height_calc_px);
  799. } else if (kind == 1) {
  800. snprintf(buf, cap, "%dpx", val);
  801. } else if (kind == 2) {
  802. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  803. } else {
  804. snprintf(buf, cap, "auto");
  805. }
  806. } else if (!strcmp(name, "color") ||
  807. !strcmp(name, "background-color")) {
  808. if (!strcmp(name, "background-color") && !st.has_bg)
  809. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  810. else
  811. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  812. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  813. int is_fill = name[0] == 'f';
  814. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  815. if (mode == BR_PAINT_COLOR)
  816. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  817. else if (mode == BR_PAINT_CURRENT)
  818. css_rgb(st.color, buf, cap);
  819. else if (mode == BR_PAINT_UNSET && is_fill)
  820. snprintf(buf, cap, "rgb(0, 0, 0)");
  821. else if (mode == BR_PAINT_URL)
  822. snprintf(buf, cap, "url()");
  823. else
  824. snprintf(buf, cap, "none");
  825. } else if (!strcmp(name, "font-size")) {
  826. snprintf(buf, cap, "%dpx", st.font_px);
  827. } else if (!strcmp(name, "font-weight")) {
  828. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  829. } else if (!strcmp(name, "font-style")) {
  830. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  831. } else if (!strcmp(name, "font-family")) {
  832. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  833. br_font_face_family(st.font_face)[0])
  834. snprintf(buf, cap, "%s",
  835. br_font_face_family(st.font_face));
  836. else
  837. snprintf(buf, cap, "%s",
  838. st.mono ? "monospace" : "sans-serif");
  839. } else if (!strcmp(name, "text-align")) {
  840. static const char *al[] = { "left", "center", "right", "justify" };
  841. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  842. } else if (!strcmp(name, "float")) {
  843. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  844. st.float_left == 2 ? "right" : "none");
  845. } else if (!strcmp(name, "clear")) {
  846. static const char *cl[] = { "none", "left", "right", "both" };
  847. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  848. } else if (!strcmp(name, "opacity")) {
  849. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  850. } else if (!strcmp(name, "visibility")) {
  851. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  852. } else if (!strcmp(name, "overflow")) {
  853. snprintf(buf, cap, "%s",
  854. st.overflow_hidden ? "hidden" : "visible");
  855. } else if (!strcmp(name, "white-space")) {
  856. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  857. } else if (!strcmp(name, "text-transform")) {
  858. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  859. } else if (!strcmp(name, "box-sizing")) {
  860. snprintf(buf, cap, "%s",
  861. st.box_sizing ? "border-box" : "content-box");
  862. } else if (!strcmp(name, "line-height")) {
  863. if (st.line_h_px)
  864. snprintf(buf, cap, "%dpx", st.line_h_px);
  865. else if (st.line_h_pct)
  866. snprintf(buf, cap, "%d%%", st.line_h_pct);
  867. else
  868. snprintf(buf, cap, "normal");
  869. } else if (!strcmp(name, "z-index")) {
  870. if (st.z_set)
  871. snprintf(buf, cap, "%d", st.z_index);
  872. else
  873. snprintf(buf, cap, "auto");
  874. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  875. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  876. int set = name[0] == 't' ? st.top_set :
  877. name[0] == 'l' ? st.left_set :
  878. name[0] == 'r' ? st.right_set : st.bottom_set;
  879. int v = name[0] == 't' ? st.top :
  880. name[0] == 'l' ? st.left :
  881. name[0] == 'r' ? st.right : st.bottom;
  882. if (set)
  883. snprintf(buf, cap, "%dpx", v);
  884. else
  885. snprintf(buf, cap, "auto");
  886. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  887. !strcmp(name, "margin-bottom") ||
  888. !strcmp(name, "margin-left") ||
  889. !strcmp(name, "padding-top") ||
  890. !strcmp(name, "padding-right") ||
  891. !strcmp(name, "padding-bottom") ||
  892. !strcmp(name, "padding-left")) {
  893. int is_pad = name[0] == 'p';
  894. int side = name[strlen(name) - 1] == 'p' ? 0 :
  895. name[strlen(name) - 1] == 't' ? 1 :
  896. name[strlen(name) - 1] == 'm' ? 2 : 3;
  897. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  898. if (!strcmp(name, "margin-right") ||
  899. !strcmp(name, "padding-right"))
  900. side = 1;
  901. else if (!strcmp(name, "margin-bottom") ||
  902. !strcmp(name, "padding-bottom"))
  903. side = 2;
  904. else if (!strcmp(name, "margin-left") ||
  905. !strcmp(name, "padding-left"))
  906. side = 3;
  907. else
  908. side = 0;
  909. side += is_pad ? 4 : 0;
  910. css_mp_value(buf, cap,
  911. side == 0 ? st.mt : side == 1 ? st.mr :
  912. side == 2 ? st.mb : side == 3 ? st.ml :
  913. side == 4 ? st.pt : side == 5 ? st.pr :
  914. side == 6 ? st.pb : st.pl,
  915. st.mp_unit[side], st.mp_calc_px[side],
  916. st.font_px);
  917. } else if (!strcmp(name, "border-top-width") ||
  918. !strcmp(name, "border-right-width") ||
  919. !strcmp(name, "border-bottom-width") ||
  920. !strcmp(name, "border-left-width")) {
  921. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  922. name[7] == 'b' ? 2 : 3;
  923. snprintf(buf, cap, "%dpx", st.border_w[side]);
  924. } else if (!strcmp(name, "border-top-color") ||
  925. !strcmp(name, "border-right-color") ||
  926. !strcmp(name, "border-bottom-color") ||
  927. !strcmp(name, "border-left-color")) {
  928. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  929. name[7] == 'b' ? 2 : 3;
  930. if (st.border_w[side] && !st.border_t[side])
  931. css_rgb(st.border_c[side], buf, cap);
  932. else
  933. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  934. } else if (!strcmp(name, "background-image")) {
  935. if (st.bg_image)
  936. snprintf(buf, cap, "url(\"%s\")",
  937. br_bg_image_url(st.bg_image - 1));
  938. else
  939. snprintf(buf, cap, "none");
  940. } else if (!strcmp(name, "background-repeat")) {
  941. static const char *rp[] = {
  942. "repeat", "no-repeat", "repeat-x", "repeat-y"
  943. };
  944. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  945. st.bg_repeat : 0]);
  946. } else if (!strcmp(name, "background-position")) {
  947. if (st.bg_pos_x_kind == 1)
  948. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  949. st.bg_pos_y);
  950. else
  951. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  952. st.bg_pos_y);
  953. } else if (!strcmp(name, "background-size")) {
  954. if (st.bg_size_kind == 3)
  955. snprintf(buf, cap, "cover");
  956. else if (st.bg_size_kind == 4)
  957. snprintf(buf, cap, "contain");
  958. else if (st.bg_size_kind == 1)
  959. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  960. st.bg_size_h);
  961. else if (st.bg_size_kind == 2)
  962. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  963. st.bg_size_h);
  964. else
  965. snprintf(buf, cap, "auto");
  966. } else if (!strcmp(name, "transform")) {
  967. char tmp[128];
  968. unsigned int n = 0;
  969. if (!st.transform_set) {
  970. snprintf(buf, cap, "none");
  971. } else {
  972. tmp[0] = '\0';
  973. if (st.tx || st.ty) {
  974. snprintf(tmp + n, sizeof(tmp) - n,
  975. "translate(%dpx, %dpx)", st.tx, st.ty);
  976. n = (unsigned int)strlen(tmp);
  977. }
  978. if (st.transform_scale) {
  979. snprintf(tmp + n, sizeof(tmp) - n,
  980. "%sscale(%d.%02d, %d.%02d)",
  981. n ? " " : "", st.scale_x / 100,
  982. st.scale_x % 100, st.scale_y / 100,
  983. st.scale_y % 100);
  984. n = (unsigned int)strlen(tmp);
  985. if (st.rotate_x100) {
  986. snprintf(tmp + n, sizeof(tmp) - n,
  987. " rotate(%d.%02ddeg)",
  988. st.rotate_x100 / 100,
  989. st.rotate_x100 % 100);
  990. }
  991. } else if (st.rotate_x100) {
  992. snprintf(tmp + n, sizeof(tmp) - n,
  993. "%srotate(%d.%02ddeg)",
  994. n ? " " : "", st.rotate_x100 / 100,
  995. st.rotate_x100 % 100);
  996. }
  997. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  998. }
  999. } else {
  1000. return 0;
  1001. }
  1002. return buf[0] != '\0';
  1003. }
  1004. static int js_host_click(unsigned int node)
  1005. {
  1006. char url[BR_URL_MAX];
  1007. const char *href;
  1008. if (node >= doc.nnode)
  1009. return 0;
  1010. if (form_is_control(node)) {
  1011. form_click(node); /* dispatches its own click event */
  1012. return 1;
  1013. }
  1014. /* element.click() fires a bubbling, cancelable click before the
  1015. * default action, like a real click (delegated list handlers). */
  1016. if (!js_browser_event(node, "click", 1, 1))
  1017. return 1;
  1018. href = br_href(&doc, node);
  1019. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1020. return 0;
  1021. s_copy(pending_url, url, sizeof(pending_url));
  1022. pending_action |= ACT_NAV;
  1023. cancel_fetch = 1;
  1024. ngui_invalidate(&ui);
  1025. return 1;
  1026. }
  1027. static int fetch_script_text(const char *url, unsigned char **out,
  1028. unsigned int *outlen, char *err,
  1029. unsigned int errcap);
  1030. struct fetch_worker;
  1031. static struct fetch_worker *fetch_worker_alloc(void);
  1032. static void fetch_worker_release(struct fetch_worker *w);
  1033. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1034. unsigned int cap, const char *post,
  1035. unsigned int post_len, unsigned int node,
  1036. int bg, char *err, unsigned int errcap);
  1037. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1038. unsigned int errcap);
  1039. static int fetch_worker_read_body(struct fetch_worker *w,
  1040. unsigned char *plain,
  1041. unsigned int plaincap,
  1042. unsigned char *comp,
  1043. unsigned int compcap,
  1044. int *truncated, char *err,
  1045. unsigned int errcap);
  1046. static void fetch_workers_stop_all(void);
  1047. static int script_cache_has(const char *url);
  1048. static void script_cache_put(const char *url, const unsigned char *data,
  1049. unsigned int len);
  1050. static void script_error(const char *what, const char *url, const char *why)
  1051. {
  1052. char msg[192];
  1053. unsigned int n = 0;
  1054. s_append(msg, &n, what, sizeof(msg));
  1055. if (url && url[0]) {
  1056. s_append(msg, &n, " ", sizeof(msg));
  1057. s_append(msg, &n, url, sizeof(msg));
  1058. }
  1059. if (why && why[0]) {
  1060. s_append(msg, &n, ": ", sizeof(msg));
  1061. s_append(msg, &n, why, sizeof(msg));
  1062. }
  1063. js_host_report(msg);
  1064. }
  1065. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1066. * submitted to helper workers ahead of time, but scripts still execute in
  1067. * document order. */
  1068. #define SCRIPT_INLINE 0
  1069. #define SCRIPT_LOCAL 1
  1070. #define SCRIPT_REMOTE 2
  1071. #define SCRIPT_ERROR 3
  1072. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1073. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1074. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1075. static void script_submit_window(unsigned int *next, char *err,
  1076. unsigned int errcap)
  1077. {
  1078. while (*next < doc.nscripts) {
  1079. struct fetch_worker *w;
  1080. if (script_kind[*next] != SCRIPT_REMOTE) {
  1081. (*next)++;
  1082. continue;
  1083. }
  1084. w = fetch_worker_alloc();
  1085. if (!w)
  1086. return;
  1087. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1088. 0, 0, 0, 0, err, errcap) != 0) {
  1089. fetch_worker_release(w);
  1090. script_kind[*next] = SCRIPT_ERROR;
  1091. (*next)++;
  1092. continue;
  1093. }
  1094. script_slot[*next] = w;
  1095. (*next)++;
  1096. }
  1097. }
  1098. /* Run the page's scripts in document order. External bodies are prefetched
  1099. * in parallel so downloading script N+1 overlaps executing script N; inline
  1100. * bodies are copied because the engine needs NUL-terminated text. */
  1101. static void run_page_scripts(void)
  1102. {
  1103. struct js_browser_host host;
  1104. unsigned int i, next = 0;
  1105. char err[64], ferr[64];
  1106. if (!doc.nscripts)
  1107. return;
  1108. host.status = js_host_status;
  1109. host.report = js_host_report;
  1110. host.navigate = js_host_navigate;
  1111. host.changed = js_host_changed;
  1112. host.rect = js_host_rect;
  1113. host.form_value = js_host_form_value;
  1114. host.form_checked = js_host_form_checked;
  1115. host.form_selected = js_host_form_selected;
  1116. host.form_set_value = js_host_form_set_value;
  1117. host.form_set_checked = js_host_form_set_checked;
  1118. host.form_set_selected = js_host_form_set_selected;
  1119. host.form_elements = js_host_form_elements;
  1120. host.form_submit = js_host_form_submit;
  1121. host.form_reset = js_host_form_reset;
  1122. host.click = js_host_click;
  1123. host.computed = js_host_computed;
  1124. host.page_url = page_url;
  1125. host.width = ui.w;
  1126. host.height = ui.h;
  1127. if (js_browser_start(&doc, &host) != 0) {
  1128. js_host_status("JavaScript: out of memory", 1);
  1129. return;
  1130. }
  1131. for (i = 0; i < doc.nscripts; i++) {
  1132. struct br_script *script = &doc.scripts[i];
  1133. const char *src_attr = script->src_off ?
  1134. doc.attrs + script->src_off : "";
  1135. script_slot[i] = 0;
  1136. if (!script->src_off) {
  1137. script_kind[i] = SCRIPT_INLINE;
  1138. continue;
  1139. }
  1140. if (!src_attr[0] ||
  1141. resolve_link(page_url, src_attr, script_urls[i],
  1142. sizeof(script_urls[i])) != 0) {
  1143. script_urls[i][0] = '\0';
  1144. script_kind[i] = SCRIPT_ERROR;
  1145. continue;
  1146. }
  1147. if (script_urls[i][0] == '/' ||
  1148. script_cache_has(script_urls[i]))
  1149. script_kind[i] = SCRIPT_LOCAL;
  1150. else
  1151. script_kind[i] = SCRIPT_REMOTE;
  1152. }
  1153. script_submit_window(&next, ferr, sizeof(ferr));
  1154. for (i = 0; i < doc.nscripts; i++) {
  1155. struct br_script *script = &doc.scripts[i];
  1156. if (script_kind[i] == SCRIPT_INLINE) {
  1157. unsigned int off = script->off;
  1158. unsigned int len = script->len;
  1159. unsigned int k;
  1160. char *src = (char *)malloc(len + 1);
  1161. if (!src) {
  1162. js_host_status("JavaScript: out of memory", 1);
  1163. break;
  1164. }
  1165. for (k = 0; k < len; k++)
  1166. src[k] = doc.script_src[off + k];
  1167. src[len] = '\0';
  1168. js_browser_run(src, page_url);
  1169. free(src);
  1170. } else if (script->src_off) {
  1171. const char *src_attr = doc.attrs + script->src_off;
  1172. if (script_kind[i] == SCRIPT_ERROR) {
  1173. script_error("Cannot load script", src_attr,
  1174. script_urls[i][0] ?
  1175. "network busy" :
  1176. "unsupported URL");
  1177. continue;
  1178. }
  1179. if (script_kind[i] == SCRIPT_LOCAL) {
  1180. unsigned char *data = 0;
  1181. unsigned int len = 0;
  1182. int rv;
  1183. set_status("Loading script...", 0, 0);
  1184. rv = fetch_script_text(script_urls[i], &data,
  1185. &len, err, sizeof(err));
  1186. if (rv == FETCH_ABORT)
  1187. break;
  1188. if (rv != 0) {
  1189. script_error("Cannot load script",
  1190. script_urls[i], err);
  1191. continue;
  1192. }
  1193. js_browser_run((const char *)data,
  1194. script_urls[i]);
  1195. free(data);
  1196. } else {
  1197. struct fetch_worker *w = script_slot[i];
  1198. int tr = 0, rv;
  1199. if (!w) {
  1200. w = fetch_worker_alloc();
  1201. if (!w)
  1202. continue;
  1203. if (fetch_worker_submit(w,
  1204. script_urls[i],
  1205. BR_SCRIPT_MAX,
  1206. 0, 0, 0, 0, err,
  1207. sizeof(err)) != 0) {
  1208. fetch_worker_release(w);
  1209. script_kind[i] = SCRIPT_ERROR;
  1210. if (i == next)
  1211. next++;
  1212. continue;
  1213. }
  1214. script_slot[i] = w;
  1215. if (i == next)
  1216. next++;
  1217. }
  1218. set_status("Loading script...", 0, 0);
  1219. rv = fetch_worker_wait(w, err, sizeof(err));
  1220. if (rv == FETCH_ABORT) {
  1221. fetch_workers_stop_all();
  1222. break;
  1223. }
  1224. if (rv == 0)
  1225. rv = fetch_worker_read_body(w,
  1226. image_io_buf, BR_SCRIPT_MAX,
  1227. image_io_buf + BR_SCRIPT_MAX,
  1228. BR_IMG_FILE_MAX, &tr, err,
  1229. sizeof(err));
  1230. else
  1231. rv = -1;
  1232. fetch_worker_release(w);
  1233. script_slot[i] = 0;
  1234. script_submit_window(&next, ferr, sizeof(ferr));
  1235. if (rv <= 0)
  1236. script_error("Cannot load script",
  1237. script_urls[i], err);
  1238. else if (tr || (unsigned int)rv >=
  1239. BR_SCRIPT_MAX)
  1240. script_error("Cannot load script",
  1241. script_urls[i],
  1242. "script is too large");
  1243. else {
  1244. image_io_buf[rv] = '\0';
  1245. script_cache_put(script_urls[i],
  1246. image_io_buf,
  1247. (unsigned int)rv);
  1248. js_browser_run(
  1249. (const char *)image_io_buf,
  1250. script_urls[i]);
  1251. }
  1252. }
  1253. }
  1254. if (pending_action)
  1255. break;
  1256. }
  1257. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  1258. * load_home() stop it before the next navigation. */
  1259. if (doc.scripts_truncated && !js_last_error)
  1260. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  1261. 1);
  1262. }
  1263. /* ---- images ---- */
  1264. static void image_reset(void)
  1265. {
  1266. int i;
  1267. for (i = 0; i < BR_MAX_IMAGES; i++) {
  1268. images[i].state = 0;
  1269. images[i].native_w = images[i].native_h = 0;
  1270. images[i].err[0] = '\0';
  1271. }
  1272. image_count = 0;
  1273. image_pixels = 0;
  1274. preload_active = 0;
  1275. preload_pending = 0;
  1276. preload_wait = 0;
  1277. preload_node = 0;
  1278. preload_loaded = 0;
  1279. }
  1280. /* Decode into the shared arena, then copy/scale the result into a display
  1281. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  1282. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  1283. * pixels. Transparent edges are composited over white. */
  1284. /* One decode scratch arena per page, reused across images. Allocating and
  1285. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  1286. * each small display bitmap landed in the hole the previous arena left, so
  1287. * the next arena no longer fit and the heap ratcheted up until an app
  1288. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  1289. * still released right after their one image. */
  1290. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  1291. static unsigned char *decode_arena_get(unsigned int bytes)
  1292. {
  1293. if (decode_arena && decode_arena_size >= bytes)
  1294. return decode_arena;
  1295. free(decode_arena);
  1296. decode_arena = (unsigned char *)malloc(bytes);
  1297. decode_arena_size = decode_arena ? bytes : 0;
  1298. return decode_arena;
  1299. }
  1300. static void decode_arena_put(void)
  1301. {
  1302. if (decode_arena_size > DECODE_ARENA_KEEP) {
  1303. free(decode_arena);
  1304. decode_arena = 0;
  1305. decode_arena_size = 0;
  1306. }
  1307. }
  1308. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  1309. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  1310. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  1311. static int decode_image_data(const unsigned char *data, unsigned int len,
  1312. struct br_image *bi, int box_w, int box_h)
  1313. {
  1314. struct img_info info;
  1315. struct img_options opt;
  1316. struct img_mem mem;
  1317. struct img_image decoded;
  1318. unsigned char *arena;
  1319. unsigned int est, bytes, i;
  1320. unsigned short *px;
  1321. unsigned char *alpha = 0;
  1322. int dw, dh, r;
  1323. if (img_sniff(data, len, &info) != 0) {
  1324. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  1325. return -1;
  1326. }
  1327. est = img_estimate(&info);
  1328. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  1329. s_copy(bi->err, "image too large", sizeof(bi->err));
  1330. return -1;
  1331. }
  1332. arena = decode_arena_get(est);
  1333. if (!arena) {
  1334. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1335. return -1;
  1336. }
  1337. img_mem_init(&mem, arena, est);
  1338. opt.max_pixels = BR_IMG_PIX_MAX;
  1339. r = img_decode(data, len, &opt, &mem, &decoded);
  1340. if (r != 0) {
  1341. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  1342. goto fail;
  1343. }
  1344. if (decoded.w == 0 || decoded.h == 0) {
  1345. s_copy(bi->err, "empty image", sizeof(bi->err));
  1346. goto fail;
  1347. }
  1348. bi->native_w = (int)decoded.w;
  1349. bi->native_h = (int)decoded.h;
  1350. dw = (int)decoded.w;
  1351. dh = (int)decoded.h;
  1352. if (box_w > 0 && box_h > 0) {
  1353. /* cover: scale so both box sides are filled, never up */
  1354. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  1355. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  1356. unsigned int sc = sw > sh ? sw : sh;
  1357. if (sc < 0x10000u) {
  1358. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  1359. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  1360. }
  1361. }
  1362. if (dw > BR_IMG_LAYOUT_W) {
  1363. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  1364. dw = BR_IMG_LAYOUT_W;
  1365. }
  1366. if (dh < 1)
  1367. dh = 1;
  1368. if (dw < 1)
  1369. dw = 1;
  1370. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  1371. BR_IMG_PIXEL_BUDGET) {
  1372. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  1373. goto fail;
  1374. }
  1375. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  1376. px = (unsigned short *)malloc(bytes);
  1377. if (!px) {
  1378. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1379. goto fail;
  1380. }
  1381. /* Keep the alpha plane for the scaled image so transparent logos and
  1382. * icons composite over the page instead of the browser's dark theme
  1383. * background. Very large alpha images stay flattened to bound the
  1384. * heap use. */
  1385. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  1386. alpha = (unsigned char *)malloc((unsigned int)dw *
  1387. (unsigned int)dh);
  1388. if (alpha) {
  1389. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1390. alpha[i] = 255;
  1391. }
  1392. }
  1393. /* With an alpha plane the colour under transparent pixels only shows
  1394. * through partially covered edge pixels of the downscale: use white,
  1395. * as documented above, not the dark browser theme (which left a dark
  1396. * fringe around scaled app icons). */
  1397. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1398. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  1399. {
  1400. struct img_blit b;
  1401. b.dst = px;
  1402. b.dst_w = dw;
  1403. b.dst_h = dh;
  1404. b.clip_x = 0;
  1405. b.clip_y = 0;
  1406. b.clip_w = dw;
  1407. b.clip_h = dh;
  1408. b.x = 0;
  1409. b.y = 0;
  1410. b.scale = ((unsigned int)dw << 16) / decoded.w;
  1411. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  1412. b.bg2 = b.bg;
  1413. b.dst_a = alpha;
  1414. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  1415. img_draw(&decoded, &b);
  1416. }
  1417. bi->img.format = decoded.format;
  1418. bi->img.w = (unsigned int)dw;
  1419. bi->img.h = (unsigned int)dh;
  1420. bi->img.px = px;
  1421. bi->img.alpha = alpha;
  1422. bi->img.flags = 0;
  1423. bi->state = 1;
  1424. image_pixels += (unsigned int)dw * (unsigned int)dh;
  1425. decode_arena_put();
  1426. return 0;
  1427. fail:
  1428. decode_arena_put();
  1429. return -1;
  1430. }
  1431. /* ---- URL / local path handling ---- */
  1432. static int is_http(const char *s)
  1433. {
  1434. return starts_with(s, "http://") || starts_with(s, "https://");
  1435. }
  1436. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  1437. static int normalize_abs(const char *in, char *out, unsigned int cap)
  1438. {
  1439. char seg[64];
  1440. unsigned int i = 0, o = 1;
  1441. int depth = 0;
  1442. int trailing;
  1443. if (!in || in[0] != '/' || cap < 2)
  1444. return -1;
  1445. trailing = 0;
  1446. {
  1447. unsigned int n = s_len(in);
  1448. if (n > 1 && in[n - 1] == '/')
  1449. trailing = 1;
  1450. }
  1451. out[0] = '/';
  1452. while (in[i]) {
  1453. unsigned int n = 0;
  1454. while (in[i] == '/')
  1455. i++;
  1456. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  1457. if (n + 1 < sizeof(seg))
  1458. seg[n++] = in[i];
  1459. i++;
  1460. }
  1461. seg[n] = '\0';
  1462. if (n == 0)
  1463. break;
  1464. if (s_eq(seg, "."))
  1465. continue;
  1466. if (s_eq(seg, "..")) {
  1467. if (depth > 0) {
  1468. while (o > 1 && out[o - 1] != '/')
  1469. o--;
  1470. if (o > 1)
  1471. o--;
  1472. depth--;
  1473. }
  1474. continue;
  1475. }
  1476. if (o > 1) {
  1477. if (o + 1 >= cap)
  1478. return -1;
  1479. out[o++] = '/';
  1480. }
  1481. if (o + n + 1 >= cap)
  1482. return -1;
  1483. {
  1484. unsigned int j;
  1485. for (j = 0; j < n; j++)
  1486. out[o++] = seg[j];
  1487. }
  1488. depth++;
  1489. }
  1490. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  1491. if (o + 1 >= cap)
  1492. return -1;
  1493. out[o++] = '/';
  1494. }
  1495. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  1496. if (in[i] == '?' || in[i] == '#') {
  1497. while (in[i]) {
  1498. if (o + 1 >= cap)
  1499. return -1;
  1500. out[o++] = in[i++];
  1501. }
  1502. }
  1503. out[o] = '\0';
  1504. return 0;
  1505. }
  1506. static void make_abs_local(const char *in, char *out, unsigned int cap)
  1507. {
  1508. char joined[BR_URL_MAX];
  1509. if (!in || !in[0]) {
  1510. s_copy(out, cwd[0] ? cwd : "/", cap);
  1511. return;
  1512. }
  1513. if (in[0] == '/') {
  1514. if (normalize_abs(in, out, cap) != 0)
  1515. s_copy(out, in, cap);
  1516. return;
  1517. }
  1518. {
  1519. unsigned int n = 0;
  1520. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  1521. s_append(joined, &n, "/", sizeof(joined));
  1522. s_append(joined, &n, in, sizeof(joined));
  1523. }
  1524. if (normalize_abs(joined, out, cap) != 0)
  1525. s_copy(out, joined, cap);
  1526. }
  1527. /* ---- canonical origin cache ---- *
  1528. *
  1529. * Sites commonly redirect http://host to https://host and then to
  1530. * https://www.host. Remember the final scheme/host of the last navigation so
  1531. * a bare domain typed again goes straight there instead of paying for two
  1532. * more connections and TLS handshakes. Only default-port requests are
  1533. * rewritten; explicit ports are left alone. */
  1534. #define ORIGIN_CACHE_MAX 8
  1535. #define ORIGIN_FILE "/share/borigins"
  1536. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  1537. UHTTP_HOST_MAX + 2))
  1538. struct origin_cache_entry {
  1539. char host[UHTTP_HOST_MAX];
  1540. char origin[UHTTP_HOST_MAX + 16];
  1541. };
  1542. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  1543. static int origin_count;
  1544. static char origin_buf[ORIGIN_BUF_SIZE];
  1545. static int default_port(const struct uhttp_url *u)
  1546. {
  1547. return u->secure ? u->port == 443 : u->port == 80;
  1548. }
  1549. static void url_origin(const struct uhttp_url *u, char *out,
  1550. unsigned int cap)
  1551. {
  1552. unsigned int n = 0;
  1553. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  1554. s_append(out, &n, u->host, cap);
  1555. if (!default_port(u)) {
  1556. s_append(out, &n, ":", cap);
  1557. s_append_dec(out, &n, u->port, cap);
  1558. }
  1559. }
  1560. static void origin_cache_apply(char *url, unsigned int cap)
  1561. {
  1562. struct uhttp_url u;
  1563. char out[BR_URL_MAX];
  1564. unsigned int n = 0;
  1565. int i;
  1566. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  1567. return;
  1568. for (i = 0; i < origin_count; i++) {
  1569. if (!s_eq(u.host, origins[i].host))
  1570. continue;
  1571. s_append(out, &n, origins[i].origin, sizeof(out));
  1572. s_append(out, &n, u.path, sizeof(out));
  1573. s_copy(url, out, cap);
  1574. return;
  1575. }
  1576. }
  1577. static void origin_cache_save(void)
  1578. {
  1579. unsigned int n = 0;
  1580. int i;
  1581. for (i = 0; i < origin_count; i++) {
  1582. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  1583. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  1584. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  1585. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  1586. }
  1587. if (n)
  1588. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  1589. (int)origin_buf, (int)n);
  1590. }
  1591. static void origin_cache_load(void)
  1592. {
  1593. char *p;
  1594. int rn;
  1595. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  1596. (int)(sizeof(origin_buf) - 1));
  1597. if (rn <= 0)
  1598. return;
  1599. origin_buf[rn] = '\0';
  1600. p = origin_buf;
  1601. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  1602. char *line = p, *origin;
  1603. while (*p && *p != '\n')
  1604. p++;
  1605. if (*p)
  1606. *p++ = '\0';
  1607. if (!line[0])
  1608. continue;
  1609. origin = line;
  1610. while (*origin && *origin != ' ')
  1611. origin++;
  1612. if (!*origin)
  1613. continue;
  1614. *origin++ = '\0';
  1615. if (!line[0] || !is_http(origin))
  1616. continue;
  1617. {
  1618. struct uhttp_url uo;
  1619. if (uhttp_parse_url(origin, &uo) != 0 ||
  1620. !s_eq(uo.path, "/"))
  1621. continue;
  1622. }
  1623. s_copy(origins[origin_count].host, line,
  1624. sizeof(origins[origin_count].host));
  1625. s_copy(origins[origin_count].origin, origin,
  1626. sizeof(origins[origin_count].origin));
  1627. origin_count++;
  1628. }
  1629. }
  1630. static int host_is_www_of(const char *host, const char *base)
  1631. {
  1632. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  1633. host[3] == '.' && s_eq(host + 4, base);
  1634. }
  1635. static void origin_cache_learn(const char *requested, const char *final)
  1636. {
  1637. struct uhttp_url from, to;
  1638. char origin[UHTTP_HOST_MAX + 16];
  1639. int i;
  1640. if (!is_http(requested) || !is_http(final))
  1641. return;
  1642. if (uhttp_parse_url(requested, &from) != 0 ||
  1643. uhttp_parse_url(final, &to) != 0)
  1644. return;
  1645. if (!default_port(&from))
  1646. return;
  1647. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  1648. from.port == to.port)
  1649. return;
  1650. /* Only remember origin-level canonicalisation: the same path, and
  1651. * either the same host or its www./apex sibling. A path- or
  1652. * host-specific redirect (a shortener, a login page) must not poison
  1653. * every request to the typed host. */
  1654. if (!s_eq(from.path, to.path))
  1655. return;
  1656. if (!s_eq(from.host, to.host) &&
  1657. !host_is_www_of(to.host, from.host) &&
  1658. !host_is_www_of(from.host, to.host))
  1659. return;
  1660. url_origin(&to, origin, sizeof(origin));
  1661. for (i = 0; i < origin_count; i++) {
  1662. if (s_eq(origins[i].host, from.host)) {
  1663. if (!s_eq(origins[i].origin, origin)) {
  1664. s_copy(origins[i].origin, origin,
  1665. sizeof(origins[i].origin));
  1666. origin_cache_save();
  1667. }
  1668. return;
  1669. }
  1670. }
  1671. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  1672. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  1673. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  1674. origin_cache_save();
  1675. }
  1676. static int path_dir(const char *path, char *out, unsigned int cap)
  1677. {
  1678. unsigned int i, last = 0;
  1679. for (i = 0; path[i]; i++)
  1680. if (path[i] == '/')
  1681. last = i;
  1682. if (last == 0) {
  1683. if (cap < 2)
  1684. return -1;
  1685. out[0] = '/';
  1686. out[1] = '\0';
  1687. return 0;
  1688. }
  1689. if (last + 1 >= cap)
  1690. return -1;
  1691. {
  1692. unsigned int j;
  1693. for (j = 0; j < last; j++)
  1694. out[j] = path[j];
  1695. out[last] = '\0';
  1696. }
  1697. return 0;
  1698. }
  1699. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  1700. static int resolve_link(const char *base, const char *href, char *out,
  1701. unsigned int cap)
  1702. {
  1703. char joined[BR_URL_MAX];
  1704. if (!href || !href[0] || href[0] == '#')
  1705. return -1;
  1706. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  1707. starts_with(href, "data:") || starts_with(href, "tel:"))
  1708. return -1;
  1709. if (starts_with(href, "about:")) {
  1710. s_copy(out, href, cap);
  1711. return 0;
  1712. }
  1713. if (is_http(href)) {
  1714. s_copy(out, href, cap);
  1715. return 0;
  1716. }
  1717. if (starts_with(href, "//")) {
  1718. if (is_http(base)) {
  1719. unsigned int n = 0;
  1720. s_append(out, &n, starts_with(base, "https:") ?
  1721. "https:" : "http:", cap);
  1722. s_append(out, &n, href, cap);
  1723. return 0;
  1724. }
  1725. return -1;
  1726. }
  1727. if (is_http(base)) {
  1728. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  1729. }
  1730. /* local page */
  1731. if (href[0] == '/') {
  1732. if (normalize_abs(href, out, cap) != 0)
  1733. return -1;
  1734. return 0;
  1735. }
  1736. {
  1737. char dir[BR_URL_MAX];
  1738. unsigned int n = 0;
  1739. if (s_eq(base, "about:home"))
  1740. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  1741. else if (path_dir(base, dir, sizeof(dir)) != 0)
  1742. s_copy(dir, "/", sizeof(dir));
  1743. s_append(joined, &n, dir, sizeof(joined));
  1744. if (n == 0 || joined[n - 1] != '/')
  1745. s_append(joined, &n, "/", sizeof(joined));
  1746. s_append(joined, &n, href, sizeof(joined));
  1747. }
  1748. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  1749. }
  1750. /* Best-effort decompression: keep the first `cap` bytes and discard the
  1751. * rest instead of failing when a page or stylesheet is larger than the
  1752. * buffer. The stream is still walked to the end, so a normal page is
  1753. * verified; a truncated compressed input still returns whatever was decoded
  1754. * so far. */
  1755. struct trunc_buf {
  1756. unsigned char *dst;
  1757. unsigned int cap, pos;
  1758. int full;
  1759. };
  1760. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  1761. {
  1762. struct trunc_buf *m = (struct trunc_buf *)ctx;
  1763. if (len > m->cap - m->pos) {
  1764. unsigned int room = m->cap - m->pos;
  1765. if (room) {
  1766. unsigned int i;
  1767. for (i = 0; i < room; i++)
  1768. m->dst[m->pos + i] = data[i];
  1769. m->pos += room;
  1770. }
  1771. m->full = 1;
  1772. return 0;
  1773. }
  1774. {
  1775. unsigned int i;
  1776. for (i = 0; i < len; i++)
  1777. m->dst[m->pos + i] = data[i];
  1778. }
  1779. m->pos += len;
  1780. return 0;
  1781. }
  1782. static void worker_wait_ui(void);
  1783. static void inflate_ui_pump(void *ctx)
  1784. {
  1785. static unsigned int last;
  1786. unsigned int now = u_ticks_ms();
  1787. (void)ctx;
  1788. if ((int)(now - last) >= 50) {
  1789. last = now;
  1790. worker_wait_ui();
  1791. }
  1792. }
  1793. static int inflate_trunc(const unsigned char *src, unsigned int len,
  1794. unsigned char *dst, unsigned int cap,
  1795. unsigned int *outlen, int gzip, int *truncated)
  1796. {
  1797. struct inflate_src in;
  1798. struct inflate_sink sink;
  1799. struct trunc_buf m;
  1800. unsigned int got = 0;
  1801. int r;
  1802. in.p = src;
  1803. in.len = len;
  1804. in.more = 0;
  1805. in.ctx = 0;
  1806. m.dst = dst;
  1807. m.cap = cap;
  1808. m.pos = 0;
  1809. m.full = 0;
  1810. sink.write = trunc_write;
  1811. sink.ctx = &m;
  1812. inflate_init(&image_inflate_ws, &in, &sink);
  1813. image_inflate_ws.progress = inflate_ui_pump;
  1814. image_inflate_ws.progress_ctx = 0;
  1815. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  1816. inflate_zlib(&image_inflate_ws, &got);
  1817. *outlen = m.pos;
  1818. *truncated = m.full || r != 0;
  1819. if (r != 0 && m.pos == 0)
  1820. return -1;
  1821. return 0;
  1822. }
  1823. /* ---- headless fetch workers ------------------------------------------ *
  1824. *
  1825. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  1826. * writes the raw response, a small metadata file and a done marker under
  1827. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  1828. * or a multi-megabyte body never freezes the UI and images download in
  1829. * parallel.
  1830. */
  1831. struct fetch_meta {
  1832. int status;
  1833. int error;
  1834. int trunc;
  1835. unsigned int len;
  1836. unsigned int open_ms;
  1837. unsigned int first_ms;
  1838. unsigned int total_ms;
  1839. char encoding[16];
  1840. char ctype[64];
  1841. char final[BR_URL_MAX];
  1842. };
  1843. static void draw(unsigned int *action);
  1844. static void handle_keys(unsigned int *action);
  1845. static void handle_page_click(unsigned int *action);
  1846. #define FETCH_WORKERS 4
  1847. #define FETCH_PATH_MAX 32
  1848. /* One long-lived curl __serve helper per worker. Each worker has its own
  1849. * request/body/meta/done files under /share so several downloads can be in
  1850. * flight at once; the keep-alive connection stays in the helper process, so
  1851. * tls.c's per-process state remains valid. */
  1852. struct fetch_worker {
  1853. int pid;
  1854. int slot;
  1855. int busy;
  1856. int ready;
  1857. int image_job;
  1858. unsigned int seq;
  1859. unsigned int deadline;
  1860. int retried;
  1861. char req[FETCH_PATH_MAX];
  1862. char body[FETCH_PATH_MAX];
  1863. char meta[FETCH_PATH_MAX];
  1864. char done[FETCH_PATH_MAX];
  1865. char post[FETCH_PATH_MAX];
  1866. /* Optional preload job attached to this worker. */
  1867. unsigned int node;
  1868. int bg;
  1869. char url[BR_URL_MAX];
  1870. struct fetch_meta m;
  1871. };
  1872. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  1873. static int fetch_tty = -2;
  1874. static void fetch_tty_drain(void);
  1875. static unsigned int fetch_session;
  1876. static unsigned int fetch_seq;
  1877. static struct fetch_meta fetch_meta;
  1878. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  1879. * an HTTP-level error (helper died, timeout in the browser, ...). */
  1880. static int fetch_last_error;
  1881. static unsigned int meta_uint(char **pp)
  1882. {
  1883. char *p = *pp;
  1884. unsigned int v = 0;
  1885. while (*p >= '0' && *p <= '9') {
  1886. v = v * 10 + (unsigned int)(*p - '0');
  1887. p++;
  1888. }
  1889. while (*p && *p != '\n')
  1890. p++;
  1891. if (*p == '\n')
  1892. p++;
  1893. *pp = p;
  1894. return v;
  1895. }
  1896. static void meta_str(char **pp, char *out, unsigned int cap)
  1897. {
  1898. char *p = *pp;
  1899. unsigned int n = 0;
  1900. while (*p && *p != '\n' && n + 1 < cap)
  1901. out[n++] = *p++;
  1902. out[n] = '\0';
  1903. while (*p && *p != '\n')
  1904. p++;
  1905. if (*p == '\n')
  1906. p++;
  1907. *pp = p;
  1908. }
  1909. static void worker_wait_ui(void)
  1910. {
  1911. unsigned int action = 0;
  1912. if (!ngui_begin(&ui))
  1913. return;
  1914. draw(&action);
  1915. handle_keys(&action);
  1916. handle_page_click(&action);
  1917. if (action & ACT_WAIT_NAV) {
  1918. pending_action |= action & ACT_WAIT_NAV;
  1919. if ((action & ACT_NAV) && click_url[0])
  1920. s_copy(pending_url, click_url, sizeof(pending_url));
  1921. click_url[0] = '\0';
  1922. cancel_fetch = 1;
  1923. }
  1924. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  1925. ngui_invalidate(&ui);
  1926. ngui_end(&ui);
  1927. }
  1928. static void fetch_path(char *out, unsigned int cap, const char *kind,
  1929. unsigned int session, int slot)
  1930. {
  1931. unsigned int n = 0;
  1932. s_append(out, &n, "/share/bf", cap);
  1933. s_append_dec(out, &n, session, cap);
  1934. s_append(out, &n, "_", cap);
  1935. s_append_dec(out, &n, (unsigned int)slot, cap);
  1936. s_append(out, &n, kind, cap);
  1937. }
  1938. static void fetch_pool_init(void)
  1939. {
  1940. static int ready;
  1941. int i;
  1942. if (ready)
  1943. return;
  1944. ready = 1;
  1945. fetch_session = ((unsigned int)u_getpid() << 16) ^
  1946. (u_ticks_ms() & 0xFFFFu);
  1947. if (!fetch_session)
  1948. fetch_session = 1;
  1949. for (i = 0; i < FETCH_WORKERS; i++) {
  1950. struct fetch_worker *w = &fetch_workers[i];
  1951. w->pid = -1;
  1952. w->slot = i;
  1953. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  1954. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  1955. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  1956. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  1957. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  1958. }
  1959. }
  1960. static void fetch_worker_stop(struct fetch_worker *w)
  1961. {
  1962. int i;
  1963. /* An abandoned image job leaves its node loadable again. */
  1964. if (w->busy && w->image_job && w->node < doc.nnode) {
  1965. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  1966. doc.nodes[w->node].bg_img_index = -1;
  1967. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  1968. doc.nodes[w->node].img_index = -1;
  1969. }
  1970. if (w->pid > 0) {
  1971. u_kill((unsigned int)w->pid);
  1972. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  1973. u_sleep_ms(5);
  1974. /* Let the reaper close the socket before we reuse the slot. */
  1975. u_sleep_ms(10);
  1976. }
  1977. w->pid = -1;
  1978. w->busy = 0;
  1979. w->ready = 0;
  1980. w->image_job = 0;
  1981. if (w->req[0]) {
  1982. u_syscall1(SYS_UNLINK, (int)w->done);
  1983. u_syscall1(SYS_UNLINK, (int)w->meta);
  1984. u_syscall1(SYS_UNLINK, (int)w->body);
  1985. u_syscall1(SYS_UNLINK, (int)w->post);
  1986. u_syscall1(SYS_UNLINK, (int)w->req);
  1987. }
  1988. }
  1989. static void fetch_workers_stop_all(void)
  1990. {
  1991. int i;
  1992. for (i = 0; i < FETCH_WORKERS; i++)
  1993. fetch_worker_stop(&fetch_workers[i]);
  1994. }
  1995. /* Abandon the transfers of the current page but keep idle helpers and their
  1996. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  1997. * because its response would otherwise land in a reused /share slot. */
  1998. static void fetch_workers_cancel_busy(void)
  1999. {
  2000. int i;
  2001. for (i = 0; i < FETCH_WORKERS; i++)
  2002. if (fetch_workers[i].busy)
  2003. fetch_worker_stop(&fetch_workers[i]);
  2004. }
  2005. static void fetch_workers_prepare_nav(const char *url)
  2006. {
  2007. int i;
  2008. (void)url;
  2009. for (i = 0; i < FETCH_WORKERS; i++) {
  2010. struct fetch_worker *w = &fetch_workers[i];
  2011. if (w->pid <= 0)
  2012. continue;
  2013. /* Only an in-flight transfer must be aborted. Idle helpers
  2014. * stay warm across origins: there are just FETCH_WORKERS of
  2015. * them, and uhttp_open drops the old connection when the
  2016. * next job is for another host. Killing and respawning all
  2017. * four on every navigation churned processes and sockets
  2018. * while images were still loading. */
  2019. if (w->busy)
  2020. fetch_worker_stop(w);
  2021. }
  2022. }
  2023. /* The browser is no longer the active window and no fetch is running: give
  2024. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  2025. static void fetch_workers_stop_if_unfocused(void)
  2026. {
  2027. int i;
  2028. fetch_tty_drain();
  2029. if (ui.focused || page_loading || preload_active)
  2030. return;
  2031. for (i = 0; i < FETCH_WORKERS; i++)
  2032. if (fetch_workers[i].pid > 0) {
  2033. fetch_workers_stop_all();
  2034. return;
  2035. }
  2036. }
  2037. /* The helpers (and this process, since u_tty_create() rebinds our own
  2038. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  2039. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  2040. * a dozen TLS connections every helper hung in its next log line, so the
  2041. * following cross-origin navigation sat at "Loading..." until it timed out.
  2042. * Drain and discard it from every wait/poll loop. */
  2043. static void fetch_tty_drain(void)
  2044. {
  2045. char sink[512];
  2046. int i;
  2047. if (fetch_tty <= 0)
  2048. return;
  2049. for (i = 0; i < 16; i++)
  2050. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  2051. break;
  2052. }
  2053. static int fetch_worker_start(struct fetch_worker *w, char *err,
  2054. unsigned int errcap)
  2055. {
  2056. char arg[40];
  2057. unsigned int n = 0;
  2058. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  2059. return 0;
  2060. w->pid = -1;
  2061. fetch_pool_init();
  2062. if (fetch_tty == -2) {
  2063. int t = u_tty_create();
  2064. fetch_tty = t > 0 ? t : 0;
  2065. }
  2066. s_append(arg, &n, "__serve ", sizeof(arg));
  2067. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  2068. s_append(arg, &n, " ", sizeof(arg));
  2069. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  2070. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  2071. if (w->pid <= 0) {
  2072. w->pid = -1;
  2073. s_copy(err, "cannot start network helper", errcap);
  2074. return -1;
  2075. }
  2076. return 0;
  2077. }
  2078. static struct fetch_worker *fetch_worker_alloc(void)
  2079. {
  2080. int i;
  2081. fetch_pool_init();
  2082. for (i = 0; i < FETCH_WORKERS; i++)
  2083. if (!fetch_workers[i].busy)
  2084. return &fetch_workers[i];
  2085. return 0;
  2086. }
  2087. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  2088. unsigned int cap, const char *post,
  2089. unsigned int post_len, unsigned int node,
  2090. int bg, char *err, unsigned int errcap)
  2091. {
  2092. static char req[768];
  2093. unsigned int n = 0;
  2094. fetch_seq++;
  2095. if (!fetch_seq)
  2096. fetch_seq = 1;
  2097. w->seq = fetch_seq;
  2098. w->ready = 0;
  2099. w->image_job = 0;
  2100. w->retried = 0;
  2101. w->m.error = 0;
  2102. w->node = node;
  2103. w->bg = bg;
  2104. s_copy(w->url, url, sizeof(w->url));
  2105. s_append_dec(req, &n, w->seq, sizeof(req));
  2106. s_append(req, &n, " ", sizeof(req));
  2107. s_append_dec(req, &n, cap, sizeof(req));
  2108. s_append(req, &n, " ", sizeof(req));
  2109. if (post_len) {
  2110. s_append(req, &n, "POST ", sizeof(req));
  2111. s_append_dec(req, &n, post_len, sizeof(req));
  2112. s_append(req, &n, " ", sizeof(req));
  2113. }
  2114. s_append(req, &n, url, sizeof(req));
  2115. s_append(req, &n, "\n", sizeof(req));
  2116. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  2117. (int)post, (int)post_len) < 0) {
  2118. s_copy(err, "cannot queue form body", errcap);
  2119. return -1;
  2120. }
  2121. u_syscall1(SYS_UNLINK, (int)w->done);
  2122. u_syscall1(SYS_UNLINK, (int)w->meta);
  2123. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  2124. s_copy(err, "cannot queue network request", errcap);
  2125. return -1;
  2126. }
  2127. if (fetch_worker_start(w, err, errcap) != 0)
  2128. return -1;
  2129. w->busy = 1;
  2130. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  2131. return 0;
  2132. }
  2133. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  2134. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  2135. unsigned int errcap)
  2136. {
  2137. static char meta[1024];
  2138. char *p;
  2139. int rn, mseq;
  2140. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  2141. (int)(sizeof(meta) - 1));
  2142. if (rn <= 0) {
  2143. s_copy(err, "network helper failed", errcap);
  2144. return -1;
  2145. }
  2146. meta[rn] = '\0';
  2147. p = meta;
  2148. mseq = (int)meta_uint(&p);
  2149. if (mseq != (int)w->seq) {
  2150. s_copy(err, "stale network response", errcap);
  2151. return -1;
  2152. }
  2153. w->m.status = (int)meta_uint(&p);
  2154. w->m.error = (int)meta_uint(&p);
  2155. w->m.trunc = (int)meta_uint(&p);
  2156. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  2157. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  2158. meta_str(&p, w->m.final, sizeof(w->m.final));
  2159. w->m.len = meta_uint(&p);
  2160. w->m.open_ms = 0;
  2161. w->m.first_ms = 0;
  2162. w->m.total_ms = 0;
  2163. if (*p) {
  2164. w->m.open_ms = meta_uint(&p);
  2165. w->m.first_ms = meta_uint(&p);
  2166. w->m.total_ms = meta_uint(&p);
  2167. }
  2168. if (w->m.error) {
  2169. s_copy(err, uhttp_error_string(w->m.error), errcap);
  2170. return -1;
  2171. }
  2172. w->ready = 1;
  2173. return 0;
  2174. }
  2175. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  2176. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  2177. unsigned int errcap)
  2178. {
  2179. static char done[24];
  2180. char *p;
  2181. int rn, mseq;
  2182. fetch_tty_drain();
  2183. if (!w->busy)
  2184. return -1;
  2185. if (w->ready)
  2186. return 1;
  2187. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  2188. (int)(sizeof(done) - 1));
  2189. if (rn > 0) {
  2190. done[rn] = '\0';
  2191. p = done;
  2192. mseq = (int)meta_uint(&p);
  2193. if (mseq == (int)w->seq) {
  2194. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  2195. fetch_worker_stop(w);
  2196. return -1;
  2197. }
  2198. return 1;
  2199. }
  2200. }
  2201. if (!u_alive((unsigned int)w->pid)) {
  2202. w->pid = -1;
  2203. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  2204. w->retried = 1;
  2205. return 0;
  2206. }
  2207. s_copy(err, "network helper stopped", errcap);
  2208. fetch_worker_stop(w);
  2209. return -1;
  2210. }
  2211. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  2212. s_copy(err, "network request timed out", errcap);
  2213. fetch_worker_stop(w);
  2214. return -1;
  2215. }
  2216. return 0;
  2217. }
  2218. /* Copy the completed body, inflating it if the server ignored our identity
  2219. * request. Mirrors the old fetch_remote body path. */
  2220. static int fetch_worker_read_body(struct fetch_worker *w,
  2221. unsigned char *plain,
  2222. unsigned int plaincap,
  2223. unsigned char *comp,
  2224. unsigned int compcap,
  2225. int *truncated, char *err,
  2226. unsigned int errcap)
  2227. {
  2228. int rv, zr, was_trunc;
  2229. if (contains_ci(w->m.encoding, "gzip") ||
  2230. contains_ci(w->m.encoding, "deflate")) {
  2231. unsigned int comp_len = 0, plen = 0;
  2232. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  2233. (int)compcap);
  2234. if (rv < 0) {
  2235. s_copy(err, "empty response", errcap);
  2236. return -1;
  2237. }
  2238. comp_len = (unsigned int)rv;
  2239. if (comp_len < w->m.len) {
  2240. s_copy(err, "compressed response is too large", errcap);
  2241. return -1;
  2242. }
  2243. if (contains_ci(w->m.encoding, "deflate"))
  2244. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2245. &plen, 0, &was_trunc);
  2246. else
  2247. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2248. &plen, 1, &was_trunc);
  2249. if (zr != 0) {
  2250. s_copy(err, "compressed response is corrupt", errcap);
  2251. return -1;
  2252. }
  2253. *truncated = w->m.trunc || was_trunc;
  2254. return (int)plen;
  2255. }
  2256. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  2257. if (rv < 0) {
  2258. s_copy(err, "empty response", errcap);
  2259. return -1;
  2260. }
  2261. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  2262. return rv;
  2263. }
  2264. static void fetch_worker_release(struct fetch_worker *w)
  2265. {
  2266. u_syscall1(SYS_UNLINK, (int)w->done);
  2267. u_syscall1(SYS_UNLINK, (int)w->meta);
  2268. u_syscall1(SYS_UNLINK, (int)w->body);
  2269. u_syscall1(SYS_UNLINK, (int)w->post);
  2270. u_syscall1(SYS_UNLINK, (int)w->req);
  2271. w->busy = 0;
  2272. w->ready = 0;
  2273. w->image_job = 0;
  2274. }
  2275. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  2276. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  2277. unsigned int errcap)
  2278. {
  2279. for (;;) {
  2280. int rv;
  2281. worker_wait_ui();
  2282. if (cancel_fetch || pending_action) {
  2283. fetch_workers_cancel_busy();
  2284. return FETCH_ABORT;
  2285. }
  2286. rv = fetch_worker_poll(w, err, errcap);
  2287. if (rv != 0)
  2288. return rv == 1 ? 0 : -1;
  2289. u_sleep_ms(10);
  2290. }
  2291. }
  2292. static int fetch_remote(const char *url, unsigned int cap,
  2293. const char *post, unsigned int post_len,
  2294. unsigned char *plain, unsigned int plaincap,
  2295. unsigned char *comp, unsigned int compcap,
  2296. struct fetch_meta *m, int *truncated,
  2297. char *err, unsigned int errcap)
  2298. {
  2299. struct fetch_worker *w = fetch_worker_alloc();
  2300. int rv;
  2301. fetch_last_error = 0;
  2302. if (!w) {
  2303. s_copy(err, "network busy", errcap);
  2304. return -1;
  2305. }
  2306. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  2307. err, errcap) != 0) {
  2308. fetch_worker_release(w);
  2309. return -1;
  2310. }
  2311. rv = fetch_worker_wait(w, err, errcap);
  2312. if (rv == FETCH_ABORT) {
  2313. fetch_worker_release(w);
  2314. return FETCH_ABORT;
  2315. }
  2316. if (rv != 0) {
  2317. fetch_last_error = w->m.error;
  2318. fetch_worker_release(w);
  2319. return -1;
  2320. }
  2321. *m = w->m;
  2322. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  2323. truncated, err, errcap);
  2324. fetch_worker_release(w);
  2325. if (rv >= 0 && (cancel_fetch || pending_action))
  2326. return FETCH_ABORT;
  2327. return rv;
  2328. }
  2329. /* ---- HTTP / file fetch ---- */
  2330. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  2331. unsigned int *outlen, int *is_local, char *ctype,
  2332. unsigned int ctcap, char *final, unsigned int finalcap,
  2333. char *err, unsigned int errcap, int *truncated,
  2334. const char *post, unsigned int post_len)
  2335. {
  2336. unsigned char *buf;
  2337. unsigned int len;
  2338. int tr = 0;
  2339. int rv;
  2340. *out = 0;
  2341. *outlen = 0;
  2342. *truncated = 0;
  2343. if (final && finalcap)
  2344. final[0] = '\0';
  2345. if (ctype && ctcap)
  2346. ctype[0] = '\0';
  2347. if (url[0] == '/') {
  2348. char pathbuf[BR_URL_MAX];
  2349. const char *open_url = url;
  2350. unsigned int i = 0;
  2351. /* A local form GET keeps ?query in the address bar but the
  2352. * file lookup uses the path alone, like a real browser. */
  2353. while (url[i] && url[i] != '?' && url[i] != '#')
  2354. i++;
  2355. if (url[i]) {
  2356. s_copy(pathbuf, url, i + 1);
  2357. open_url = pathbuf;
  2358. }
  2359. buf = (unsigned char *)malloc(cap);
  2360. if (!buf) {
  2361. s_copy(err, "out of memory", errcap);
  2362. return -1;
  2363. }
  2364. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  2365. if (rv < 0) {
  2366. free(buf);
  2367. s_copy(err, "file not found", errcap);
  2368. return -1;
  2369. }
  2370. *out = buf;
  2371. *outlen = (unsigned int)rv;
  2372. *is_local = 1;
  2373. if (ctype)
  2374. s_copy(ctype, "text/html", ctcap);
  2375. if (final)
  2376. s_copy(final, url, finalcap);
  2377. if ((unsigned int)rv == cap)
  2378. *truncated = 1;
  2379. return 0;
  2380. }
  2381. buf = (unsigned char *)malloc(cap);
  2382. if (!buf) {
  2383. s_copy(err, "out of memory", errcap);
  2384. return -1;
  2385. }
  2386. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  2387. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  2388. if (rv == FETCH_ABORT) {
  2389. free(buf);
  2390. return FETCH_ABORT;
  2391. }
  2392. if (rv < 0) {
  2393. free(buf);
  2394. return -1;
  2395. }
  2396. len = (unsigned int)rv;
  2397. if (len == 0) {
  2398. free(buf);
  2399. s_copy(err, "empty response", errcap);
  2400. return -1;
  2401. }
  2402. if (ctype)
  2403. s_copy(ctype, fetch_meta.ctype, ctcap);
  2404. if (final && fetch_meta.final[0])
  2405. s_copy(final, fetch_meta.final, finalcap);
  2406. *is_local = 0;
  2407. *out = buf;
  2408. *outlen = len;
  2409. *truncated = tr;
  2410. return 0;
  2411. }
  2412. /* Load every @font-face the parser registered. Local files go through
  2413. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  2414. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  2415. * to the built-in regular/bold/italic/mono set. */
  2416. static void load_font_faces(void)
  2417. {
  2418. unsigned int i;
  2419. memset(font_faces, 0, sizeof(font_faces));
  2420. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  2421. i <= BR_MAX_FACES; i++) {
  2422. const char *url = br_font_face_url((int)i);
  2423. const char *base = br_font_face_base((int)i);
  2424. char abs[BR_URL_MAX];
  2425. if (!url || !url[0])
  2426. continue;
  2427. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  2428. sizeof(abs)) != 0)
  2429. continue;
  2430. if (abs[0] == '/') {
  2431. font_faces[i - 1] = ufont_face_open_path(abs);
  2432. } else if (is_http(abs)) {
  2433. unsigned char *buf;
  2434. char err[64];
  2435. int rv, tr = 0;
  2436. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  2437. if (!buf)
  2438. continue;
  2439. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  2440. UFONT_MAX_FILE, image_io_buf,
  2441. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  2442. err, sizeof(err));
  2443. if (rv > 0)
  2444. font_faces[i - 1] = ufont_face_open_mem(buf,
  2445. rv);
  2446. free(buf);
  2447. }
  2448. }
  2449. }
  2450. /* Remote scripts are cached under /share for the current boot, like the
  2451. * stylesheet cache, so reloads and later visits skip the network. */
  2452. static int script_cache_count;
  2453. static unsigned int script_cache_hash(const char *s)
  2454. {
  2455. unsigned int h = 2166136261u;
  2456. while (*s) {
  2457. h ^= (unsigned char)*s++;
  2458. h *= 16777619u;
  2459. }
  2460. return h;
  2461. }
  2462. static void script_cache_path(const char *url, char *out, unsigned int cap)
  2463. {
  2464. unsigned int n = 0;
  2465. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  2466. s_append_dec(out, &n, script_cache_hash(url), cap);
  2467. }
  2468. static void script_cache_clear(void)
  2469. {
  2470. struct sys_dirent d;
  2471. char path[96];
  2472. for (;;) {
  2473. int i, found = 0;
  2474. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2475. (int)&d) == 1; i++) {
  2476. unsigned int n = 0;
  2477. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  2478. continue;
  2479. s_append(path, &n, "/share/", sizeof(path));
  2480. s_append(path, &n, d.name, sizeof(path));
  2481. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  2482. return;
  2483. found = 1;
  2484. break;
  2485. }
  2486. if (!found)
  2487. break;
  2488. }
  2489. script_cache_count = 0;
  2490. }
  2491. static void script_cache_init(void)
  2492. {
  2493. struct sys_dirent d;
  2494. int i, count = 0;
  2495. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2496. (int)&d) == 1; i++)
  2497. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  2498. count++;
  2499. if (count >= SCRIPT_CACHE_MAX) {
  2500. script_cache_clear();
  2501. return;
  2502. }
  2503. script_cache_count = count;
  2504. }
  2505. static int script_cache_get(const char *url, unsigned char **out,
  2506. unsigned int *outlen)
  2507. {
  2508. char path[96];
  2509. struct sys_stat st;
  2510. unsigned char *buf;
  2511. int rn;
  2512. script_cache_path(url, path, sizeof(path));
  2513. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  2514. st.size >= SCRIPT_CACHE_FILE_MAX)
  2515. return 0;
  2516. buf = (unsigned char *)malloc(st.size + 1);
  2517. if (!buf)
  2518. return 0;
  2519. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  2520. if (rn != (int)st.size) {
  2521. free(buf);
  2522. return 0;
  2523. }
  2524. buf[st.size] = '\0';
  2525. *out = buf;
  2526. *outlen = st.size;
  2527. return 1;
  2528. }
  2529. static void script_cache_put(const char *url, const unsigned char *data,
  2530. unsigned int len)
  2531. {
  2532. char path[96];
  2533. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  2534. len >= SCRIPT_CACHE_FILE_MAX)
  2535. return;
  2536. script_cache_path(url, path, sizeof(path));
  2537. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  2538. (int)len) >= 0)
  2539. script_cache_count++;
  2540. }
  2541. static int script_cache_has(const char *url)
  2542. {
  2543. char path[96];
  2544. struct sys_stat st;
  2545. script_cache_path(url, path, sizeof(path));
  2546. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  2547. st.size < SCRIPT_CACHE_FILE_MAX;
  2548. }
  2549. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  2550. static int fetch_script_text(const char *url, unsigned char **out,
  2551. unsigned int *outlen, char *err,
  2552. unsigned int errcap)
  2553. {
  2554. unsigned char *buf;
  2555. unsigned int len;
  2556. int local, truncated = 0;
  2557. char ctype[64], final[BR_URL_MAX];
  2558. int rv;
  2559. *out = 0;
  2560. *outlen = 0;
  2561. if (url[0] != '/' && script_cache_get(url, out, outlen))
  2562. return 0;
  2563. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  2564. sizeof(ctype), final, sizeof(final), err, errcap,
  2565. &truncated, 0, 0);
  2566. if (rv != 0)
  2567. return rv;
  2568. if (truncated || len >= BR_SCRIPT_MAX) {
  2569. free(buf);
  2570. s_copy(err, "script is too large", errcap);
  2571. return -1;
  2572. }
  2573. buf[len] = '\0';
  2574. if (!local)
  2575. script_cache_put(url, buf, len);
  2576. *out = buf;
  2577. *outlen = len;
  2578. return 0;
  2579. }
  2580. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  2581. * the heap, so images must not allocate their file body from it as well. */
  2582. static int fetch_image(const char *url, unsigned int cap,
  2583. unsigned char **out, unsigned int *outlen,
  2584. char *err, unsigned int errcap)
  2585. {
  2586. unsigned int len;
  2587. int tr = 0;
  2588. int rv;
  2589. *out = 0;
  2590. *outlen = 0;
  2591. if (cap > BR_IMG_FILE_MAX)
  2592. cap = BR_IMG_FILE_MAX;
  2593. if (url[0] == '/') {
  2594. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  2595. (int)cap);
  2596. if (rv < 0) {
  2597. s_copy(err, "file not found", errcap);
  2598. return -1;
  2599. }
  2600. *out = image_file_buf;
  2601. *outlen = (unsigned int)rv;
  2602. return 0;
  2603. }
  2604. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  2605. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  2606. if (rv == FETCH_ABORT)
  2607. return FETCH_ABORT;
  2608. if (rv < 0)
  2609. return -1;
  2610. len = (unsigned int)rv;
  2611. if (len == 0) {
  2612. s_copy(err, "empty image", errcap);
  2613. return -1;
  2614. }
  2615. *out = image_file_buf;
  2616. *outlen = len;
  2617. return 0;
  2618. }
  2619. /* Remote stylesheets are immutable enough for the current boot: keep
  2620. * successful responses under /share so a reload, a second visit or a fresh
  2621. * browser launch does not fetch the same five sheets over the network again.
  2622. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  2623. static int css_cache_count;
  2624. static unsigned int css_cache_hash(const char *s)
  2625. {
  2626. unsigned int h = 2166136261u;
  2627. while (*s) {
  2628. h ^= (unsigned char)*s++;
  2629. h *= 16777619u;
  2630. }
  2631. return h;
  2632. }
  2633. static void css_cache_path(const char *url, char *out, unsigned int cap)
  2634. {
  2635. unsigned int n = 0;
  2636. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  2637. s_append_dec(out, &n, css_cache_hash(url), cap);
  2638. }
  2639. static void css_cache_clear(void)
  2640. {
  2641. struct sys_dirent d;
  2642. char path[96];
  2643. for (;;) {
  2644. int i, found = 0;
  2645. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2646. (int)&d) == 1; i++) {
  2647. unsigned int n = 0;
  2648. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  2649. continue;
  2650. s_append(path, &n, "/share/", sizeof(path));
  2651. s_append(path, &n, d.name, sizeof(path));
  2652. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  2653. return;
  2654. found = 1;
  2655. break;
  2656. }
  2657. if (!found)
  2658. break;
  2659. }
  2660. css_cache_count = 0;
  2661. }
  2662. static void css_cache_init(void)
  2663. {
  2664. struct sys_dirent d;
  2665. int i, count = 0;
  2666. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2667. (int)&d) == 1; i++)
  2668. if (starts_with(d.name, CSS_CACHE_PREFIX))
  2669. count++;
  2670. if (count >= CSS_CACHE_MAX) {
  2671. css_cache_clear();
  2672. return;
  2673. }
  2674. css_cache_count = count;
  2675. }
  2676. static int css_cache_get(const char *url, unsigned char **out,
  2677. unsigned int *outlen)
  2678. {
  2679. char path[96];
  2680. int rn;
  2681. css_cache_path(url, path, sizeof(path));
  2682. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  2683. (int)CSS_CACHE_FILE_MAX);
  2684. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  2685. return 0;
  2686. *out = image_io_buf;
  2687. *outlen = (unsigned int)rn;
  2688. return 1;
  2689. }
  2690. static void css_cache_put(const char *url, const unsigned char *data,
  2691. unsigned int len)
  2692. {
  2693. char path[96];
  2694. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  2695. len >= CSS_CACHE_FILE_MAX)
  2696. return;
  2697. css_cache_path(url, path, sizeof(path));
  2698. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  2699. (int)len) >= 0)
  2700. css_cache_count++;
  2701. }
  2702. static int css_cache_has(const char *url)
  2703. {
  2704. char path[96];
  2705. struct sys_stat st;
  2706. css_cache_path(url, path, sizeof(path));
  2707. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  2708. st.size < CSS_CACHE_FILE_MAX;
  2709. }
  2710. /* Read one stylesheet into the shared static buffer. CSS is parsed
  2711. * immediately, so it does not need the page heap; this leaves the heap for
  2712. * the 2 MB page body, the rules and the scaled image bitmaps. */
  2713. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  2714. char *err, unsigned int errcap)
  2715. {
  2716. unsigned int len;
  2717. int tr = 0;
  2718. int rv;
  2719. *out = 0;
  2720. *outlen = 0;
  2721. if (url[0] == '/') {
  2722. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  2723. (int)BR_CSS_MAX);
  2724. if (rv < 0) {
  2725. s_copy(err, "stylesheet not found", errcap);
  2726. return -1;
  2727. }
  2728. *out = image_io_buf;
  2729. *outlen = (unsigned int)rv;
  2730. return 0;
  2731. }
  2732. if (css_cache_get(url, out, outlen))
  2733. return 0;
  2734. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  2735. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  2736. &fetch_meta, &tr, err, errcap);
  2737. if (rv == FETCH_ABORT)
  2738. return FETCH_ABORT;
  2739. if (rv < 0)
  2740. return -1;
  2741. len = (unsigned int)rv;
  2742. if (len == 0) {
  2743. s_copy(err, "empty stylesheet", errcap);
  2744. return -1;
  2745. }
  2746. *out = image_io_buf;
  2747. *outlen = len;
  2748. css_cache_put(url, image_io_buf, len);
  2749. return 0;
  2750. }
  2751. static void redraw_now(void);
  2752. static char error_page[1024];
  2753. static void show_error(const char *title, const char *detail)
  2754. {
  2755. char *page = error_page;
  2756. unsigned int n = 0;
  2757. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  2758. s_append(page, &n, title, sizeof(error_page));
  2759. s_append(page, &n, "</h2><p>", sizeof(error_page));
  2760. {
  2761. const char *p = detail;
  2762. while (*p && n + 1 < sizeof(error_page)) {
  2763. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  2764. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  2765. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  2766. else page[n++] = *p;
  2767. p++;
  2768. }
  2769. }
  2770. page[n] = '\0';
  2771. s_append(page, &n, "</p><p>", sizeof(error_page));
  2772. s_append(page, &n, page_url, sizeof(error_page));
  2773. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  2774. sizeof(error_page));
  2775. br_parse(&doc, page, n);
  2776. layout_valid = 0;
  2777. preload_active = 0;
  2778. preload_pending = 0;
  2779. preload_wait = 0;
  2780. fetch_workers_cancel_busy();
  2781. s_copy(page_title, title, sizeof(page_title));
  2782. page_loading = 0;
  2783. set_status(title, 1, 0);
  2784. ngui_invalidate(&ui);
  2785. }
  2786. static int decode_direct_image(const unsigned char *data, unsigned int len,
  2787. unsigned int node)
  2788. {
  2789. if (image_count >= BR_MAX_IMAGES)
  2790. return -1;
  2791. if (decode_image_data(data, len, &images[0], 0, 0) != 0)
  2792. return -1;
  2793. doc.nodes[node].img_index = 0;
  2794. image_count = 1;
  2795. return 0;
  2796. }
  2797. static int ancestor_is(unsigned int node, unsigned int tag)
  2798. {
  2799. unsigned int p = doc.nodes[node].parent;
  2800. while (p) {
  2801. if (doc.nodes[p].tag == tag)
  2802. return 1;
  2803. p = doc.nodes[p].parent;
  2804. }
  2805. return 0;
  2806. }
  2807. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  2808. * parallel but parsed in document order, so the cascade is unchanged. */
  2809. static int load_stylesheets(void)
  2810. {
  2811. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  2812. static unsigned char remote[BR_MAX_SHEETS];
  2813. struct fetch_worker *slot[BR_MAX_SHEETS];
  2814. unsigned int i, n = 0, next = 0, k;
  2815. char err[64];
  2816. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  2817. struct br_node *nd = &doc.nodes[i];
  2818. const char *rel, *href;
  2819. char url[BR_URL_MAX];
  2820. int dup = 0;
  2821. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  2822. continue;
  2823. rel = br_rel(&doc, i);
  2824. if (!contains_ci(rel, "stylesheet"))
  2825. continue;
  2826. href = br_href(&doc, i);
  2827. if (!href[0])
  2828. continue;
  2829. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  2830. continue;
  2831. for (k = 0; k < n; k++)
  2832. if (s_eq(urls[k], url)) {
  2833. dup = 1;
  2834. break;
  2835. }
  2836. if (dup)
  2837. continue;
  2838. s_copy(urls[n], url, BR_URL_MAX);
  2839. remote[n] = url[0] != '/' && !css_cache_has(url);
  2840. n++;
  2841. }
  2842. for (i = 0; i < BR_MAX_SHEETS; i++)
  2843. slot[i] = 0;
  2844. /* Start as many remote sheets as there are free workers. */
  2845. for (; next < n; next++) {
  2846. struct fetch_worker *w;
  2847. if (!remote[next])
  2848. continue;
  2849. w = fetch_worker_alloc();
  2850. if (!w)
  2851. break;
  2852. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  2853. err, sizeof(err)) != 0) {
  2854. fetch_worker_release(w);
  2855. remote[next] = 0;
  2856. continue;
  2857. }
  2858. slot[next] = w;
  2859. }
  2860. for (i = 0; i < n; i++) {
  2861. unsigned char *data = 0;
  2862. unsigned int len = 0;
  2863. int rv;
  2864. if (!remote[i]) {
  2865. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  2866. if (rv == FETCH_ABORT) {
  2867. fetch_workers_stop_all();
  2868. return FETCH_ABORT;
  2869. }
  2870. if (rv != 0 || !len)
  2871. continue;
  2872. } else {
  2873. struct fetch_worker *w = slot[i];
  2874. int tr = 0;
  2875. if (!w) {
  2876. w = fetch_worker_alloc();
  2877. if (!w)
  2878. continue;
  2879. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  2880. 0, 0, 0, 0, err,
  2881. sizeof(err)) != 0) {
  2882. fetch_worker_release(w);
  2883. remote[i] = 0;
  2884. if (i == next)
  2885. next++;
  2886. continue;
  2887. }
  2888. slot[i] = w;
  2889. if (i == next)
  2890. next++;
  2891. }
  2892. rv = fetch_worker_wait(w, err, sizeof(err));
  2893. if (rv == FETCH_ABORT) {
  2894. fetch_workers_stop_all();
  2895. return FETCH_ABORT;
  2896. }
  2897. if (rv == 0)
  2898. rv = fetch_worker_read_body(w, image_io_buf,
  2899. BR_CSS_MAX,
  2900. image_io_buf + BR_CSS_MAX,
  2901. BR_CSS_COMP_MAX, &tr,
  2902. err, sizeof(err));
  2903. else
  2904. rv = -1;
  2905. fetch_worker_release(w);
  2906. slot[i] = 0;
  2907. /* Refill the worker window before parsing this sheet. */
  2908. for (; next < n; next++) {
  2909. struct fetch_worker *nw;
  2910. if (!remote[next])
  2911. continue;
  2912. nw = fetch_worker_alloc();
  2913. if (!nw)
  2914. break;
  2915. if (fetch_worker_submit(nw, urls[next],
  2916. BR_CSS_MAX, 0, 0, 0, 0,
  2917. err, sizeof(err)) != 0) {
  2918. fetch_worker_release(nw);
  2919. remote[next] = 0;
  2920. continue;
  2921. }
  2922. slot[next] = nw;
  2923. }
  2924. if (rv <= 0)
  2925. continue;
  2926. len = (unsigned int)rv;
  2927. data = image_io_buf;
  2928. css_cache_put(urls[i], data, len);
  2929. }
  2930. if (len) {
  2931. br_set_font_base(urls[i]);
  2932. br_parse_css_text(&doc, (const char *)data, len);
  2933. }
  2934. }
  2935. br_set_font_base(page_url);
  2936. br_parse_inline_css(&doc);
  2937. load_font_faces();
  2938. br_reset_styles(&doc);
  2939. layout_valid = 0;
  2940. return 0;
  2941. }
  2942. static void preload_begin(void)
  2943. {
  2944. preload_active = 1;
  2945. preload_pending = 0;
  2946. preload_wait = 1;
  2947. preload_max_jobs = FETCH_WORKERS;
  2948. preload_node = 0;
  2949. preload_loaded = 0;
  2950. preload_scroll = 0;
  2951. }
  2952. /* Styles are computed top-down during layout, but images inside a hidden
  2953. * menu/carousel are never visited and keep img_top == 0. Without this check
  2954. * the preloader walks the DOM in node order and spends the whole image
  2955. * budget on logos and off-canvas thumbnails the reader cannot see. */
  2956. static int node_hidden(unsigned int node)
  2957. {
  2958. unsigned int path[32], n = 0, p = node, i;
  2959. struct br_style st, parent;
  2960. while (p && n < sizeof(path) / sizeof(path[0])) {
  2961. path[n++] = p;
  2962. p = doc.nodes[p].parent;
  2963. }
  2964. parent = (struct br_style){0};
  2965. parent.font_px = 16;
  2966. parent.display = BR_DISPLAY_BLOCK;
  2967. for (i = n; i > 0; i--) {
  2968. br_style_for(&doc, path[i - 1], &parent, &st);
  2969. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  2970. st.opacity_hidden)
  2971. return 1;
  2972. parent = st;
  2973. }
  2974. return 0;
  2975. }
  2976. static struct br_style base_style(void);
  2977. static void style_for_node(unsigned int node, struct br_style *out)
  2978. {
  2979. unsigned int p = doc.nodes[node].parent;
  2980. struct br_style parent;
  2981. if (p) {
  2982. style_for_node(p, &parent);
  2983. br_style_for(&doc, node, &parent, out);
  2984. } else {
  2985. parent = base_style();
  2986. br_style_for(&doc, node, &parent, out);
  2987. }
  2988. }
  2989. /* ---- parallel image preloading ---- *
  2990. *
  2991. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  2992. * preload_step() only starts jobs and harvests completed ones; the browser
  2993. * main loop keeps drawing between calls, instead of blocking on one fetch.
  2994. */
  2995. static int preload_active_jobs(void)
  2996. {
  2997. int i, n = 0;
  2998. for (i = 0; i < FETCH_WORKERS; i++)
  2999. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  3000. n++;
  3001. return n;
  3002. }
  3003. static void preload_job_error(struct fetch_worker *w)
  3004. {
  3005. if (w->node < doc.nnode) {
  3006. if (w->bg)
  3007. doc.nodes[w->node].bg_img_index = -2;
  3008. else
  3009. doc.nodes[w->node].img_index = -2;
  3010. ngui_invalidate(&ui);
  3011. }
  3012. }
  3013. static void preload_decode(unsigned int node, int bg,
  3014. const unsigned char *data, unsigned int len)
  3015. {
  3016. if (image_count >= BR_MAX_IMAGES) {
  3017. if (bg)
  3018. doc.nodes[node].bg_img_index = -2;
  3019. else
  3020. doc.nodes[node].img_index = -2;
  3021. return;
  3022. }
  3023. if (decode_image_data(data, len, &images[image_count],
  3024. bg && node < BR_MAX_NODES &&
  3025. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  3026. bg && node < BR_MAX_NODES &&
  3027. layout_boxes[node].valid ? layout_boxes[node].h : 0) == 0) {
  3028. if (bg)
  3029. doc.nodes[node].bg_img_index = (short)image_count;
  3030. else
  3031. doc.nodes[node].img_index = (short)image_count;
  3032. image_count++;
  3033. preload_loaded++;
  3034. layout_valid = 0;
  3035. } else {
  3036. if (bg)
  3037. doc.nodes[node].bg_img_index = -2;
  3038. else
  3039. doc.nodes[node].img_index = -2;
  3040. }
  3041. ngui_invalidate(&ui);
  3042. }
  3043. /* Harvest one completed worker. Returns 1 when a job was finished. */
  3044. static int preload_finish_worker(struct fetch_worker *w)
  3045. {
  3046. char err[64];
  3047. int rv, tr = 0;
  3048. rv = fetch_worker_poll(w, err, sizeof(err));
  3049. if (rv < 0) {
  3050. preload_job_error(w);
  3051. fetch_worker_release(w);
  3052. return 1;
  3053. }
  3054. if (rv == 0)
  3055. return 0;
  3056. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  3057. image_comp_buf, BR_IMG_FILE_MAX,
  3058. &tr, err, sizeof(err));
  3059. if (rv >= 0)
  3060. preload_decode(w->node, w->bg, image_file_buf,
  3061. (unsigned int)rv);
  3062. else
  3063. preload_job_error(w);
  3064. fetch_worker_release(w);
  3065. return 1;
  3066. }
  3067. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  3068. * the number of jobs started. */
  3069. static int preload_fill_jobs(void)
  3070. {
  3071. int started = 0;
  3072. char err[64];
  3073. while (preload_active && preload_node < doc.nnode) {
  3074. unsigned int i = preload_node;
  3075. struct br_node *nd = &doc.nodes[i];
  3076. const char *src;
  3077. char url[BR_URL_MAX];
  3078. struct fetch_worker *w;
  3079. if (preload_active_jobs() >= preload_max_jobs)
  3080. break;
  3081. if (nd->type != BR_NODE_ELEM) {
  3082. preload_node++;
  3083. continue;
  3084. }
  3085. if (nd->tag != BR_TAG_IMG) {
  3086. if (nd->bg_img_index == -1) {
  3087. struct br_style bs;
  3088. style_for_node(i, &bs);
  3089. if (bs.display != BR_DISPLAY_NONE &&
  3090. !bs.vis_hidden && bs.bg_image) {
  3091. const char *bsrc =
  3092. br_bg_image_url(bs.bg_image - 1);
  3093. /* Lazy like <img>: a background box
  3094. * below the viewport (or not laid
  3095. * out yet) waits for the next scan. */
  3096. if (bsrc[0] &&
  3097. (!layout_boxes[i].valid ||
  3098. block_top[i] >
  3099. (unsigned int)(page_scroll.offset +
  3100. page_rect.h + 160))) {
  3101. preload_pending = 1;
  3102. preload_node++;
  3103. continue;
  3104. }
  3105. if (bsrc[0] &&
  3106. !contains_ci(bsrc, ".svg") &&
  3107. !starts_with(bsrc, "data:") &&
  3108. resolve_link(page_url, bsrc, url,
  3109. sizeof(url)) == 0) {
  3110. if (image_count +
  3111. preload_active_jobs() >=
  3112. BR_MAX_IMAGES) {
  3113. preload_node = doc.nnode;
  3114. break;
  3115. }
  3116. if (url[0] == '/') {
  3117. unsigned char *data = 0;
  3118. unsigned int len = 0;
  3119. preload_node = i + 1;
  3120. if (fetch_image(url,
  3121. BR_IMG_FILE_MAX,
  3122. &data, &len,
  3123. err,
  3124. sizeof(err)) == 0)
  3125. preload_decode(i, 1, data, len);
  3126. else
  3127. nd->bg_img_index = -2;
  3128. continue;
  3129. }
  3130. w = fetch_worker_alloc();
  3131. if (!w)
  3132. return started;
  3133. preload_node = i + 1;
  3134. if (fetch_worker_submit(w, url,
  3135. BR_IMG_FILE_MAX,
  3136. 0, 0, i, 1,
  3137. err,
  3138. sizeof(err)) != 0) {
  3139. nd->bg_img_index = -2;
  3140. fetch_worker_release(w);
  3141. continue;
  3142. }
  3143. w->image_job = 1;
  3144. w->deadline = u_ticks_ms() +
  3145. BR_IMG_JOB_TIMEOUT_MS;
  3146. /* in flight: rescans skip it */
  3147. nd->bg_img_index = -3;
  3148. started++;
  3149. continue;
  3150. }
  3151. }
  3152. nd->bg_img_index = -2;
  3153. }
  3154. preload_node++;
  3155. continue;
  3156. }
  3157. if (nd->img_index != -1) {
  3158. preload_node++;
  3159. continue;
  3160. }
  3161. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  3162. preload_node++;
  3163. continue;
  3164. }
  3165. src = br_src(&doc, i);
  3166. if (!src[0] || contains_ci(src, ".svg") ||
  3167. starts_with(src, "data:")) {
  3168. preload_node++;
  3169. continue;
  3170. }
  3171. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  3172. preload_node++;
  3173. continue;
  3174. }
  3175. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  3176. preload_node = doc.nnode;
  3177. break;
  3178. }
  3179. /* Do not stop at the first below-fold image: DOM order is
  3180. * not visual order, and a footer/ad image early in the DOM
  3181. * used to hide every later article image from the loader. */
  3182. if (img_top[i] >
  3183. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  3184. preload_pending = 1;
  3185. preload_node++;
  3186. continue;
  3187. }
  3188. if (url[0] == '/') {
  3189. unsigned char *data = 0;
  3190. unsigned int len = 0;
  3191. preload_node = i + 1;
  3192. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  3193. err, sizeof(err)) == 0)
  3194. preload_decode(i, 0, data, len);
  3195. else
  3196. nd->img_index = -2;
  3197. continue;
  3198. }
  3199. w = fetch_worker_alloc();
  3200. if (!w)
  3201. return started;
  3202. preload_node = i + 1;
  3203. {
  3204. char msg[64];
  3205. unsigned int n = 0;
  3206. s_append(msg, &n, "Loading images ", sizeof(msg));
  3207. s_append_dec(msg, &n,
  3208. (unsigned int)preload_loaded + 1,
  3209. sizeof(msg));
  3210. s_append(msg, &n, "...", sizeof(msg));
  3211. set_status(msg, 0, 0);
  3212. }
  3213. if (fetch_worker_submit(w, url, BR_IMG_FILE_MAX, 0, 0, i, 0,
  3214. err, sizeof(err)) != 0) {
  3215. nd->img_index = -2;
  3216. fetch_worker_release(w);
  3217. continue;
  3218. }
  3219. w->image_job = 1;
  3220. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  3221. nd->img_index = -3; /* in flight: rescans skip it */
  3222. started++;
  3223. }
  3224. return started;
  3225. }
  3226. static void preload_step(void)
  3227. {
  3228. int i;
  3229. if (!preload_active)
  3230. return;
  3231. if (cancel_fetch || pending_action) {
  3232. preload_active = 0;
  3233. preload_pending = 0;
  3234. fetch_workers_cancel_busy();
  3235. return;
  3236. }
  3237. preload_fill_jobs();
  3238. /* Decode at most one completed image per main-loop pass. A full-size
  3239. * JPEG decode blocks this single-threaded UI for a long time, and
  3240. * harvesting a batch back-to-back starved the TCP pump (and therefore
  3241. * every other image download) on slow CPUs: requests looked stuck
  3242. * while four decodes ran in a row. */
  3243. for (i = 0; i < FETCH_WORKERS; i++) {
  3244. if (!fetch_workers[i].busy)
  3245. continue;
  3246. if (preload_finish_worker(&fetch_workers[i]))
  3247. return;
  3248. }
  3249. if (preload_active && preload_node >= doc.nnode &&
  3250. preload_active_jobs() == 0) {
  3251. preload_active = 0;
  3252. if (preload_pending)
  3253. preload_scroll = page_scroll.offset;
  3254. else
  3255. preload_pending = 0;
  3256. /* Keep the now idle helpers and their connections; a later
  3257. * navigation reuses them. They exit after ten idle seconds,
  3258. * and losing window focus stops them at once. */
  3259. set_status(post_status_text, post_status_error, post_status_ttl);
  3260. ngui_invalidate(&ui);
  3261. }
  3262. }
  3263. /* Set by navigate() when it turned a typed bare host into https://; the next
  3264. * load_page() consumes it and may retry over http. */
  3265. static int nav_https_upgraded;
  3266. /* Errors that mean "https is not served here" rather than "the site is
  3267. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  3268. static int https_fallback_error(int e)
  3269. {
  3270. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  3271. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  3272. e == UHTTP_ERR_RESET;
  3273. }
  3274. static void history_push(const char *url)
  3275. {
  3276. if (!url || !url[0])
  3277. return;
  3278. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  3279. s_eq(history[hist_pos], url))
  3280. return;
  3281. if (hist_len > 0 && hist_pos + 1 < hist_len)
  3282. hist_len = hist_pos + 1;
  3283. if (hist_len < BR_HISTORY) {
  3284. s_copy(history[hist_len], url, BR_URL_MAX);
  3285. hist_pos = hist_len;
  3286. hist_len++;
  3287. } else {
  3288. int i;
  3289. for (i = 1; i < BR_HISTORY; i++)
  3290. s_copy(history[i - 1], history[i], BR_URL_MAX);
  3291. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  3292. hist_pos = BR_HISTORY - 1;
  3293. }
  3294. }
  3295. static void load_page(const char *url, int local, int push)
  3296. {
  3297. unsigned char *body = 0;
  3298. unsigned int len = 0;
  3299. int truncated = 0;
  3300. struct img_info image_info;
  3301. char ctype[64];
  3302. char final[BR_URL_MAX];
  3303. char err[80];
  3304. const char *detail = 0;
  3305. const char *post = pending_post_len ? pending_post : 0;
  3306. unsigned int post_len = pending_post_len;
  3307. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  3308. /* Phase timings for the status line: where a slow load spends it. */
  3309. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  3310. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  3311. int upgraded = nav_https_upgraded;
  3312. int retried = 0;
  3313. int rv;
  3314. nav_https_upgraded = 0;
  3315. final[0] = '\0';
  3316. pending_post_len = 0;
  3317. cancel_fetch = 0;
  3318. preload_active = 0;
  3319. preload_pending = 0;
  3320. fetch_workers_prepare_nav(url);
  3321. js_browser_stop();
  3322. js_last_status[0] = '\0';
  3323. js_last_error = 0;
  3324. heap_clear();
  3325. image_reset();
  3326. form_reset_state();
  3327. layout_valid = 0;
  3328. page_scroll.offset = 0;
  3329. page_scroll.dragging = 0;
  3330. page_title[0] = '\0';
  3331. page_loading = 1;
  3332. page_is_local = local;
  3333. s_copy(page_url, url, sizeof(page_url));
  3334. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3335. url_in.len = s_len(url_in.text);
  3336. url_in.cursor = url_in.len;
  3337. url_in.scroll = 0;
  3338. ngui_set_focus(&ui, 0);
  3339. if (final[0])
  3340. final[0] = '\0';
  3341. if (push)
  3342. history_push(url);
  3343. set_status("Loading...", 0, 0);
  3344. ngui_invalidate(&ui);
  3345. /* heap_clear() detaches the fonts, so attach them again before the
  3346. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  3347. if (heap_start() != 0) {
  3348. show_error("Out of memory", "Cannot allocate the page buffer");
  3349. return;
  3350. }
  3351. br_parse_plain(&doc, "", 0); /* blank while loading */
  3352. ngui_font_attach(&ui);
  3353. redraw_now();
  3354. browser_rules_alloc();
  3355. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  3356. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  3357. &truncated, post, post_len);
  3358. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  3359. fetch_last_error == UHTTP_ERR_DNS) {
  3360. /* A busy previous page can leave the receiver ring full just
  3361. * long enough to lose a DNS reply. Tear the old helpers down
  3362. * and try once more before giving up. */
  3363. retried = 1;
  3364. fetch_workers_stop_all();
  3365. u_sleep_ms(500);
  3366. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  3367. sizeof(ctype), final, sizeof(final), err,
  3368. sizeof(err), &truncated, post, post_len);
  3369. }
  3370. if (rv == FETCH_ABORT)
  3371. return;
  3372. t_fetch = u_ticks_ms() - t_start;
  3373. /* Capture the page timing before CSS/script/image fetches overwrite the
  3374. * shared fetch_meta block. */
  3375. if (rv == 0 && !local) {
  3376. page_open_ms = fetch_meta.open_ms;
  3377. page_first_ms = fetch_meta.first_ms;
  3378. page_total_ms = fetch_meta.total_ms;
  3379. }
  3380. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  3381. https_fallback_error(fetch_last_error)) {
  3382. char http_url[BR_URL_MAX];
  3383. unsigned int n = 0;
  3384. s_append(http_url, &n, "http://", sizeof(http_url));
  3385. s_append(http_url, &n, url + 8, sizeof(http_url));
  3386. /* Replace the https entry instead of adding a second one. */
  3387. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  3388. s_eq(history[hist_pos], url))
  3389. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  3390. load_page(http_url, 0, 0);
  3391. return;
  3392. }
  3393. if (rv != 0) {
  3394. detail = err;
  3395. show_error("Cannot load this page", detail);
  3396. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3397. url_in.len = s_len(url_in.text);
  3398. url_in.cursor = url_in.len;
  3399. url_in.scroll = 0;
  3400. return;
  3401. }
  3402. if (!local)
  3403. origin_cache_learn(url, final[0] ? final : url);
  3404. page_is_local = local;
  3405. if (final[0]) {
  3406. s_copy(page_url, final, sizeof(page_url));
  3407. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3408. url_in.len = s_len(url_in.text);
  3409. url_in.cursor = url_in.len;
  3410. url_in.scroll = 0;
  3411. }
  3412. if (contains_ci(ctype, "text/plain")) {
  3413. br_parse_plain(&doc, (const char *)body, len);
  3414. } else if (contains_ci(ctype, "image/") ||
  3415. (!contains_ci(ctype, "text/html") &&
  3416. img_sniff(body, len, &image_info) == 0)) {
  3417. unsigned int node = br_parse_image_doc(&doc, page_url);
  3418. if (node)
  3419. decode_direct_image(body, len, node);
  3420. s_copy(page_title, "Image", sizeof(page_title));
  3421. } else {
  3422. br_set_viewport(ui.w);
  3423. t_mark = u_ticks_ms();
  3424. br_parse(&doc, (const char *)body, len);
  3425. t_parse = u_ticks_ms() - t_mark;
  3426. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  3427. sizeof(page_title));
  3428. t_mark = u_ticks_ms();
  3429. if (load_stylesheets() == FETCH_ABORT)
  3430. return;
  3431. t_css = u_ticks_ms() - t_mark;
  3432. if (pending_action)
  3433. return;
  3434. }
  3435. preload_begin();
  3436. page_loading = 0;
  3437. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3438. url_in.len = s_len(url_in.text);
  3439. url_in.cursor = url_in.len;
  3440. url_in.scroll = 0;
  3441. ngui_set_focus(&ui, 0);
  3442. /* Paint the parsed page before fetching/running scripts. A slow
  3443. * remote <script src> then does not hide the page behind the loading
  3444. * screen; the fetch helper pumps this UI while it waits. */
  3445. set_status("Loading scripts...", 0, 0);
  3446. t_mark = u_ticks_ms();
  3447. redraw_now();
  3448. t_paint = u_ticks_ms() - t_mark;
  3449. /* Start one image download before the scripts. The other workers
  3450. * fetch the external script bodies in parallel, and the remaining
  3451. * images start as soon as the script phase ends. */
  3452. preload_max_jobs = 1;
  3453. preload_fill_jobs();
  3454. preload_wait = 0;
  3455. t_mark = u_ticks_ms();
  3456. run_page_scripts();
  3457. t_js = u_ticks_ms() - t_mark;
  3458. preload_max_jobs = FETCH_WORKERS;
  3459. if (pending_action)
  3460. return;
  3461. post_status_text[0] = '\0';
  3462. post_status_error = 0;
  3463. post_status_ttl = 0;
  3464. if (js_last_status[0]) {
  3465. s_copy(post_status_text, js_last_status,
  3466. sizeof(post_status_text));
  3467. post_status_error = js_last_error;
  3468. post_status_ttl = 8000;
  3469. } else if (truncated) {
  3470. s_copy(post_status_text, "Page truncated at the buffer limit",
  3471. sizeof(post_status_text));
  3472. post_status_ttl = 6000;
  3473. } else if (doc.truncated) {
  3474. s_copy(post_status_text, "Page truncated by the parser",
  3475. sizeof(post_status_text));
  3476. post_status_ttl = 6000;
  3477. } else if (page_total_ms) {
  3478. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  3479. * paint 220, js 1750" -- the phases of this load. */
  3480. unsigned int n = 0;
  3481. static const char *const names[] = {
  3482. ", parse ", ", css ", ", paint ", ", js "
  3483. };
  3484. unsigned int vals[4];
  3485. int k;
  3486. vals[0] = t_parse;
  3487. vals[1] = t_css;
  3488. vals[2] = t_paint;
  3489. vals[3] = t_js;
  3490. (void)page_first_ms;
  3491. if (starts_with(page_url, "https://"))
  3492. s_append(post_status_text, &n,
  3493. "HTTPS (not verified), ",
  3494. sizeof(post_status_text));
  3495. s_append(post_status_text, &n, "Loaded in ",
  3496. sizeof(post_status_text));
  3497. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  3498. sizeof(post_status_text));
  3499. s_append(post_status_text, &n, " ms: page ",
  3500. sizeof(post_status_text));
  3501. s_append_dec(post_status_text, &n, t_fetch,
  3502. sizeof(post_status_text));
  3503. s_append(post_status_text, &n, " (headers ",
  3504. sizeof(post_status_text));
  3505. s_append_dec(post_status_text, &n, page_open_ms,
  3506. sizeof(post_status_text));
  3507. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  3508. for (k = 0; k < 4; k++) {
  3509. s_append(post_status_text, &n, names[k],
  3510. sizeof(post_status_text));
  3511. s_append_dec(post_status_text, &n, vals[k],
  3512. sizeof(post_status_text));
  3513. }
  3514. post_status_ttl = 12000;
  3515. } else if (starts_with(page_url, "https://")) {
  3516. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  3517. sizeof(post_status_text));
  3518. post_status_ttl = 6000;
  3519. }
  3520. set_status(post_status_text, post_status_error, post_status_ttl);
  3521. ngui_invalidate(&ui);
  3522. }
  3523. static void load_home(int push)
  3524. {
  3525. pending_post_len = 0;
  3526. cancel_fetch = 0;
  3527. preload_active = 0;
  3528. preload_pending = 0;
  3529. js_browser_stop();
  3530. js_last_status[0] = '\0';
  3531. js_last_error = 0;
  3532. heap_clear();
  3533. image_reset();
  3534. form_reset_state();
  3535. layout_valid = 0;
  3536. page_scroll.offset = 0;
  3537. page_scroll.dragging = 0;
  3538. page_loading = 1;
  3539. page_is_local = 0;
  3540. s_copy(page_url, "about:home", sizeof(page_url));
  3541. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3542. url_in.len = s_len(url_in.text);
  3543. url_in.cursor = url_in.len;
  3544. url_in.scroll = 0;
  3545. ngui_set_focus(&ui, 0);
  3546. if (push)
  3547. history_push(page_url);
  3548. ngui_invalidate(&ui);
  3549. /* See load_page(): reattach the fonts before the first redraw. */
  3550. if (heap_start() != 0) {
  3551. show_error("Out of memory", "Cannot allocate the browser heap");
  3552. return;
  3553. }
  3554. br_parse_plain(&doc, "", 0);
  3555. ngui_font_attach(&ui);
  3556. redraw_now();
  3557. browser_rules_alloc();
  3558. {
  3559. static const char home[] =
  3560. "<html><head><title>NebOS Browser</title><style>"
  3561. "body { margin: 10px; color: #e4e6f0; }"
  3562. "h1 { color: #7fb0ff; }"
  3563. ".box { background-color: #262b3a; margin: 12px; "
  3564. "padding: 10px; }"
  3565. "a { color: #7fb0ff; }"
  3566. "pre { background-color: #32384a; }"
  3567. "</style></head><body>"
  3568. "<h1>NebOS Browser</h1>"
  3569. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  3570. "shared HTTP client and the image library.</p>"
  3571. "<div class=\"box\"><b>Try:</b>"
  3572. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  3573. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  3574. "<li><a href=\"/floppy1/JS.HTM\">/"
  3575. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  3576. "<li><a href=\"http://10.0.2.2:8000/\">"
  3577. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  3578. "<li><a href=\"https://example.com/\">"
  3579. "https://example.com/</a> (TLS, not verified)</li>"
  3580. "</ul></div>"
  3581. "<p>Type a URL in the bar above. Esc closes the "
  3582. "window, Ctrl+L focuses the address bar.</p>"
  3583. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  3584. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  3585. "</body></html>";
  3586. br_set_viewport(ui.w);
  3587. br_parse(&doc, home, sizeof(home) - 1);
  3588. br_parse_inline_css(&doc);
  3589. br_reset_styles(&doc);
  3590. s_copy(page_title, doc.title, sizeof(page_title));
  3591. }
  3592. post_status_text[0] = '\0';
  3593. post_status_error = 0;
  3594. post_status_ttl = 0;
  3595. page_loading = 0;
  3596. set_status("", 0, 0);
  3597. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3598. url_in.len = s_len(url_in.text);
  3599. url_in.cursor = url_in.len;
  3600. url_in.scroll = 0;
  3601. ngui_set_focus(&ui, 0);
  3602. ngui_invalidate(&ui);
  3603. }
  3604. /* Extensions the browser opens from the local filesystem. A dotted input
  3605. * with one of these still resolves relative to the cwd. */
  3606. static int local_file_ext(const char *s)
  3607. {
  3608. static const char *const exts[] = {
  3609. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  3610. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  3611. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  3612. "cfg", "conf", 0
  3613. };
  3614. unsigned int i = 0, start = 0, len = 0, e;
  3615. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  3616. s[i] != '#') {
  3617. if (s[i] == '.') {
  3618. start = i + 1;
  3619. len = 0;
  3620. } else if (start) {
  3621. len++;
  3622. }
  3623. i++;
  3624. }
  3625. if (!len)
  3626. return 0;
  3627. for (e = 0; exts[e]; e++) {
  3628. const char *x = exts[e];
  3629. unsigned int xn = s_len(x), k;
  3630. if (xn != len)
  3631. continue;
  3632. for (k = 0; k < len; k++) {
  3633. char a = s[start + k];
  3634. if (a >= 'A' && a <= 'Z')
  3635. a = (char)(a - 'A' + 'a');
  3636. if (a != x[k])
  3637. break;
  3638. }
  3639. if (k == len)
  3640. return 1;
  3641. }
  3642. return 0;
  3643. }
  3644. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  3645. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  3646. * Enter to the first network request. */
  3647. static int looks_like_host(const char *s)
  3648. {
  3649. unsigned int i = 0;
  3650. int dot = 0;
  3651. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  3652. s[i] != ':') {
  3653. char c = s[i];
  3654. if (c == '.') {
  3655. dot = 1;
  3656. } else if (!((c >= 'a' && c <= 'z') ||
  3657. (c >= 'A' && c <= 'Z') ||
  3658. (c >= '0' && c <= '9') ||
  3659. c == '-' || c == '_')) {
  3660. return 0;
  3661. }
  3662. i++;
  3663. }
  3664. return dot && i > 0 && !local_file_ext(s);
  3665. }
  3666. static void load_remote(const char *url, int push)
  3667. {
  3668. char canon[BR_URL_MAX];
  3669. s_copy(canon, url, sizeof(canon));
  3670. origin_cache_apply(canon, sizeof(canon));
  3671. load_page(canon, 0, push);
  3672. }
  3673. static void navigate(const char *input, int push)
  3674. {
  3675. char target[BR_URL_MAX];
  3676. char *t;
  3677. if (!input)
  3678. return;
  3679. s_copy(target, input, sizeof(target));
  3680. t = trim(target);
  3681. if (!t[0])
  3682. return;
  3683. if (s_eq(t, "about:home")) {
  3684. load_home(push);
  3685. return;
  3686. }
  3687. if (starts_with(t, "file://")) {
  3688. make_abs_local(t + 7, target, sizeof(target));
  3689. load_page(target, 1, push);
  3690. return;
  3691. }
  3692. if (is_http(t)) {
  3693. load_remote(t, push);
  3694. return;
  3695. }
  3696. if (t[0] == '/') {
  3697. make_abs_local(t, target, sizeof(target));
  3698. load_page(target, 1, push);
  3699. return;
  3700. }
  3701. if (!looks_like_host(t)) {
  3702. struct sys_stat st;
  3703. if (u_stat(t, &st) == 0 && !st.is_dir) {
  3704. make_abs_local(t, target, sizeof(target));
  3705. load_page(target, 1, push);
  3706. return;
  3707. }
  3708. }
  3709. {
  3710. /* A typed bare host tries https first: nearly every site
  3711. * redirects http -> https anyway, and that hop costs a whole
  3712. * extra connection. load_page() falls back to http when the
  3713. * https connection itself fails. */
  3714. char with_scheme[BR_URL_MAX];
  3715. unsigned int n = 0;
  3716. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  3717. s_append(with_scheme, &n, t, sizeof(with_scheme));
  3718. nav_https_upgraded = 1;
  3719. load_remote(with_scheme, push);
  3720. }
  3721. }
  3722. /* ---- layout ---- */
  3723. static struct ufont_face *style_face(const struct br_style *st)
  3724. {
  3725. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  3726. return font_faces[st->font_face - 1];
  3727. return 0;
  3728. }
  3729. static struct ufont_face *run_face(const struct lay_run *r)
  3730. {
  3731. if (r->font_face && r->font_face <= BR_MAX_FACES)
  3732. return font_faces[r->font_face - 1];
  3733. return 0;
  3734. }
  3735. static unsigned int face_text_width(struct ngui *gui,
  3736. const struct br_style *st,
  3737. const char *s, unsigned int n)
  3738. {
  3739. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  3740. st->bold, st->italic, st->mono);
  3741. }
  3742. static int face_line_height(struct ngui *gui, const struct br_style *st)
  3743. {
  3744. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  3745. st->mono);
  3746. }
  3747. static unsigned int run_text_width(struct ngui *gui,
  3748. const struct lay_run *r,
  3749. const char *s, unsigned int n)
  3750. {
  3751. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  3752. r->bold, r->italic, r->mono);
  3753. }
  3754. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  3755. {
  3756. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  3757. r->mono);
  3758. }
  3759. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  3760. {
  3761. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  3762. }
  3763. static struct br_style base_style(void)
  3764. {
  3765. struct br_style s = { 0 };
  3766. s.color = ui.theme.text;
  3767. s.bg = ui.theme.bg;
  3768. s.has_bg = 0;
  3769. for (int i = 0; i < 4; i++) {
  3770. s.border_c[i] = 0;
  3771. s.border_w[i] = 0;
  3772. s.border_s[i] = BR_BORDER_SOLID;
  3773. }
  3774. s.font_px = 16;
  3775. s.bold = 0;
  3776. s.italic = 0;
  3777. s.mono = 0;
  3778. s.underline = 0;
  3779. s.strike = 0;
  3780. s.overline = 0;
  3781. s.align = BR_ALIGN_LEFT;
  3782. s.display = BR_DISPLAY_BLOCK;
  3783. s.no_bullet = 0;
  3784. s.list_style = BR_LIST_AUTO;
  3785. s.uppercase = 0;
  3786. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  3787. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  3788. s.width = s.max_width = s.min_width = 0;
  3789. s.height = s.min_height = s.max_height = 0;
  3790. s.box_sizing = 0;
  3791. s.ml_auto = s.mr_auto = 0;
  3792. s.line_h_pct = 0;
  3793. s.line_h_px = 0;
  3794. s.mt = s.mb = s.ml = s.mr = 0;
  3795. s.pt = s.pb = s.pl = s.pr = 0;
  3796. return s;
  3797. }
  3798. /* Resolve a margin/padding raw value. Percentages use the containing
  3799. * block width for all four sides, as CSS specifies. */
  3800. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  3801. {
  3802. if (unit == 1)
  3803. return base * v / 10000;
  3804. if (unit == 2)
  3805. return st->font_px * v / 100;
  3806. if (unit == 3)
  3807. return (int)br_root_font_px() * v / 100;
  3808. if (unit == 4)
  3809. return 0;
  3810. return v;
  3811. }
  3812. static int mp_px(const struct br_style *st, int side, int base)
  3813. {
  3814. int raw;
  3815. switch (side) {
  3816. case 0: raw = st->mt; break;
  3817. case 1: raw = st->mr; break;
  3818. case 2: raw = st->mb; break;
  3819. case 3: raw = st->ml; break;
  3820. case 4: raw = st->pt; break;
  3821. case 5: raw = st->pr; break;
  3822. case 6: raw = st->pb; break;
  3823. default: raw = st->pl; break;
  3824. }
  3825. if (st->mp_unit[side] == 5)
  3826. return base * raw / 100 + st->mp_calc_px[side];
  3827. return css_mp_px(st, raw, st->mp_unit[side], base);
  3828. }
  3829. static int style_width_px(const struct br_style *st, int base)
  3830. {
  3831. if (st->width_kind == 1)
  3832. return st->width;
  3833. if (st->width_kind == 2)
  3834. return base * (int)st->width / 100;
  3835. if (st->width_kind == 3)
  3836. return base * st->width_calc_pct / 100 + st->width_calc_px;
  3837. return 0;
  3838. }
  3839. static int style_height_px(const struct br_style *st, int base)
  3840. {
  3841. if (st->height_kind == 1)
  3842. return st->height;
  3843. if (st->height_kind == 2)
  3844. return base * (int)st->height / 100;
  3845. if (st->height_kind == 3)
  3846. return base * st->height_calc_pct / 100 + st->height_calc_px;
  3847. return 0;
  3848. }
  3849. static int css_size(unsigned char kind, int val, int base)
  3850. {
  3851. if (kind == 1)
  3852. return val;
  3853. if (kind == 2)
  3854. return base * val / 100;
  3855. return -1;
  3856. }
  3857. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  3858. int thick, int horizontal, unsigned short color,
  3859. unsigned char style)
  3860. {
  3861. int pos;
  3862. if (len <= 0 || thick <= 0)
  3863. return;
  3864. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  3865. if (horizontal)
  3866. ngui_fill_rect(ui, (struct ngui_rect){
  3867. x, y, len, thick}, color);
  3868. else
  3869. ngui_fill_rect(ui, (struct ngui_rect){
  3870. x, y, thick, len}, color);
  3871. return;
  3872. }
  3873. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  3874. int seg = len - pos;
  3875. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  3876. seg = style == BR_BORDER_DASHED ? 4 : 2;
  3877. if (horizontal)
  3878. ngui_fill_rect(ui, (struct ngui_rect){
  3879. x + pos, y, seg, thick}, color);
  3880. else
  3881. ngui_fill_rect(ui, (struct ngui_rect){
  3882. x, y + pos, thick, seg}, color);
  3883. }
  3884. }
  3885. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  3886. const struct br_style *st)
  3887. {
  3888. int top = st->border_w[0], right = st->border_w[1];
  3889. int bottom = st->border_w[2], left = st->border_w[3];
  3890. if (r.w <= 0 || r.h <= 0)
  3891. return;
  3892. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  3893. int i;
  3894. for (i = 0; i < 4; i++)
  3895. if (st->border_w[i] && !st->border_t[i]) {
  3896. ngui_fill_rect(ui, r, st->border_c[i]);
  3897. break;
  3898. }
  3899. return;
  3900. }
  3901. if (top && !st->border_t[0])
  3902. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  3903. st->border_c[0], st->border_s[0]);
  3904. if (bottom && !st->border_t[2])
  3905. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  3906. st->border_c[2], st->border_s[2]);
  3907. if (left && !st->border_t[3])
  3908. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  3909. left, 0, st->border_c[3], st->border_s[3]);
  3910. if (right && !st->border_t[1])
  3911. draw_border_side(ui, r.x + r.w - right, r.y + top,
  3912. r.h - top - bottom, right, 0,
  3913. st->border_c[1], st->border_s[1]);
  3914. }
  3915. static void transform_origin(const struct br_style *st, int w, int h,
  3916. int *ox, int *oy)
  3917. {
  3918. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  3919. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  3920. }
  3921. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  3922. unsigned int a)
  3923. {
  3924. unsigned int dr, dg, db, sr, sg, sb;
  3925. if (a >= 255)
  3926. return s;
  3927. dr = (d >> 11) & 31;
  3928. dg = (d >> 5) & 63;
  3929. db = d & 31;
  3930. sr = (s >> 11) & 31;
  3931. sg = (s >> 5) & 63;
  3932. sb = s & 31;
  3933. dr = (dr * (255 - a) + sr * a) / 255;
  3934. dg = (dg * (255 - a) + sg * a) / 255;
  3935. db = (db * (255 - a) + sb * a) / 255;
  3936. return (unsigned short)((dr << 11) | (dg << 5) | db);
  3937. }
  3938. /* Paint a solid box through scale()/rotate() around transform-origin. This
  3939. * transforms the element's own background box; text and descendants keep
  3940. * their layout (documented approximation). */
  3941. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  3942. unsigned short color,
  3943. const struct br_style *st)
  3944. {
  3945. double sx = st->scale_x / 100.0;
  3946. double sy = st->scale_y / 100.0;
  3947. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  3948. double c = cos(th), sn = sin(th);
  3949. int ox, oy, minx, miny, maxx, maxy, x, y;
  3950. double ax, ay;
  3951. double px[4], py[4];
  3952. int cx1, cy1, cx2, cy2, i;
  3953. if (sx == 0)
  3954. sx = 0.01;
  3955. if (sy == 0)
  3956. sy = 0.01;
  3957. transform_origin(st, box.w, box.h, &ox, &oy);
  3958. ax = box.x + ox;
  3959. ay = box.y + oy;
  3960. px[0] = -ox; py[0] = -oy;
  3961. px[1] = box.w - ox; py[1] = -oy;
  3962. px[2] = box.w - ox; py[2] = box.h - oy;
  3963. px[3] = -ox; py[3] = box.h - oy;
  3964. minx = miny = 1000000;
  3965. maxx = maxy = -1000000;
  3966. for (i = 0; i < 4; i++) {
  3967. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  3968. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  3969. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  3970. if (dx < minx) minx = dx;
  3971. if (dx > maxx) maxx = dx;
  3972. if (dy < miny) miny = dy;
  3973. if (dy > maxy) maxy = dy;
  3974. }
  3975. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  3976. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  3977. cx2 = page_rect.x + page_rect.w - 12;
  3978. cy2 = page_rect.y + page_rect.h;
  3979. if (cx2 > gui->w) cx2 = gui->w;
  3980. if (cy2 > gui->h) cy2 = gui->h;
  3981. if (minx < cx1) minx = cx1;
  3982. if (miny < cy1) miny = cy1;
  3983. if (maxx > cx2 - 1) maxx = cx2 - 1;
  3984. if (maxy > cy2 - 1) maxy = cy2 - 1;
  3985. for (y = miny; y <= maxy; y++) {
  3986. for (x = minx; x <= maxx; x++) {
  3987. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  3988. double rx = dx * c + dy * sn;
  3989. double ry = -dx * sn + dy * c;
  3990. double bx = rx / sx + ox;
  3991. double by = ry / sy + oy;
  3992. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  3993. gui->px[y * gui->w + x] = color;
  3994. }
  3995. }
  3996. }
  3997. static void draw_image_transformed(struct ngui *gui,
  3998. const struct img_image *im,
  3999. int x, int y, int w, int h,
  4000. int sx100, int sy100, int rot100,
  4001. int origin_x, int origin_y,
  4002. int origin_x_kind, int origin_y_kind)
  4003. {
  4004. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  4005. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  4006. double c = cos(th), sn = sin(th);
  4007. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  4008. double ax, ay;
  4009. double bx[4], by[4];
  4010. int cx1, cy1, cx2, cy2;
  4011. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  4012. return;
  4013. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  4014. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  4015. ax = x + ox;
  4016. ay = y + oy;
  4017. bx[0] = -ox; by[0] = -oy;
  4018. bx[1] = w - ox; by[1] = -oy;
  4019. bx[2] = w - ox; by[2] = h - oy;
  4020. bx[3] = -ox; by[3] = h - oy;
  4021. minx = miny = 1000000;
  4022. maxx = maxy = -1000000;
  4023. for (i = 0; i < 4; i++) {
  4024. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  4025. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  4026. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  4027. if (dx < minx) minx = dx;
  4028. if (dx > maxx) maxx = dx;
  4029. if (dy < miny) miny = dy;
  4030. if (dy > maxy) maxy = dy;
  4031. }
  4032. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  4033. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  4034. cx2 = page_rect.x + page_rect.w - 12;
  4035. cy2 = page_rect.y + page_rect.h;
  4036. if (cx2 > gui->w) cx2 = gui->w;
  4037. if (cy2 > gui->h) cy2 = gui->h;
  4038. if (minx < cx1) minx = cx1;
  4039. if (miny < cy1) miny = cy1;
  4040. if (maxx > cx2 - 1) maxx = cx2 - 1;
  4041. if (maxy > cy2 - 1) maxy = cy2 - 1;
  4042. for (py = miny; py <= maxy; py++) {
  4043. for (px = minx; px <= maxx; px++) {
  4044. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  4045. double rx = dx * c + dy * sn;
  4046. double ry = -dx * sn + dy * c;
  4047. double fx = rx / sx + ox;
  4048. double fy = ry / sy + oy;
  4049. int ix, iy;
  4050. unsigned int si, a;
  4051. unsigned short src;
  4052. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  4053. continue;
  4054. ix = (int)(fx * (double)im->w / w);
  4055. iy = (int)(fy * (double)im->h / h);
  4056. if (ix < 0 || ix >= (int)im->w ||
  4057. iy < 0 || iy >= (int)im->h)
  4058. continue;
  4059. si = (unsigned int)iy * im->w + (unsigned int)ix;
  4060. src = im->px[si];
  4061. a = im->alpha ? im->alpha[si] : 255;
  4062. gui->px[py * gui->w + px] =
  4063. a >= 255 ? src :
  4064. blend_rgb565(gui->px[py * gui->w + px],
  4065. src, a);
  4066. }
  4067. }
  4068. }
  4069. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  4070. unsigned int node, const struct br_style *st);
  4071. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  4072. * first and every pixel outside a corner's arc is restored afterwards. */
  4073. #define BG_ROUND_MAX 64
  4074. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  4075. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  4076. unsigned int node, const struct br_style *st,
  4077. int rtl, int rtr, int rbr, int rbl)
  4078. {
  4079. struct ngui *ui = l->ui;
  4080. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  4081. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  4082. if (ui->nclip > 0)
  4083. clip = ui->clip[ui->nclip - 1];
  4084. for (c = 0; c < 4; c++) {
  4085. if (r[c] > BG_ROUND_MAX)
  4086. r[c] = BG_ROUND_MAX;
  4087. if (r[c] > box.w / 2)
  4088. r[c] = box.w / 2;
  4089. if (r[c] > box.h / 2)
  4090. r[c] = box.h / 2;
  4091. }
  4092. for (c = 0; c < 4; c++) {
  4093. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  4094. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  4095. for (dy = 0; dy < r[c]; dy++)
  4096. for (dx = 0; dx < r[c]; dx++) {
  4097. int px = ox + dx, py = oy + dy;
  4098. if (px >= clip.x && py >= clip.y &&
  4099. px < clip.x + clip.w && py < clip.y + clip.h)
  4100. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  4101. ui->px[py * ui->w + px];
  4102. }
  4103. }
  4104. draw_bg_image(l, box, node, st);
  4105. for (c = 0; c < 4; c++) {
  4106. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  4107. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  4108. /* arc centre, in corner-square coordinates */
  4109. int cx = (c == 1 || c == 2) ? 0 : r[c];
  4110. int cy = (c >= 2) ? 0 : r[c];
  4111. for (dy = 0; dy < r[c]; dy++)
  4112. for (dx = 0; dx < r[c]; dx++) {
  4113. int px = ox + dx, py = oy + dy;
  4114. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  4115. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  4116. continue;
  4117. if (px >= clip.x && py >= clip.y &&
  4118. px < clip.x + clip.w && py < clip.y + clip.h)
  4119. ui->px[py * ui->w + px] =
  4120. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  4121. }
  4122. }
  4123. }
  4124. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  4125. unsigned int node, const struct br_style *st)
  4126. {
  4127. struct br_image *bi;
  4128. struct img_blit b;
  4129. int tw, th, x, y, rep_x, rep_y, posx, posy;
  4130. unsigned int scale = 65536;
  4131. int legacy, tiles = 0, rows = 0;
  4132. int cx1, cy1, cx2, cy2;
  4133. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  4134. return;
  4135. if (doc.nodes[node].bg_img_index < 0 ||
  4136. doc.nodes[node].bg_img_index >= image_count)
  4137. return;
  4138. bi = &images[doc.nodes[node].bg_img_index];
  4139. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  4140. return;
  4141. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  4142. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  4143. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  4144. if (legacy) {
  4145. scale = ((unsigned int)box.w << 16) / bi->img.w;
  4146. tw = box.w;
  4147. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  4148. x = box.x;
  4149. y = box.y;
  4150. rep_x = rep_y = 0;
  4151. } else {
  4152. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  4153. unsigned int sx = ((unsigned int)box.w << 16) /
  4154. bi->img.w;
  4155. unsigned int sy = ((unsigned int)box.h << 16) /
  4156. bi->img.h;
  4157. scale = st->bg_size_kind == 3 ?
  4158. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  4159. } else if (st->bg_size_kind == 1 ||
  4160. st->bg_size_kind == 2) {
  4161. int w = st->bg_size_w;
  4162. int h = st->bg_size_h;
  4163. if (st->bg_size_kind == 2) {
  4164. if (w)
  4165. w = box.w * w / 100;
  4166. if (h)
  4167. h = box.h * h / 100;
  4168. }
  4169. if (w)
  4170. scale = ((unsigned int)w << 16) / bi->img.w;
  4171. else if (h)
  4172. scale = ((unsigned int)h << 16) / bi->img.h;
  4173. }
  4174. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  4175. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  4176. if (tw < 1)
  4177. tw = 1;
  4178. if (th < 1)
  4179. th = 1;
  4180. posx = st->bg_pos_x_kind == 1 ?
  4181. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  4182. posy = st->bg_pos_y_kind == 1 ?
  4183. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  4184. x = box.x + posx;
  4185. y = box.y + posy;
  4186. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  4187. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  4188. if (rep_x) {
  4189. int m = (x - box.x) % tw;
  4190. if (m > 0)
  4191. m -= tw;
  4192. x = box.x + m;
  4193. }
  4194. if (rep_y) {
  4195. int m = (y - box.y) % th;
  4196. if (m > 0)
  4197. m -= th;
  4198. y = box.y + m;
  4199. }
  4200. }
  4201. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  4202. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  4203. cx2 = box.x + box.w;
  4204. cy2 = box.y + box.h;
  4205. if (cx2 > page_rect.x + page_rect.w - 12)
  4206. cx2 = page_rect.x + page_rect.w - 12;
  4207. if (cy2 > page_rect.y + page_rect.h)
  4208. cy2 = page_rect.y + page_rect.h;
  4209. if (cx1 >= cx2 || cy1 >= cy2)
  4210. return;
  4211. b.dst = l->ui->px;
  4212. b.dst_w = l->ui->w;
  4213. b.dst_h = l->ui->h;
  4214. b.clip_x = cx1;
  4215. b.clip_y = cy1;
  4216. b.clip_w = cx2 - cx1;
  4217. b.clip_h = cy2 - cy1;
  4218. b.scale = scale;
  4219. b.bg = ui.theme.bg;
  4220. b.bg2 = ui.theme.bg;
  4221. b.flags = IMG_BLIT_OVER_DST;
  4222. {
  4223. int row_x = x;
  4224. for (;;) {
  4225. for (;;) {
  4226. b.x = x;
  4227. b.y = y;
  4228. img_draw(&bi->img, &b);
  4229. if (!rep_x || ++tiles > 512)
  4230. break;
  4231. x += tw;
  4232. if (x >= box.x + box.w)
  4233. break;
  4234. }
  4235. if (!rep_y || ++rows > 64)
  4236. break;
  4237. y += th;
  4238. if (y >= box.y + box.h)
  4239. break;
  4240. x = row_x;
  4241. }
  4242. }
  4243. }
  4244. static int run_width(const struct lay_run *r)
  4245. {
  4246. if (r->img >= 0)
  4247. return r->iw;
  4248. if (r->img == -2)
  4249. return r->iw;
  4250. return (int)r->w;
  4251. }
  4252. static void start_line(struct lay *l, const struct br_style *st)
  4253. {
  4254. (void)st;
  4255. if (l->nruns == 0) {
  4256. l->line_y = l->y;
  4257. l->line_h = 0;
  4258. }
  4259. l->line_left = l->left;
  4260. l->line_right = l->right;
  4261. if (l->float_active && l->line_y < l->float_bottom) {
  4262. if (l->float_left > l->line_left)
  4263. l->line_left = l->float_left;
  4264. if (l->float_right < l->line_right)
  4265. l->line_right = l->float_right;
  4266. }
  4267. if (l->line_right < l->line_left + 8)
  4268. l->line_right = l->line_left + 8;
  4269. l->line_x = l->line_left;
  4270. l->run_x = l->line_left;
  4271. }
  4272. static void flush_line(struct lay *l)
  4273. {
  4274. int total, x, i, vis;
  4275. if (!l->nruns && l->line_x == l->line_left) {
  4276. l->line_h = 0;
  4277. return;
  4278. }
  4279. total = l->line_x - l->line_left;
  4280. x = l->line_left;
  4281. vis = 1;
  4282. if (l->draw) {
  4283. int lh = l->line_h ? l->line_h : 16;
  4284. vis = l->line_y + lh >= page_rect.y &&
  4285. l->line_y <= page_rect.y + page_rect.h;
  4286. }
  4287. if (l->align == BR_ALIGN_CENTER)
  4288. x += (l->line_right - l->line_left - total) / 2;
  4289. else if (l->align == BR_ALIGN_RIGHT)
  4290. x = l->line_right - total;
  4291. if (x < l->line_left)
  4292. x = l->line_left;
  4293. for (i = 0; i < l->nruns; i++) {
  4294. struct lay_run *r = &l->runs[i];
  4295. int w = run_width(r);
  4296. int ry = l->line_y + r->dy;
  4297. x += r->gap;
  4298. if (l->draw && vis) {
  4299. if (r->form) {
  4300. unsigned int node = r->form - 1;
  4301. struct form_state *fs = form_get(node, 1);
  4302. int hh = r->ih ? r->ih : 20;
  4303. int focused = form_focus == node;
  4304. int disabled = r->form_disabled;
  4305. unsigned short bg = l->ui->theme.panel_alt;
  4306. unsigned short fg = disabled ? 0x8410 : r->color;
  4307. struct ngui_rect box = {x, ry, w, hh};
  4308. if (r->form_kind == FORM_CHECKBOX ||
  4309. r->form_kind == FORM_RADIO) {
  4310. ngui_fill_rect(l->ui, box, bg);
  4311. ngui_frame(l->ui, box,
  4312. focused ? l->ui->theme.accent :
  4313. l->ui->theme.border);
  4314. if (fs && fs->checked) {
  4315. struct ngui_rect dot = {
  4316. x + 4, ry + 4,
  4317. w > 8 ? w - 8 : 1,
  4318. hh > 8 ? hh - 8 : 1
  4319. };
  4320. if (r->form_kind == FORM_RADIO)
  4321. ngui_fill_round_rect(
  4322. l->ui, dot, 4,
  4323. 4, 4, 4,
  4324. l->ui->theme.accent);
  4325. else
  4326. ngui_fill_rect(l->ui,
  4327. dot,
  4328. l->ui->theme.accent);
  4329. }
  4330. } else {
  4331. ngui_fill_rect(l->ui, box, bg);
  4332. ngui_frame(l->ui, box,
  4333. focused ? l->ui->theme.accent :
  4334. l->ui->theme.border);
  4335. ngui_text_px_face(l->ui, run_face(r),
  4336. x + 6, ry + 2,
  4337. r->lit, s_len(r->lit),
  4338. fg, r->font_px, r->bold,
  4339. r->italic, r->mono);
  4340. if (focused && fs &&
  4341. (r->form_kind == FORM_TEXT ||
  4342. r->form_kind == FORM_PASSWORD ||
  4343. r->form_kind == FORM_TEXTAREA)) {
  4344. int cw = 0;
  4345. if (fs->len && fs->caret)
  4346. cw = (int)run_text_width(
  4347. l->ui, r, r->lit,
  4348. fs->caret < fs->len ?
  4349. fs->caret : fs->len);
  4350. ngui_fill_rect(l->ui,
  4351. (struct ngui_rect){
  4352. x + 6 + cw,
  4353. ry + 4, 1,
  4354. hh > 8 ? hh - 8 : 1
  4355. },
  4356. l->ui->theme.accent);
  4357. }
  4358. if (r->form_kind == FORM_SELECT) {
  4359. ngui_text_px(l->ui, x + w - 12,
  4360. ry + 2, "v", 1, fg,
  4361. r->font_px, 0, 0, 0);
  4362. }
  4363. }
  4364. } else if (r->img == -2) {
  4365. int hh = r->ih ? r->ih : 20;
  4366. ngui_fill_rect(l->ui,
  4367. (struct ngui_rect){x, ry, w, hh},
  4368. l->ui->theme.panel_alt);
  4369. ngui_frame(l->ui,
  4370. (struct ngui_rect){x, ry, w, hh},
  4371. l->ui->theme.border);
  4372. ngui_text_px_face(l->ui, run_face(r),
  4373. x + 6, ry + 2, r->lit,
  4374. s_len(r->lit), r->color,
  4375. r->font_px, r->bold, r->italic,
  4376. r->mono);
  4377. } else if (r->img >= 0) {
  4378. struct br_image *bi = &images[r->img];
  4379. if (bi->state == 1 && r->transform_scale) {
  4380. draw_image_transformed(l->ui, &bi->img,
  4381. x, ry, r->iw, r->ih,
  4382. r->scale_x, r->scale_y,
  4383. r->rotate_x100, r->origin_x,
  4384. r->origin_y, r->origin_x_kind,
  4385. r->origin_y_kind);
  4386. } else if (bi->state == 1) {
  4387. struct img_blit b;
  4388. b.dst = l->ui->px;
  4389. b.dst_w = l->ui->w;
  4390. b.dst_h = l->ui->h;
  4391. b.clip_x = page_rect.x;
  4392. b.clip_y = page_rect.y;
  4393. b.clip_w = page_rect.w - 12;
  4394. b.clip_h = page_rect.h;
  4395. b.x = x;
  4396. b.y = ry;
  4397. b.scale = ((unsigned int)r->iw << 16) /
  4398. bi->img.w;
  4399. b.bg = ui.theme.bg;
  4400. b.bg2 = ui.theme.bg;
  4401. b.flags = IMG_BLIT_OVER_DST;
  4402. img_draw(&bi->img, &b);
  4403. }
  4404. } else {
  4405. const char *s = r->has_lit ? r->lit :
  4406. doc.text + r->off;
  4407. unsigned int n = r->has_lit ? s_len(r->lit) :
  4408. r->len;
  4409. ngui_text_px_face(l->ui, run_face(r), x, ry,
  4410. s, n, r->color, r->font_px,
  4411. r->bold, r->italic, r->mono);
  4412. if (r->underline)
  4413. ngui_fill_rect(l->ui,
  4414. (struct ngui_rect){x,
  4415. ry + run_ascent(l->ui, r) + 2,
  4416. w, 1}, r->color);
  4417. if (r->strike)
  4418. ngui_fill_rect(l->ui,
  4419. (struct ngui_rect){x,
  4420. ry + run_ascent(l->ui, r) -
  4421. (r->font_px > 3 ?
  4422. r->font_px / 3 : 1),
  4423. w, 1}, r->color);
  4424. if (r->overline)
  4425. ngui_fill_rect(l->ui,
  4426. (struct ngui_rect){x, ry,
  4427. w, 1}, r->color);
  4428. }
  4429. if (r->form || r->href) {
  4430. if (nhits < HIT_MAX) {
  4431. struct hit *h = &hits[nhits];
  4432. unsigned int target = r->form ?
  4433. r->form - 1 : r->href;
  4434. int hh = (r->form || r->img >= 0) ?
  4435. r->ih :
  4436. run_line_height(l->ui, r);
  4437. int merge = nhits > 0 &&
  4438. hits[nhits - 1].node == target &&
  4439. hits[nhits - 1].y == ry &&
  4440. hits[nhits - 1].h == hh &&
  4441. x <= hits[nhits - 1].x +
  4442. hits[nhits - 1].w + 2;
  4443. if (merge) {
  4444. struct hit *p = &hits[nhits - 1];
  4445. int end = x + w;
  4446. if (end > p->x + p->w)
  4447. p->w = end - p->x;
  4448. } else {
  4449. h->x = x;
  4450. h->y = ry;
  4451. h->w = w;
  4452. h->h = hh;
  4453. h->node = (unsigned short)target;
  4454. nhits++;
  4455. }
  4456. }
  4457. }
  4458. }
  4459. x += w;
  4460. }
  4461. l->y += l->line_h + 2;
  4462. if (l->float_active && l->y >= l->float_bottom)
  4463. l->float_active = 0;
  4464. l->nruns = 0;
  4465. l->line_x = l->left;
  4466. l->run_x = l->left;
  4467. l->line_left = l->left;
  4468. l->line_right = l->right;
  4469. l->line_h = 0;
  4470. l->space_pending = 0;
  4471. }
  4472. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  4473. const struct br_style *st, unsigned short href,
  4474. const char *lit)
  4475. {
  4476. unsigned int n = lit ? s_len(lit) : len;
  4477. const char *tp = lit ? lit : doc.text + off;
  4478. int w = (int)face_text_width(l->ui, st, tp, n);
  4479. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  4480. flush_line(l);
  4481. if (l->nruns == 0) {
  4482. l->line_y = l->y;
  4483. l->line_h = 0;
  4484. start_line(l, st);
  4485. }
  4486. {
  4487. struct lay_run *r = &l->runs[l->nruns++];
  4488. int gap = l->line_x - l->run_x;
  4489. if (gap < 0)
  4490. gap = 0;
  4491. r->gap = (unsigned short)gap;
  4492. r->off = off;
  4493. r->len = len;
  4494. r->color = st->color;
  4495. r->href = href;
  4496. r->dy = 0;
  4497. r->has_lit = 0;
  4498. r->form = 0;
  4499. r->form_kind = 0;
  4500. r->form_disabled = 0;
  4501. r->lit[0] = '\0';
  4502. if (lit && lit[0]) {
  4503. unsigned int i;
  4504. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  4505. r->lit[i] = lit[i];
  4506. r->lit[i] = '\0';
  4507. r->has_lit = 1;
  4508. }
  4509. r->img = -1;
  4510. r->iw = r->ih = 0;
  4511. r->font_px = st->font_px;
  4512. r->bold = st->bold;
  4513. r->italic = st->italic;
  4514. r->mono = st->mono;
  4515. r->font_face = st->font_face;
  4516. /* A control with its own background is a button, not body copy;
  4517. * an inherited link underline would strike through the fill. */
  4518. r->underline = st->underline && !st->has_bg;
  4519. r->strike = st->strike && !st->has_bg;
  4520. r->overline = st->overline && !st->has_bg;
  4521. r->w = (unsigned short)w;
  4522. if (r->has_lit)
  4523. r->w = (unsigned short)run_text_width(
  4524. l->ui, r, r->lit, s_len(r->lit));
  4525. w = r->w;
  4526. }
  4527. l->line_x += w;
  4528. l->run_x = l->line_x;
  4529. {
  4530. int lh = face_line_height(l->ui, st);
  4531. if (st->line_h_px)
  4532. lh = st->line_h_px;
  4533. else if (st->line_h_pct)
  4534. lh = st->font_px * st->line_h_pct / 100;
  4535. if (lh < face_line_height(l->ui, st))
  4536. lh = face_line_height(l->ui, st);
  4537. if (l->line_h < lh)
  4538. l->line_h = lh;
  4539. }
  4540. }
  4541. static void add_image_run(struct lay *l, unsigned int node,
  4542. const struct br_style *st, unsigned short href)
  4543. {
  4544. struct br_image *bi = 0;
  4545. int idx = doc.nodes[node].img_index;
  4546. int dw, dh, maxw;
  4547. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  4548. bi = &images[idx];
  4549. if (l->nruns == 0)
  4550. start_line(l, st);
  4551. if (l->space_pending &&
  4552. (l->nruns > 0 || l->line_x > l->line_left)) {
  4553. int sp = (int)face_text_width(l->ui, st, " ", 1);
  4554. if (l->line_x + sp <= l->line_right)
  4555. l->line_x += sp;
  4556. }
  4557. l->space_pending = 0;
  4558. if (!bi) {
  4559. const char *alt = br_alt(&doc, node);
  4560. struct br_style gs = *st;
  4561. char tmp[96];
  4562. unsigned int n = 0;
  4563. int w;
  4564. gs.color = BR_GRAY;
  4565. gs.underline = 0;
  4566. s_append(tmp, &n, "[", sizeof(tmp));
  4567. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  4568. s_append(tmp, &n, "]", sizeof(tmp));
  4569. w = (int)face_text_width(l->ui, &gs, tmp, n);
  4570. if (l->line_x + w > l->line_right &&
  4571. (l->nruns > 0 || l->line_x > l->line_left))
  4572. flush_line(l);
  4573. add_run(l, 0, 0, &gs, href, tmp);
  4574. if (!l->draw) {
  4575. int t = l->line_y < 0 ? 0 : l->line_y;
  4576. int hh = face_line_height(l->ui, &gs);
  4577. if (t > 65535)
  4578. t = 65535;
  4579. if (hh > 65535)
  4580. hh = 65535;
  4581. img_top[node] = (unsigned short)t;
  4582. img_h[node] = (unsigned short)hh;
  4583. }
  4584. return;
  4585. }
  4586. maxw = l->line_right - l->line_left;
  4587. if (maxw < 8)
  4588. maxw = 8;
  4589. {
  4590. int iw = bi->native_w, ih = bi->native_h;
  4591. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  4592. if (iw <= 0 || ih <= 0) {
  4593. iw = (int)bi->img.w;
  4594. ih = (int)bi->img.h;
  4595. }
  4596. dw = iw;
  4597. dh = ih;
  4598. if (doc.nodes[node].width_attr) {
  4599. int want = doc.nodes[node].width_attr;
  4600. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  4601. have_w = 1;
  4602. }
  4603. if (doc.nodes[node].height_attr) {
  4604. int want = doc.nodes[node].height_attr;
  4605. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  4606. have_h = 1;
  4607. }
  4608. if (have_w && !have_h)
  4609. dh = ih ? ih * dw / iw : 0;
  4610. if (have_h && !have_w)
  4611. dw = iw ? iw * dh / ih : 0;
  4612. if (st->width_kind) {
  4613. css_w = 1;
  4614. if (st->width_kind == 3)
  4615. dw = maxw * st->width_calc_pct / 100 +
  4616. st->width_calc_px;
  4617. else
  4618. dw = st->width_kind == 2 ?
  4619. maxw * (int)st->width / 100 :
  4620. (int)st->width;
  4621. }
  4622. if (st->height_kind) {
  4623. css_h = 1;
  4624. if (st->height_kind == 3)
  4625. dh = maxw * st->height_calc_pct / 100 +
  4626. st->height_calc_px;
  4627. else
  4628. dh = st->height_kind == 2 ?
  4629. maxw * (int)st->height / 100 :
  4630. (int)st->height;
  4631. }
  4632. if (css_w && !css_h)
  4633. dh = ih ? ih * dw / iw : 0;
  4634. if (css_h && !css_w)
  4635. dw = iw ? iw * dh / ih : 0;
  4636. if (st->max_width_kind) {
  4637. int mw = st->max_width_kind == 3 ?
  4638. maxw * st->max_width_calc_pct / 100 +
  4639. st->max_width_calc_px :
  4640. st->max_width_kind == 2 ?
  4641. maxw * (int)st->max_width / 100 :
  4642. (int)st->max_width;
  4643. if (mw > 0 && dw > mw) {
  4644. dh = iw ? ih * mw / iw : 0;
  4645. dw = mw;
  4646. }
  4647. }
  4648. }
  4649. if (dw < 8)
  4650. dw = 8;
  4651. if (dh < 8)
  4652. dh = 8;
  4653. if (dw > maxw) {
  4654. dh = dw ? dh * maxw / dw : dh;
  4655. dw = maxw;
  4656. }
  4657. if (!l->draw) {
  4658. int t = l->line_y < 0 ? 0 : l->line_y;
  4659. if (t > 65535)
  4660. t = 65535;
  4661. if (dh > 65535)
  4662. dh = 65535;
  4663. img_top[node] = (unsigned short)t;
  4664. img_h[node] = (unsigned short)dh;
  4665. }
  4666. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  4667. l->line_x > l->line_left))
  4668. flush_line(l);
  4669. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  4670. flush_line(l);
  4671. if (l->nruns == 0) {
  4672. l->line_y = l->y;
  4673. l->line_h = 0;
  4674. start_line(l, st);
  4675. }
  4676. {
  4677. struct lay_run *r = &l->runs[l->nruns++];
  4678. int gap = l->line_x - l->run_x;
  4679. if (gap < 0)
  4680. gap = 0;
  4681. r->gap = (unsigned short)gap;
  4682. r->off = 0;
  4683. r->len = 0;
  4684. r->color = 0;
  4685. r->href = href;
  4686. r->form = 0;
  4687. r->form_kind = 0;
  4688. r->form_disabled = 0;
  4689. /* Inline replaced elements honour their vertical margins; this
  4690. * is how Bootstrap's negative logo margins centre the wordmark. */
  4691. {
  4692. int idy = mp_px(st, 0, l->right - l->left);
  4693. if (idy < -2048)
  4694. idy = -2048;
  4695. if (idy > 2048)
  4696. idy = 2048;
  4697. r->dy = (signed short)idy;
  4698. }
  4699. r->has_lit = 0;
  4700. r->lit[0] = '\0';
  4701. r->img = (short)idx;
  4702. r->iw = (unsigned short)dw;
  4703. r->ih = (unsigned short)dh;
  4704. r->w = (unsigned short)dw;
  4705. r->font_px = st->font_px;
  4706. r->bold = st->bold;
  4707. r->italic = st->italic;
  4708. r->mono = st->mono;
  4709. r->font_face = st->font_face;
  4710. r->transform_scale = st->transform_scale;
  4711. r->scale_x = st->scale_x;
  4712. r->scale_y = st->scale_y;
  4713. r->rotate_x100 = st->rotate_x100;
  4714. r->origin_x = st->origin_x;
  4715. r->origin_y = st->origin_y;
  4716. r->origin_x_kind = st->origin_x_kind;
  4717. r->origin_y_kind = st->origin_y_kind;
  4718. r->underline = 0;
  4719. }
  4720. if (node < BR_MAX_NODES) {
  4721. layout_boxes[node].x = l->line_x;
  4722. layout_boxes[node].y = l->line_y +
  4723. mp_px(st, 0, l->right - l->left);
  4724. layout_boxes[node].w = dw;
  4725. layout_boxes[node].h = dh;
  4726. layout_boxes[node].valid = 1;
  4727. }
  4728. l->line_x += dw;
  4729. l->run_x = l->line_x;
  4730. if (l->line_h < dh)
  4731. l->line_h = dh;
  4732. }
  4733. static int text_width(struct lay *l, const char *s, unsigned int n,
  4734. const struct br_style *st)
  4735. {
  4736. return (int)face_text_width(l->ui, st, s, n);
  4737. }
  4738. /* Longest prefix that fits in maxw, at least one byte. */
  4739. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  4740. const struct br_style *st, int maxw)
  4741. {
  4742. unsigned int take = 0;
  4743. while (take < n) {
  4744. if (text_width(l, s, take + 1, st) > maxw)
  4745. break;
  4746. take++;
  4747. }
  4748. return take ? take : 1;
  4749. }
  4750. static void emit_word(struct lay *l, const char *s, unsigned int start,
  4751. unsigned int n, unsigned int base,
  4752. const struct br_style *st, unsigned short href)
  4753. {
  4754. int avail;
  4755. int w = text_width(l, s + start, n, st);
  4756. unsigned int off = start;
  4757. if (l->nruns == 0)
  4758. start_line(l, st);
  4759. avail = l->line_right - l->line_left;
  4760. if (st->nowrap) {
  4761. if (n)
  4762. add_run(l, base + start,
  4763. (unsigned short)n, st, href, 0);
  4764. return;
  4765. }
  4766. /* A padded/bordered one-word button can be a few pixels wider than
  4767. * the content box; keep it on one line instead of splitting it. */
  4768. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  4769. add_run(l, base + start,
  4770. (unsigned short)n, st, href, 0);
  4771. return;
  4772. }
  4773. if (l->line_x + w > l->line_right &&
  4774. (l->nruns > 0 || l->line_x > l->line_left)) {
  4775. flush_line(l);
  4776. start_line(l, st);
  4777. avail = l->line_right - l->line_left;
  4778. }
  4779. if (w <= avail) {
  4780. if (n)
  4781. add_run(l, base + start,
  4782. (unsigned short)n, st, href, 0);
  4783. return;
  4784. }
  4785. while (n > 0) {
  4786. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  4787. add_run(l, base + off,
  4788. (unsigned short)take, st, href, 0);
  4789. off += take;
  4790. n -= take;
  4791. if (n) {
  4792. flush_line(l);
  4793. start_line(l, st);
  4794. avail = l->line_right - l->line_left;
  4795. }
  4796. }
  4797. }
  4798. static void emit_text(struct lay *l, const char *s, unsigned int len,
  4799. const struct br_style *st, unsigned short href, int pre)
  4800. {
  4801. unsigned int i = 0;
  4802. unsigned int base;
  4803. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  4804. if (!s || !len)
  4805. return;
  4806. if (space_w <= 0)
  4807. space_w = 8;
  4808. if (l->nruns == 0)
  4809. start_line(l, st);
  4810. base = (unsigned int)(s - doc.text);
  4811. if (st->uppercase) {
  4812. char *p = (char *)s;
  4813. unsigned int j;
  4814. for (j = 0; j < len; j++)
  4815. if (p[j] >= 'a' && p[j] <= 'z')
  4816. p[j] = (char)(p[j] - 'a' + 'A');
  4817. }
  4818. if (pre) {
  4819. while (i < len) {
  4820. unsigned int start;
  4821. if (s[i] == '\n') {
  4822. flush_line(l);
  4823. start_line(l, st);
  4824. i++;
  4825. continue;
  4826. }
  4827. if (s[i] == ' ') {
  4828. if (l->line_x + space_w > l->line_right &&
  4829. (l->nruns > 0 || l->line_x > l->line_left)) {
  4830. flush_line(l);
  4831. start_line(l, st);
  4832. } else {
  4833. l->line_x += space_w;
  4834. }
  4835. i++;
  4836. continue;
  4837. }
  4838. start = i;
  4839. while (i < len && s[i] != ' ' && s[i] != '\n')
  4840. i++;
  4841. emit_word(l, s, start, i - start, base, st, href);
  4842. }
  4843. return;
  4844. }
  4845. while (i < len) {
  4846. unsigned int start, n;
  4847. if (s[i] == ' ') {
  4848. l->space_pending = 1;
  4849. i++;
  4850. continue;
  4851. }
  4852. start = i;
  4853. while (i < len && s[i] != ' ')
  4854. i++;
  4855. n = i - start;
  4856. if (l->space_pending &&
  4857. (l->nruns > 0 || l->line_x > l->line_left)) {
  4858. if (st->nowrap ||
  4859. l->line_x + space_w <= l->line_right)
  4860. l->line_x += space_w;
  4861. }
  4862. l->space_pending = 0;
  4863. emit_word(l, s, start, n, base, st, href);
  4864. }
  4865. }
  4866. static int list_index(unsigned int parent, unsigned int node)
  4867. {
  4868. unsigned int n = 0, i;
  4869. for (i = doc.nodes[parent].first; i && i != node;
  4870. i = doc.nodes[i].next)
  4871. if (doc.nodes[i].tag == BR_TAG_LI)
  4872. n++;
  4873. return (int)n + 1;
  4874. }
  4875. static void list_roman(char *m, unsigned int *n, int v, int upper,
  4876. unsigned int cap)
  4877. {
  4878. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  4879. 50, 40, 10, 9, 5, 4, 1 };
  4880. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  4881. "l", "xl", "x", "ix", "v", "iv", "i" };
  4882. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  4883. "L", "XL", "X", "IX", "V", "IV", "I" };
  4884. unsigned int i;
  4885. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  4886. while (v >= val[i] && *n + 1 < cap) {
  4887. const char *s = upper ? up[i] : lo[i];
  4888. while (*s && *n + 1 < cap)
  4889. m[(*n)++] = *s++;
  4890. v -= val[i];
  4891. }
  4892. }
  4893. }
  4894. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  4895. {
  4896. unsigned int n = 0;
  4897. if (style == BR_LIST_DISC) {
  4898. m[n++] = '-';
  4899. } else if (style == BR_LIST_CIRCLE) {
  4900. m[n++] = 'o';
  4901. } else if (style == BR_LIST_SQUARE) {
  4902. m[n++] = '+';
  4903. } else if (style == BR_LIST_LOWER_ALPHA ||
  4904. style == BR_LIST_UPPER_ALPHA) {
  4905. if (idx >= 1 && idx <= 26)
  4906. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  4907. 'A' : 'a') + idx - 1);
  4908. else
  4909. m[n++] = '?';
  4910. m[n++] = '.';
  4911. } else if (style == BR_LIST_LOWER_ROMAN ||
  4912. style == BR_LIST_UPPER_ROMAN) {
  4913. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  4914. if (n + 1 < cap)
  4915. m[n++] = '.';
  4916. } else {
  4917. s_append_dec(m, &n, (unsigned int)idx, cap);
  4918. if (n + 1 < cap)
  4919. m[n++] = '.';
  4920. }
  4921. m[n] = '\0';
  4922. }
  4923. static void add_form_run(struct lay *l, unsigned int node,
  4924. const struct br_style *st, unsigned short href)
  4925. {
  4926. struct form_state *fs = form_get(node, 1);
  4927. char shown[FORM_VALUE_MAX + 1];
  4928. char opt[64];
  4929. const char *text = "";
  4930. struct lay_run *r;
  4931. int kind = form_kind_of(node);
  4932. int disabled = form_disabled(node);
  4933. int tw, w = 120, h = 20, i;
  4934. if (!fs)
  4935. return;
  4936. if (l->nruns == 0)
  4937. start_line(l, st);
  4938. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  4939. text = "";
  4940. w = 16;
  4941. h = 16;
  4942. } else if (kind == FORM_SELECT) {
  4943. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  4944. s_copy(opt, "Select", sizeof(opt));
  4945. text = opt;
  4946. w = 120;
  4947. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  4948. kind == FORM_RESET) {
  4949. if (fs->len)
  4950. text = fs->value;
  4951. else
  4952. text = kind == FORM_SUBMIT ? "Submit" :
  4953. kind == FORM_RESET ? "Reset" : "Button";
  4954. } else if (kind == FORM_PASSWORD) {
  4955. for (i = 0; i < fs->len; i++)
  4956. shown[i] = '*';
  4957. shown[fs->len] = '\0';
  4958. text = fs->len ? shown : br_placeholder(&doc, node);
  4959. } else {
  4960. if (fs->len)
  4961. text = fs->value;
  4962. else
  4963. text = br_placeholder(&doc, node);
  4964. if (kind == FORM_TEXTAREA) {
  4965. w = 180;
  4966. h = 40;
  4967. }
  4968. }
  4969. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  4970. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  4971. w = tw + 18;
  4972. if (w < 64)
  4973. w = 64;
  4974. h = 22;
  4975. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD) {
  4976. w = st->width_kind == 1 ? st->width : 120;
  4977. } else if (kind == FORM_SELECT) {
  4978. w = st->width_kind == 1 ? st->width : 120;
  4979. }
  4980. if (w > l->line_right - l->line_left)
  4981. w = l->line_right - l->line_left;
  4982. if (w < 8)
  4983. w = 8;
  4984. if (l->line_x + w > l->line_right &&
  4985. (l->nruns > 0 || l->line_x > l->line_left))
  4986. flush_line(l);
  4987. if (l->nruns >= 96)
  4988. return;
  4989. if (l->nruns == 0) {
  4990. l->line_y = l->y;
  4991. l->line_h = 0;
  4992. start_line(l, st);
  4993. }
  4994. r = &l->runs[l->nruns++];
  4995. r->gap = (unsigned short)(l->line_x - l->run_x);
  4996. r->off = r->len = 0;
  4997. r->color = st->color;
  4998. r->href = href;
  4999. r->dy = 0;
  5000. r->has_lit = 1;
  5001. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  5002. r->lit[i] = text[i];
  5003. r->lit[i] = '\0';
  5004. r->img = -2;
  5005. r->iw = (unsigned short)w;
  5006. r->ih = (unsigned short)h;
  5007. r->w = (unsigned short)w;
  5008. r->font_px = st->font_px;
  5009. r->bold = st->bold;
  5010. r->italic = st->italic;
  5011. r->mono = st->mono;
  5012. r->font_face = st->font_face;
  5013. r->underline = 0;
  5014. r->form = node + 1;
  5015. r->form_kind = (unsigned char)kind;
  5016. r->form_disabled = (unsigned char)disabled;
  5017. if (node < BR_MAX_NODES) {
  5018. layout_boxes[node].x = l->line_x;
  5019. layout_boxes[node].y = l->line_y;
  5020. layout_boxes[node].w = w;
  5021. layout_boxes[node].h = h;
  5022. layout_boxes[node].valid = 1;
  5023. }
  5024. l->line_x += w;
  5025. l->run_x = l->line_x;
  5026. if (l->line_h < h)
  5027. l->line_h = h;
  5028. }
  5029. /* A poster wrapper is absolutely positioned over the media slot; the
  5030. * measured height of its picture is normally added back to the flow. When a
  5031. * loading-skeleton sibling already reserves that slot, adding both doubles
  5032. * the media height and pushes the article text a full screen down. */
  5033. static int has_skeleton_sibling(unsigned int node)
  5034. {
  5035. unsigned int p = doc.nodes[node].parent, c;
  5036. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  5037. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  5038. continue;
  5039. if (doc.nodes[c].class_off &&
  5040. contains_ci(doc.attrs + doc.nodes[c].class_off,
  5041. "skeleton"))
  5042. return 1;
  5043. }
  5044. return 0;
  5045. }
  5046. static void layout_children(struct lay *l, unsigned int parent,
  5047. const struct br_style *pst, int depth,
  5048. unsigned short link);
  5049. static void layout_flex_children(struct lay *l, unsigned int parent,
  5050. const struct br_style *pst, int depth,
  5051. unsigned short link);
  5052. static void layout_grid_children(struct lay *l, unsigned int parent,
  5053. const struct br_style *pst, int depth,
  5054. unsigned short link);
  5055. static void layout_grid_auto(struct lay *l, unsigned int parent,
  5056. const struct br_style *pst, int depth,
  5057. unsigned short link);
  5058. static int flex_item_width(struct lay *l, unsigned int n,
  5059. const struct br_style *cs, int avail);
  5060. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  5061. const struct br_style *pst, int depth,
  5062. unsigned short link);
  5063. static void layout_table_row(struct lay *l, unsigned int row,
  5064. const struct br_style *pst, int depth,
  5065. unsigned short link);
  5066. static int table_has_rowspan(unsigned int table);
  5067. static void layout_table(struct lay *l, unsigned int table,
  5068. const struct br_style *st, int depth,
  5069. unsigned short link);
  5070. /* A flex container whose items are only inline spans is usually just a
  5071. * heading/icon pair. Our flex row positions such items without emitting
  5072. * their inline text in some deep page contexts; normal inline flow renders
  5073. * the same content correctly. */
  5074. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  5075. {
  5076. unsigned int c;
  5077. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  5078. struct br_node *nd = &doc.nodes[c];
  5079. struct br_style cs;
  5080. if (nd->type == BR_NODE_TEXT)
  5081. continue;
  5082. br_style_for(&doc, c, pst, &cs);
  5083. if (cs.display == BR_DISPLAY_NONE)
  5084. continue;
  5085. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  5086. cs.width_kind || cs.has_bg ||
  5087. cs.border_w[0] || cs.border_w[1] ||
  5088. cs.border_w[2] || cs.border_w[3] ||
  5089. nd->tag == BR_TAG_IMG)
  5090. return 1;
  5091. }
  5092. return 0;
  5093. }
  5094. static int css_radius(const struct br_style *st, int corner,
  5095. int w, int h)
  5096. {
  5097. int r = st->radius[corner];
  5098. if (r <= 0)
  5099. return 0;
  5100. if (r > w / 2)
  5101. r = w / 2;
  5102. if (r > h / 2)
  5103. r = h / 2;
  5104. return r;
  5105. }
  5106. /* ---- inline SVG ----
  5107. *
  5108. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  5109. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  5110. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  5111. * opacity and solid paint; a gradient paints the average of its stops) and
  5112. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  5113. #define SVG_CACHE_MAX 48
  5114. #define SVG_CACHE_PIXELS (640 * 1024)
  5115. #define SVG_MAX_POINTS 24576
  5116. struct svg_cache_ent {
  5117. unsigned int node;
  5118. int w, h;
  5119. unsigned short *px;
  5120. unsigned char *a;
  5121. unsigned int stamp;
  5122. };
  5123. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  5124. static unsigned int svg_cache_pixels, svg_cache_clock;
  5125. static struct svgr svg_geom;
  5126. static void *svg_geom_buf;
  5127. /* Current viewport in user units: percentage lengths resolve against it
  5128. * (the viewBox size, not the device pixels). */
  5129. static double svg_vp_w = 300, svg_vp_h = 150;
  5130. /* The layers live in the page heap: forget them before heap_reset(). */
  5131. static void svg_cache_clear(void)
  5132. {
  5133. memset(svg_cache, 0, sizeof(svg_cache));
  5134. svg_cache_pixels = 0;
  5135. svg_geom_buf = 0;
  5136. }
  5137. static int svg_name_is(const char *a, const char *b)
  5138. {
  5139. while (*a && *b) {
  5140. char x = *a, y = *b;
  5141. if (x >= 'A' && x <= 'Z')
  5142. x = (char)(x - 'A' + 'a');
  5143. if (x != y)
  5144. return 0;
  5145. a++;
  5146. b++;
  5147. }
  5148. return *a == *b;
  5149. }
  5150. static const char *svg_elem_name(unsigned int node)
  5151. {
  5152. const struct br_node *nd = &doc.nodes[node];
  5153. if (nd->name_off)
  5154. return doc.attrs + nd->name_off;
  5155. return br_tag_name(nd->tag);
  5156. }
  5157. /* A numeric attribute; a percentage resolves against `base`. */
  5158. static double svg_attr_num(unsigned int node, const char *name, double def,
  5159. double base)
  5160. {
  5161. const char *v = br_find_attr(&doc, node, name);
  5162. const char *p = v;
  5163. int ok = 0;
  5164. double x;
  5165. if (!v)
  5166. return def;
  5167. x = svgr_num(&p, &ok);
  5168. if (!ok)
  5169. return def;
  5170. if (*p == '%')
  5171. x = x * base / 100.0;
  5172. return x;
  5173. }
  5174. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  5175. static int svg_viewbox4(unsigned int node, double vb[4])
  5176. {
  5177. const char *v = br_find_attr(&doc, node, "viewbox");
  5178. const char *p = v;
  5179. int i, ok = 1;
  5180. if (!v)
  5181. return 0;
  5182. for (i = 0; i < 4 && ok; i++)
  5183. vb[i] = svgr_num(&p, &ok);
  5184. return ok && vb[2] > 0 && vb[3] > 0;
  5185. }
  5186. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  5187. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  5188. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  5189. double w, double h, double m[6])
  5190. {
  5191. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  5192. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  5193. int ax = 1, ay = 1;
  5194. if (par && contains_ci(par, "none")) {
  5195. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  5196. m[4] = -vb[0] * sx;
  5197. m[5] = -vb[1] * sy;
  5198. return;
  5199. }
  5200. if (par) {
  5201. if (contains_ci(par, "xmin"))
  5202. ax = 0;
  5203. else if (contains_ci(par, "xmax"))
  5204. ax = 2;
  5205. if (contains_ci(par, "ymin"))
  5206. ay = 0;
  5207. else if (contains_ci(par, "ymax"))
  5208. ay = 2;
  5209. }
  5210. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  5211. (sx < sy ? sx : sy);
  5212. tx = (w - vb[2] * s) * ax / 2.0;
  5213. ty = (h - vb[3] * s) * ay / 2.0;
  5214. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  5215. m[4] = tx - vb[0] * s;
  5216. m[5] = ty - vb[1] * s;
  5217. }
  5218. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  5219. * the paint attribute, then average the gradient's stops. */
  5220. static int svg_url_paint(unsigned int node, const char *attr,
  5221. unsigned short *color, unsigned int *alpha)
  5222. {
  5223. const char *v = 0, *h;
  5224. char id[64];
  5225. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  5226. for (k = 0; node && k < 32 && !v; k++) {
  5227. v = br_find_attr(&doc, node, attr);
  5228. if (!v) {
  5229. const char *style = br_find_attr(&doc, node, "style");
  5230. if (style && contains_ci(style, "url(#"))
  5231. v = strstr(style, "url(#");
  5232. }
  5233. if (v && !contains_ci(v, "url("))
  5234. v = 0;
  5235. node = doc.nodes[node].parent;
  5236. }
  5237. if (!v || !(h = strstr(v, "#")))
  5238. return 0;
  5239. h++;
  5240. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  5241. id[n++] = *h++;
  5242. id[n] = '\0';
  5243. g = br_find_id(&doc, id);
  5244. /* Follow href chains (a gradient that only references another one's
  5245. * stops), at most a few hops. */
  5246. for (k = 0; g && k < 4; k++) {
  5247. unsigned int gi = g - 1;
  5248. const char *ref;
  5249. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  5250. const char *nm, *sc, *so;
  5251. unsigned short col = 0;
  5252. double op = 1;
  5253. if (doc.nodes[c].type != BR_NODE_ELEM)
  5254. continue;
  5255. nm = svg_elem_name(c);
  5256. if (!svg_name_is(nm, "stop"))
  5257. continue;
  5258. sc = br_find_attr(&doc, c, "stop-color");
  5259. so = br_find_attr(&doc, c, "stop-opacity");
  5260. {
  5261. const char *st = br_find_attr(&doc, c, "style");
  5262. const char *q;
  5263. if (st && (q = strstr(st, "stop-color:")) != 0)
  5264. sc = q + 11;
  5265. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  5266. so = q + 13;
  5267. }
  5268. if (sc) {
  5269. unsigned int L = 0;
  5270. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  5271. L++;
  5272. if (!br_parse_color(sc, L, &col))
  5273. col = 0;
  5274. }
  5275. if (so) {
  5276. const char *p = so;
  5277. int ok = 0;
  5278. double x = svgr_num(&p, &ok);
  5279. if (ok)
  5280. op = x < 0 ? 0 : x > 1 ? 1 : x;
  5281. }
  5282. sr += (col >> 11) & 31;
  5283. sg += (col >> 5) & 63;
  5284. sb += col & 31;
  5285. sa += (unsigned int)(op * 255);
  5286. cnt++;
  5287. }
  5288. if (cnt)
  5289. break;
  5290. ref = br_find_attr(&doc, gi, "href");
  5291. if (!ref)
  5292. ref = br_find_attr(&doc, gi, "xlink:href");
  5293. if (!ref || ref[0] != '#')
  5294. break;
  5295. g = br_find_id(&doc, ref + 1);
  5296. }
  5297. if (!cnt)
  5298. return 0;
  5299. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  5300. (sb / cnt));
  5301. *alpha = sa / cnt;
  5302. return 1;
  5303. }
  5304. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  5305. unsigned short *color, unsigned int *alpha)
  5306. {
  5307. int mode = fill ? st->fill_mode : st->stroke_mode;
  5308. const char *op = br_find_attr(&doc, node,
  5309. fill ? "fill-opacity" : "stroke-opacity");
  5310. *alpha = 255;
  5311. switch (mode) {
  5312. case BR_PAINT_UNSET:
  5313. if (!fill)
  5314. return 0;
  5315. *color = 0;
  5316. break;
  5317. case BR_PAINT_COLOR:
  5318. *color = fill ? st->fill : st->stroke;
  5319. break;
  5320. case BR_PAINT_CURRENT:
  5321. *color = st->color;
  5322. break;
  5323. case BR_PAINT_URL:
  5324. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  5325. alpha))
  5326. return 0;
  5327. break;
  5328. default:
  5329. return 0;
  5330. }
  5331. if (op) {
  5332. const char *p = op;
  5333. int ok = 0;
  5334. double x = svgr_num(&p, &ok);
  5335. if (ok)
  5336. *alpha = (unsigned int)(*alpha *
  5337. (x < 0 ? 0 : x > 1 ? 1 : x));
  5338. }
  5339. return *alpha > 0;
  5340. }
  5341. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  5342. const double m[6], const struct br_style *pst,
  5343. unsigned int alpha, int depth);
  5344. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  5345. const double m[6], const struct br_style *st,
  5346. unsigned int alpha, int depth)
  5347. {
  5348. unsigned int c;
  5349. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  5350. if (doc.nodes[c].type == BR_NODE_ELEM)
  5351. svg_draw_node(L, c, m, st, alpha, depth + 1);
  5352. }
  5353. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  5354. const double pm[6], const struct br_style *pst,
  5355. unsigned int alpha, int depth)
  5356. {
  5357. struct br_style st;
  5358. const char *nm = svg_elem_name(node);
  5359. const char *tf;
  5360. double m[6];
  5361. unsigned short color;
  5362. unsigned int pa;
  5363. int shape = 0, fillable = 1;
  5364. if (depth > 24 || !nm)
  5365. return;
  5366. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  5367. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  5368. svg_name_is(nm, "lineargradient") ||
  5369. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  5370. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  5371. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  5372. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  5373. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  5374. svg_name_is(nm, "foreignobject"))
  5375. return;
  5376. br_style_for(&doc, node, pst, &st);
  5377. if (st.display == BR_DISPLAY_NONE)
  5378. return;
  5379. memcpy(m, pm, sizeof(m));
  5380. tf = br_find_attr(&doc, node, "transform");
  5381. if (tf)
  5382. svgr_transform(m, tf);
  5383. {
  5384. const char *op = br_find_attr(&doc, node, "opacity");
  5385. if (op) {
  5386. const char *p = op;
  5387. int ok = 0;
  5388. double x = svgr_num(&p, &ok);
  5389. if (ok)
  5390. alpha = (unsigned int)(alpha *
  5391. (x < 0 ? 0 :
  5392. x > 1 ? 1 : x));
  5393. }
  5394. }
  5395. if (!alpha)
  5396. return;
  5397. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  5398. svg_name_is(nm, "switch")) {
  5399. svg_draw_children(L, node, m, &st, alpha, depth);
  5400. return;
  5401. }
  5402. if (svg_name_is(nm, "svg")) {
  5403. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  5404. y = svg_attr_num(node, "y", 0, 0);
  5405. double t[6] = { 1, 0, 0, 1, 0, 0 };
  5406. t[4] = x;
  5407. t[5] = y;
  5408. svgr_mat_mul(m, m, t);
  5409. double ow = svg_vp_w, oh = svg_vp_h;
  5410. if (svg_viewbox4(node, vb)) {
  5411. double w = svg_attr_num(node, "width", vb[2], ow);
  5412. double h = svg_attr_num(node, "height", vb[3], oh);
  5413. double vm[6];
  5414. svg_viewport_matrix(node, vb, w, h, vm);
  5415. svgr_mat_mul(m, m, vm);
  5416. svg_vp_w = vb[2];
  5417. svg_vp_h = vb[3];
  5418. }
  5419. svg_draw_children(L, node, m, &st, alpha, depth);
  5420. svg_vp_w = ow;
  5421. svg_vp_h = oh;
  5422. return;
  5423. }
  5424. if (svg_name_is(nm, "use")) {
  5425. const char *ref = br_find_attr(&doc, node, "href");
  5426. unsigned int tgt;
  5427. double t[6] = { 1, 0, 0, 1, 0, 0 };
  5428. if (!ref)
  5429. ref = br_find_attr(&doc, node, "xlink:href");
  5430. if (!ref || ref[0] != '#')
  5431. return;
  5432. tgt = br_find_id(&doc, ref + 1);
  5433. if (!tgt || tgt - 1 == node)
  5434. return;
  5435. tgt--;
  5436. t[4] = svg_attr_num(node, "x", 0, 0);
  5437. t[5] = svg_attr_num(node, "y", 0, 0);
  5438. svgr_mat_mul(m, m, t);
  5439. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  5440. double vb[4];
  5441. double ow = svg_vp_w, oh = svg_vp_h;
  5442. if (svg_viewbox4(tgt, vb)) {
  5443. double w = svg_attr_num(node, "width", vb[2],
  5444. ow);
  5445. double h = svg_attr_num(node, "height", vb[3],
  5446. oh);
  5447. double vm[6];
  5448. svg_viewport_matrix(tgt, vb, w, h, vm);
  5449. svgr_mat_mul(m, m, vm);
  5450. svg_vp_w = vb[2];
  5451. svg_vp_h = vb[3];
  5452. }
  5453. svg_draw_children(L, tgt, m, &st, alpha, depth);
  5454. svg_vp_w = ow;
  5455. svg_vp_h = oh;
  5456. } else {
  5457. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  5458. }
  5459. return;
  5460. }
  5461. svgr_reset(&svg_geom, m);
  5462. if (svg_name_is(nm, "path")) {
  5463. const char *d = br_find_attr(&doc, node, "d");
  5464. if (d) {
  5465. svgr_path(&svg_geom, d);
  5466. shape = 1;
  5467. }
  5468. } else if (svg_name_is(nm, "rect")) {
  5469. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  5470. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  5471. double rx = svg_attr_num(node, "rx", -1, w);
  5472. double ry = svg_attr_num(node, "ry", -1, h);
  5473. if (rx < 0)
  5474. rx = ry < 0 ? 0 : ry;
  5475. if (ry < 0)
  5476. ry = rx;
  5477. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  5478. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  5479. shape = 1;
  5480. } else if (svg_name_is(nm, "circle")) {
  5481. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  5482. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  5483. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  5484. shape = 1;
  5485. } else if (svg_name_is(nm, "ellipse")) {
  5486. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  5487. svg_attr_num(node, "cy", 0, svg_vp_h),
  5488. svg_attr_num(node, "rx", 0, svg_vp_w),
  5489. svg_attr_num(node, "ry", 0, svg_vp_h));
  5490. shape = 1;
  5491. } else if (svg_name_is(nm, "line")) {
  5492. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  5493. svg_attr_num(node, "y1", 0, svg_vp_h));
  5494. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  5495. svg_attr_num(node, "y2", 0, svg_vp_h));
  5496. shape = 1;
  5497. fillable = 0;
  5498. } else if (svg_name_is(nm, "polyline") ||
  5499. svg_name_is(nm, "polygon")) {
  5500. const char *pts = br_find_attr(&doc, node, "points");
  5501. if (pts) {
  5502. svgr_points(&svg_geom, pts,
  5503. svg_name_is(nm, "polygon"));
  5504. shape = 1;
  5505. }
  5506. }
  5507. if (!shape)
  5508. return;
  5509. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  5510. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  5511. st.fill_evenodd);
  5512. if (svg_paint(node, &st, 0, &color, &pa)) {
  5513. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  5514. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  5515. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  5516. }
  5517. }
  5518. /* <text> elements: drawn straight onto the page every frame (the glyph
  5519. * renderer targets the ngui canvas, not a layer). x/y map through the
  5520. * accumulated transform; the font size scales with it. */
  5521. static void svg_draw_text(struct ngui *ui, unsigned int node,
  5522. const double pm[6], const struct br_style *pst,
  5523. int ox, int oy, int depth)
  5524. {
  5525. unsigned int c;
  5526. if (depth > 24)
  5527. return;
  5528. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  5529. struct br_style st;
  5530. const char *nm, *tf;
  5531. double m[6];
  5532. if (doc.nodes[c].type != BR_NODE_ELEM)
  5533. continue;
  5534. nm = svg_elem_name(c);
  5535. if (!nm || svg_name_is(nm, "defs") ||
  5536. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  5537. svg_name_is(nm, "clippath"))
  5538. continue;
  5539. br_style_for(&doc, c, pst, &st);
  5540. if (st.display == BR_DISPLAY_NONE)
  5541. continue;
  5542. memcpy(m, pm, sizeof(m));
  5543. tf = br_find_attr(&doc, c, "transform");
  5544. if (tf)
  5545. svgr_transform(m, tf);
  5546. if (svg_name_is(nm, "text")) {
  5547. unsigned int t = doc.nodes[c].first;
  5548. const char *s;
  5549. unsigned int n, tw;
  5550. double x = svg_attr_num(c, "x", 0, 0),
  5551. y = svg_attr_num(c, "y", 0, 0);
  5552. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  5553. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  5554. int tx, ty, anchor;
  5555. unsigned short col;
  5556. unsigned int pa;
  5557. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  5558. continue;
  5559. if (px < 6)
  5560. px = 6;
  5561. if (px > 72)
  5562. px = 72;
  5563. if (!svg_paint(c, &st, 1, &col, &pa))
  5564. continue;
  5565. s = doc.text + doc.nodes[t].text_off;
  5566. n = doc.nodes[t].text_len;
  5567. st.font_px = (unsigned char)px;
  5568. tw = face_text_width(ui, &st, s, n);
  5569. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  5570. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  5571. ngui_text_ascent_face(ui, style_face(&st), px,
  5572. st.mono);
  5573. anchor = st.align;
  5574. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  5575. anchor = BR_ALIGN_CENTER;
  5576. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  5577. anchor = BR_ALIGN_RIGHT;
  5578. if (anchor == BR_ALIGN_CENTER)
  5579. tx -= (int)tw / 2;
  5580. else if (anchor == BR_ALIGN_RIGHT)
  5581. tx -= (int)tw;
  5582. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  5583. col, px, st.bold, st.italic,
  5584. st.mono);
  5585. } else {
  5586. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  5587. }
  5588. }
  5589. }
  5590. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  5591. {
  5592. double vb[4];
  5593. if (svg_viewbox4(node, vb)) {
  5594. svg_viewport_matrix(node, vb, w, h, m);
  5595. } else {
  5596. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  5597. }
  5598. }
  5599. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  5600. const struct br_style *st)
  5601. {
  5602. struct svg_cache_ent *e = 0;
  5603. struct svgr_layer L;
  5604. double m[6];
  5605. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  5606. svg_cache_clock++;
  5607. for (i = 0; i < SVG_CACHE_MAX; i++)
  5608. if (svg_cache[i].px && svg_cache[i].node == node &&
  5609. svg_cache[i].w == w && svg_cache[i].h == h) {
  5610. svg_cache[i].stamp = svg_cache_clock;
  5611. return &svg_cache[i];
  5612. }
  5613. if (need > SVG_CACHE_PIXELS)
  5614. return 0;
  5615. /* Evict least recently used layers until this one fits. */
  5616. for (;;) {
  5617. struct svg_cache_ent *lru = 0, *free_slot = 0;
  5618. for (i = 0; i < SVG_CACHE_MAX; i++) {
  5619. if (!svg_cache[i].px) {
  5620. if (!free_slot)
  5621. free_slot = &svg_cache[i];
  5622. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  5623. lru = &svg_cache[i];
  5624. }
  5625. }
  5626. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  5627. e = free_slot;
  5628. break;
  5629. }
  5630. if (!lru)
  5631. return 0;
  5632. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  5633. free(lru->px);
  5634. free(lru->a);
  5635. memset(lru, 0, sizeof(*lru));
  5636. }
  5637. if (!svg_geom_buf) {
  5638. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  5639. if (!svg_geom_buf)
  5640. return 0;
  5641. }
  5642. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  5643. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  5644. e->a = (unsigned char *)calloc(need, 1);
  5645. if (!e->px || !e->a) {
  5646. free(e->px);
  5647. free(e->a);
  5648. memset(e, 0, sizeof(*e));
  5649. return 0;
  5650. }
  5651. e->node = node;
  5652. e->w = w;
  5653. e->h = h;
  5654. e->stamp = svg_cache_clock;
  5655. svg_cache_pixels += need;
  5656. L.px = e->px;
  5657. L.a = e->a;
  5658. L.w = w;
  5659. L.h = h;
  5660. svg_root_matrix(node, w, h, m);
  5661. {
  5662. double vb[4];
  5663. if (svg_viewbox4(node, vb)) {
  5664. svg_vp_w = vb[2];
  5665. svg_vp_h = vb[3];
  5666. } else {
  5667. svg_vp_w = w;
  5668. svg_vp_h = h;
  5669. }
  5670. }
  5671. svg_draw_children(&L, node, m, st, 255, 0);
  5672. return e;
  5673. }
  5674. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  5675. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  5676. int *out_w, int *out_h)
  5677. {
  5678. double vb[4];
  5679. int has_vb = svg_viewbox4(node, vb);
  5680. double aw = svg_attr_num(node, "width", -1, cw);
  5681. double ah = svg_attr_num(node, "height", -1, 0);
  5682. int w, h;
  5683. if (st->width_kind)
  5684. w = cw;
  5685. else if (aw > 0)
  5686. w = (int)(aw + 0.5);
  5687. else if (st->height_kind == 1 && has_vb)
  5688. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  5689. else if (ah > 0 && has_vb)
  5690. w = (int)(ah * vb[2] / vb[3] + 0.5);
  5691. else if (has_vb)
  5692. w = cw;
  5693. else
  5694. w = 300;
  5695. if (st->max_width_kind == 1 && w > st->max_width)
  5696. w = st->max_width;
  5697. if (w > cw && cw > 0 && !(aw > 0))
  5698. w = cw;
  5699. if (w < 1)
  5700. w = 1;
  5701. if (w > 2000)
  5702. w = 2000;
  5703. if (st->height_kind == 1)
  5704. h = st->height;
  5705. else if (ah > 0)
  5706. h = (int)(ah + 0.5);
  5707. else if (has_vb)
  5708. h = (int)(w * vb[3] / vb[2] + 0.5);
  5709. else
  5710. h = 150;
  5711. if (h < 1)
  5712. h = 1;
  5713. if (h > 1400)
  5714. h = 1400;
  5715. *out_w = w;
  5716. *out_h = h;
  5717. }
  5718. static void svg_paint_box(struct ngui *ui, unsigned int node,
  5719. const struct br_style *st, int x, int y, int w, int h)
  5720. {
  5721. struct svg_cache_ent *e;
  5722. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  5723. int cx0, cy0, cx1, cy1, px, py;
  5724. double m[6];
  5725. if (ui->nclip > 0)
  5726. clip = ui->clip[ui->nclip - 1];
  5727. cx0 = r.x > clip.x ? r.x : clip.x;
  5728. cy0 = r.y > clip.y ? r.y : clip.y;
  5729. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  5730. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  5731. if (cx0 >= cx1 || cy0 >= cy1)
  5732. return;
  5733. e = svg_layer(node, w, h, st);
  5734. if (e) {
  5735. for (py = cy0; py < cy1; py++) {
  5736. unsigned int srow = (unsigned int)(py - y) *
  5737. (unsigned int)w;
  5738. unsigned short *dst = ui->px + py * ui->w;
  5739. for (px = cx0; px < cx1; px++) {
  5740. unsigned int si = srow + (unsigned int)(px - x);
  5741. unsigned int a = e->a[si];
  5742. if (!a)
  5743. continue;
  5744. dst[px] = a >= 255 ? e->px[si] :
  5745. blend_rgb565(dst[px], e->px[si], a);
  5746. }
  5747. }
  5748. }
  5749. svg_root_matrix(node, w, h, m);
  5750. ngui_push_clip(ui, r);
  5751. svg_draw_text(ui, node, m, st, x, y, 0);
  5752. ngui_pop_clip(ui);
  5753. }
  5754. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  5755. * keep using add_image_run(); this covers the CSS `position:absolute;
  5756. * width:100%` poster pattern used by news sites. */
  5757. static void image_block_size(unsigned int node, const struct br_style *st,
  5758. int cbw, int *out_w, int *out_h)
  5759. {
  5760. struct br_node *nd = &doc.nodes[node];
  5761. int idx = nd->img_index;
  5762. int iw = 0, ih = 0, w, h;
  5763. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  5764. iw = (int)images[idx].img.w;
  5765. ih = (int)images[idx].img.h;
  5766. if (iw <= 0 || ih <= 0) {
  5767. iw = (int)images[idx].native_w;
  5768. ih = (int)images[idx].native_h;
  5769. }
  5770. }
  5771. if (st->width_kind)
  5772. w = style_width_px(st, cbw);
  5773. else if (nd->width_attr)
  5774. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  5775. (int)nd->width_attr;
  5776. else if (iw)
  5777. w = iw;
  5778. else
  5779. w = 64;
  5780. if (w < 8)
  5781. w = 8;
  5782. if (cbw > 0 && w > cbw)
  5783. w = cbw;
  5784. if (st->height_kind)
  5785. h = style_height_px(st, cbw);
  5786. else if (nd->height_attr)
  5787. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  5788. (int)nd->height_attr;
  5789. else if (iw && ih)
  5790. h = w * ih / iw;
  5791. else
  5792. h = 64;
  5793. if (h < 8)
  5794. h = 8;
  5795. *out_w = w;
  5796. *out_h = h;
  5797. }
  5798. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  5799. int dw, int dh)
  5800. {
  5801. int idx = doc.nodes[node].img_index;
  5802. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  5803. struct img_blit b;
  5804. b.dst = l->ui->px;
  5805. b.dst_w = l->ui->w;
  5806. b.dst_h = l->ui->h;
  5807. b.clip_x = page_rect.x;
  5808. b.clip_y = page_rect.y;
  5809. b.clip_w = page_rect.w - 12;
  5810. b.clip_h = page_rect.h;
  5811. b.x = x;
  5812. b.y = y;
  5813. b.scale = ((unsigned int)dw << 16) / images[idx].img.w;
  5814. b.bg = ui.theme.bg;
  5815. b.bg2 = ui.theme.bg;
  5816. b.flags = IMG_BLIT_OVER_DST;
  5817. img_draw(&images[idx].img, &b);
  5818. } else if (l->draw) {
  5819. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  5820. 0xD69A);
  5821. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  5822. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  5823. }
  5824. }
  5825. static void layout_block(struct lay *l, unsigned int node,
  5826. const struct br_style *st, int depth,
  5827. unsigned short link)
  5828. {
  5829. int old_left = l->left, old_right = l->right, old_align = l->align;
  5830. int saved_parent_top = l->parent_top;
  5831. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  5832. int saved_cb_top = l->cb_top;
  5833. int top, l0, r0;
  5834. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  5835. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  5836. int deco_w, deco_h, content_w, content_h, box_h;
  5837. int img_dh = 0;
  5838. int definite_w = 0;
  5839. int normal_top = 0;
  5840. int rel_dx = 0, rel_dy = 0;
  5841. int clip_pushed = 0;
  5842. struct ngui_rect clip_rect;
  5843. /* A DOM level costs about two depth units (layout_block ->
  5844. * layout_children), so 48 covers a ~24-level page. Real news pages
  5845. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  5846. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  5847. return;
  5848. flow_y = l->y;
  5849. flow_left = l->left;
  5850. flow_right = l->right;
  5851. positioned = st->pos == 1 || st->pos == 2;
  5852. relative = st->pos == 3;
  5853. sticky = st->pos == 4;
  5854. shifted = relative || sticky || st->transform_set;
  5855. if (positioned) {
  5856. int def_w = st->width_kind == 1 ? st->width : -1;
  5857. if (st->pos == 2) {
  5858. int avail_w = page_rect.w - 12;
  5859. if (st->right_set && def_w >= 0)
  5860. l->left = page_rect.x + avail_w - st->right -
  5861. def_w;
  5862. else
  5863. l->left = page_rect.x +
  5864. (st->left_set ? st->left : 0);
  5865. l->right = def_w >= 0 ? l->left + def_w :
  5866. page_rect.x + avail_w;
  5867. if (st->bottom_set && st->height_kind)
  5868. l->y = page_rect.y + page_rect.h -
  5869. st->bottom -
  5870. style_height_px(st, page_rect.w);
  5871. else
  5872. l->y = page_rect.y +
  5873. (st->top_set ? st->top : 0);
  5874. } else {
  5875. int left = flow_left + (st->left_set ? st->left : 0);
  5876. unsigned int parent = doc.nodes[node].parent;
  5877. if (st->right_set && def_w >= 0)
  5878. left = flow_right - st->right - def_w;
  5879. l->left = left;
  5880. l->right = def_w >= 0 ? left + def_w :
  5881. flow_right +
  5882. (st->left_set ? st->left : 0);
  5883. l->y = flow_y + (st->top_set ? st->top : 0);
  5884. if (st->bottom_set && st->height_kind &&
  5885. parent < BR_MAX_NODES && block_h[parent] > 0)
  5886. l->y = flow_y + block_h[parent] - st->bottom -
  5887. style_height_px(st, old_right - old_left);
  5888. }
  5889. old_left = l->left;
  5890. old_right = l->right;
  5891. } else if (relative) {
  5892. rel_dx = st->left_set ? st->left :
  5893. (st->right_set ? -st->right : 0);
  5894. rel_dy = st->top_set ? st->top :
  5895. (st->bottom_set ? -st->bottom : 0);
  5896. }
  5897. if (st->transform_set) {
  5898. rel_dx += st->tx;
  5899. rel_dy += st->ty;
  5900. }
  5901. if (doc.nodes[node].tag == BR_TAG_INPUT ||
  5902. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  5903. doc.nodes[node].tag == BR_TAG_SELECT ||
  5904. doc.nodes[node].tag == BR_TAG_BUTTON) {
  5905. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  5906. s_eq(br_type(&doc, node), "hidden"))
  5907. return;
  5908. add_form_run(l, node, st, link);
  5909. l->y += doc.nodes[node].tag == BR_TAG_TEXTAREA ? 40 :
  5910. doc.nodes[node].tag == BR_TAG_BUTTON ? 22 : 20;
  5911. return;
  5912. }
  5913. flush_line(l);
  5914. cbw = old_right - old_left;
  5915. if (cbw < 8)
  5916. cbw = 8;
  5917. l->y += mp_px(st, 0, cbw);
  5918. top = l->y;
  5919. ml = mp_px(st, 3, cbw);
  5920. mr = mp_px(st, 1, cbw);
  5921. bl = st->border_w[3];
  5922. br = st->border_w[1];
  5923. pl = mp_px(st, 7, cbw);
  5924. pr = mp_px(st, 5, cbw);
  5925. bt = st->border_w[0];
  5926. bb = st->border_w[2];
  5927. pt = mp_px(st, 4, cbw);
  5928. pb = mp_px(st, 6, cbw);
  5929. deco_w = bl + br + pl + pr;
  5930. deco_h = bt + bb + pt + pb;
  5931. if (st->width_kind) {
  5932. int w;
  5933. if (st->width_kind == 3)
  5934. w = cbw * st->width_calc_pct / 100 +
  5935. st->width_calc_px;
  5936. else
  5937. w = css_size(st->width_kind, st->width, cbw);
  5938. if (w < 0)
  5939. w = 0;
  5940. content_w = st->box_sizing ? w - deco_w : w;
  5941. definite_w = 1;
  5942. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  5943. doc.nodes[node].tag == BR_TAG_TD ||
  5944. doc.nodes[node].tag == BR_TAG_TH) &&
  5945. doc.nodes[node].width_attr) {
  5946. /* Legacy table/cell width attributes: percentages resolve
  5947. * against the containing block, bare numbers are pixels. */
  5948. int w = doc.nodes[node].width_pct ?
  5949. cbw * doc.nodes[node].width_attr / 100 :
  5950. doc.nodes[node].width_attr;
  5951. if (w < 0)
  5952. w = 0;
  5953. content_w = st->box_sizing ? w - deco_w : w;
  5954. definite_w = 1;
  5955. } else {
  5956. content_w = cbw - ml - mr - deco_w;
  5957. }
  5958. if (content_w < 0)
  5959. content_w = 0;
  5960. if (st->max_width_kind) {
  5961. int mw = st->max_width_kind == 3 ?
  5962. cbw * st->max_width_calc_pct / 100 +
  5963. st->max_width_calc_px :
  5964. css_size(st->max_width_kind, st->max_width, cbw);
  5965. int max_box = st->box_sizing ? mw : mw + deco_w;
  5966. if (content_w + deco_w > max_box)
  5967. content_w = max_box - deco_w;
  5968. }
  5969. if (st->min_width_kind) {
  5970. int mw = st->min_width_kind == 3 ?
  5971. cbw * st->min_width_calc_pct / 100 +
  5972. st->min_width_calc_px :
  5973. css_size(st->min_width_kind, st->min_width, cbw);
  5974. int min_box = st->box_sizing ? mw : mw + deco_w;
  5975. if (content_w + deco_w < min_box) {
  5976. content_w = min_box - deco_w;
  5977. definite_w = 1;
  5978. }
  5979. }
  5980. if (content_w < 8)
  5981. content_w = 8;
  5982. if (definite_w) {
  5983. int free_w = cbw - ml - mr - deco_w - content_w;
  5984. if (free_w < 0)
  5985. free_w = 0;
  5986. if (st->ml_auto && st->mr_auto) {
  5987. ml = free_w / 2;
  5988. mr = free_w - ml;
  5989. } else if (st->ml_auto) {
  5990. ml = free_w;
  5991. } else if (st->mr_auto) {
  5992. mr = free_w;
  5993. }
  5994. }
  5995. if (doc.nodes[node].tag == BR_TAG_IMG) {
  5996. int iw, ih;
  5997. image_block_size(node, st, cbw, &iw, &ih);
  5998. content_w = iw;
  5999. img_dh = ih;
  6000. }
  6001. l0 = old_left + ml;
  6002. r0 = l0 + deco_w + content_w;
  6003. if (r0 < l0 + 8)
  6004. r0 = l0 + 8;
  6005. normal_top = top;
  6006. if (sticky) {
  6007. if (st->top_set) {
  6008. int stick = page_rect.y + 4 + st->top;
  6009. if (normal_top < stick)
  6010. rel_dy += stick - normal_top;
  6011. } else if (st->bottom_set && block_h[node]) {
  6012. int stick = page_rect.y + page_rect.h - st->bottom -
  6013. block_h[node];
  6014. if (normal_top > stick)
  6015. rel_dy += stick - normal_top;
  6016. }
  6017. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  6018. block_h[doc.nodes[node].parent]) {
  6019. unsigned int p = doc.nodes[node].parent;
  6020. int ptop = l->parent_top;
  6021. int pbottom = ptop + block_h[p];
  6022. int eh = block_h[node];
  6023. int moved_top = normal_top + rel_dy;
  6024. int moved_bottom = moved_top + eh;
  6025. if (moved_bottom > pbottom)
  6026. rel_dy -= moved_bottom - pbottom;
  6027. moved_top = normal_top + rel_dy;
  6028. if (moved_top < ptop)
  6029. rel_dy += ptop - moved_top;
  6030. }
  6031. }
  6032. if (shifted && l->draw) {
  6033. top += rel_dy;
  6034. l0 += rel_dx;
  6035. r0 += rel_dx;
  6036. }
  6037. l->parent_top = top;
  6038. if (st->pos != 0) {
  6039. /* Positioned boxes establish the containing block for their
  6040. * absolutely positioned descendants. */
  6041. l->cb_left = l0;
  6042. l->cb_right = r0;
  6043. l->cb_top = top;
  6044. }
  6045. if (l->draw && block_h[node] &&
  6046. top < page_rect.y + page_rect.h &&
  6047. top + block_h[node] > page_rect.y) {
  6048. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  6049. int rtl = css_radius(st, 0, box.w, box.h);
  6050. int rtr = css_radius(st, 1, box.w, box.h);
  6051. int rbr = css_radius(st, 2, box.w, box.h);
  6052. int rbl = css_radius(st, 3, box.w, box.h);
  6053. if (st->transform_scale) {
  6054. if (st->has_bg)
  6055. fill_transformed_rect(l->ui, box, st->bg, st);
  6056. } else if (rtl || rtr || rbr || rbl) {
  6057. if (st->has_bg) {
  6058. int bw = st->border_w[0];
  6059. if (bw > 0 && !st->border_t[0] &&
  6060. st->border_c[0] != st->bg &&
  6061. box.w > bw * 2 && box.h > bw * 2) {
  6062. struct ngui_rect inner = {
  6063. box.x + bw, box.y + bw,
  6064. box.w - bw * 2, box.h - bw * 2
  6065. };
  6066. int itl = rtl > bw ? rtl - bw : 0;
  6067. int itr = rtr > bw ? rtr - bw : 0;
  6068. int ibr = rbr > bw ? rbr - bw : 0;
  6069. int ibl = rbl > bw ? rbl - bw : 0;
  6070. ngui_fill_round_rect(l->ui, box, rtl,
  6071. rtr, rbr, rbl,
  6072. st->border_c[0]);
  6073. ngui_fill_round_rect(l->ui, inner,
  6074. itl, itr, ibr,
  6075. ibl, st->bg);
  6076. } else {
  6077. ngui_fill_round_rect(l->ui, box, rtl,
  6078. rtr, rbr, rbl,
  6079. st->bg);
  6080. }
  6081. } else if (st->border_w[0] && !st->border_t[0]) {
  6082. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  6083. rbl, st->border_w[0],
  6084. st->border_c[0]);
  6085. }
  6086. /* Rounded boxes paint their background image too
  6087. * (app icons are rounded squares), kept inside the
  6088. * corner arcs. */
  6089. if (st->bg_image)
  6090. draw_bg_image_round(l, box, node, st, rtl, rtr,
  6091. rbr, rbl);
  6092. } else {
  6093. if (st->has_bg)
  6094. ngui_fill_rect(l->ui, box, st->bg);
  6095. if (st->bg_image)
  6096. draw_bg_image(l, box, node, st);
  6097. if (st->border_w[0] || st->border_w[1] ||
  6098. st->border_w[2] || st->border_w[3])
  6099. draw_border_box(l->ui, box, st);
  6100. }
  6101. }
  6102. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  6103. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  6104. content_w, img_dh);
  6105. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  6106. l->ui && l->ui->nclip < 4) {
  6107. clip_rect.x = l0 + bl;
  6108. clip_rect.y = top + bt;
  6109. clip_rect.w = (r0 - l0) - bl - br;
  6110. clip_rect.h = (int)block_h[node] - bt - bb;
  6111. if (clip_rect.w > 0 && clip_rect.h > 0) {
  6112. ngui_push_clip(l->ui, clip_rect);
  6113. clip_pushed = 1;
  6114. }
  6115. }
  6116. l->left = l0 + bl + pl;
  6117. l->right = l->left + content_w;
  6118. if (l->right < l->left + 8)
  6119. l->right = l->left + 8;
  6120. l->align = st->align;
  6121. l->line_left = l->left;
  6122. l->line_right = l->right;
  6123. l->y = top + bt + pt;
  6124. if (doc.nodes[node].tag == BR_TAG_HR) {
  6125. if (l->draw)
  6126. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  6127. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  6128. l->y += 8;
  6129. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  6130. int vw = l->right - l->left;
  6131. int vh;
  6132. if (doc.nodes[node].width_pct)
  6133. vw = vw * doc.nodes[node].width_attr / 100;
  6134. else if (doc.nodes[node].width_attr)
  6135. vw = doc.nodes[node].width_attr;
  6136. if (vw > l->right - l->left)
  6137. vw = l->right - l->left;
  6138. if (vw < 8)
  6139. vw = 8;
  6140. vh = vw * 9 / 16;
  6141. if (vh > 240)
  6142. vh = 240;
  6143. if (vh < 80)
  6144. vh = 80;
  6145. if (l->draw) {
  6146. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  6147. vw, vh}, 0xD69A);
  6148. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  6149. vw, vh}, 0x8410);
  6150. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  6151. 0x4208);
  6152. }
  6153. l->y += vh + 4;
  6154. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  6155. int dw, dh, cw = l->right - l->left;
  6156. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  6157. if (l->draw && l->y < page_rect.y + page_rect.h &&
  6158. l->y + dh > page_rect.y)
  6159. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  6160. l->y += dh;
  6161. } else {
  6162. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  6163. !st->no_bullet) {
  6164. char *m = li_marker[node];
  6165. if (!m[0]) {
  6166. unsigned int parent = doc.nodes[node].parent;
  6167. int style = st->list_style;
  6168. int idx = parent ? list_index(parent, node) : 1;
  6169. if (style == BR_LIST_AUTO)
  6170. style = (parent &&
  6171. doc.nodes[parent].tag ==
  6172. BR_TAG_OL) ?
  6173. BR_LIST_DECIMAL : BR_LIST_DISC;
  6174. list_marker_text(m, sizeof(li_marker[node]),
  6175. style, idx);
  6176. }
  6177. if (l->draw && m[0]) {
  6178. int mw = (int)ngui_text_width_ui(l->ui, m);
  6179. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  6180. st->color);
  6181. }
  6182. }
  6183. if (doc.nodes[node].tag == BR_TAG_TR)
  6184. layout_table_row(l, node, st, depth + 1, link);
  6185. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  6186. table_has_rowspan(node))
  6187. layout_table(l, node, st, depth + 1, link);
  6188. else if (st->grid_auto)
  6189. layout_grid_auto(l, node, st, depth + 1, link);
  6190. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  6191. st->grid_gap > 0)
  6192. layout_grid_children(l, node, st, depth + 1, link);
  6193. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  6194. flex_wants_row(node, st))
  6195. layout_flex_children(l, node, st, depth + 1, link);
  6196. else
  6197. layout_children(l, node, st, depth + 1, link);
  6198. }
  6199. flush_line(l);
  6200. if (clip_pushed)
  6201. ngui_pop_clip(l->ui);
  6202. if (l->float_active) {
  6203. if (l->y < l->float_bottom)
  6204. l->y = l->float_bottom;
  6205. l->float_active = 0;
  6206. }
  6207. if (doc.nodes[node].tag == BR_TAG_IMG) {
  6208. content_h = img_dh;
  6209. } else if (st->height_kind &&
  6210. !((doc.nodes[node].tag == BR_TAG_HTML ||
  6211. doc.nodes[node].tag == BR_TAG_BODY) &&
  6212. st->height_kind == 2)) {
  6213. content_h = style_height_px(st, cbw);
  6214. if (st->box_sizing)
  6215. content_h -= deco_h;
  6216. } else {
  6217. /* Percentage heights on html/body resolve against the
  6218. * viewport, but their content still defines the document
  6219. * scroll height. Treating them as auto avoids collapsing
  6220. * the measured page to the containing block width. */
  6221. content_h = l->y - (top + bt + pt);
  6222. }
  6223. if (content_h < 0)
  6224. content_h = 0;
  6225. if (st->max_height_kind) {
  6226. int mh = st->max_height_kind == 3 ?
  6227. cbw * st->max_height_calc_pct / 100 +
  6228. st->max_height_calc_px :
  6229. css_size(st->max_height_kind, st->max_height, cbw);
  6230. int max_box = st->box_sizing ? mh : mh + deco_h;
  6231. if (content_h + deco_h > max_box)
  6232. content_h = max_box - deco_h;
  6233. }
  6234. if (st->min_height_kind &&
  6235. !((doc.nodes[node].tag == BR_TAG_HTML ||
  6236. doc.nodes[node].tag == BR_TAG_BODY) &&
  6237. st->min_height_kind == 2)) {
  6238. int mh = st->min_height_kind == 3 ?
  6239. cbw * st->min_height_calc_pct / 100 +
  6240. st->min_height_calc_px :
  6241. css_size(st->min_height_kind, st->min_height, cbw);
  6242. int min_box = st->box_sizing ? mh : mh + deco_h;
  6243. if (content_h + deco_h < min_box)
  6244. content_h = min_box - deco_h;
  6245. }
  6246. if (content_h < 0)
  6247. content_h = 0;
  6248. box_h = deco_h + content_h;
  6249. if (box_h < 0)
  6250. box_h = 0;
  6251. l->y = (shifted ? normal_top : top) + box_h;
  6252. if (node < BR_MAX_NODES) {
  6253. layout_boxes[node].x = l0;
  6254. layout_boxes[node].y = top;
  6255. layout_boxes[node].w = r0 - l0;
  6256. layout_boxes[node].h = box_h;
  6257. layout_boxes[node].valid = r0 > l0;
  6258. }
  6259. l->left = old_left;
  6260. l->right = old_right;
  6261. l->align = old_align;
  6262. l->y += mp_px(st, 2, cbw);
  6263. if (!l->draw) {
  6264. if (box_h > 65535)
  6265. box_h = 65535;
  6266. block_h[node] = (unsigned short)box_h;
  6267. block_top[node] = (unsigned short)(top < 0 ? 0 :
  6268. top > 65535 ? 65535 : top);
  6269. }
  6270. if (positioned) {
  6271. l->y = flow_y;
  6272. l->left = flow_left;
  6273. l->right = flow_right;
  6274. }
  6275. l->parent_top = saved_parent_top;
  6276. l->cb_left = saved_cb_left;
  6277. l->cb_right = saved_cb_right;
  6278. l->cb_top = saved_cb_top;
  6279. }
  6280. static int text_node_blank(const struct br_node *nd)
  6281. {
  6282. const char *t = doc.text + nd->text_off;
  6283. unsigned int i;
  6284. for (i = 0; i < nd->text_len; i++)
  6285. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  6286. t[i] != '\r')
  6287. return 0;
  6288. return 1;
  6289. }
  6290. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  6291. * text/image widths in the subtree, plus padding and margins. This keeps
  6292. * Bootstrap's floated nav items on one line instead of giving each the whole
  6293. * row. */
  6294. static int text_space(char c)
  6295. {
  6296. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  6297. }
  6298. static int intrinsic_width(struct ngui *ui, unsigned int node,
  6299. const struct br_style *pst, int depth, int base)
  6300. {
  6301. unsigned int c;
  6302. int line_w = 0, max_w = 0;
  6303. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  6304. if (depth > 32)
  6305. return 0;
  6306. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  6307. struct br_node *nd = &doc.nodes[c];
  6308. struct br_style cs;
  6309. if (nd->type == BR_NODE_TEXT) {
  6310. const char *t = doc.text + nd->text_off;
  6311. unsigned int tn = nd->text_len;
  6312. if (doc.nodes[node].tag == BR_TAG_PRE) {
  6313. line_w += (int)face_text_width(ui, pst, t, tn);
  6314. } else {
  6315. unsigned int ti = 0;
  6316. int first = 1;
  6317. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  6318. int sp = (int)face_text_width(ui, pst, " ", 1);
  6319. while (ti < tn) {
  6320. unsigned int ts;
  6321. while (ti < tn && text_space(t[ti]))
  6322. ti++;
  6323. ts = ti;
  6324. while (ti < tn && !text_space(t[ti]))
  6325. ti++;
  6326. if (ti == ts)
  6327. break;
  6328. if (!first || lead)
  6329. line_w += sp;
  6330. lead = 0;
  6331. line_w += (int)face_text_width(ui, pst,
  6332. t + ts, ti - ts);
  6333. first = 0;
  6334. }
  6335. }
  6336. continue;
  6337. }
  6338. br_style_for(&doc, c, pst, &cs);
  6339. if (cs.display == BR_DISPLAY_NONE)
  6340. continue;
  6341. if (nd->tag == BR_TAG_BR) {
  6342. if (line_w > max_w)
  6343. max_w = line_w;
  6344. line_w = 0;
  6345. continue;
  6346. }
  6347. if (nd->tag == BR_TAG_IMG) {
  6348. /* Measure the image as layout will draw it: a CSS or
  6349. * attribute height keeps the intrinsic aspect ratio, and
  6350. * a CSS width overrides the native pixel width. Bootstrap
  6351. * sizes the Cloudron logo with height:40px only. */
  6352. int idx = nd->img_index;
  6353. int iw = 0, ih = 0;
  6354. if (idx >= 0 && idx < image_count &&
  6355. images[idx].state == 1) {
  6356. iw = (int)images[idx].native_w;
  6357. ih = (int)images[idx].native_h;
  6358. if (iw <= 0 || ih <= 0) {
  6359. iw = (int)images[idx].img.w;
  6360. ih = (int)images[idx].img.h;
  6361. }
  6362. }
  6363. if (cs.width_kind) {
  6364. int ww = style_width_px(&cs, base);
  6365. line_w += ww > 0 ? ww : 64;
  6366. } else if (nd->width_attr) {
  6367. line_w += nd->width_attr;
  6368. } else if (nd->height_attr && iw && ih) {
  6369. line_w += iw * (int)nd->height_attr / ih;
  6370. } else if (cs.height_kind && iw && ih) {
  6371. int hh = style_height_px(&cs, base);
  6372. line_w += hh > 0 ? iw * hh / ih : iw;
  6373. } else if (iw) {
  6374. line_w += iw;
  6375. } else {
  6376. line_w += 64;
  6377. }
  6378. continue;
  6379. }
  6380. {
  6381. int cw = mp_px(&cs, 7, base) +
  6382. mp_px(&cs, 5, base) +
  6383. mp_px(&cs, 3, base) +
  6384. mp_px(&cs, 1, base) +
  6385. cs.border_w[1] + cs.border_w[3];
  6386. /* width/height do not apply to non-replaced inline
  6387. * boxes. The tagesschau home label is an inline span
  6388. * with width:1px for the mobile icon-only header; using
  6389. * that width made the whole subnav collapse to a
  6390. * one-character column. */
  6391. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  6392. cw += cs.width_kind == 1 ? cs.width :
  6393. style_width_px(&cs, base);
  6394. else
  6395. cw += intrinsic_width(ui, c, &cs, depth + 1,
  6396. base);
  6397. if (flex_row || cs.float_left ||
  6398. cs.display == BR_DISPLAY_INLINE ||
  6399. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  6400. line_w += cw;
  6401. } else {
  6402. if (line_w > max_w)
  6403. max_w = line_w;
  6404. line_w = 0;
  6405. if (cw > max_w)
  6406. max_w = cw;
  6407. }
  6408. }
  6409. if (line_w > 4096 || max_w > 4096)
  6410. break;
  6411. }
  6412. return line_w > max_w ? line_w : max_w;
  6413. }
  6414. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  6415. * the main user: .row > .col-md-* with float:left and a percentage width.
  6416. * Each column is laid out with its own left/right edge and the row advances
  6417. * to the tallest column. Returns the first child not consumed. */
  6418. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  6419. const struct br_style *pst, int depth,
  6420. unsigned short link)
  6421. {
  6422. unsigned int n = first;
  6423. int row_left = l->left, row_right = l->right;
  6424. int row_top, row_bottom, xl, xr, any = 0;
  6425. int fl_left = row_left, fl_right = row_right, fl_bottom;
  6426. flush_line(l);
  6427. row_top = l->y;
  6428. row_bottom = l->y;
  6429. fl_bottom = row_top;
  6430. xl = row_left;
  6431. xr = row_right;
  6432. while (n) {
  6433. struct br_node *nd = &doc.nodes[n];
  6434. struct br_style cs;
  6435. unsigned short lk = link;
  6436. int colw, right;
  6437. if (nd->type == BR_NODE_TEXT) {
  6438. if (text_node_blank(nd)) {
  6439. n = nd->next;
  6440. continue;
  6441. }
  6442. break;
  6443. }
  6444. br_style_for(&doc, n, pst, &cs);
  6445. if (cs.display == BR_DISPLAY_NONE) {
  6446. n = nd->next;
  6447. continue;
  6448. }
  6449. /* A float blockifies its box: Bootstrap floats inline
  6450. * anchors too (the navbar brand and its text links), and
  6451. * their padding must be honoured. */
  6452. if (!cs.float_left)
  6453. break;
  6454. if (nd->tag == BR_TAG_A && nd->href_off)
  6455. lk = (unsigned short)n;
  6456. right = cs.float_left == 2;
  6457. if (cs.width_kind == 2 || cs.width_kind == 3) {
  6458. colw = style_width_px(&cs, row_right - row_left);
  6459. } else if (cs.width_kind == 1) {
  6460. colw = (int)cs.width;
  6461. } else {
  6462. int base = row_right - row_left;
  6463. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  6464. mp_px(&cs, 7, base) +
  6465. mp_px(&cs, 5, base) +
  6466. mp_px(&cs, 3, base) +
  6467. mp_px(&cs, 1, base);
  6468. if (colw < 8)
  6469. colw = 8;
  6470. }
  6471. if (colw < 8)
  6472. colw = 8;
  6473. if (colw > row_right - row_left)
  6474. colw = row_right - row_left;
  6475. /* The float column width is already resolved. */
  6476. cs.width_kind = 0;
  6477. cs.max_width_kind = 0;
  6478. if (right) {
  6479. if (any && xr - colw < xl) {
  6480. row_top = row_bottom;
  6481. row_bottom = row_top;
  6482. xl = row_left;
  6483. xr = row_right;
  6484. }
  6485. if (xr - colw < xl)
  6486. colw = xr - xl;
  6487. if (colw < 8)
  6488. colw = 8;
  6489. l->left = xr - colw;
  6490. if (l->left < row_left)
  6491. l->left = row_left;
  6492. l->right = xr;
  6493. xr = l->left;
  6494. if (xr < fl_right)
  6495. fl_right = xr;
  6496. } else {
  6497. if (any && xl + colw > xr) {
  6498. row_top = row_bottom;
  6499. row_bottom = row_top;
  6500. xl = row_left;
  6501. xr = row_right;
  6502. }
  6503. l->left = xl;
  6504. l->right = xl + colw;
  6505. xl += colw;
  6506. if (xl > fl_left)
  6507. fl_left = xl;
  6508. }
  6509. if (l->right < l->left + 8)
  6510. l->right = l->left + 8;
  6511. l->y = row_top;
  6512. l->line_x = l->left;
  6513. l->run_x = l->left;
  6514. l->line_y = l->y;
  6515. l->line_h = 0;
  6516. l->nruns = 0;
  6517. l->space_pending = 0;
  6518. l->align = cs.align;
  6519. layout_block(l, n, &cs, depth + 1, lk);
  6520. if (l->y > row_bottom)
  6521. row_bottom = l->y;
  6522. if (l->y > fl_bottom)
  6523. fl_bottom = l->y;
  6524. any = 1;
  6525. n = nd->next;
  6526. }
  6527. l->left = row_left;
  6528. l->right = row_right;
  6529. if (n && any) {
  6530. struct br_node *nd = &doc.nodes[n];
  6531. int inline_next = 0;
  6532. if (nd->type == BR_NODE_TEXT) {
  6533. inline_next = 1;
  6534. } else if (nd->type == BR_NODE_ELEM) {
  6535. struct br_style cs;
  6536. br_style_for(&doc, n, pst, &cs);
  6537. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  6538. cs.display != BR_DISPLAY_NONE &&
  6539. !br_tag_is_block(nd->tag);
  6540. }
  6541. if (inline_next) {
  6542. if (l->float_active) {
  6543. if (l->float_left > fl_left)
  6544. fl_left = l->float_left;
  6545. if (l->float_right < fl_right)
  6546. fl_right = l->float_right;
  6547. if (l->float_bottom > fl_bottom)
  6548. fl_bottom = l->float_bottom;
  6549. }
  6550. l->float_active = 1;
  6551. l->float_left = fl_left;
  6552. l->float_right = fl_right;
  6553. l->float_bottom = fl_bottom;
  6554. l->y = row_top;
  6555. } else {
  6556. l->float_active = 0;
  6557. l->y = row_bottom;
  6558. }
  6559. } else {
  6560. l->float_active = 0;
  6561. l->y = row_bottom;
  6562. }
  6563. l->line_x = l->left;
  6564. l->run_x = l->left;
  6565. l->line_left = l->left;
  6566. l->line_right = l->right;
  6567. l->line_y = l->y;
  6568. l->line_h = 0;
  6569. l->nruns = 0;
  6570. l->space_pending = 0;
  6571. return n;
  6572. }
  6573. static int flex_item_width(struct lay *l, unsigned int n,
  6574. const struct br_style *cs, int avail)
  6575. {
  6576. struct br_node *nd = &doc.nodes[n];
  6577. (void)l;
  6578. int w;
  6579. if (cs->width_kind == 2 || cs->width_kind == 3)
  6580. w = style_width_px(cs, avail);
  6581. else if (cs->width_kind == 1)
  6582. w = (int)cs->width;
  6583. else if (nd->tag == BR_TAG_IMG) {
  6584. int idx = nd->img_index;
  6585. if (idx >= 0 && idx < image_count &&
  6586. images[idx].state == 1)
  6587. w = (int)images[idx].img.w;
  6588. else if (nd->width_attr)
  6589. w = (int)nd->width_attr;
  6590. else
  6591. w = 64;
  6592. } else {
  6593. w = intrinsic_width(l->ui, n, cs, 0, avail);
  6594. }
  6595. /* Explicit widths are content-box sizes; the flex item's outer width
  6596. * must include padding, borders and margins. */
  6597. w += mp_px(cs, 7, avail);
  6598. w += mp_px(cs, 5, avail);
  6599. w += mp_px(cs, 3, avail);
  6600. w += mp_px(cs, 1, avail);
  6601. w += cs->border_w[1] + cs->border_w[3];
  6602. if (w < 24)
  6603. w = 24;
  6604. if (w > avail)
  6605. w = avail;
  6606. return w;
  6607. }
  6608. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  6609. * on one line, not one full-width block each. Place intrinsic widths from
  6610. * left to right and wrap when the row is full. */
  6611. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  6612. const struct br_style *pst, int depth,
  6613. unsigned short link)
  6614. {
  6615. unsigned int n = first;
  6616. int row_left = l->left, row_right = l->right;
  6617. int avail = row_right - row_left;
  6618. int x = row_left, y = l->y, row_h = 0, any = 0;
  6619. flush_line(l);
  6620. y = l->y;
  6621. while (n) {
  6622. struct br_node *nd = &doc.nodes[n];
  6623. struct br_style cs;
  6624. unsigned short lk = link;
  6625. int colw, h;
  6626. if (nd->type == BR_NODE_TEXT) {
  6627. if (!text_node_blank(nd))
  6628. break;
  6629. if (any)
  6630. x += 4;
  6631. n = nd->next;
  6632. continue;
  6633. }
  6634. br_style_for(&doc, n, pst, &cs);
  6635. if (cs.display == BR_DISPLAY_NONE) {
  6636. n = nd->next;
  6637. continue;
  6638. }
  6639. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  6640. break;
  6641. if (nd->tag == BR_TAG_A && nd->href_off)
  6642. lk = (unsigned short)n;
  6643. colw = flex_item_width(l, n, &cs, avail);
  6644. /* A few pixels of slack keep a single long token (boot.S)
  6645. * from wrapping at the exact content width. */
  6646. colw += 8;
  6647. if (colw > avail)
  6648. colw = avail;
  6649. cs.width_kind = 0;
  6650. cs.max_width_kind = 0;
  6651. if (any && x + colw > row_right) {
  6652. y += row_h + 2;
  6653. x = row_left;
  6654. row_h = 0;
  6655. any = 0;
  6656. }
  6657. if (any && x > row_left)
  6658. x += 4;
  6659. l->left = x;
  6660. l->right = x + colw;
  6661. if (l->right < l->left + 8)
  6662. l->right = l->left + 8;
  6663. l->y = y;
  6664. l->line_x = l->left;
  6665. l->run_x = l->left;
  6666. l->line_y = l->y;
  6667. l->line_h = 0;
  6668. l->nruns = 0;
  6669. l->space_pending = 0;
  6670. l->align = cs.align;
  6671. layout_block(l, n, &cs, depth + 1, lk);
  6672. h = l->y - y;
  6673. if (h > row_h)
  6674. row_h = h;
  6675. x += colw;
  6676. any = 1;
  6677. n = nd->next;
  6678. }
  6679. if (any)
  6680. y += row_h;
  6681. l->left = row_left;
  6682. l->right = row_right;
  6683. l->y = y;
  6684. l->line_x = l->left;
  6685. l->run_x = l->left;
  6686. l->line_y = l->y;
  6687. l->line_h = 0;
  6688. l->nruns = 0;
  6689. l->space_pending = 0;
  6690. return n;
  6691. }
  6692. struct flex_item {
  6693. unsigned int node;
  6694. unsigned short link;
  6695. int w;
  6696. };
  6697. static void layout_flex_children(struct lay *l, unsigned int parent,
  6698. const struct br_style *pst, int depth,
  6699. unsigned short link)
  6700. {
  6701. struct flex_item it[32];
  6702. unsigned int c;
  6703. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  6704. int row_left = l->left, row_right = l->right;
  6705. int avail = row_right - row_left;
  6706. int idx, row_top;
  6707. if (avail < 160 || depth > 48) {
  6708. layout_children(l, parent, pst, depth, link);
  6709. return;
  6710. }
  6711. /* If direct text is not just whitespace, normal block flow handles it
  6712. * better than pretending it is a flex item. */
  6713. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  6714. struct br_node *nd = &doc.nodes[c];
  6715. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  6716. layout_children(l, parent, pst, depth, link);
  6717. return;
  6718. }
  6719. }
  6720. for (c = doc.nodes[parent].first;
  6721. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  6722. c = doc.nodes[c].next) {
  6723. struct br_node *nd = &doc.nodes[c];
  6724. struct br_style cs;
  6725. if (nd->type == BR_NODE_TEXT)
  6726. continue;
  6727. br_style_for(&doc, c, pst, &cs);
  6728. if (cs.display == BR_DISPLAY_NONE)
  6729. continue;
  6730. it[nitem].node = c;
  6731. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  6732. (unsigned short)c : link;
  6733. it[nitem].w = 0;
  6734. if (cs.flex_grow && !cs.width_kind)
  6735. grow_count++;
  6736. else
  6737. fixed += flex_item_width(l, c, &cs, avail);
  6738. nitem++;
  6739. }
  6740. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  6741. if (grow_w < 96)
  6742. grow_w = 96;
  6743. for (idx = 0; idx < nitem; idx++) {
  6744. struct br_style cs;
  6745. br_style_for(&doc, it[idx].node, pst, &cs);
  6746. if (cs.flex_grow && !cs.width_kind)
  6747. it[idx].w = grow_w;
  6748. else
  6749. it[idx].w = flex_item_width(l, it[idx].node, &cs, avail);
  6750. if (it[idx].w > avail)
  6751. it[idx].w = avail;
  6752. if (it[idx].w < 8)
  6753. it[idx].w = 8;
  6754. }
  6755. row_top = l->y;
  6756. idx = 0;
  6757. while (idx < nitem) {
  6758. int start = idx, count = 0, row_w = 0;
  6759. int free_w, x, extra = 0, row_h = 0, k;
  6760. while (idx < nitem) {
  6761. int add = it[idx].w + (count ? gap : 0);
  6762. /* CSS default is nowrap; only flex-wrap: wrap (1)
  6763. * starts a new row. */
  6764. if (count && pst->flex_wrap == 1 &&
  6765. row_w + add > avail)
  6766. break;
  6767. row_w += add;
  6768. count++;
  6769. idx++;
  6770. }
  6771. if (!count) {
  6772. count = 1;
  6773. row_w = it[start].w;
  6774. idx = start + 1;
  6775. }
  6776. free_w = avail - row_w;
  6777. if (free_w < 0)
  6778. free_w = 0;
  6779. x = row_left;
  6780. if (pst->justify == 1) {
  6781. x += free_w / 2;
  6782. } else if (pst->justify == 2) {
  6783. x += free_w;
  6784. } else if (pst->justify == 3) {
  6785. extra = count > 1 ? free_w / (count - 1) : 0;
  6786. } else if (pst->justify == 4) {
  6787. extra = count ? free_w / count : 0;
  6788. x += extra / 2;
  6789. } else if (pst->justify == 5) {
  6790. extra = count ? free_w / (count + 1) : 0;
  6791. x += extra;
  6792. }
  6793. for (k = 0; k < count; k++) {
  6794. int node = (int)it[start + k].node;
  6795. int h = block_h[node];
  6796. if (h > row_h)
  6797. row_h = h;
  6798. }
  6799. if (pst->height_kind) {
  6800. int hh = style_height_px(pst, avail);
  6801. if (hh > row_h)
  6802. row_h = hh;
  6803. }
  6804. for (k = 0; k < count; k++) {
  6805. struct br_style cs;
  6806. int node = (int)it[start + k].node;
  6807. int yoff = 0;
  6808. br_style_for(&doc, node, pst, &cs);
  6809. cs.width_kind = 0;
  6810. cs.max_width_kind = 0;
  6811. if (l->draw && pst->align_items &&
  6812. row_h > block_h[node]) {
  6813. if (pst->align_items == 1)
  6814. yoff = (row_h - block_h[node]) / 2;
  6815. else if (pst->align_items == 2)
  6816. yoff = row_h - block_h[node];
  6817. }
  6818. l->left = x;
  6819. l->right = x + it[start + k].w;
  6820. if (l->right < l->left + 8)
  6821. l->right = l->left + 8;
  6822. l->y = row_top + yoff;
  6823. l->line_x = l->left;
  6824. l->run_x = l->left;
  6825. l->line_y = l->y;
  6826. l->line_h = 0;
  6827. l->nruns = 0;
  6828. l->space_pending = 0;
  6829. l->align = cs.align;
  6830. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  6831. if (!l->draw) {
  6832. int h = l->y - row_top;
  6833. if (h > row_h)
  6834. row_h = h;
  6835. }
  6836. x += it[start + k].w;
  6837. if (k + 1 < count)
  6838. x += gap + extra;
  6839. }
  6840. row_top += row_h;
  6841. }
  6842. l->left = row_left;
  6843. l->right = row_right;
  6844. l->y = row_top;
  6845. l->line_x = l->left;
  6846. l->run_x = l->left;
  6847. l->line_y = l->y;
  6848. l->line_h = 0;
  6849. l->nruns = 0;
  6850. l->space_pending = 0;
  6851. }
  6852. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  6853. * plus the grid-area hints used by site shells (site notice/footer full
  6854. * width, column-start left, page-content right). Anything more elaborate
  6855. * falls back to normal block flow. */
  6856. static int grid_track_width(unsigned char kind, unsigned short val,
  6857. int avail, int other)
  6858. {
  6859. if (kind == 2)
  6860. return avail * (int)val / 100;
  6861. if (kind == 1)
  6862. return val;
  6863. return other;
  6864. }
  6865. static void layout_grid_children(struct lay *l, unsigned int parent,
  6866. const struct br_style *pst, int depth,
  6867. unsigned short link)
  6868. {
  6869. unsigned int n;
  6870. int row_left = l->left, row_right = l->right;
  6871. int avail = row_right - row_left;
  6872. int gap = pst->grid_gap;
  6873. int track_total = avail - gap;
  6874. int col0, col1, x0, x1;
  6875. int row_y, row_bottom, have_left = 0, have_right = 0;
  6876. unsigned int c;
  6877. if (avail < 32 || depth > 48)
  6878. return;
  6879. if (track_total < 16)
  6880. track_total = 16;
  6881. col0 = grid_track_width((unsigned char)(pst->width_kind),
  6882. pst->width, track_total, 0);
  6883. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  6884. pst->max_width, track_total, 0);
  6885. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  6886. int w0 = pst->width ? pst->width : 1;
  6887. int w1 = pst->max_width ? pst->max_width : 1;
  6888. col0 = track_total * w0 / (w0 + w1);
  6889. col1 = track_total - col0;
  6890. } else if (pst->width_kind == 3) {
  6891. col0 = track_total - col1;
  6892. if (col0 < 24)
  6893. col0 = 24;
  6894. } else if (pst->max_width_kind == 3) {
  6895. col1 = track_total - col0;
  6896. if (col1 < 24)
  6897. col1 = 24;
  6898. }
  6899. if (col0 < 24)
  6900. col0 = 24;
  6901. if (col1 < 24)
  6902. col1 = 24;
  6903. if (col0 + col1 > track_total) {
  6904. col1 = track_total - col0;
  6905. if (col1 < 24)
  6906. col1 = 24;
  6907. }
  6908. x0 = row_left;
  6909. x1 = row_left + col0 + gap;
  6910. /* Direct text makes a grid ambiguous; use block flow instead. */
  6911. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  6912. struct br_node *nd = &doc.nodes[c];
  6913. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  6914. layout_children(l, parent, pst, depth, link);
  6915. return;
  6916. }
  6917. }
  6918. row_y = row_bottom = l->y;
  6919. n = doc.nodes[parent].first;
  6920. while (n) {
  6921. struct br_node *nd = &doc.nodes[n];
  6922. struct br_style cs;
  6923. unsigned short lk = link;
  6924. int slot, x, w;
  6925. if (nd->type == BR_NODE_TEXT) {
  6926. n = nd->next;
  6927. continue;
  6928. }
  6929. br_style_for(&doc, n, pst, &cs);
  6930. if (cs.display == BR_DISPLAY_NONE) {
  6931. n = nd->next;
  6932. continue;
  6933. }
  6934. if (nd->tag == BR_TAG_A && nd->href_off)
  6935. lk = (unsigned short)n;
  6936. slot = cs.grid_slot;
  6937. if (!slot) {
  6938. if (!have_left)
  6939. slot = 2;
  6940. else if (!have_right)
  6941. slot = 3;
  6942. else
  6943. slot = 2;
  6944. }
  6945. if (slot == 1) {
  6946. if (have_left || have_right) {
  6947. row_y = row_bottom;
  6948. have_left = have_right = 0;
  6949. }
  6950. x = row_left;
  6951. w = avail;
  6952. } else if (slot == 2) {
  6953. if (have_left) {
  6954. row_y = row_bottom;
  6955. have_left = have_right = 0;
  6956. }
  6957. x = x0;
  6958. w = col0;
  6959. have_left = 1;
  6960. } else {
  6961. if (have_right) {
  6962. row_y = row_bottom;
  6963. have_left = have_right = 0;
  6964. }
  6965. x = x1;
  6966. w = col1;
  6967. have_right = 1;
  6968. }
  6969. cs.width_kind = 0;
  6970. cs.max_width_kind = 0;
  6971. l->left = x;
  6972. l->right = x + w;
  6973. if (l->right < l->left + 8)
  6974. l->right = l->left + 8;
  6975. l->y = row_y;
  6976. l->line_x = l->left;
  6977. l->run_x = l->left;
  6978. l->line_y = l->y;
  6979. l->line_h = 0;
  6980. l->nruns = 0;
  6981. l->space_pending = 0;
  6982. l->align = cs.align;
  6983. layout_block(l, n, &cs, depth + 1, lk);
  6984. if (l->y > row_bottom)
  6985. row_bottom = l->y;
  6986. n = nd->next;
  6987. }
  6988. l->left = row_left;
  6989. l->right = row_right;
  6990. l->y = row_bottom;
  6991. l->line_x = l->left;
  6992. l->run_x = l->left;
  6993. l->line_y = l->y;
  6994. l->line_h = 0;
  6995. l->nruns = 0;
  6996. l->space_pending = 0;
  6997. }
  6998. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  6999. * capped at four. Used by the project docs' card grids. */
  7000. static void layout_grid_auto(struct lay *l, unsigned int parent,
  7001. const struct br_style *pst, int depth,
  7002. unsigned short link)
  7003. {
  7004. unsigned int n, c;
  7005. int row_left = l->left, row_right = l->right;
  7006. int avail = row_right - row_left;
  7007. int gap = pst->grid_gap;
  7008. int minw = pst->width_kind == 1 ? pst->width : 200;
  7009. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  7010. if (avail < 32 || depth > 48) {
  7011. layout_children(l, parent, pst, depth, link);
  7012. return;
  7013. }
  7014. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7015. struct br_node *nd = &doc.nodes[c];
  7016. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7017. layout_children(l, parent, pst, depth, link);
  7018. return;
  7019. }
  7020. }
  7021. if (minw < 80)
  7022. minw = 80;
  7023. ncols = (avail + gap) / (minw + gap);
  7024. if (ncols < 1)
  7025. ncols = 1;
  7026. if (ncols > 4)
  7027. ncols = 4;
  7028. colw = (avail - gap * (ncols - 1)) / ncols;
  7029. if (colw < 24)
  7030. colw = 24;
  7031. x = row_left;
  7032. n = doc.nodes[parent].first;
  7033. while (n) {
  7034. struct br_node *nd = &doc.nodes[n];
  7035. struct br_style cs;
  7036. unsigned short lk = link;
  7037. int h;
  7038. if (nd->type == BR_NODE_TEXT) {
  7039. n = nd->next;
  7040. continue;
  7041. }
  7042. br_style_for(&doc, n, pst, &cs);
  7043. if (cs.display == BR_DISPLAY_NONE) {
  7044. n = nd->next;
  7045. continue;
  7046. }
  7047. if (nd->tag == BR_TAG_A && nd->href_off)
  7048. lk = (unsigned short)n;
  7049. cs.width_kind = 0;
  7050. cs.max_width_kind = 0;
  7051. l->left = x;
  7052. l->right = x + colw;
  7053. if (l->right < l->left + 8)
  7054. l->right = l->left + 8;
  7055. l->y = y;
  7056. l->line_x = l->left;
  7057. l->run_x = l->left;
  7058. l->line_y = l->y;
  7059. l->line_h = 0;
  7060. l->nruns = 0;
  7061. l->space_pending = 0;
  7062. l->align = cs.align;
  7063. layout_block(l, n, &cs, depth + 1, lk);
  7064. h = l->y - y;
  7065. if (h > row_h)
  7066. row_h = h;
  7067. col++;
  7068. n = nd->next;
  7069. if (col == ncols) {
  7070. y += row_h + gap;
  7071. x = row_left;
  7072. row_h = 0;
  7073. col = 0;
  7074. } else {
  7075. x += colw + gap;
  7076. }
  7077. }
  7078. if (col)
  7079. y += row_h;
  7080. else if (y > start_y)
  7081. y -= gap;
  7082. l->left = row_left;
  7083. l->right = row_right;
  7084. l->y = y;
  7085. l->line_x = l->left;
  7086. l->run_x = l->left;
  7087. l->line_y = l->y;
  7088. l->line_h = 0;
  7089. l->nruns = 0;
  7090. l->space_pending = 0;
  7091. }
  7092. /* Column widths are the widest cell in each column across every row, so all
  7093. * rows line up. The table model is still deliberately basic: no colspan,
  7094. * border-collapse or percentage columns. */
  7095. static void table_columns(struct lay *l, unsigned int table,
  7096. const struct br_style *pst, int avail,
  7097. int *raw, int maxcols, int *out_cols,
  7098. int *out_total)
  7099. {
  7100. unsigned int r, c;
  7101. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  7102. int fixed[12];
  7103. for (c = 0; c < (unsigned int)maxcols; c++) {
  7104. raw[c] = 0;
  7105. fixed[c] = 0;
  7106. }
  7107. /* Intrinsic widths of single-column cells. */
  7108. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7109. struct br_node *rn = &doc.nodes[r];
  7110. int col = 0;
  7111. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7112. continue;
  7113. for (c = rn->first; c; c = doc.nodes[c].next) {
  7114. struct br_node *cn = &doc.nodes[c];
  7115. struct br_style cs;
  7116. int w, span;
  7117. if (cn->type != BR_NODE_ELEM ||
  7118. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  7119. continue;
  7120. span = cn->colspan ? cn->colspan : 1;
  7121. br_style_for(&doc, c, pst, &cs);
  7122. if (cs.display == BR_DISPLAY_NONE)
  7123. continue;
  7124. if (col + span > maxcols)
  7125. span = maxcols - col;
  7126. if (span < 1)
  7127. break;
  7128. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  7129. mp_px(&cs, 7, avail) +
  7130. mp_px(&cs, 5, avail) +
  7131. mp_px(&cs, 3, avail) +
  7132. mp_px(&cs, 1, avail) +
  7133. cs.border_w[0] + cs.border_w[1] +
  7134. cs.border_w[2] + cs.border_w[3];
  7135. if (w < 24)
  7136. w = 24;
  7137. if (span == 1) {
  7138. if (w > raw[col])
  7139. raw[col] = w;
  7140. }
  7141. if (col + span > cols)
  7142. cols = col + span;
  7143. col += span;
  7144. }
  7145. }
  7146. /* A colspan cell only has to be as wide as the sum of its columns. */
  7147. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7148. struct br_node *rn = &doc.nodes[r];
  7149. int col = 0;
  7150. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7151. continue;
  7152. for (c = rn->first; c; c = doc.nodes[c].next) {
  7153. struct br_node *cn = &doc.nodes[c];
  7154. struct br_style cs;
  7155. int span, w, sum, i;
  7156. if (cn->type != BR_NODE_ELEM ||
  7157. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  7158. continue;
  7159. span = cn->colspan ? cn->colspan : 1;
  7160. if (col + span > maxcols)
  7161. span = maxcols - col;
  7162. if (span < 1)
  7163. break;
  7164. if (span > 1) {
  7165. br_style_for(&doc, c, pst, &cs);
  7166. if (cs.display != BR_DISPLAY_NONE) {
  7167. w = intrinsic_width(l->ui, c, &cs,
  7168. 0, avail) +
  7169. mp_px(&cs, 7, avail) +
  7170. mp_px(&cs, 5, avail) +
  7171. mp_px(&cs, 3, avail) +
  7172. mp_px(&cs, 1, avail) +
  7173. cs.border_w[0] + cs.border_w[1] +
  7174. cs.border_w[2] + cs.border_w[3];
  7175. sum = 0;
  7176. for (i = 0; i < span; i++)
  7177. sum += raw[col + i];
  7178. if (w > sum)
  7179. raw[col + span - 1] += w - sum;
  7180. }
  7181. }
  7182. col += span;
  7183. }
  7184. }
  7185. /* Explicit and percentage widths override intrinsic widths. */
  7186. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7187. struct br_node *rn = &doc.nodes[r];
  7188. int col = 0;
  7189. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7190. continue;
  7191. for (c = rn->first; c; c = doc.nodes[c].next) {
  7192. struct br_node *cn = &doc.nodes[c];
  7193. struct br_style cs;
  7194. int span;
  7195. if (cn->type != BR_NODE_ELEM ||
  7196. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  7197. continue;
  7198. span = cn->colspan ? cn->colspan : 1;
  7199. if (col + span > maxcols)
  7200. span = maxcols - col;
  7201. if (span < 1)
  7202. break;
  7203. if (span == 1) {
  7204. br_style_for(&doc, c, pst, &cs);
  7205. if (cs.display != BR_DISPLAY_NONE) {
  7206. if (cs.width_kind == 1) {
  7207. raw[col] = cs.width;
  7208. fixed[col] = 1;
  7209. } else if (cs.width_kind == 2 ||
  7210. cs.width_kind == 3) {
  7211. raw[col] = style_width_px(&cs,
  7212. avail);
  7213. fixed[col] = 1;
  7214. }
  7215. }
  7216. }
  7217. col += span;
  7218. }
  7219. }
  7220. for (c = 0; c < (unsigned int)cols; c++) {
  7221. if (raw[c] < 8)
  7222. raw[c] = 8;
  7223. total += raw[c];
  7224. if (fixed[c])
  7225. fixed_sum += raw[c];
  7226. else {
  7227. free_raw += raw[c];
  7228. free_cols++;
  7229. }
  7230. }
  7231. if (fixed_sum > 0 && fixed_sum < avail) {
  7232. int free_avail = avail - fixed_sum;
  7233. int i;
  7234. if (free_raw > 0) {
  7235. for (i = 0; i < cols; i++)
  7236. if (!fixed[i])
  7237. raw[i] = free_avail * raw[i] /
  7238. free_raw;
  7239. } else if (free_cols > 0) {
  7240. for (i = 0; i < cols; i++)
  7241. if (!fixed[i])
  7242. raw[i] = free_avail / free_cols;
  7243. }
  7244. total = 0;
  7245. for (i = 0; i < cols; i++)
  7246. total += raw[i];
  7247. } else if (total < avail && total > 0) {
  7248. int i;
  7249. for (i = 0; i < cols; i++)
  7250. raw[i] = raw[i] * avail / total;
  7251. total = 0;
  7252. for (i = 0; i < cols; i++)
  7253. total += raw[i];
  7254. }
  7255. *out_cols = cols;
  7256. *out_total = total;
  7257. }
  7258. static void layout_table_row(struct lay *l, unsigned int row,
  7259. const struct br_style *pst, int depth,
  7260. unsigned short link)
  7261. {
  7262. unsigned int n, cell[12];
  7263. int raw[12], colstart[12], colspan[12];
  7264. int prefix[13];
  7265. int ncell = 0, total = 0, cols = 0, col = 0;
  7266. int row_left = l->left, row_right = l->right;
  7267. int avail = row_right - row_left;
  7268. int y = l->y, bottom = l->y;
  7269. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  7270. struct br_node *nd = &doc.nodes[n];
  7271. struct br_style cs;
  7272. int span;
  7273. if (nd->type == BR_NODE_TEXT) {
  7274. if (text_node_blank(nd))
  7275. continue;
  7276. layout_children(l, row, pst, depth, link);
  7277. return;
  7278. }
  7279. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  7280. layout_children(l, row, pst, depth, link);
  7281. return;
  7282. }
  7283. br_style_for(&doc, n, pst, &cs);
  7284. if (cs.display == BR_DISPLAY_NONE)
  7285. continue;
  7286. if (ncell >= 12) {
  7287. layout_children(l, row, pst, depth, link);
  7288. return;
  7289. }
  7290. span = nd->colspan ? nd->colspan : 1;
  7291. if (span > 12 - col)
  7292. span = 12 - col;
  7293. if (span < 1)
  7294. continue;
  7295. cell[ncell] = n;
  7296. colstart[ncell] = col;
  7297. colspan[ncell] = span;
  7298. col += span;
  7299. ncell++;
  7300. }
  7301. if (ncell < 1 || avail < 32) {
  7302. layout_children(l, row, pst, depth, link);
  7303. return;
  7304. }
  7305. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  7306. &total);
  7307. if (cols < 2 || total <= 0) {
  7308. int c;
  7309. total = 0;
  7310. for (c = 0; c < ncell; c++) {
  7311. struct br_style cs;
  7312. br_style_for(&doc, cell[c], pst, &cs);
  7313. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  7314. avail) +
  7315. mp_px(&cs, 7, avail) +
  7316. mp_px(&cs, 5, avail) +
  7317. mp_px(&cs, 3, avail) +
  7318. mp_px(&cs, 1, avail);
  7319. if (raw[c] < 24)
  7320. raw[c] = 24;
  7321. total += raw[c];
  7322. }
  7323. /* A one-column table still has to fill its own width; the
  7324. * intrinsic fallback above otherwise leaves the cell at its
  7325. * text width (HN's outer table and nested story table). */
  7326. if (total > 0 && total < avail) {
  7327. int c;
  7328. for (c = 0; c < ncell; c++)
  7329. raw[c] = raw[c] * avail / total;
  7330. total = avail;
  7331. }
  7332. }
  7333. prefix[0] = row_left;
  7334. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  7335. prefix[n + 1] = prefix[n] + raw[n];
  7336. for (n = 0; n < (unsigned int)ncell; n++) {
  7337. struct br_style cs;
  7338. int start = colstart[n];
  7339. int end = start + colspan[n];
  7340. int w;
  7341. if (end > cols)
  7342. end = cols;
  7343. if (start >= cols)
  7344. continue;
  7345. w = prefix[end] - prefix[start];
  7346. br_style_for(&doc, cell[n], pst, &cs);
  7347. /* The column width already reflects the cell's width property. */
  7348. cs.width_kind = 0;
  7349. cs.max_width_kind = 0;
  7350. if (w < 24)
  7351. w = 24;
  7352. if (w < 8)
  7353. w = 8;
  7354. l->left = prefix[start];
  7355. l->right = l->left + w;
  7356. l->y = y;
  7357. l->line_x = l->left;
  7358. l->run_x = l->left;
  7359. l->line_y = l->y;
  7360. l->line_h = 0;
  7361. l->nruns = 0;
  7362. l->space_pending = 0;
  7363. l->align = cs.align;
  7364. layout_block(l, cell[n], &cs, depth + 1, link);
  7365. if (l->y > bottom)
  7366. bottom = l->y;
  7367. }
  7368. l->left = row_left;
  7369. l->right = row_right;
  7370. l->y = bottom;
  7371. l->line_x = l->left;
  7372. l->run_x = l->left;
  7373. l->line_y = l->y;
  7374. l->line_h = 0;
  7375. l->nruns = 0;
  7376. l->space_pending = 0;
  7377. }
  7378. #define TBL_MAX_ROWS 32
  7379. #define TBL_MAX_COLS 12
  7380. #define TBL_MAX_CELLS 128
  7381. struct tbl_cell {
  7382. unsigned int node;
  7383. unsigned char row, col, rowspan, colspan;
  7384. int height;
  7385. };
  7386. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  7387. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  7388. static int table_active;
  7389. static int table_has_rowspan(unsigned int table)
  7390. {
  7391. unsigned int r, c;
  7392. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7393. struct br_node *rn = &doc.nodes[r];
  7394. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7395. continue;
  7396. for (c = rn->first; c; c = doc.nodes[c].next) {
  7397. struct br_node *cn = &doc.nodes[c];
  7398. if (cn->type == BR_NODE_ELEM &&
  7399. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  7400. cn->rowspan > 1)
  7401. return 1;
  7402. }
  7403. }
  7404. return 0;
  7405. }
  7406. static void table_cell_style(unsigned int row, unsigned int cell,
  7407. const struct br_style *st, struct br_style *out)
  7408. {
  7409. struct br_style trs;
  7410. br_style_for(&doc, row, st, &trs);
  7411. br_style_for(&doc, cell, &trs, out);
  7412. }
  7413. /* Tables that use rowspan need row heights before anything is painted. This
  7414. * path builds a small occupancy grid, measures the natural cell heights, then
  7415. * lays every cell out at its row/column position. Tables without rowspan
  7416. * keep the lighter per-row path in layout_table_row(). */
  7417. static void layout_table(struct lay *l, unsigned int table,
  7418. const struct br_style *st, int depth,
  7419. unsigned short link)
  7420. {
  7421. unsigned int rows[TBL_MAX_ROWS];
  7422. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  7423. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  7424. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  7425. int free_raw = 0, free_cols = 0;
  7426. int table_left = l->left, table_right = l->right;
  7427. int top = l->y, avail = table_right - table_left;
  7428. unsigned int r, c;
  7429. int i, rr, cc;
  7430. if (depth > 48 || table_active) {
  7431. layout_children(l, table, st, depth, link);
  7432. return;
  7433. }
  7434. table_active = 1;
  7435. for (r = doc.nodes[table].first;
  7436. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  7437. struct br_node *rn = &doc.nodes[r];
  7438. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  7439. rows[nrows++] = r;
  7440. }
  7441. if (!nrows) {
  7442. table_active = 0;
  7443. layout_children(l, table, st, depth, link);
  7444. return;
  7445. }
  7446. for (rr = 0; rr < nrows; rr++)
  7447. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  7448. tbl_at[rr][cc] = 0;
  7449. for (rr = 0; rr < nrows; rr++) {
  7450. int col = 0;
  7451. for (c = doc.nodes[rows[rr]].first; c;
  7452. c = doc.nodes[c].next) {
  7453. struct br_node *cn = &doc.nodes[c];
  7454. struct br_style cs;
  7455. int rs, csn;
  7456. if (cn->type != BR_NODE_ELEM ||
  7457. (cn->tag != BR_TAG_TD &&
  7458. cn->tag != BR_TAG_TH))
  7459. continue;
  7460. table_cell_style(rows[rr], c, st, &cs);
  7461. if (cs.display == BR_DISPLAY_NONE)
  7462. continue;
  7463. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  7464. col++;
  7465. if (col >= TBL_MAX_COLS)
  7466. break;
  7467. rs = cn->rowspan ? cn->rowspan : 1;
  7468. csn = cn->colspan ? cn->colspan : 1;
  7469. if (rr + rs > nrows)
  7470. rs = nrows - rr;
  7471. if (col + csn > TBL_MAX_COLS)
  7472. csn = TBL_MAX_COLS - col;
  7473. if (rs < 1 || csn < 1)
  7474. continue;
  7475. if (ncells >= TBL_MAX_CELLS)
  7476. break;
  7477. tbl_cells[ncells].node = c;
  7478. tbl_cells[ncells].row = (unsigned char)rr;
  7479. tbl_cells[ncells].col = (unsigned char)col;
  7480. tbl_cells[ncells].rowspan = (unsigned char)rs;
  7481. tbl_cells[ncells].colspan = (unsigned char)csn;
  7482. tbl_cells[ncells].height = 0;
  7483. for (i = rr; i < rr + rs; i++)
  7484. for (int j = col; j < col + csn; j++)
  7485. tbl_at[i][j] =
  7486. (unsigned short)(ncells + 1);
  7487. ncells++;
  7488. col += csn;
  7489. if (col > cols)
  7490. cols = col;
  7491. }
  7492. }
  7493. if (!ncells || cols < 1) {
  7494. table_active = 0;
  7495. layout_children(l, table, st, depth, link);
  7496. return;
  7497. }
  7498. for (i = 0; i < cols; i++) {
  7499. raw[i] = 0;
  7500. fixed[i] = 0;
  7501. }
  7502. /* Intrinsic widths of single-column cells. */
  7503. for (i = 0; i < ncells; i++) {
  7504. struct br_style cs;
  7505. int w;
  7506. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  7507. st, &cs);
  7508. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  7509. mp_px(&cs, 7, avail) +
  7510. mp_px(&cs, 5, avail) +
  7511. mp_px(&cs, 3, avail) +
  7512. mp_px(&cs, 1, avail) +
  7513. cs.border_w[0] + cs.border_w[1] +
  7514. cs.border_w[2] + cs.border_w[3];
  7515. if (w < 24)
  7516. w = 24;
  7517. if (tbl_cells[i].colspan == 1) {
  7518. int col = tbl_cells[i].col;
  7519. if (w > raw[col])
  7520. raw[col] = w;
  7521. }
  7522. }
  7523. /* A spanning cell only needs the sum of its columns to be large
  7524. * enough; put the deficit in the last column. */
  7525. for (i = 0; i < ncells; i++) {
  7526. struct br_style cs;
  7527. int w, sum, col, span;
  7528. if (tbl_cells[i].colspan < 2)
  7529. continue;
  7530. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  7531. st, &cs);
  7532. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  7533. mp_px(&cs, 7, avail) +
  7534. mp_px(&cs, 5, avail) +
  7535. mp_px(&cs, 3, avail) +
  7536. mp_px(&cs, 1, avail) +
  7537. cs.border_w[0] + cs.border_w[1] +
  7538. cs.border_w[2] + cs.border_w[3];
  7539. col = tbl_cells[i].col;
  7540. span = tbl_cells[i].colspan;
  7541. sum = 0;
  7542. for (int j = 0; j < span; j++)
  7543. sum += raw[col + j];
  7544. if (w > sum)
  7545. raw[col + span - 1] += w - sum;
  7546. }
  7547. /* Explicit/percentage widths, as in table_columns(). */
  7548. for (i = 0; i < ncells; i++) {
  7549. struct br_style cs;
  7550. int col;
  7551. if (tbl_cells[i].colspan != 1)
  7552. continue;
  7553. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  7554. st, &cs);
  7555. col = tbl_cells[i].col;
  7556. if (cs.width_kind == 1) {
  7557. raw[col] = cs.width;
  7558. fixed[col] = 1;
  7559. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  7560. raw[col] = style_width_px(&cs, avail);
  7561. fixed[col] = 1;
  7562. }
  7563. }
  7564. for (i = 0; i < cols; i++) {
  7565. if (raw[i] < 8)
  7566. raw[i] = 8;
  7567. total += raw[i];
  7568. if (fixed[i])
  7569. fixed_sum += raw[i];
  7570. else {
  7571. free_raw += raw[i];
  7572. free_cols++;
  7573. }
  7574. }
  7575. if (fixed_sum > 0 && fixed_sum < avail) {
  7576. int free_avail = avail - fixed_sum;
  7577. if (free_raw > 0) {
  7578. for (i = 0; i < cols; i++)
  7579. if (!fixed[i])
  7580. raw[i] = free_avail * raw[i] /
  7581. free_raw;
  7582. } else if (free_cols > 0) {
  7583. for (i = 0; i < cols; i++)
  7584. if (!fixed[i])
  7585. raw[i] = free_avail / free_cols;
  7586. }
  7587. } else if (total < avail && total > 0) {
  7588. for (i = 0; i < cols; i++)
  7589. raw[i] = raw[i] * avail / total;
  7590. }
  7591. prefix[0] = table_left;
  7592. for (i = 0; i < cols; i++)
  7593. prefix[i + 1] = prefix[i] + raw[i];
  7594. /* Measure natural cell heights with the column widths. */
  7595. for (i = 0; i < ncells; i++) {
  7596. struct br_style cs;
  7597. int col = tbl_cells[i].col;
  7598. int span = tbl_cells[i].colspan;
  7599. int w = prefix[col + span] - prefix[col];
  7600. int sl = l->left, sr = l->right, sy = l->y;
  7601. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  7602. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  7603. int sal = l->align, sdraw = l->draw;
  7604. struct ngui *sui = l->ui;
  7605. if (w < 8)
  7606. w = 8;
  7607. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  7608. st, &cs);
  7609. cs.width_kind = 0;
  7610. cs.max_width_kind = 0;
  7611. l->draw = 0;
  7612. l->ui = 0;
  7613. l->left = prefix[col];
  7614. l->right = l->left + w;
  7615. l->y = 0;
  7616. l->line_x = l->left;
  7617. l->run_x = l->left;
  7618. l->line_y = 0;
  7619. l->line_h = 0;
  7620. l->nruns = 0;
  7621. l->space_pending = 0;
  7622. l->align = cs.align;
  7623. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  7624. tbl_cells[i].height = block_h[tbl_cells[i].node];
  7625. l->left = sl;
  7626. l->right = sr;
  7627. l->y = sy;
  7628. l->line_x = slx;
  7629. l->run_x = srx;
  7630. l->line_y = sly;
  7631. l->line_h = slh;
  7632. l->nruns = snr;
  7633. l->space_pending = ssp;
  7634. l->align = sal;
  7635. l->draw = sdraw;
  7636. l->ui = sui;
  7637. }
  7638. for (i = 0; i < nrows; i++)
  7639. rowh[i] = 0;
  7640. for (i = 0; i < ncells; i++) {
  7641. int row = tbl_cells[i].row;
  7642. if (tbl_cells[i].rowspan == 1) {
  7643. if (tbl_cells[i].height > rowh[row])
  7644. rowh[row] = tbl_cells[i].height;
  7645. }
  7646. }
  7647. for (i = 0; i < ncells; i++) {
  7648. int row = tbl_cells[i].row;
  7649. int span = tbl_cells[i].rowspan;
  7650. int sum = 0;
  7651. if (span < 2)
  7652. continue;
  7653. for (int j = 0; j < span; j++)
  7654. sum += rowh[row + j];
  7655. if (sum < tbl_cells[i].height)
  7656. rowh[row + span - 1] +=
  7657. tbl_cells[i].height - sum;
  7658. }
  7659. for (i = 0; i < nrows; i++)
  7660. if (rowh[i] < 8)
  7661. rowh[i] = 8;
  7662. rowy[0] = top;
  7663. for (i = 1; i < nrows; i++)
  7664. rowy[i] = rowy[i - 1] + rowh[i - 1];
  7665. if (!l->draw) {
  7666. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  7667. table_active = 0;
  7668. return;
  7669. }
  7670. for (i = 0; i < ncells; i++) {
  7671. struct br_style cs;
  7672. int col = tbl_cells[i].col;
  7673. int span = tbl_cells[i].colspan;
  7674. int row = tbl_cells[i].row;
  7675. int rspan = tbl_cells[i].rowspan;
  7676. int w = prefix[col + span] - prefix[col];
  7677. int h = 0;
  7678. int sl = l->left, sr = l->right, sy = l->y;
  7679. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  7680. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  7681. int sal = l->align;
  7682. int deco;
  7683. for (int j = 0; j < rspan; j++)
  7684. h += rowh[row + j];
  7685. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  7686. cs.width_kind = 0;
  7687. cs.max_width_kind = 0;
  7688. cs.box_sizing = 0;
  7689. deco = mp_px(&cs, 4, avail) +
  7690. mp_px(&cs, 6, avail) +
  7691. cs.border_w[0] + cs.border_w[2];
  7692. cs.height_kind = 1;
  7693. cs.height = h > deco ? h - deco : 0;
  7694. /* The block painter reads block_h[] from the measure pass; make
  7695. * the table cell fill its row/rowspan, not just its content. */
  7696. if (h > 0 && h < 65536)
  7697. block_h[tbl_cells[i].node] = (unsigned short)h;
  7698. l->left = prefix[col];
  7699. l->right = l->left + w;
  7700. l->y = rowy[row];
  7701. l->line_x = l->left;
  7702. l->run_x = l->left;
  7703. l->line_y = l->y;
  7704. l->line_h = 0;
  7705. l->nruns = 0;
  7706. l->space_pending = 0;
  7707. l->align = cs.align;
  7708. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  7709. l->left = sl;
  7710. l->right = sr;
  7711. l->y = sy;
  7712. l->line_x = slx;
  7713. l->run_x = srx;
  7714. l->line_y = sly;
  7715. l->line_h = slh;
  7716. l->nruns = snr;
  7717. l->space_pending = ssp;
  7718. l->align = sal;
  7719. }
  7720. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  7721. table_active = 0;
  7722. }
  7723. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  7724. * flow so they sit above it, like CSS painting order. Their flow origin is
  7725. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  7726. struct br_deferred {
  7727. unsigned int node;
  7728. int flow_y, flow_left, flow_right;
  7729. unsigned short link;
  7730. signed short z_index;
  7731. unsigned char z_set;
  7732. unsigned int order;
  7733. };
  7734. /* Positioned boxes painted after the flow. News front pages have one or two
  7735. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  7736. * old 16 entries the rest fell back into the flow, so a hero image landed
  7737. * below its padding-top aspect box instead of on top of it. */
  7738. #define BR_MAX_DEFERRED 256
  7739. static struct br_deferred deferred[BR_MAX_DEFERRED];
  7740. static int ndeferred;
  7741. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  7742. * element's line. A block-level pseudo-element gets its own line; its box
  7743. * (margins, padding, background) is not drawn. */
  7744. static void emit_pseudo(struct lay *l, unsigned int node,
  7745. const struct br_style *st, int pe, unsigned short link)
  7746. {
  7747. char buf[160];
  7748. struct br_style ps;
  7749. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  7750. unsigned int i = 0;
  7751. int block, space_w;
  7752. if (!n)
  7753. return;
  7754. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  7755. if (block)
  7756. flush_line(l);
  7757. if (ps.uppercase)
  7758. for (i = 0; i < n; i++)
  7759. if (buf[i] >= 'a' && buf[i] <= 'z')
  7760. buf[i] = (char)(buf[i] - 'a' + 'A');
  7761. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  7762. if (space_w <= 0)
  7763. space_w = 8;
  7764. i = 0;
  7765. while (i < n) {
  7766. char word[28];
  7767. unsigned int k = 0;
  7768. int w;
  7769. if (buf[i] == ' ') {
  7770. l->space_pending = 1;
  7771. i++;
  7772. continue;
  7773. }
  7774. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  7775. word[k++] = buf[i++];
  7776. word[k] = '\0';
  7777. if (l->space_pending &&
  7778. (l->nruns > 0 || l->line_x > l->line_left) &&
  7779. l->line_x + space_w <= l->line_right)
  7780. l->line_x += space_w;
  7781. l->space_pending = 0;
  7782. w = (int)face_text_width(l->ui, &ps, word, k);
  7783. if (l->line_x + w > l->line_right &&
  7784. (l->nruns > 0 || l->line_x > l->line_left))
  7785. flush_line(l);
  7786. add_run(l, 0, 0, &ps, link, word);
  7787. }
  7788. if (block)
  7789. flush_line(l);
  7790. }
  7791. static void layout_children(struct lay *l, unsigned int parent,
  7792. const struct br_style *pst, int depth,
  7793. unsigned short link)
  7794. {
  7795. unsigned int n;
  7796. if (depth > 48)
  7797. return;
  7798. emit_pseudo(l, parent, pst, 1, link);
  7799. n = doc.nodes[parent].first;
  7800. while (n) {
  7801. struct br_node *nd = &doc.nodes[n];
  7802. struct br_style cs;
  7803. unsigned short lk = link;
  7804. if (nd->type == BR_NODE_TEXT) {
  7805. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  7806. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  7807. n = nd->next;
  7808. continue;
  7809. }
  7810. br_style_for(&doc, n, pst, &cs);
  7811. if (cs.display == BR_DISPLAY_NONE) {
  7812. n = nd->next;
  7813. continue;
  7814. }
  7815. if (cs.clear && l->float_active) {
  7816. flush_line(l);
  7817. if (l->y < l->float_bottom)
  7818. l->y = l->float_bottom;
  7819. l->float_active = 0;
  7820. l->line_x = l->left;
  7821. l->run_x = l->left;
  7822. l->line_left = l->left;
  7823. l->line_right = l->right;
  7824. l->line_y = l->y;
  7825. l->line_h = 0;
  7826. l->nruns = 0;
  7827. l->space_pending = 0;
  7828. }
  7829. if (nd->tag == BR_TAG_A && nd->href_off)
  7830. lk = (unsigned short)n;
  7831. if (cs.pos == 1 || cs.pos == 2 ||
  7832. (cs.pos == 3 && cs.z_set)) {
  7833. if (cs.pos == 3 && l->draw &&
  7834. ndeferred < BR_MAX_DEFERRED) {
  7835. /* Relative z-index: measure and advance the flow
  7836. * without painting, then paint it in the
  7837. * deferred (stacked) pass. */
  7838. int fy = l->y, fl = l->left, fr = l->right;
  7839. int save_draw = l->draw;
  7840. l->draw = 0;
  7841. layout_block(l, n, &cs, depth + 1, lk);
  7842. l->draw = save_draw;
  7843. deferred[ndeferred].node = n;
  7844. deferred[ndeferred].flow_y = fy;
  7845. deferred[ndeferred].flow_left = fl;
  7846. deferred[ndeferred].flow_right = fr;
  7847. deferred[ndeferred].link = lk;
  7848. deferred[ndeferred].z_index = cs.z_index;
  7849. deferred[ndeferred].z_set = cs.z_set;
  7850. deferred[ndeferred].order = (unsigned int)ndeferred;
  7851. ndeferred++;
  7852. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  7853. deferred[ndeferred].node = n;
  7854. deferred[ndeferred].flow_y =
  7855. cs.pos == 1 ? l->cb_top : l->y;
  7856. deferred[ndeferred].flow_left =
  7857. cs.pos == 1 ? l->cb_left : l->left;
  7858. deferred[ndeferred].flow_right =
  7859. cs.pos == 1 ? l->cb_right : l->right;
  7860. deferred[ndeferred].link = lk;
  7861. deferred[ndeferred].z_index = cs.z_index;
  7862. deferred[ndeferred].z_set = cs.z_set;
  7863. deferred[ndeferred].order = (unsigned int)ndeferred;
  7864. ndeferred++;
  7865. } else if (l->draw && cs.pos == 1) {
  7866. /* Deferred list full: paint in place, but still
  7867. * against the containing block, not the flow. */
  7868. int fy = l->y, fl = l->left, fr = l->right;
  7869. l->y = l->cb_top;
  7870. l->left = l->cb_left;
  7871. l->right = l->cb_right;
  7872. layout_block(l, n, &cs, depth + 1, lk);
  7873. l->y = fy;
  7874. l->left = fl;
  7875. l->right = fr;
  7876. } else {
  7877. layout_block(l, n, &cs, depth + 1, lk);
  7878. }
  7879. if (cs.pos == 1 && block_h[n] &&
  7880. doc.nodes[n].class_off) {
  7881. const char *cl = doc.attrs +
  7882. doc.nodes[n].class_off;
  7883. if ((contains_ci(cl, "poster-wrapper") ||
  7884. contains_ci(cl, "ts-picture")) &&
  7885. !has_skeleton_sibling(n))
  7886. l->y += block_h[n];
  7887. }
  7888. n = nd->next;
  7889. continue;
  7890. }
  7891. if (nd->tag == BR_TAG_BR) {
  7892. flush_line(l);
  7893. n = nd->next;
  7894. continue;
  7895. }
  7896. if (nd->tag == BR_TAG_HR) {
  7897. flush_line(l);
  7898. if (l->draw)
  7899. ngui_fill_rect(l->ui,
  7900. (struct ngui_rect){l->left, l->y + 2,
  7901. l->right - l->left, 1}, BR_GRAY);
  7902. l->y += 8;
  7903. n = nd->next;
  7904. continue;
  7905. }
  7906. if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  7907. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) {
  7908. if (!(nd->tag == BR_TAG_INPUT &&
  7909. s_eq(br_type(&doc, n), "hidden")))
  7910. add_form_run(l, n, &cs, lk);
  7911. n = nd->next;
  7912. continue;
  7913. }
  7914. if (nd->tag == BR_TAG_IMG) {
  7915. add_image_run(l, n, &cs, lk);
  7916. n = nd->next;
  7917. continue;
  7918. }
  7919. if (nd->tag == BR_TAG_VIDEO) {
  7920. layout_block(l, n, &cs, depth + 1, lk);
  7921. n = nd->next;
  7922. continue;
  7923. }
  7924. if (cs.float_left) {
  7925. n = layout_float_group(l, n, pst, depth, lk);
  7926. continue;
  7927. }
  7928. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  7929. n = layout_inline_blocks(l, n, pst, depth, link);
  7930. continue;
  7931. }
  7932. /* A flex container is block-level like any block box even when
  7933. * the element is an inline tag such as <a> (a link card with
  7934. * display:flex is common on news sites). Without the block box
  7935. * its children were laid out in the parent flow with a 0x0 box
  7936. * of their own. */
  7937. /* inline-flex around inline content only ("| mehr" link
  7938. * tails, icon+label pills) stays in the text line. */
  7939. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  7940. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  7941. !flex_wants_row(n, &cs)) {
  7942. layout_children(l, n, &cs, depth + 1, lk);
  7943. } else if (cs.display == BR_DISPLAY_BLOCK ||
  7944. cs.display == BR_DISPLAY_FLEX ||
  7945. br_tag_is_block(nd->tag))
  7946. layout_block(l, n, &cs, depth + 1, lk);
  7947. else {
  7948. layout_children(l, n, &cs, depth + 1, lk);
  7949. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  7950. l->space_pending = 1;
  7951. }
  7952. n = nd->next;
  7953. }
  7954. emit_pseudo(l, parent, pst, 2, link);
  7955. }
  7956. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  7957. * runs and a recursive page can otherwise overflow the stack. */
  7958. static struct lay layout_state;
  7959. static int measure_page(int left, int right)
  7960. {
  7961. struct lay *l = &layout_state;
  7962. struct br_style base = base_style();
  7963. unsigned int i;
  7964. for (i = 0; i < BR_MAX_NODES; i++) {
  7965. block_h[i] = 0;
  7966. img_top[i] = 0;
  7967. block_top[i] = 0;
  7968. img_h[i] = 0;
  7969. layout_boxes[i].valid = 0;
  7970. }
  7971. memset(li_marker, 0, sizeof(li_marker));
  7972. l->draw = 0;
  7973. l->ui = &ui;
  7974. l->left = left;
  7975. l->right = right;
  7976. l->y = 0;
  7977. l->line_x = left;
  7978. l->run_x = left;
  7979. l->line_left = left;
  7980. l->line_right = right;
  7981. l->line_y = 0;
  7982. l->line_h = 0;
  7983. l->align = BR_ALIGN_LEFT;
  7984. l->float_active = 0;
  7985. l->parent_top = 0;
  7986. l->cb_left = left;
  7987. l->cb_right = right;
  7988. l->cb_top = 0;
  7989. l->depth = 0;
  7990. l->nruns = 0;
  7991. l->space_pending = 0;
  7992. layout_children(l, doc.root, &base, 0, 0);
  7993. return l->y + 8;
  7994. }
  7995. static int deferred_cmp(const struct br_deferred *a,
  7996. const struct br_deferred *b)
  7997. {
  7998. int az = a->z_set ? a->z_index : 0;
  7999. int bz = b->z_set ? b->z_index : 0;
  8000. if (az != bz)
  8001. return az < bz ? -1 : 1;
  8002. if (a->order != b->order)
  8003. return a->order < b->order ? -1 : 1;
  8004. return 0;
  8005. }
  8006. static void sort_deferred(void)
  8007. {
  8008. int i;
  8009. for (i = 1; i < ndeferred; i++) {
  8010. struct br_deferred key = deferred[i];
  8011. int j = i;
  8012. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  8013. deferred[j] = deferred[j - 1];
  8014. j--;
  8015. }
  8016. deferred[j] = key;
  8017. }
  8018. }
  8019. static void render_page(int left, int right, int y0)
  8020. {
  8021. struct lay *l = &layout_state;
  8022. struct br_style base = base_style();
  8023. l->draw = 1;
  8024. l->ui = &ui;
  8025. l->left = left;
  8026. l->right = right;
  8027. l->y = y0;
  8028. l->line_x = left;
  8029. l->run_x = left;
  8030. l->line_left = left;
  8031. l->line_right = right;
  8032. l->line_y = y0;
  8033. l->line_h = 0;
  8034. l->align = BR_ALIGN_LEFT;
  8035. l->float_active = 0;
  8036. l->parent_top = 0;
  8037. l->cb_left = left;
  8038. l->cb_right = right;
  8039. l->cb_top = y0;
  8040. l->depth = 0;
  8041. l->nruns = 0;
  8042. l->space_pending = 0;
  8043. nhits = 0;
  8044. ndeferred = 0;
  8045. layout_children(l, doc.root, &base, 0, 0);
  8046. sort_deferred();
  8047. {
  8048. int i;
  8049. for (i = 0; i < ndeferred; i++) {
  8050. struct br_style st;
  8051. br_style_for(&doc, deferred[i].node, &base, &st);
  8052. if (st.display == BR_DISPLAY_NONE)
  8053. continue;
  8054. l->draw = 1;
  8055. l->left = deferred[i].flow_left;
  8056. l->right = deferred[i].flow_right;
  8057. l->y = deferred[i].flow_y;
  8058. l->line_x = l->left;
  8059. l->run_x = l->left;
  8060. l->line_y = l->y;
  8061. l->line_h = 0;
  8062. l->nruns = 0;
  8063. l->space_pending = 0;
  8064. l->align = st.align;
  8065. if (st.pos == 2 && block_h[deferred[i].node]) {
  8066. struct ngui_rect clip;
  8067. int ch = block_h[deferred[i].node] + 24;
  8068. clip.x = page_rect.x;
  8069. clip.y = page_rect.y;
  8070. clip.w = page_rect.w - 12;
  8071. if (ch > page_rect.h)
  8072. ch = page_rect.h;
  8073. clip.h = ch;
  8074. ngui_push_clip(&ui, clip);
  8075. if (st.has_bg)
  8076. ngui_fill_rect(&ui, clip, st.bg);
  8077. layout_block(l, deferred[i].node, &st, 0,
  8078. deferred[i].link);
  8079. ngui_pop_clip(&ui);
  8080. } else {
  8081. layout_block(l, deferred[i].node, &st, 0,
  8082. deferred[i].link);
  8083. }
  8084. }
  8085. }
  8086. }
  8087. /* ---- UI ---- */
  8088. static int find_hit(int x, int y)
  8089. {
  8090. int i;
  8091. for (i = nhits - 1; i >= 0; i--) {
  8092. struct hit *h = &hits[i];
  8093. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  8094. y < h->y + h->h)
  8095. return (int)h->node;
  8096. }
  8097. return 0;
  8098. }
  8099. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  8100. {
  8101. int x = r.x + 4, y = r.y + 4, h = 22;
  8102. int compact = r.w < 560;
  8103. int go_w = r.w < 420 ? 32 : 42;
  8104. int in_x, in_w, res;
  8105. ngui_fill_rect(&ui, r, ui.theme.panel);
  8106. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  8107. ui.theme.border);
  8108. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  8109. NGUI_ICON_CHEVRON_LEFT))
  8110. *action |= ACT_BACK;
  8111. x += 32;
  8112. if (!compact) {
  8113. if (ngui_icon_button(&ui, ID_FORWARD,
  8114. (struct ngui_rect){x, y, 28, h},
  8115. NGUI_ICON_CHEVRON_RIGHT))
  8116. *action |= ACT_FORWARD;
  8117. x += 32;
  8118. }
  8119. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  8120. NGUI_ICON_REFRESH))
  8121. *action |= ACT_RELOAD;
  8122. x += 32;
  8123. if (!compact) {
  8124. if (ngui_icon_button(&ui, ID_HOME,
  8125. (struct ngui_rect){x, y, 28, h},
  8126. NGUI_ICON_HOME))
  8127. *action |= ACT_HOME;
  8128. x += 32;
  8129. }
  8130. in_x = x + 2;
  8131. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  8132. if (in_w < 60)
  8133. in_w = 60;
  8134. res = ngui_text_input(&ui, ID_URL,
  8135. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  8136. if (res & NGUI_INPUT_SUBMIT)
  8137. *action |= ACT_NAV;
  8138. if (res & NGUI_INPUT_CANCEL)
  8139. ngui_set_focus(&ui, 0);
  8140. if (ngui_button(&ui, ID_GO,
  8141. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  8142. "Go"))
  8143. *action |= ACT_NAV;
  8144. }
  8145. static int page_hover_node(void)
  8146. {
  8147. if (!ui.inside)
  8148. return 0;
  8149. if (ui.mouse_x < page_rect.x ||
  8150. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  8151. ui.mouse_y < page_rect.y ||
  8152. ui.mouse_y >= page_rect.y + page_rect.h)
  8153. return 0;
  8154. return find_hit(ui.mouse_x, ui.mouse_y);
  8155. }
  8156. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  8157. {
  8158. int x, y, w = page.w, h = page.h;
  8159. if (!src || w <= 0 || h <= 0)
  8160. return;
  8161. for (y = 0; y < h; y++) {
  8162. unsigned short *s = src + (page.y + y) * sw + page.x;
  8163. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  8164. for (x = 0; x + 1 < w; x += 2) {
  8165. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  8166. }
  8167. if (x < w)
  8168. d[x] = s[x];
  8169. }
  8170. }
  8171. static void draw_page(struct ngui_rect page)
  8172. {
  8173. int left, right, ch;
  8174. int old_panel, old_dim;
  8175. unsigned short *saved_px;
  8176. unsigned short page_bg = ui.theme.bg;
  8177. int saved_w, saved_h, use_buf;
  8178. page_rect = page;
  8179. {
  8180. unsigned int root = doc.nnode > 1 ?
  8181. br_find_tag(&doc, BR_TAG_HTML) : 0;
  8182. unsigned int body = doc.nnode > 1 ?
  8183. br_find_tag(&doc, BR_TAG_BODY) : 0;
  8184. struct br_style bs;
  8185. if (root) {
  8186. style_for_node(root - 1, &bs);
  8187. if (bs.has_bg)
  8188. page_bg = bs.bg;
  8189. }
  8190. if (body) {
  8191. style_for_node(body - 1, &bs);
  8192. if (bs.has_bg)
  8193. page_bg = bs.bg;
  8194. }
  8195. }
  8196. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  8197. page_cache_valid && layout_valid &&
  8198. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  8199. !(ui.scroll_y &&
  8200. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  8201. page_scroll.offset == page_cache_scroll &&
  8202. page_cache_nnode == doc.nnode &&
  8203. page_cache_x == page.x && page_cache_y == page.y &&
  8204. page_cache_w == page.w && page_cache_h == page.h) {
  8205. blit_page(page, page_backbuf, pagebuf_w);
  8206. return;
  8207. }
  8208. ngui_fill_rect(&ui, page, page_bg);
  8209. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  8210. const char *s = page_loading ? "Loading..." : "No page";
  8211. int w = (int)ngui_text_width_ui(&ui, s);
  8212. ngui_text(&ui, page.x + (page.w - w) / 2,
  8213. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  8214. page_scroll.content_h = 0;
  8215. page_scroll.view_h = page.h;
  8216. page_cache_valid = 0;
  8217. return;
  8218. }
  8219. if (page.w < 40 || page.h < 40) {
  8220. page_cache_valid = 0;
  8221. return;
  8222. }
  8223. saved_px = ui.px;
  8224. saved_w = ui.w;
  8225. saved_h = ui.h;
  8226. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  8227. if (use_buf) {
  8228. ui.px = page_backbuf;
  8229. ui.w = pagebuf_w;
  8230. ui.h = pagebuf_h;
  8231. ngui_fill_rect(&ui, page, page_bg);
  8232. }
  8233. left = page.x + 8;
  8234. right = page.x + page.w - 16;
  8235. if (!layout_valid || left != layout_left || right != layout_right ||
  8236. layout_nnode != doc.nnode) {
  8237. layout_content_h = measure_page(left, right);
  8238. layout_valid = 1;
  8239. layout_left = left;
  8240. layout_right = right;
  8241. layout_nnode = doc.nnode;
  8242. }
  8243. ch = layout_content_h;
  8244. page_scroll.content_h = ch;
  8245. page_scroll.view_h = page.h;
  8246. ngui_scroll_begin(&ui, page, &page_scroll);
  8247. ngui_scroll_wheel(&ui, page, &page_scroll);
  8248. render_page(left, right, page.y + 4 - page_scroll.offset);
  8249. old_panel = ui.theme.panel_alt;
  8250. old_dim = ui.theme.text_dim;
  8251. ui.theme.panel_alt = 0xC618;
  8252. ui.theme.text_dim = 0x8410;
  8253. ngui_scroll_end(&ui, page, &page_scroll);
  8254. ui.theme.panel_alt = old_panel;
  8255. ui.theme.text_dim = old_dim;
  8256. if (use_buf) {
  8257. ui.px = saved_px;
  8258. ui.w = saved_w;
  8259. ui.h = saved_h;
  8260. blit_page(page, page_backbuf, pagebuf_w);
  8261. page_cache_valid = 1;
  8262. page_cache_scroll = page_scroll.offset;
  8263. page_cache_nnode = doc.nnode;
  8264. page_cache_x = page.x;
  8265. page_cache_y = page.y;
  8266. page_cache_w = page.w;
  8267. page_cache_h = page.h;
  8268. } else {
  8269. page_cache_valid = 0;
  8270. }
  8271. }
  8272. static void draw_status(struct ngui_rect r)
  8273. {
  8274. char msg[BR_URL_MAX + 32];
  8275. unsigned int n = 0;
  8276. int hover = page_hover_node();
  8277. unsigned short color;
  8278. const char *kind;
  8279. ngui_fill_rect(&ui, r, ui.theme.panel);
  8280. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  8281. ui.theme.border);
  8282. if (hover) {
  8283. const char *href = br_href(&doc, (unsigned int)hover);
  8284. char url[BR_URL_MAX];
  8285. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  8286. s_append(msg, &n, "Link: ", sizeof(msg));
  8287. s_append(msg, &n, url, sizeof(msg));
  8288. } else {
  8289. s_copy(msg, "Link", sizeof(msg));
  8290. }
  8291. color = ui.theme.accent;
  8292. } else if (status_text[0]) {
  8293. s_copy(msg, status_text, sizeof(msg));
  8294. color = status_error ? ui.theme.error : ui.theme.text;
  8295. } else if (page_title[0]) {
  8296. s_copy(msg, page_title, sizeof(msg));
  8297. color = ui.theme.text;
  8298. } else {
  8299. s_copy(msg, "Ready", sizeof(msg));
  8300. color = ui.theme.text_dim;
  8301. }
  8302. kind = s_eq(page_url, "about:home") ? "HOME" :
  8303. page_is_local ? "FILE" :
  8304. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  8305. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  8306. {
  8307. int kw = (int)ngui_text_width_ui(&ui, kind);
  8308. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  8309. ui.theme.text_dim);
  8310. }
  8311. }
  8312. static void draw(unsigned int *action)
  8313. {
  8314. struct ngui_rect r = {0, 0, ui.w, ui.h};
  8315. struct ngui_rect toolbar, status, page;
  8316. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  8317. status = ngui_cut_bottom(&r, BR_STATUS_H);
  8318. page = r;
  8319. draw_toolbar(toolbar, action);
  8320. draw_page(page);
  8321. draw_status(status);
  8322. }
  8323. static void redraw_now(void)
  8324. {
  8325. unsigned int action = 0;
  8326. ngui_begin(&ui);
  8327. draw(&action);
  8328. ngui_end(&ui);
  8329. }
  8330. static void handle_keys(unsigned int *action)
  8331. {
  8332. int k, scrolled = 0;
  8333. if (form_focus >= doc.nnode)
  8334. form_focus = 0;
  8335. if (form_focus && !ngui_focus(&ui)) {
  8336. while ((k = ngui_key(&ui)) != 0)
  8337. form_key(k);
  8338. return;
  8339. }
  8340. /* Batch queued page keys: a slow full-page render must not make a
  8341. * held Page Down advance only once every few frames. */
  8342. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  8343. scrolled++;
  8344. if (scrolled)
  8345. ngui_invalidate(&ui);
  8346. if (ngui_focus(&ui))
  8347. return;
  8348. while ((k = ngui_key(&ui)) != 0) {
  8349. switch (k) {
  8350. case NGUI_KEY_ESC:
  8351. *action |= ACT_CLOSE;
  8352. break;
  8353. case NGUI_KEY_TAB:
  8354. case 0x0C: /* Ctrl+L */
  8355. ngui_set_focus(&ui, ID_URL);
  8356. break;
  8357. case 0x12: /* Ctrl+R */
  8358. *action |= ACT_RELOAD;
  8359. break;
  8360. case NGUI_KEY_BACKSPACE:
  8361. *action |= ACT_BACK;
  8362. break;
  8363. case NGUI_KEY_UP:
  8364. ngui_scroll_to(&page_scroll,
  8365. page_scroll.offset - 24);
  8366. ngui_invalidate(&ui);
  8367. break;
  8368. case NGUI_KEY_DOWN:
  8369. ngui_scroll_to(&page_scroll,
  8370. page_scroll.offset + 24);
  8371. ngui_invalidate(&ui);
  8372. break;
  8373. case NGUI_KEY_HOME:
  8374. ngui_scroll_to(&page_scroll, 0);
  8375. ngui_invalidate(&ui);
  8376. break;
  8377. case NGUI_KEY_END:
  8378. ngui_scroll_to(&page_scroll,
  8379. page_scroll.content_h -
  8380. page_scroll.view_h);
  8381. ngui_invalidate(&ui);
  8382. break;
  8383. default:
  8384. break;
  8385. }
  8386. }
  8387. }
  8388. static unsigned int form_ancestor(unsigned int node)
  8389. {
  8390. unsigned int p = node;
  8391. while (p && p < doc.nnode) {
  8392. if (doc.nodes[p].tag == BR_TAG_FORM &&
  8393. doc.nodes[p].type == BR_NODE_ELEM)
  8394. return p;
  8395. p = doc.nodes[p].parent;
  8396. }
  8397. return 0;
  8398. }
  8399. static int form_descendant(unsigned int node, unsigned int form)
  8400. {
  8401. unsigned int p = node;
  8402. while (p && p < doc.nnode) {
  8403. if (p == form)
  8404. return 1;
  8405. p = doc.nodes[p].parent;
  8406. }
  8407. return 0;
  8408. }
  8409. static void form_reset_form(unsigned int form)
  8410. {
  8411. unsigned int i;
  8412. for (i = 0; i < FORM_MAX; i++)
  8413. if (form_states[i].used &&
  8414. form_descendant(form_states[i].node, form))
  8415. form_states[i].used = 0;
  8416. form_focus = 0;
  8417. }
  8418. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  8419. const char *s)
  8420. {
  8421. static const char hex[] = "0123456789ABCDEF";
  8422. while (s && *s && *n + 1 < cap) {
  8423. unsigned char c = (unsigned char)*s++;
  8424. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  8425. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  8426. c == '.' || c == '~') {
  8427. dst[(*n)++] = (char)c;
  8428. } else if (c == ' ') {
  8429. dst[(*n)++] = '+';
  8430. } else if (*n + 3 < cap) {
  8431. dst[(*n)++] = '%';
  8432. dst[(*n)++] = hex[c >> 4];
  8433. dst[(*n)++] = hex[c & 15];
  8434. }
  8435. }
  8436. dst[*n] = '\0';
  8437. }
  8438. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  8439. const char *name, const char *value, int *first)
  8440. {
  8441. if (!name || !name[0])
  8442. return;
  8443. if (!*first && *n + 1 < cap)
  8444. dst[(*n)++] = '&';
  8445. *first = 0;
  8446. form_url_append(dst, n, cap, name);
  8447. if (*n + 1 < cap)
  8448. dst[(*n)++] = '=';
  8449. form_url_append(dst, n, cap, value ? value : "");
  8450. dst[*n] = '\0';
  8451. }
  8452. static int form_submit_form(unsigned int node, int fire_event)
  8453. {
  8454. unsigned int form = form_ancestor(node);
  8455. char action[BR_URL_MAX], query[2048];
  8456. unsigned int qn = 0, i;
  8457. int first = 1, is_post = 0;
  8458. const char *a, *method;
  8459. if (!form)
  8460. return 0;
  8461. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  8462. return 0;
  8463. method = br_find_attr(&doc, form, "method");
  8464. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  8465. is_post = 1;
  8466. a = br_find_attr(&doc, form, "action");
  8467. if (a && a[0]) {
  8468. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  8469. return 0;
  8470. } else {
  8471. s_copy(action, page_url, sizeof(action));
  8472. }
  8473. query[0] = '\0';
  8474. for (i = 0; i < doc.nnode; i++) {
  8475. struct br_node *nd = &doc.nodes[i];
  8476. struct form_state *fs;
  8477. const char *name;
  8478. const char *value = "";
  8479. if (nd->type != BR_NODE_ELEM || i == form ||
  8480. !form_descendant(i, form))
  8481. continue;
  8482. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  8483. nd->tag != BR_TAG_SELECT)
  8484. continue;
  8485. if (form_disabled(i))
  8486. continue;
  8487. name = br_find_attr(&doc, i, "name");
  8488. if (!name || !name[0])
  8489. continue;
  8490. fs = form_get(i, 1);
  8491. if (!fs)
  8492. continue;
  8493. if (nd->tag == BR_TAG_SELECT) {
  8494. char opt[64];
  8495. if (!form_option_text(i, fs->selected, opt,
  8496. sizeof(opt)))
  8497. s_copy(opt, "", sizeof(opt));
  8498. value = opt;
  8499. {
  8500. unsigned int c, oi = 0;
  8501. for (c = nd->first; c;
  8502. c = doc.nodes[c].next) {
  8503. if (doc.nodes[c].type != BR_NODE_ELEM ||
  8504. doc.nodes[c].tag != BR_TAG_OPTION)
  8505. continue;
  8506. if (oi == fs->selected) {
  8507. const char *v =
  8508. br_value(&doc, c);
  8509. if (v && v[0])
  8510. value = v;
  8511. break;
  8512. }
  8513. oi++;
  8514. }
  8515. }
  8516. } else if (nd->tag == BR_TAG_INPUT) {
  8517. int kind = form_kind_of(i);
  8518. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  8519. if (!fs->checked)
  8520. continue;
  8521. value = br_value(&doc, i);
  8522. if (!value || !value[0])
  8523. value = "on";
  8524. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  8525. kind == FORM_BUTTON) {
  8526. if (i != node)
  8527. continue;
  8528. value = fs->value;
  8529. } else {
  8530. value = fs->value;
  8531. }
  8532. } else {
  8533. value = fs->value;
  8534. }
  8535. form_add_param(query, &qn, sizeof(query), name, value, &first);
  8536. }
  8537. if (is_post) {
  8538. if (action[0] == '/') {
  8539. set_status("POST forms need an HTTP action URL", 1, 4000);
  8540. ngui_invalidate(&ui);
  8541. return 0;
  8542. }
  8543. if (qn >= sizeof(pending_post))
  8544. qn = sizeof(pending_post) - 1;
  8545. if (qn)
  8546. memcpy(pending_post, query, qn);
  8547. pending_post[qn] = '\0';
  8548. pending_post_len = qn;
  8549. } else {
  8550. pending_post_len = 0;
  8551. if (qn) {
  8552. unsigned int an = s_len(action);
  8553. if (an + qn + 2 < sizeof(action)) {
  8554. action[an++] = strchr(action, '?') ? '&' : '?';
  8555. action[an] = '\0';
  8556. s_copy(action + an, query,
  8557. sizeof(action) - an);
  8558. }
  8559. }
  8560. }
  8561. s_copy(pending_url, action, sizeof(pending_url));
  8562. pending_action |= ACT_NAV;
  8563. cancel_fetch = 1;
  8564. ngui_invalidate(&ui);
  8565. return 1;
  8566. }
  8567. static void form_reset_event(unsigned int form)
  8568. {
  8569. if (form && !js_browser_event(form, "reset", 1, 1))
  8570. return;
  8571. if (form)
  8572. form_reset_form(form);
  8573. else
  8574. form_reset_state();
  8575. form_dirty = 0;
  8576. layout_valid = 0;
  8577. ngui_invalidate(&ui);
  8578. }
  8579. static void form_blur(void)
  8580. {
  8581. unsigned int node = form_focus;
  8582. form_focus = 0;
  8583. if (node && form_dirty) {
  8584. form_dirty = 0;
  8585. js_browser_event(node, "change", 1, 0);
  8586. }
  8587. }
  8588. static void form_click(unsigned int node)
  8589. {
  8590. struct form_state *fs;
  8591. int kind, changed = 0;
  8592. if (!form_is_control(node) || form_disabled(node))
  8593. return;
  8594. if (form_focus != node)
  8595. form_blur();
  8596. if (!js_browser_event(node, "click", 1, 1))
  8597. return;
  8598. fs = form_get(node, 1);
  8599. if (!fs)
  8600. return;
  8601. kind = form_kind_of(node);
  8602. form_focus = node;
  8603. form_dirty = 0;
  8604. if (kind == FORM_CHECKBOX) {
  8605. fs->checked = !fs->checked;
  8606. changed = 1;
  8607. } else if (kind == FORM_RADIO) {
  8608. const char *name = br_find_attr(&doc, node, "name");
  8609. unsigned int i;
  8610. fs->checked = 1;
  8611. changed = 1;
  8612. if (name) {
  8613. for (i = 0; i < FORM_MAX; i++) {
  8614. struct form_state *o = &form_states[i];
  8615. if (!o->used || o->node == node)
  8616. continue;
  8617. if (form_kind_of(o->node) == FORM_RADIO) {
  8618. const char *on = br_find_attr(&doc,
  8619. o->node,
  8620. "name");
  8621. if (on && s_eq(on, name))
  8622. o->checked = 0;
  8623. }
  8624. }
  8625. }
  8626. } else if (kind == FORM_SELECT) {
  8627. unsigned int n = form_option_count(node);
  8628. if (n) {
  8629. fs->selected = (unsigned char)
  8630. ((fs->selected + 1) % n);
  8631. changed = 1;
  8632. }
  8633. } else if (kind == FORM_SUBMIT) {
  8634. form_submit_form(node, 1);
  8635. return;
  8636. } else if (kind == FORM_RESET) {
  8637. form_reset_event(form_ancestor(node));
  8638. return;
  8639. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  8640. kind == FORM_TEXTAREA) {
  8641. fs->caret = fs->len;
  8642. }
  8643. if (changed) {
  8644. js_browser_event(node, "input", 1, 0);
  8645. js_browser_event(node, "change", 1, 0);
  8646. }
  8647. layout_valid = 0;
  8648. ngui_invalidate(&ui);
  8649. }
  8650. static void form_focus_next(void)
  8651. {
  8652. unsigned int start = form_focus ? form_focus + 1 : 0;
  8653. unsigned int i;
  8654. form_blur();
  8655. for (i = start; i < doc.nnode; i++) {
  8656. if (form_is_control(i) && !form_disabled(i) &&
  8657. !s_eq(br_type(&doc, i), "hidden")) {
  8658. form_focus = i;
  8659. layout_valid = 0;
  8660. ngui_invalidate(&ui);
  8661. return;
  8662. }
  8663. }
  8664. form_focus = 0;
  8665. layout_valid = 0;
  8666. ngui_invalidate(&ui);
  8667. }
  8668. static void form_key(int k)
  8669. {
  8670. struct form_state *fs;
  8671. int kind;
  8672. if (!form_focus || form_focus >= doc.nnode) {
  8673. form_focus = 0;
  8674. return;
  8675. }
  8676. fs = form_get(form_focus, 1);
  8677. if (!fs || form_disabled(form_focus))
  8678. return;
  8679. kind = form_kind_of(form_focus);
  8680. if (kind == FORM_SELECT) {
  8681. unsigned int n = form_option_count(form_focus);
  8682. int changed = 0;
  8683. if (k == NGUI_KEY_UP && n) {
  8684. fs->selected = (unsigned char)
  8685. ((fs->selected + n - 1) % n);
  8686. changed = 1;
  8687. } else if (k == NGUI_KEY_DOWN && n) {
  8688. fs->selected = (unsigned char)
  8689. ((fs->selected + 1) % n);
  8690. changed = 1;
  8691. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  8692. form_blur();
  8693. layout_valid = 0;
  8694. ngui_invalidate(&ui);
  8695. return;
  8696. } else {
  8697. return;
  8698. }
  8699. if (changed) {
  8700. js_browser_event(form_focus, "input", 1, 0);
  8701. js_browser_event(form_focus, "change", 1, 0);
  8702. }
  8703. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  8704. if (k == ' ') {
  8705. form_click(form_focus);
  8706. return;
  8707. }
  8708. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  8709. form_blur();
  8710. layout_valid = 0;
  8711. ngui_invalidate(&ui);
  8712. }
  8713. return;
  8714. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  8715. kind == FORM_RESET) {
  8716. if (k == NGUI_KEY_ESC) {
  8717. form_blur();
  8718. layout_valid = 0;
  8719. ngui_invalidate(&ui);
  8720. } else if (k == '\r' || k == '\n' || k == ' ') {
  8721. form_click(form_focus);
  8722. }
  8723. return;
  8724. } else if (k == NGUI_KEY_TAB) {
  8725. form_focus_next();
  8726. return;
  8727. } else if (k == NGUI_KEY_ESC) {
  8728. form_blur();
  8729. layout_valid = 0;
  8730. ngui_invalidate(&ui);
  8731. return;
  8732. } else if (k == '\r' || k == '\n') {
  8733. unsigned int node = form_focus;
  8734. form_blur();
  8735. if (form_ancestor(node))
  8736. form_submit_form(node, 1);
  8737. layout_valid = 0;
  8738. ngui_invalidate(&ui);
  8739. return;
  8740. } else if (k == NGUI_KEY_BACKSPACE) {
  8741. if (fs->caret) {
  8742. unsigned int i = --fs->caret;
  8743. for (; i < fs->len; i++)
  8744. fs->value[i] = fs->value[i + 1];
  8745. if (fs->len)
  8746. fs->len--;
  8747. form_dirty = 1;
  8748. js_browser_event(form_focus, "input", 1, 0);
  8749. }
  8750. } else if (k == NGUI_KEY_DELETE) {
  8751. if (fs->caret < fs->len) {
  8752. unsigned int i;
  8753. for (i = fs->caret; i < fs->len; i++)
  8754. fs->value[i] = fs->value[i + 1];
  8755. fs->len--;
  8756. form_dirty = 1;
  8757. js_browser_event(form_focus, "input", 1, 0);
  8758. }
  8759. } else if (k == NGUI_KEY_LEFT) {
  8760. if (fs->caret)
  8761. fs->caret--;
  8762. } else if (k == NGUI_KEY_RIGHT) {
  8763. if (fs->caret < fs->len)
  8764. fs->caret++;
  8765. } else if (k == NGUI_KEY_HOME) {
  8766. fs->caret = 0;
  8767. } else if (k == NGUI_KEY_END) {
  8768. fs->caret = fs->len;
  8769. } else if (k >= 32 && k < 127) {
  8770. if (fs->len < FORM_VALUE_MAX) {
  8771. unsigned int i;
  8772. for (i = fs->len; i > fs->caret; i--)
  8773. fs->value[i] = fs->value[i - 1];
  8774. fs->value[fs->caret++] = (char)k;
  8775. fs->len++;
  8776. form_dirty = 1;
  8777. js_browser_event(form_focus, "input", 1, 0);
  8778. }
  8779. } else {
  8780. return;
  8781. }
  8782. fs->value[fs->len] = '\0';
  8783. layout_valid = 0;
  8784. ngui_invalidate(&ui);
  8785. }
  8786. static void handle_page_click(unsigned int *action)
  8787. {
  8788. int node;
  8789. char url[BR_URL_MAX];
  8790. if (!ui.pressed)
  8791. return;
  8792. if (ui.press_x < page_rect.x ||
  8793. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  8794. ui.press_y < page_rect.y ||
  8795. ui.press_y >= page_rect.y + page_rect.h)
  8796. return;
  8797. node = find_hit(ui.press_x, ui.press_y);
  8798. if (!node)
  8799. return;
  8800. if (form_is_control((unsigned int)node)) {
  8801. form_click((unsigned int)node);
  8802. return;
  8803. }
  8804. form_blur();
  8805. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  8806. return;
  8807. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  8808. sizeof(url)) != 0)
  8809. return;
  8810. s_copy(click_url, url, sizeof(click_url));
  8811. *action |= ACT_NAV;
  8812. }
  8813. void _start(const char *arg)
  8814. {
  8815. struct win_info wi;
  8816. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  8817. u_win_create(960, 640, "Browser", &wi) != 0 &&
  8818. u_win_create(780, 540, "Browser", &wi) != 0) {
  8819. u_puts("browser: no graphics window\n");
  8820. u_exit(1);
  8821. }
  8822. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  8823. url_in.placeholder = "http://...";
  8824. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  8825. ui.theme.accent);
  8826. br_set_viewport(wi.width);
  8827. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  8828. s_copy(cwd, "/", sizeof(cwd));
  8829. heap_clear();
  8830. origin_cache_load();
  8831. css_cache_init();
  8832. script_cache_init();
  8833. page_scroll.offset = 0;
  8834. page_scroll.content_h = 0;
  8835. if (arg && arg[0]) {
  8836. navigate(arg, 1);
  8837. } else {
  8838. load_home(1);
  8839. /* Start ready to type: keep the home page, but leave the address
  8840. * bar empty instead of showing "about:home". */
  8841. ngui_input_set(&url_in, "");
  8842. ngui_set_focus(&ui, ID_URL);
  8843. }
  8844. for (;;) {
  8845. unsigned int action = 0;
  8846. unsigned int now;
  8847. click_url[0] = '\0';
  8848. if (pending_action) {
  8849. action |= pending_action & ACT_WAIT_NAV;
  8850. if (pending_url[0])
  8851. s_copy(click_url, pending_url, sizeof(click_url));
  8852. pending_action = 0;
  8853. pending_url[0] = '\0';
  8854. cancel_fetch = 0;
  8855. } else if (preload_active) {
  8856. if (preload_wait)
  8857. preload_wait = 0;
  8858. else
  8859. preload_step();
  8860. } else if ((preload_pending &&
  8861. page_scroll.offset != preload_scroll) ||
  8862. (preload_rescan && layout_valid)) {
  8863. preload_scroll = page_scroll.offset;
  8864. preload_rescan = 0;
  8865. preload_pending = 0;
  8866. preload_node = 0;
  8867. preload_active = 1;
  8868. }
  8869. js_browser_tick();
  8870. if (pending_action)
  8871. continue;
  8872. now = u_ticks_ms();
  8873. if (status_until && (int)(now - status_until) >= 0) {
  8874. status_text[0] = '\0';
  8875. status_until = 0;
  8876. status_error = 0;
  8877. ngui_invalidate(&ui);
  8878. }
  8879. if (!ngui_begin(&ui)) {
  8880. /* A queued navigation (e.g. Enter in the URL bar during
  8881. * a slow fetch) must be handled even when this frame
  8882. * needs no redraw. */
  8883. if (!action) {
  8884. fetch_workers_stop_if_unfocused();
  8885. u_sleep_ms(10);
  8886. continue;
  8887. }
  8888. } else {
  8889. draw(&action);
  8890. handle_keys(&action);
  8891. handle_page_click(&action);
  8892. ngui_end(&ui);
  8893. }
  8894. if (action & ACT_NAV) {
  8895. if (click_url[0]) {
  8896. navigate(click_url, 1);
  8897. click_url[0] = '\0';
  8898. } else {
  8899. navigate(url_in.text, 1);
  8900. }
  8901. }
  8902. if (action & ACT_BACK) {
  8903. if (hist_pos > 0) {
  8904. hist_pos--;
  8905. navigate(history[hist_pos], 0);
  8906. }
  8907. }
  8908. if (action & ACT_FORWARD) {
  8909. if (hist_pos + 1 < hist_len) {
  8910. hist_pos++;
  8911. navigate(history[hist_pos], 0);
  8912. }
  8913. }
  8914. if (action & ACT_RELOAD) {
  8915. if (s_eq(page_url, "about:home"))
  8916. load_home(0);
  8917. else
  8918. navigate(page_url, 0);
  8919. }
  8920. if (action & ACT_HOME)
  8921. load_home(1);
  8922. if (action & ACT_CLOSE)
  8923. quit = 1;
  8924. if (quit)
  8925. break;
  8926. if (pending_action)
  8927. continue;
  8928. fetch_workers_stop_if_unfocused();
  8929. u_sleep_ms(10);
  8930. }
  8931. fetch_workers_stop_all();
  8932. u_win_close();
  8933. u_exit(0);
  8934. }