browser.c 166 KB

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