browser.c 236 KB

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