browser.c 205 KB

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