browser.c 221 KB

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