browser.c 170 KB

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