browser.c 221 KB

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