browser.c 377 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137
  1. /* browser: a small HTML/CSS browser built on ngui, the image library and the
  2. * shared uhttp client.
  3. *
  4. * Page scripts run on the vendored QuickJS engine (modern ECMAScript) through
  5. * the DOM layer in js_browser.c; forms render and submit natively. External CSS is loaded over uhttp, and images are
  6. * decoded with img.c and drawn inline. Page-scoped buffers (page body,
  7. * rules and image bitmaps) come from the ring-3 libc heap; each image gets an
  8. * exact-size decode arena that is freed as soon as the scaled bitmap exists.
  9. * The DOM and the image/CSS I/O scratch use fixed static arenas.
  10. */
  11. #include <stdlib.h>
  12. #include <stdio.h>
  13. #include <string.h>
  14. #include <math.h>
  15. #include <ucmd_heap.h>
  16. #include "ucmd_lib.h"
  17. #include "ngui.h"
  18. #include "browser_html.h"
  19. #include "js_browser.h"
  20. #include "uhttp.h"
  21. #include "uhttp_cookie.h"
  22. #include "img.h"
  23. #include "inflate.h"
  24. #include "ufont.h"
  25. #include "svg_raster.h"
  26. static void svg_cache_clear(void);
  27. static unsigned char *decode_arena; /* see decode_arena_get() */
  28. static unsigned int decode_arena_size;
  29. /* Start wide enough for the desktop nav; smaller screens fall back to
  30. * 960x640 and 780x540, which still fit a 1024x768 panel. */
  31. #define BR_W 1100
  32. #define BR_H 700
  33. #define BR_TOOLBAR_H 30
  34. #define BR_STATUS_H 18
  35. #define BR_PAGE_MAX (2u * 1024u * 1024u)
  36. #define BR_IMG_FILE_MAX (1024u * 1024u)
  37. #define BR_IMG_PIX_MAX (8u * 1024u * 1024u)
  38. #define BR_MAX_IMAGES 256
  39. /* Decoded display bitmaps share the page heap: cap their total pixels
  40. * (RGB565 plus an optional alpha plane) instead of their count. */
  41. #define BR_IMG_PIXEL_BUDGET (4u * 1024u * 1024u)
  42. #define BR_IMG_DISP_BUDGET (6u * 1024u * 1024u)
  43. #define BR_IMG_ARENA_MAX (24u * 1024u * 1024u)
  44. #define BR_IMG_LAYOUT_W 1000
  45. /* Decode completed image jobs for at most this long per main-loop pass, then
  46. * return to input/painting. One image per pass plus a 10 ms sleep made a
  47. * page of small icons trickle in. */
  48. #define BR_IMG_DECODE_BUDGET_MS 40u
  49. /* Coalesce image-driven repaints: each decode invalidates the page, and a
  50. * full repaint per image made loading superlinear on image-heavy pages. */
  51. #define BR_IMG_REPAINT_MS 100u
  52. #define BR_IMG_STAT_LOG 3584
  53. /* An image job may hold a fetch helper this long. The page/script
  54. * deadline (UHTTP_TOTAL_TIMEOUT_MS) is minutes; one unreachable image host
  55. * must not starve the other images of all four helpers that long. */
  56. #define BR_IMG_JOB_TIMEOUT_MS 30000u
  57. #define BR_CSS_MAX (832u * 1024u)
  58. #define BR_CSS_COMP_MAX (192u * 1024u)
  59. /* Scripts and ES modules: Vite bundles reach ~1.7 MB (the Cloudron
  60. * dashboard's main chunk); the helper's FETCH_MAX is the same 2 MB. */
  61. #define BR_SCRIPT_MAX (2u * 1024u * 1024u)
  62. #define FETCH_ABORT (-2)
  63. /* Session cache for remote stylesheets (per launch; cleared at startup). */
  64. #define CSS_CACHE_MAX 16
  65. #define CSS_CACHE_FILE_MAX (256u * 1024u)
  66. #define CSS_CACHE_PREFIX "bcss-"
  67. #define SCRIPT_CACHE_MAX 24
  68. #define SCRIPT_CACHE_FILE_MAX BR_SCRIPT_MAX
  69. #define SCRIPT_CACHE_PREFIX "bjs-"
  70. /* Web fonts cached for the boot; /share holds 64 entries / 16 MB in all. */
  71. #define FONT_CACHE_MAX 8
  72. #define FONT_CACHE_PREFIX "bfont-"
  73. /* The ufont arena (built-in faces, @font-face files and glyph masks); the
  74. * 512 KB default holds the built-in set but not a page's web fonts. */
  75. #define BR_FONT_ARENA (3u * 1024u * 1024u)
  76. #define BR_MAX_SHEETS 6
  77. #define BR_HISTORY 16
  78. #define BR_URL_MAX 4096 /* = UHTTP_PATH_MAX: google.com's JS URL is ~3.7 KB */
  79. #define BR_STATUS_MAX 200
  80. #define BR_IMG_RGB565(r, g, b) \
  81. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  82. #define BR_GRAY 0x8410
  83. enum {
  84. ID_URL = 1,
  85. ID_GO,
  86. ID_BACK,
  87. ID_FORWARD,
  88. ID_RELOAD,
  89. ID_HOME
  90. };
  91. #define ACT_NAV (1u << 0)
  92. #define ACT_BACK (1u << 1)
  93. #define ACT_FORWARD (1u << 2)
  94. #define ACT_RELOAD (1u << 3)
  95. #define ACT_HOME (1u << 4)
  96. #define ACT_CLOSE (1u << 5)
  97. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  98. ACT_HOME | ACT_CLOSE)
  99. struct br_image {
  100. int state; /* 0 empty, 1 ready */
  101. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  102. int native_w, native_h;
  103. unsigned int url_hash; /* <img> source, 0 = not shareable */
  104. char err[32];
  105. /* Display-size cache: the box an image is actually painted in. The
  106. * source bitmap above is deliberately capped at BR_IMG_LAYOUT_W so a
  107. * window resize can re-scale it; the cached copy is exactly dw x dh,
  108. * so every repaint is a 1:1 blit instead of a per-pixel resample. */
  109. struct img_image disp;
  110. unsigned int disp_pixels;
  111. unsigned int disp_last;
  112. };
  113. static struct ngui ui;
  114. static struct ngui_input url_in;
  115. static struct ngui_scroll page_scroll;
  116. static struct br_doc doc;
  117. static struct br_image images[BR_MAX_IMAGES];
  118. static int image_count;
  119. static unsigned int image_pixels;
  120. static unsigned int image_disp_pixels;
  121. static unsigned int image_disp_clock;
  122. /* Per-image pipeline timing for the status line and /share/IMGSTAT. The
  123. * numbers are what decides whether the next work is network, decode or
  124. * display; keep them cheap (one tick read per phase). */
  125. static unsigned int img_stat_start;
  126. static unsigned int img_stat_wall;
  127. static unsigned int img_stat_net;
  128. static unsigned int img_stat_open;
  129. static unsigned int img_stat_first;
  130. static unsigned int img_stat_io;
  131. static unsigned int img_stat_dec;
  132. static unsigned int img_stat_scale;
  133. static unsigned int img_stat_paint;
  134. static unsigned int img_stat_reflow;
  135. static unsigned int img_stat_bytes;
  136. static int img_stat_n;
  137. static unsigned int img_last_dec_ms;
  138. static unsigned int img_last_scale_ms;
  139. static char img_stat_log[BR_IMG_STAT_LOG];
  140. static unsigned int img_stat_log_len;
  141. static unsigned int img_repaint_ms;
  142. static int img_repaint_pending;
  143. /* Painted border boxes, in page/screen coordinates (layout starts at
  144. * page_rect.y - scroll). getBoundingClientRect() subtracts page_rect. */
  145. struct br_layout_box {
  146. int x, y;
  147. int w, h;
  148. unsigned char valid;
  149. };
  150. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  151. /* Inline boxes are built from their line runs in flush_line(): a box is
  152. * replaced when a new layout pass (or a re-layout at the same or an
  153. * earlier line) reaches it, and grown when its runs continue on the same
  154. * or a later line of the same pass. inline_box_parent[] is the enclosing
  155. * inline box (node + 1), so nested spans grow their ancestors too. */
  156. static unsigned int inline_box_pass_id;
  157. static unsigned int inline_box_flush_id;
  158. static unsigned int inline_box_pass[BR_MAX_NODES];
  159. static unsigned int inline_box_flush[BR_MAX_NODES];
  160. static int inline_box_y[BR_MAX_NODES];
  161. static unsigned short inline_box_parent[BR_MAX_NODES];
  162. /* Images are loaded one per main-loop iteration so the parsed page stays
  163. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  164. static int preload_active;
  165. static int preload_max_jobs;
  166. static int preload_pending;
  167. static int preload_wait;
  168. static unsigned int preload_node;
  169. static int preload_loaded;
  170. static int preload_scroll;
  171. static int preload_rescan;
  172. static char post_status_text[BR_STATUS_MAX];
  173. static int post_status_error;
  174. static unsigned int post_status_ttl;
  175. /* Content-relative position/height of each <img>, recorded by the measure
  176. * pass so image loading can be deferred until it is near the viewport. */
  177. static unsigned short img_top[BR_MAX_NODES];
  178. static unsigned short img_h[BR_MAX_NODES];
  179. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  180. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  181. * body. Decode arenas are allocated per image instead of living here. */
  182. static unsigned char *image_io_buf;
  183. static struct ufont_face *font_faces[BR_MAX_FACES];
  184. /* [family id - 1][bold * 2 + italic] -> 1-based face id, 0 = built-in. */
  185. static unsigned char font_pick[BR_MAX_FACES][4];
  186. #define image_file_buf (image_io_buf)
  187. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  188. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  189. static struct inflate image_inflate_ws;
  190. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  191. #error "CSS scratch must fit in image_io_buf"
  192. #endif
  193. static char page_url[BR_URL_MAX];
  194. static char page_title[BR_TITLE_MAX];
  195. static char cwd[64];
  196. static int page_is_local;
  197. static int page_loading;
  198. static char status_text[BR_STATUS_MAX];
  199. static unsigned int status_until;
  200. static int status_error;
  201. static char history[BR_HISTORY][BR_URL_MAX];
  202. static int hist_len, hist_pos;
  203. static char click_url[BR_URL_MAX];
  204. static char pending_url[BR_URL_MAX];
  205. #define BR_POST_MAX 4096
  206. static char pending_post[BR_POST_MAX];
  207. static unsigned int pending_post_len;
  208. /* The pending navigation is a POST even when its body is empty (a form
  209. * without fields, e.g. the OIDC consent auto-submit). */
  210. static int pending_post_is;
  211. /* window "resize" bookkeeping: the page width the last event was for. */
  212. static int resize_sent_w = -1;
  213. static int resize_pending;
  214. static unsigned int pending_action;
  215. static int cancel_fetch;
  216. static int quit;
  217. static struct ngui_rect page_rect;
  218. static unsigned short *page_backbuf;
  219. static int pagebuf_w, pagebuf_h;
  220. static int page_cache_valid;
  221. static int page_cache_scroll;
  222. static unsigned int page_cache_nnode;
  223. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  224. static int layout_valid, layout_left, layout_right;
  225. /* Height of the page viewport: what html/body height:100% resolves to. */
  226. static int layout_view_h;
  227. static unsigned int layout_nnode;
  228. static int layout_content_h;
  229. /* layout output */
  230. struct lay_run {
  231. unsigned int off;
  232. unsigned short len;
  233. unsigned short gap;
  234. unsigned short color;
  235. unsigned short href;
  236. char lit[28];
  237. short img;
  238. signed short dy; /* inline image vertical offset */
  239. unsigned short iw, ih;
  240. unsigned short w;
  241. unsigned char font_px, bold, italic, mono, underline, strike;
  242. unsigned char overline, font_face;
  243. unsigned char transform_scale;
  244. unsigned char origin_x_kind, origin_y_kind;
  245. signed short scale_x, scale_y, rotate_x100;
  246. signed short origin_x, origin_y;
  247. unsigned char has_lit;
  248. unsigned int form; /* node + 1, 0 = not a control */
  249. unsigned char form_kind;
  250. unsigned char form_disabled;
  251. /* RUN_PBOX: background colour, background image and its placement
  252. * inside the iw x ih box (relative offsets, drawn size). */
  253. unsigned char pb_has_bg;
  254. unsigned short pb_bg;
  255. short pb_img;
  256. short pb_x, pb_y, pb_w, pb_h;
  257. /* Innermost inline element (node + 1) whose box this run belongs
  258. * to, 0 = none; flush_line() unions the placed runs into
  259. * layout_boxes[] so getBoundingClientRect() sees inline boxes. */
  260. unsigned short box;
  261. };
  262. struct lay {
  263. int draw;
  264. struct ngui *ui;
  265. int left, right;
  266. int y;
  267. int line_x, line_y, line_h;
  268. int line_left, line_right;
  269. int parent_top;
  270. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  271. int cb_h; /* definite content height of the containing block for
  272. * percentage heights; 0 = indefinite (auto) */
  273. int run_x;
  274. int align;
  275. int depth;
  276. int space_pending;
  277. unsigned char float_active;
  278. int float_left, float_right, float_bottom;
  279. struct lay_run runs[96];
  280. int nruns;
  281. unsigned short box_owner; /* node + 1 of the open inline box */
  282. };
  283. struct hit {
  284. int x, y, w, h;
  285. unsigned short node;
  286. };
  287. /* Live form state; the DOM attributes stay the initial/default value. */
  288. #define FORM_MAX 64
  289. #define FORM_VALUE_MAX 63
  290. enum {
  291. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  292. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  293. };
  294. struct form_state {
  295. unsigned int node;
  296. char value[FORM_VALUE_MAX + 1];
  297. unsigned char len, caret, checked, selected, used;
  298. };
  299. static struct form_state form_states[FORM_MAX];
  300. static unsigned int form_focus;
  301. static unsigned int form_dirty;
  302. static int form_descendant(unsigned int node, unsigned int form);
  303. static int form_submit_form(unsigned int node, int fire_event);
  304. static int link_fragment_nav(unsigned int node);
  305. static void history_push(const char *url);
  306. static void form_reset_event(unsigned int form);
  307. static unsigned int s_len(const char *s);
  308. static int s_eq(const char *a, const char *b);
  309. static void form_key(int k);
  310. static void form_click(unsigned int node);
  311. static void style_for_node(unsigned int node, struct br_style *out);
  312. static int form_author_styled(const struct br_style *st);
  313. static int css_radius(const struct br_style *st, int corner, int w, int h);
  314. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  315. const struct br_style *st, int focused);
  316. static int form_disabled(unsigned int node)
  317. {
  318. struct br_node *n = &doc.nodes[node];
  319. if (n->attr_flags & BR_ATTR_DISABLED)
  320. return 1;
  321. return br_find_attr(&doc, node, "disabled") != 0;
  322. }
  323. static int form_kind_of(unsigned int node)
  324. {
  325. const char *type = br_type(&doc, node);
  326. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  327. return FORM_TEXTAREA;
  328. if (doc.nodes[node].tag == BR_TAG_SELECT)
  329. return FORM_SELECT;
  330. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  331. if (s_eq(type, "reset"))
  332. return FORM_RESET;
  333. if (s_eq(type, "button"))
  334. return FORM_BUTTON;
  335. return FORM_SUBMIT;
  336. }
  337. if (s_eq(type, "password"))
  338. return FORM_PASSWORD;
  339. if (s_eq(type, "checkbox"))
  340. return FORM_CHECKBOX;
  341. if (s_eq(type, "radio"))
  342. return FORM_RADIO;
  343. if (s_eq(type, "submit"))
  344. return FORM_SUBMIT;
  345. if (s_eq(type, "reset"))
  346. return FORM_RESET;
  347. if (s_eq(type, "button"))
  348. return FORM_BUTTON;
  349. return FORM_TEXT;
  350. }
  351. static unsigned int form_option_count(unsigned int node)
  352. {
  353. unsigned int c, n = 0;
  354. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  355. if (doc.nodes[c].type == BR_NODE_ELEM &&
  356. doc.nodes[c].tag == BR_TAG_OPTION)
  357. n++;
  358. return n;
  359. }
  360. static unsigned int form_option_selected(unsigned int node)
  361. {
  362. unsigned int c, i = 0;
  363. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  364. if (doc.nodes[c].type != BR_NODE_ELEM ||
  365. doc.nodes[c].tag != BR_TAG_OPTION)
  366. continue;
  367. if (br_find_attr(&doc, c, "selected"))
  368. return i;
  369. i++;
  370. }
  371. return 0;
  372. }
  373. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  374. char *out, unsigned int cap)
  375. {
  376. unsigned int c, i = 0;
  377. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  378. if (doc.nodes[c].type != BR_NODE_ELEM ||
  379. doc.nodes[c].tag != BR_TAG_OPTION)
  380. continue;
  381. if (i == idx)
  382. return br_text_content(&doc, c, out, cap);
  383. i++;
  384. }
  385. return 0;
  386. }
  387. static int form_is_control(unsigned int node);
  388. static struct form_state *form_get(unsigned int node, int create)
  389. {
  390. struct form_state *slot = 0;
  391. unsigned int i;
  392. for (i = 0; i < FORM_MAX; i++) {
  393. if (form_states[i].used) {
  394. if (form_states[i].node == node)
  395. return &form_states[i];
  396. } else if (!slot) {
  397. slot = &form_states[i];
  398. }
  399. }
  400. if (create && !slot) {
  401. /* Full: a client-side router (Docusaurus' React Router)
  402. * replaces page content without a navigation, so slots of
  403. * controls that left the document pile up until no new
  404. * control can be drawn or focused.
  405. * Reuse those first, then slots of nodes that are no longer
  406. * controls. */
  407. for (i = 0; i < FORM_MAX && !slot; i++)
  408. if (form_states[i].node != form_focus &&
  409. br_node_detached(&doc, form_states[i].node))
  410. slot = &form_states[i];
  411. for (i = 0; i < FORM_MAX && !slot; i++)
  412. if (form_states[i].node != form_focus &&
  413. !form_is_control(form_states[i].node))
  414. slot = &form_states[i];
  415. }
  416. if (!create || !slot)
  417. return 0;
  418. slot->node = node;
  419. slot->len = 0;
  420. slot->caret = 0;
  421. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  422. slot->selected = form_option_selected(node);
  423. slot->used = 1;
  424. {
  425. unsigned int n = 0;
  426. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  427. n = br_text_content(&doc, node, slot->value,
  428. FORM_VALUE_MAX + 1);
  429. } else {
  430. const char *v = br_value(&doc, node);
  431. if (v) {
  432. n = s_len(v);
  433. if (n > FORM_VALUE_MAX)
  434. n = FORM_VALUE_MAX;
  435. for (unsigned int j = 0; j < n; j++)
  436. slot->value[j] = v[j];
  437. }
  438. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  439. n = br_text_content(&doc, node, slot->value,
  440. FORM_VALUE_MAX + 1);
  441. }
  442. if (n > FORM_VALUE_MAX)
  443. n = FORM_VALUE_MAX;
  444. slot->value[n] = '\0';
  445. slot->len = (unsigned char)n;
  446. slot->caret = (unsigned char)n;
  447. }
  448. return slot;
  449. }
  450. static void form_reset_state(void)
  451. {
  452. unsigned int i;
  453. for (i = 0; i < FORM_MAX; i++)
  454. form_states[i].used = 0;
  455. form_focus = 0;
  456. }
  457. /* A <button> with element content (an icon <svg>/<img>, a <span> label)
  458. * is laid out like a normal element so that content shows; only a text or
  459. * empty button is drawn as a native control. Clicks still reach it
  460. * through the box hit test. */
  461. static int button_has_elements(unsigned int node)
  462. {
  463. unsigned int c;
  464. if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
  465. return 0;
  466. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  467. if (doc.nodes[c].type == BR_NODE_ELEM)
  468. return 1;
  469. /* An empty button whose icon is a ::before/::after box (Docusaurus'
  470. * sidebar caret) is laid out as an element so the box is drawn. */
  471. if (!doc.nodes[node].first && doc.npe_rules) {
  472. struct br_style st, ps;
  473. char buf[8];
  474. int pe;
  475. style_for_node(node, &st);
  476. for (pe = 1; pe <= 2; pe++)
  477. if (!br_pseudo(&doc, node, pe, &st, &ps, buf,
  478. sizeof(buf)) &&
  479. ps.content == BR_CONTENT_EMPTY &&
  480. ps.display != BR_DISPLAY_NONE)
  481. return 1;
  482. }
  483. return 0;
  484. }
  485. static int form_is_control(unsigned int node)
  486. {
  487. unsigned int tag;
  488. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  489. return 0;
  490. tag = doc.nodes[node].tag;
  491. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  492. tag == BR_TAG_SELECT ||
  493. (tag == BR_TAG_BUTTON && !button_has_elements(node));
  494. }
  495. #define HIT_MAX 96
  496. static struct hit hits[HIT_MAX];
  497. static int nhits;
  498. static unsigned short block_h[BR_MAX_NODES];
  499. /* Border-box height a flex container stretches an item to (align-items:
  500. * stretch in a row with a taller line or a definite height), 0 = none.
  501. * Written by the measure pass, read by both. */
  502. static unsigned short flex_stretch_h[BR_MAX_NODES];
  503. /* Measure-pass top of each block, in the same document coordinates as
  504. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  505. * paint, so it cannot drive the lazy background loader). */
  506. static unsigned short block_top[BR_MAX_NODES];
  507. static char li_marker[BR_MAX_NODES][12];
  508. /* one connection object; the browser fetches one resource at a time */
  509. /* ---- tiny strings ---- */
  510. static unsigned int s_len(const char *s)
  511. {
  512. unsigned int n = 0;
  513. while (s && s[n])
  514. n++;
  515. return n;
  516. }
  517. static void s_copy(char *d, const char *s, unsigned int cap)
  518. {
  519. unsigned int i = 0;
  520. if (!cap)
  521. return;
  522. while (s && s[i] && i + 1 < cap) {
  523. d[i] = s[i];
  524. i++;
  525. }
  526. d[i] = '\0';
  527. }
  528. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  529. {
  530. while (s && *s && *n + 1 < cap)
  531. d[(*n)++] = *s++;
  532. d[*n] = '\0';
  533. }
  534. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  535. unsigned int cap)
  536. {
  537. char tmp[12];
  538. unsigned int i = 0, j;
  539. do {
  540. tmp[i++] = (char)('0' + v % 10);
  541. v /= 10;
  542. } while (v && i < sizeof(tmp));
  543. for (j = 0; j < i && *n + 1 < cap; j++)
  544. d[(*n)++] = tmp[i - 1 - j];
  545. d[*n] = '\0';
  546. }
  547. static int s_eq(const char *a, const char *b)
  548. {
  549. while (*a && *b) {
  550. if (*a != *b)
  551. return 0;
  552. a++;
  553. b++;
  554. }
  555. return *a == *b;
  556. }
  557. static int starts_with(const char *s, const char *p)
  558. {
  559. unsigned int i = 0;
  560. while (p[i]) {
  561. if (s[i] != p[i])
  562. return 0;
  563. i++;
  564. }
  565. return 1;
  566. }
  567. static int contains_ci(const char *s, const char *p)
  568. {
  569. unsigned int i, j;
  570. for (i = 0; s[i]; i++) {
  571. for (j = 0; p[j]; j++) {
  572. char a = s[i + j];
  573. if (a >= 'A' && a <= 'Z')
  574. a = (char)(a - 'A' + 'a');
  575. if (a != p[j])
  576. break;
  577. }
  578. if (!p[j])
  579. return 1;
  580. }
  581. return 0;
  582. }
  583. static char *trim(char *s)
  584. {
  585. unsigned int n;
  586. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  587. s++;
  588. n = s_len(s);
  589. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  590. s[n - 1] == '\r' || s[n - 1] == '\n'))
  591. s[--n] = '\0';
  592. return s;
  593. }
  594. /* ---- per-process heap ---- */
  595. static int heap_start(void)
  596. {
  597. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  598. if (!image_io_buf)
  599. return -1;
  600. page_backbuf = (unsigned short *)malloc(
  601. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  602. pagebuf_w = page_backbuf ? ui.w : 0;
  603. pagebuf_h = page_backbuf ? ui.h : 0;
  604. page_cache_valid = 0;
  605. return 0;
  606. }
  607. static void heap_clear(void)
  608. {
  609. memset(font_faces, 0, sizeof(font_faces));
  610. memset(font_pick, 0, sizeof(font_pick));
  611. ngui_font_detach(&ui);
  612. svg_cache_clear();
  613. decode_arena = 0; /* lives in the page heap too */
  614. decode_arena_size = 0;
  615. heap_reset();
  616. /* The document arenas live in that heap; drop the stale pointers so
  617. * the next br_parse_plain() allocates fresh ones. */
  618. doc.nodes = 0;
  619. doc.text = 0;
  620. doc.attrs = 0;
  621. image_io_buf = 0;
  622. page_backbuf = 0;
  623. pagebuf_w = pagebuf_h = 0;
  624. page_cache_valid = 0;
  625. }
  626. static void browser_rules_alloc(void)
  627. {
  628. struct br_rule *rules;
  629. rules = (struct br_rule *)malloc(
  630. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  631. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  632. }
  633. /* ---- status ---- */
  634. static void set_status(const char *s, int err, unsigned int ttl_ms)
  635. {
  636. s_copy(status_text, s, sizeof(status_text));
  637. status_error = err;
  638. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  639. ngui_invalidate(&ui);
  640. }
  641. /* Update the status text without forcing a frame; the throttled image
  642. * repaint picks it up. Starting one helper per image used to invalidate the
  643. * whole page before every decode. */
  644. static void set_status_quiet(const char *s)
  645. {
  646. s_copy(status_text, s, sizeof(status_text));
  647. status_error = 0;
  648. status_until = 0;
  649. }
  650. /* ---- JavaScript ---- */
  651. static int resolve_link(const char *base, const char *href, char *out,
  652. unsigned int cap);
  653. static char js_last_status[BR_STATUS_MAX];
  654. static int js_last_error;
  655. static void js_host_status(const char *msg, int error)
  656. {
  657. s_copy(js_last_status, msg, sizeof(js_last_status));
  658. js_last_error = error;
  659. set_status(msg, error, 6000);
  660. }
  661. static void js_host_report(const char *msg)
  662. {
  663. u_puts("[js] ");
  664. u_puts(msg);
  665. u_putc('\n');
  666. s_copy(js_last_status, msg, sizeof(js_last_status));
  667. js_last_error = 1;
  668. set_status(msg, 1, 8000);
  669. }
  670. static void js_host_navigate(const char *url)
  671. {
  672. char resolved[BR_URL_MAX];
  673. if (!url || !url[0])
  674. return;
  675. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  676. return;
  677. s_copy(pending_url, resolved, sizeof(pending_url));
  678. pending_action |= ACT_NAV;
  679. cancel_fetch = 1;
  680. }
  681. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  682. * back/forward between fragments): the page URL, address bar and history
  683. * follow, nothing is reloaded. `push` adds a history entry. */
  684. static int page_set_fragment(const char *url, int push)
  685. {
  686. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  687. return -1;
  688. s_copy(page_url, url, sizeof(page_url));
  689. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  690. url_in.len = s_len(url_in.text);
  691. url_in.cursor = url_in.len;
  692. url_in.scroll = 0;
  693. if (push)
  694. history_push(page_url);
  695. ngui_invalidate(&ui);
  696. return 0;
  697. }
  698. static int js_host_set_hash(const char *url)
  699. {
  700. return page_set_fragment(url, 1);
  701. }
  702. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  703. * the page, so a hash router can react). */
  704. static int same_doc_fragment(const char *url)
  705. {
  706. unsigned int a = 0, b = 0;
  707. if (!js_browser_active() || !url)
  708. return 0;
  709. while (url[a] && url[a] != '#')
  710. a++;
  711. while (page_url[b] && page_url[b] != '#')
  712. b++;
  713. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  714. !s_eq(url, page_url);
  715. }
  716. static void js_host_changed(void)
  717. {
  718. /* Class/style/attribute mutations change computed styles, not just the
  719. * text: drop the per-node style cache before the next layout. */
  720. br_reset_styles(&doc);
  721. layout_valid = 0;
  722. /* Script-built content (Angular's ng-repeat cards) brings new images
  723. * and inline background styles: rescan once the main loop is idle. */
  724. preload_rescan = 1;
  725. ngui_invalidate(&ui);
  726. }
  727. static void js_force_layout(void);
  728. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  729. {
  730. if (node >= BR_MAX_NODES)
  731. return 0;
  732. /* A geometry read after a DOM change gets a synchronous layout, like
  733. * a browser's forced reflow: Bootstrap's tooltip inserts itself,
  734. * reads offsetWidth, then moves itself twice with $.offset(), which
  735. * reads its own current position each time. */
  736. if (!layout_valid)
  737. js_force_layout();
  738. if (!layout_boxes[node].valid)
  739. return 0;
  740. *x = layout_boxes[node].x - page_rect.x;
  741. *y = layout_boxes[node].y - page_rect.y;
  742. *w = layout_boxes[node].w;
  743. *h = layout_boxes[node].h;
  744. return 1;
  745. }
  746. static void form_copy_out(const char *s, char *buf, int cap)
  747. {
  748. int i = 0;
  749. if (!buf || cap <= 0)
  750. return;
  751. while (s && s[i] && i + 1 < cap) {
  752. buf[i] = s[i];
  753. i++;
  754. }
  755. buf[i] = '\0';
  756. }
  757. static int js_host_form_value(unsigned int node, char *buf, int cap)
  758. {
  759. struct form_state *fs;
  760. int kind;
  761. if (!form_is_control(node))
  762. return 0;
  763. kind = form_kind_of(node);
  764. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  765. return 0;
  766. if (kind == FORM_SELECT) {
  767. char opt[64] = "";
  768. unsigned int c, i = 0;
  769. fs = form_get(node, 1);
  770. if (!fs)
  771. return 0;
  772. form_option_text(node, fs->selected, opt, sizeof(opt));
  773. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  774. if (doc.nodes[c].type != BR_NODE_ELEM ||
  775. doc.nodes[c].tag != BR_TAG_OPTION)
  776. continue;
  777. if (i == fs->selected) {
  778. const char *v = br_value(&doc, c);
  779. if (v && v[0])
  780. form_copy_out(v, buf, cap);
  781. else
  782. form_copy_out(opt, buf, cap);
  783. return 1;
  784. }
  785. i++;
  786. }
  787. form_copy_out(opt, buf, cap);
  788. return 1;
  789. }
  790. fs = form_get(node, 1);
  791. if (!fs)
  792. return 0;
  793. form_copy_out(fs->value, buf, cap);
  794. return 1;
  795. }
  796. static int js_host_form_checked(unsigned int node)
  797. {
  798. struct form_state *fs;
  799. int kind;
  800. if (!form_is_control(node))
  801. return -1;
  802. kind = form_kind_of(node);
  803. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  804. return -1;
  805. fs = form_get(node, 1);
  806. return fs ? fs->checked : 0;
  807. }
  808. static int js_host_form_selected(unsigned int node)
  809. {
  810. struct form_state *fs;
  811. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  812. return -1;
  813. fs = form_get(node, 1);
  814. return fs ? fs->selected : 0;
  815. }
  816. static int js_host_form_set_value(unsigned int node, const char *value)
  817. {
  818. struct form_state *fs;
  819. unsigned int n;
  820. if (!form_is_control(node))
  821. return 0;
  822. fs = form_get(node, 1);
  823. if (!fs)
  824. return 0;
  825. n = s_len(value ? value : "");
  826. if (n > FORM_VALUE_MAX)
  827. n = FORM_VALUE_MAX;
  828. for (unsigned int i = 0; i < n; i++)
  829. fs->value[i] = value[i];
  830. fs->value[n] = '\0';
  831. fs->len = (unsigned char)n;
  832. fs->caret = (unsigned char)n;
  833. layout_valid = 0;
  834. ngui_invalidate(&ui);
  835. return 1;
  836. }
  837. static int js_host_form_set_checked(unsigned int node, int checked)
  838. {
  839. struct form_state *fs;
  840. int kind;
  841. if (!form_is_control(node))
  842. return 0;
  843. kind = form_kind_of(node);
  844. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  845. return 0;
  846. fs = form_get(node, 1);
  847. if (!fs)
  848. return 0;
  849. fs->checked = (unsigned char)(checked != 0);
  850. layout_valid = 0;
  851. ngui_invalidate(&ui);
  852. return 1;
  853. }
  854. static int js_host_form_set_selected(unsigned int node, int index)
  855. {
  856. struct form_state *fs;
  857. unsigned int n;
  858. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  859. return 0;
  860. fs = form_get(node, 1);
  861. if (!fs)
  862. return 0;
  863. n = form_option_count(node);
  864. if (index < 0)
  865. index = 0;
  866. if (n && (unsigned int)index >= n)
  867. index = (int)n - 1;
  868. fs->selected = (unsigned char)index;
  869. layout_valid = 0;
  870. ngui_invalidate(&ui);
  871. return 1;
  872. }
  873. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  874. {
  875. unsigned int i;
  876. int n = 0;
  877. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  878. doc.nodes[form].tag != BR_TAG_FORM)
  879. return 0;
  880. for (i = 0; i < doc.nnode && n < cap; i++) {
  881. struct br_node *nd = &doc.nodes[i];
  882. if (i == form || nd->type != BR_NODE_ELEM)
  883. continue;
  884. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  885. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  886. continue;
  887. if (!form_descendant(i, form))
  888. continue;
  889. out[n++] = i;
  890. }
  891. return n;
  892. }
  893. static int js_host_form_submit(unsigned int form)
  894. {
  895. form_submit_form(form, 0);
  896. return 1;
  897. }
  898. static int js_host_form_reset(unsigned int form)
  899. {
  900. form_reset_event(form);
  901. return 1;
  902. }
  903. static void css_computed_name(const char *p, char *out, int cap)
  904. {
  905. int n = 0;
  906. for (; p && *p && n + 2 < cap; p++) {
  907. char c = *p;
  908. if (c >= 'A' && c <= 'Z') {
  909. out[n++] = '-';
  910. c = (char)(c - 'A' + 'a');
  911. } else if (c == '_') {
  912. c = '-';
  913. } else if (c >= 'a' && c <= 'z') {
  914. /* keep */
  915. }
  916. out[n++] = c;
  917. }
  918. out[n] = '\0';
  919. if (!strcmp(out, "css-float"))
  920. strcpy(out, "float");
  921. }
  922. static void css_rgb(unsigned short c, char *buf, int cap)
  923. {
  924. int r = ((c >> 11) & 31) * 255 / 31;
  925. int g = ((c >> 5) & 63) * 255 / 63;
  926. int b = (c & 31) * 255 / 31;
  927. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  928. }
  929. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  930. int font_px)
  931. {
  932. if (unit == 4) {
  933. snprintf(buf, cap, "auto");
  934. } else if (unit == 0) {
  935. snprintf(buf, cap, "%dpx", raw);
  936. } else if (unit == 1) {
  937. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  938. } else if (unit == 2) {
  939. /* Chrome's getComputedStyle() reports used pixel values. */
  940. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  941. } else if (unit == 3) {
  942. snprintf(buf, cap, "%dpx",
  943. (int)br_root_font_px() * raw / 100);
  944. } else {
  945. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  946. raw / 100, raw % 100, px);
  947. }
  948. }
  949. static int js_host_computed(unsigned int node, const char *property,
  950. char *buf, int cap)
  951. {
  952. struct br_style st;
  953. char name[40];
  954. /* Node 0 is a real element when the page starts with <html>. */
  955. if (!buf || cap <= 0 || node >= doc.nnode ||
  956. (node == 0 && doc.nodes[0].type != BR_NODE_ELEM))
  957. return 0;
  958. buf[0] = '\0';
  959. css_computed_name(property, name, sizeof(name));
  960. style_for_node(node, &st);
  961. if (!strcmp(name, "display")) {
  962. const char *v = "inline";
  963. if (st.display == BR_DISPLAY_BLOCK)
  964. v = "block";
  965. else if (st.display == BR_DISPLAY_NONE)
  966. v = "none";
  967. else if (st.display == BR_DISPLAY_FLEX)
  968. v = "flex";
  969. else if (st.display == BR_DISPLAY_GRID)
  970. v = "grid";
  971. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  972. v = "inline-block";
  973. snprintf(buf, cap, "%s", v);
  974. } else if (!strcmp(name, "position")) {
  975. static const char *pos[] = {
  976. "static", "absolute", "fixed", "relative", "sticky"
  977. };
  978. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  979. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  980. int is_w = name[0] == 'w';
  981. int kind = is_w ? st.width_kind : st.height_kind;
  982. int val = is_w ? st.width : st.height;
  983. if (kind == 3) {
  984. if (is_w)
  985. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  986. st.width_calc_pct / 100,
  987. st.width_calc_pct % 100,
  988. st.width_calc_px);
  989. else
  990. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  991. st.height_calc_pct / 100,
  992. st.height_calc_pct % 100,
  993. st.height_calc_px);
  994. } else if (kind == 1) {
  995. snprintf(buf, cap, "%dpx", val);
  996. } else if (kind == 2) {
  997. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  998. } else {
  999. snprintf(buf, cap, "auto");
  1000. }
  1001. } else if (!strcmp(name, "color") ||
  1002. !strcmp(name, "background-color")) {
  1003. if (!strcmp(name, "background-color") && !st.has_bg)
  1004. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1005. else
  1006. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  1007. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  1008. int is_fill = name[0] == 'f';
  1009. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  1010. if (mode == BR_PAINT_COLOR)
  1011. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  1012. else if (mode == BR_PAINT_CURRENT)
  1013. css_rgb(st.color, buf, cap);
  1014. else if (mode == BR_PAINT_UNSET && is_fill)
  1015. snprintf(buf, cap, "rgb(0, 0, 0)");
  1016. else if (mode == BR_PAINT_URL)
  1017. snprintf(buf, cap, "url()");
  1018. else
  1019. snprintf(buf, cap, "none");
  1020. } else if (!strcmp(name, "font-size")) {
  1021. snprintf(buf, cap, "%dpx", st.font_px);
  1022. } else if (!strcmp(name, "font-weight")) {
  1023. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  1024. } else if (!strcmp(name, "font-style")) {
  1025. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  1026. } else if (!strcmp(name, "font-family")) {
  1027. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  1028. br_font_face_family(st.font_face)[0])
  1029. snprintf(buf, cap, "%s",
  1030. br_font_face_family(st.font_face));
  1031. else
  1032. snprintf(buf, cap, "%s",
  1033. st.mono ? "monospace" : "sans-serif");
  1034. } else if (!strcmp(name, "text-align")) {
  1035. static const char *al[] = { "left", "center", "right", "justify" };
  1036. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  1037. } else if (!strcmp(name, "float")) {
  1038. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  1039. st.float_left == 2 ? "right" : "none");
  1040. } else if (!strcmp(name, "clear")) {
  1041. static const char *cl[] = { "none", "left", "right", "both" };
  1042. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  1043. } else if (!strcmp(name, "opacity")) {
  1044. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  1045. } else if (!strcmp(name, "visibility")) {
  1046. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  1047. } else if (!strcmp(name, "overflow")) {
  1048. snprintf(buf, cap, "%s",
  1049. st.overflow_hidden ? "hidden" : "visible");
  1050. } else if (!strcmp(name, "white-space")) {
  1051. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  1052. } else if (!strcmp(name, "text-transform")) {
  1053. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  1054. } else if (!strcmp(name, "box-sizing")) {
  1055. snprintf(buf, cap, "%s",
  1056. st.box_sizing ? "border-box" : "content-box");
  1057. } else if (!strcmp(name, "line-height")) {
  1058. if (st.line_h_px)
  1059. snprintf(buf, cap, "%dpx", st.line_h_px);
  1060. else if (st.line_h_pct)
  1061. snprintf(buf, cap, "%d%%", st.line_h_pct);
  1062. else
  1063. snprintf(buf, cap, "normal");
  1064. } else if (!strcmp(name, "z-index")) {
  1065. if (st.z_set)
  1066. snprintf(buf, cap, "%d", st.z_index);
  1067. else
  1068. snprintf(buf, cap, "auto");
  1069. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  1070. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  1071. int set = name[0] == 't' ? st.top_set :
  1072. name[0] == 'l' ? st.left_set :
  1073. name[0] == 'r' ? st.right_set : st.bottom_set;
  1074. int v = name[0] == 't' ? st.top :
  1075. name[0] == 'l' ? st.left :
  1076. name[0] == 'r' ? st.right : st.bottom;
  1077. if (set)
  1078. snprintf(buf, cap, "%dpx", v);
  1079. else
  1080. snprintf(buf, cap, "auto");
  1081. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  1082. !strcmp(name, "margin-bottom") ||
  1083. !strcmp(name, "margin-left") ||
  1084. !strcmp(name, "padding-top") ||
  1085. !strcmp(name, "padding-right") ||
  1086. !strcmp(name, "padding-bottom") ||
  1087. !strcmp(name, "padding-left")) {
  1088. int is_pad = name[0] == 'p';
  1089. int side = name[strlen(name) - 1] == 'p' ? 0 :
  1090. name[strlen(name) - 1] == 't' ? 1 :
  1091. name[strlen(name) - 1] == 'm' ? 2 : 3;
  1092. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  1093. if (!strcmp(name, "margin-right") ||
  1094. !strcmp(name, "padding-right"))
  1095. side = 1;
  1096. else if (!strcmp(name, "margin-bottom") ||
  1097. !strcmp(name, "padding-bottom"))
  1098. side = 2;
  1099. else if (!strcmp(name, "margin-left") ||
  1100. !strcmp(name, "padding-left"))
  1101. side = 3;
  1102. else
  1103. side = 0;
  1104. side += is_pad ? 4 : 0;
  1105. css_mp_value(buf, cap,
  1106. side == 0 ? st.mt : side == 1 ? st.mr :
  1107. side == 2 ? st.mb : side == 3 ? st.ml :
  1108. side == 4 ? st.pt : side == 5 ? st.pr :
  1109. side == 6 ? st.pb : st.pl,
  1110. st.mp_unit[side], st.mp_calc_px[side],
  1111. st.font_px);
  1112. } else if (!strcmp(name, "border-top-width") ||
  1113. !strcmp(name, "border-right-width") ||
  1114. !strcmp(name, "border-bottom-width") ||
  1115. !strcmp(name, "border-left-width")) {
  1116. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1117. name[7] == 'b' ? 2 : 3;
  1118. snprintf(buf, cap, "%dpx", st.border_w[side]);
  1119. } else if (!strcmp(name, "border-top-color") ||
  1120. !strcmp(name, "border-right-color") ||
  1121. !strcmp(name, "border-bottom-color") ||
  1122. !strcmp(name, "border-left-color")) {
  1123. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1124. name[7] == 'b' ? 2 : 3;
  1125. if (st.border_w[side] && !st.border_t[side])
  1126. css_rgb(st.border_c[side], buf, cap);
  1127. else
  1128. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1129. } else if (!strcmp(name, "background-image")) {
  1130. if (st.bg_image)
  1131. snprintf(buf, cap, "url(\"%s\")",
  1132. br_bg_image_url(st.bg_image - 1));
  1133. else
  1134. snprintf(buf, cap, "none");
  1135. } else if (!strcmp(name, "background-repeat")) {
  1136. static const char *rp[] = {
  1137. "repeat", "no-repeat", "repeat-x", "repeat-y"
  1138. };
  1139. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  1140. st.bg_repeat : 0]);
  1141. } else if (!strcmp(name, "background-position")) {
  1142. if (st.bg_pos_x_kind == 1)
  1143. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  1144. st.bg_pos_y);
  1145. else
  1146. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1147. st.bg_pos_y);
  1148. } else if (!strcmp(name, "background-size")) {
  1149. if (st.bg_size_kind == 3)
  1150. snprintf(buf, cap, "cover");
  1151. else if (st.bg_size_kind == 4)
  1152. snprintf(buf, cap, "contain");
  1153. else if (st.bg_size_kind == 1)
  1154. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1155. st.bg_size_h);
  1156. else if (st.bg_size_kind == 2)
  1157. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1158. st.bg_size_h);
  1159. else
  1160. snprintf(buf, cap, "auto");
  1161. } else if (!strcmp(name, "transform")) {
  1162. char tmp[128];
  1163. unsigned int n = 0;
  1164. if (!st.transform_set) {
  1165. snprintf(buf, cap, "none");
  1166. } else {
  1167. tmp[0] = '\0';
  1168. if (st.tx || st.ty) {
  1169. snprintf(tmp + n, sizeof(tmp) - n,
  1170. "translate(%dpx, %dpx)", st.tx, st.ty);
  1171. n = (unsigned int)strlen(tmp);
  1172. }
  1173. if (st.transform_scale) {
  1174. snprintf(tmp + n, sizeof(tmp) - n,
  1175. "%sscale(%d.%02d, %d.%02d)",
  1176. n ? " " : "", st.scale_x / 100,
  1177. st.scale_x % 100, st.scale_y / 100,
  1178. st.scale_y % 100);
  1179. n = (unsigned int)strlen(tmp);
  1180. if (st.rotate_x100) {
  1181. snprintf(tmp + n, sizeof(tmp) - n,
  1182. " rotate(%d.%02ddeg)",
  1183. st.rotate_x100 / 100,
  1184. st.rotate_x100 % 100);
  1185. }
  1186. } else if (st.rotate_x100) {
  1187. snprintf(tmp + n, sizeof(tmp) - n,
  1188. "%srotate(%d.%02ddeg)",
  1189. n ? " " : "", st.rotate_x100 / 100,
  1190. st.rotate_x100 % 100);
  1191. }
  1192. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1193. }
  1194. } else {
  1195. return 0;
  1196. }
  1197. return buf[0] != '\0';
  1198. }
  1199. static int js_host_click(unsigned int node)
  1200. {
  1201. char url[BR_URL_MAX];
  1202. const char *href;
  1203. if (node >= doc.nnode)
  1204. return 0;
  1205. if (form_is_control(node)) {
  1206. form_click(node); /* dispatches its own click event */
  1207. return 1;
  1208. }
  1209. /* element.click() fires a bubbling, cancelable click before the
  1210. * default action, like a real click (delegated list handlers). */
  1211. if (!js_browser_event(node, "click", 1, 1))
  1212. return 1;
  1213. if (link_fragment_nav(node))
  1214. return 1;
  1215. href = br_href(&doc, node);
  1216. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1217. return 0;
  1218. s_copy(pending_url, url, sizeof(pending_url));
  1219. pending_action |= ACT_NAV;
  1220. cancel_fetch = 1;
  1221. ngui_invalidate(&ui);
  1222. return 1;
  1223. }
  1224. static int fetch_script_text(const char *url, unsigned char **out,
  1225. unsigned int *outlen, char *err,
  1226. unsigned int errcap);
  1227. struct fetch_worker;
  1228. static struct fetch_worker *fetch_worker_alloc(void);
  1229. static void fetch_worker_release(struct fetch_worker *w);
  1230. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1231. unsigned int cap, const char *post,
  1232. unsigned int post_len, unsigned int node,
  1233. int bg, char *err, unsigned int errcap);
  1234. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1235. unsigned int errcap);
  1236. static int fetch_worker_read_body(struct fetch_worker *w,
  1237. unsigned char *plain,
  1238. unsigned int plaincap,
  1239. unsigned char *comp,
  1240. unsigned int compcap,
  1241. int *truncated, char *err,
  1242. unsigned int errcap);
  1243. static void fetch_workers_stop_all(void);
  1244. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1245. unsigned int cap, const char *method,
  1246. const char *ctype, const char *post,
  1247. unsigned int post_len, unsigned int node,
  1248. int bg, unsigned int dec_w,
  1249. unsigned int dec_h, char *err,
  1250. unsigned int errcap);
  1251. static int script_cache_has(const char *url);
  1252. static void script_cache_put(const char *url, const unsigned char *data,
  1253. unsigned int len);
  1254. static unsigned int script_cache_hash(const char *s);
  1255. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1256. unsigned int errcap);
  1257. static void fetch_workers_cancel_busy(void);
  1258. static void worker_wait_ui(void);
  1259. static int fetch_worker_status(const struct fetch_worker *w);
  1260. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1261. * module load: the wait must not pump input, or a click would dispatch DOM
  1262. * events into the middle of the running script. */
  1263. static int fetch_wait_passive;
  1264. static void script_error(const char *what, const char *url, const char *why)
  1265. {
  1266. char msg[192];
  1267. unsigned int n = 0;
  1268. s_append(msg, &n, what, sizeof(msg));
  1269. if (url && url[0]) {
  1270. s_append(msg, &n, " ", sizeof(msg));
  1271. s_append(msg, &n, url, sizeof(msg));
  1272. }
  1273. if (why && why[0]) {
  1274. s_append(msg, &n, ": ", sizeof(msg));
  1275. s_append(msg, &n, why, sizeof(msg));
  1276. }
  1277. js_host_report(msg);
  1278. }
  1279. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1280. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1281. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1282. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1283. #define JS_HTTP_POST_MAX (16u * 1024u)
  1284. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1285. static int js_worker_http(const char *method, const char *url,
  1286. const char *ctype, const char *body,
  1287. unsigned int body_len, struct js_http_resp *r,
  1288. char *err, int errcap);
  1289. static int js_host_http(const char *method, const char *url,
  1290. const char *ctype, const char *body,
  1291. unsigned int body_len, struct js_http_resp *r,
  1292. char *err, int errcap)
  1293. {
  1294. if (pending_action) {
  1295. s_copy(err, "page is navigating", (unsigned int)errcap);
  1296. return -1;
  1297. }
  1298. if (url[0] == '/') {
  1299. /* Local file: GET only. */
  1300. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1301. int rv;
  1302. if (!buf) {
  1303. s_copy(err, "out of memory", (unsigned int)errcap);
  1304. return -1;
  1305. }
  1306. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1307. (int)JS_HTTP_MAX);
  1308. r->status = rv < 0 ? 404 : 200;
  1309. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1310. buf[r->len] = '\0';
  1311. r->body = (char *)buf;
  1312. s_copy(r->url, url, sizeof(r->url));
  1313. if (contains_ci(url, ".json"))
  1314. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1315. return 0;
  1316. }
  1317. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1318. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1319. return -1;
  1320. }
  1321. if (body_len > JS_HTTP_POST_MAX) {
  1322. s_copy(err, "request body too large", (unsigned int)errcap);
  1323. return -1;
  1324. }
  1325. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1326. errcap);
  1327. }
  1328. /* Module source for the engine's loader: the boot script cache first, then
  1329. * one blocking fetch with input pumping disabled (the loader runs inside
  1330. * JavaScript). */
  1331. static char *js_host_load_script(const char *url, unsigned int *len)
  1332. {
  1333. unsigned char *data = 0;
  1334. char err[64];
  1335. int rv;
  1336. fetch_wait_passive++;
  1337. set_status("Loading module...", 0, 0);
  1338. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1339. fetch_wait_passive--;
  1340. if (rv != 0) {
  1341. script_error("Cannot load module", url,
  1342. rv == FETCH_ABORT ? "navigation" : err);
  1343. return 0;
  1344. }
  1345. return (char *)data;
  1346. }
  1347. /* Web Storage lives in /share, outside the page heap that every navigation
  1348. * resets: localStorage per origin for the boot, sessionStorage per origin
  1349. * and browser window. */
  1350. #define JS_ORIGIN_MAX 160
  1351. /* scheme://host[:port] of the page (a local page's whole path). */
  1352. static void js_page_origin(char *origin, unsigned int cap)
  1353. {
  1354. unsigned int i = 0, slashes = 0;
  1355. while (page_url[i] && i + 1 < cap) {
  1356. if (page_url[i] == '/' && ++slashes == 3)
  1357. break;
  1358. origin[i] = page_url[i];
  1359. i++;
  1360. }
  1361. origin[i] = '\0';
  1362. }
  1363. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1364. {
  1365. unsigned int n = 0;
  1366. s_append(out, &n, "/share/bls", cap);
  1367. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1368. }
  1369. static void js_storage_path(int kind, char *out, unsigned int cap)
  1370. {
  1371. char origin[JS_ORIGIN_MAX];
  1372. unsigned int n = 0;
  1373. js_page_origin(origin, sizeof(origin));
  1374. if (!kind) {
  1375. js_origin_path(origin, out, cap);
  1376. return;
  1377. }
  1378. s_append(out, &n, "/share/bss", cap);
  1379. if (kind) {
  1380. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1381. s_append(out, &n, "-", cap);
  1382. }
  1383. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1384. }
  1385. static void persist_mark_origin(const char *origin);
  1386. static int persist_store_lookup(const char *origin, char *out, int cap);
  1387. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1388. {
  1389. char path[48], origin[JS_ORIGIN_MAX];
  1390. int rv;
  1391. js_storage_path(kind, path, sizeof(path));
  1392. if (set) {
  1393. if (kind) {
  1394. if (!set[0] || !strcmp(set, "{}")) {
  1395. u_syscall1(SYS_UNLINK, (int)path);
  1396. return 0;
  1397. }
  1398. } else {
  1399. /* localStorage keeps an explicit "{}" rather than no
  1400. * file: a missing /share file means "not loaded from
  1401. * /data yet", and a cleared store must not come back
  1402. * from the disk copy before it is flushed. */
  1403. if (!set[0])
  1404. set = "{}";
  1405. js_page_origin(origin, sizeof(origin));
  1406. persist_mark_origin(origin);
  1407. }
  1408. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1409. (int)strlen(set)) < 0 ? -1 : 0;
  1410. }
  1411. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1412. if (rv < 0 && !kind) {
  1413. /* First use this boot: the persistent copy on /data. */
  1414. js_page_origin(origin, sizeof(origin));
  1415. rv = persist_store_lookup(origin, out, cap);
  1416. if (rv >= 0)
  1417. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1418. }
  1419. if (rv < 0)
  1420. return -1;
  1421. out[rv] = '\0';
  1422. return rv;
  1423. }
  1424. /* ---- persistence on /data ----
  1425. *
  1426. * /share is the working copy (RAM, shared by every helper and window); the
  1427. * installed disk's /data volume keeps the cookie jar and localStorage
  1428. * across reboots when it is mounted. The browser owns the disk copies: at
  1429. * start it restores the jar into /share, and its main loop writes back
  1430. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1431. * setItem updates costs one FAT write. The helpers only touch /share (they
  1432. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1433. * /data mount every disk access simply fails. Both files are plaintext
  1434. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1435. #define PERSIST_MS 3000u
  1436. #define SHARE_COOKIES "/share/bcookies"
  1437. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1438. #define DATA_STORE "/data/BSTORE.DAT"
  1439. #define DATA_STORE_MAGIC "NBLS1\n"
  1440. #define DATA_STORE_MAX (192u * 1024u)
  1441. #define PERSIST_DIRTY_MAX 8
  1442. static unsigned int persist_due;
  1443. static unsigned int cookie_sum_saved;
  1444. static int cookie_sum_valid;
  1445. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1446. static int persist_ndirty;
  1447. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1448. {
  1449. unsigned int h = 2166136261u, i;
  1450. for (i = 0; i < n; i++)
  1451. h = (h ^ p[i]) * 16777619u;
  1452. return h;
  1453. }
  1454. /* Called once at startup, before any helper runs. */
  1455. static void persist_restore(void)
  1456. {
  1457. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1458. int n;
  1459. if (!jar)
  1460. return;
  1461. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1462. (int)sizeof(struct uhttp_jar));
  1463. if (n != (int)sizeof(struct uhttp_jar)) {
  1464. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1465. (int)sizeof(struct uhttp_jar));
  1466. if (n == (int)sizeof(struct uhttp_jar)) {
  1467. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1468. (int)jar, n);
  1469. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1470. cookie_sum_valid = 1;
  1471. }
  1472. }
  1473. free(jar);
  1474. persist_due = u_ticks_ms() + PERSIST_MS;
  1475. }
  1476. static void persist_mark_origin(const char *origin)
  1477. {
  1478. int i;
  1479. for (i = 0; i < persist_ndirty; i++)
  1480. if (s_eq(persist_dirty[i], origin))
  1481. return;
  1482. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1483. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1484. }
  1485. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1486. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1487. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1488. unsigned int *o_off, unsigned int *o_len,
  1489. unsigned int *d_off, unsigned int *d_len,
  1490. unsigned int *rec_end)
  1491. {
  1492. unsigned int p = *pos, v = 0;
  1493. if (p >= len)
  1494. return 0;
  1495. *o_off = p;
  1496. while (p < len && buf[p] != '\n')
  1497. p++;
  1498. if (p >= len)
  1499. return 0;
  1500. *o_len = p - *o_off;
  1501. p++;
  1502. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1503. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1504. if (p >= len || buf[p] != '\n')
  1505. return 0;
  1506. p++;
  1507. if (v > len - p)
  1508. return 0;
  1509. *d_off = p;
  1510. *d_len = v;
  1511. p += v;
  1512. if (p < len && buf[p] == '\n')
  1513. p++;
  1514. *rec_end = p;
  1515. *pos = p;
  1516. return 1;
  1517. }
  1518. static int store_load(char **out)
  1519. {
  1520. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1521. int n;
  1522. *out = buf;
  1523. if (!buf)
  1524. return -1;
  1525. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1526. (int)DATA_STORE_MAX);
  1527. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1528. !starts_with(buf, DATA_STORE_MAGIC))
  1529. return 0;
  1530. return n;
  1531. }
  1532. static int persist_store_lookup(const char *origin, char *out, int cap)
  1533. {
  1534. char *buf;
  1535. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1536. unsigned int olen = s_len(origin);
  1537. int n = store_load(&buf), rv = -1;
  1538. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1539. &dl, &e)) {
  1540. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1541. if ((int)dl < cap) {
  1542. memcpy(out, buf + d, dl);
  1543. out[dl] = '\0';
  1544. rv = (int)dl;
  1545. }
  1546. break;
  1547. }
  1548. }
  1549. free(buf);
  1550. return rv;
  1551. }
  1552. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1553. static void persist_store_flush(void)
  1554. {
  1555. char *old, *nb, path[48];
  1556. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1557. int n = store_load(&old), i, w;
  1558. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1559. if (n < 0 || !nb) {
  1560. free(old);
  1561. free(nb);
  1562. return;
  1563. }
  1564. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1565. /* Untouched origins first, in their old order. */
  1566. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1567. &dl, &e)) {
  1568. int dirty = 0;
  1569. for (i = 0; i < persist_ndirty; i++)
  1570. if (s_len(persist_dirty[i]) == ol &&
  1571. !memcmp(persist_dirty[i], old + oo, ol))
  1572. dirty = 1;
  1573. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1574. continue;
  1575. memcpy(nb + nn, old + oo, e - oo);
  1576. nn += e - oo;
  1577. }
  1578. /* Then the changed ones (an emptied store is dropped). */
  1579. for (i = 0; i < persist_ndirty; i++) {
  1580. char num[12];
  1581. unsigned int k = 0;
  1582. js_origin_path(persist_dirty[i], path, sizeof(path));
  1583. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1584. (int)DATA_STORE_MAX);
  1585. if (w <= 2) /* missing or "{}" */
  1586. continue;
  1587. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1588. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1589. DATA_STORE_MAX) {
  1590. set_status("Saved site data is full; a site's "
  1591. "localStorage was not saved", 1, 6000);
  1592. continue;
  1593. }
  1594. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1595. nb[nn++] = '\n';
  1596. s_append(nb, &nn, num, DATA_STORE_MAX);
  1597. nb[nn++] = '\n';
  1598. memcpy(nb + nn, old, (unsigned int)w);
  1599. nn += (unsigned int)w;
  1600. nb[nn++] = '\n';
  1601. }
  1602. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1603. persist_ndirty = 0;
  1604. free(old);
  1605. free(nb);
  1606. }
  1607. static void persist_cookies_flush(void)
  1608. {
  1609. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1610. unsigned int sum;
  1611. int n;
  1612. if (!jar)
  1613. return;
  1614. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1615. (int)sizeof(struct uhttp_jar));
  1616. if (n == (int)sizeof(struct uhttp_jar)) {
  1617. sum = persist_sum(jar, (unsigned int)n);
  1618. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1619. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1620. (int)jar, n) >= 0) {
  1621. cookie_sum_saved = sum;
  1622. cookie_sum_valid = 1;
  1623. }
  1624. }
  1625. }
  1626. free(jar);
  1627. }
  1628. /* ---- visit history (URL-bar autocomplete) ----
  1629. *
  1630. * Every page that finishes loading is recorded with its title, a visit
  1631. * count and a stamp: a counter that only grows and travels with the file,
  1632. * so it orders visits across windows and boots without a wall clock. The
  1633. * table lives in BSS, because the page heap is reset on every navigation.
  1634. * The boot's browser windows share it through /share/bhist (rewritten on
  1635. * every visit) and it is persisted to /data/BHIST.DAT from persist_tick()
  1636. * at most every PERSIST_MS, like the cookie jar. A save re-reads
  1637. * /share/bhist and merges it first, so two windows add to one history
  1638. * instead of overwriting each other. File format: "NBHIST1\n", then
  1639. * "<visits> <stamp> <url>\t<title>\n" per entry. Plaintext, like the
  1640. * other browser state on /data. */
  1641. #define HIST_MAX 128
  1642. #define HIST_URL_MAX 512
  1643. #define HIST_FILE_MAX (HIST_MAX * (HIST_URL_MAX + BR_TITLE_MAX + 24) + 16)
  1644. #define HIST_MAGIC "NBHIST1\n"
  1645. #define SHARE_HIST "/share/bhist"
  1646. #define DATA_HIST "/data/BHIST.DAT"
  1647. #define HIST_FORGET_MAX 16
  1648. struct hist_ent {
  1649. unsigned int visits;
  1650. unsigned int stamp;
  1651. char url[HIST_URL_MAX];
  1652. char title[BR_TITLE_MAX];
  1653. };
  1654. static struct hist_ent hist_tab[HIST_MAX];
  1655. static int hist_n;
  1656. static int hist_share_dirty, hist_data_dirty;
  1657. /* URLs removed in this process: a merge must not bring them back. */
  1658. static unsigned int hist_forgot[HIST_FORGET_MAX];
  1659. static int hist_nforgot;
  1660. static unsigned int hist_hash(const char *s)
  1661. {
  1662. return persist_sum((const unsigned char *)s, s_len(s));
  1663. }
  1664. static int hist_is_forgotten(const char *url)
  1665. {
  1666. unsigned int h = hist_hash(url);
  1667. int i;
  1668. for (i = 0; i < hist_nforgot; i++)
  1669. if (hist_forgot[i] == h)
  1670. return 1;
  1671. return 0;
  1672. }
  1673. static int hist_find(const char *url)
  1674. {
  1675. int i;
  1676. for (i = 0; i < hist_n; i++)
  1677. if (s_eq(hist_tab[i].url, url))
  1678. return i;
  1679. return -1;
  1680. }
  1681. static unsigned int hist_next_stamp(void)
  1682. {
  1683. unsigned int m = 0;
  1684. int i;
  1685. for (i = 0; i < hist_n; i++)
  1686. if (hist_tab[i].stamp > m)
  1687. m = hist_tab[i].stamp;
  1688. return m + 1;
  1689. }
  1690. /* Copy a title, turning tabs/newlines (the file separators) into spaces. */
  1691. static void hist_copy_title(char *d, const char *s, unsigned int n)
  1692. {
  1693. unsigned int i;
  1694. for (i = 0; i + 1 < BR_TITLE_MAX && i < n && s[i]; i++)
  1695. d[i] = (unsigned char)s[i] < 0x20 ? ' ' : s[i];
  1696. d[i] = '\0';
  1697. }
  1698. /* Insert or update an entry; the newer stamp wins the title, the larger
  1699. * visit count is kept. A full table evicts the least recent entry, unless
  1700. * the new one is older still. Returns NULL when nothing was stored. */
  1701. static struct hist_ent *hist_put(const char *url, const char *title,
  1702. unsigned int visits, unsigned int stamp)
  1703. {
  1704. struct hist_ent *e;
  1705. int i = hist_find(url);
  1706. if (i < 0) {
  1707. if (hist_n < HIST_MAX) {
  1708. i = hist_n++;
  1709. } else {
  1710. int j;
  1711. i = 0;
  1712. for (j = 1; j < hist_n; j++)
  1713. if (hist_tab[j].stamp < hist_tab[i].stamp)
  1714. i = j;
  1715. if (hist_tab[i].stamp >= stamp)
  1716. return 0;
  1717. }
  1718. e = &hist_tab[i];
  1719. e->visits = 0;
  1720. e->stamp = 0;
  1721. e->title[0] = '\0';
  1722. s_copy(e->url, url, sizeof(e->url));
  1723. }
  1724. e = &hist_tab[i];
  1725. if (visits > e->visits)
  1726. e->visits = visits;
  1727. if (stamp >= e->stamp) {
  1728. e->stamp = stamp;
  1729. if (title && title[0])
  1730. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1731. } else if (!e->title[0] && title) {
  1732. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1733. }
  1734. return e;
  1735. }
  1736. static unsigned int hist_parse_dec(const char *b, int n, int *pos)
  1737. {
  1738. unsigned int v = 0;
  1739. while (*pos < n && b[*pos] >= '0' && b[*pos] <= '9')
  1740. v = v * 10 + (unsigned int)(b[(*pos)++] - '0');
  1741. return v;
  1742. }
  1743. static void hist_merge_buf(const char *b, int n)
  1744. {
  1745. int pos = (int)s_len(HIST_MAGIC);
  1746. char url[HIST_URL_MAX], title[BR_TITLE_MAX];
  1747. if (n < pos || memcmp(b, HIST_MAGIC, (unsigned int)pos))
  1748. return;
  1749. while (pos < n) {
  1750. unsigned int visits, stamp, ul = 0;
  1751. int t0, t1;
  1752. visits = hist_parse_dec(b, n, &pos);
  1753. if (pos < n && b[pos] == ' ')
  1754. pos++;
  1755. stamp = hist_parse_dec(b, n, &pos);
  1756. if (pos < n && b[pos] == ' ')
  1757. pos++;
  1758. while (pos < n && b[pos] != '\t' && b[pos] != '\n') {
  1759. if (ul + 1 < sizeof(url))
  1760. url[ul++] = b[pos];
  1761. pos++;
  1762. }
  1763. url[ul] = '\0';
  1764. t0 = t1 = pos < n && b[pos] == '\t' ? pos + 1 : pos;
  1765. while (t1 < n && b[t1] != '\n')
  1766. t1++;
  1767. pos = t1 + 1;
  1768. hist_copy_title(title, b + t0, (unsigned int)(t1 - t0));
  1769. if (ul && ul + 1 < sizeof(url) && !hist_is_forgotten(url))
  1770. hist_put(url, title, visits, stamp);
  1771. }
  1772. }
  1773. static int hist_serialize(char *b, unsigned int cap)
  1774. {
  1775. unsigned int n = 0;
  1776. int i;
  1777. s_append(b, &n, HIST_MAGIC, cap);
  1778. for (i = 0; i < hist_n; i++) {
  1779. struct hist_ent *e = &hist_tab[i];
  1780. if (n + s_len(e->url) + s_len(e->title) + 26 >= cap)
  1781. break;
  1782. s_append_dec(b, &n, e->visits, cap);
  1783. b[n++] = ' ';
  1784. s_append_dec(b, &n, e->stamp, cap);
  1785. b[n++] = ' ';
  1786. s_append(b, &n, e->url, cap);
  1787. b[n++] = '\t';
  1788. s_append(b, &n, e->title, cap);
  1789. b[n++] = '\n';
  1790. }
  1791. return (int)n;
  1792. }
  1793. /* Merge /share/bhist, then write it back (and /data when asked). */
  1794. static void hist_sync(int to_data)
  1795. {
  1796. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1797. int n;
  1798. if (!b)
  1799. return;
  1800. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1801. (int)HIST_FILE_MAX);
  1802. if (n > 0)
  1803. hist_merge_buf(b, n);
  1804. n = hist_serialize(b, HIST_FILE_MAX);
  1805. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1806. hist_share_dirty = 0;
  1807. if (to_data) {
  1808. /* No /data mount: the write fails, and there is nothing to
  1809. * retry until the next visit. */
  1810. u_syscall3(SYS_WRITE_FILE, (int)DATA_HIST, (int)b, n);
  1811. hist_data_dirty = 0;
  1812. }
  1813. free(b);
  1814. }
  1815. /* Startup: the boot's shared copy, else the saved one from /data. */
  1816. static void hist_load(void)
  1817. {
  1818. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1819. int n;
  1820. if (!b)
  1821. return;
  1822. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1823. (int)HIST_FILE_MAX);
  1824. if (n <= 0) {
  1825. n = u_syscall3(SYS_READ_FILE, (int)DATA_HIST, (int)b,
  1826. (int)HIST_FILE_MAX);
  1827. if (n > 0)
  1828. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1829. }
  1830. if (n > 0)
  1831. hist_merge_buf(b, n);
  1832. free(b);
  1833. }
  1834. static void hist_visit(const char *url, const char *title)
  1835. {
  1836. struct hist_ent *e;
  1837. unsigned int i;
  1838. if (!url[0] || starts_with(url, "about:") ||
  1839. s_len(url) >= HIST_URL_MAX)
  1840. return;
  1841. for (i = 0; url[i]; i++)
  1842. if ((unsigned char)url[i] < 0x20)
  1843. return;
  1844. e = hist_put(url, title, 0, hist_next_stamp());
  1845. if (!e)
  1846. return;
  1847. e->visits++;
  1848. hist_data_dirty = 1;
  1849. hist_sync(0);
  1850. }
  1851. static void hist_forget(int i)
  1852. {
  1853. if (i < 0 || i >= hist_n)
  1854. return;
  1855. if (hist_nforgot < HIST_FORGET_MAX)
  1856. hist_forgot[hist_nforgot++] = hist_hash(hist_tab[i].url);
  1857. hist_n--;
  1858. for (; i < hist_n; i++)
  1859. hist_tab[i] = hist_tab[i + 1];
  1860. hist_data_dirty = 1;
  1861. hist_sync(0);
  1862. }
  1863. static void hist_tick(void)
  1864. {
  1865. if (hist_share_dirty || hist_data_dirty)
  1866. hist_sync(hist_data_dirty);
  1867. }
  1868. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1869. static void persist_tick(void)
  1870. {
  1871. unsigned int now = u_ticks_ms();
  1872. if ((int)(now - persist_due) < 0)
  1873. return;
  1874. persist_due = now + PERSIST_MS;
  1875. persist_cookies_flush();
  1876. if (persist_ndirty)
  1877. persist_store_flush();
  1878. hist_tick();
  1879. }
  1880. /* <link rel="modulepreload">: download the page's module graph on all
  1881. * helpers at once into the boot script cache, before any script runs. The
  1882. * engine's module loader is sequential (one blocking fetch per import), so
  1883. * without this a Vite app with a dozen chunks pays every round trip in a
  1884. * row. Failures are ignored; the loader fetches what is missing. */
  1885. #define MODULE_PRELOAD_MAX 24
  1886. static void prefetch_module_preloads(void)
  1887. {
  1888. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1889. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1890. unsigned int count = 0, next = 0, done = 0, i;
  1891. char err[64];
  1892. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1893. struct br_node *nd = &doc.nodes[i];
  1894. const char *rel, *href;
  1895. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1896. continue;
  1897. rel = br_rel(&doc, i);
  1898. href = br_href(&doc, i);
  1899. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1900. continue;
  1901. if (resolve_link(page_url, href, urls[count],
  1902. sizeof(urls[count])) != 0 ||
  1903. urls[count][0] == '/' || script_cache_has(urls[count]))
  1904. continue;
  1905. slot[count++] = 0;
  1906. }
  1907. if (!count)
  1908. return;
  1909. set_status("Loading modules...", 0, 0);
  1910. while (done < count) {
  1911. struct fetch_worker *w;
  1912. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1913. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1914. 0, 0, 0, err,
  1915. sizeof(err)) != 0) {
  1916. fetch_worker_release(w);
  1917. done++;
  1918. } else {
  1919. slot[next] = w;
  1920. }
  1921. next++;
  1922. }
  1923. worker_wait_ui();
  1924. if (cancel_fetch || pending_action) {
  1925. fetch_workers_cancel_busy();
  1926. return;
  1927. }
  1928. for (i = 0; i < next; i++) {
  1929. unsigned char *body;
  1930. int rv, tr = 0;
  1931. if (!slot[i])
  1932. continue;
  1933. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1934. if (rv == 0)
  1935. continue;
  1936. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1937. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1938. if (body) {
  1939. rv = fetch_worker_read_body(slot[i], body,
  1940. BR_SCRIPT_MAX, image_io_buf,
  1941. BR_PAGE_COMP_MAX, &tr, err,
  1942. sizeof(err));
  1943. if (rv > 0 && !tr)
  1944. script_cache_put(urls[i], body,
  1945. (unsigned int)rv);
  1946. free(body);
  1947. }
  1948. fetch_worker_release(slot[i]);
  1949. slot[i] = 0;
  1950. done++;
  1951. }
  1952. u_sleep_ms(10);
  1953. }
  1954. }
  1955. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1956. * submitted to helper workers ahead of time, but scripts still execute in
  1957. * document order. */
  1958. #define SCRIPT_INLINE 0
  1959. #define SCRIPT_LOCAL 1
  1960. #define SCRIPT_REMOTE 2
  1961. #define SCRIPT_ERROR 3
  1962. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1963. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1964. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1965. static void script_submit_window(unsigned int *next, char *err,
  1966. unsigned int errcap)
  1967. {
  1968. while (*next < doc.nscripts) {
  1969. struct fetch_worker *w;
  1970. if (script_kind[*next] != SCRIPT_REMOTE) {
  1971. (*next)++;
  1972. continue;
  1973. }
  1974. w = fetch_worker_alloc();
  1975. if (!w)
  1976. return;
  1977. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1978. 0, 0, 0, 0, err, errcap) != 0) {
  1979. fetch_worker_release(w);
  1980. script_kind[*next] = SCRIPT_ERROR;
  1981. (*next)++;
  1982. continue;
  1983. }
  1984. script_slot[*next] = w;
  1985. (*next)++;
  1986. }
  1987. }
  1988. /* Run the page's scripts in document order. External bodies are prefetched
  1989. * in parallel so downloading script N+1 overlaps executing script N; inline
  1990. * bodies are copied because the engine needs NUL-terminated text. */
  1991. static void run_page_scripts(void)
  1992. {
  1993. struct js_browser_host host;
  1994. unsigned int i, next = 0;
  1995. char err[64], ferr[64];
  1996. if (!doc.nscripts)
  1997. return;
  1998. host.status = js_host_status;
  1999. host.report = js_host_report;
  2000. host.navigate = js_host_navigate;
  2001. host.changed = js_host_changed;
  2002. host.rect = js_host_rect;
  2003. host.form_value = js_host_form_value;
  2004. host.form_checked = js_host_form_checked;
  2005. host.form_selected = js_host_form_selected;
  2006. host.form_set_value = js_host_form_set_value;
  2007. host.form_set_checked = js_host_form_set_checked;
  2008. host.form_set_selected = js_host_form_set_selected;
  2009. host.form_elements = js_host_form_elements;
  2010. host.form_submit = js_host_form_submit;
  2011. host.form_reset = js_host_form_reset;
  2012. host.click = js_host_click;
  2013. host.computed = js_host_computed;
  2014. host.http = js_host_http;
  2015. host.load_script = js_host_load_script;
  2016. host.storage = js_host_storage;
  2017. host.set_hash = js_host_set_hash;
  2018. host.page_url = page_url;
  2019. host.width = ui.w;
  2020. host.height = ui.h;
  2021. if (js_browser_start(&doc, &host) != 0) {
  2022. js_host_status("JavaScript: out of memory", 1);
  2023. return;
  2024. }
  2025. resize_sent_w = -1;
  2026. resize_pending = 0;
  2027. prefetch_module_preloads();
  2028. for (i = 0; i < doc.nscripts; i++) {
  2029. struct br_script *script = &doc.scripts[i];
  2030. const char *src_attr = script->src_off ?
  2031. doc.attrs + script->src_off : "";
  2032. script_slot[i] = 0;
  2033. if (!script->src_off) {
  2034. script_kind[i] = SCRIPT_INLINE;
  2035. continue;
  2036. }
  2037. if (!src_attr[0] ||
  2038. resolve_link(page_url, src_attr, script_urls[i],
  2039. sizeof(script_urls[i])) != 0) {
  2040. script_urls[i][0] = '\0';
  2041. script_kind[i] = SCRIPT_ERROR;
  2042. continue;
  2043. }
  2044. if (script_urls[i][0] == '/' ||
  2045. script_cache_has(script_urls[i]))
  2046. script_kind[i] = SCRIPT_LOCAL;
  2047. else
  2048. script_kind[i] = SCRIPT_REMOTE;
  2049. }
  2050. script_submit_window(&next, ferr, sizeof(ferr));
  2051. for (i = 0; i < doc.nscripts; i++) {
  2052. struct br_script *script = &doc.scripts[i];
  2053. /* document.currentScript for classic scripts (null for modules) */
  2054. js_browser_set_current_script(script->module ? 0 : script->node);
  2055. if (script_kind[i] == SCRIPT_INLINE) {
  2056. unsigned int off = script->off;
  2057. unsigned int len = script->len;
  2058. unsigned int k;
  2059. char *src = (char *)malloc(len + 1);
  2060. if (!src) {
  2061. js_host_status("JavaScript: out of memory", 1);
  2062. break;
  2063. }
  2064. for (k = 0; k < len; k++)
  2065. src[k] = doc.script_src[off + k];
  2066. src[len] = '\0';
  2067. if (script->module) {
  2068. /* A distinct module name per inline module
  2069. * (QuickJS registers modules by name); the
  2070. * fragment keeps relative imports resolving
  2071. * against the page. */
  2072. char mname[BR_URL_MAX + 16];
  2073. unsigned int mn = 0;
  2074. s_append(mname, &mn, page_url, sizeof(mname));
  2075. s_append(mname, &mn, "#module", sizeof(mname));
  2076. s_append_dec(mname, &mn, i, sizeof(mname));
  2077. js_browser_run_module(src, mname);
  2078. } else {
  2079. js_browser_run(src, page_url);
  2080. }
  2081. free(src);
  2082. } else if (script->src_off) {
  2083. const char *src_attr = doc.attrs + script->src_off;
  2084. if (script_kind[i] == SCRIPT_ERROR) {
  2085. script_error("Cannot load script", src_attr,
  2086. script_urls[i][0] ?
  2087. "network busy" :
  2088. "unsupported URL");
  2089. continue;
  2090. }
  2091. if (script_kind[i] == SCRIPT_LOCAL) {
  2092. unsigned char *data = 0;
  2093. unsigned int len = 0;
  2094. int rv;
  2095. set_status("Loading script...", 0, 0);
  2096. rv = fetch_script_text(script_urls[i], &data,
  2097. &len, err, sizeof(err));
  2098. if (rv == FETCH_ABORT)
  2099. break;
  2100. if (rv != 0) {
  2101. script_error("Cannot load script",
  2102. script_urls[i], err);
  2103. continue;
  2104. }
  2105. if (script->module)
  2106. js_browser_run_module(
  2107. (const char *)data,
  2108. script_urls[i]);
  2109. else
  2110. js_browser_run((const char *)data,
  2111. script_urls[i]);
  2112. free(data);
  2113. } else {
  2114. struct fetch_worker *w = script_slot[i];
  2115. unsigned char *body = 0;
  2116. int tr = 0, rv;
  2117. if (!w) {
  2118. w = fetch_worker_alloc();
  2119. if (!w)
  2120. continue;
  2121. if (fetch_worker_submit(w,
  2122. script_urls[i],
  2123. BR_SCRIPT_MAX,
  2124. 0, 0, 0, 0, err,
  2125. sizeof(err)) != 0) {
  2126. fetch_worker_release(w);
  2127. script_kind[i] = SCRIPT_ERROR;
  2128. if (i == next)
  2129. next++;
  2130. continue;
  2131. }
  2132. script_slot[i] = w;
  2133. if (i == next)
  2134. next++;
  2135. }
  2136. set_status("Loading script...", 0, 0);
  2137. rv = fetch_worker_wait(w, err, sizeof(err));
  2138. if (rv == FETCH_ABORT) {
  2139. fetch_workers_stop_all();
  2140. break;
  2141. }
  2142. /* The body gets its own buffer (scripts are up
  2143. * to 2 MB); image_io_buf takes the gzip
  2144. * stream. */
  2145. body = rv == 0 ? (unsigned char *)malloc(
  2146. BR_SCRIPT_MAX + 1) : 0;
  2147. if (body)
  2148. rv = fetch_worker_read_body(w, body,
  2149. BR_SCRIPT_MAX, image_io_buf,
  2150. BR_PAGE_COMP_MAX, &tr, err,
  2151. sizeof(err));
  2152. else {
  2153. if (rv == 0)
  2154. s_copy(err, "out of memory",
  2155. sizeof(err));
  2156. rv = -1;
  2157. }
  2158. fetch_worker_release(w);
  2159. script_slot[i] = 0;
  2160. script_submit_window(&next, ferr, sizeof(ferr));
  2161. if (rv <= 0)
  2162. script_error("Cannot load script",
  2163. script_urls[i], err);
  2164. else if (tr || (unsigned int)rv >=
  2165. BR_SCRIPT_MAX)
  2166. script_error("Cannot load script",
  2167. script_urls[i],
  2168. "script is too large");
  2169. else {
  2170. body[rv] = '\0';
  2171. script_cache_put(script_urls[i], body,
  2172. (unsigned int)rv);
  2173. if (script->module)
  2174. js_browser_run_module(
  2175. (const char *)body,
  2176. script_urls[i]);
  2177. else
  2178. js_browser_run(
  2179. (const char *)body,
  2180. script_urls[i]);
  2181. }
  2182. free(body);
  2183. }
  2184. }
  2185. if (pending_action)
  2186. break;
  2187. }
  2188. js_browser_set_current_script(0);
  2189. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  2190. * load_home() stop it before the next navigation. */
  2191. if (doc.scripts_truncated && !js_last_error)
  2192. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  2193. 1);
  2194. }
  2195. /* ---- images ---- */
  2196. /* data: images that failed to decode (key = data_img_key()), so a layout
  2197. * pass does not retry them on every frame. */
  2198. #define DATA_IMG_FAIL_MAX 32
  2199. static unsigned int data_img_fail[DATA_IMG_FAIL_MAX];
  2200. static int data_img_nfail;
  2201. static void image_reset(void)
  2202. {
  2203. int i;
  2204. for (i = 0; i < BR_MAX_IMAGES; i++) {
  2205. images[i].state = 0;
  2206. images[i].native_w = images[i].native_h = 0;
  2207. images[i].err[0] = '\0';
  2208. /* heap_clear() ran before us, so these pointers are stale: drop
  2209. * them without calling free(). */
  2210. memset(&images[i].disp, 0, sizeof(images[i].disp));
  2211. images[i].disp_pixels = 0;
  2212. images[i].disp_last = 0;
  2213. }
  2214. image_count = 0;
  2215. data_img_nfail = 0;
  2216. image_pixels = 0;
  2217. image_disp_pixels = 0;
  2218. image_disp_clock = 0;
  2219. memset(img_stat_log, 0, sizeof(img_stat_log));
  2220. img_stat_log_len = 0;
  2221. img_stat_start = 0;
  2222. img_stat_wall = 0;
  2223. img_stat_net = img_stat_open = img_stat_first = 0;
  2224. img_stat_io = img_stat_dec = img_stat_scale = 0;
  2225. img_stat_paint = img_stat_reflow = 0;
  2226. img_stat_bytes = 0;
  2227. img_stat_n = 0;
  2228. img_last_dec_ms = img_last_scale_ms = 0;
  2229. img_repaint_ms = 0;
  2230. img_repaint_pending = 0;
  2231. preload_active = 0;
  2232. preload_pending = 0;
  2233. preload_wait = 0;
  2234. preload_node = 0;
  2235. preload_loaded = 0;
  2236. }
  2237. /* Ask for a repaint, but not more often than BR_IMG_REPAINT_MS while images
  2238. * are arriving. The main loop draws once per dirty frame; without this a
  2239. * page of N images did N full layout+paint passes. */
  2240. static void image_repaint(void)
  2241. {
  2242. unsigned int now = u_ticks_ms();
  2243. if (!img_repaint_ms || (now - img_repaint_ms) >= BR_IMG_REPAINT_MS) {
  2244. img_repaint_ms = now;
  2245. img_repaint_pending = 0;
  2246. ngui_invalidate(&ui);
  2247. } else {
  2248. img_repaint_pending = 1;
  2249. }
  2250. }
  2251. static void image_disp_drop(struct br_image *bi)
  2252. {
  2253. if (bi->disp.px)
  2254. free(bi->disp.px);
  2255. if (bi->disp.alpha)
  2256. free(bi->disp.alpha);
  2257. memset(&bi->disp, 0, sizeof(bi->disp));
  2258. if (bi->disp_pixels) {
  2259. if (image_disp_pixels >= bi->disp_pixels)
  2260. image_disp_pixels -= bi->disp_pixels;
  2261. bi->disp_pixels = 0;
  2262. }
  2263. }
  2264. /* Free the least recently used display caches until need pixels fit. The
  2265. * source bitmap (bi->img) is never evicted; a later draw rescales it again. */
  2266. static int image_disp_room(unsigned int need)
  2267. {
  2268. while (image_disp_pixels + need > BR_IMG_DISP_BUDGET) {
  2269. unsigned int oldest = ~0u;
  2270. int i, victim = -1;
  2271. for (i = 0; i < image_count; i++) {
  2272. if (!images[i].disp.px)
  2273. continue;
  2274. if (images[i].disp_last < oldest) {
  2275. oldest = images[i].disp_last;
  2276. victim = i;
  2277. }
  2278. }
  2279. if (victim < 0)
  2280. return -1;
  2281. image_disp_drop(&images[victim]);
  2282. }
  2283. return 0;
  2284. }
  2285. /* Return a bitmap at exactly dw x dh, building it once from the capped source
  2286. * bitmap. Callers then draw with scale 1 and img_draw's copy fast path. */
  2287. static struct img_image *image_display_get(struct br_image *bi, int dw, int dh)
  2288. {
  2289. struct img_blit b;
  2290. unsigned int px;
  2291. if (!bi || bi->state != 1 || !bi->img.px || dw < 1 || dh < 1)
  2292. return 0;
  2293. if (dw == (int)bi->img.w && dh == (int)bi->img.h)
  2294. return &bi->img;
  2295. if (dw > 4096 || dh > 4096)
  2296. return &bi->img;
  2297. if (bi->disp.px && bi->disp.w == (unsigned int)dw &&
  2298. bi->disp.h == (unsigned int)dh) {
  2299. bi->disp_last = ++image_disp_clock;
  2300. return &bi->disp;
  2301. }
  2302. px = (unsigned int)dw * (unsigned int)dh;
  2303. if (px > BR_IMG_DISP_BUDGET || image_disp_room(px) != 0)
  2304. return &bi->img;
  2305. image_disp_drop(bi);
  2306. bi->disp.px = (unsigned short *)malloc(px * 2u);
  2307. if (!bi->disp.px)
  2308. return &bi->img;
  2309. if (bi->img.alpha) {
  2310. bi->disp.alpha = (unsigned char *)malloc(px);
  2311. if (!bi->disp.alpha) {
  2312. free(bi->disp.px);
  2313. bi->disp.px = 0;
  2314. return &bi->img;
  2315. }
  2316. }
  2317. bi->disp.w = (unsigned int)dw;
  2318. bi->disp.h = (unsigned int)dh;
  2319. bi->disp.format = bi->img.format;
  2320. bi->disp.flags = 0;
  2321. memset(&b, 0, sizeof(b));
  2322. b.dst = bi->disp.px;
  2323. b.dst_w = dw;
  2324. b.dst_h = dh;
  2325. b.clip_w = dw;
  2326. b.clip_h = dh;
  2327. b.scale = ((unsigned int)dw << 16) / bi->img.w;
  2328. b.dst_a = bi->disp.alpha;
  2329. b.flags = bi->disp.alpha ? IMG_BLIT_SAVE_ALPHA : 0;
  2330. img_draw(&bi->img, &b);
  2331. bi->disp_pixels = px;
  2332. image_disp_pixels += px;
  2333. bi->disp_last = ++image_disp_clock;
  2334. return &bi->disp;
  2335. }
  2336. /* Decode into the shared arena, then copy/scale the result into a display
  2337. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  2338. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  2339. * pixels. Transparent edges are composited over white. */
  2340. /* One decode scratch arena per page, reused across images. Allocating and
  2341. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  2342. * each small display bitmap landed in the hole the previous arena left, so
  2343. * the next arena no longer fit and the heap ratcheted up until an app
  2344. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  2345. * still released right after their one image. */
  2346. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  2347. static unsigned char *decode_arena_get(unsigned int bytes)
  2348. {
  2349. if (decode_arena && decode_arena_size >= bytes)
  2350. return decode_arena;
  2351. free(decode_arena);
  2352. decode_arena = (unsigned char *)malloc(bytes);
  2353. decode_arena_size = decode_arena ? bytes : 0;
  2354. return decode_arena;
  2355. }
  2356. static void decode_arena_put(void)
  2357. {
  2358. if (decode_arena_size > DECODE_ARENA_KEEP) {
  2359. free(decode_arena);
  2360. decode_arena = 0;
  2361. decode_arena_size = 0;
  2362. }
  2363. }
  2364. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  2365. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  2366. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  2367. static int svg_text_sniff(const unsigned char *d, unsigned int len);
  2368. static int svg_decode_image(const unsigned char *data, unsigned int len,
  2369. struct br_image *bi, int box_w, int box_h);
  2370. static int decode_image_data(const unsigned char *data, unsigned int len,
  2371. struct br_image *bi, int box_w, int box_h,
  2372. int fit_w, int fit_h)
  2373. {
  2374. struct img_info info;
  2375. struct img_options opt;
  2376. struct img_mem mem;
  2377. struct img_image decoded;
  2378. unsigned char *arena;
  2379. unsigned int est, bytes, i;
  2380. unsigned int t0;
  2381. unsigned short *px;
  2382. unsigned char *alpha = 0;
  2383. int dw, dh, r;
  2384. bi->url_hash = 0;
  2385. img_last_dec_ms = 0;
  2386. img_last_scale_ms = 0;
  2387. if (img_sniff(data, len, &info) != 0) {
  2388. if (svg_text_sniff(data, len))
  2389. return svg_decode_image(data, len, bi,
  2390. box_w > 0 && box_h > 0 ? box_w : fit_w,
  2391. box_w > 0 && box_h > 0 ? box_h : fit_h);
  2392. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  2393. return -1;
  2394. }
  2395. est = img_estimate(&info);
  2396. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  2397. s_copy(bi->err, "image too large", sizeof(bi->err));
  2398. return -1;
  2399. }
  2400. arena = decode_arena_get(est);
  2401. if (!arena) {
  2402. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2403. return -1;
  2404. }
  2405. img_mem_init(&mem, arena, est);
  2406. opt.max_pixels = BR_IMG_PIX_MAX;
  2407. opt.max_w = fit_w > 0 ? (unsigned int)fit_w :
  2408. (box_w > 0 ? (unsigned int)box_w : 0);
  2409. opt.max_h = fit_h > 0 ? (unsigned int)fit_h :
  2410. (box_h > 0 ? (unsigned int)box_h : 0);
  2411. t0 = u_ticks_ms();
  2412. r = img_decode(data, len, &opt, &mem, &decoded);
  2413. img_last_dec_ms = u_ticks_ms() - t0;
  2414. if (r != 0) {
  2415. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  2416. goto fail;
  2417. }
  2418. if (decoded.w == 0 || decoded.h == 0) {
  2419. s_copy(bi->err, "empty image", sizeof(bi->err));
  2420. goto fail;
  2421. }
  2422. /* The JPEG decoder may have reduced the IDCT output; the layout still
  2423. * needs the intrinsic dimensions from the header. */
  2424. bi->native_w = info.width ? (int)info.width : (int)decoded.w;
  2425. bi->native_h = info.height ? (int)info.height : (int)decoded.h;
  2426. dw = (int)decoded.w;
  2427. dh = (int)decoded.h;
  2428. /* An <img> with a CSS/attribute box only ever needs a bitmap that big:
  2429. * decoding 1200x800 and then box-filtering it to 1000x666, only to
  2430. * paint it at 400x267, doubled the decode-time scaling work. cap both
  2431. * axes with one scale so the aspect ratio is preserved. */
  2432. if (fit_w > 0 || fit_h > 0) {
  2433. unsigned int scw = fit_w > 0 ?
  2434. ((unsigned int)fit_w << 16) / decoded.w : ~0u;
  2435. unsigned int sch = fit_h > 0 ?
  2436. ((unsigned int)fit_h << 16) / decoded.h : ~0u;
  2437. unsigned int sc = scw < sch ? scw : sch;
  2438. if (sc < 0x10000u) {
  2439. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2440. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2441. if (dw < 1)
  2442. dw = 1;
  2443. if (dh < 1)
  2444. dh = 1;
  2445. }
  2446. }
  2447. if (box_w > 0 && box_h > 0) {
  2448. /* cover: scale so both box sides are filled, never up */
  2449. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  2450. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  2451. unsigned int sc = sw > sh ? sw : sh;
  2452. if (sc < 0x10000u) {
  2453. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2454. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2455. }
  2456. }
  2457. if (dw > BR_IMG_LAYOUT_W) {
  2458. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  2459. dw = BR_IMG_LAYOUT_W;
  2460. }
  2461. if (dh < 1)
  2462. dh = 1;
  2463. if (dw < 1)
  2464. dw = 1;
  2465. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  2466. BR_IMG_PIXEL_BUDGET) {
  2467. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  2468. goto fail;
  2469. }
  2470. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  2471. px = (unsigned short *)malloc(bytes);
  2472. if (!px) {
  2473. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2474. goto fail;
  2475. }
  2476. /* Keep the alpha plane for the scaled image so transparent logos and
  2477. * icons composite over the page instead of the browser's dark theme
  2478. * background. Very large alpha images stay flattened to bound the
  2479. * heap use. */
  2480. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  2481. alpha = (unsigned char *)malloc((unsigned int)dw *
  2482. (unsigned int)dh);
  2483. if (alpha) {
  2484. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2485. alpha[i] = 255;
  2486. }
  2487. }
  2488. /* With an alpha plane the colour under transparent pixels only shows
  2489. * through partially covered edge pixels of the downscale: use white,
  2490. * as documented above, not the dark browser theme (which left a dark
  2491. * fringe around scaled app icons). */
  2492. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2493. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  2494. {
  2495. struct img_blit b;
  2496. b.dst = px;
  2497. b.dst_w = dw;
  2498. b.dst_h = dh;
  2499. b.clip_x = 0;
  2500. b.clip_y = 0;
  2501. b.clip_w = dw;
  2502. b.clip_h = dh;
  2503. b.x = 0;
  2504. b.y = 0;
  2505. b.scale = ((unsigned int)dw << 16) / decoded.w;
  2506. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  2507. b.bg2 = b.bg;
  2508. b.dst_a = alpha;
  2509. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  2510. t0 = u_ticks_ms();
  2511. img_draw(&decoded, &b);
  2512. img_last_scale_ms = u_ticks_ms() - t0;
  2513. }
  2514. bi->img.format = decoded.format;
  2515. bi->img.w = (unsigned int)dw;
  2516. bi->img.h = (unsigned int)dh;
  2517. bi->img.px = px;
  2518. bi->img.alpha = alpha;
  2519. bi->img.flags = 0;
  2520. bi->state = 1;
  2521. image_pixels += (unsigned int)dw * (unsigned int)dh;
  2522. decode_arena_put();
  2523. return 0;
  2524. fail:
  2525. decode_arena_put();
  2526. return -1;
  2527. }
  2528. /* ---- URL / local path handling ---- */
  2529. static int is_http(const char *s)
  2530. {
  2531. return starts_with(s, "http://") || starts_with(s, "https://");
  2532. }
  2533. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  2534. static int normalize_abs(const char *in, char *out, unsigned int cap)
  2535. {
  2536. char seg[64];
  2537. unsigned int i = 0, o = 1;
  2538. int depth = 0;
  2539. int trailing;
  2540. if (!in || in[0] != '/' || cap < 2)
  2541. return -1;
  2542. trailing = 0;
  2543. {
  2544. unsigned int n = s_len(in);
  2545. if (n > 1 && in[n - 1] == '/')
  2546. trailing = 1;
  2547. }
  2548. out[0] = '/';
  2549. while (in[i]) {
  2550. unsigned int n = 0;
  2551. while (in[i] == '/')
  2552. i++;
  2553. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  2554. if (n + 1 < sizeof(seg))
  2555. seg[n++] = in[i];
  2556. i++;
  2557. }
  2558. seg[n] = '\0';
  2559. if (n == 0)
  2560. break;
  2561. if (s_eq(seg, "."))
  2562. continue;
  2563. if (s_eq(seg, "..")) {
  2564. if (depth > 0) {
  2565. while (o > 1 && out[o - 1] != '/')
  2566. o--;
  2567. if (o > 1)
  2568. o--;
  2569. depth--;
  2570. }
  2571. continue;
  2572. }
  2573. if (o > 1) {
  2574. if (o + 1 >= cap)
  2575. return -1;
  2576. out[o++] = '/';
  2577. }
  2578. if (o + n + 1 >= cap)
  2579. return -1;
  2580. {
  2581. unsigned int j;
  2582. for (j = 0; j < n; j++)
  2583. out[o++] = seg[j];
  2584. }
  2585. depth++;
  2586. }
  2587. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2588. if (o + 1 >= cap)
  2589. return -1;
  2590. out[o++] = '/';
  2591. }
  2592. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2593. if (in[i] == '?' || in[i] == '#') {
  2594. while (in[i]) {
  2595. if (o + 1 >= cap)
  2596. return -1;
  2597. out[o++] = in[i++];
  2598. }
  2599. }
  2600. out[o] = '\0';
  2601. return 0;
  2602. }
  2603. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2604. {
  2605. char joined[BR_URL_MAX];
  2606. if (!in || !in[0]) {
  2607. s_copy(out, cwd[0] ? cwd : "/", cap);
  2608. return;
  2609. }
  2610. if (in[0] == '/') {
  2611. if (normalize_abs(in, out, cap) != 0)
  2612. s_copy(out, in, cap);
  2613. return;
  2614. }
  2615. {
  2616. unsigned int n = 0;
  2617. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2618. s_append(joined, &n, "/", sizeof(joined));
  2619. s_append(joined, &n, in, sizeof(joined));
  2620. }
  2621. if (normalize_abs(joined, out, cap) != 0)
  2622. s_copy(out, joined, cap);
  2623. }
  2624. /* ---- canonical origin cache ---- *
  2625. *
  2626. * Sites commonly redirect http://host to https://host and then to
  2627. * https://www.host. Remember the final scheme/host of the last navigation so
  2628. * a bare domain typed again goes straight there instead of paying for two
  2629. * more connections and TLS handshakes. Only default-port requests are
  2630. * rewritten; explicit ports are left alone. */
  2631. #define ORIGIN_CACHE_MAX 8
  2632. #define ORIGIN_FILE "/share/borigins"
  2633. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2634. UHTTP_HOST_MAX + 2))
  2635. struct origin_cache_entry {
  2636. char host[UHTTP_HOST_MAX];
  2637. char origin[UHTTP_HOST_MAX + 16];
  2638. };
  2639. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2640. static int origin_count;
  2641. static char origin_buf[ORIGIN_BUF_SIZE];
  2642. static int default_port(const struct uhttp_url *u)
  2643. {
  2644. return u->secure ? u->port == 443 : u->port == 80;
  2645. }
  2646. static void url_origin(const struct uhttp_url *u, char *out,
  2647. unsigned int cap)
  2648. {
  2649. unsigned int n = 0;
  2650. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2651. s_append(out, &n, u->host, cap);
  2652. if (!default_port(u)) {
  2653. s_append(out, &n, ":", cap);
  2654. s_append_dec(out, &n, u->port, cap);
  2655. }
  2656. }
  2657. static void origin_cache_apply(char *url, unsigned int cap)
  2658. {
  2659. struct uhttp_url u;
  2660. char out[BR_URL_MAX];
  2661. unsigned int n = 0;
  2662. int i;
  2663. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2664. return;
  2665. for (i = 0; i < origin_count; i++) {
  2666. if (!s_eq(u.host, origins[i].host))
  2667. continue;
  2668. s_append(out, &n, origins[i].origin, sizeof(out));
  2669. s_append(out, &n, u.path, sizeof(out));
  2670. s_copy(url, out, cap);
  2671. return;
  2672. }
  2673. }
  2674. static void origin_cache_save(void)
  2675. {
  2676. unsigned int n = 0;
  2677. int i;
  2678. for (i = 0; i < origin_count; i++) {
  2679. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2680. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2681. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2682. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2683. }
  2684. if (n)
  2685. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2686. (int)origin_buf, (int)n);
  2687. }
  2688. static void origin_cache_load(void)
  2689. {
  2690. char *p;
  2691. int rn;
  2692. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2693. (int)(sizeof(origin_buf) - 1));
  2694. if (rn <= 0)
  2695. return;
  2696. origin_buf[rn] = '\0';
  2697. p = origin_buf;
  2698. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2699. char *line = p, *origin;
  2700. while (*p && *p != '\n')
  2701. p++;
  2702. if (*p)
  2703. *p++ = '\0';
  2704. if (!line[0])
  2705. continue;
  2706. origin = line;
  2707. while (*origin && *origin != ' ')
  2708. origin++;
  2709. if (!*origin)
  2710. continue;
  2711. *origin++ = '\0';
  2712. if (!line[0] || !is_http(origin))
  2713. continue;
  2714. {
  2715. struct uhttp_url uo;
  2716. if (uhttp_parse_url(origin, &uo) != 0 ||
  2717. !s_eq(uo.path, "/"))
  2718. continue;
  2719. }
  2720. s_copy(origins[origin_count].host, line,
  2721. sizeof(origins[origin_count].host));
  2722. s_copy(origins[origin_count].origin, origin,
  2723. sizeof(origins[origin_count].origin));
  2724. origin_count++;
  2725. }
  2726. }
  2727. static int host_is_www_of(const char *host, const char *base)
  2728. {
  2729. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2730. host[3] == '.' && s_eq(host + 4, base);
  2731. }
  2732. static void origin_cache_learn(const char *requested, const char *final)
  2733. {
  2734. struct uhttp_url from, to;
  2735. char origin[UHTTP_HOST_MAX + 16];
  2736. int i;
  2737. if (!is_http(requested) || !is_http(final))
  2738. return;
  2739. if (uhttp_parse_url(requested, &from) != 0 ||
  2740. uhttp_parse_url(final, &to) != 0)
  2741. return;
  2742. if (!default_port(&from))
  2743. return;
  2744. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2745. from.port == to.port)
  2746. return;
  2747. /* Only remember origin-level canonicalisation: the same path, and
  2748. * either the same host or its www./apex sibling. A path- or
  2749. * host-specific redirect (a shortener, a login page) must not poison
  2750. * every request to the typed host. */
  2751. if (!s_eq(from.path, to.path))
  2752. return;
  2753. if (!s_eq(from.host, to.host) &&
  2754. !host_is_www_of(to.host, from.host) &&
  2755. !host_is_www_of(from.host, to.host))
  2756. return;
  2757. url_origin(&to, origin, sizeof(origin));
  2758. for (i = 0; i < origin_count; i++) {
  2759. if (s_eq(origins[i].host, from.host)) {
  2760. if (!s_eq(origins[i].origin, origin)) {
  2761. s_copy(origins[i].origin, origin,
  2762. sizeof(origins[i].origin));
  2763. origin_cache_save();
  2764. }
  2765. return;
  2766. }
  2767. }
  2768. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2769. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2770. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2771. origin_cache_save();
  2772. }
  2773. static int path_dir(const char *path, char *out, unsigned int cap)
  2774. {
  2775. unsigned int i, last = 0;
  2776. for (i = 0; path[i]; i++)
  2777. if (path[i] == '/')
  2778. last = i;
  2779. if (last == 0) {
  2780. if (cap < 2)
  2781. return -1;
  2782. out[0] = '/';
  2783. out[1] = '\0';
  2784. return 0;
  2785. }
  2786. if (last + 1 >= cap)
  2787. return -1;
  2788. {
  2789. unsigned int j;
  2790. for (j = 0; j < last; j++)
  2791. out[j] = path[j];
  2792. out[last] = '\0';
  2793. }
  2794. return 0;
  2795. }
  2796. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2797. static int resolve_link(const char *base, const char *href, char *out,
  2798. unsigned int cap)
  2799. {
  2800. static char joined[BR_URL_MAX]; /* leaf: off the stack */
  2801. if (!href || !href[0] || href[0] == '#')
  2802. return -1;
  2803. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2804. starts_with(href, "data:") || starts_with(href, "tel:"))
  2805. return -1;
  2806. if (starts_with(href, "about:")) {
  2807. s_copy(out, href, cap);
  2808. return 0;
  2809. }
  2810. if (is_http(href)) {
  2811. s_copy(out, href, cap);
  2812. return 0;
  2813. }
  2814. if (starts_with(href, "//")) {
  2815. if (is_http(base)) {
  2816. unsigned int n = 0;
  2817. s_append(out, &n, starts_with(base, "https:") ?
  2818. "https:" : "http:", cap);
  2819. s_append(out, &n, href, cap);
  2820. return 0;
  2821. }
  2822. return -1;
  2823. }
  2824. if (is_http(base)) {
  2825. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2826. }
  2827. /* local page */
  2828. if (href[0] == '/') {
  2829. if (normalize_abs(href, out, cap) != 0)
  2830. return -1;
  2831. return 0;
  2832. }
  2833. {
  2834. static char dir[BR_URL_MAX];
  2835. unsigned int n = 0;
  2836. if (s_eq(base, "about:home"))
  2837. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2838. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2839. s_copy(dir, "/", sizeof(dir));
  2840. s_append(joined, &n, dir, sizeof(joined));
  2841. if (n == 0 || joined[n - 1] != '/')
  2842. s_append(joined, &n, "/", sizeof(joined));
  2843. s_append(joined, &n, href, sizeof(joined));
  2844. }
  2845. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2846. }
  2847. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2848. * rest instead of failing when a page or stylesheet is larger than the
  2849. * buffer. The stream is still walked to the end, so a normal page is
  2850. * verified; a truncated compressed input still returns whatever was decoded
  2851. * so far. */
  2852. struct trunc_buf {
  2853. unsigned char *dst;
  2854. unsigned int cap, pos;
  2855. int full;
  2856. };
  2857. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2858. {
  2859. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2860. if (len > m->cap - m->pos) {
  2861. unsigned int room = m->cap - m->pos;
  2862. if (room) {
  2863. unsigned int i;
  2864. for (i = 0; i < room; i++)
  2865. m->dst[m->pos + i] = data[i];
  2866. m->pos += room;
  2867. }
  2868. m->full = 1;
  2869. return 0;
  2870. }
  2871. {
  2872. unsigned int i;
  2873. for (i = 0; i < len; i++)
  2874. m->dst[m->pos + i] = data[i];
  2875. }
  2876. m->pos += len;
  2877. return 0;
  2878. }
  2879. static void worker_wait_ui(void);
  2880. static void inflate_ui_pump(void *ctx)
  2881. {
  2882. static unsigned int last;
  2883. unsigned int now = u_ticks_ms();
  2884. (void)ctx;
  2885. if ((int)(now - last) >= 50) {
  2886. last = now;
  2887. worker_wait_ui();
  2888. }
  2889. }
  2890. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2891. unsigned char *dst, unsigned int cap,
  2892. unsigned int *outlen, int gzip, int *truncated)
  2893. {
  2894. struct inflate_src in;
  2895. struct inflate_sink sink;
  2896. struct trunc_buf m;
  2897. unsigned int got = 0;
  2898. int r;
  2899. in.p = src;
  2900. in.len = len;
  2901. in.more = 0;
  2902. in.ctx = 0;
  2903. m.dst = dst;
  2904. m.cap = cap;
  2905. m.pos = 0;
  2906. m.full = 0;
  2907. sink.write = trunc_write;
  2908. sink.ctx = &m;
  2909. inflate_init(&image_inflate_ws, &in, &sink);
  2910. image_inflate_ws.progress = inflate_ui_pump;
  2911. image_inflate_ws.progress_ctx = 0;
  2912. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2913. inflate_zlib(&image_inflate_ws, &got);
  2914. *outlen = m.pos;
  2915. *truncated = m.full || r != 0;
  2916. if (r != 0 && m.pos == 0)
  2917. return -1;
  2918. return 0;
  2919. }
  2920. /* ---- headless fetch workers ------------------------------------------ *
  2921. *
  2922. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2923. * writes the raw response, a small metadata file and a done marker under
  2924. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2925. * or a multi-megabyte body never freezes the UI and images download in
  2926. * parallel.
  2927. */
  2928. struct fetch_meta {
  2929. int status;
  2930. int error;
  2931. int trunc;
  2932. unsigned int len;
  2933. unsigned int open_ms;
  2934. unsigned int first_ms;
  2935. unsigned int total_ms;
  2936. /* Optional decoded bitmap produced by the helper (image jobs). */
  2937. unsigned int dw, dh, nw, nh;
  2938. unsigned int alpha;
  2939. unsigned int px_len;
  2940. unsigned int dec_ms;
  2941. int dec_err;
  2942. char encoding[16];
  2943. char ctype[64];
  2944. char final[BR_URL_MAX];
  2945. };
  2946. static void draw(unsigned int *action);
  2947. static void handle_keys(unsigned int *action);
  2948. static void handle_page_click(unsigned int *action);
  2949. #define FETCH_WORKERS 4
  2950. #define FETCH_PATH_MAX 32
  2951. /* One long-lived curl __serve helper per worker. Each worker has its own
  2952. * request/body/meta/done files under /share so several downloads can be in
  2953. * flight at once; the keep-alive connection stays in the helper process, so
  2954. * tls.c's per-process state remains valid. */
  2955. struct fetch_worker {
  2956. int pid;
  2957. int slot;
  2958. int busy;
  2959. int ready;
  2960. int image_job;
  2961. unsigned int seq;
  2962. unsigned int deadline;
  2963. int retried;
  2964. unsigned int dec_w, dec_h;
  2965. int dec_retried;
  2966. char req[FETCH_PATH_MAX];
  2967. char body[FETCH_PATH_MAX];
  2968. char meta[FETCH_PATH_MAX];
  2969. char done[FETCH_PATH_MAX];
  2970. char post[FETCH_PATH_MAX];
  2971. char px[FETCH_PATH_MAX];
  2972. /* Optional preload job attached to this worker. */
  2973. unsigned int node;
  2974. int bg;
  2975. char url[BR_URL_MAX];
  2976. struct fetch_meta m;
  2977. };
  2978. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2979. static int fetch_tty = -2;
  2980. static void fetch_tty_drain(void);
  2981. static unsigned int fetch_session;
  2982. static unsigned int fetch_seq;
  2983. static struct fetch_meta fetch_meta;
  2984. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2985. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2986. static int fetch_last_error;
  2987. static unsigned int meta_uint(char **pp)
  2988. {
  2989. char *p = *pp;
  2990. unsigned int v = 0;
  2991. while (*p >= '0' && *p <= '9') {
  2992. v = v * 10 + (unsigned int)(*p - '0');
  2993. p++;
  2994. }
  2995. while (*p && *p != '\n')
  2996. p++;
  2997. if (*p == '\n')
  2998. p++;
  2999. *pp = p;
  3000. return v;
  3001. }
  3002. static void meta_str(char **pp, char *out, unsigned int cap)
  3003. {
  3004. char *p = *pp;
  3005. unsigned int n = 0;
  3006. while (*p && *p != '\n' && n + 1 < cap)
  3007. out[n++] = *p++;
  3008. out[n] = '\0';
  3009. while (*p && *p != '\n')
  3010. p++;
  3011. if (*p == '\n')
  3012. p++;
  3013. *pp = p;
  3014. }
  3015. static void worker_wait_ui(void)
  3016. {
  3017. unsigned int action = 0;
  3018. if (!ngui_begin(&ui))
  3019. return;
  3020. draw(&action);
  3021. handle_keys(&action);
  3022. handle_page_click(&action);
  3023. if (action & ACT_WAIT_NAV) {
  3024. pending_action |= action & ACT_WAIT_NAV;
  3025. if ((action & ACT_NAV) && click_url[0])
  3026. s_copy(pending_url, click_url, sizeof(pending_url));
  3027. click_url[0] = '\0';
  3028. cancel_fetch = 1;
  3029. }
  3030. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  3031. ngui_invalidate(&ui);
  3032. ngui_end(&ui);
  3033. }
  3034. static void fetch_path(char *out, unsigned int cap, const char *kind,
  3035. unsigned int session, int slot)
  3036. {
  3037. unsigned int n = 0;
  3038. s_append(out, &n, "/share/bf", cap);
  3039. s_append_dec(out, &n, session, cap);
  3040. s_append(out, &n, "_", cap);
  3041. s_append_dec(out, &n, (unsigned int)slot, cap);
  3042. s_append(out, &n, kind, cap);
  3043. }
  3044. static void fetch_pool_init(void)
  3045. {
  3046. static int ready;
  3047. int i;
  3048. if (ready)
  3049. return;
  3050. ready = 1;
  3051. fetch_session = ((unsigned int)u_getpid() << 16) ^
  3052. (u_ticks_ms() & 0xFFFFu);
  3053. if (!fetch_session)
  3054. fetch_session = 1;
  3055. for (i = 0; i < FETCH_WORKERS; i++) {
  3056. struct fetch_worker *w = &fetch_workers[i];
  3057. w->pid = -1;
  3058. w->slot = i;
  3059. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  3060. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  3061. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  3062. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  3063. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  3064. fetch_path(w->px, sizeof(w->px), "px", fetch_session, i);
  3065. }
  3066. }
  3067. static void fetch_worker_stop(struct fetch_worker *w)
  3068. {
  3069. int i;
  3070. /* An abandoned image job leaves its node loadable again. */
  3071. if (w->busy && w->image_job && w->node < doc.nnode) {
  3072. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  3073. doc.nodes[w->node].bg_img_index = -1;
  3074. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  3075. doc.nodes[w->node].img_index = -1;
  3076. }
  3077. if (w->pid > 0) {
  3078. u_kill((unsigned int)w->pid);
  3079. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  3080. u_sleep_ms(5);
  3081. /* Let the reaper close the socket before we reuse the slot. */
  3082. u_sleep_ms(10);
  3083. }
  3084. w->pid = -1;
  3085. w->busy = 0;
  3086. w->ready = 0;
  3087. w->image_job = 0;
  3088. if (w->req[0]) {
  3089. u_syscall1(SYS_UNLINK, (int)w->done);
  3090. u_syscall1(SYS_UNLINK, (int)w->meta);
  3091. u_syscall1(SYS_UNLINK, (int)w->body);
  3092. u_syscall1(SYS_UNLINK, (int)w->post);
  3093. u_syscall1(SYS_UNLINK, (int)w->req);
  3094. }
  3095. }
  3096. static void fetch_workers_stop_all(void)
  3097. {
  3098. int i;
  3099. for (i = 0; i < FETCH_WORKERS; i++)
  3100. fetch_worker_stop(&fetch_workers[i]);
  3101. }
  3102. /* Abandon the transfers of the current page but keep idle helpers and their
  3103. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  3104. * because its response would otherwise land in a reused /share slot. */
  3105. static void fetch_workers_cancel_busy(void)
  3106. {
  3107. int i;
  3108. for (i = 0; i < FETCH_WORKERS; i++)
  3109. if (fetch_workers[i].busy)
  3110. fetch_worker_stop(&fetch_workers[i]);
  3111. }
  3112. static void fetch_workers_prepare_nav(const char *url)
  3113. {
  3114. int i;
  3115. (void)url;
  3116. for (i = 0; i < FETCH_WORKERS; i++) {
  3117. struct fetch_worker *w = &fetch_workers[i];
  3118. if (w->pid <= 0)
  3119. continue;
  3120. /* Only an in-flight transfer must be aborted. Idle helpers
  3121. * stay warm across origins: there are just FETCH_WORKERS of
  3122. * them, and uhttp_open drops the old connection when the
  3123. * next job is for another host. Killing and respawning all
  3124. * four on every navigation churned processes and sockets
  3125. * while images were still loading. */
  3126. if (w->busy)
  3127. fetch_worker_stop(w);
  3128. }
  3129. }
  3130. /* The browser is no longer the active window and no fetch is running: give
  3131. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  3132. static void fetch_workers_stop_if_unfocused(void)
  3133. {
  3134. int i;
  3135. fetch_tty_drain();
  3136. if (ui.focused || page_loading || preload_active)
  3137. return;
  3138. for (i = 0; i < FETCH_WORKERS; i++)
  3139. if (fetch_workers[i].pid > 0) {
  3140. fetch_workers_stop_all();
  3141. return;
  3142. }
  3143. }
  3144. /* The helpers (and this process, since u_tty_create() rebinds our own
  3145. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  3146. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  3147. * a dozen TLS connections every helper hung in its next log line, so the
  3148. * following cross-origin navigation sat at "Loading..." until it timed out.
  3149. * Drain and discard it from every wait/poll loop. */
  3150. static void fetch_tty_drain(void)
  3151. {
  3152. char sink[512];
  3153. int i;
  3154. if (fetch_tty <= 0)
  3155. return;
  3156. for (i = 0; i < 16; i++)
  3157. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  3158. break;
  3159. }
  3160. static int fetch_worker_start(struct fetch_worker *w, char *err,
  3161. unsigned int errcap)
  3162. {
  3163. char arg[40];
  3164. unsigned int n = 0;
  3165. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  3166. return 0;
  3167. w->pid = -1;
  3168. fetch_pool_init();
  3169. if (fetch_tty == -2) {
  3170. int t = u_tty_create();
  3171. fetch_tty = t > 0 ? t : 0;
  3172. }
  3173. s_append(arg, &n, "__serve ", sizeof(arg));
  3174. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  3175. s_append(arg, &n, " ", sizeof(arg));
  3176. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  3177. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  3178. if (w->pid <= 0) {
  3179. w->pid = -1;
  3180. s_copy(err, "cannot start network helper", errcap);
  3181. return -1;
  3182. }
  3183. return 0;
  3184. }
  3185. static struct fetch_worker *fetch_worker_alloc(void)
  3186. {
  3187. int i;
  3188. fetch_pool_init();
  3189. for (i = 0; i < FETCH_WORKERS; i++)
  3190. if (!fetch_workers[i].busy)
  3191. return &fetch_workers[i];
  3192. return 0;
  3193. }
  3194. /* A worker for a synchronous foreground fetch (the page, a module, a
  3195. * script's fetch()/XHR). When image prefetches hold every helper, the
  3196. * newest image job (least progress) is abandoned: fetch_worker_stop()
  3197. * re-arms its node, so a later scan loads it again. Failing instead made
  3198. * cloudron.io's catalogue XHR return status 0 while its icons loaded. */
  3199. static struct fetch_worker *fetch_worker_alloc_fg(void)
  3200. {
  3201. struct fetch_worker *w = fetch_worker_alloc(), *victim = 0;
  3202. int i;
  3203. if (w)
  3204. return w;
  3205. for (i = 0; i < FETCH_WORKERS; i++) {
  3206. struct fetch_worker *c = &fetch_workers[i];
  3207. if (c->busy && c->image_job &&
  3208. (!victim || (int)(c->seq - victim->seq) > 0))
  3209. victim = c;
  3210. }
  3211. if (victim)
  3212. fetch_worker_stop(victim);
  3213. return victim;
  3214. }
  3215. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3216. unsigned int cap, const char *method,
  3217. const char *ctype, const char *post,
  3218. unsigned int post_len, unsigned int node,
  3219. int bg, unsigned int dec_w,
  3220. unsigned int dec_h, char *err,
  3221. unsigned int errcap);
  3222. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  3223. unsigned int cap, const char *post,
  3224. unsigned int post_len, unsigned int node,
  3225. int bg, char *err, unsigned int errcap)
  3226. {
  3227. /* A body pointer with no bytes is still a POST: the classic request
  3228. * line would turn it into a GET. */
  3229. if (post && !post_len)
  3230. return fetch_worker_submit_req(w, url, cap, "POST",
  3231. "application/x-www-form-urlencoded", post, 0, node,
  3232. bg, 0, 0, err, errcap);
  3233. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  3234. node, bg, 0, 0, err, errcap);
  3235. }
  3236. /* Image job: ask the helper to decode at these display bounds as well. */
  3237. static int fetch_worker_submit_image(struct fetch_worker *w, const char *url,
  3238. unsigned int cap, unsigned int node,
  3239. int bg, unsigned int dec_w,
  3240. unsigned int dec_h, char *err,
  3241. unsigned int errcap)
  3242. {
  3243. return fetch_worker_submit_req(w, url, cap, 0, 0, 0, 0, node, bg,
  3244. dec_w, dec_h, err, errcap);
  3245. }
  3246. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  3247. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  3248. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3249. unsigned int cap, const char *method,
  3250. const char *ctype, const char *post,
  3251. unsigned int post_len, unsigned int node,
  3252. int bg, unsigned int dec_w,
  3253. unsigned int dec_h, char *err,
  3254. unsigned int errcap)
  3255. {
  3256. static char req[BR_URL_MAX + 256];
  3257. unsigned int n = 0;
  3258. fetch_seq++;
  3259. if (!fetch_seq)
  3260. fetch_seq = 1;
  3261. w->seq = fetch_seq;
  3262. w->ready = 0;
  3263. w->image_job = 0;
  3264. w->retried = 0;
  3265. w->m.error = 0;
  3266. w->node = node;
  3267. w->bg = bg;
  3268. w->dec_w = dec_w;
  3269. w->dec_h = dec_h;
  3270. w->dec_retried = 0;
  3271. s_copy(w->url, url, sizeof(w->url));
  3272. s_append_dec(req, &n, w->seq, sizeof(req));
  3273. s_append(req, &n, " ", sizeof(req));
  3274. s_append_dec(req, &n, cap, sizeof(req));
  3275. s_append(req, &n, " ", sizeof(req));
  3276. if (dec_w || dec_h) {
  3277. s_append(req, &n, "D ", sizeof(req));
  3278. s_append_dec(req, &n, dec_w, sizeof(req));
  3279. s_append(req, &n, " ", sizeof(req));
  3280. s_append_dec(req, &n, dec_h, sizeof(req));
  3281. s_append(req, &n, " ", sizeof(req));
  3282. } else if (method) {
  3283. unsigned int k;
  3284. s_append(req, &n, "X ", sizeof(req));
  3285. s_append(req, &n, method, sizeof(req));
  3286. s_append(req, &n, " ", sizeof(req));
  3287. s_append_dec(req, &n, post_len, sizeof(req));
  3288. s_append(req, &n, " ", sizeof(req));
  3289. if (!ctype || !ctype[0])
  3290. s_append(req, &n, "-", sizeof(req));
  3291. /* One token on the request line: drop the spaces
  3292. * ("application/json; charset=utf-8" stays valid). */
  3293. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  3294. if (ctype[k] != ' ')
  3295. req[n++] = ctype[k];
  3296. req[n] = '\0';
  3297. s_append(req, &n, " ", sizeof(req));
  3298. } else if (post_len) {
  3299. s_append(req, &n, "POST ", sizeof(req));
  3300. s_append_dec(req, &n, post_len, sizeof(req));
  3301. s_append(req, &n, " ", sizeof(req));
  3302. }
  3303. s_append(req, &n, url, sizeof(req));
  3304. s_append(req, &n, "\n", sizeof(req));
  3305. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  3306. (int)post, (int)post_len) < 0) {
  3307. s_copy(err, "cannot queue form body", errcap);
  3308. return -1;
  3309. }
  3310. u_syscall1(SYS_UNLINK, (int)w->done);
  3311. u_syscall1(SYS_UNLINK, (int)w->meta);
  3312. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  3313. s_copy(err, "cannot queue network request", errcap);
  3314. return -1;
  3315. }
  3316. if (fetch_worker_start(w, err, errcap) != 0)
  3317. return -1;
  3318. w->busy = 1;
  3319. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  3320. return 0;
  3321. }
  3322. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  3323. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  3324. unsigned int errcap)
  3325. {
  3326. static char meta[BR_URL_MAX + 1024];
  3327. char *p;
  3328. int rn, mseq;
  3329. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  3330. (int)(sizeof(meta) - 1));
  3331. if (rn <= 0) {
  3332. s_copy(err, "network helper failed", errcap);
  3333. return -1;
  3334. }
  3335. meta[rn] = '\0';
  3336. p = meta;
  3337. mseq = (int)meta_uint(&p);
  3338. if (mseq != (int)w->seq) {
  3339. s_copy(err, "stale network response", errcap);
  3340. return -1;
  3341. }
  3342. w->m.status = (int)meta_uint(&p);
  3343. w->m.error = (int)meta_uint(&p);
  3344. w->m.trunc = (int)meta_uint(&p);
  3345. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  3346. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  3347. meta_str(&p, w->m.final, sizeof(w->m.final));
  3348. w->m.len = meta_uint(&p);
  3349. w->m.open_ms = 0;
  3350. w->m.first_ms = 0;
  3351. w->m.total_ms = 0;
  3352. if (*p) {
  3353. w->m.open_ms = meta_uint(&p);
  3354. w->m.first_ms = meta_uint(&p);
  3355. w->m.total_ms = meta_uint(&p);
  3356. }
  3357. w->m.dw = w->m.dh = w->m.nw = w->m.nh = 0;
  3358. w->m.alpha = w->m.px_len = w->m.dec_ms = 0;
  3359. w->m.dec_err = 0;
  3360. if (*p) {
  3361. w->m.dw = meta_uint(&p);
  3362. w->m.dh = meta_uint(&p);
  3363. w->m.nw = meta_uint(&p);
  3364. w->m.nh = meta_uint(&p);
  3365. w->m.alpha = meta_uint(&p);
  3366. w->m.px_len = meta_uint(&p);
  3367. w->m.dec_err = (int)meta_uint(&p);
  3368. w->m.dec_ms = meta_uint(&p);
  3369. }
  3370. if (w->m.error) {
  3371. s_copy(err, uhttp_error_string(w->m.error), errcap);
  3372. return -1;
  3373. }
  3374. w->ready = 1;
  3375. return 0;
  3376. }
  3377. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  3378. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  3379. unsigned int errcap)
  3380. {
  3381. static char done[24];
  3382. char *p;
  3383. int rn, mseq;
  3384. fetch_tty_drain();
  3385. if (!w->busy)
  3386. return -1;
  3387. if (w->ready)
  3388. return 1;
  3389. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  3390. (int)(sizeof(done) - 1));
  3391. if (rn > 0) {
  3392. done[rn] = '\0';
  3393. p = done;
  3394. mseq = (int)meta_uint(&p);
  3395. if (mseq == (int)w->seq) {
  3396. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  3397. fetch_worker_stop(w);
  3398. return -1;
  3399. }
  3400. return 1;
  3401. }
  3402. }
  3403. if (!u_alive((unsigned int)w->pid)) {
  3404. w->pid = -1;
  3405. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  3406. w->retried = 1;
  3407. return 0;
  3408. }
  3409. s_copy(err, "network helper stopped", errcap);
  3410. fetch_worker_stop(w);
  3411. return -1;
  3412. }
  3413. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  3414. s_copy(err, "network request timed out", errcap);
  3415. fetch_worker_stop(w);
  3416. return -1;
  3417. }
  3418. return 0;
  3419. }
  3420. /* Copy the completed body, inflating it if the server ignored our identity
  3421. * request. Mirrors the old fetch_remote body path. */
  3422. static int fetch_worker_read_body(struct fetch_worker *w,
  3423. unsigned char *plain,
  3424. unsigned int plaincap,
  3425. unsigned char *comp,
  3426. unsigned int compcap,
  3427. int *truncated, char *err,
  3428. unsigned int errcap)
  3429. {
  3430. int rv, zr, was_trunc;
  3431. if (contains_ci(w->m.encoding, "gzip") ||
  3432. contains_ci(w->m.encoding, "deflate")) {
  3433. unsigned int comp_len = 0, plen = 0;
  3434. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  3435. (int)compcap);
  3436. if (rv < 0) {
  3437. s_copy(err, "empty response", errcap);
  3438. return -1;
  3439. }
  3440. comp_len = (unsigned int)rv;
  3441. if (comp_len < w->m.len) {
  3442. s_copy(err, "compressed response is too large", errcap);
  3443. return -1;
  3444. }
  3445. if (contains_ci(w->m.encoding, "deflate"))
  3446. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3447. &plen, 0, &was_trunc);
  3448. else
  3449. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3450. &plen, 1, &was_trunc);
  3451. if (zr != 0) {
  3452. s_copy(err, "compressed response is corrupt", errcap);
  3453. return -1;
  3454. }
  3455. *truncated = w->m.trunc || was_trunc;
  3456. return (int)plen;
  3457. }
  3458. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  3459. if (rv < 0) {
  3460. s_copy(err, "empty response", errcap);
  3461. return -1;
  3462. }
  3463. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  3464. return rv;
  3465. }
  3466. static void fetch_worker_release(struct fetch_worker *w)
  3467. {
  3468. u_syscall1(SYS_UNLINK, (int)w->done);
  3469. u_syscall1(SYS_UNLINK, (int)w->meta);
  3470. u_syscall1(SYS_UNLINK, (int)w->body);
  3471. u_syscall1(SYS_UNLINK, (int)w->post);
  3472. u_syscall1(SYS_UNLINK, (int)w->px);
  3473. u_syscall1(SYS_UNLINK, (int)w->req);
  3474. w->busy = 0;
  3475. w->ready = 0;
  3476. w->image_job = 0;
  3477. w->dec_w = 0;
  3478. w->dec_h = 0;
  3479. w->dec_retried = 0;
  3480. }
  3481. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  3482. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  3483. unsigned int errcap)
  3484. {
  3485. for (;;) {
  3486. int rv;
  3487. if (!fetch_wait_passive)
  3488. worker_wait_ui();
  3489. if (cancel_fetch || pending_action) {
  3490. fetch_workers_cancel_busy();
  3491. return FETCH_ABORT;
  3492. }
  3493. rv = fetch_worker_poll(w, err, errcap);
  3494. if (rv != 0)
  3495. return rv == 1 ? 0 : -1;
  3496. u_sleep_ms(10);
  3497. }
  3498. }
  3499. static int fetch_remote(const char *url, unsigned int cap,
  3500. const char *post, unsigned int post_len,
  3501. unsigned char *plain, unsigned int plaincap,
  3502. unsigned char *comp, unsigned int compcap,
  3503. struct fetch_meta *m, int *truncated,
  3504. char *err, unsigned int errcap)
  3505. {
  3506. struct fetch_worker *w = fetch_worker_alloc_fg();
  3507. int rv;
  3508. fetch_last_error = 0;
  3509. if (!w) {
  3510. s_copy(err, "network busy", errcap);
  3511. return -1;
  3512. }
  3513. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  3514. err, errcap) != 0) {
  3515. fetch_worker_release(w);
  3516. return -1;
  3517. }
  3518. rv = fetch_worker_wait(w, err, errcap);
  3519. if (rv == FETCH_ABORT) {
  3520. fetch_worker_release(w);
  3521. return FETCH_ABORT;
  3522. }
  3523. if (rv != 0) {
  3524. fetch_last_error = w->m.error;
  3525. fetch_worker_release(w);
  3526. return -1;
  3527. }
  3528. *m = w->m;
  3529. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  3530. truncated, err, errcap);
  3531. fetch_worker_release(w);
  3532. if (rv >= 0 && (cancel_fetch || pending_action))
  3533. return FETCH_ABORT;
  3534. return rv;
  3535. }
  3536. static int fetch_worker_status(const struct fetch_worker *w)
  3537. {
  3538. return w->m.status;
  3539. }
  3540. /* fetch()/XHR through a helper: one request, the status and body come back
  3541. * whatever the HTTP status (a 401 is an answer, not a network error). */
  3542. static int js_worker_http(const char *method, const char *url,
  3543. const char *ctype, const char *body,
  3544. unsigned int body_len, struct js_http_resp *r,
  3545. char *err, int errcap)
  3546. {
  3547. struct fetch_worker *w = fetch_worker_alloc_fg();
  3548. unsigned char *plain;
  3549. int rv, tr = 0;
  3550. if (!w) {
  3551. s_copy(err, "network busy", (unsigned int)errcap);
  3552. return -1;
  3553. }
  3554. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  3555. body_len, 0, 0, 0, 0, err,
  3556. (unsigned int)errcap) != 0) {
  3557. fetch_worker_release(w);
  3558. return -1;
  3559. }
  3560. fetch_wait_passive++;
  3561. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  3562. fetch_wait_passive--;
  3563. if (rv != 0) {
  3564. if (rv == FETCH_ABORT)
  3565. s_copy(err, "page is navigating", (unsigned int)errcap);
  3566. fetch_worker_release(w);
  3567. return -1;
  3568. }
  3569. r->status = w->m.status;
  3570. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  3571. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  3572. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  3573. if (!plain) {
  3574. fetch_worker_release(w);
  3575. s_copy(err, "out of memory", (unsigned int)errcap);
  3576. return -1;
  3577. }
  3578. if (w->m.len == 0) {
  3579. rv = 0; /* 204, an empty 200: no body file */
  3580. } else {
  3581. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  3582. image_io_buf, BR_PAGE_COMP_MAX,
  3583. &tr, err, (unsigned int)errcap);
  3584. }
  3585. fetch_worker_release(w);
  3586. if (rv < 0) {
  3587. free(plain);
  3588. return -1;
  3589. }
  3590. plain[rv] = '\0';
  3591. r->body = (char *)plain;
  3592. r->len = (unsigned int)rv;
  3593. return 0;
  3594. }
  3595. /* ---- HTTP / file fetch ---- */
  3596. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  3597. unsigned int *outlen, int *is_local, char *ctype,
  3598. unsigned int ctcap, char *final, unsigned int finalcap,
  3599. char *err, unsigned int errcap, int *truncated,
  3600. const char *post, unsigned int post_len)
  3601. {
  3602. unsigned char *buf;
  3603. unsigned int len;
  3604. int tr = 0;
  3605. int rv;
  3606. *out = 0;
  3607. *outlen = 0;
  3608. *truncated = 0;
  3609. if (final && finalcap)
  3610. final[0] = '\0';
  3611. if (ctype && ctcap)
  3612. ctype[0] = '\0';
  3613. if (url[0] == '/') {
  3614. char pathbuf[BR_URL_MAX];
  3615. const char *open_url = url;
  3616. unsigned int i = 0;
  3617. /* A local form GET keeps ?query in the address bar but the
  3618. * file lookup uses the path alone, like a real browser. */
  3619. while (url[i] && url[i] != '?' && url[i] != '#')
  3620. i++;
  3621. if (url[i]) {
  3622. s_copy(pathbuf, url, i + 1);
  3623. open_url = pathbuf;
  3624. }
  3625. buf = (unsigned char *)malloc(cap);
  3626. if (!buf) {
  3627. s_copy(err, "out of memory", errcap);
  3628. return -1;
  3629. }
  3630. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  3631. if (rv < 0) {
  3632. free(buf);
  3633. s_copy(err, "file not found", errcap);
  3634. return -1;
  3635. }
  3636. *out = buf;
  3637. *outlen = (unsigned int)rv;
  3638. *is_local = 1;
  3639. if (ctype)
  3640. s_copy(ctype, "text/html", ctcap);
  3641. if (final)
  3642. s_copy(final, url, finalcap);
  3643. if ((unsigned int)rv == cap)
  3644. *truncated = 1;
  3645. return 0;
  3646. }
  3647. buf = (unsigned char *)malloc(cap);
  3648. if (!buf) {
  3649. s_copy(err, "out of memory", errcap);
  3650. return -1;
  3651. }
  3652. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3653. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3654. if (rv == FETCH_ABORT) {
  3655. free(buf);
  3656. return FETCH_ABORT;
  3657. }
  3658. if (rv < 0) {
  3659. free(buf);
  3660. return -1;
  3661. }
  3662. len = (unsigned int)rv;
  3663. if (len == 0) {
  3664. free(buf);
  3665. s_copy(err, "empty response", errcap);
  3666. return -1;
  3667. }
  3668. if (ctype)
  3669. s_copy(ctype, fetch_meta.ctype, ctcap);
  3670. if (final && fetch_meta.final[0])
  3671. s_copy(final, fetch_meta.final, finalcap);
  3672. *is_local = 0;
  3673. *out = buf;
  3674. *outlen = len;
  3675. *truncated = tr;
  3676. return 0;
  3677. }
  3678. static unsigned int css_cache_hash(const char *s);
  3679. /* Remote fonts are cached under /share for the current boot like the
  3680. * stylesheets, as the raw response (a WOFF stays compressed). */
  3681. static int font_cache_count;
  3682. static void font_cache_path(const char *url, char *out, unsigned int cap)
  3683. {
  3684. unsigned int n = 0;
  3685. s_append(out, &n, "/share/" FONT_CACHE_PREFIX, cap);
  3686. s_append_dec(out, &n, css_cache_hash(url), cap);
  3687. }
  3688. static void font_cache_init(void)
  3689. {
  3690. struct sys_dirent d;
  3691. int i;
  3692. font_cache_count = 0;
  3693. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3694. (int)&d) == 1; i++)
  3695. if (starts_with(d.name, FONT_CACHE_PREFIX))
  3696. font_cache_count++;
  3697. }
  3698. /* Read one font file (local path, boot cache or network) into a fresh
  3699. * malloc'ed buffer. Returns its length, or -1. */
  3700. static int font_fetch(const char *abs, unsigned char **out)
  3701. {
  3702. unsigned char *buf;
  3703. char path[96];
  3704. int rv;
  3705. *out = 0;
  3706. buf = (unsigned char *)malloc(UFONT_MAX_FILE + 512u);
  3707. if (!buf)
  3708. return -1;
  3709. if (abs[0] == '/') {
  3710. struct sys_stat st;
  3711. /* FAT reads may write past the length: the 512 bytes of
  3712. * slack above cover the final partial sector. */
  3713. if (u_stat(abs, &st) != 0 || st.is_dir || st.size == 0 ||
  3714. st.size > UFONT_MAX_FILE) {
  3715. free(buf);
  3716. return -1;
  3717. }
  3718. rv = u_syscall3(SYS_READ_FILE, (int)abs, (int)buf,
  3719. (int)st.size);
  3720. if (rv != (int)st.size) {
  3721. free(buf);
  3722. return -1;
  3723. }
  3724. *out = buf;
  3725. return rv;
  3726. }
  3727. if (!is_http(abs)) {
  3728. free(buf);
  3729. return -1;
  3730. }
  3731. font_cache_path(abs, path, sizeof(path));
  3732. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)buf,
  3733. (int)UFONT_MAX_FILE);
  3734. if (rv > 0 && (unsigned int)rv < UFONT_MAX_FILE) {
  3735. *out = buf;
  3736. return rv;
  3737. }
  3738. {
  3739. char err[64];
  3740. int tr = 0;
  3741. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3742. UFONT_MAX_FILE, image_io_buf,
  3743. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err,
  3744. sizeof(err));
  3745. /* An error page is not a font: never parse or cache it. */
  3746. if (rv > 0 && !tr && fetch_meta.status >= 300) {
  3747. snprintf(err, sizeof(err), "HTTP %d", fetch_meta.status);
  3748. rv = 0;
  3749. }
  3750. if (rv <= 0 || tr) {
  3751. u_puts("[font] failed: ");
  3752. u_puts(abs);
  3753. u_puts(rv <= 0 ? " " : " truncated ");
  3754. u_puts(rv <= 0 ? err : "");
  3755. u_putc('\n');
  3756. free(buf);
  3757. return -1;
  3758. }
  3759. }
  3760. if (font_cache_count < FONT_CACHE_MAX &&
  3761. u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, rv) >= 0)
  3762. font_cache_count++;
  3763. *out = buf;
  3764. return rv;
  3765. }
  3766. /* Open one @font-face entry: fetch, unwrap WOFF, parse into the ufont
  3767. * arena. A WOFF2 or CFF (OTTO) file is reported and left unloaded. */
  3768. static struct ufont_face *font_open_entry(int id)
  3769. {
  3770. const char *url = br_font_face_url(id);
  3771. const char *base = br_font_face_base(id);
  3772. char abs[BR_URL_MAX];
  3773. unsigned char *buf, *sfnt;
  3774. unsigned int slen = 0;
  3775. struct ufont_face *f = 0;
  3776. const char *why = 0;
  3777. int n;
  3778. if (!url || !url[0] ||
  3779. resolve_link(base && base[0] ? base : page_url, url, abs,
  3780. sizeof(abs)) != 0)
  3781. return 0;
  3782. n = font_fetch(abs, &buf);
  3783. if (n <= 0)
  3784. return 0;
  3785. sfnt = buf;
  3786. slen = (unsigned int)n;
  3787. if (ufont_is_woff2(buf, slen)) {
  3788. why = "WOFF2 not supported";
  3789. } else if (ufont_is_woff(buf, slen)) {
  3790. sfnt = ufont_woff_decode(buf, slen, &slen);
  3791. if (!sfnt)
  3792. why = "bad WOFF";
  3793. }
  3794. if (!why) {
  3795. f = ufont_face_open_mem(sfnt, slen);
  3796. if (!f)
  3797. why = (slen >= 4 && sfnt[0] == 'O' && sfnt[1] == 'T' &&
  3798. sfnt[2] == 'T' && sfnt[3] == 'O') ?
  3799. "CFF outlines not supported" :
  3800. "not a TrueType font or arena full";
  3801. }
  3802. if (sfnt && sfnt != buf)
  3803. free(sfnt);
  3804. free(buf);
  3805. u_puts(f ? "[font] loaded " : "[font] skipped ");
  3806. u_puts(br_font_face_family(id));
  3807. u_puts(": ");
  3808. u_puts(abs);
  3809. if (why) {
  3810. u_puts(" (");
  3811. u_puts(why);
  3812. u_putc(')');
  3813. }
  3814. u_putc('\n');
  3815. return f;
  3816. }
  3817. /* Distance of a face from the requested weight: 0 inside its range. A
  3818. * bold request prefers heavier faces and a normal one lighter faces, as
  3819. * the CSS font-matching steps do. */
  3820. static unsigned int font_weight_dist(const struct br_font_face_info *fi,
  3821. unsigned int want)
  3822. {
  3823. if (want >= fi->wmin && want <= fi->wmax)
  3824. return 0;
  3825. if (want > fi->wmax)
  3826. return (want - fi->wmax) * 2u + (want >= 500 ? 1u : 0u);
  3827. return (fi->wmin - want) * 2u + (want < 500 ? 1u : 0u);
  3828. }
  3829. /* Load the @font-face entries a font-family declaration named: per family
  3830. * the regular face first, then bold, italic and the rest, so a full arena
  3831. * drops the least common variants. Then precompute, for every family and
  3832. * (bold, italic) combination, the loaded face CSS font matching picks;
  3833. * layout reads only that table. A family with no loaded face keeps
  3834. * font_pick 0, and its text uses the built-in set. */
  3835. static void load_font_faces(void)
  3836. {
  3837. int n = br_font_face_count(), pass, id;
  3838. memset(font_faces, 0, sizeof(font_faces));
  3839. memset(font_pick, 0, sizeof(font_pick));
  3840. if (n > BR_MAX_FACES)
  3841. n = BR_MAX_FACES;
  3842. for (pass = 0; pass < 4; pass++) {
  3843. for (id = 1; id <= n; id++) {
  3844. struct br_font_face_info fi;
  3845. int cls;
  3846. if (br_font_face_info(id, &fi) != 0 || !fi.used)
  3847. continue;
  3848. if (!fi.italic && fi.wmin <= 400 && fi.wmax >= 400)
  3849. cls = 0;
  3850. else if (!fi.italic && fi.wmin <= 700 &&
  3851. fi.wmax >= 700)
  3852. cls = 1;
  3853. else if (fi.italic && fi.wmin <= 400 &&
  3854. fi.wmax >= 400)
  3855. cls = 2;
  3856. else
  3857. cls = 3;
  3858. if (cls == pass)
  3859. font_faces[id - 1] = font_open_entry(id);
  3860. }
  3861. }
  3862. for (id = 1; id <= n; id++) {
  3863. struct br_font_face_info fam;
  3864. int combo;
  3865. if (br_font_face_info(id, &fam) != 0 || fam.family_id != id)
  3866. continue;
  3867. for (combo = 0; combo < 4; combo++) {
  3868. unsigned int want = (combo & 2) ? 700u : 400u;
  3869. int italic = combo & 1, k, best = 0;
  3870. unsigned int best_score = 0;
  3871. for (k = 1; k <= n; k++) {
  3872. struct br_font_face_info fi;
  3873. unsigned int score;
  3874. if (!font_faces[k - 1] ||
  3875. br_font_face_info(k, &fi) != 0 ||
  3876. fi.family_id != id)
  3877. continue;
  3878. score = font_weight_dist(&fi, want) +
  3879. ((fi.italic != 0) != (italic != 0) ?
  3880. 100000u : 0u);
  3881. if (!best || score < best_score) {
  3882. best = k;
  3883. best_score = score;
  3884. }
  3885. }
  3886. font_pick[id - 1][combo] = (unsigned char)best;
  3887. }
  3888. }
  3889. }
  3890. /* Remote scripts are cached under /share for the current boot, like the
  3891. * stylesheet cache, so reloads and later visits skip the network. */
  3892. static int script_cache_count;
  3893. static unsigned int script_cache_hash(const char *s)
  3894. {
  3895. unsigned int h = 2166136261u;
  3896. while (*s) {
  3897. h ^= (unsigned char)*s++;
  3898. h *= 16777619u;
  3899. }
  3900. return h;
  3901. }
  3902. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3903. {
  3904. unsigned int n = 0;
  3905. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3906. s_append_dec(out, &n, script_cache_hash(url), cap);
  3907. }
  3908. static void script_cache_clear(void)
  3909. {
  3910. struct sys_dirent d;
  3911. char path[96];
  3912. for (;;) {
  3913. int i, found = 0;
  3914. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3915. (int)&d) == 1; i++) {
  3916. unsigned int n = 0;
  3917. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3918. continue;
  3919. s_append(path, &n, "/share/", sizeof(path));
  3920. s_append(path, &n, d.name, sizeof(path));
  3921. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3922. return;
  3923. found = 1;
  3924. break;
  3925. }
  3926. if (!found)
  3927. break;
  3928. }
  3929. script_cache_count = 0;
  3930. }
  3931. static void script_cache_init(void)
  3932. {
  3933. struct sys_dirent d;
  3934. int i, count = 0;
  3935. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3936. (int)&d) == 1; i++)
  3937. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3938. count++;
  3939. if (count >= SCRIPT_CACHE_MAX) {
  3940. script_cache_clear();
  3941. return;
  3942. }
  3943. script_cache_count = count;
  3944. }
  3945. static int script_cache_get(const char *url, unsigned char **out,
  3946. unsigned int *outlen)
  3947. {
  3948. char path[96];
  3949. struct sys_stat st;
  3950. unsigned char *buf;
  3951. int rn;
  3952. script_cache_path(url, path, sizeof(path));
  3953. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3954. st.size >= SCRIPT_CACHE_FILE_MAX)
  3955. return 0;
  3956. buf = (unsigned char *)malloc(st.size + 1);
  3957. if (!buf)
  3958. return 0;
  3959. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3960. if (rn != (int)st.size) {
  3961. free(buf);
  3962. return 0;
  3963. }
  3964. buf[st.size] = '\0';
  3965. *out = buf;
  3966. *outlen = st.size;
  3967. return 1;
  3968. }
  3969. static void script_cache_put(const char *url, const unsigned char *data,
  3970. unsigned int len)
  3971. {
  3972. char path[96];
  3973. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3974. len >= SCRIPT_CACHE_FILE_MAX)
  3975. return;
  3976. script_cache_path(url, path, sizeof(path));
  3977. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3978. (int)len) >= 0)
  3979. script_cache_count++;
  3980. }
  3981. static int script_cache_has(const char *url)
  3982. {
  3983. char path[96];
  3984. struct sys_stat st;
  3985. script_cache_path(url, path, sizeof(path));
  3986. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3987. st.size < SCRIPT_CACHE_FILE_MAX;
  3988. }
  3989. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3990. static int fetch_script_text(const char *url, unsigned char **out,
  3991. unsigned int *outlen, char *err,
  3992. unsigned int errcap)
  3993. {
  3994. unsigned char *buf;
  3995. unsigned int len;
  3996. int local, truncated = 0;
  3997. char ctype[64], final[BR_URL_MAX];
  3998. int rv;
  3999. *out = 0;
  4000. *outlen = 0;
  4001. if (url[0] != '/' && script_cache_get(url, out, outlen))
  4002. return 0;
  4003. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  4004. sizeof(ctype), final, sizeof(final), err, errcap,
  4005. &truncated, 0, 0);
  4006. if (rv != 0)
  4007. return rv;
  4008. if (truncated || len >= BR_SCRIPT_MAX) {
  4009. free(buf);
  4010. s_copy(err, "script is too large", errcap);
  4011. return -1;
  4012. }
  4013. buf[len] = '\0';
  4014. if (!local)
  4015. script_cache_put(url, buf, len);
  4016. *out = buf;
  4017. *outlen = len;
  4018. return 0;
  4019. }
  4020. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  4021. * the heap, so images must not allocate their file body from it as well. */
  4022. static int fetch_image(const char *url, unsigned int cap,
  4023. unsigned char **out, unsigned int *outlen,
  4024. char *err, unsigned int errcap)
  4025. {
  4026. unsigned int len;
  4027. int tr = 0;
  4028. int rv;
  4029. *out = 0;
  4030. *outlen = 0;
  4031. if (cap > BR_IMG_FILE_MAX)
  4032. cap = BR_IMG_FILE_MAX;
  4033. if (url[0] == '/') {
  4034. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  4035. (int)cap);
  4036. if (rv < 0) {
  4037. s_copy(err, "file not found", errcap);
  4038. return -1;
  4039. }
  4040. *out = image_file_buf;
  4041. *outlen = (unsigned int)rv;
  4042. return 0;
  4043. }
  4044. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  4045. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  4046. if (rv == FETCH_ABORT)
  4047. return FETCH_ABORT;
  4048. if (rv < 0)
  4049. return -1;
  4050. len = (unsigned int)rv;
  4051. if (len == 0) {
  4052. s_copy(err, "empty image", errcap);
  4053. return -1;
  4054. }
  4055. *out = image_file_buf;
  4056. *outlen = len;
  4057. return 0;
  4058. }
  4059. /* Remote stylesheets are immutable enough for the current boot: keep
  4060. * successful responses under /share so a reload, a second visit or a fresh
  4061. * browser launch does not fetch the same five sheets over the network again.
  4062. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  4063. static int css_cache_count;
  4064. static unsigned int css_cache_hash(const char *s)
  4065. {
  4066. unsigned int h = 2166136261u;
  4067. while (*s) {
  4068. h ^= (unsigned char)*s++;
  4069. h *= 16777619u;
  4070. }
  4071. return h;
  4072. }
  4073. static void css_cache_path(const char *url, char *out, unsigned int cap)
  4074. {
  4075. unsigned int n = 0;
  4076. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  4077. s_append_dec(out, &n, css_cache_hash(url), cap);
  4078. }
  4079. static void css_cache_clear(void)
  4080. {
  4081. struct sys_dirent d;
  4082. char path[96];
  4083. for (;;) {
  4084. int i, found = 0;
  4085. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4086. (int)&d) == 1; i++) {
  4087. unsigned int n = 0;
  4088. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  4089. continue;
  4090. s_append(path, &n, "/share/", sizeof(path));
  4091. s_append(path, &n, d.name, sizeof(path));
  4092. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  4093. return;
  4094. found = 1;
  4095. break;
  4096. }
  4097. if (!found)
  4098. break;
  4099. }
  4100. css_cache_count = 0;
  4101. }
  4102. static void css_cache_init(void)
  4103. {
  4104. struct sys_dirent d;
  4105. int i, count = 0;
  4106. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4107. (int)&d) == 1; i++)
  4108. if (starts_with(d.name, CSS_CACHE_PREFIX))
  4109. count++;
  4110. if (count >= CSS_CACHE_MAX) {
  4111. css_cache_clear();
  4112. return;
  4113. }
  4114. css_cache_count = count;
  4115. }
  4116. static int css_cache_get(const char *url, unsigned char **out,
  4117. unsigned int *outlen)
  4118. {
  4119. char path[96];
  4120. int rn;
  4121. css_cache_path(url, path, sizeof(path));
  4122. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  4123. (int)CSS_CACHE_FILE_MAX);
  4124. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  4125. return 0;
  4126. *out = image_io_buf;
  4127. *outlen = (unsigned int)rn;
  4128. return 1;
  4129. }
  4130. static void css_cache_put(const char *url, const unsigned char *data,
  4131. unsigned int len)
  4132. {
  4133. char path[96];
  4134. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  4135. len >= CSS_CACHE_FILE_MAX)
  4136. return;
  4137. css_cache_path(url, path, sizeof(path));
  4138. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  4139. (int)len) >= 0)
  4140. css_cache_count++;
  4141. }
  4142. static int css_cache_has(const char *url)
  4143. {
  4144. char path[96];
  4145. struct sys_stat st;
  4146. css_cache_path(url, path, sizeof(path));
  4147. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  4148. st.size < CSS_CACHE_FILE_MAX;
  4149. }
  4150. /* Read one stylesheet into the shared static buffer. CSS is parsed
  4151. * immediately, so it does not need the page heap; this leaves the heap for
  4152. * the 2 MB page body, the rules and the scaled image bitmaps. */
  4153. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  4154. char *err, unsigned int errcap)
  4155. {
  4156. unsigned int len;
  4157. int tr = 0;
  4158. int rv;
  4159. *out = 0;
  4160. *outlen = 0;
  4161. if (url[0] == '/') {
  4162. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  4163. (int)BR_CSS_MAX);
  4164. if (rv < 0) {
  4165. s_copy(err, "stylesheet not found", errcap);
  4166. return -1;
  4167. }
  4168. *out = image_io_buf;
  4169. *outlen = (unsigned int)rv;
  4170. return 0;
  4171. }
  4172. if (css_cache_get(url, out, outlen))
  4173. return 0;
  4174. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  4175. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  4176. &fetch_meta, &tr, err, errcap);
  4177. if (rv == FETCH_ABORT)
  4178. return FETCH_ABORT;
  4179. if (rv < 0)
  4180. return -1;
  4181. len = (unsigned int)rv;
  4182. if (len == 0) {
  4183. s_copy(err, "empty stylesheet", errcap);
  4184. return -1;
  4185. }
  4186. *out = image_io_buf;
  4187. *outlen = len;
  4188. css_cache_put(url, image_io_buf, len);
  4189. return 0;
  4190. }
  4191. static void redraw_now(void);
  4192. static char error_page[1024];
  4193. static void show_error(const char *title, const char *detail)
  4194. {
  4195. char *page = error_page;
  4196. unsigned int n = 0;
  4197. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  4198. s_append(page, &n, title, sizeof(error_page));
  4199. s_append(page, &n, "</h2><p>", sizeof(error_page));
  4200. {
  4201. const char *p = detail;
  4202. while (*p && n + 1 < sizeof(error_page)) {
  4203. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  4204. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  4205. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  4206. else page[n++] = *p;
  4207. p++;
  4208. }
  4209. }
  4210. page[n] = '\0';
  4211. s_append(page, &n, "</p><p>", sizeof(error_page));
  4212. s_append(page, &n, page_url, sizeof(error_page));
  4213. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  4214. sizeof(error_page));
  4215. br_parse(&doc, page, n);
  4216. layout_valid = 0;
  4217. preload_active = 0;
  4218. preload_pending = 0;
  4219. preload_wait = 0;
  4220. fetch_workers_cancel_busy();
  4221. s_copy(page_title, title, sizeof(page_title));
  4222. page_loading = 0;
  4223. set_status(title, 1, 0);
  4224. ngui_invalidate(&ui);
  4225. }
  4226. static int decode_direct_image(const unsigned char *data, unsigned int len,
  4227. unsigned int node)
  4228. {
  4229. if (image_count >= BR_MAX_IMAGES)
  4230. return -1;
  4231. if (decode_image_data(data, len, &images[0], 0, 0, 0, 0) != 0)
  4232. return -1;
  4233. doc.nodes[node].img_index = 0;
  4234. image_count = 1;
  4235. return 0;
  4236. }
  4237. static int ancestor_is(unsigned int node, unsigned int tag)
  4238. {
  4239. unsigned int p = doc.nodes[node].parent;
  4240. while (p) {
  4241. if (doc.nodes[p].tag == tag)
  4242. return 1;
  4243. p = doc.nodes[p].parent;
  4244. }
  4245. return 0;
  4246. }
  4247. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  4248. * parallel but parsed in document order, so the cascade is unchanged. */
  4249. static int load_stylesheets(void)
  4250. {
  4251. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  4252. static unsigned char remote[BR_MAX_SHEETS];
  4253. struct fetch_worker *slot[BR_MAX_SHEETS];
  4254. unsigned int i, n = 0, next = 0, k;
  4255. char err[64];
  4256. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  4257. struct br_node *nd = &doc.nodes[i];
  4258. const char *rel, *href;
  4259. char url[BR_URL_MAX];
  4260. int dup = 0;
  4261. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  4262. continue;
  4263. rel = br_rel(&doc, i);
  4264. if (!contains_ci(rel, "stylesheet"))
  4265. continue;
  4266. href = br_href(&doc, i);
  4267. if (!href[0])
  4268. continue;
  4269. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  4270. continue;
  4271. for (k = 0; k < n; k++)
  4272. if (s_eq(urls[k], url)) {
  4273. dup = 1;
  4274. break;
  4275. }
  4276. if (dup)
  4277. continue;
  4278. s_copy(urls[n], url, BR_URL_MAX);
  4279. remote[n] = url[0] != '/' && !css_cache_has(url);
  4280. n++;
  4281. }
  4282. for (i = 0; i < BR_MAX_SHEETS; i++)
  4283. slot[i] = 0;
  4284. /* Start as many remote sheets as there are free workers. */
  4285. for (; next < n; next++) {
  4286. struct fetch_worker *w;
  4287. if (!remote[next])
  4288. continue;
  4289. w = fetch_worker_alloc();
  4290. if (!w)
  4291. break;
  4292. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  4293. err, sizeof(err)) != 0) {
  4294. fetch_worker_release(w);
  4295. remote[next] = 0;
  4296. continue;
  4297. }
  4298. slot[next] = w;
  4299. }
  4300. for (i = 0; i < n; i++) {
  4301. unsigned char *data = 0;
  4302. unsigned int len = 0;
  4303. int rv;
  4304. if (!remote[i]) {
  4305. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  4306. if (rv == FETCH_ABORT) {
  4307. fetch_workers_stop_all();
  4308. return FETCH_ABORT;
  4309. }
  4310. if (rv != 0 || !len)
  4311. continue;
  4312. } else {
  4313. struct fetch_worker *w = slot[i];
  4314. int tr = 0;
  4315. if (!w) {
  4316. w = fetch_worker_alloc();
  4317. if (!w) {
  4318. rv = -1;
  4319. goto css_failed;
  4320. }
  4321. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  4322. 0, 0, 0, 0, err,
  4323. sizeof(err)) != 0) {
  4324. fetch_worker_release(w);
  4325. remote[i] = 0;
  4326. if (i == next)
  4327. next++;
  4328. continue;
  4329. }
  4330. slot[i] = w;
  4331. if (i == next)
  4332. next++;
  4333. }
  4334. rv = fetch_worker_wait(w, err, sizeof(err));
  4335. if (rv == FETCH_ABORT) {
  4336. fetch_workers_stop_all();
  4337. return FETCH_ABORT;
  4338. }
  4339. if (rv == 0)
  4340. rv = fetch_worker_read_body(w, image_io_buf,
  4341. BR_CSS_MAX,
  4342. image_io_buf + BR_CSS_MAX,
  4343. BR_CSS_COMP_MAX, &tr,
  4344. err, sizeof(err));
  4345. else
  4346. rv = -1;
  4347. fetch_worker_release(w);
  4348. slot[i] = 0;
  4349. /* Refill the worker window before parsing this sheet. */
  4350. for (; next < n; next++) {
  4351. struct fetch_worker *nw;
  4352. if (!remote[next])
  4353. continue;
  4354. nw = fetch_worker_alloc();
  4355. if (!nw)
  4356. break;
  4357. if (fetch_worker_submit(nw, urls[next],
  4358. BR_CSS_MAX, 0, 0, 0, 0,
  4359. err, sizeof(err)) != 0) {
  4360. fetch_worker_release(nw);
  4361. remote[next] = 0;
  4362. continue;
  4363. }
  4364. slot[next] = nw;
  4365. }
  4366. css_failed:
  4367. if (rv <= 0) {
  4368. /* One synchronous retry: a dropped sheet leaves the
  4369. * whole page unstyled (seen intermittently on
  4370. * arstechnica's CDN). */
  4371. u_puts("[css] retry ");
  4372. u_puts(urls[i]);
  4373. u_puts(": ");
  4374. u_puts(err[0] ? err : "no worker/empty body");
  4375. u_putc('\n');
  4376. err[0] = '\0';
  4377. rv = fetch_css(urls[i], &data, &len, err,
  4378. sizeof(err));
  4379. if (rv == FETCH_ABORT) {
  4380. fetch_workers_stop_all();
  4381. return FETCH_ABORT;
  4382. }
  4383. if (rv != 0 || !len) {
  4384. u_puts("[css] failed: ");
  4385. u_puts(err);
  4386. u_putc('\n');
  4387. continue;
  4388. }
  4389. } else {
  4390. len = (unsigned int)rv;
  4391. data = image_io_buf;
  4392. css_cache_put(urls[i], data, len);
  4393. }
  4394. }
  4395. if (len) {
  4396. br_set_font_base(urls[i]);
  4397. br_parse_css_text(&doc, (const char *)data, len);
  4398. }
  4399. }
  4400. br_set_font_base(page_url);
  4401. br_parse_inline_css(&doc);
  4402. load_font_faces();
  4403. br_reset_styles(&doc);
  4404. layout_valid = 0;
  4405. return 0;
  4406. }
  4407. static void preload_begin(void)
  4408. {
  4409. preload_active = 1;
  4410. preload_pending = 0;
  4411. preload_wait = 1;
  4412. preload_max_jobs = FETCH_WORKERS;
  4413. preload_node = 0;
  4414. preload_loaded = 0;
  4415. preload_scroll = 0;
  4416. img_stat_start = u_ticks_ms();
  4417. img_stat_wall = 0;
  4418. img_stat_net = img_stat_open = img_stat_first = 0;
  4419. img_stat_io = img_stat_dec = img_stat_scale = 0;
  4420. img_stat_paint = img_stat_reflow = 0;
  4421. img_stat_bytes = 0;
  4422. img_stat_n = 0;
  4423. img_stat_log_len = 0;
  4424. if (img_stat_log[0])
  4425. img_stat_log[0] = '\0';
  4426. img_repaint_ms = 0;
  4427. img_repaint_pending = 0;
  4428. }
  4429. /* Styles are computed top-down during layout, but images inside a hidden
  4430. * menu/carousel are never visited and keep img_top == 0. Without this check
  4431. * the preloader walks the DOM in node order and spends the whole image
  4432. * budget on logos and off-canvas thumbnails the reader cannot see. */
  4433. static struct br_style base_style(void);
  4434. static int node_hidden(unsigned int node)
  4435. {
  4436. unsigned int path[32], n = 0, p = node, i;
  4437. struct br_style st, parent;
  4438. while (p && n < sizeof(path) / sizeof(path[0])) {
  4439. path[n++] = p;
  4440. p = doc.nodes[p].parent;
  4441. }
  4442. /* Node 0 is the <html> element when the page starts with one: it
  4443. * is an ancestor too. Styles are cached per node, so the chain
  4444. * must start from the same base as style_for_node(); seeding it
  4445. * with a zeroed style left <body> cached with black text and no
  4446. * line-height once an image job ran (docs.cloudron.io). */
  4447. if (!p && n && n < sizeof(path) / sizeof(path[0]) &&
  4448. doc.nodes[0].type == BR_NODE_ELEM &&
  4449. doc.nodes[0].tag == BR_TAG_HTML &&
  4450. !(doc.nodes[path[n - 1]].flags & BR_NODE_DETACHED))
  4451. path[n++] = 0;
  4452. parent = base_style();
  4453. for (i = n; i > 0; i--) {
  4454. br_style_for(&doc, path[i - 1], &parent, &st);
  4455. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  4456. st.opacity_hidden)
  4457. return 1;
  4458. parent = st;
  4459. }
  4460. return 0;
  4461. }
  4462. static struct br_style base_style(void);
  4463. static int style_width_px(const struct br_style *st, int base);
  4464. static int style_height_px(const struct br_style *st, int base);
  4465. static void style_for_node(unsigned int node, struct br_style *out)
  4466. {
  4467. unsigned int p = doc.nodes[node].parent;
  4468. struct br_style parent;
  4469. /* Parent index 0 is ambiguous: it is the <html> element when the page
  4470. * starts with one (see root_style()), but also the parent field of a
  4471. * detached subtree root. */
  4472. if (p || (node != 0 && doc.nodes[0].type == BR_NODE_ELEM &&
  4473. doc.nodes[0].tag == BR_TAG_HTML &&
  4474. !(doc.nodes[node].flags & BR_NODE_DETACHED))) {
  4475. style_for_node(p, &parent);
  4476. br_style_for(&doc, node, &parent, out);
  4477. } else {
  4478. parent = base_style();
  4479. br_style_for(&doc, node, &parent, out);
  4480. }
  4481. }
  4482. /* ---- parallel image preloading ---- *
  4483. *
  4484. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  4485. * preload_step() only starts jobs and harvests completed ones; the browser
  4486. * main loop keeps drawing between calls, instead of blocking on one fetch.
  4487. */
  4488. static int preload_active_jobs(void)
  4489. {
  4490. int i, n = 0;
  4491. for (i = 0; i < FETCH_WORKERS; i++)
  4492. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  4493. n++;
  4494. return n;
  4495. }
  4496. static void preload_job_error(struct fetch_worker *w)
  4497. {
  4498. if (w->node < doc.nnode) {
  4499. if (w->bg)
  4500. doc.nodes[w->node].bg_img_index = -2;
  4501. else
  4502. doc.nodes[w->node].img_index = -2;
  4503. image_repaint();
  4504. }
  4505. }
  4506. /* Is the image's box anywhere near the visible page? A decode below the
  4507. * fold changes the layout (scroll extent) but not a single on-screen pixel,
  4508. * so it does not need a repaint. top/h come from the last layout; treat an
  4509. * unknown box as visible to stay safe. */
  4510. static int image_preload_visible(unsigned int node, int bg)
  4511. {
  4512. int top, h, scroll;
  4513. if (node >= BR_MAX_NODES || node >= doc.nnode || page_rect.h <= 0)
  4514. return 1;
  4515. if (bg) {
  4516. top = (int)block_top[node];
  4517. h = (int)block_h[node];
  4518. } else {
  4519. top = (int)img_top[node];
  4520. h = (int)img_h[node];
  4521. }
  4522. if (!top && !h)
  4523. return 1;
  4524. scroll = (int)page_scroll.offset;
  4525. if (top > scroll + page_rect.h + 160)
  4526. return 0;
  4527. if (top + h + 160 < scroll)
  4528. return 0;
  4529. return 1;
  4530. }
  4531. /* Upper bounds for the bitmap an <img> will paint. Zero means "unbounded";
  4532. * decode_image_data applies one scale to both axes so the aspect ratio is
  4533. * preserved. This is what keeps a 1200x800 photo that CSS paints at 400 px
  4534. * from being decoded and box-filtered to the 1000 px layout cap first. */
  4535. static void image_fit_size(unsigned int node, int *out_w, int *out_h)
  4536. {
  4537. struct br_style st;
  4538. struct br_node *nd;
  4539. unsigned int p;
  4540. int cw, w = 0, h = 0;
  4541. *out_w = *out_h = 0;
  4542. if (node >= doc.nnode)
  4543. return;
  4544. nd = &doc.nodes[node];
  4545. style_for_node(node, &st);
  4546. cw = page_rect.w > 24 ? page_rect.w - 24 : 0;
  4547. p = doc.nodes[node].parent;
  4548. if (p && p < BR_MAX_NODES && layout_boxes[p].valid &&
  4549. layout_boxes[p].w > 0 && layout_boxes[p].w < cw)
  4550. cw = layout_boxes[p].w;
  4551. if (st.width_kind)
  4552. w = style_width_px(&st, cw);
  4553. else if (nd->width_attr)
  4554. w = nd->width_pct ? cw * (int)nd->width_attr / 100 :
  4555. (int)nd->width_attr;
  4556. if (st.height_kind)
  4557. h = style_height_px(&st, cw);
  4558. else if (nd->height_attr)
  4559. h = nd->height_pct ? cw * (int)nd->height_attr / 100 :
  4560. (int)nd->height_attr;
  4561. if (st.max_width_kind) {
  4562. int mw = st.max_width_kind == 3 ?
  4563. cw * st.max_width_calc_pct / 100 +
  4564. st.max_width_calc_px :
  4565. st.max_width_kind == 2 ?
  4566. cw * (int)st.max_width / 100 :
  4567. (int)st.max_width;
  4568. if (mw > 0 && (w == 0 || w > mw))
  4569. w = mw;
  4570. }
  4571. if (st.max_height_kind) {
  4572. int mh = st.max_height_kind == 3 ?
  4573. cw * st.max_height_calc_pct / 100 +
  4574. st.max_height_calc_px :
  4575. st.max_height_kind == 2 ?
  4576. cw * (int)st.max_height / 100 :
  4577. (int)st.max_height;
  4578. if (mh > 0 && (h == 0 || h > mh))
  4579. h = mh;
  4580. }
  4581. if (w > BR_IMG_LAYOUT_W)
  4582. w = BR_IMG_LAYOUT_W;
  4583. if (h > 4096)
  4584. h = 4096;
  4585. if (w < 0)
  4586. w = 0;
  4587. if (h < 0)
  4588. h = 0;
  4589. *out_w = w;
  4590. *out_h = h;
  4591. }
  4592. static void preload_accept_image(unsigned int node, int bg, const char *url)
  4593. {
  4594. /* An <img> bitmap only depends on its URL, so the next <img> with the
  4595. * same source reuses it (heise repeats one comment icon 85 times).
  4596. * Backgrounds are scaled to their box and are not shared. */
  4597. images[image_count].url_hash =
  4598. !bg && url ? script_cache_hash(url) | 1u : 0;
  4599. if (bg)
  4600. doc.nodes[node].bg_img_index = (short)image_count;
  4601. else
  4602. doc.nodes[node].img_index = (short)image_count;
  4603. image_count++;
  4604. preload_loaded++;
  4605. /* A background bitmap never changes its box, so keep the (expensive)
  4606. * measured layout and only repaint the pixels. */
  4607. if (bg)
  4608. page_cache_valid = 0;
  4609. else
  4610. layout_valid = 0;
  4611. if (image_preload_visible(node, bg))
  4612. image_repaint();
  4613. }
  4614. /* Install a bitmap decoded by the fetch helper. The helper already applied
  4615. * the display bounds (and the JPEG reduced IDCT), so this is a read + copy
  4616. * on the UI thread instead of a decode. */
  4617. static int preload_store_helper(unsigned int node, int bg,
  4618. unsigned char *px, unsigned int pxlen,
  4619. unsigned int dw, unsigned int dh,
  4620. int alpha, unsigned int nw, unsigned int nh,
  4621. const char *url)
  4622. {
  4623. struct br_image *bi;
  4624. unsigned int npx;
  4625. if (image_count >= BR_MAX_IMAGES || !px || !dw || !dh ||
  4626. dw > 4096 || dh > 4096) {
  4627. free(px);
  4628. return -1;
  4629. }
  4630. npx = dw * dh;
  4631. if (image_pixels + npx > BR_IMG_PIXEL_BUDGET ||
  4632. pxlen < npx * 2u + (alpha ? npx : 0)) {
  4633. free(px);
  4634. return -1;
  4635. }
  4636. bi = &images[image_count];
  4637. bi->img.format = 0;
  4638. bi->img.w = dw;
  4639. bi->img.h = dh;
  4640. bi->img.px = (unsigned short *)px;
  4641. bi->img.alpha = alpha ? px + npx * 2u : 0;
  4642. bi->img.flags = 0;
  4643. bi->native_w = nw ? (int)nw : (int)dw;
  4644. bi->native_h = nh ? (int)nh : (int)dh;
  4645. bi->state = 1;
  4646. image_pixels += npx;
  4647. preload_accept_image(node, bg, url);
  4648. return 0;
  4649. }
  4650. static void preload_decode(unsigned int node, int bg,
  4651. const unsigned char *data, unsigned int len,
  4652. const char *url)
  4653. {
  4654. int fit_w = 0, fit_h = 0;
  4655. if (image_count >= BR_MAX_IMAGES) {
  4656. if (bg)
  4657. doc.nodes[node].bg_img_index = -2;
  4658. else
  4659. doc.nodes[node].img_index = -2;
  4660. return;
  4661. }
  4662. if (!bg)
  4663. image_fit_size(node, &fit_w, &fit_h);
  4664. if (decode_image_data(data, len, &images[image_count],
  4665. bg && node < BR_MAX_NODES &&
  4666. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  4667. bg && node < BR_MAX_NODES &&
  4668. layout_boxes[node].valid ? layout_boxes[node].h : 0,
  4669. fit_w, fit_h) == 0) {
  4670. preload_accept_image(node, bg, url);
  4671. } else {
  4672. if (bg)
  4673. doc.nodes[node].bg_img_index = -2;
  4674. else
  4675. doc.nodes[node].img_index = -2;
  4676. layout_valid = 0;
  4677. }
  4678. if (image_preload_visible(node, bg))
  4679. image_repaint();
  4680. }
  4681. /* ---- data: URLs ----
  4682. *
  4683. * `data:[<type>][;base64],<payload>` decoded to bytes from the page heap
  4684. * (the caller frees them). The payload is percent-decoded, then base64-
  4685. * decoded when the header says so. Infima's menu chevron and many icon
  4686. * fonts' fallbacks are inline SVGs written this way. */
  4687. static int b64_val(int c)
  4688. {
  4689. if (c >= 'A' && c <= 'Z') return c - 'A';
  4690. if (c >= 'a' && c <= 'z') return c - 'a' + 26;
  4691. if (c >= '0' && c <= '9') return c - '0' + 52;
  4692. if (c == '+' || c == '-') return 62;
  4693. if (c == '/' || c == '_') return 63;
  4694. return -1;
  4695. }
  4696. static int hex_val(int c)
  4697. {
  4698. if (c >= '0' && c <= '9') return c - '0';
  4699. c |= 32;
  4700. if (c >= 'a' && c <= 'f') return c - 'a' + 10;
  4701. return -1;
  4702. }
  4703. static int data_url_decode(const char *url, unsigned char **out,
  4704. unsigned int *out_len)
  4705. {
  4706. const char *comma, *p;
  4707. unsigned int n = 0, len, i;
  4708. unsigned char *buf;
  4709. int base64 = 0;
  4710. *out = 0;
  4711. *out_len = 0;
  4712. if (!starts_with(url, "data:"))
  4713. return -1;
  4714. comma = url + 5;
  4715. while (*comma && *comma != ',')
  4716. comma++;
  4717. if (!*comma)
  4718. return -1;
  4719. for (p = url + 5; p + 7 <= comma; p++)
  4720. if (!strncmp(p, ";base64", 7))
  4721. base64 = 1;
  4722. len = s_len(comma + 1);
  4723. buf = (unsigned char *)malloc(len + 1);
  4724. if (!buf)
  4725. return -1;
  4726. for (i = 0, p = comma + 1; i < len; i++) {
  4727. int c = (unsigned char)p[i];
  4728. if (c == '%' && i + 2 < len &&
  4729. hex_val(p[i + 1]) >= 0 && hex_val(p[i + 2]) >= 0) {
  4730. c = hex_val(p[i + 1]) * 16 + hex_val(p[i + 2]);
  4731. i += 2;
  4732. }
  4733. buf[n++] = (unsigned char)c;
  4734. }
  4735. if (base64) {
  4736. unsigned int acc = 0, o = 0;
  4737. int bits = 0;
  4738. for (i = 0; i < n; i++) {
  4739. int v = b64_val(buf[i]);
  4740. if (v < 0)
  4741. continue; /* padding, whitespace */
  4742. acc = (acc << 6) | (unsigned int)v;
  4743. bits += 6;
  4744. if (bits >= 8) {
  4745. bits -= 8;
  4746. buf[o++] = (unsigned char)(acc >> bits);
  4747. }
  4748. }
  4749. n = o;
  4750. }
  4751. buf[n] = 0;
  4752. *out = buf;
  4753. *out_len = n;
  4754. return 0;
  4755. }
  4756. static unsigned int data_img_key(const char *url, int w, int h)
  4757. {
  4758. return (script_cache_hash(url) ^ ((unsigned int)w * 2654435761u) ^
  4759. ((unsigned int)h * 40503u)) | 1u;
  4760. }
  4761. /* The image index of a data: URL decoded for a w x h box (an SVG is
  4762. * rasterized at that size), decoding it on first use; -1 on failure.
  4763. * Decoded bitmaps are found again through url_hash, which is distinct
  4764. * from the <img> sharing hash because it mixes in the size. */
  4765. static int data_url_image(const char *url, int w, int h)
  4766. {
  4767. unsigned int key, len;
  4768. unsigned char *data;
  4769. int i;
  4770. if (!starts_with(url, "data:") || w <= 0 || h <= 0)
  4771. return -1;
  4772. key = data_img_key(url, w, h);
  4773. for (i = 0; i < image_count; i++)
  4774. if (images[i].state == 1 && images[i].url_hash == key)
  4775. return i;
  4776. for (i = 0; i < data_img_nfail; i++)
  4777. if (data_img_fail[i] == key)
  4778. return -1;
  4779. if (image_count < BR_MAX_IMAGES &&
  4780. data_url_decode(url, &data, &len) == 0) {
  4781. int r = decode_image_data(data, len, &images[image_count],
  4782. w, h, w, h);
  4783. free(data);
  4784. if (r == 0) {
  4785. images[image_count].url_hash = key;
  4786. return image_count++;
  4787. }
  4788. }
  4789. if (data_img_nfail < DATA_IMG_FAIL_MAX)
  4790. data_img_fail[data_img_nfail++] = key;
  4791. return -1;
  4792. }
  4793. /* A local file image bypasses the helpers: count its decode so a page opened
  4794. * from /share or /data still produces the same timing breakdown. */
  4795. static void img_stat_local(int before, unsigned int bytes, unsigned int io_ms)
  4796. {
  4797. img_stat_n++;
  4798. img_stat_bytes += bytes;
  4799. img_stat_io += io_ms;
  4800. if (image_count > before) {
  4801. struct br_image *bi = &images[image_count - 1];
  4802. img_stat_dec += img_last_dec_ms;
  4803. img_stat_scale += img_last_scale_ms;
  4804. if (img_stat_log_len + 100 < sizeof(img_stat_log)) {
  4805. unsigned int n = img_stat_log_len;
  4806. s_append(img_stat_log, &n, "local ", sizeof(img_stat_log));
  4807. s_append_dec(img_stat_log, &n, bytes,
  4808. sizeof(img_stat_log));
  4809. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4810. s_append_dec(img_stat_log, &n, img_last_dec_ms,
  4811. sizeof(img_stat_log));
  4812. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4813. s_append_dec(img_stat_log, &n, img_last_scale_ms,
  4814. sizeof(img_stat_log));
  4815. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4816. s_append_dec(img_stat_log, &n,
  4817. (unsigned int)bi->native_w,
  4818. sizeof(img_stat_log));
  4819. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4820. s_append_dec(img_stat_log, &n,
  4821. (unsigned int)bi->native_h,
  4822. sizeof(img_stat_log));
  4823. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4824. s_append_dec(img_stat_log, &n, bi->img.w,
  4825. sizeof(img_stat_log));
  4826. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4827. s_append_dec(img_stat_log, &n, bi->img.h,
  4828. sizeof(img_stat_log));
  4829. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4830. s_append_dec(img_stat_log, &n,
  4831. bi->img.alpha ? 1u : 0u,
  4832. sizeof(img_stat_log));
  4833. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4834. img_stat_log_len = n;
  4835. }
  4836. }
  4837. }
  4838. /* Harvest one completed worker. Returns 1 when a job was finished. */
  4839. static int preload_finish_worker(struct fetch_worker *w)
  4840. {
  4841. char err[64];
  4842. int rv, tr = 0;
  4843. unsigned int t0, io_ms;
  4844. int before;
  4845. int used_px = 0;
  4846. rv = fetch_worker_poll(w, err, sizeof(err));
  4847. if (rv < 0) {
  4848. /* A helper from an older pack does not understand the image
  4849. * decode request; retry once without it and decode in-process. */
  4850. if (w->image_job && w->dec_w && !w->dec_retried &&
  4851. fetch_worker_submit_req(w, w->url, BR_IMG_FILE_MAX,
  4852. 0, 0, 0, 0, w->node, w->bg,
  4853. 0, 0, err, sizeof(err)) == 0) {
  4854. w->image_job = 1;
  4855. w->dec_retried = 1;
  4856. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4857. return 0;
  4858. }
  4859. preload_job_error(w);
  4860. if (img_stat_log_len + 64 < sizeof(img_stat_log)) {
  4861. unsigned int n = img_stat_log_len;
  4862. char u[48];
  4863. s_copy(u, w->url, sizeof(u));
  4864. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4865. s_append(img_stat_log, &n, " error\n",
  4866. sizeof(img_stat_log));
  4867. img_stat_log_len = n;
  4868. }
  4869. img_stat_n++;
  4870. fetch_worker_release(w);
  4871. return 1;
  4872. }
  4873. if (rv == 0)
  4874. return 0;
  4875. t0 = u_ticks_ms();
  4876. rv = -1;
  4877. before = image_count;
  4878. if (w->m.px_len && !w->m.dec_err && w->m.dw && w->m.dh &&
  4879. w->m.px_len <= 8u * 1024u * 1024u) {
  4880. unsigned char *px = (unsigned char *)malloc(w->m.px_len);
  4881. int pr = -1;
  4882. if (px)
  4883. pr = u_syscall3(SYS_READ_FILE, (int)w->px, (int)px,
  4884. (int)w->m.px_len);
  4885. if (pr == (int)w->m.px_len) {
  4886. if (preload_store_helper(w->node, w->bg, px,
  4887. w->m.px_len, w->m.dw,
  4888. w->m.dh, (int)w->m.alpha,
  4889. w->m.nw, w->m.nh,
  4890. w->url) == 0) {
  4891. rv = (int)w->m.len;
  4892. img_last_dec_ms = w->m.dec_ms;
  4893. img_last_scale_ms = 0;
  4894. used_px = 1;
  4895. } else {
  4896. px = 0; /* the helper freed it */
  4897. }
  4898. }
  4899. if (px && !(pr == (int)w->m.px_len))
  4900. free(px);
  4901. }
  4902. io_ms = u_ticks_ms() - t0;
  4903. if (rv < 0) {
  4904. t0 = u_ticks_ms();
  4905. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  4906. image_comp_buf, BR_IMG_FILE_MAX,
  4907. &tr, err, sizeof(err));
  4908. io_ms += u_ticks_ms() - t0;
  4909. before = image_count;
  4910. if (rv >= 0)
  4911. preload_decode(w->node, w->bg, image_file_buf,
  4912. (unsigned int)rv, w->url);
  4913. else
  4914. preload_job_error(w);
  4915. }
  4916. img_stat_n++;
  4917. img_stat_net += w->m.total_ms;
  4918. img_stat_open += w->m.open_ms;
  4919. img_stat_first += w->m.first_ms;
  4920. img_stat_io += io_ms;
  4921. img_stat_bytes += rv > 0 ? (unsigned int)rv : 0;
  4922. img_stat_dec += w->m.dec_ms;
  4923. if (rv >= 0 && !used_px) {
  4924. img_stat_dec += img_last_dec_ms;
  4925. img_stat_scale += img_last_scale_ms;
  4926. }
  4927. if (img_stat_log_len + 160 < sizeof(img_stat_log)) {
  4928. unsigned int n = img_stat_log_len;
  4929. char u[48];
  4930. s_copy(u, w->url, sizeof(u));
  4931. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4932. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4933. s_append_dec(img_stat_log, &n,
  4934. rv > 0 ? (unsigned int)rv : 0,
  4935. sizeof(img_stat_log));
  4936. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4937. s_append_dec(img_stat_log, &n, w->m.open_ms,
  4938. sizeof(img_stat_log));
  4939. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4940. s_append_dec(img_stat_log, &n, w->m.first_ms,
  4941. sizeof(img_stat_log));
  4942. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4943. s_append_dec(img_stat_log, &n, w->m.total_ms,
  4944. sizeof(img_stat_log));
  4945. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4946. s_append_dec(img_stat_log, &n, io_ms, sizeof(img_stat_log));
  4947. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4948. s_append_dec(img_stat_log, &n,
  4949. rv >= 0 ? img_last_dec_ms : 0,
  4950. sizeof(img_stat_log));
  4951. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4952. s_append_dec(img_stat_log, &n,
  4953. rv >= 0 ? img_last_scale_ms : 0,
  4954. sizeof(img_stat_log));
  4955. if (image_count > before) {
  4956. struct br_image *bi = &images[image_count - 1];
  4957. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4958. s_append_dec(img_stat_log, &n,
  4959. (unsigned int)bi->native_w,
  4960. sizeof(img_stat_log));
  4961. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4962. s_append_dec(img_stat_log, &n,
  4963. (unsigned int)bi->native_h,
  4964. sizeof(img_stat_log));
  4965. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4966. s_append_dec(img_stat_log, &n, bi->img.w,
  4967. sizeof(img_stat_log));
  4968. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4969. s_append_dec(img_stat_log, &n, bi->img.h,
  4970. sizeof(img_stat_log));
  4971. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4972. s_append_dec(img_stat_log, &n,
  4973. bi->img.alpha ? 1u : 0u,
  4974. sizeof(img_stat_log));
  4975. }
  4976. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4977. img_stat_log_len = n;
  4978. }
  4979. fetch_worker_release(w);
  4980. return 1;
  4981. }
  4982. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  4983. * the number of jobs started. */
  4984. static int preload_fill_jobs(void)
  4985. {
  4986. int started = 0;
  4987. char err[64];
  4988. while (preload_active && preload_node < doc.nnode) {
  4989. unsigned int i = preload_node;
  4990. struct br_node *nd = &doc.nodes[i];
  4991. const char *src;
  4992. char url[BR_URL_MAX];
  4993. struct fetch_worker *w;
  4994. if (preload_active_jobs() >= preload_max_jobs)
  4995. break;
  4996. if (nd->type != BR_NODE_ELEM) {
  4997. preload_node++;
  4998. continue;
  4999. }
  5000. if (nd->tag != BR_TAG_IMG) {
  5001. if (nd->bg_img_index == -1) {
  5002. struct br_style bs;
  5003. style_for_node(i, &bs);
  5004. if (bs.display != BR_DISPLAY_NONE &&
  5005. !bs.vis_hidden && bs.bg_image) {
  5006. const char *bsrc =
  5007. br_bg_image_url(bs.bg_image - 1);
  5008. /* Lazy like <img>: a background box
  5009. * below the viewport (or not laid
  5010. * out yet) waits for the next scan. */
  5011. if (bsrc[0] &&
  5012. (!layout_boxes[i].valid ||
  5013. block_top[i] >
  5014. (unsigned int)(page_scroll.offset +
  5015. page_rect.h + 160))) {
  5016. preload_pending = 1;
  5017. preload_node++;
  5018. continue;
  5019. }
  5020. if (starts_with(bsrc, "data:")) {
  5021. /* Inline image: decode now,
  5022. * no fetch helper. */
  5023. unsigned char *data;
  5024. unsigned int len;
  5025. preload_node = i + 1;
  5026. if (data_url_decode(bsrc, &data,
  5027. &len) == 0) {
  5028. preload_decode(i, 1, data,
  5029. len, 0);
  5030. free(data);
  5031. } else {
  5032. nd->bg_img_index = -2;
  5033. }
  5034. continue;
  5035. }
  5036. if (bsrc[0] &&
  5037. resolve_link(page_url, bsrc, url,
  5038. sizeof(url)) == 0) {
  5039. if (image_count +
  5040. preload_active_jobs() >=
  5041. BR_MAX_IMAGES) {
  5042. preload_node = doc.nnode;
  5043. break;
  5044. }
  5045. if (url[0] == '/') {
  5046. unsigned char *data = 0;
  5047. unsigned int len = 0;
  5048. unsigned int t0;
  5049. int before;
  5050. preload_node = i + 1;
  5051. before = image_count;
  5052. t0 = u_ticks_ms();
  5053. if (fetch_image(url,
  5054. BR_IMG_FILE_MAX,
  5055. &data, &len,
  5056. err,
  5057. sizeof(err)) == 0) {
  5058. preload_decode(i, 1, data, len, 0);
  5059. img_stat_local(before, len,
  5060. u_ticks_ms() - t0);
  5061. } else {
  5062. nd->bg_img_index = -2;
  5063. }
  5064. continue;
  5065. }
  5066. w = fetch_worker_alloc();
  5067. if (!w)
  5068. return started;
  5069. preload_node = i + 1;
  5070. if (fetch_worker_submit(w, url,
  5071. BR_IMG_FILE_MAX,
  5072. 0, 0, i, 1,
  5073. err,
  5074. sizeof(err)) != 0) {
  5075. nd->bg_img_index = -2;
  5076. fetch_worker_release(w);
  5077. continue;
  5078. }
  5079. w->image_job = 1;
  5080. w->deadline = u_ticks_ms() +
  5081. BR_IMG_JOB_TIMEOUT_MS;
  5082. /* in flight: rescans skip it */
  5083. nd->bg_img_index = -3;
  5084. started++;
  5085. continue;
  5086. }
  5087. }
  5088. nd->bg_img_index = -2;
  5089. }
  5090. preload_node++;
  5091. continue;
  5092. }
  5093. if (nd->img_index != -1) {
  5094. preload_node++;
  5095. continue;
  5096. }
  5097. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  5098. preload_node++;
  5099. continue;
  5100. }
  5101. src = br_src(&doc, i);
  5102. if (starts_with(src, "data:")) {
  5103. unsigned char *data;
  5104. unsigned int len;
  5105. preload_node = i + 1;
  5106. if (data_url_decode(src, &data, &len) == 0) {
  5107. preload_decode(i, 0, data, len, 0);
  5108. free(data);
  5109. } else {
  5110. doc.nodes[i].img_index = -2;
  5111. }
  5112. continue;
  5113. }
  5114. if (!src[0]) {
  5115. preload_node++;
  5116. continue;
  5117. }
  5118. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  5119. preload_node++;
  5120. continue;
  5121. }
  5122. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  5123. preload_node = doc.nnode;
  5124. break;
  5125. }
  5126. /* Do not stop at the first below-fold image: DOM order is
  5127. * not visual order, and a footer/ad image early in the DOM
  5128. * used to hide every later article image from the loader. */
  5129. if (img_top[i] >
  5130. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  5131. preload_pending = 1;
  5132. preload_node++;
  5133. continue;
  5134. }
  5135. {
  5136. unsigned int uh = script_cache_hash(url) | 1u;
  5137. int k;
  5138. for (k = 0; k < image_count; k++)
  5139. if (images[k].state == 1 &&
  5140. images[k].url_hash == uh)
  5141. break;
  5142. if (k < image_count) {
  5143. nd->img_index = (short)k;
  5144. layout_valid = 0;
  5145. preload_node = i + 1;
  5146. image_repaint();
  5147. continue;
  5148. }
  5149. }
  5150. if (url[0] == '/') {
  5151. unsigned char *data = 0;
  5152. unsigned int len = 0;
  5153. unsigned int t0;
  5154. int before;
  5155. preload_node = i + 1;
  5156. before = image_count;
  5157. t0 = u_ticks_ms();
  5158. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  5159. err, sizeof(err)) == 0) {
  5160. preload_decode(i, 0, data, len, url);
  5161. img_stat_local(before, len, u_ticks_ms() - t0);
  5162. } else {
  5163. nd->img_index = -2;
  5164. }
  5165. continue;
  5166. }
  5167. w = fetch_worker_alloc();
  5168. if (!w)
  5169. return started;
  5170. preload_node = i + 1;
  5171. {
  5172. char msg[64];
  5173. unsigned int n = 0;
  5174. s_append(msg, &n, "Loading images ", sizeof(msg));
  5175. s_append_dec(msg, &n,
  5176. (unsigned int)preload_loaded + 1,
  5177. sizeof(msg));
  5178. s_append(msg, &n, "...", sizeof(msg));
  5179. set_status_quiet(msg);
  5180. image_repaint();
  5181. }
  5182. {
  5183. int fit_w = 0, fit_h = 0;
  5184. image_fit_size(i, &fit_w, &fit_h);
  5185. if (!fit_w)
  5186. fit_w = BR_IMG_LAYOUT_W;
  5187. if (fetch_worker_submit_image(w, url, BR_IMG_FILE_MAX,
  5188. i, 0,
  5189. (unsigned int)fit_w,
  5190. (unsigned int)fit_h,
  5191. err, sizeof(err)) != 0) {
  5192. nd->img_index = -2;
  5193. fetch_worker_release(w);
  5194. continue;
  5195. }
  5196. }
  5197. w->image_job = 1;
  5198. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  5199. nd->img_index = -3; /* in flight: rescans skip it */
  5200. started++;
  5201. }
  5202. return started;
  5203. }
  5204. /* Report where the image batch spent its time: status bar for the headline,
  5205. * /share/IMGSTAT for the per-image breakdown (cat it from a terminal). */
  5206. static void img_stats_report(void)
  5207. {
  5208. char msg[80];
  5209. static char out[BR_IMG_STAT_LOG + 512];
  5210. unsigned int n = 0, o = 0;
  5211. if (!img_stat_n)
  5212. return;
  5213. img_stat_wall = img_stat_start ?
  5214. u_ticks_ms() - img_stat_start : 1;
  5215. if (!img_stat_wall)
  5216. img_stat_wall = 1;
  5217. /* Compact on-screen form; /share/IMGSTAT has the full breakdown. */
  5218. s_append(msg, &n, "img ", sizeof(msg));
  5219. s_append_dec(msg, &n, (unsigned int)img_stat_n, sizeof(msg));
  5220. s_append(msg, &n, " ", sizeof(msg));
  5221. s_append_dec(msg, &n, img_stat_wall, sizeof(msg));
  5222. s_append(msg, &n, "ms net ", sizeof(msg));
  5223. s_append_dec(msg, &n, img_stat_net, sizeof(msg));
  5224. s_append(msg, &n, " dec ", sizeof(msg));
  5225. s_append_dec(msg, &n, img_stat_dec, sizeof(msg));
  5226. s_append(msg, &n, " sc ", sizeof(msg));
  5227. s_append_dec(msg, &n, img_stat_scale, sizeof(msg));
  5228. s_append(msg, &n, " paint ", sizeof(msg));
  5229. s_append_dec(msg, &n, img_stat_paint, sizeof(msg));
  5230. /* Keep the page's phase breakdown and append the image summary when
  5231. * it fits; never hide a JS error or a truncation notice. */
  5232. if (!post_status_error && !contains_ci(post_status_text, "truncated")) {
  5233. unsigned int plen = s_len(post_status_text);
  5234. if (!plen) {
  5235. s_copy(post_status_text, msg, sizeof(post_status_text));
  5236. } else if (plen + s_len(msg) + 4 < sizeof(post_status_text)) {
  5237. unsigned int pn = plen;
  5238. s_append(post_status_text, &pn, " | ",
  5239. sizeof(post_status_text));
  5240. s_append(post_status_text, &pn, msg,
  5241. sizeof(post_status_text));
  5242. } else {
  5243. s_copy(post_status_text, msg, sizeof(post_status_text));
  5244. }
  5245. post_status_ttl = 12000;
  5246. }
  5247. s_append(out, &o, "browser image stats\n", sizeof(out));
  5248. s_append(out, &o, "n=", sizeof(out));
  5249. s_append_dec(out, &o, (unsigned int)img_stat_n, sizeof(out));
  5250. s_append(out, &o, " wall=", sizeof(out));
  5251. s_append_dec(out, &o, img_stat_wall, sizeof(out));
  5252. s_append(out, &o, " net=", sizeof(out));
  5253. s_append_dec(out, &o, img_stat_net, sizeof(out));
  5254. s_append(out, &o, " open=", sizeof(out));
  5255. s_append_dec(out, &o, img_stat_open, sizeof(out));
  5256. s_append(out, &o, " first=", sizeof(out));
  5257. s_append_dec(out, &o, img_stat_first, sizeof(out));
  5258. s_append(out, &o, " io=", sizeof(out));
  5259. s_append_dec(out, &o, img_stat_io, sizeof(out));
  5260. s_append(out, &o, " dec=", sizeof(out));
  5261. s_append_dec(out, &o, img_stat_dec, sizeof(out));
  5262. s_append(out, &o, " scale=", sizeof(out));
  5263. s_append_dec(out, &o, img_stat_scale, sizeof(out));
  5264. s_append(out, &o, " paint=", sizeof(out));
  5265. s_append_dec(out, &o, img_stat_paint, sizeof(out));
  5266. s_append(out, &o, " reflow=", sizeof(out));
  5267. s_append_dec(out, &o, img_stat_reflow, sizeof(out));
  5268. s_append(out, &o, " bytes=", sizeof(out));
  5269. s_append_dec(out, &o, img_stat_bytes, sizeof(out));
  5270. s_append(out, &o, "\nurl bytes open first total io dec scale native bitmap\n",
  5271. sizeof(out));
  5272. s_append(out, &o, img_stat_log, sizeof(out));
  5273. u_syscall3(SYS_WRITE_FILE, (int)"/share/IMGSTAT", (int)out,
  5274. (int)s_len(out));
  5275. }
  5276. static void preload_step(void)
  5277. {
  5278. int i;
  5279. unsigned int t0;
  5280. if (!preload_active)
  5281. return;
  5282. if (cancel_fetch || pending_action) {
  5283. preload_active = 0;
  5284. preload_pending = 0;
  5285. fetch_workers_cancel_busy();
  5286. return;
  5287. }
  5288. preload_fill_jobs();
  5289. /* Decode completed images in a short batch instead of one per pass.
  5290. * A pass used to decode one image and then sleep 10 ms, so a page of
  5291. * small icons trickled in at the decode rate. The budget keeps a
  5292. * single huge JPEG from monopolising the UI while small images
  5293. * finish together. */
  5294. t0 = u_ticks_ms();
  5295. for (i = 0; i < FETCH_WORKERS; i++) {
  5296. if (!fetch_workers[i].busy)
  5297. continue;
  5298. if (preload_finish_worker(&fetch_workers[i]) &&
  5299. u_ticks_ms() - t0 >= BR_IMG_DECODE_BUDGET_MS)
  5300. break;
  5301. }
  5302. if (preload_active && preload_node >= doc.nnode &&
  5303. preload_active_jobs() == 0) {
  5304. preload_active = 0;
  5305. if (preload_pending)
  5306. preload_scroll = page_scroll.offset;
  5307. else
  5308. preload_pending = 0;
  5309. /* Keep the now idle helpers and their connections; a later
  5310. * navigation reuses them. They exit after ten idle seconds,
  5311. * and losing window focus stops them at once. */
  5312. if (img_repaint_pending) {
  5313. img_repaint_pending = 0;
  5314. ngui_invalidate(&ui);
  5315. }
  5316. img_stats_report();
  5317. set_status(post_status_text, post_status_error, post_status_ttl);
  5318. ngui_invalidate(&ui);
  5319. }
  5320. }
  5321. /* Set by navigate() when it turned a typed bare host into https://; the next
  5322. * load_page() consumes it and may retry over http. */
  5323. static int nav_https_upgraded;
  5324. /* Errors that mean "https is not served here" rather than "the site is
  5325. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  5326. static int https_fallback_error(int e)
  5327. {
  5328. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  5329. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  5330. e == UHTTP_ERR_RESET;
  5331. }
  5332. static void history_push(const char *url)
  5333. {
  5334. if (!url || !url[0])
  5335. return;
  5336. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  5337. s_eq(history[hist_pos], url))
  5338. return;
  5339. if (hist_len > 0 && hist_pos + 1 < hist_len)
  5340. hist_len = hist_pos + 1;
  5341. if (hist_len < BR_HISTORY) {
  5342. s_copy(history[hist_len], url, BR_URL_MAX);
  5343. hist_pos = hist_len;
  5344. hist_len++;
  5345. } else {
  5346. int i;
  5347. for (i = 1; i < BR_HISTORY; i++)
  5348. s_copy(history[i - 1], history[i], BR_URL_MAX);
  5349. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  5350. hist_pos = BR_HISTORY - 1;
  5351. }
  5352. }
  5353. static void load_page(const char *url, int local, int push)
  5354. {
  5355. unsigned char *body = 0;
  5356. unsigned int len = 0;
  5357. int truncated = 0;
  5358. struct img_info image_info;
  5359. char ctype[64];
  5360. char final[BR_URL_MAX];
  5361. char err[80];
  5362. const char *detail = 0;
  5363. const char *post = pending_post_is ? pending_post : 0;
  5364. unsigned int post_len = pending_post_len;
  5365. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  5366. /* Phase timings for the status line: where a slow load spends it. */
  5367. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  5368. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  5369. int upgraded = nav_https_upgraded;
  5370. int retried = 0;
  5371. int rv;
  5372. nav_https_upgraded = 0;
  5373. final[0] = '\0';
  5374. pending_post_len = 0;
  5375. pending_post_is = 0;
  5376. cancel_fetch = 0;
  5377. preload_active = 0;
  5378. preload_pending = 0;
  5379. fetch_workers_prepare_nav(url);
  5380. js_browser_stop();
  5381. js_last_status[0] = '\0';
  5382. js_last_error = 0;
  5383. heap_clear();
  5384. image_reset();
  5385. form_reset_state();
  5386. layout_valid = 0;
  5387. page_scroll.offset = 0;
  5388. page_scroll.dragging = 0;
  5389. page_title[0] = '\0';
  5390. page_loading = 1;
  5391. page_is_local = local;
  5392. s_copy(page_url, url, sizeof(page_url));
  5393. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5394. url_in.len = s_len(url_in.text);
  5395. url_in.cursor = url_in.len;
  5396. url_in.scroll = 0;
  5397. ngui_set_focus(&ui, 0);
  5398. if (final[0])
  5399. final[0] = '\0';
  5400. if (push)
  5401. history_push(url);
  5402. set_status("Loading...", 0, 0);
  5403. ngui_invalidate(&ui);
  5404. /* heap_clear() detaches the fonts, so attach them again before the
  5405. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  5406. if (heap_start() != 0) {
  5407. show_error("Out of memory", "Cannot allocate the page buffer");
  5408. return;
  5409. }
  5410. br_parse_plain(&doc, "", 0); /* blank while loading */
  5411. ngui_font_attach(&ui);
  5412. redraw_now();
  5413. browser_rules_alloc();
  5414. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5415. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  5416. &truncated, post, post_len);
  5417. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  5418. fetch_last_error == UHTTP_ERR_DNS) {
  5419. /* A busy previous page can leave the receiver ring full just
  5420. * long enough to lose a DNS reply. Tear the old helpers down
  5421. * and try once more before giving up. */
  5422. retried = 1;
  5423. fetch_workers_stop_all();
  5424. u_sleep_ms(500);
  5425. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5426. sizeof(ctype), final, sizeof(final), err,
  5427. sizeof(err), &truncated, post, post_len);
  5428. }
  5429. if (rv == FETCH_ABORT)
  5430. return;
  5431. t_fetch = u_ticks_ms() - t_start;
  5432. /* Capture the page timing before CSS/script/image fetches overwrite the
  5433. * shared fetch_meta block. */
  5434. if (rv == 0 && !local) {
  5435. page_open_ms = fetch_meta.open_ms;
  5436. page_first_ms = fetch_meta.first_ms;
  5437. page_total_ms = fetch_meta.total_ms;
  5438. }
  5439. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  5440. https_fallback_error(fetch_last_error)) {
  5441. char http_url[BR_URL_MAX];
  5442. unsigned int n = 0;
  5443. s_append(http_url, &n, "http://", sizeof(http_url));
  5444. s_append(http_url, &n, url + 8, sizeof(http_url));
  5445. /* Replace the https entry instead of adding a second one. */
  5446. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  5447. s_eq(history[hist_pos], url))
  5448. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  5449. load_page(http_url, 0, 0);
  5450. return;
  5451. }
  5452. if (rv != 0) {
  5453. detail = err;
  5454. show_error("Cannot load this page", detail);
  5455. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5456. url_in.len = s_len(url_in.text);
  5457. url_in.cursor = url_in.len;
  5458. url_in.scroll = 0;
  5459. return;
  5460. }
  5461. if (!local)
  5462. origin_cache_learn(url, final[0] ? final : url);
  5463. page_is_local = local;
  5464. if (final[0]) {
  5465. s_copy(page_url, final, sizeof(page_url));
  5466. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5467. url_in.len = s_len(url_in.text);
  5468. url_in.cursor = url_in.len;
  5469. url_in.scroll = 0;
  5470. }
  5471. if (contains_ci(ctype, "text/plain")) {
  5472. br_parse_plain(&doc, (const char *)body, len);
  5473. } else if (contains_ci(ctype, "image/") ||
  5474. (!contains_ci(ctype, "text/html") &&
  5475. img_sniff(body, len, &image_info) == 0)) {
  5476. unsigned int node = br_parse_image_doc(&doc, page_url);
  5477. if (node)
  5478. decode_direct_image(body, len, node);
  5479. s_copy(page_title, "Image", sizeof(page_title));
  5480. } else {
  5481. br_set_viewport(ui.w);
  5482. t_mark = u_ticks_ms();
  5483. br_parse(&doc, (const char *)body, len);
  5484. t_parse = u_ticks_ms() - t_mark;
  5485. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  5486. sizeof(page_title));
  5487. t_mark = u_ticks_ms();
  5488. if (load_stylesheets() == FETCH_ABORT)
  5489. return;
  5490. t_css = u_ticks_ms() - t_mark;
  5491. if (pending_action)
  5492. return;
  5493. }
  5494. preload_begin();
  5495. page_loading = 0;
  5496. hist_visit(page_url, page_title);
  5497. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5498. url_in.len = s_len(url_in.text);
  5499. url_in.cursor = url_in.len;
  5500. url_in.scroll = 0;
  5501. ngui_set_focus(&ui, 0);
  5502. /* Paint the parsed page before fetching/running scripts. A slow
  5503. * remote <script src> then does not hide the page behind the loading
  5504. * screen; the fetch helper pumps this UI while it waits. */
  5505. set_status("Loading scripts...", 0, 0);
  5506. t_mark = u_ticks_ms();
  5507. redraw_now();
  5508. t_paint = u_ticks_ms() - t_mark;
  5509. /* Start one image download before the scripts. The other workers
  5510. * fetch the external script bodies in parallel, and the remaining
  5511. * images start as soon as the script phase ends. */
  5512. preload_max_jobs = 1;
  5513. preload_fill_jobs();
  5514. preload_wait = 0;
  5515. t_mark = u_ticks_ms();
  5516. run_page_scripts();
  5517. t_js = u_ticks_ms() - t_mark;
  5518. preload_max_jobs = FETCH_WORKERS;
  5519. if (pending_action)
  5520. return;
  5521. post_status_text[0] = '\0';
  5522. post_status_error = 0;
  5523. post_status_ttl = 0;
  5524. if (js_last_status[0]) {
  5525. s_copy(post_status_text, js_last_status,
  5526. sizeof(post_status_text));
  5527. post_status_error = js_last_error;
  5528. post_status_ttl = 8000;
  5529. } else if (truncated) {
  5530. s_copy(post_status_text, "Page truncated at the buffer limit",
  5531. sizeof(post_status_text));
  5532. post_status_ttl = 6000;
  5533. } else if (doc.truncated) {
  5534. s_copy(post_status_text, "Page truncated by the parser",
  5535. sizeof(post_status_text));
  5536. post_status_ttl = 6000;
  5537. } else if (page_total_ms) {
  5538. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  5539. * paint 220, js 1750" -- the phases of this load. */
  5540. unsigned int n = 0;
  5541. static const char *const names[] = {
  5542. ", parse ", ", css ", ", paint ", ", js "
  5543. };
  5544. unsigned int vals[4];
  5545. int k;
  5546. vals[0] = t_parse;
  5547. vals[1] = t_css;
  5548. vals[2] = t_paint;
  5549. vals[3] = t_js;
  5550. (void)page_first_ms;
  5551. if (starts_with(page_url, "https://"))
  5552. s_append(post_status_text, &n,
  5553. "HTTPS (not verified), ",
  5554. sizeof(post_status_text));
  5555. s_append(post_status_text, &n, "Loaded in ",
  5556. sizeof(post_status_text));
  5557. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  5558. sizeof(post_status_text));
  5559. s_append(post_status_text, &n, " ms: page ",
  5560. sizeof(post_status_text));
  5561. s_append_dec(post_status_text, &n, t_fetch,
  5562. sizeof(post_status_text));
  5563. s_append(post_status_text, &n, " (headers ",
  5564. sizeof(post_status_text));
  5565. s_append_dec(post_status_text, &n, page_open_ms,
  5566. sizeof(post_status_text));
  5567. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  5568. for (k = 0; k < 4; k++) {
  5569. s_append(post_status_text, &n, names[k],
  5570. sizeof(post_status_text));
  5571. s_append_dec(post_status_text, &n, vals[k],
  5572. sizeof(post_status_text));
  5573. }
  5574. post_status_ttl = 12000;
  5575. } else if (starts_with(page_url, "https://")) {
  5576. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  5577. sizeof(post_status_text));
  5578. post_status_ttl = 6000;
  5579. }
  5580. set_status(post_status_text, post_status_error, post_status_ttl);
  5581. ngui_invalidate(&ui);
  5582. }
  5583. static void load_home(int push)
  5584. {
  5585. pending_post_len = 0;
  5586. pending_post_is = 0;
  5587. cancel_fetch = 0;
  5588. preload_active = 0;
  5589. preload_pending = 0;
  5590. js_browser_stop();
  5591. js_last_status[0] = '\0';
  5592. js_last_error = 0;
  5593. heap_clear();
  5594. image_reset();
  5595. form_reset_state();
  5596. layout_valid = 0;
  5597. page_scroll.offset = 0;
  5598. page_scroll.dragging = 0;
  5599. page_loading = 1;
  5600. page_is_local = 0;
  5601. s_copy(page_url, "about:home", sizeof(page_url));
  5602. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5603. url_in.len = s_len(url_in.text);
  5604. url_in.cursor = url_in.len;
  5605. url_in.scroll = 0;
  5606. ngui_set_focus(&ui, 0);
  5607. if (push)
  5608. history_push(page_url);
  5609. ngui_invalidate(&ui);
  5610. /* See load_page(): reattach the fonts before the first redraw. */
  5611. if (heap_start() != 0) {
  5612. show_error("Out of memory", "Cannot allocate the browser heap");
  5613. return;
  5614. }
  5615. br_parse_plain(&doc, "", 0);
  5616. ngui_font_attach(&ui);
  5617. redraw_now();
  5618. browser_rules_alloc();
  5619. {
  5620. static const char home[] =
  5621. "<html><head><title>NebOS Browser</title><style>"
  5622. "body { margin: 10px; color: #e4e6f0; }"
  5623. "h1 { color: #7fb0ff; }"
  5624. ".box { background-color: #262b3a; margin: 12px; "
  5625. "padding: 10px; }"
  5626. "a { color: #7fb0ff; }"
  5627. "pre { background-color: #32384a; }"
  5628. "</style></head><body>"
  5629. "<h1>NebOS Browser</h1>"
  5630. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  5631. "shared HTTP client and the image library.</p>"
  5632. "<div class=\"box\"><b>Try:</b>"
  5633. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  5634. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  5635. "<li><a href=\"/floppy1/JS.HTM\">/"
  5636. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  5637. "<li><a href=\"http://10.0.2.2:8000/\">"
  5638. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  5639. "<li><a href=\"https://example.com/\">"
  5640. "https://example.com/</a> (TLS, not verified)</li>"
  5641. "</ul></div>"
  5642. "<p>Type a URL in the bar above. Esc closes the "
  5643. "window, Ctrl+L focuses the address bar.</p>"
  5644. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  5645. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  5646. "</body></html>";
  5647. br_set_viewport(ui.w);
  5648. br_parse(&doc, home, sizeof(home) - 1);
  5649. br_parse_inline_css(&doc);
  5650. br_reset_styles(&doc);
  5651. s_copy(page_title, doc.title, sizeof(page_title));
  5652. }
  5653. post_status_text[0] = '\0';
  5654. post_status_error = 0;
  5655. post_status_ttl = 0;
  5656. page_loading = 0;
  5657. set_status("", 0, 0);
  5658. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5659. url_in.len = s_len(url_in.text);
  5660. url_in.cursor = url_in.len;
  5661. url_in.scroll = 0;
  5662. ngui_set_focus(&ui, 0);
  5663. ngui_invalidate(&ui);
  5664. }
  5665. /* Extensions the browser opens from the local filesystem. A dotted input
  5666. * with one of these still resolves relative to the cwd. */
  5667. static int local_file_ext(const char *s)
  5668. {
  5669. static const char *const exts[] = {
  5670. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  5671. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  5672. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  5673. "cfg", "conf", 0
  5674. };
  5675. unsigned int i = 0, start = 0, len = 0, e;
  5676. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  5677. s[i] != '#') {
  5678. if (s[i] == '.') {
  5679. start = i + 1;
  5680. len = 0;
  5681. } else if (start) {
  5682. len++;
  5683. }
  5684. i++;
  5685. }
  5686. if (!len)
  5687. return 0;
  5688. for (e = 0; exts[e]; e++) {
  5689. const char *x = exts[e];
  5690. unsigned int xn = s_len(x), k;
  5691. if (xn != len)
  5692. continue;
  5693. for (k = 0; k < len; k++) {
  5694. char a = s[start + k];
  5695. if (a >= 'A' && a <= 'Z')
  5696. a = (char)(a - 'A' + 'a');
  5697. if (a != x[k])
  5698. break;
  5699. }
  5700. if (k == len)
  5701. return 1;
  5702. }
  5703. return 0;
  5704. }
  5705. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  5706. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  5707. * Enter to the first network request. */
  5708. static int looks_like_host(const char *s)
  5709. {
  5710. unsigned int i = 0;
  5711. int dot = 0;
  5712. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  5713. s[i] != ':') {
  5714. char c = s[i];
  5715. if (c == '.') {
  5716. dot = 1;
  5717. } else if (!((c >= 'a' && c <= 'z') ||
  5718. (c >= 'A' && c <= 'Z') ||
  5719. (c >= '0' && c <= '9') ||
  5720. c == '-' || c == '_')) {
  5721. return 0;
  5722. }
  5723. i++;
  5724. }
  5725. return dot && i > 0 && !local_file_ext(s);
  5726. }
  5727. static void load_remote(const char *url, int push)
  5728. {
  5729. char canon[BR_URL_MAX];
  5730. s_copy(canon, url, sizeof(canon));
  5731. origin_cache_apply(canon, sizeof(canon));
  5732. load_page(canon, 0, push);
  5733. }
  5734. static void navigate(const char *input, int push)
  5735. {
  5736. char target[BR_URL_MAX];
  5737. char *t;
  5738. if (!input)
  5739. return;
  5740. s_copy(target, input, sizeof(target));
  5741. t = trim(target);
  5742. if (!t[0])
  5743. return;
  5744. if (s_eq(t, "about:home")) {
  5745. load_home(push);
  5746. return;
  5747. }
  5748. if (starts_with(t, "file://")) {
  5749. make_abs_local(t + 7, target, sizeof(target));
  5750. load_page(target, 1, push);
  5751. return;
  5752. }
  5753. if (is_http(t)) {
  5754. load_remote(t, push);
  5755. return;
  5756. }
  5757. if (t[0] == '/') {
  5758. make_abs_local(t, target, sizeof(target));
  5759. load_page(target, 1, push);
  5760. return;
  5761. }
  5762. if (!looks_like_host(t)) {
  5763. struct sys_stat st;
  5764. if (u_stat(t, &st) == 0 && !st.is_dir) {
  5765. make_abs_local(t, target, sizeof(target));
  5766. load_page(target, 1, push);
  5767. return;
  5768. }
  5769. }
  5770. {
  5771. /* A typed bare host tries https first: nearly every site
  5772. * redirects http -> https anyway, and that hop costs a whole
  5773. * extra connection. load_page() falls back to http when the
  5774. * https connection itself fails. */
  5775. char with_scheme[BR_URL_MAX];
  5776. unsigned int n = 0;
  5777. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  5778. s_append(with_scheme, &n, t, sizeof(with_scheme));
  5779. nav_https_upgraded = 1;
  5780. load_remote(with_scheme, push);
  5781. }
  5782. }
  5783. /* ---- layout ---- */
  5784. static struct ufont_face *face_for(unsigned int family, int bold, int italic)
  5785. {
  5786. unsigned int id;
  5787. if (!family || family > BR_MAX_FACES)
  5788. return 0;
  5789. id = font_pick[family - 1][(bold ? 2 : 0) | (italic ? 1 : 0)];
  5790. return id ? font_faces[id - 1] : 0;
  5791. }
  5792. static struct ufont_face *style_face(const struct br_style *st)
  5793. {
  5794. return st ? face_for(st->font_face, st->bold, st->italic) : 0;
  5795. }
  5796. static struct ufont_face *run_face(const struct lay_run *r)
  5797. {
  5798. return face_for(r->font_face, r->bold, r->italic);
  5799. }
  5800. static unsigned int face_text_width(struct ngui *gui,
  5801. const struct br_style *st,
  5802. const char *s, unsigned int n)
  5803. {
  5804. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  5805. st->bold, st->italic, st->mono);
  5806. }
  5807. static int face_line_height(struct ngui *gui, const struct br_style *st)
  5808. {
  5809. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  5810. st->mono);
  5811. }
  5812. static unsigned int run_text_width(struct ngui *gui,
  5813. const struct lay_run *r,
  5814. const char *s, unsigned int n)
  5815. {
  5816. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  5817. r->bold, r->italic, r->mono);
  5818. }
  5819. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  5820. {
  5821. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  5822. r->mono);
  5823. }
  5824. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  5825. {
  5826. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  5827. }
  5828. static struct br_style base_style(void)
  5829. {
  5830. struct br_style s = { 0 };
  5831. s.color = ui.theme.text;
  5832. s.bg = ui.theme.bg;
  5833. s.has_bg = 0;
  5834. for (int i = 0; i < 4; i++) {
  5835. s.border_c[i] = 0;
  5836. s.border_w[i] = 0;
  5837. s.border_s[i] = BR_BORDER_SOLID;
  5838. }
  5839. s.font_px = 16;
  5840. s.bold = 0;
  5841. s.italic = 0;
  5842. s.mono = 0;
  5843. s.underline = 0;
  5844. s.strike = 0;
  5845. s.overline = 0;
  5846. s.align = BR_ALIGN_LEFT;
  5847. s.display = BR_DISPLAY_BLOCK;
  5848. s.no_bullet = 0;
  5849. s.list_style = BR_LIST_AUTO;
  5850. s.uppercase = 0;
  5851. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  5852. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  5853. s.width = s.max_width = s.min_width = 0;
  5854. s.height = s.min_height = s.max_height = 0;
  5855. s.box_sizing = 0;
  5856. s.ml_auto = s.mr_auto = 0;
  5857. s.line_h_pct = 0;
  5858. s.line_h_px = 0;
  5859. s.mt = s.mb = s.ml = s.mr = 0;
  5860. s.pt = s.pb = s.pl = s.pr = 0;
  5861. return s;
  5862. }
  5863. /* The style node 0's children inherit. Node 0 is the first parsed node:
  5864. * a minified page that starts `<!doctype html><html ...>` makes it the
  5865. * <html> element itself, and the layout walks only its children, so its
  5866. * own cascade (html { color; font } -- Docusaurus/Infima put the page
  5867. * colour and font there) used to be skipped and the theme defaults showed
  5868. * through. Only inherited properties are taken: the root's box (margins,
  5869. * display, background) is not a container style for its children here. */
  5870. static struct br_style root_style(void)
  5871. {
  5872. struct br_style base = base_style(), st;
  5873. if (!doc.nnode || doc.nodes[doc.root].type != BR_NODE_ELEM ||
  5874. doc.nodes[doc.root].tag != BR_TAG_HTML)
  5875. return base;
  5876. br_style_for(&doc, doc.root, &base, &st);
  5877. base.color = st.color;
  5878. base.font_px = st.font_px;
  5879. base.bold = st.bold;
  5880. base.italic = st.italic;
  5881. base.mono = st.mono;
  5882. base.font_face = st.font_face;
  5883. base.align = st.align;
  5884. base.line_h_pct = st.line_h_pct;
  5885. base.line_h_px = st.line_h_px;
  5886. base.nowrap = st.nowrap;
  5887. base.uppercase = st.uppercase;
  5888. base.cursor = st.cursor;
  5889. base.vis_hidden = st.vis_hidden;
  5890. base.fill_mode = st.fill_mode;
  5891. base.fill = st.fill;
  5892. base.stroke_mode = st.stroke_mode;
  5893. base.stroke = st.stroke;
  5894. base.stroke_w = st.stroke_w;
  5895. base.fill_evenodd = st.fill_evenodd;
  5896. return base;
  5897. }
  5898. /* Resolve a margin/padding raw value. Percentages use the containing
  5899. * block width for all four sides, as CSS specifies. */
  5900. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  5901. {
  5902. if (unit == 1)
  5903. return base * v / 10000;
  5904. if (unit == 2)
  5905. return st->font_px * v / 100;
  5906. if (unit == 3)
  5907. return (int)br_root_font_px() * v / 100;
  5908. if (unit == 4)
  5909. return 0;
  5910. return v;
  5911. }
  5912. static int mp_px(const struct br_style *st, int side, int base)
  5913. {
  5914. int raw;
  5915. switch (side) {
  5916. case 0: raw = st->mt; break;
  5917. case 1: raw = st->mr; break;
  5918. case 2: raw = st->mb; break;
  5919. case 3: raw = st->ml; break;
  5920. case 4: raw = st->pt; break;
  5921. case 5: raw = st->pr; break;
  5922. case 6: raw = st->pb; break;
  5923. default: raw = st->pl; break;
  5924. }
  5925. if (st->mp_unit[side] == 5)
  5926. return base * raw / 100 + st->mp_calc_px[side];
  5927. return css_mp_px(st, raw, st->mp_unit[side], base);
  5928. }
  5929. static int style_width_px(const struct br_style *st, int base)
  5930. {
  5931. if (st->width_kind == 1)
  5932. return st->width;
  5933. if (st->width_kind == 2)
  5934. return base * (int)st->width / 100;
  5935. if (st->width_kind == 3)
  5936. return base * st->width_calc_pct / 100 + st->width_calc_px;
  5937. return 0;
  5938. }
  5939. static int style_height_px(const struct br_style *st, int base)
  5940. {
  5941. if (st->height_kind == 1)
  5942. return st->height;
  5943. if (st->height_kind == 2)
  5944. return base * (int)st->height / 100;
  5945. if (st->height_kind == 3)
  5946. return base * st->height_calc_pct / 100 + st->height_calc_px;
  5947. return 0;
  5948. }
  5949. static int css_size(unsigned char kind, int val, int base)
  5950. {
  5951. if (kind == 1)
  5952. return val;
  5953. if (kind == 2)
  5954. return base * val / 100;
  5955. return -1;
  5956. }
  5957. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  5958. int thick, int horizontal, unsigned short color,
  5959. unsigned char style)
  5960. {
  5961. int pos;
  5962. if (len <= 0 || thick <= 0)
  5963. return;
  5964. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  5965. if (horizontal)
  5966. ngui_fill_rect(ui, (struct ngui_rect){
  5967. x, y, len, thick}, color);
  5968. else
  5969. ngui_fill_rect(ui, (struct ngui_rect){
  5970. x, y, thick, len}, color);
  5971. return;
  5972. }
  5973. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  5974. int seg = len - pos;
  5975. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  5976. seg = style == BR_BORDER_DASHED ? 4 : 2;
  5977. if (horizontal)
  5978. ngui_fill_rect(ui, (struct ngui_rect){
  5979. x + pos, y, seg, thick}, color);
  5980. else
  5981. ngui_fill_rect(ui, (struct ngui_rect){
  5982. x, y + pos, thick, seg}, color);
  5983. }
  5984. }
  5985. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  5986. const struct br_style *st)
  5987. {
  5988. int top = st->border_w[0], right = st->border_w[1];
  5989. int bottom = st->border_w[2], left = st->border_w[3];
  5990. if (r.w <= 0 || r.h <= 0)
  5991. return;
  5992. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  5993. int i;
  5994. for (i = 0; i < 4; i++)
  5995. if (st->border_w[i] && !st->border_t[i]) {
  5996. ngui_fill_rect(ui, r, st->border_c[i]);
  5997. break;
  5998. }
  5999. return;
  6000. }
  6001. if (top && !st->border_t[0])
  6002. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  6003. st->border_c[0], st->border_s[0]);
  6004. if (bottom && !st->border_t[2])
  6005. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  6006. st->border_c[2], st->border_s[2]);
  6007. if (left && !st->border_t[3])
  6008. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  6009. left, 0, st->border_c[3], st->border_s[3]);
  6010. if (right && !st->border_t[1])
  6011. draw_border_side(ui, r.x + r.w - right, r.y + top,
  6012. r.h - top - bottom, right, 0,
  6013. st->border_c[1], st->border_s[1]);
  6014. }
  6015. static void transform_origin(const struct br_style *st, int w, int h,
  6016. int *ox, int *oy)
  6017. {
  6018. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  6019. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  6020. }
  6021. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  6022. unsigned int a)
  6023. {
  6024. unsigned int dr, dg, db, sr, sg, sb;
  6025. if (a >= 255)
  6026. return s;
  6027. dr = (d >> 11) & 31;
  6028. dg = (d >> 5) & 63;
  6029. db = d & 31;
  6030. sr = (s >> 11) & 31;
  6031. sg = (s >> 5) & 63;
  6032. sb = s & 31;
  6033. dr = (dr * (255 - a) + sr * a) / 255;
  6034. dg = (dg * (255 - a) + sg * a) / 255;
  6035. db = (db * (255 - a) + sb * a) / 255;
  6036. return (unsigned short)((dr << 11) | (dg << 5) | db);
  6037. }
  6038. /* Paint a solid box through scale()/rotate() around transform-origin. This
  6039. * transforms the element's own background box; text and descendants keep
  6040. * their layout (documented approximation). */
  6041. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  6042. unsigned short color,
  6043. const struct br_style *st)
  6044. {
  6045. double sx = st->scale_x / 100.0;
  6046. double sy = st->scale_y / 100.0;
  6047. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  6048. double c = cos(th), sn = sin(th);
  6049. int ox, oy, minx, miny, maxx, maxy, x, y;
  6050. double ax, ay;
  6051. double px[4], py[4];
  6052. int cx1, cy1, cx2, cy2, i;
  6053. if (sx == 0)
  6054. sx = 0.01;
  6055. if (sy == 0)
  6056. sy = 0.01;
  6057. transform_origin(st, box.w, box.h, &ox, &oy);
  6058. ax = box.x + ox;
  6059. ay = box.y + oy;
  6060. px[0] = -ox; py[0] = -oy;
  6061. px[1] = box.w - ox; py[1] = -oy;
  6062. px[2] = box.w - ox; py[2] = box.h - oy;
  6063. px[3] = -ox; py[3] = box.h - oy;
  6064. minx = miny = 1000000;
  6065. maxx = maxy = -1000000;
  6066. for (i = 0; i < 4; i++) {
  6067. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  6068. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  6069. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  6070. if (dx < minx) minx = dx;
  6071. if (dx > maxx) maxx = dx;
  6072. if (dy < miny) miny = dy;
  6073. if (dy > maxy) maxy = dy;
  6074. }
  6075. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  6076. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  6077. cx2 = page_rect.x + page_rect.w - 12;
  6078. cy2 = page_rect.y + page_rect.h;
  6079. if (cx2 > gui->w) cx2 = gui->w;
  6080. if (cy2 > gui->h) cy2 = gui->h;
  6081. if (minx < cx1) minx = cx1;
  6082. if (miny < cy1) miny = cy1;
  6083. if (maxx > cx2 - 1) maxx = cx2 - 1;
  6084. if (maxy > cy2 - 1) maxy = cy2 - 1;
  6085. for (y = miny; y <= maxy; y++) {
  6086. for (x = minx; x <= maxx; x++) {
  6087. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  6088. double rx = dx * c + dy * sn;
  6089. double ry = -dx * sn + dy * c;
  6090. double bx = rx / sx + ox;
  6091. double by = ry / sy + oy;
  6092. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  6093. gui->px[y * gui->w + x] = color;
  6094. }
  6095. }
  6096. }
  6097. static void draw_image_transformed(struct ngui *gui,
  6098. const struct img_image *im,
  6099. int x, int y, int w, int h,
  6100. int sx100, int sy100, int rot100,
  6101. int origin_x, int origin_y,
  6102. int origin_x_kind, int origin_y_kind)
  6103. {
  6104. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  6105. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  6106. double c = cos(th), sn = sin(th);
  6107. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  6108. double ax, ay;
  6109. double bx[4], by[4];
  6110. int cx1, cy1, cx2, cy2;
  6111. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  6112. return;
  6113. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  6114. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  6115. ax = x + ox;
  6116. ay = y + oy;
  6117. bx[0] = -ox; by[0] = -oy;
  6118. bx[1] = w - ox; by[1] = -oy;
  6119. bx[2] = w - ox; by[2] = h - oy;
  6120. bx[3] = -ox; by[3] = h - oy;
  6121. minx = miny = 1000000;
  6122. maxx = maxy = -1000000;
  6123. for (i = 0; i < 4; i++) {
  6124. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  6125. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  6126. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  6127. if (dx < minx) minx = dx;
  6128. if (dx > maxx) maxx = dx;
  6129. if (dy < miny) miny = dy;
  6130. if (dy > maxy) maxy = dy;
  6131. }
  6132. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  6133. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  6134. cx2 = page_rect.x + page_rect.w - 12;
  6135. cy2 = page_rect.y + page_rect.h;
  6136. if (cx2 > gui->w) cx2 = gui->w;
  6137. if (cy2 > gui->h) cy2 = gui->h;
  6138. if (minx < cx1) minx = cx1;
  6139. if (miny < cy1) miny = cy1;
  6140. if (maxx > cx2 - 1) maxx = cx2 - 1;
  6141. if (maxy > cy2 - 1) maxy = cy2 - 1;
  6142. for (py = miny; py <= maxy; py++) {
  6143. for (px = minx; px <= maxx; px++) {
  6144. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  6145. double rx = dx * c + dy * sn;
  6146. double ry = -dx * sn + dy * c;
  6147. double fx = rx / sx + ox;
  6148. double fy = ry / sy + oy;
  6149. int ix, iy;
  6150. unsigned int si, a;
  6151. unsigned short src;
  6152. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  6153. continue;
  6154. ix = (int)(fx * (double)im->w / w);
  6155. iy = (int)(fy * (double)im->h / h);
  6156. if (ix < 0 || ix >= (int)im->w ||
  6157. iy < 0 || iy >= (int)im->h)
  6158. continue;
  6159. si = (unsigned int)iy * im->w + (unsigned int)ix;
  6160. src = im->px[si];
  6161. a = im->alpha ? im->alpha[si] : 255;
  6162. gui->px[py * gui->w + px] =
  6163. a >= 255 ? src :
  6164. blend_rgb565(gui->px[py * gui->w + px],
  6165. src, a);
  6166. }
  6167. }
  6168. }
  6169. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  6170. unsigned int node, const struct br_style *st);
  6171. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  6172. * first and every pixel outside a corner's arc is restored afterwards. */
  6173. #define BG_ROUND_MAX 64
  6174. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  6175. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  6176. unsigned int node, const struct br_style *st,
  6177. int rtl, int rtr, int rbr, int rbl)
  6178. {
  6179. struct ngui *ui = l->ui;
  6180. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  6181. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  6182. if (ui->nclip > 0)
  6183. clip = ui->clip[ui->nclip - 1];
  6184. for (c = 0; c < 4; c++) {
  6185. if (r[c] > BG_ROUND_MAX)
  6186. r[c] = BG_ROUND_MAX;
  6187. if (r[c] > box.w / 2)
  6188. r[c] = box.w / 2;
  6189. if (r[c] > box.h / 2)
  6190. r[c] = box.h / 2;
  6191. }
  6192. for (c = 0; c < 4; c++) {
  6193. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  6194. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  6195. for (dy = 0; dy < r[c]; dy++)
  6196. for (dx = 0; dx < r[c]; dx++) {
  6197. int px = ox + dx, py = oy + dy;
  6198. if (px >= clip.x && py >= clip.y &&
  6199. px < clip.x + clip.w && py < clip.y + clip.h)
  6200. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  6201. ui->px[py * ui->w + px];
  6202. }
  6203. }
  6204. draw_bg_image(l, box, node, st);
  6205. for (c = 0; c < 4; c++) {
  6206. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  6207. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  6208. /* arc centre, in corner-square coordinates */
  6209. int cx = (c == 1 || c == 2) ? 0 : r[c];
  6210. int cy = (c >= 2) ? 0 : r[c];
  6211. for (dy = 0; dy < r[c]; dy++)
  6212. for (dx = 0; dx < r[c]; dx++) {
  6213. int px = ox + dx, py = oy + dy;
  6214. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  6215. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  6216. continue;
  6217. if (px >= clip.x && py >= clip.y &&
  6218. px < clip.x + clip.w && py < clip.y + clip.h)
  6219. ui->px[py * ui->w + px] =
  6220. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  6221. }
  6222. }
  6223. }
  6224. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  6225. unsigned int node, const struct br_style *st)
  6226. {
  6227. struct br_image *bi;
  6228. struct img_blit b;
  6229. int tw, th, x, y, rep_x, rep_y, posx, posy;
  6230. unsigned int scale = 65536;
  6231. int legacy, tiles = 0, rows = 0;
  6232. int cx1, cy1, cx2, cy2;
  6233. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  6234. return;
  6235. if (doc.nodes[node].bg_img_index < 0 ||
  6236. doc.nodes[node].bg_img_index >= image_count)
  6237. return;
  6238. bi = &images[doc.nodes[node].bg_img_index];
  6239. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  6240. return;
  6241. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  6242. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  6243. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  6244. if (legacy) {
  6245. scale = ((unsigned int)box.w << 16) / bi->img.w;
  6246. tw = box.w;
  6247. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6248. x = box.x;
  6249. y = box.y;
  6250. rep_x = rep_y = 0;
  6251. } else {
  6252. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  6253. unsigned int sx = ((unsigned int)box.w << 16) /
  6254. bi->img.w;
  6255. unsigned int sy = ((unsigned int)box.h << 16) /
  6256. bi->img.h;
  6257. scale = st->bg_size_kind == 3 ?
  6258. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  6259. } else if (st->bg_size_kind == 1 ||
  6260. st->bg_size_kind == 2) {
  6261. int w = st->bg_size_w;
  6262. int h = st->bg_size_h;
  6263. if (st->bg_size_kind == 2) {
  6264. if (w)
  6265. w = box.w * w / 100;
  6266. if (h)
  6267. h = box.h * h / 100;
  6268. }
  6269. if (w)
  6270. scale = ((unsigned int)w << 16) / bi->img.w;
  6271. else if (h)
  6272. scale = ((unsigned int)h << 16) / bi->img.h;
  6273. }
  6274. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  6275. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6276. if (tw < 1)
  6277. tw = 1;
  6278. if (th < 1)
  6279. th = 1;
  6280. posx = st->bg_pos_x_kind == 1 ?
  6281. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  6282. posy = st->bg_pos_y_kind == 1 ?
  6283. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  6284. x = box.x + posx;
  6285. y = box.y + posy;
  6286. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  6287. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  6288. if (rep_x) {
  6289. int m = (x - box.x) % tw;
  6290. if (m > 0)
  6291. m -= tw;
  6292. x = box.x + m;
  6293. }
  6294. if (rep_y) {
  6295. int m = (y - box.y) % th;
  6296. if (m > 0)
  6297. m -= th;
  6298. y = box.y + m;
  6299. }
  6300. }
  6301. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  6302. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  6303. cx2 = box.x + box.w;
  6304. cy2 = box.y + box.h;
  6305. if (cx2 > page_rect.x + page_rect.w - 12)
  6306. cx2 = page_rect.x + page_rect.w - 12;
  6307. if (cy2 > page_rect.y + page_rect.h)
  6308. cy2 = page_rect.y + page_rect.h;
  6309. if (cx1 >= cx2 || cy1 >= cy2)
  6310. return;
  6311. b.dst = l->ui->px;
  6312. b.dst_w = l->ui->w;
  6313. b.dst_h = l->ui->h;
  6314. b.clip_x = cx1;
  6315. b.clip_y = cy1;
  6316. b.clip_w = cx2 - cx1;
  6317. b.clip_h = cy2 - cy1;
  6318. b.bg = ui.theme.bg;
  6319. b.bg2 = ui.theme.bg;
  6320. b.dst_a = 0;
  6321. {
  6322. struct img_image *src = image_display_get(bi, tw, th);
  6323. int row_x;
  6324. if (!src)
  6325. src = &bi->img;
  6326. b.scale = ((unsigned int)tw << 16) / src->w;
  6327. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  6328. row_x = x;
  6329. for (;;) {
  6330. for (;;) {
  6331. b.x = x;
  6332. b.y = y;
  6333. img_draw(src, &b);
  6334. if (!rep_x || ++tiles > 512)
  6335. break;
  6336. x += tw;
  6337. if (x >= box.x + box.w)
  6338. break;
  6339. }
  6340. if (!rep_y || ++rows > 64)
  6341. break;
  6342. y += th;
  6343. if (y >= box.y + box.h)
  6344. break;
  6345. x = row_x;
  6346. }
  6347. }
  6348. }
  6349. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  6350. int *out_w, int *out_h);
  6351. static void svg_paint_box(struct ngui *ui, unsigned int node,
  6352. const struct br_style *st, int x, int y, int w,
  6353. int h);
  6354. /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
  6355. * RUN_SVG an inline <svg> icon (its node in off), RUN_PBOX an empty
  6356. * ::before/::after box with a background (Infima's menu chevrons). */
  6357. #define RUN_SVG (-3)
  6358. #define RUN_PBOX (-4)
  6359. static int run_width(const struct lay_run *r)
  6360. {
  6361. if (r->img >= 0)
  6362. return r->iw;
  6363. if (r->img == -2 || r->img == RUN_SVG || r->img == RUN_PBOX)
  6364. return r->iw;
  6365. return (int)r->w;
  6366. }
  6367. static void start_line(struct lay *l, const struct br_style *st)
  6368. {
  6369. (void)st;
  6370. if (l->nruns == 0) {
  6371. l->line_y = l->y;
  6372. l->line_h = 0;
  6373. }
  6374. l->line_left = l->left;
  6375. l->line_right = l->right;
  6376. if (l->float_active && l->line_y < l->float_bottom) {
  6377. if (l->float_left > l->line_left)
  6378. l->line_left = l->float_left;
  6379. if (l->float_right < l->line_right)
  6380. l->line_right = l->float_right;
  6381. }
  6382. if (l->line_right < l->line_left + 8)
  6383. l->line_right = l->line_left + 8;
  6384. l->line_x = l->line_left;
  6385. l->run_x = l->line_left;
  6386. }
  6387. static void inline_box_add(const struct lay *l, unsigned int owner, int x,
  6388. int w)
  6389. {
  6390. int y = l->line_y;
  6391. int h = l->line_h ? l->line_h : 16;
  6392. int depth = 0;
  6393. while (owner && owner <= BR_MAX_NODES && depth++ < 16) {
  6394. unsigned int node = owner - 1;
  6395. struct br_layout_box *b = &layout_boxes[node];
  6396. if (b->valid && inline_box_pass[node] == inline_box_pass_id &&
  6397. (inline_box_flush[node] == inline_box_flush_id ||
  6398. inline_box_y[node] < y)) {
  6399. int x1 = b->x + b->w, y1 = b->y + b->h;
  6400. if (x < b->x)
  6401. b->x = x;
  6402. if (y < b->y)
  6403. b->y = y;
  6404. if (x + w > x1)
  6405. x1 = x + w;
  6406. if (y + h > y1)
  6407. y1 = y + h;
  6408. b->w = x1 - b->x;
  6409. b->h = y1 - b->y;
  6410. } else {
  6411. b->x = x;
  6412. b->y = y;
  6413. b->w = w;
  6414. b->h = h;
  6415. b->valid = 1;
  6416. }
  6417. inline_box_pass[node] = inline_box_pass_id;
  6418. inline_box_flush[node] = inline_box_flush_id;
  6419. inline_box_y[node] = y;
  6420. owner = inline_box_parent[node];
  6421. }
  6422. }
  6423. static void flush_line(struct lay *l)
  6424. {
  6425. int total, x, i, vis;
  6426. inline_box_flush_id++;
  6427. if (!l->nruns && l->line_x == l->line_left) {
  6428. l->line_h = 0;
  6429. return;
  6430. }
  6431. total = l->line_x - l->line_left;
  6432. x = l->line_left;
  6433. vis = 1;
  6434. if (l->draw) {
  6435. int lh = l->line_h ? l->line_h : 16;
  6436. vis = l->line_y + lh >= page_rect.y &&
  6437. l->line_y <= page_rect.y + page_rect.h;
  6438. }
  6439. if (l->align == BR_ALIGN_CENTER)
  6440. x += (l->line_right - l->line_left - total) / 2;
  6441. else if (l->align == BR_ALIGN_RIGHT)
  6442. x = l->line_right - total;
  6443. if (x < l->line_left)
  6444. x = l->line_left;
  6445. for (i = 0; i < l->nruns; i++) {
  6446. struct lay_run *r = &l->runs[i];
  6447. int w = run_width(r);
  6448. int ry = l->line_y + r->dy;
  6449. x += r->gap;
  6450. if (l->draw && vis) {
  6451. if (r->form) {
  6452. unsigned int node = r->form - 1;
  6453. struct form_state *fs = form_get(node, 1);
  6454. int hh = r->ih ? r->ih : 20;
  6455. int focused = form_focus == node;
  6456. int disabled = r->form_disabled;
  6457. unsigned short bg = l->ui->theme.panel_alt;
  6458. unsigned short fg = disabled ? 0x8410 : r->color;
  6459. struct ngui_rect box = {x, ry, w, hh};
  6460. if (r->form_kind == FORM_CHECKBOX ||
  6461. r->form_kind == FORM_RADIO) {
  6462. ngui_fill_rect(l->ui, box, bg);
  6463. ngui_frame(l->ui, box,
  6464. focused ? l->ui->theme.accent :
  6465. l->ui->theme.border);
  6466. if (fs && fs->checked) {
  6467. struct ngui_rect dot = {
  6468. x + 4, ry + 4,
  6469. w > 8 ? w - 8 : 1,
  6470. hh > 8 ? hh - 8 : 1
  6471. };
  6472. if (r->form_kind == FORM_RADIO)
  6473. ngui_fill_round_rect(
  6474. l->ui, dot, 4,
  6475. 4, 4, 4,
  6476. l->ui->theme.accent);
  6477. else
  6478. ngui_fill_rect(l->ui,
  6479. dot,
  6480. l->ui->theme.accent);
  6481. }
  6482. } else {
  6483. int editable =
  6484. r->form_kind == FORM_TEXT ||
  6485. r->form_kind == FORM_PASSWORD ||
  6486. r->form_kind == FORM_TEXTAREA;
  6487. int scroll = 0;
  6488. /* Editable fields draw the live value
  6489. * (r->lit is a short copy). */
  6490. static char shown[FORM_VALUE_MAX + 1];
  6491. const char *txt = r->lit;
  6492. unsigned int tl = s_len(r->lit);
  6493. if (editable && fs && fs->len) {
  6494. unsigned int k;
  6495. if (r->form_kind == FORM_PASSWORD) {
  6496. for (k = 0; k < fs->len; k++)
  6497. shown[k] = '*';
  6498. shown[k] = '\0';
  6499. txt = shown;
  6500. } else {
  6501. txt = fs->value;
  6502. }
  6503. tl = fs->len;
  6504. }
  6505. struct br_style fst;
  6506. int author, tx = x + 6, pr = 6;
  6507. style_for_node(node, &fst);
  6508. author = form_author_styled(&fst);
  6509. if (author) {
  6510. /* The page styled the control:
  6511. * its background, border, radius
  6512. * and text colour. */
  6513. form_paint_author(l->ui, box, &fst,
  6514. focused);
  6515. tx = x + fst.border_w[3] +
  6516. mp_px(&fst, 7, w);
  6517. pr = fst.border_w[1] +
  6518. mp_px(&fst, 5, w);
  6519. if (tx < x + 2 && !editable)
  6520. tx = x + 2;
  6521. if (!disabled)
  6522. fg = editable && fs &&
  6523. !fs->len ?
  6524. 0x8410 : fst.color;
  6525. if (!editable) {
  6526. int tw0 = (int)
  6527. run_text_width(l->ui,
  6528. r, txt, tl);
  6529. tx = x + (w - tw0) / 2;
  6530. }
  6531. } else {
  6532. /* The box is drawn in theme colours, so
  6533. * the text is too: the page's CSS colour
  6534. * (dark on a light page) would vanish on
  6535. * the dark field. */
  6536. if (!disabled)
  6537. fg = editable && fs && !fs->len ?
  6538. l->ui->theme.text_dim :
  6539. l->ui->theme.text;
  6540. ngui_fill_rect(l->ui, box, bg);
  6541. ngui_frame(l->ui, box,
  6542. focused ? l->ui->theme.accent :
  6543. l->ui->theme.border);
  6544. }
  6545. /* A value wider than the field shows its
  6546. * tail (where typing happens). */
  6547. if (editable && fs && fs->len &&
  6548. w > (tx - x) + pr) {
  6549. int tw = (int)run_text_width(l->ui,
  6550. r, txt, tl);
  6551. int room = w - (tx - x) - pr;
  6552. if (tw > room)
  6553. scroll = tw - room;
  6554. }
  6555. ngui_push_clip(l->ui, (struct ngui_rect){
  6556. x + 1, ry + 1,
  6557. w > 2 ? w - 2 : 1,
  6558. hh > 2 ? hh - 2 : 1 });
  6559. ngui_text_px_face(l->ui, run_face(r),
  6560. tx - scroll,
  6561. ry + (hh - r->font_px) / 2 - 1,
  6562. txt, tl, fg, r->font_px,
  6563. r->bold, r->italic, r->mono);
  6564. if (focused && fs && editable) {
  6565. int cw = 0;
  6566. if (fs->len && fs->caret)
  6567. cw = (int)run_text_width(
  6568. l->ui, r, txt,
  6569. fs->caret < fs->len ?
  6570. fs->caret : fs->len);
  6571. ngui_fill_rect(l->ui,
  6572. (struct ngui_rect){
  6573. tx + cw - scroll,
  6574. ry + 4, 1,
  6575. hh > 8 ? hh - 8 : 1
  6576. },
  6577. l->ui->theme.accent);
  6578. }
  6579. ngui_pop_clip(l->ui);
  6580. if (r->form_kind == FORM_SELECT) {
  6581. ngui_text_px(l->ui, x + w - 12,
  6582. ry + 2, "v", 1, fg,
  6583. r->font_px, 0, 0, 0);
  6584. }
  6585. }
  6586. } else if (r->img == RUN_PBOX) {
  6587. struct ngui_rect bx = { x, ry, w, r->ih };
  6588. ngui_push_clip(l->ui, bx);
  6589. if (r->pb_has_bg)
  6590. ngui_fill_rect(l->ui, bx, r->pb_bg);
  6591. if (r->pb_img >= 0 && r->pb_img < image_count &&
  6592. images[r->pb_img].state == 1) {
  6593. /* Rotate about the box centre: the
  6594. * image is centred in it here. */
  6595. draw_image_transformed(l->ui,
  6596. &images[r->pb_img].img,
  6597. x + r->pb_x, ry + r->pb_y,
  6598. r->pb_w, r->pb_h,
  6599. r->transform_scale ?
  6600. r->scale_x : 100,
  6601. r->transform_scale ?
  6602. r->scale_y : 100,
  6603. r->transform_scale ?
  6604. r->rotate_x100 : 0,
  6605. 50, 50, 1, 1);
  6606. }
  6607. ngui_pop_clip(l->ui);
  6608. } else if (r->img == RUN_SVG) {
  6609. struct br_style sst;
  6610. style_for_node(r->off, &sst);
  6611. svg_paint_box(l->ui, r->off, &sst, x, ry, w,
  6612. r->ih);
  6613. } else if (r->img == -2) {
  6614. int hh = r->ih ? r->ih : 20;
  6615. ngui_fill_rect(l->ui,
  6616. (struct ngui_rect){x, ry, w, hh},
  6617. l->ui->theme.panel_alt);
  6618. ngui_frame(l->ui,
  6619. (struct ngui_rect){x, ry, w, hh},
  6620. l->ui->theme.border);
  6621. ngui_text_px_face(l->ui, run_face(r),
  6622. x + 6, ry + 2, r->lit,
  6623. s_len(r->lit), r->color,
  6624. r->font_px, r->bold, r->italic,
  6625. r->mono);
  6626. } else if (r->img >= 0) {
  6627. struct br_image *bi = &images[r->img];
  6628. if (bi->state == 1 && r->transform_scale) {
  6629. draw_image_transformed(l->ui, &bi->img,
  6630. x, ry, r->iw, r->ih,
  6631. r->scale_x, r->scale_y,
  6632. r->rotate_x100, r->origin_x,
  6633. r->origin_y, r->origin_x_kind,
  6634. r->origin_y_kind);
  6635. } else if (bi->state == 1) {
  6636. struct img_image *src =
  6637. image_display_get(bi, r->iw, r->ih);
  6638. struct img_blit b;
  6639. if (!src)
  6640. src = &bi->img;
  6641. b.dst = l->ui->px;
  6642. b.dst_w = l->ui->w;
  6643. b.dst_h = l->ui->h;
  6644. b.clip_x = page_rect.x;
  6645. b.clip_y = page_rect.y;
  6646. b.clip_w = page_rect.w - 12;
  6647. b.clip_h = page_rect.h;
  6648. b.x = x;
  6649. b.y = ry;
  6650. b.scale = ((unsigned int)r->iw << 16) /
  6651. src->w;
  6652. b.bg = ui.theme.bg;
  6653. b.bg2 = ui.theme.bg;
  6654. b.dst_a = 0;
  6655. b.flags = src->alpha ?
  6656. IMG_BLIT_OVER_DST : 0;
  6657. img_draw(src, &b);
  6658. }
  6659. } else {
  6660. const char *s = r->has_lit ? r->lit :
  6661. doc.text + r->off;
  6662. unsigned int n = r->has_lit ? s_len(r->lit) :
  6663. r->len;
  6664. ngui_text_px_face(l->ui, run_face(r), x, ry,
  6665. s, n, r->color, r->font_px,
  6666. r->bold, r->italic, r->mono);
  6667. if (r->underline)
  6668. ngui_fill_rect(l->ui,
  6669. (struct ngui_rect){x,
  6670. ry + run_ascent(l->ui, r) + 2,
  6671. w, 1}, r->color);
  6672. if (r->strike)
  6673. ngui_fill_rect(l->ui,
  6674. (struct ngui_rect){x,
  6675. ry + run_ascent(l->ui, r) -
  6676. (r->font_px > 3 ?
  6677. r->font_px / 3 : 1),
  6678. w, 1}, r->color);
  6679. if (r->overline)
  6680. ngui_fill_rect(l->ui,
  6681. (struct ngui_rect){x, ry,
  6682. w, 1}, r->color);
  6683. }
  6684. if (r->form || r->href) {
  6685. if (nhits < HIT_MAX) {
  6686. struct hit *h = &hits[nhits];
  6687. unsigned int target = r->form ?
  6688. r->form - 1 : r->href;
  6689. int hh = (r->form || r->img >= 0 ||
  6690. r->img == RUN_SVG) ?
  6691. r->ih :
  6692. run_line_height(l->ui, r);
  6693. int merge = nhits > 0 &&
  6694. hits[nhits - 1].node == target &&
  6695. hits[nhits - 1].y == ry &&
  6696. hits[nhits - 1].h == hh &&
  6697. x <= hits[nhits - 1].x +
  6698. hits[nhits - 1].w + 2;
  6699. if (merge) {
  6700. struct hit *p = &hits[nhits - 1];
  6701. int end = x + w;
  6702. if (end > p->x + p->w)
  6703. p->w = end - p->x;
  6704. } else {
  6705. h->x = x;
  6706. h->y = ry;
  6707. h->w = w;
  6708. h->h = hh;
  6709. h->node = (unsigned short)target;
  6710. nhits++;
  6711. }
  6712. }
  6713. }
  6714. }
  6715. if (r->box)
  6716. inline_box_add(l, r->box, x, w);
  6717. x += w;
  6718. }
  6719. l->y += l->line_h + 2;
  6720. if (l->float_active && l->y >= l->float_bottom)
  6721. l->float_active = 0;
  6722. l->nruns = 0;
  6723. l->line_x = l->left;
  6724. l->run_x = l->left;
  6725. l->line_left = l->left;
  6726. l->line_right = l->right;
  6727. l->line_h = 0;
  6728. l->space_pending = 0;
  6729. }
  6730. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  6731. const struct br_style *st, unsigned short href,
  6732. const char *lit)
  6733. {
  6734. unsigned int n = lit ? s_len(lit) : len;
  6735. const char *tp = lit ? lit : doc.text + off;
  6736. int w = (int)face_text_width(l->ui, st, tp, n);
  6737. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6738. flush_line(l);
  6739. if (l->nruns == 0) {
  6740. l->line_y = l->y;
  6741. l->line_h = 0;
  6742. start_line(l, st);
  6743. }
  6744. {
  6745. struct lay_run *r = &l->runs[l->nruns++];
  6746. int gap = l->line_x - l->run_x;
  6747. if (gap < 0)
  6748. gap = 0;
  6749. r->box = l->box_owner;
  6750. r->gap = (unsigned short)gap;
  6751. r->off = off;
  6752. r->len = len;
  6753. r->color = st->color;
  6754. r->href = href;
  6755. r->dy = 0;
  6756. r->has_lit = 0;
  6757. r->form = 0;
  6758. r->form_kind = 0;
  6759. r->form_disabled = 0;
  6760. r->lit[0] = '\0';
  6761. if (lit && lit[0]) {
  6762. unsigned int i;
  6763. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  6764. r->lit[i] = lit[i];
  6765. r->lit[i] = '\0';
  6766. r->has_lit = 1;
  6767. }
  6768. r->img = -1;
  6769. r->iw = r->ih = 0;
  6770. r->font_px = st->font_px;
  6771. r->bold = st->bold;
  6772. r->italic = st->italic;
  6773. r->mono = st->mono;
  6774. r->font_face = st->font_face;
  6775. /* A control with its own background is a button, not body copy;
  6776. * an inherited link underline would strike through the fill. */
  6777. r->underline = st->underline && !st->has_bg;
  6778. r->strike = st->strike && !st->has_bg;
  6779. r->overline = st->overline && !st->has_bg;
  6780. r->w = (unsigned short)w;
  6781. if (r->has_lit)
  6782. r->w = (unsigned short)run_text_width(
  6783. l->ui, r, r->lit, s_len(r->lit));
  6784. w = r->w;
  6785. }
  6786. l->line_x += w;
  6787. l->run_x = l->line_x;
  6788. {
  6789. int lh = face_line_height(l->ui, st);
  6790. if (st->line_h_px)
  6791. lh = st->line_h_px;
  6792. else if (st->line_h_pct)
  6793. lh = st->font_px * st->line_h_pct / 100;
  6794. if (lh < face_line_height(l->ui, st))
  6795. lh = face_line_height(l->ui, st);
  6796. if (l->line_h < lh)
  6797. l->line_h = lh;
  6798. }
  6799. }
  6800. static void add_image_run(struct lay *l, unsigned int node,
  6801. const struct br_style *st, unsigned short href)
  6802. {
  6803. struct br_image *bi = 0;
  6804. int idx = doc.nodes[node].img_index;
  6805. int dw, dh, maxw;
  6806. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  6807. bi = &images[idx];
  6808. if (l->nruns == 0)
  6809. start_line(l, st);
  6810. if (l->space_pending &&
  6811. (l->nruns > 0 || l->line_x > l->line_left)) {
  6812. int sp = (int)face_text_width(l->ui, st, " ", 1);
  6813. if (l->line_x + sp <= l->line_right)
  6814. l->line_x += sp;
  6815. }
  6816. l->space_pending = 0;
  6817. if (!bi) {
  6818. const char *alt = br_alt(&doc, node);
  6819. struct br_style gs = *st;
  6820. char tmp[96];
  6821. unsigned int n = 0;
  6822. int w;
  6823. gs.color = BR_GRAY;
  6824. gs.underline = 0;
  6825. s_append(tmp, &n, "[", sizeof(tmp));
  6826. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  6827. s_append(tmp, &n, "]", sizeof(tmp));
  6828. w = (int)face_text_width(l->ui, &gs, tmp, n);
  6829. if (l->line_x + w > l->line_right &&
  6830. (l->nruns > 0 || l->line_x > l->line_left))
  6831. flush_line(l);
  6832. add_run(l, 0, 0, &gs, href, tmp);
  6833. if (!l->draw) {
  6834. int t = l->line_y < 0 ? 0 : l->line_y;
  6835. int hh = face_line_height(l->ui, &gs);
  6836. if (t > 65535)
  6837. t = 65535;
  6838. if (hh > 65535)
  6839. hh = 65535;
  6840. img_top[node] = (unsigned short)t;
  6841. img_h[node] = (unsigned short)hh;
  6842. }
  6843. return;
  6844. }
  6845. maxw = l->line_right - l->line_left;
  6846. if (maxw < 8)
  6847. maxw = 8;
  6848. {
  6849. int iw = bi->native_w, ih = bi->native_h;
  6850. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  6851. if (iw <= 0 || ih <= 0) {
  6852. iw = (int)bi->img.w;
  6853. ih = (int)bi->img.h;
  6854. }
  6855. dw = iw;
  6856. dh = ih;
  6857. if (doc.nodes[node].width_attr) {
  6858. int want = doc.nodes[node].width_attr;
  6859. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  6860. have_w = 1;
  6861. }
  6862. if (doc.nodes[node].height_attr) {
  6863. int want = doc.nodes[node].height_attr;
  6864. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  6865. have_h = 1;
  6866. }
  6867. if (have_w && !have_h)
  6868. dh = ih ? ih * dw / iw : 0;
  6869. if (have_h && !have_w)
  6870. dw = iw ? iw * dh / ih : 0;
  6871. if (st->width_kind) {
  6872. css_w = 1;
  6873. if (st->width_kind == 3)
  6874. dw = maxw * st->width_calc_pct / 100 +
  6875. st->width_calc_px;
  6876. else
  6877. dw = st->width_kind == 2 ?
  6878. maxw * (int)st->width / 100 :
  6879. (int)st->width;
  6880. }
  6881. /* Percentage heights resolve against the containing block's
  6882. * definite height (Docusaurus' logo: `.navbar__logo { height:
  6883. * 2rem }` holding an `img { height: 100% }`), and are auto
  6884. * when it has none; they used to use the width. */
  6885. if (st->height_kind == 1 ||
  6886. ((st->height_kind == 2 || st->height_kind == 3) &&
  6887. l->cb_h > 0)) {
  6888. css_h = 1;
  6889. if (st->height_kind == 3)
  6890. dh = l->cb_h * st->height_calc_pct / 100 +
  6891. st->height_calc_px;
  6892. else
  6893. dh = st->height_kind == 2 ?
  6894. l->cb_h * (int)st->height / 100 :
  6895. (int)st->height;
  6896. }
  6897. if (css_w && !css_h)
  6898. dh = ih ? ih * dw / iw : 0;
  6899. if (css_h && !css_w)
  6900. dw = iw ? iw * dh / ih : 0;
  6901. if (st->max_width_kind) {
  6902. int mw = st->max_width_kind == 3 ?
  6903. maxw * st->max_width_calc_pct / 100 +
  6904. st->max_width_calc_px :
  6905. st->max_width_kind == 2 ?
  6906. maxw * (int)st->max_width / 100 :
  6907. (int)st->max_width;
  6908. if (mw > 0 && dw > mw) {
  6909. dh = iw ? ih * mw / iw : 0;
  6910. dw = mw;
  6911. }
  6912. }
  6913. }
  6914. if (dw < 8)
  6915. dw = 8;
  6916. if (dh < 8)
  6917. dh = 8;
  6918. if (dw > maxw) {
  6919. dh = dw ? dh * maxw / dw : dh;
  6920. dw = maxw;
  6921. }
  6922. if (!l->draw) {
  6923. int t = l->line_y < 0 ? 0 : l->line_y;
  6924. if (t > 65535)
  6925. t = 65535;
  6926. if (dh > 65535)
  6927. dh = 65535;
  6928. img_top[node] = (unsigned short)t;
  6929. img_h[node] = (unsigned short)dh;
  6930. }
  6931. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  6932. l->line_x > l->line_left))
  6933. flush_line(l);
  6934. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6935. flush_line(l);
  6936. if (l->nruns == 0) {
  6937. l->line_y = l->y;
  6938. l->line_h = 0;
  6939. start_line(l, st);
  6940. }
  6941. {
  6942. struct lay_run *r = &l->runs[l->nruns++];
  6943. int gap = l->line_x - l->run_x;
  6944. if (gap < 0)
  6945. gap = 0;
  6946. r->box = l->box_owner;
  6947. r->gap = (unsigned short)gap;
  6948. r->off = 0;
  6949. r->len = 0;
  6950. r->color = 0;
  6951. r->href = href;
  6952. r->form = 0;
  6953. r->form_kind = 0;
  6954. r->form_disabled = 0;
  6955. /* Inline replaced elements honour their vertical margins; this
  6956. * is how Bootstrap's negative logo margins centre the wordmark. */
  6957. {
  6958. int idy = mp_px(st, 0, l->right - l->left);
  6959. if (idy < -2048)
  6960. idy = -2048;
  6961. if (idy > 2048)
  6962. idy = 2048;
  6963. r->dy = (signed short)idy;
  6964. }
  6965. r->has_lit = 0;
  6966. r->lit[0] = '\0';
  6967. r->img = (short)idx;
  6968. r->iw = (unsigned short)dw;
  6969. r->ih = (unsigned short)dh;
  6970. r->w = (unsigned short)dw;
  6971. r->font_px = st->font_px;
  6972. r->bold = st->bold;
  6973. r->italic = st->italic;
  6974. r->mono = st->mono;
  6975. r->font_face = st->font_face;
  6976. r->transform_scale = st->transform_scale;
  6977. r->scale_x = st->scale_x;
  6978. r->scale_y = st->scale_y;
  6979. r->rotate_x100 = st->rotate_x100;
  6980. r->origin_x = st->origin_x;
  6981. r->origin_y = st->origin_y;
  6982. r->origin_x_kind = st->origin_x_kind;
  6983. r->origin_y_kind = st->origin_y_kind;
  6984. r->underline = 0;
  6985. }
  6986. if (node < BR_MAX_NODES) {
  6987. layout_boxes[node].x = l->line_x;
  6988. layout_boxes[node].y = l->line_y +
  6989. mp_px(st, 0, l->right - l->left);
  6990. layout_boxes[node].w = dw;
  6991. layout_boxes[node].h = dh;
  6992. layout_boxes[node].valid = 1;
  6993. }
  6994. l->line_x += dw;
  6995. l->run_x = l->line_x;
  6996. if (l->line_h < dh)
  6997. l->line_h = dh;
  6998. }
  6999. /* An inline (or inline-block) <svg> is a replaced element in the text
  7000. * line, like an <img>: comment bubbles and arrows sit next to their label
  7001. * instead of starting a block of their own. */
  7002. static void add_svg_run(struct lay *l, unsigned int node,
  7003. const struct br_style *st, unsigned short href)
  7004. {
  7005. struct lay_run *r;
  7006. int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
  7007. if (lw < 8)
  7008. lw = 8;
  7009. cw = st->width_kind ? style_width_px(st, lw) : lw;
  7010. if (cw < 1)
  7011. cw = 1;
  7012. svg_size(node, st, cw, &dw, &dh);
  7013. if (dw > lw)
  7014. dw = lw;
  7015. ml = mp_px(st, 3, lw);
  7016. mr = mp_px(st, 1, lw);
  7017. if (ml < 0)
  7018. ml = 0;
  7019. if (mr < 0)
  7020. mr = 0;
  7021. if (l->line_x + ml + dw > l->line_right &&
  7022. (l->nruns > 0 || l->line_x > l->line_left))
  7023. flush_line(l);
  7024. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  7025. flush_line(l);
  7026. if (l->nruns == 0) {
  7027. l->line_y = l->y;
  7028. l->line_h = 0;
  7029. start_line(l, st);
  7030. }
  7031. l->line_x += ml;
  7032. r = &l->runs[l->nruns++];
  7033. memset(r, 0, sizeof(*r));
  7034. r->box = l->box_owner;
  7035. r->gap = (unsigned short)(l->line_x > l->run_x ?
  7036. l->line_x - l->run_x : 0);
  7037. r->off = node;
  7038. r->color = st->color;
  7039. r->href = href;
  7040. r->img = RUN_SVG;
  7041. r->iw = (unsigned short)dw;
  7042. r->ih = (unsigned short)dh;
  7043. r->w = (unsigned short)dw;
  7044. r->font_px = st->font_px;
  7045. if (node < BR_MAX_NODES) {
  7046. layout_boxes[node].x = l->line_x;
  7047. layout_boxes[node].y = l->line_y;
  7048. layout_boxes[node].w = dw;
  7049. layout_boxes[node].h = dh;
  7050. layout_boxes[node].valid = 1;
  7051. }
  7052. l->line_x += dw + mr;
  7053. l->run_x = l->line_x;
  7054. if (l->line_h < dh)
  7055. l->line_h = dh;
  7056. }
  7057. static int text_width(struct lay *l, const char *s, unsigned int n,
  7058. const struct br_style *st)
  7059. {
  7060. return (int)face_text_width(l->ui, st, s, n);
  7061. }
  7062. /* Longest prefix that fits in maxw, at least one byte. */
  7063. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  7064. const struct br_style *st, int maxw)
  7065. {
  7066. unsigned int take = 0;
  7067. while (take < n) {
  7068. if (text_width(l, s, take + 1, st) > maxw)
  7069. break;
  7070. take++;
  7071. }
  7072. return take ? take : 1;
  7073. }
  7074. static void emit_word(struct lay *l, const char *s, unsigned int start,
  7075. unsigned int n, unsigned int base,
  7076. const struct br_style *st, unsigned short href)
  7077. {
  7078. int avail;
  7079. int w = text_width(l, s + start, n, st);
  7080. unsigned int off = start;
  7081. if (l->nruns == 0)
  7082. start_line(l, st);
  7083. avail = l->line_right - l->line_left;
  7084. if (st->nowrap) {
  7085. if (n)
  7086. add_run(l, base + start,
  7087. (unsigned short)n, st, href, 0);
  7088. return;
  7089. }
  7090. /* A padded/bordered one-word button can be a few pixels wider than
  7091. * the content box; keep it on one line instead of splitting it. */
  7092. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  7093. add_run(l, base + start,
  7094. (unsigned short)n, st, href, 0);
  7095. return;
  7096. }
  7097. if (l->line_x + w > l->line_right &&
  7098. (l->nruns > 0 || l->line_x > l->line_left)) {
  7099. flush_line(l);
  7100. start_line(l, st);
  7101. avail = l->line_right - l->line_left;
  7102. }
  7103. if (w <= avail) {
  7104. if (n)
  7105. add_run(l, base + start,
  7106. (unsigned short)n, st, href, 0);
  7107. return;
  7108. }
  7109. while (n > 0) {
  7110. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  7111. add_run(l, base + off,
  7112. (unsigned short)take, st, href, 0);
  7113. off += take;
  7114. n -= take;
  7115. if (n) {
  7116. flush_line(l);
  7117. start_line(l, st);
  7118. avail = l->line_right - l->line_left;
  7119. }
  7120. }
  7121. }
  7122. static void emit_text(struct lay *l, const char *s, unsigned int len,
  7123. const struct br_style *st, unsigned short href, int pre)
  7124. {
  7125. unsigned int i = 0;
  7126. unsigned int base;
  7127. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  7128. if (!s || !len)
  7129. return;
  7130. if (space_w <= 0)
  7131. space_w = 8;
  7132. if (l->nruns == 0)
  7133. start_line(l, st);
  7134. base = (unsigned int)(s - doc.text);
  7135. if (st->uppercase) {
  7136. char *p = (char *)s;
  7137. unsigned int j;
  7138. for (j = 0; j < len; j++)
  7139. if (p[j] >= 'a' && p[j] <= 'z')
  7140. p[j] = (char)(p[j] - 'a' + 'A');
  7141. }
  7142. if (pre) {
  7143. while (i < len) {
  7144. unsigned int start;
  7145. if (s[i] == '\n') {
  7146. flush_line(l);
  7147. start_line(l, st);
  7148. i++;
  7149. continue;
  7150. }
  7151. if (s[i] == ' ') {
  7152. if (l->line_x + space_w > l->line_right &&
  7153. (l->nruns > 0 || l->line_x > l->line_left)) {
  7154. flush_line(l);
  7155. start_line(l, st);
  7156. } else {
  7157. l->line_x += space_w;
  7158. }
  7159. i++;
  7160. continue;
  7161. }
  7162. start = i;
  7163. while (i < len && s[i] != ' ' && s[i] != '\n')
  7164. i++;
  7165. emit_word(l, s, start, i - start, base, st, href);
  7166. }
  7167. return;
  7168. }
  7169. while (i < len) {
  7170. unsigned int start, n;
  7171. if (s[i] == ' ') {
  7172. l->space_pending = 1;
  7173. i++;
  7174. continue;
  7175. }
  7176. start = i;
  7177. while (i < len && s[i] != ' ')
  7178. i++;
  7179. n = i - start;
  7180. if (l->space_pending &&
  7181. (l->nruns > 0 || l->line_x > l->line_left)) {
  7182. if (st->nowrap ||
  7183. l->line_x + space_w <= l->line_right)
  7184. l->line_x += space_w;
  7185. }
  7186. l->space_pending = 0;
  7187. emit_word(l, s, start, n, base, st, href);
  7188. }
  7189. }
  7190. static int list_index(unsigned int parent, unsigned int node)
  7191. {
  7192. unsigned int n = 0, i;
  7193. for (i = doc.nodes[parent].first; i && i != node;
  7194. i = doc.nodes[i].next)
  7195. if (doc.nodes[i].tag == BR_TAG_LI)
  7196. n++;
  7197. return (int)n + 1;
  7198. }
  7199. static void list_roman(char *m, unsigned int *n, int v, int upper,
  7200. unsigned int cap)
  7201. {
  7202. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  7203. 50, 40, 10, 9, 5, 4, 1 };
  7204. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  7205. "l", "xl", "x", "ix", "v", "iv", "i" };
  7206. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  7207. "L", "XL", "X", "IX", "V", "IV", "I" };
  7208. unsigned int i;
  7209. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  7210. while (v >= val[i] && *n + 1 < cap) {
  7211. const char *s = upper ? up[i] : lo[i];
  7212. while (*s && *n + 1 < cap)
  7213. m[(*n)++] = *s++;
  7214. v -= val[i];
  7215. }
  7216. }
  7217. }
  7218. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  7219. {
  7220. unsigned int n = 0;
  7221. if (style == BR_LIST_DISC) {
  7222. m[n++] = '-';
  7223. } else if (style == BR_LIST_CIRCLE) {
  7224. m[n++] = 'o';
  7225. } else if (style == BR_LIST_SQUARE) {
  7226. m[n++] = '+';
  7227. } else if (style == BR_LIST_LOWER_ALPHA ||
  7228. style == BR_LIST_UPPER_ALPHA) {
  7229. if (idx >= 1 && idx <= 26)
  7230. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  7231. 'A' : 'a') + idx - 1);
  7232. else
  7233. m[n++] = '?';
  7234. m[n++] = '.';
  7235. } else if (style == BR_LIST_LOWER_ROMAN ||
  7236. style == BR_LIST_UPPER_ROMAN) {
  7237. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  7238. if (n + 1 < cap)
  7239. m[n++] = '.';
  7240. } else {
  7241. s_append_dec(m, &n, (unsigned int)idx, cap);
  7242. if (n + 1 < cap)
  7243. m[n++] = '.';
  7244. }
  7245. m[n] = '\0';
  7246. }
  7247. /* A control the page styled itself (background, border or radius in author
  7248. * CSS -- `background:transparent;border:none` counts) is painted with that
  7249. * style, sized from its padding/height and keeps the page's text colour.
  7250. * Unstyled controls keep the ngui theme look. */
  7251. static int form_author_styled(const struct br_style *st)
  7252. {
  7253. int i;
  7254. if (st->bg_set)
  7255. return 1;
  7256. for (i = 0; i < 4; i++)
  7257. if (st->border_w[i] || st->radius[i])
  7258. return 1;
  7259. return 0;
  7260. }
  7261. /* Set by the layout when the control is stretched to its line: a flex item
  7262. * (its box width was assigned by the flex row) or a child of a flex column,
  7263. * whose default align-items: stretch makes inputs full width. */
  7264. static int form_fill_line;
  7265. static void add_form_run(struct lay *l, unsigned int node,
  7266. const struct br_style *st, unsigned short href)
  7267. {
  7268. struct form_state *fs = form_get(node, 1);
  7269. char shown[FORM_VALUE_MAX + 1];
  7270. char opt[64];
  7271. const char *text = "";
  7272. struct lay_run *r;
  7273. int kind = form_kind_of(node);
  7274. int disabled = form_disabled(node);
  7275. int author = form_author_styled(st);
  7276. int tw, w = 120, h = 20, i, line_w, pad_x, pad_y;
  7277. int ml = 0, mr = 0, mt = 0, mb = 0;
  7278. if (!fs)
  7279. return;
  7280. if (l->nruns == 0)
  7281. start_line(l, st);
  7282. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  7283. text = "";
  7284. w = 16;
  7285. h = 16;
  7286. } else if (kind == FORM_SELECT) {
  7287. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  7288. s_copy(opt, "Select", sizeof(opt));
  7289. text = opt;
  7290. w = 120;
  7291. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  7292. kind == FORM_RESET) {
  7293. if (fs->len)
  7294. text = fs->value;
  7295. else if (doc.nodes[node].tag == BR_TAG_BUTTON)
  7296. /* A <button>'s label is its content: an empty one
  7297. * (Docusaurus' sidebar caret, drawn by a CSS
  7298. * ::before icon) shows none. Only <input> buttons
  7299. * get the UA's default label. */
  7300. text = "";
  7301. else
  7302. text = kind == FORM_SUBMIT ? "Submit" :
  7303. kind == FORM_RESET ? "Reset" : "Button";
  7304. } else if (kind == FORM_PASSWORD) {
  7305. for (i = 0; i < fs->len; i++)
  7306. shown[i] = '*';
  7307. shown[fs->len] = '\0';
  7308. text = fs->len ? shown : br_placeholder(&doc, node);
  7309. } else {
  7310. if (fs->len)
  7311. text = fs->value;
  7312. else
  7313. text = br_placeholder(&doc, node);
  7314. if (kind == FORM_TEXTAREA) {
  7315. w = 180;
  7316. h = 40;
  7317. }
  7318. }
  7319. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  7320. line_w = l->line_right - l->line_left;
  7321. pad_x = mp_px(st, 7, line_w) + mp_px(st, 5, line_w) +
  7322. st->border_w[1] + st->border_w[3];
  7323. pad_y = mp_px(st, 4, line_w) + mp_px(st, 6, line_w) +
  7324. st->border_w[0] + st->border_w[2];
  7325. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  7326. /* Buttons are border-box in every UA stylesheet: an
  7327. * explicit width/height is the whole box. */
  7328. if (author || pad_x) {
  7329. w = tw + pad_x;
  7330. } else {
  7331. w = tw + 18;
  7332. if (w < 64)
  7333. w = 64;
  7334. }
  7335. if (st->width_kind)
  7336. w = style_width_px(st, line_w);
  7337. if (st->min_width_kind == 1 && w < (int)st->min_width)
  7338. w = st->min_width;
  7339. if (st->height_kind == 1)
  7340. h = st->height;
  7341. else if (author)
  7342. h = st->font_px + 6 + pad_y;
  7343. else
  7344. h = 22;
  7345. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  7346. kind == FORM_TEXTAREA) {
  7347. int fill = form_fill_line || st->display == BR_DISPLAY_BLOCK ||
  7348. st->display == BR_DISPLAY_FLEX;
  7349. int boxed = st->box_sizing ? 0 : pad_x;
  7350. if (st->width_kind)
  7351. w = style_width_px(st, line_w) + boxed;
  7352. else if (fill)
  7353. w = line_w - (l->line_x - l->line_left);
  7354. else
  7355. w = kind == FORM_TEXTAREA ? 180 : 120;
  7356. if (kind == FORM_TEXTAREA) {
  7357. const char *ra = br_find_attr(&doc, node, "rows");
  7358. int rows = 0;
  7359. int lh = st->line_h_px ? st->line_h_px :
  7360. st->font_px * 5 / 4;
  7361. while (ra && *ra >= '0' && *ra <= '9')
  7362. rows = rows * 10 + (*ra++ - '0');
  7363. if (rows < 1 || rows > 40)
  7364. rows = 2;
  7365. h = author ? rows * lh + pad_y : 40;
  7366. } else if (author) {
  7367. h = st->font_px + 8 + pad_y;
  7368. } else if (st->font_px + 8 > h) {
  7369. /* Taller fields for large text (min-height/padding
  7370. * on login pages): keep the box around the glyphs. */
  7371. h = st->font_px + 8;
  7372. }
  7373. if (st->height_kind == 1)
  7374. h = st->height + (st->box_sizing ? 0 : pad_y);
  7375. if (st->min_height_kind == 1 && h < (int)st->min_height)
  7376. h = st->min_height;
  7377. } else if (kind == FORM_SELECT) {
  7378. w = st->width_kind == 1 ? st->width : 120;
  7379. }
  7380. if (author) {
  7381. /* Inline margins (Google's `margin:11px 4px` between its
  7382. * two submit buttons). */
  7383. ml = mp_px(st, 3, line_w);
  7384. mr = mp_px(st, 1, line_w);
  7385. mt = mp_px(st, 0, line_w);
  7386. mb = mp_px(st, 2, line_w);
  7387. if (ml < 0 || ml > 64) ml = 0;
  7388. if (mr < 0 || mr > 64) mr = 0;
  7389. if (mt < 0 || mt > 64) mt = 0;
  7390. if (mb < 0 || mb > 64) mb = 0;
  7391. }
  7392. if (w > line_w - ml - mr)
  7393. w = line_w - ml - mr;
  7394. if (w < 8)
  7395. w = 8;
  7396. if (h > 400)
  7397. h = 400;
  7398. if (l->line_x + ml + w > l->line_right &&
  7399. (l->nruns > 0 || l->line_x > l->line_left))
  7400. flush_line(l);
  7401. if (l->nruns >= 96)
  7402. return;
  7403. if (l->nruns == 0) {
  7404. l->line_y = l->y;
  7405. l->line_h = 0;
  7406. start_line(l, st);
  7407. }
  7408. l->line_x += ml;
  7409. r = &l->runs[l->nruns++];
  7410. r->box = l->box_owner;
  7411. r->gap = (unsigned short)(l->line_x - l->run_x);
  7412. r->off = r->len = 0;
  7413. r->color = st->color;
  7414. r->href = href;
  7415. r->dy = (signed short)mt;
  7416. r->has_lit = 1;
  7417. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  7418. r->lit[i] = text[i];
  7419. r->lit[i] = '\0';
  7420. r->img = -2;
  7421. r->iw = (unsigned short)w;
  7422. r->ih = (unsigned short)h;
  7423. r->w = (unsigned short)w;
  7424. r->font_px = st->font_px;
  7425. r->bold = st->bold;
  7426. r->italic = st->italic;
  7427. r->mono = st->mono;
  7428. r->font_face = st->font_face;
  7429. r->underline = 0;
  7430. r->form = node + 1;
  7431. r->form_kind = (unsigned char)kind;
  7432. r->form_disabled = (unsigned char)disabled;
  7433. if (node < BR_MAX_NODES) {
  7434. layout_boxes[node].x = l->line_x;
  7435. layout_boxes[node].y = l->line_y + mt;
  7436. layout_boxes[node].w = w;
  7437. layout_boxes[node].h = h;
  7438. layout_boxes[node].valid = 1;
  7439. }
  7440. l->line_x += w;
  7441. l->run_x = l->line_x;
  7442. l->line_x += mr;
  7443. if (l->line_h < h + mt + mb)
  7444. l->line_h = h + mt + mb;
  7445. }
  7446. /* Background, border and corner radius of an author-styled control, the
  7447. * same decoration rules as a block box. */
  7448. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  7449. const struct br_style *st, int focused)
  7450. {
  7451. int rtl = css_radius(st, 0, box.w, box.h);
  7452. int rtr = css_radius(st, 1, box.w, box.h);
  7453. int rbr = css_radius(st, 2, box.w, box.h);
  7454. int rbl = css_radius(st, 3, box.w, box.h);
  7455. int bw = st->border_t[0] ? 0 : st->border_w[0];
  7456. (void)focused;
  7457. if (box.w <= 0 || box.h <= 0)
  7458. return;
  7459. if (rtl || rtr || rbr || rbl) {
  7460. if (bw > 0 && st->has_bg && st->border_c[0] != st->bg &&
  7461. box.w > bw * 2 && box.h > bw * 2) {
  7462. struct ngui_rect in = { box.x + bw, box.y + bw,
  7463. box.w - bw * 2,
  7464. box.h - bw * 2 };
  7465. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  7466. st->border_c[0]);
  7467. ngui_fill_round_rect(ui, in,
  7468. rtl > bw ? rtl - bw : 0,
  7469. rtr > bw ? rtr - bw : 0,
  7470. rbr > bw ? rbr - bw : 0,
  7471. rbl > bw ? rbl - bw : 0, st->bg);
  7472. } else if (st->has_bg) {
  7473. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  7474. st->bg);
  7475. } else if (bw > 0) {
  7476. ngui_frame_round(ui, box, rtl, rtr, rbr, rbl, bw,
  7477. st->border_c[0]);
  7478. }
  7479. return;
  7480. }
  7481. if (st->has_bg)
  7482. ngui_fill_rect(ui, box, st->bg);
  7483. if (st->border_w[0] || st->border_w[1] || st->border_w[2] ||
  7484. st->border_w[3])
  7485. draw_border_box(ui, box, st);
  7486. }
  7487. /* A poster wrapper is absolutely positioned over the media slot; the
  7488. * measured height of its picture is normally added back to the flow. When a
  7489. * loading-skeleton sibling already reserves that slot, adding both doubles
  7490. * the media height and pushes the article text a full screen down. */
  7491. static int has_skeleton_sibling(unsigned int node)
  7492. {
  7493. unsigned int p = doc.nodes[node].parent, c;
  7494. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  7495. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  7496. continue;
  7497. if (doc.nodes[c].class_off &&
  7498. contains_ci(doc.attrs + doc.nodes[c].class_off,
  7499. "skeleton"))
  7500. return 1;
  7501. }
  7502. return 0;
  7503. }
  7504. static void layout_children(struct lay *l, unsigned int parent,
  7505. const struct br_style *pst, int depth,
  7506. unsigned short link);
  7507. static void layout_flex_children(struct lay *l, unsigned int parent,
  7508. const struct br_style *pst, int depth,
  7509. unsigned short link);
  7510. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  7511. struct br_style *ps, int base);
  7512. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  7513. const struct br_style *ps, unsigned short link);
  7514. static void layout_grid_children(struct lay *l, unsigned int parent,
  7515. const struct br_style *pst, int depth,
  7516. unsigned short link);
  7517. static void layout_grid_auto(struct lay *l, unsigned int parent,
  7518. const struct br_style *pst, int depth,
  7519. unsigned short link);
  7520. static int flex_item_width(struct lay *l, unsigned int n,
  7521. const struct br_style *cs, int avail);
  7522. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  7523. const struct br_style *pst, int depth,
  7524. unsigned short link);
  7525. static void layout_table_row(struct lay *l, unsigned int row,
  7526. const struct br_style *pst, int depth,
  7527. unsigned short link);
  7528. static int table_has_rowspan(unsigned int table);
  7529. static void layout_table(struct lay *l, unsigned int table,
  7530. const struct br_style *st, int depth,
  7531. unsigned short link);
  7532. /* A flex container whose items are only inline spans is usually just a
  7533. * heading/icon pair. Our flex row positions such items without emitting
  7534. * their inline text in some deep page contexts; normal inline flow renders
  7535. * the same content correctly. */
  7536. static int layout_out_of_flow(struct lay *l, unsigned int n,
  7537. const struct br_style *cs, int depth,
  7538. unsigned short lk);
  7539. static void layout_flex_column(struct lay *l, unsigned int parent,
  7540. const struct br_style *pst, int depth,
  7541. unsigned short link);
  7542. static void emit_pseudo(struct lay *l, unsigned int node,
  7543. const struct br_style *st, int pe, unsigned short link);
  7544. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  7545. {
  7546. unsigned int c;
  7547. int items = 0;
  7548. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7549. struct br_node *nd = &doc.nodes[c];
  7550. struct br_style cs;
  7551. if (nd->type == BR_NODE_TEXT)
  7552. continue;
  7553. br_style_for(&doc, c, pst, &cs);
  7554. if (cs.display == BR_DISPLAY_NONE)
  7555. continue;
  7556. /* `justify-content: space-between` spreads even two plain
  7557. * inline items (a "Password ... Reset password" label row)
  7558. * across the line; inline flow would set them side by side. */
  7559. if (++items >= 2 && pst->justify >= 3)
  7560. return 1;
  7561. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  7562. cs.width_kind || cs.has_bg ||
  7563. cs.border_w[0] || cs.border_w[1] ||
  7564. cs.border_w[2] || cs.border_w[3] ||
  7565. nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG)
  7566. return 1;
  7567. }
  7568. return 0;
  7569. }
  7570. static int css_radius(const struct br_style *st, int corner,
  7571. int w, int h)
  7572. {
  7573. int r = st->radius[corner];
  7574. if (r <= 0)
  7575. return 0;
  7576. if (r > w / 2)
  7577. r = w / 2;
  7578. if (r > h / 2)
  7579. r = h / 2;
  7580. return r;
  7581. }
  7582. /* ---- inline SVG ----
  7583. *
  7584. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  7585. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  7586. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  7587. * opacity and solid paint; a gradient paints the average of its stops) and
  7588. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  7589. #define SVG_CACHE_MAX 48
  7590. #define SVG_CACHE_PIXELS (640 * 1024)
  7591. #define SVG_MAX_POINTS 24576
  7592. struct svg_cache_ent {
  7593. unsigned int node;
  7594. int w, h;
  7595. unsigned short *px;
  7596. unsigned char *a;
  7597. unsigned int stamp;
  7598. };
  7599. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  7600. static unsigned int svg_cache_pixels, svg_cache_clock;
  7601. static struct svgr svg_geom;
  7602. static void *svg_geom_buf;
  7603. /* Current viewport in user units: percentage lengths resolve against it
  7604. * (the viewBox size, not the device pixels). */
  7605. static double svg_vp_w = 300, svg_vp_h = 150;
  7606. /* The layers live in the page heap: forget them before heap_reset(). */
  7607. static void svg_cache_clear(void)
  7608. {
  7609. memset(svg_cache, 0, sizeof(svg_cache));
  7610. svg_cache_pixels = 0;
  7611. svg_geom_buf = 0;
  7612. }
  7613. static int svg_name_is(const char *a, const char *b)
  7614. {
  7615. while (*a && *b) {
  7616. char x = *a, y = *b;
  7617. if (x >= 'A' && x <= 'Z')
  7618. x = (char)(x - 'A' + 'a');
  7619. if (x != y)
  7620. return 0;
  7621. a++;
  7622. b++;
  7623. }
  7624. return *a == *b;
  7625. }
  7626. static const char *svg_elem_name(unsigned int node)
  7627. {
  7628. const struct br_node *nd = &doc.nodes[node];
  7629. if (nd->name_off)
  7630. return doc.attrs + nd->name_off;
  7631. return br_tag_name(nd->tag);
  7632. }
  7633. /* A numeric attribute; a percentage resolves against `base`. */
  7634. static double svg_attr_num(unsigned int node, const char *name, double def,
  7635. double base)
  7636. {
  7637. const char *v = br_find_attr(&doc, node, name);
  7638. const char *p = v;
  7639. int ok = 0;
  7640. double x;
  7641. if (!v)
  7642. return def;
  7643. x = svgr_num(&p, &ok);
  7644. if (!ok)
  7645. return def;
  7646. if (*p == '%')
  7647. x = x * base / 100.0;
  7648. return x;
  7649. }
  7650. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  7651. static int svg_viewbox4(unsigned int node, double vb[4])
  7652. {
  7653. const char *v = br_find_attr(&doc, node, "viewbox");
  7654. const char *p = v;
  7655. int i, ok = 1;
  7656. if (!v)
  7657. return 0;
  7658. for (i = 0; i < 4 && ok; i++)
  7659. vb[i] = svgr_num(&p, &ok);
  7660. return ok && vb[2] > 0 && vb[3] > 0;
  7661. }
  7662. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  7663. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  7664. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  7665. double w, double h, double m[6])
  7666. {
  7667. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  7668. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  7669. int ax = 1, ay = 1;
  7670. if (par && contains_ci(par, "none")) {
  7671. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  7672. m[4] = -vb[0] * sx;
  7673. m[5] = -vb[1] * sy;
  7674. return;
  7675. }
  7676. if (par) {
  7677. if (contains_ci(par, "xmin"))
  7678. ax = 0;
  7679. else if (contains_ci(par, "xmax"))
  7680. ax = 2;
  7681. if (contains_ci(par, "ymin"))
  7682. ay = 0;
  7683. else if (contains_ci(par, "ymax"))
  7684. ay = 2;
  7685. }
  7686. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  7687. (sx < sy ? sx : sy);
  7688. tx = (w - vb[2] * s) * ax / 2.0;
  7689. ty = (h - vb[3] * s) * ay / 2.0;
  7690. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  7691. m[4] = tx - vb[0] * s;
  7692. m[5] = ty - vb[1] * s;
  7693. }
  7694. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  7695. * the paint attribute, then average the gradient's stops. */
  7696. static int svg_url_paint(unsigned int node, const char *attr,
  7697. unsigned short *color, unsigned int *alpha)
  7698. {
  7699. const char *v = 0, *h;
  7700. char id[64];
  7701. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  7702. for (k = 0; node && k < 32 && !v; k++) {
  7703. v = br_find_attr(&doc, node, attr);
  7704. if (!v) {
  7705. const char *style = br_find_attr(&doc, node, "style");
  7706. if (style && contains_ci(style, "url(#"))
  7707. v = strstr(style, "url(#");
  7708. }
  7709. if (v && !contains_ci(v, "url("))
  7710. v = 0;
  7711. node = doc.nodes[node].parent;
  7712. }
  7713. if (!v || !(h = strstr(v, "#")))
  7714. return 0;
  7715. h++;
  7716. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  7717. id[n++] = *h++;
  7718. id[n] = '\0';
  7719. g = br_find_id(&doc, id);
  7720. /* Follow href chains (a gradient that only references another one's
  7721. * stops), at most a few hops. */
  7722. for (k = 0; g && k < 4; k++) {
  7723. unsigned int gi = g - 1;
  7724. const char *ref;
  7725. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  7726. const char *nm, *sc, *so;
  7727. unsigned short col = 0;
  7728. double op = 1;
  7729. if (doc.nodes[c].type != BR_NODE_ELEM)
  7730. continue;
  7731. nm = svg_elem_name(c);
  7732. if (!svg_name_is(nm, "stop"))
  7733. continue;
  7734. sc = br_find_attr(&doc, c, "stop-color");
  7735. so = br_find_attr(&doc, c, "stop-opacity");
  7736. {
  7737. const char *st = br_find_attr(&doc, c, "style");
  7738. const char *q;
  7739. if (st && (q = strstr(st, "stop-color:")) != 0)
  7740. sc = q + 11;
  7741. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  7742. so = q + 13;
  7743. }
  7744. if (sc) {
  7745. unsigned int L = 0;
  7746. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  7747. L++;
  7748. if (!br_parse_color(sc, L, &col))
  7749. col = 0;
  7750. }
  7751. if (so) {
  7752. const char *p = so;
  7753. int ok = 0;
  7754. double x = svgr_num(&p, &ok);
  7755. if (ok)
  7756. op = x < 0 ? 0 : x > 1 ? 1 : x;
  7757. }
  7758. sr += (col >> 11) & 31;
  7759. sg += (col >> 5) & 63;
  7760. sb += col & 31;
  7761. sa += (unsigned int)(op * 255);
  7762. cnt++;
  7763. }
  7764. if (cnt)
  7765. break;
  7766. ref = br_find_attr(&doc, gi, "href");
  7767. if (!ref)
  7768. ref = br_find_attr(&doc, gi, "xlink:href");
  7769. if (!ref || ref[0] != '#')
  7770. break;
  7771. g = br_find_id(&doc, ref + 1);
  7772. }
  7773. if (!cnt)
  7774. return 0;
  7775. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  7776. (sb / cnt));
  7777. *alpha = sa / cnt;
  7778. return 1;
  7779. }
  7780. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  7781. unsigned short *color, unsigned int *alpha)
  7782. {
  7783. int mode = fill ? st->fill_mode : st->stroke_mode;
  7784. const char *op = br_find_attr(&doc, node,
  7785. fill ? "fill-opacity" : "stroke-opacity");
  7786. *alpha = 255;
  7787. switch (mode) {
  7788. case BR_PAINT_UNSET:
  7789. if (!fill)
  7790. return 0;
  7791. *color = 0;
  7792. break;
  7793. case BR_PAINT_COLOR:
  7794. *color = fill ? st->fill : st->stroke;
  7795. break;
  7796. case BR_PAINT_CURRENT:
  7797. *color = st->color;
  7798. break;
  7799. case BR_PAINT_URL:
  7800. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  7801. alpha))
  7802. return 0;
  7803. break;
  7804. default:
  7805. return 0;
  7806. }
  7807. if (op) {
  7808. const char *p = op;
  7809. int ok = 0;
  7810. double x = svgr_num(&p, &ok);
  7811. if (ok)
  7812. *alpha = (unsigned int)(*alpha *
  7813. (x < 0 ? 0 : x > 1 ? 1 : x));
  7814. }
  7815. return *alpha > 0;
  7816. }
  7817. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7818. const double m[6], const struct br_style *pst,
  7819. unsigned int alpha, int depth);
  7820. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  7821. const double m[6], const struct br_style *st,
  7822. unsigned int alpha, int depth)
  7823. {
  7824. unsigned int c;
  7825. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  7826. if (doc.nodes[c].type == BR_NODE_ELEM)
  7827. svg_draw_node(L, c, m, st, alpha, depth + 1);
  7828. }
  7829. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7830. const double pm[6], const struct br_style *pst,
  7831. unsigned int alpha, int depth)
  7832. {
  7833. struct br_style st;
  7834. const char *nm = svg_elem_name(node);
  7835. const char *tf;
  7836. double m[6];
  7837. unsigned short color;
  7838. unsigned int pa;
  7839. int shape = 0, fillable = 1;
  7840. if (depth > 24 || !nm)
  7841. return;
  7842. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  7843. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  7844. svg_name_is(nm, "lineargradient") ||
  7845. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  7846. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  7847. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  7848. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  7849. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  7850. svg_name_is(nm, "foreignobject"))
  7851. return;
  7852. br_style_for(&doc, node, pst, &st);
  7853. if (st.display == BR_DISPLAY_NONE)
  7854. return;
  7855. memcpy(m, pm, sizeof(m));
  7856. tf = br_find_attr(&doc, node, "transform");
  7857. if (tf)
  7858. svgr_transform(m, tf);
  7859. {
  7860. const char *op = br_find_attr(&doc, node, "opacity");
  7861. if (op) {
  7862. const char *p = op;
  7863. int ok = 0;
  7864. double x = svgr_num(&p, &ok);
  7865. if (ok)
  7866. alpha = (unsigned int)(alpha *
  7867. (x < 0 ? 0 :
  7868. x > 1 ? 1 : x));
  7869. }
  7870. }
  7871. if (!alpha)
  7872. return;
  7873. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  7874. svg_name_is(nm, "switch")) {
  7875. svg_draw_children(L, node, m, &st, alpha, depth);
  7876. return;
  7877. }
  7878. if (svg_name_is(nm, "svg")) {
  7879. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  7880. y = svg_attr_num(node, "y", 0, 0);
  7881. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7882. t[4] = x;
  7883. t[5] = y;
  7884. svgr_mat_mul(m, m, t);
  7885. double ow = svg_vp_w, oh = svg_vp_h;
  7886. if (svg_viewbox4(node, vb)) {
  7887. double w = svg_attr_num(node, "width", vb[2], ow);
  7888. double h = svg_attr_num(node, "height", vb[3], oh);
  7889. double vm[6];
  7890. svg_viewport_matrix(node, vb, w, h, vm);
  7891. svgr_mat_mul(m, m, vm);
  7892. svg_vp_w = vb[2];
  7893. svg_vp_h = vb[3];
  7894. }
  7895. svg_draw_children(L, node, m, &st, alpha, depth);
  7896. svg_vp_w = ow;
  7897. svg_vp_h = oh;
  7898. return;
  7899. }
  7900. if (svg_name_is(nm, "use")) {
  7901. const char *ref = br_find_attr(&doc, node, "href");
  7902. unsigned int tgt;
  7903. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7904. if (!ref)
  7905. ref = br_find_attr(&doc, node, "xlink:href");
  7906. if (!ref || ref[0] != '#')
  7907. return;
  7908. tgt = br_find_id(&doc, ref + 1);
  7909. if (!tgt || tgt - 1 == node)
  7910. return;
  7911. tgt--;
  7912. t[4] = svg_attr_num(node, "x", 0, 0);
  7913. t[5] = svg_attr_num(node, "y", 0, 0);
  7914. svgr_mat_mul(m, m, t);
  7915. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  7916. double vb[4];
  7917. double ow = svg_vp_w, oh = svg_vp_h;
  7918. if (svg_viewbox4(tgt, vb)) {
  7919. /* A <use> without width/height sizes the
  7920. * symbol to 100% of the viewport: Docusaurus'
  7921. * 13.5px external-link icon references a
  7922. * 24-unit symbol and showed only its corner. */
  7923. double w = svg_attr_num(node, "width",
  7924. ow > 0 ? ow : vb[2], ow);
  7925. double h = svg_attr_num(node, "height",
  7926. oh > 0 ? oh : vb[3], oh);
  7927. double vm[6];
  7928. svg_viewport_matrix(tgt, vb, w, h, vm);
  7929. svgr_mat_mul(m, m, vm);
  7930. svg_vp_w = vb[2];
  7931. svg_vp_h = vb[3];
  7932. }
  7933. svg_draw_children(L, tgt, m, &st, alpha, depth);
  7934. svg_vp_w = ow;
  7935. svg_vp_h = oh;
  7936. } else {
  7937. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  7938. }
  7939. return;
  7940. }
  7941. svgr_reset(&svg_geom, m);
  7942. if (svg_name_is(nm, "path")) {
  7943. const char *d = br_find_attr(&doc, node, "d");
  7944. if (d) {
  7945. svgr_path(&svg_geom, d);
  7946. shape = 1;
  7947. }
  7948. } else if (svg_name_is(nm, "rect")) {
  7949. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  7950. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  7951. double rx = svg_attr_num(node, "rx", -1, w);
  7952. double ry = svg_attr_num(node, "ry", -1, h);
  7953. if (rx < 0)
  7954. rx = ry < 0 ? 0 : ry;
  7955. if (ry < 0)
  7956. ry = rx;
  7957. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  7958. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  7959. shape = 1;
  7960. } else if (svg_name_is(nm, "circle")) {
  7961. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  7962. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7963. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  7964. shape = 1;
  7965. } else if (svg_name_is(nm, "ellipse")) {
  7966. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7967. svg_attr_num(node, "cy", 0, svg_vp_h),
  7968. svg_attr_num(node, "rx", 0, svg_vp_w),
  7969. svg_attr_num(node, "ry", 0, svg_vp_h));
  7970. shape = 1;
  7971. } else if (svg_name_is(nm, "line")) {
  7972. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  7973. svg_attr_num(node, "y1", 0, svg_vp_h));
  7974. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  7975. svg_attr_num(node, "y2", 0, svg_vp_h));
  7976. shape = 1;
  7977. fillable = 0;
  7978. } else if (svg_name_is(nm, "polyline") ||
  7979. svg_name_is(nm, "polygon")) {
  7980. const char *pts = br_find_attr(&doc, node, "points");
  7981. if (pts) {
  7982. svgr_points(&svg_geom, pts,
  7983. svg_name_is(nm, "polygon"));
  7984. shape = 1;
  7985. }
  7986. }
  7987. if (!shape)
  7988. return;
  7989. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  7990. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  7991. st.fill_evenodd);
  7992. if (svg_paint(node, &st, 0, &color, &pa)) {
  7993. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  7994. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7995. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  7996. }
  7997. }
  7998. /* <text> elements: drawn straight onto the page every frame (the glyph
  7999. * renderer targets the ngui canvas, not a layer). x/y map through the
  8000. * accumulated transform; the font size scales with it. */
  8001. static void svg_draw_text(struct ngui *ui, unsigned int node,
  8002. const double pm[6], const struct br_style *pst,
  8003. int ox, int oy, int depth)
  8004. {
  8005. unsigned int c;
  8006. if (depth > 24)
  8007. return;
  8008. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8009. struct br_style st;
  8010. const char *nm, *tf;
  8011. double m[6];
  8012. if (doc.nodes[c].type != BR_NODE_ELEM)
  8013. continue;
  8014. nm = svg_elem_name(c);
  8015. if (!nm || svg_name_is(nm, "defs") ||
  8016. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  8017. svg_name_is(nm, "clippath"))
  8018. continue;
  8019. br_style_for(&doc, c, pst, &st);
  8020. if (st.display == BR_DISPLAY_NONE)
  8021. continue;
  8022. memcpy(m, pm, sizeof(m));
  8023. tf = br_find_attr(&doc, c, "transform");
  8024. if (tf)
  8025. svgr_transform(m, tf);
  8026. if (svg_name_is(nm, "text")) {
  8027. unsigned int t = doc.nodes[c].first;
  8028. const char *s;
  8029. unsigned int n, tw;
  8030. double x = svg_attr_num(c, "x", 0, 0),
  8031. y = svg_attr_num(c, "y", 0, 0);
  8032. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  8033. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  8034. int tx, ty, anchor;
  8035. unsigned short col;
  8036. unsigned int pa;
  8037. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  8038. continue;
  8039. if (px < 6)
  8040. px = 6;
  8041. if (px > 72)
  8042. px = 72;
  8043. if (!svg_paint(c, &st, 1, &col, &pa))
  8044. continue;
  8045. s = doc.text + doc.nodes[t].text_off;
  8046. n = doc.nodes[t].text_len;
  8047. st.font_px = (unsigned char)px;
  8048. tw = face_text_width(ui, &st, s, n);
  8049. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  8050. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  8051. ngui_text_ascent_face(ui, style_face(&st), px,
  8052. st.mono);
  8053. anchor = st.align;
  8054. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  8055. anchor = BR_ALIGN_CENTER;
  8056. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  8057. anchor = BR_ALIGN_RIGHT;
  8058. if (anchor == BR_ALIGN_CENTER)
  8059. tx -= (int)tw / 2;
  8060. else if (anchor == BR_ALIGN_RIGHT)
  8061. tx -= (int)tw;
  8062. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  8063. col, px, st.bold, st.italic,
  8064. st.mono);
  8065. } else {
  8066. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  8067. }
  8068. }
  8069. }
  8070. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  8071. {
  8072. double vb[4];
  8073. if (svg_viewbox4(node, vb)) {
  8074. svg_viewport_matrix(node, vb, w, h, m);
  8075. } else {
  8076. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  8077. }
  8078. }
  8079. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  8080. const struct br_style *st)
  8081. {
  8082. struct svg_cache_ent *e = 0;
  8083. struct svgr_layer L;
  8084. double m[6];
  8085. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  8086. svg_cache_clock++;
  8087. for (i = 0; i < SVG_CACHE_MAX; i++)
  8088. if (svg_cache[i].px && svg_cache[i].node == node &&
  8089. svg_cache[i].w == w && svg_cache[i].h == h) {
  8090. svg_cache[i].stamp = svg_cache_clock;
  8091. return &svg_cache[i];
  8092. }
  8093. if (need > SVG_CACHE_PIXELS)
  8094. return 0;
  8095. /* Evict least recently used layers until this one fits. */
  8096. for (;;) {
  8097. struct svg_cache_ent *lru = 0, *free_slot = 0;
  8098. for (i = 0; i < SVG_CACHE_MAX; i++) {
  8099. if (!svg_cache[i].px) {
  8100. if (!free_slot)
  8101. free_slot = &svg_cache[i];
  8102. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  8103. lru = &svg_cache[i];
  8104. }
  8105. }
  8106. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  8107. e = free_slot;
  8108. break;
  8109. }
  8110. if (!lru)
  8111. return 0;
  8112. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  8113. free(lru->px);
  8114. free(lru->a);
  8115. memset(lru, 0, sizeof(*lru));
  8116. }
  8117. if (!svg_geom_buf) {
  8118. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  8119. if (!svg_geom_buf)
  8120. return 0;
  8121. }
  8122. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  8123. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  8124. e->a = (unsigned char *)calloc(need, 1);
  8125. if (!e->px || !e->a) {
  8126. free(e->px);
  8127. free(e->a);
  8128. memset(e, 0, sizeof(*e));
  8129. return 0;
  8130. }
  8131. e->node = node;
  8132. e->w = w;
  8133. e->h = h;
  8134. e->stamp = svg_cache_clock;
  8135. svg_cache_pixels += need;
  8136. L.px = e->px;
  8137. L.a = e->a;
  8138. L.w = w;
  8139. L.h = h;
  8140. svg_root_matrix(node, w, h, m);
  8141. {
  8142. double vb[4];
  8143. if (svg_viewbox4(node, vb)) {
  8144. svg_vp_w = vb[2];
  8145. svg_vp_h = vb[3];
  8146. } else {
  8147. svg_vp_w = w;
  8148. svg_vp_h = h;
  8149. }
  8150. }
  8151. svg_draw_children(&L, node, m, st, 255, 0);
  8152. return e;
  8153. }
  8154. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  8155. *
  8156. * The markup is parsed into a detached subtree of the page document and
  8157. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  8158. * bitmap, which then behaves like any decoded image. currentColor is
  8159. * black (an image has no inherited text colour); <text> is not drawn. */
  8160. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  8161. {
  8162. unsigned int i = 0;
  8163. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  8164. i = 3;
  8165. while (i < len) {
  8166. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  8167. d[i] == '\r' || d[i] == '\n'))
  8168. i++;
  8169. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  8170. return 1;
  8171. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  8172. i += 4;
  8173. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  8174. i++;
  8175. i += 3;
  8176. continue;
  8177. }
  8178. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  8179. while (i < len && d[i] != '>')
  8180. i++;
  8181. i++;
  8182. continue;
  8183. }
  8184. return 0;
  8185. }
  8186. return 0;
  8187. }
  8188. static int svg_len_attr(unsigned int node, const char *name)
  8189. {
  8190. const char *v = br_find_attr(&doc, node, name);
  8191. int n = 0, any = 0;
  8192. if (!v)
  8193. return 0;
  8194. while (*v == ' ')
  8195. v++;
  8196. while (*v >= '0' && *v <= '9') {
  8197. n = n * 10 + (*v++ - '0');
  8198. any = 1;
  8199. }
  8200. if (*v == '.')
  8201. while (*++v >= '0' && *v <= '9')
  8202. ;
  8203. if (!any || *v == '%')
  8204. return 0;
  8205. return n;
  8206. }
  8207. static int svg_decode_image(const unsigned char *data, unsigned int len,
  8208. struct br_image *bi, int box_w, int box_h)
  8209. {
  8210. unsigned int holder, svg = 0, c, need, i;
  8211. struct br_style base = base_style(), st;
  8212. struct svgr_layer L;
  8213. double vb[4], m[6];
  8214. int w, h, have_vb, nat_w, nat_h;
  8215. holder = br_create_element(&doc, "div", 3);
  8216. if (!holder) {
  8217. s_copy(bi->err, "page is full", sizeof(bi->err));
  8218. return -1;
  8219. }
  8220. holder--;
  8221. br_set_inner_html(&doc, holder, (const char *)data, len);
  8222. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  8223. if (doc.nodes[c].type == BR_NODE_ELEM &&
  8224. doc.nodes[c].tag == BR_TAG_SVG) {
  8225. svg = c;
  8226. break;
  8227. }
  8228. if (!svg) {
  8229. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  8230. return -1;
  8231. }
  8232. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  8233. w = svg_len_attr(svg, "width");
  8234. h = svg_len_attr(svg, "height");
  8235. if (box_w > 0 && box_h > 0) {
  8236. w = box_w;
  8237. h = box_h;
  8238. } else if (!w && !h) {
  8239. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  8240. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  8241. } else if (!w) {
  8242. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  8243. } else if (!h) {
  8244. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  8245. }
  8246. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  8247. * so CSS scaling stays crisp. */
  8248. nat_w = w;
  8249. nat_h = h;
  8250. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  8251. w *= 2;
  8252. h *= 2;
  8253. }
  8254. if (w > BR_IMG_LAYOUT_W) {
  8255. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  8256. w = BR_IMG_LAYOUT_W;
  8257. }
  8258. if (h > 2048)
  8259. h = 2048;
  8260. if (w < 1)
  8261. w = 1;
  8262. if (h < 1)
  8263. h = 1;
  8264. need = (unsigned int)w * (unsigned int)h;
  8265. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  8266. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  8267. return -1;
  8268. }
  8269. if (!svg_geom_buf) {
  8270. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  8271. if (!svg_geom_buf) {
  8272. s_copy(bi->err, "out of memory", sizeof(bi->err));
  8273. return -1;
  8274. }
  8275. }
  8276. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  8277. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  8278. L.a = (unsigned char *)calloc(need, 1);
  8279. if (!L.px || !L.a) {
  8280. free(L.px);
  8281. free(L.a);
  8282. s_copy(bi->err, "out of memory", sizeof(bi->err));
  8283. return -1;
  8284. }
  8285. for (i = 0; i < need; i++)
  8286. L.px[i] = 0xFFFF;
  8287. L.w = w;
  8288. L.h = h;
  8289. base.color = 0x0000;
  8290. br_style_for(&doc, svg, &base, &st);
  8291. svg_root_matrix(svg, w, h, m);
  8292. if (!have_vb && nat_w > 0 && nat_h > 0) {
  8293. /* No viewBox: user units are CSS pixels of the natural size,
  8294. * so the up-to-4x raster (and a box size) must scale them.
  8295. * A 40x20 icon used to fill only the top-left quarter of its
  8296. * 160x80 bitmap and was drawn at a quarter of its size. */
  8297. m[0] = (double)w / nat_w;
  8298. m[3] = (double)h / nat_h;
  8299. }
  8300. svg_vp_w = have_vb ? vb[2] : nat_w;
  8301. svg_vp_h = have_vb ? vb[3] : nat_h;
  8302. svg_draw_children(&L, svg, m, &st, 255, 0);
  8303. bi->native_w = nat_w;
  8304. bi->native_h = nat_h;
  8305. bi->img.format = 0;
  8306. bi->img.w = (unsigned int)w;
  8307. bi->img.h = (unsigned int)h;
  8308. bi->img.px = L.px;
  8309. bi->img.alpha = L.a;
  8310. bi->img.flags = 0;
  8311. bi->state = 1;
  8312. image_pixels += need;
  8313. return 0;
  8314. }
  8315. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  8316. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  8317. int *out_w, int *out_h)
  8318. {
  8319. double vb[4];
  8320. int has_vb = svg_viewbox4(node, vb);
  8321. double aw = svg_attr_num(node, "width", -1, cw);
  8322. double ah = svg_attr_num(node, "height", -1, 0);
  8323. int w, h;
  8324. if (st->width_kind)
  8325. w = cw;
  8326. else if (aw > 0)
  8327. w = (int)(aw + 0.5);
  8328. else if (st->height_kind == 1 && has_vb)
  8329. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  8330. else if (ah > 0 && has_vb)
  8331. w = (int)(ah * vb[2] / vb[3] + 0.5);
  8332. else if (has_vb)
  8333. w = cw;
  8334. else
  8335. w = 300;
  8336. if (st->max_width_kind == 1 && w > st->max_width)
  8337. w = st->max_width;
  8338. if (w > cw && cw > 0 && !(aw > 0))
  8339. w = cw;
  8340. if (w < 1)
  8341. w = 1;
  8342. if (w > 2000)
  8343. w = 2000;
  8344. if (st->height_kind == 1)
  8345. h = st->height;
  8346. else if (ah > 0)
  8347. h = (int)(ah + 0.5);
  8348. else if (has_vb)
  8349. h = (int)(w * vb[3] / vb[2] + 0.5);
  8350. else
  8351. h = 150;
  8352. if (h < 1)
  8353. h = 1;
  8354. if (h > 1400)
  8355. h = 1400;
  8356. *out_w = w;
  8357. *out_h = h;
  8358. }
  8359. static void svg_paint_box(struct ngui *ui, unsigned int node,
  8360. const struct br_style *st, int x, int y, int w, int h)
  8361. {
  8362. struct svg_cache_ent *e;
  8363. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  8364. int cx0, cy0, cx1, cy1, px, py;
  8365. double m[6];
  8366. if (ui->nclip > 0)
  8367. clip = ui->clip[ui->nclip - 1];
  8368. cx0 = r.x > clip.x ? r.x : clip.x;
  8369. cy0 = r.y > clip.y ? r.y : clip.y;
  8370. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  8371. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  8372. if (cx0 >= cx1 || cy0 >= cy1)
  8373. return;
  8374. e = svg_layer(node, w, h, st);
  8375. if (e) {
  8376. for (py = cy0; py < cy1; py++) {
  8377. unsigned int srow = (unsigned int)(py - y) *
  8378. (unsigned int)w;
  8379. unsigned short *dst = ui->px + py * ui->w;
  8380. for (px = cx0; px < cx1; px++) {
  8381. unsigned int si = srow + (unsigned int)(px - x);
  8382. unsigned int a = e->a[si];
  8383. if (!a)
  8384. continue;
  8385. dst[px] = a >= 255 ? e->px[si] :
  8386. blend_rgb565(dst[px], e->px[si], a);
  8387. }
  8388. }
  8389. }
  8390. svg_root_matrix(node, w, h, m);
  8391. ngui_push_clip(ui, r);
  8392. svg_draw_text(ui, node, m, st, x, y, 0);
  8393. ngui_pop_clip(ui);
  8394. }
  8395. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  8396. * keep using add_image_run(); this covers the CSS `position:absolute;
  8397. * width:100%` poster pattern used by news sites. */
  8398. static void image_block_size(unsigned int node, const struct br_style *st,
  8399. int cbw, int *out_w, int *out_h)
  8400. {
  8401. struct br_node *nd = &doc.nodes[node];
  8402. int idx = nd->img_index;
  8403. int iw = 0, ih = 0, w, h, aw, ah;
  8404. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  8405. iw = (int)images[idx].img.w;
  8406. ih = (int)images[idx].img.h;
  8407. if (iw <= 0 || ih <= 0) {
  8408. iw = (int)images[idx].native_w;
  8409. ih = (int)images[idx].native_h;
  8410. }
  8411. }
  8412. if (st->width_kind)
  8413. w = style_width_px(st, cbw);
  8414. else if (nd->width_attr)
  8415. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  8416. (int)nd->width_attr;
  8417. else if (nd->height_attr && !nd->height_pct && iw && ih)
  8418. w = iw * (int)nd->height_attr / ih;
  8419. else if (iw)
  8420. w = iw;
  8421. else
  8422. w = 64;
  8423. /* max-width/min-width against the containing block: Tailwind's
  8424. * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
  8425. * 300x300 thumbnail to its 75 px avatar box. */
  8426. if (st->max_width_kind) {
  8427. int mw = st->max_width_kind == 3 ?
  8428. cbw * st->max_width_calc_pct / 100 +
  8429. st->max_width_calc_px :
  8430. st->max_width_kind == 2 ?
  8431. cbw * (int)st->max_width / 100 : (int)st->max_width;
  8432. if (mw > 0 && w > mw)
  8433. w = mw;
  8434. }
  8435. if (st->min_width_kind) {
  8436. int mn = st->min_width_kind == 3 ?
  8437. cbw * st->min_width_calc_pct / 100 +
  8438. st->min_width_calc_px :
  8439. st->min_width_kind == 2 ?
  8440. cbw * (int)st->min_width / 100 : (int)st->min_width;
  8441. if (mn > w)
  8442. w = mn;
  8443. }
  8444. if (w < 8)
  8445. w = 8;
  8446. if (cbw > 0 && w > cbw)
  8447. w = cbw;
  8448. /* Without a CSS height the attributes (or the bitmap) only give the
  8449. * aspect ratio: a width clamped by max-width scales the height too,
  8450. * instead of letterboxing the image into its attribute height. */
  8451. aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
  8452. ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
  8453. if (st->height_kind)
  8454. h = style_height_px(st, cbw);
  8455. else if (aw > 0 && ah > 0)
  8456. h = w * ah / aw;
  8457. else if (nd->height_attr)
  8458. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  8459. (int)nd->height_attr;
  8460. else
  8461. h = 64;
  8462. if (h < 8)
  8463. h = 8;
  8464. *out_w = w;
  8465. *out_h = h;
  8466. }
  8467. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  8468. int dw, int dh)
  8469. {
  8470. int idx = doc.nodes[node].img_index;
  8471. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  8472. struct img_image *src = image_display_get(&images[idx], dw, dh);
  8473. struct img_blit b;
  8474. if (!src)
  8475. src = &images[idx].img;
  8476. b.dst = l->ui->px;
  8477. b.dst_w = l->ui->w;
  8478. b.dst_h = l->ui->h;
  8479. b.clip_x = page_rect.x;
  8480. b.clip_y = page_rect.y;
  8481. b.clip_w = page_rect.w - 12;
  8482. b.clip_h = page_rect.h;
  8483. b.x = x;
  8484. b.y = y;
  8485. b.scale = ((unsigned int)dw << 16) / src->w;
  8486. b.bg = ui.theme.bg;
  8487. b.bg2 = ui.theme.bg;
  8488. b.dst_a = 0;
  8489. /* OVER_DST is only needed for an alpha source; an opaque one can
  8490. * take img_draw's 1:1 copy path. */
  8491. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  8492. img_draw(src, &b);
  8493. } else if (l->draw) {
  8494. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  8495. 0xD69A);
  8496. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  8497. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  8498. }
  8499. }
  8500. static int intrinsic_width(struct ngui *ui, unsigned int node,
  8501. const struct br_style *pst, int depth, int base);
  8502. static void layout_block(struct lay *l, unsigned int node,
  8503. const struct br_style *st, int depth,
  8504. unsigned short link)
  8505. {
  8506. int old_left = l->left, old_right = l->right, old_align = l->align;
  8507. int parent_cb_h = l->cb_h;
  8508. int saved_parent_top = l->parent_top;
  8509. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  8510. int saved_cb_top = l->cb_top;
  8511. int top, l0, r0;
  8512. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  8513. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  8514. int deco_w, deco_h, content_w, content_h, box_h;
  8515. int img_dh = 0;
  8516. int definite_w = 0;
  8517. int normal_top = 0;
  8518. int rel_dx = 0, rel_dy = 0;
  8519. int clip_pushed = 0;
  8520. struct ngui_rect clip_rect;
  8521. /* A DOM level costs about two depth units (layout_block ->
  8522. * layout_children), so 48 covers a ~24-level page. Real news pages
  8523. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  8524. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  8525. return;
  8526. flow_y = l->y;
  8527. flow_left = l->left;
  8528. flow_right = l->right;
  8529. positioned = st->pos == 1 || st->pos == 2;
  8530. relative = st->pos == 3;
  8531. sticky = st->pos == 4;
  8532. shifted = relative || sticky || st->transform_set;
  8533. if (positioned) {
  8534. int def_w = st->width_kind == 1 ? st->width : -1;
  8535. if (st->pos == 2) {
  8536. int avail_w = page_rect.w - 12;
  8537. if (st->right_set && def_w >= 0)
  8538. l->left = page_rect.x + avail_w - st->right -
  8539. def_w;
  8540. else if (!st->left_set && !st->right_set)
  8541. l->left = flow_left; /* static position */
  8542. else
  8543. l->left = page_rect.x +
  8544. (st->left_set ? st->left : 0);
  8545. l->right = def_w >= 0 ? l->left + def_w :
  8546. st->width_kind == 2 ?
  8547. l->left + avail_w * (int)st->width / 100 :
  8548. page_rect.x + avail_w;
  8549. /* Placed by `bottom` (a page footer): an auto
  8550. * height is the measured one. */
  8551. if (st->bottom_set && st->height_kind)
  8552. l->y = page_rect.y + page_rect.h -
  8553. st->bottom -
  8554. style_height_px(st, page_rect.w);
  8555. else if (st->bottom_set && !st->top_set &&
  8556. block_h[node])
  8557. l->y = page_rect.y + page_rect.h -
  8558. st->bottom - (int)block_h[node] -
  8559. mp_px(st, 0, avail_w) -
  8560. mp_px(st, 2, avail_w);
  8561. else
  8562. l->y = page_rect.y +
  8563. (st->top_set ? st->top : 0);
  8564. } else {
  8565. int left = flow_left + (st->left_set ? st->left : 0);
  8566. unsigned int parent = doc.nodes[node].parent;
  8567. if (st->right_set && def_w >= 0)
  8568. left = flow_right - st->right - def_w;
  8569. l->left = left;
  8570. l->right = def_w >= 0 ? left + def_w :
  8571. flow_right +
  8572. (st->left_set ? st->left : 0);
  8573. l->y = flow_y + (st->top_set ? st->top : 0);
  8574. if (st->bottom_set && st->height_kind &&
  8575. parent < BR_MAX_NODES && block_h[parent] > 0)
  8576. l->y = flow_y + block_h[parent] - st->bottom -
  8577. style_height_px(st, old_right - old_left);
  8578. else if (st->bottom_set && !st->top_set &&
  8579. parent < BR_MAX_NODES && block_h[parent] > 0 &&
  8580. block_h[node] > 0)
  8581. l->y = flow_y + block_h[parent] - st->bottom -
  8582. (int)block_h[node] -
  8583. mp_px(st, 0, old_right - old_left) -
  8584. mp_px(st, 2, old_right - old_left);
  8585. }
  8586. /* An auto width placed by one horizontal offset is
  8587. * shrink-to-fit (CSS 2.1 10.3.7): a Bootstrap tooltip or a
  8588. * dropdown is as wide as its content, not its containing
  8589. * block. With neither offset the box keeps the containing
  8590. * width, since `inset: 0` overlays are not parsed and only
  8591. * stretch that way; an empty measure keeps it too. */
  8592. if (st->width_kind == 0 && st->left_set != st->right_set) {
  8593. int cb_l = st->pos == 2 ? page_rect.x : flow_left;
  8594. int cb_r = st->pos == 2 ? page_rect.x +
  8595. page_rect.w - 12 : flow_right;
  8596. int avail = cb_r - cb_l - (st->left_set ? st->left :
  8597. st->right);
  8598. int w = intrinsic_width(l->ui, node, st, 0,
  8599. cb_r - cb_l);
  8600. if (w > 0) {
  8601. w += mp_px(st, 7, cb_r - cb_l) +
  8602. mp_px(st, 5, cb_r - cb_l) +
  8603. mp_px(st, 3, cb_r - cb_l) +
  8604. mp_px(st, 1, cb_r - cb_l) +
  8605. st->border_w[1] + st->border_w[3];
  8606. if (st->max_width_kind == 1 &&
  8607. w > (int)st->max_width)
  8608. w = (int)st->max_width;
  8609. if (avail > 8 && w > avail)
  8610. w = avail;
  8611. if (st->right_set) {
  8612. l->right = cb_r - st->right;
  8613. l->left = l->right - w;
  8614. } else {
  8615. l->right = l->left + w;
  8616. }
  8617. }
  8618. }
  8619. /* `left: 100%` parks a box (Docusaurus' "Skip to main
  8620. * content" link) past the containing block's right edge
  8621. * until it is focused. An auto width then has no room: it
  8622. * used to collapse to 8 px and wrap one word per line into a
  8623. * tall column painted over the page. Lay it out at the
  8624. * containing block's width so it stays one line and
  8625. * overflows (off-screen) like in a real browser. */
  8626. if (def_w < 0 && l->right - l->left < 8) {
  8627. int avail = st->pos == 2 ? page_rect.w - 12 :
  8628. flow_right - flow_left;
  8629. l->right = l->left + (avail > 8 ? avail : 8);
  8630. }
  8631. old_left = l->left;
  8632. old_right = l->right;
  8633. } else if (relative) {
  8634. rel_dx = st->left_set ? st->left :
  8635. (st->right_set ? -st->right : 0);
  8636. rel_dy = st->top_set ? st->top :
  8637. (st->bottom_set ? -st->bottom : 0);
  8638. }
  8639. if (st->transform_set) {
  8640. rel_dx += st->tx;
  8641. rel_dy += st->ty;
  8642. }
  8643. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  8644. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  8645. doc.nodes[node].tag == BR_TAG_SELECT ||
  8646. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  8647. !button_has_elements(node)) {
  8648. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  8649. s_eq(br_type(&doc, node), "hidden"))
  8650. return;
  8651. /* Reached as a block-level box (a flex item): the control
  8652. * fills the box the caller assigned, and its line is flushed
  8653. * here; flex layout resets the run list for the next item, so
  8654. * a queued run would never be drawn. */
  8655. form_fill_line = 1;
  8656. add_form_run(l, node, st, link);
  8657. form_fill_line = 0;
  8658. flush_line(l);
  8659. return;
  8660. }
  8661. flush_line(l);
  8662. cbw = old_right - old_left;
  8663. if (cbw < 8)
  8664. cbw = 8;
  8665. l->y += mp_px(st, 0, cbw);
  8666. top = l->y;
  8667. ml = mp_px(st, 3, cbw);
  8668. mr = mp_px(st, 1, cbw);
  8669. bl = st->border_w[3];
  8670. br = st->border_w[1];
  8671. pl = mp_px(st, 7, cbw);
  8672. pr = mp_px(st, 5, cbw);
  8673. bt = st->border_w[0];
  8674. bb = st->border_w[2];
  8675. pt = mp_px(st, 4, cbw);
  8676. pb = mp_px(st, 6, cbw);
  8677. deco_w = bl + br + pl + pr;
  8678. deco_h = bt + bb + pt + pb;
  8679. if (st->width_kind) {
  8680. int w;
  8681. if (st->width_kind == 3)
  8682. w = cbw * st->width_calc_pct / 100 +
  8683. st->width_calc_px;
  8684. else
  8685. w = css_size(st->width_kind, st->width, cbw);
  8686. if (w < 0)
  8687. w = 0;
  8688. content_w = st->box_sizing ? w - deco_w : w;
  8689. definite_w = 1;
  8690. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  8691. doc.nodes[node].tag == BR_TAG_TD ||
  8692. doc.nodes[node].tag == BR_TAG_TH) &&
  8693. doc.nodes[node].width_attr) {
  8694. /* Legacy table/cell width attributes: percentages resolve
  8695. * against the containing block, bare numbers are pixels. */
  8696. int w = doc.nodes[node].width_pct ?
  8697. cbw * doc.nodes[node].width_attr / 100 :
  8698. doc.nodes[node].width_attr;
  8699. if (w < 0)
  8700. w = 0;
  8701. content_w = st->box_sizing ? w - deco_w : w;
  8702. definite_w = 1;
  8703. } else {
  8704. content_w = cbw - ml - mr - deco_w;
  8705. }
  8706. if (content_w < 0)
  8707. content_w = 0;
  8708. if (st->max_width_kind) {
  8709. int mw = st->max_width_kind == 3 ?
  8710. cbw * st->max_width_calc_pct / 100 +
  8711. st->max_width_calc_px :
  8712. css_size(st->max_width_kind, st->max_width, cbw);
  8713. int max_box = st->box_sizing ? mw : mw + deco_w;
  8714. /* A clamped auto width is used as the width, so auto
  8715. * margins share the rest (Google's 688 px search box). */
  8716. if (content_w + deco_w > max_box) {
  8717. content_w = max_box - deco_w;
  8718. definite_w = 1;
  8719. }
  8720. }
  8721. if (st->min_width_kind) {
  8722. int mw = st->min_width_kind == 3 ?
  8723. cbw * st->min_width_calc_pct / 100 +
  8724. st->min_width_calc_px :
  8725. css_size(st->min_width_kind, st->min_width, cbw);
  8726. int min_box = st->box_sizing ? mw : mw + deco_w;
  8727. if (content_w + deco_w < min_box) {
  8728. content_w = min_box - deco_w;
  8729. definite_w = 1;
  8730. }
  8731. }
  8732. if (content_w < 8)
  8733. content_w = 8;
  8734. if (definite_w) {
  8735. int free_w = cbw - ml - mr - deco_w - content_w;
  8736. if (free_w < 0)
  8737. free_w = 0;
  8738. if (st->ml_auto && st->mr_auto) {
  8739. ml = free_w / 2;
  8740. mr = free_w - ml;
  8741. } else if (st->ml_auto) {
  8742. ml = free_w;
  8743. } else if (st->mr_auto) {
  8744. mr = free_w;
  8745. }
  8746. }
  8747. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8748. int iw, ih;
  8749. image_block_size(node, st, cbw, &iw, &ih);
  8750. content_w = iw;
  8751. img_dh = ih;
  8752. }
  8753. l0 = old_left + ml;
  8754. r0 = l0 + deco_w + content_w;
  8755. if (r0 < l0 + 8)
  8756. r0 = l0 + 8;
  8757. normal_top = top;
  8758. if (sticky) {
  8759. if (st->top_set) {
  8760. int stick = page_rect.y + st->top;
  8761. if (normal_top < stick)
  8762. rel_dy += stick - normal_top;
  8763. } else if (st->bottom_set && block_h[node]) {
  8764. int stick = page_rect.y + page_rect.h - st->bottom -
  8765. block_h[node];
  8766. if (normal_top > stick)
  8767. rel_dy += stick - normal_top;
  8768. }
  8769. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  8770. block_h[doc.nodes[node].parent]) {
  8771. unsigned int p = doc.nodes[node].parent;
  8772. int ptop = l->parent_top;
  8773. int pbottom = ptop + block_h[p];
  8774. int eh = block_h[node];
  8775. int moved_top = normal_top + rel_dy;
  8776. int moved_bottom = moved_top + eh;
  8777. if (moved_bottom > pbottom)
  8778. rel_dy -= moved_bottom - pbottom;
  8779. moved_top = normal_top + rel_dy;
  8780. if (moved_top < ptop)
  8781. rel_dy += ptop - moved_top;
  8782. }
  8783. }
  8784. if (shifted && l->draw) {
  8785. top += rel_dy;
  8786. l0 += rel_dx;
  8787. r0 += rel_dx;
  8788. }
  8789. l->parent_top = top;
  8790. if (st->pos != 0) {
  8791. /* Positioned boxes establish the containing block for their
  8792. * absolutely positioned descendants. */
  8793. l->cb_left = l0;
  8794. l->cb_right = r0;
  8795. l->cb_top = top;
  8796. }
  8797. if (l->draw && block_h[node] &&
  8798. top < page_rect.y + page_rect.h &&
  8799. top + block_h[node] > page_rect.y) {
  8800. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  8801. int rtl = css_radius(st, 0, box.w, box.h);
  8802. int rtr = css_radius(st, 1, box.w, box.h);
  8803. int rbr = css_radius(st, 2, box.w, box.h);
  8804. int rbl = css_radius(st, 3, box.w, box.h);
  8805. if (st->transform_scale) {
  8806. if (st->has_bg)
  8807. fill_transformed_rect(l->ui, box, st->bg, st);
  8808. } else if (rtl || rtr || rbr || rbl) {
  8809. if (st->has_bg) {
  8810. int bw = st->border_w[0];
  8811. if (bw > 0 && !st->border_t[0] &&
  8812. st->border_c[0] != st->bg &&
  8813. box.w > bw * 2 && box.h > bw * 2) {
  8814. struct ngui_rect inner = {
  8815. box.x + bw, box.y + bw,
  8816. box.w - bw * 2, box.h - bw * 2
  8817. };
  8818. int itl = rtl > bw ? rtl - bw : 0;
  8819. int itr = rtr > bw ? rtr - bw : 0;
  8820. int ibr = rbr > bw ? rbr - bw : 0;
  8821. int ibl = rbl > bw ? rbl - bw : 0;
  8822. ngui_fill_round_rect(l->ui, box, rtl,
  8823. rtr, rbr, rbl,
  8824. st->border_c[0]);
  8825. ngui_fill_round_rect(l->ui, inner,
  8826. itl, itr, ibr,
  8827. ibl, st->bg);
  8828. } else {
  8829. ngui_fill_round_rect(l->ui, box, rtl,
  8830. rtr, rbr, rbl,
  8831. st->bg);
  8832. }
  8833. } else if (st->border_w[0] && !st->border_t[0]) {
  8834. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  8835. rbl, st->border_w[0],
  8836. st->border_c[0]);
  8837. }
  8838. /* Rounded boxes paint their background image too
  8839. * (app icons are rounded squares), kept inside the
  8840. * corner arcs. */
  8841. if (st->bg_image)
  8842. draw_bg_image_round(l, box, node, st, rtl, rtr,
  8843. rbr, rbl);
  8844. } else {
  8845. if (st->has_bg)
  8846. ngui_fill_rect(l->ui, box, st->bg);
  8847. if (st->bg_image)
  8848. draw_bg_image(l, box, node, st);
  8849. if (st->border_w[0] || st->border_w[1] ||
  8850. st->border_w[2] || st->border_w[3])
  8851. draw_border_box(l->ui, box, st);
  8852. }
  8853. }
  8854. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  8855. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  8856. content_w, img_dh);
  8857. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  8858. l->ui && l->ui->nclip < 4) {
  8859. clip_rect.x = l0 + bl;
  8860. clip_rect.y = top + bt;
  8861. clip_rect.w = (r0 - l0) - bl - br;
  8862. clip_rect.h = (int)block_h[node] - bt - bb;
  8863. if (clip_rect.w > 0 && clip_rect.h > 0) {
  8864. ngui_push_clip(l->ui, clip_rect);
  8865. clip_pushed = 1;
  8866. }
  8867. }
  8868. l->left = l0 + bl + pl;
  8869. l->right = l->left + content_w;
  8870. if (l->right < l->left + 8)
  8871. l->right = l->left + 8;
  8872. l->align = st->align;
  8873. l->line_left = l->left;
  8874. l->line_right = l->right;
  8875. l->y = top + bt + pt;
  8876. if (doc.nodes[node].tag == BR_TAG_HR) {
  8877. if (l->draw)
  8878. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  8879. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  8880. l->y += 8;
  8881. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  8882. int vw = l->right - l->left;
  8883. int vh;
  8884. if (doc.nodes[node].width_pct)
  8885. vw = vw * doc.nodes[node].width_attr / 100;
  8886. else if (doc.nodes[node].width_attr)
  8887. vw = doc.nodes[node].width_attr;
  8888. if (vw > l->right - l->left)
  8889. vw = l->right - l->left;
  8890. if (vw < 8)
  8891. vw = 8;
  8892. vh = vw * 9 / 16;
  8893. if (vh > 240)
  8894. vh = 240;
  8895. if (vh < 80)
  8896. vh = 80;
  8897. if (l->draw) {
  8898. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  8899. vw, vh}, 0xD69A);
  8900. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  8901. vw, vh}, 0x8410);
  8902. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  8903. 0x4208);
  8904. }
  8905. l->y += vh + 4;
  8906. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  8907. int dw, dh, cw = l->right - l->left;
  8908. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  8909. if (l->draw && l->y < page_rect.y + page_rect.h &&
  8910. l->y + dh > page_rect.y)
  8911. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  8912. l->y += dh;
  8913. } else {
  8914. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  8915. !st->no_bullet) {
  8916. char *m = li_marker[node];
  8917. if (!m[0]) {
  8918. unsigned int parent = doc.nodes[node].parent;
  8919. int style = st->list_style;
  8920. int idx = parent ? list_index(parent, node) : 1;
  8921. if (style == BR_LIST_AUTO)
  8922. style = (parent &&
  8923. doc.nodes[parent].tag ==
  8924. BR_TAG_OL) ?
  8925. BR_LIST_DECIMAL : BR_LIST_DISC;
  8926. list_marker_text(m, sizeof(li_marker[node]),
  8927. style, idx);
  8928. }
  8929. if (l->draw && m[0]) {
  8930. int mw = (int)ngui_text_width_ui(l->ui, m);
  8931. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  8932. st->color);
  8933. }
  8934. }
  8935. /* This box's definite content height, for its children's
  8936. * percentage heights. */
  8937. if (doc.nodes[node].tag == BR_TAG_HTML ||
  8938. doc.nodes[node].tag == BR_TAG_BODY)
  8939. l->cb_h = layout_view_h;
  8940. else if (st->height_kind == 1)
  8941. l->cb_h = (int)st->height -
  8942. (st->box_sizing ? deco_h : 0);
  8943. else if (st->height_kind == 2 && parent_cb_h > 0)
  8944. l->cb_h = parent_cb_h * (int)st->height / 100 -
  8945. (st->box_sizing ? deco_h : 0);
  8946. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  8947. l->cb_h = content_w * (int)st->aspect_h /
  8948. (int)st->aspect_w;
  8949. else if (!st->height_kind && node < BR_MAX_NODES &&
  8950. flex_stretch_h[node] > deco_h)
  8951. l->cb_h = flex_stretch_h[node] - deco_h;
  8952. else
  8953. l->cb_h = 0;
  8954. if (l->cb_h < 0)
  8955. l->cb_h = 0;
  8956. if (doc.nodes[node].tag == BR_TAG_TR)
  8957. layout_table_row(l, node, st, depth + 1, link);
  8958. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  8959. table_has_rowspan(node))
  8960. layout_table(l, node, st, depth + 1, link);
  8961. else if (st->grid_auto)
  8962. layout_grid_auto(l, node, st, depth + 1, link);
  8963. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  8964. st->grid_gap > 0)
  8965. layout_grid_children(l, node, st, depth + 1, link);
  8966. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  8967. flex_wants_row(node, st))
  8968. layout_flex_children(l, node, st, depth + 1, link);
  8969. else if (st->display == BR_DISPLAY_FLEX && st->flex_col)
  8970. layout_flex_column(l, node, st, depth + 1, link);
  8971. else
  8972. layout_children(l, node, st, depth + 1, link);
  8973. l->cb_h = parent_cb_h;
  8974. }
  8975. flush_line(l);
  8976. if (clip_pushed)
  8977. ngui_pop_clip(l->ui);
  8978. if (l->float_active) {
  8979. if (l->y < l->float_bottom)
  8980. l->y = l->float_bottom;
  8981. l->float_active = 0;
  8982. }
  8983. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8984. content_h = img_dh;
  8985. } else if (st->height_kind == 2 &&
  8986. doc.nodes[node].tag != BR_TAG_HTML &&
  8987. doc.nodes[node].tag != BR_TAG_BODY) {
  8988. /* A percentage of the containing block's definite height, or
  8989. * auto when it has none (it used to resolve against the
  8990. * width). The result is a minimum: without scrollable inner
  8991. * boxes, an app shell's height:100%; overflow:hidden column
  8992. * would otherwise clip everything past the first screen. */
  8993. int auto_h = l->y - (top + bt + pt);
  8994. content_h = parent_cb_h > 0 ?
  8995. parent_cb_h * (int)st->height / 100 -
  8996. (st->box_sizing ? deco_h : 0) : 0;
  8997. if (content_h < auto_h)
  8998. content_h = auto_h;
  8999. } else if (st->height_kind &&
  9000. !((doc.nodes[node].tag == BR_TAG_HTML ||
  9001. doc.nodes[node].tag == BR_TAG_BODY) &&
  9002. st->height_kind == 2)) {
  9003. content_h = style_height_px(st, cbw);
  9004. if (st->box_sizing)
  9005. content_h -= deco_h;
  9006. } else {
  9007. /* Percentage heights on html/body resolve against the
  9008. * viewport, but their content still defines the document
  9009. * scroll height. Treating them as auto avoids collapsing
  9010. * the measured page to the containing block width. */
  9011. content_h = l->y - (top + bt + pt);
  9012. /* aspect-ratio: the preferred height of an auto-height box
  9013. * (Tailwind aspect-video image frames); content can still
  9014. * make it taller, as with min-height: auto. */
  9015. if (st->aspect_w && st->aspect_h && content_w > 0) {
  9016. int ah = content_w * (int)st->aspect_h /
  9017. (int)st->aspect_w;
  9018. if (content_h < ah)
  9019. content_h = ah;
  9020. }
  9021. }
  9022. if (content_h < 0)
  9023. content_h = 0;
  9024. if (!st->height_kind && node < BR_MAX_NODES &&
  9025. content_h + deco_h < flex_stretch_h[node])
  9026. content_h = flex_stretch_h[node] - deco_h;
  9027. if (st->max_height_kind) {
  9028. int mh = st->max_height_kind == 3 ?
  9029. cbw * st->max_height_calc_pct / 100 +
  9030. st->max_height_calc_px :
  9031. css_size(st->max_height_kind, st->max_height, cbw);
  9032. int max_box = st->box_sizing ? mh : mh + deco_h;
  9033. if (content_h + deco_h > max_box)
  9034. content_h = max_box - deco_h;
  9035. }
  9036. if (st->min_height_kind &&
  9037. !((doc.nodes[node].tag == BR_TAG_HTML ||
  9038. doc.nodes[node].tag == BR_TAG_BODY) &&
  9039. st->min_height_kind == 2)) {
  9040. int mh = st->min_height_kind == 3 ?
  9041. cbw * st->min_height_calc_pct / 100 +
  9042. st->min_height_calc_px :
  9043. css_size(st->min_height_kind, st->min_height, cbw);
  9044. int min_box = st->box_sizing ? mh : mh + deco_h;
  9045. if (content_h + deco_h < min_box)
  9046. content_h = min_box - deco_h;
  9047. }
  9048. if (content_h < 0)
  9049. content_h = 0;
  9050. box_h = deco_h + content_h;
  9051. if (box_h < 0)
  9052. box_h = 0;
  9053. l->y = (shifted ? normal_top : top) + box_h;
  9054. if (node < BR_MAX_NODES) {
  9055. layout_boxes[node].x = l0;
  9056. layout_boxes[node].y = top;
  9057. layout_boxes[node].w = r0 - l0;
  9058. layout_boxes[node].h = box_h;
  9059. layout_boxes[node].valid = r0 > l0;
  9060. }
  9061. l->left = old_left;
  9062. l->right = old_right;
  9063. l->align = old_align;
  9064. l->y += mp_px(st, 2, cbw);
  9065. if (!l->draw) {
  9066. if (box_h > 65535)
  9067. box_h = 65535;
  9068. block_h[node] = (unsigned short)box_h;
  9069. block_top[node] = (unsigned short)(top < 0 ? 0 :
  9070. top > 65535 ? 65535 : top);
  9071. }
  9072. if (positioned) {
  9073. l->y = flow_y;
  9074. l->left = flow_left;
  9075. l->right = flow_right;
  9076. }
  9077. l->parent_top = saved_parent_top;
  9078. l->cb_left = saved_cb_left;
  9079. l->cb_right = saved_cb_right;
  9080. l->cb_top = saved_cb_top;
  9081. }
  9082. static int text_node_blank(const struct br_node *nd)
  9083. {
  9084. const char *t = doc.text + nd->text_off;
  9085. unsigned int i;
  9086. for (i = 0; i < nd->text_len; i++)
  9087. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  9088. t[i] != '\r')
  9089. return 0;
  9090. return 1;
  9091. }
  9092. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  9093. * text/image widths in the subtree, plus padding and margins. This keeps
  9094. * Bootstrap's floated nav items on one line instead of giving each the whole
  9095. * row. */
  9096. static int text_space(char c)
  9097. {
  9098. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  9099. }
  9100. static int intrinsic_width(struct ngui *ui, unsigned int node,
  9101. const struct br_style *pst, int depth, int base)
  9102. {
  9103. unsigned int c;
  9104. int line_w = 0, max_w = 0;
  9105. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  9106. if (depth > 32)
  9107. return 0;
  9108. if (doc.npe_rules) {
  9109. struct br_style ps;
  9110. /* Icon boxes (::before/::after with a size) are inline
  9111. * content of the element. */
  9112. line_w += pseudo_box_w(node, pst, 1, &ps, base) +
  9113. pseudo_box_w(node, pst, 2, &ps, base);
  9114. }
  9115. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9116. struct br_node *nd = &doc.nodes[c];
  9117. struct br_style cs;
  9118. if (nd->type == BR_NODE_TEXT) {
  9119. const char *t = doc.text + nd->text_off;
  9120. unsigned int tn = nd->text_len;
  9121. if (doc.nodes[node].tag == BR_TAG_PRE) {
  9122. line_w += (int)face_text_width(ui, pst, t, tn);
  9123. } else {
  9124. unsigned int ti = 0;
  9125. int first = 1;
  9126. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  9127. int sp = (int)face_text_width(ui, pst, " ", 1);
  9128. while (ti < tn) {
  9129. unsigned int ts;
  9130. while (ti < tn && text_space(t[ti]))
  9131. ti++;
  9132. ts = ti;
  9133. while (ti < tn && !text_space(t[ti]))
  9134. ti++;
  9135. if (ti == ts)
  9136. break;
  9137. if (!first || lead)
  9138. line_w += sp;
  9139. lead = 0;
  9140. line_w += (int)face_text_width(ui, pst,
  9141. t + ts, ti - ts);
  9142. first = 0;
  9143. }
  9144. }
  9145. continue;
  9146. }
  9147. br_style_for(&doc, c, pst, &cs);
  9148. /* Absolute/fixed children take no room in the parent's
  9149. * shrink-to-fit width: a shown Bootstrap tooltip widened the
  9150. * floated navbar list and slid the hovered item away. */
  9151. if (cs.display == BR_DISPLAY_NONE || cs.pos == 1 ||
  9152. cs.pos == 2)
  9153. continue;
  9154. if (nd->tag == BR_TAG_BR) {
  9155. if (line_w > max_w)
  9156. max_w = line_w;
  9157. line_w = 0;
  9158. continue;
  9159. }
  9160. if (nd->tag == BR_TAG_IMG) {
  9161. /* Measure the image as layout will draw it: a CSS or
  9162. * attribute height keeps the intrinsic aspect ratio, and
  9163. * a CSS width overrides the native pixel width. Bootstrap
  9164. * sizes the Cloudron logo with height:40px only. */
  9165. int idx = nd->img_index;
  9166. int iw = 0, ih = 0;
  9167. if (idx >= 0 && idx < image_count &&
  9168. images[idx].state == 1) {
  9169. iw = (int)images[idx].native_w;
  9170. ih = (int)images[idx].native_h;
  9171. if (iw <= 0 || ih <= 0) {
  9172. iw = (int)images[idx].img.w;
  9173. ih = (int)images[idx].img.h;
  9174. }
  9175. }
  9176. if (cs.width_kind) {
  9177. int ww = style_width_px(&cs, base);
  9178. line_w += ww > 0 ? ww : 64;
  9179. } else if (nd->width_attr) {
  9180. line_w += nd->width_attr;
  9181. } else if (nd->height_attr && iw && ih) {
  9182. line_w += iw * (int)nd->height_attr / ih;
  9183. } else if (cs.height_kind && iw && ih) {
  9184. /* A percentage height needs the parent's
  9185. * definite height (the logo's 2rem box), as in
  9186. * add_image_run(); otherwise it is auto. */
  9187. int hh = cs.height_kind == 1 ?
  9188. style_height_px(&cs, base) :
  9189. cs.height_kind == 2 &&
  9190. pst->height_kind == 1 ?
  9191. (int)pst->height * (int)cs.height / 100 :
  9192. 0;
  9193. line_w += hh > 0 ? iw * hh / ih : iw;
  9194. } else if (iw) {
  9195. line_w += iw;
  9196. } else {
  9197. line_w += 64;
  9198. }
  9199. continue;
  9200. }
  9201. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  9202. nd->tag == BR_TAG_TEXTAREA) &&
  9203. !s_eq(br_type(&doc, c), "hidden")) {
  9204. /* Form controls are replaced: CSS width applies even
  9205. * when they are inline (add_form_run's sizes). */
  9206. int fw = cs.width_kind ? style_width_px(&cs, base) :
  9207. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  9208. if (s_eq(br_type(&doc, c), "checkbox") ||
  9209. s_eq(br_type(&doc, c), "radio"))
  9210. fw = 16;
  9211. line_w += (fw > 0 ? fw : 120) +
  9212. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  9213. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  9214. continue;
  9215. }
  9216. if (nd->tag == BR_TAG_SVG) {
  9217. /* A replaced element: its own size, like add_svg_run()
  9218. * (its path children have no width). */
  9219. int sw, sh, sb = cs.width_kind ?
  9220. style_width_px(&cs, base) : base;
  9221. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  9222. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  9223. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  9224. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  9225. line_w += sw;
  9226. } else {
  9227. if (line_w > max_w)
  9228. max_w = line_w;
  9229. line_w = 0;
  9230. if (sw > max_w)
  9231. max_w = sw;
  9232. }
  9233. continue;
  9234. }
  9235. {
  9236. int cw = mp_px(&cs, 7, base) +
  9237. mp_px(&cs, 5, base) +
  9238. mp_px(&cs, 3, base) +
  9239. mp_px(&cs, 1, base) +
  9240. cs.border_w[1] + cs.border_w[3];
  9241. /* width/height do not apply to non-replaced inline
  9242. * boxes. The tagesschau home label is an inline span
  9243. * with width:1px for the mobile icon-only header; using
  9244. * that width made the whole subnav collapse to a
  9245. * one-character column. */
  9246. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  9247. cw += cs.width_kind == 1 ? cs.width :
  9248. style_width_px(&cs, base);
  9249. else
  9250. cw += intrinsic_width(ui, c, &cs, depth + 1,
  9251. base);
  9252. if (flex_row || cs.float_left ||
  9253. cs.display == BR_DISPLAY_INLINE ||
  9254. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  9255. line_w += cw;
  9256. } else {
  9257. if (line_w > max_w)
  9258. max_w = line_w;
  9259. line_w = 0;
  9260. if (cw > max_w)
  9261. max_w = cw;
  9262. }
  9263. }
  9264. if (line_w > 4096 || max_w > 4096)
  9265. break;
  9266. }
  9267. return line_w > max_w ? line_w : max_w;
  9268. }
  9269. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  9270. * the main user: .row > .col-md-* with float:left and a percentage width.
  9271. * Each column is laid out with its own left/right edge and the row advances
  9272. * to the tallest column. Returns the first child not consumed. */
  9273. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  9274. const struct br_style *pst, int depth,
  9275. unsigned short link)
  9276. {
  9277. unsigned int n = first;
  9278. int row_left = l->left, row_right = l->right;
  9279. int row_top, row_bottom, xl, xr, any = 0;
  9280. int fl_left = row_left, fl_right = row_right, fl_bottom;
  9281. flush_line(l);
  9282. row_top = l->y;
  9283. row_bottom = l->y;
  9284. fl_bottom = row_top;
  9285. xl = row_left;
  9286. xr = row_right;
  9287. while (n) {
  9288. struct br_node *nd = &doc.nodes[n];
  9289. struct br_style cs;
  9290. unsigned short lk = link;
  9291. int colw, right;
  9292. if (nd->type == BR_NODE_TEXT) {
  9293. if (text_node_blank(nd)) {
  9294. n = nd->next;
  9295. continue;
  9296. }
  9297. break;
  9298. }
  9299. br_style_for(&doc, n, pst, &cs);
  9300. if (cs.display == BR_DISPLAY_NONE) {
  9301. n = nd->next;
  9302. continue;
  9303. }
  9304. /* A float blockifies its box: Bootstrap floats inline
  9305. * anchors too (the navbar brand and its text links), and
  9306. * their padding must be honoured. */
  9307. /* An absolute/fixed sibling is out of flow and does not end
  9308. * the row: Bootstrap inserts its tooltip right after the
  9309. * hovered navbar <li>, and the row used to break there. */
  9310. if (!cs.float_left && (cs.pos == 1 || cs.pos == 2)) {
  9311. int sy = l->y, sl = l->left, sr = l->right;
  9312. layout_out_of_flow(l, n, &cs, depth, lk);
  9313. l->y = sy;
  9314. l->left = sl;
  9315. l->right = sr;
  9316. n = nd->next;
  9317. continue;
  9318. }
  9319. if (!cs.float_left)
  9320. break;
  9321. if (nd->tag == BR_TAG_A && nd->href_off)
  9322. lk = (unsigned short)n;
  9323. right = cs.float_left == 2;
  9324. if (cs.width_kind == 1 || cs.width_kind == 2 ||
  9325. cs.width_kind == 3) {
  9326. /* The column is the margin box: `width` is the
  9327. * content (or, with border-box, the border) box,
  9328. * and layout_block() takes margins, padding and
  9329. * borders back out of the column. A 200px float
  9330. * with margin-right:20px used to get 180px of
  9331. * content. */
  9332. int base = row_right - row_left;
  9333. colw = cs.width_kind == 1 ? (int)cs.width :
  9334. style_width_px(&cs, base);
  9335. colw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  9336. if (!cs.box_sizing)
  9337. colw += mp_px(&cs, 7, base) +
  9338. mp_px(&cs, 5, base) +
  9339. cs.border_w[1] + cs.border_w[3];
  9340. } else {
  9341. int base = row_right - row_left;
  9342. /* Shrink-to-fit outer width: borders too (Google's
  9343. * 1px-bordered "Anmelden" pill wrapped otherwise). */
  9344. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  9345. mp_px(&cs, 7, base) +
  9346. mp_px(&cs, 5, base) +
  9347. mp_px(&cs, 3, base) +
  9348. mp_px(&cs, 1, base) +
  9349. cs.border_w[1] + cs.border_w[3];
  9350. if (colw < 8)
  9351. colw = 8;
  9352. }
  9353. if (colw < 8)
  9354. colw = 8;
  9355. if (colw > row_right - row_left)
  9356. colw = row_right - row_left;
  9357. /* The float column width is already resolved. */
  9358. cs.width_kind = 0;
  9359. cs.max_width_kind = 0;
  9360. if (right) {
  9361. if (any && xr - colw < xl) {
  9362. row_top = row_bottom;
  9363. row_bottom = row_top;
  9364. xl = row_left;
  9365. xr = row_right;
  9366. }
  9367. if (xr - colw < xl)
  9368. colw = xr - xl;
  9369. if (colw < 8)
  9370. colw = 8;
  9371. l->left = xr - colw;
  9372. if (l->left < row_left)
  9373. l->left = row_left;
  9374. l->right = xr;
  9375. xr = l->left;
  9376. if (xr < fl_right)
  9377. fl_right = xr;
  9378. } else {
  9379. if (any && xl + colw > xr) {
  9380. row_top = row_bottom;
  9381. row_bottom = row_top;
  9382. xl = row_left;
  9383. xr = row_right;
  9384. }
  9385. l->left = xl;
  9386. l->right = xl + colw;
  9387. xl += colw;
  9388. if (xl > fl_left)
  9389. fl_left = xl;
  9390. }
  9391. if (l->right < l->left + 8)
  9392. l->right = l->left + 8;
  9393. l->y = row_top;
  9394. l->line_left = l->line_x = l->left;
  9395. l->run_x = l->left;
  9396. l->line_y = l->y;
  9397. l->line_h = 0;
  9398. l->nruns = 0;
  9399. l->space_pending = 0;
  9400. l->align = cs.align;
  9401. layout_block(l, n, &cs, depth + 1, lk);
  9402. if (l->y > row_bottom)
  9403. row_bottom = l->y;
  9404. if (l->y > fl_bottom)
  9405. fl_bottom = l->y;
  9406. any = 1;
  9407. n = nd->next;
  9408. }
  9409. l->left = row_left;
  9410. l->right = row_right;
  9411. if (n && any) {
  9412. struct br_node *nd = &doc.nodes[n];
  9413. int inline_next = 0;
  9414. if (nd->type == BR_NODE_TEXT) {
  9415. inline_next = 1;
  9416. } else if (nd->type == BR_NODE_ELEM) {
  9417. struct br_style cs;
  9418. br_style_for(&doc, n, pst, &cs);
  9419. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  9420. cs.display != BR_DISPLAY_NONE &&
  9421. !br_tag_is_block(nd->tag);
  9422. }
  9423. if (inline_next) {
  9424. if (l->float_active) {
  9425. if (l->float_left > fl_left)
  9426. fl_left = l->float_left;
  9427. if (l->float_right < fl_right)
  9428. fl_right = l->float_right;
  9429. if (l->float_bottom > fl_bottom)
  9430. fl_bottom = l->float_bottom;
  9431. }
  9432. l->float_active = 1;
  9433. l->float_left = fl_left;
  9434. l->float_right = fl_right;
  9435. l->float_bottom = fl_bottom;
  9436. l->y = row_top;
  9437. } else {
  9438. l->float_active = 0;
  9439. l->y = row_bottom;
  9440. }
  9441. } else {
  9442. l->float_active = 0;
  9443. l->y = row_bottom;
  9444. }
  9445. l->line_x = l->left;
  9446. l->run_x = l->left;
  9447. l->line_left = l->left;
  9448. l->line_right = l->right;
  9449. l->line_y = l->y;
  9450. l->line_h = 0;
  9451. l->nruns = 0;
  9452. l->space_pending = 0;
  9453. return n;
  9454. }
  9455. static int flex_item_width(struct lay *l, unsigned int n,
  9456. const struct br_style *cs, int avail)
  9457. {
  9458. struct br_node *nd = &doc.nodes[n];
  9459. (void)l;
  9460. int w;
  9461. if (cs->width_kind == 2 || cs->width_kind == 3)
  9462. w = style_width_px(cs, avail);
  9463. else if (cs->width_kind == 1)
  9464. w = (int)cs->width;
  9465. else if (nd->tag == BR_TAG_IMG) {
  9466. int idx = nd->img_index;
  9467. if (idx >= 0 && idx < image_count &&
  9468. images[idx].state == 1)
  9469. w = (int)images[idx].img.w;
  9470. else if (nd->width_attr)
  9471. w = (int)nd->width_attr;
  9472. else
  9473. w = 64;
  9474. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  9475. nd->tag == BR_TAG_TEXTAREA) {
  9476. /* A control has no content to measure: its default size
  9477. * (a search field in a filter bar). */
  9478. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  9479. } else {
  9480. w = intrinsic_width(l->ui, n, cs, 0, avail);
  9481. }
  9482. /* Explicit widths are content-box sizes; the flex item's outer width
  9483. * must include padding, borders and margins. */
  9484. w += mp_px(cs, 7, avail);
  9485. w += mp_px(cs, 5, avail);
  9486. w += mp_px(cs, 3, avail);
  9487. w += mp_px(cs, 1, avail);
  9488. w += cs->border_w[1] + cs->border_w[3];
  9489. if (w < 24)
  9490. w = 24;
  9491. if (w > avail)
  9492. w = avail;
  9493. return w;
  9494. }
  9495. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  9496. int depth);
  9497. /* An inline child of a text-only inline-block: the same test minus the
  9498. * display check (an inline <span> may have padding/background in CSS, but
  9499. * the inline path paints those for spans anyway). */
  9500. static int inline_block_flows_inline(unsigned int node,
  9501. const struct br_style *cs, int depth)
  9502. {
  9503. unsigned int c;
  9504. if (depth > 3 || cs->pos)
  9505. return 0;
  9506. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9507. const struct br_node *nd = &doc.nodes[c];
  9508. struct br_style ch;
  9509. if (nd->type != BR_NODE_ELEM)
  9510. continue;
  9511. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  9512. br_tag_is_block(nd->tag))
  9513. return 0;
  9514. br_style_for(&doc, c, cs, &ch);
  9515. if (ch.display == BR_DISPLAY_NONE)
  9516. continue;
  9517. if (ch.display != BR_DISPLAY_INLINE ||
  9518. !inline_block_flows_inline(c, &ch, depth + 1))
  9519. return 0;
  9520. }
  9521. return 1;
  9522. }
  9523. /* An inline-block that is only text in a line (a <time> in a byline, a
  9524. * label) with no box of its own -- no size, background, border or padding
  9525. * -- lays out exactly like an inline element, so it stays in the text line
  9526. * instead of ending it. Boxes with any of those keep the row path. */
  9527. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  9528. int depth)
  9529. {
  9530. unsigned int c;
  9531. int i;
  9532. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  9533. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  9534. cs->pos || depth > 3)
  9535. return 0;
  9536. for (i = 0; i < 4; i++)
  9537. if (cs->border_w[i])
  9538. return 0;
  9539. for (i = 4; i < 8; i++)
  9540. if (mp_px(cs, i, 0) > 0)
  9541. return 0;
  9542. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9543. const struct br_node *nd = &doc.nodes[c];
  9544. struct br_style ch;
  9545. if (nd->type != BR_NODE_ELEM)
  9546. continue;
  9547. if (nd->tag == BR_TAG_SVG) {
  9548. /* An icon box (Docusaurus' admonition heading:
  9549. * `<span inline-block><svg/></span>Note`): the SVG
  9550. * is an inline replaced run, so the box can stay in
  9551. * the text line. */
  9552. br_style_for(&doc, c, cs, &ch);
  9553. if (ch.display == BR_DISPLAY_NONE ||
  9554. ch.display == BR_DISPLAY_INLINE ||
  9555. ch.display == BR_DISPLAY_INLINE_BLOCK)
  9556. continue;
  9557. return 0;
  9558. }
  9559. if (nd->tag == BR_TAG_IMG || br_tag_is_block(nd->tag))
  9560. return 0;
  9561. br_style_for(&doc, c, cs, &ch);
  9562. if (ch.display == BR_DISPLAY_NONE)
  9563. continue;
  9564. if (ch.display != BR_DISPLAY_INLINE ||
  9565. !inline_block_flows_inline(c, &ch, depth + 1))
  9566. return 0;
  9567. }
  9568. return 1;
  9569. }
  9570. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  9571. * on one line, not one full-width block each. Place intrinsic widths from
  9572. * left to right and wrap when the row is full. */
  9573. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  9574. const struct br_style *pst, int depth,
  9575. unsigned short link)
  9576. {
  9577. unsigned int n = first;
  9578. int row_left = l->left, row_right = l->right;
  9579. int avail = row_right - row_left;
  9580. int x = row_left, y = l->y, row_h = 0, any = 0;
  9581. /* Each box sets l->align from its own style; the text after the row
  9582. * must keep the container's (a centred .fa-fw icon centred the menu
  9583. * label that followed it). */
  9584. unsigned char row_align = l->align;
  9585. flush_line(l);
  9586. y = l->y;
  9587. while (n) {
  9588. struct br_node *nd = &doc.nodes[n];
  9589. struct br_style cs;
  9590. unsigned short lk = link;
  9591. int colw, h;
  9592. if (nd->type == BR_NODE_TEXT) {
  9593. if (!text_node_blank(nd))
  9594. break;
  9595. if (any)
  9596. x += 4;
  9597. n = nd->next;
  9598. continue;
  9599. }
  9600. br_style_for(&doc, n, pst, &cs);
  9601. if (cs.display == BR_DISPLAY_NONE) {
  9602. n = nd->next;
  9603. continue;
  9604. }
  9605. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  9606. break;
  9607. if (nd->tag == BR_TAG_A && nd->href_off)
  9608. lk = (unsigned short)n;
  9609. colw = flex_item_width(l, n, &cs, avail);
  9610. /* A few pixels of slack keep a single long token (boot.S)
  9611. * from wrapping at the exact content width. */
  9612. colw += 8;
  9613. if (colw > avail)
  9614. colw = avail;
  9615. cs.width_kind = 0;
  9616. cs.max_width_kind = 0;
  9617. if (any && x + colw > row_right) {
  9618. y += row_h + 2;
  9619. x = row_left;
  9620. row_h = 0;
  9621. any = 0;
  9622. }
  9623. if (any && x > row_left)
  9624. x += 4;
  9625. l->left = x;
  9626. l->right = x + colw;
  9627. if (l->right < l->left + 8)
  9628. l->right = l->left + 8;
  9629. l->y = y;
  9630. l->line_left = l->line_x = l->left;
  9631. l->run_x = l->left;
  9632. l->line_y = l->y;
  9633. l->line_h = 0;
  9634. l->nruns = 0;
  9635. l->space_pending = 0;
  9636. l->align = cs.align;
  9637. layout_block(l, n, &cs, depth + 1, lk);
  9638. h = l->y - y;
  9639. if (h > row_h)
  9640. row_h = h;
  9641. x += colw;
  9642. any = 1;
  9643. n = nd->next;
  9644. }
  9645. if (any)
  9646. y += row_h;
  9647. l->left = row_left;
  9648. l->right = row_right;
  9649. l->align = row_align;
  9650. l->y = y;
  9651. l->line_left = l->line_x = l->left;
  9652. l->run_x = l->left;
  9653. l->line_y = l->y;
  9654. l->line_h = 0;
  9655. l->nruns = 0;
  9656. l->space_pending = 0;
  9657. return n;
  9658. }
  9659. struct flex_item {
  9660. unsigned int node;
  9661. unsigned short link;
  9662. int w;
  9663. };
  9664. /* An item's min-width/max-width as outer (margin-box) widths in the flex
  9665. * row, or -1 when unset. Percentages and calc() resolve against the
  9666. * container width. */
  9667. static int flex_limit_w(const struct br_style *cs, int which_max, int avail)
  9668. {
  9669. unsigned char kind = which_max ? cs->max_width_kind :
  9670. cs->min_width_kind;
  9671. int w;
  9672. if (kind == 3)
  9673. w = which_max ?
  9674. avail * cs->max_width_calc_pct / 100 +
  9675. cs->max_width_calc_px :
  9676. avail * cs->min_width_calc_pct / 100 +
  9677. cs->min_width_calc_px;
  9678. else
  9679. w = css_size(kind, which_max ? cs->max_width : cs->min_width,
  9680. avail);
  9681. if (w < 0)
  9682. return -1;
  9683. if (!cs->box_sizing)
  9684. w += mp_px(cs, 7, avail) + mp_px(cs, 5, avail) +
  9685. cs->border_w[1] + cs->border_w[3];
  9686. return w + mp_px(cs, 3, avail) + mp_px(cs, 1, avail);
  9687. }
  9688. static int flex_clamp_w(const struct br_style *cs, int w, int avail)
  9689. {
  9690. int mx = flex_limit_w(cs, 1, avail), mn = flex_limit_w(cs, 0, avail);
  9691. if (mx >= 0 && w > mx)
  9692. w = mx;
  9693. if (mn >= 0 && w < mn)
  9694. w = mn;
  9695. return w;
  9696. }
  9697. /* Does a flex row stretch this item to the line height? Only items with
  9698. * no height of their own and align-self/align-items stretch; replaced
  9699. * content (images, icons) keeps its aspect ratio. */
  9700. static int flex_item_stretches(unsigned int node, const struct br_style *cs,
  9701. const struct br_style *pst)
  9702. {
  9703. int ai = cs->align_self ? cs->align_self - 1 : pst->align_items;
  9704. unsigned char tag = doc.nodes[node].tag;
  9705. return ai == 0 && !cs->height_kind && !cs->max_height_kind &&
  9706. tag != BR_TAG_IMG && tag != BR_TAG_SVG && tag != BR_TAG_INPUT &&
  9707. tag != BR_TAG_SELECT && tag != BR_TAG_TEXTAREA &&
  9708. tag != BR_TAG_BUTTON;
  9709. }
  9710. static void flex_set_stretch(unsigned int node, const struct br_style *cs,
  9711. int line_h, int cbw)
  9712. {
  9713. int h = line_h - mp_px(cs, 0, cbw) - mp_px(cs, 2, cbw);
  9714. if (node >= BR_MAX_NODES || h <= 0)
  9715. return;
  9716. if (h > 65535)
  9717. h = 65535;
  9718. flex_stretch_h[node] = (unsigned short)h;
  9719. if (block_h[node] < h)
  9720. block_h[node] = (unsigned short)h;
  9721. }
  9722. static void layout_flex_children(struct lay *l, unsigned int parent,
  9723. const struct br_style *pst, int depth,
  9724. unsigned short link)
  9725. {
  9726. struct flex_item it[32];
  9727. unsigned int c;
  9728. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  9729. int grow_need = 0; /* growing items at their content width */
  9730. int row_left = l->left, row_right = l->right;
  9731. int avail = row_right - row_left;
  9732. int idx, row_top;
  9733. unsigned char row_align = l->align;
  9734. int box_left = l->left, box_right = l->right, row_top0 = l->y;
  9735. int bw = 0, aw = 0, first_h = -1;
  9736. int cont_h = l->cb_h; /* the container's definite content height */
  9737. struct br_style bps, aps;
  9738. if (avail < 8 || depth > 48) {
  9739. layout_children(l, parent, pst, depth, link);
  9740. return;
  9741. }
  9742. /* If direct text is not just whitespace, normal block flow handles it
  9743. * better than pretending it is a flex item. */
  9744. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9745. struct br_node *nd = &doc.nodes[c];
  9746. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9747. layout_children(l, parent, pst, depth, link);
  9748. return;
  9749. }
  9750. }
  9751. /* ::before/::after icon boxes are the row's first and last items
  9752. * (Docusaurus' sidebar chevron): reserve their columns. */
  9753. if (doc.npe_rules) {
  9754. bw = pseudo_box_w(parent, pst, 1, &bps, avail);
  9755. aw = pseudo_box_w(parent, pst, 2, &aps, avail);
  9756. if (bw + aw > avail - 8) {
  9757. bw = 0;
  9758. aw = 0;
  9759. }
  9760. row_left += bw;
  9761. row_right -= aw;
  9762. avail = row_right - row_left;
  9763. }
  9764. for (c = doc.nodes[parent].first;
  9765. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  9766. c = doc.nodes[c].next) {
  9767. struct br_node *nd = &doc.nodes[c];
  9768. struct br_style cs;
  9769. if (nd->type == BR_NODE_TEXT)
  9770. continue;
  9771. br_style_for(&doc, c, pst, &cs);
  9772. if (cs.display == BR_DISPLAY_NONE)
  9773. continue;
  9774. if ((cs.pos == 1 || cs.pos == 2) &&
  9775. layout_out_of_flow(l, c, &cs, depth,
  9776. (nd->tag == BR_TAG_A && nd->href_off) ?
  9777. (unsigned short)c : link))
  9778. continue; /* absolutely positioned: not an item */
  9779. it[nitem].node = c;
  9780. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  9781. (unsigned short)c : link;
  9782. it[nitem].w = 0;
  9783. if (cs.flex_grow && !cs.width_kind) {
  9784. grow_count++;
  9785. grow_need += flex_item_width(l, c, &cs, avail);
  9786. } else
  9787. fixed += flex_clamp_w(&cs,
  9788. flex_item_width(l, c, &cs, avail),
  9789. avail);
  9790. nitem++;
  9791. }
  9792. /* A narrow container (an icon row sized to its content, Google's
  9793. * mic + lens buttons) is still a row when its items fit; only a
  9794. * narrow one that would overflow or squeeze growing items falls
  9795. * back to block flow. */
  9796. if (avail < 160 && fixed + grow_need > avail) {
  9797. layout_children(l, parent, pst, depth, link);
  9798. return;
  9799. }
  9800. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  9801. /* A growing item capped by max-width (Docusaurus' doc column,
  9802. * `max-width: 75%`; its main container, `calc(100% - 300px)`)
  9803. * keeps its cap and leaves the rest of the free space to the other
  9804. * growing items. */
  9805. if (grow_count) {
  9806. int pass, capped[32] = { 0 };
  9807. for (pass = 0; pass < nitem; pass++) {
  9808. int changed = 0;
  9809. for (idx = 0; idx < nitem; idx++) {
  9810. struct br_style cs;
  9811. int lim;
  9812. if (capped[idx])
  9813. continue;
  9814. br_style_for(&doc, it[idx].node, pst, &cs);
  9815. if (!cs.flex_grow || cs.width_kind)
  9816. continue;
  9817. lim = flex_clamp_w(&cs, grow_w, avail);
  9818. if (lim == grow_w)
  9819. continue;
  9820. capped[idx] = lim + 1;
  9821. fixed += lim;
  9822. grow_count--;
  9823. changed = 1;
  9824. }
  9825. if (!changed || !grow_count)
  9826. break;
  9827. grow_w = (avail - fixed) / grow_count;
  9828. }
  9829. for (idx = 0; idx < nitem; idx++)
  9830. it[idx].w = capped[idx] ? capped[idx] - 1 : 0;
  9831. }
  9832. if (grow_w < 96 && avail >= 160)
  9833. grow_w = 96;
  9834. for (idx = 0; idx < nitem; idx++) {
  9835. struct br_style cs;
  9836. if (it[idx].w)
  9837. continue; /* capped growing item */
  9838. br_style_for(&doc, it[idx].node, pst, &cs);
  9839. if (cs.flex_grow && !cs.width_kind)
  9840. it[idx].w = grow_w;
  9841. else
  9842. it[idx].w = flex_clamp_w(&cs,
  9843. flex_item_width(l,
  9844. it[idx].node,
  9845. &cs, avail),
  9846. avail);
  9847. if (it[idx].w > avail)
  9848. it[idx].w = avail;
  9849. if (it[idx].w < 8)
  9850. it[idx].w = 8;
  9851. }
  9852. row_top = l->y;
  9853. idx = 0;
  9854. while (idx < nitem) {
  9855. int start = idx, count = 0, row_w = 0;
  9856. int free_w, x, extra = 0, row_h = 0, k;
  9857. while (idx < nitem) {
  9858. int add = it[idx].w + (count ? gap : 0);
  9859. /* CSS default is nowrap; only flex-wrap: wrap (1)
  9860. * starts a new row. */
  9861. if (count && pst->flex_wrap == 1 &&
  9862. row_w + add > avail)
  9863. break;
  9864. row_w += add;
  9865. count++;
  9866. idx++;
  9867. }
  9868. if (!count) {
  9869. count = 1;
  9870. row_w = it[start].w;
  9871. idx = start + 1;
  9872. }
  9873. free_w = avail - row_w;
  9874. if (free_w < 0)
  9875. free_w = 0;
  9876. x = row_left;
  9877. if (pst->justify == 1) {
  9878. x += free_w / 2;
  9879. } else if (pst->justify == 2) {
  9880. x += free_w;
  9881. } else if (pst->justify == 3) {
  9882. extra = count > 1 ? free_w / (count - 1) : 0;
  9883. } else if (pst->justify == 4) {
  9884. extra = count ? free_w / count : 0;
  9885. x += extra / 2;
  9886. } else if (pst->justify == 5) {
  9887. extra = count ? free_w / (count + 1) : 0;
  9888. x += extra;
  9889. }
  9890. for (k = 0; k < count; k++) {
  9891. int node = (int)it[start + k].node;
  9892. int h = block_h[node];
  9893. if (h > row_h)
  9894. row_h = h;
  9895. }
  9896. /* A single line fills a definite container height (an app
  9897. * shell's `height: 100%` sidebar + content row). */
  9898. if (pst->flex_wrap != 1 && cont_h > row_h)
  9899. row_h = cont_h;
  9900. else if (pst->height_kind == 1 && (int)pst->height > row_h)
  9901. row_h = pst->height;
  9902. for (k = 0; k < count; k++) {
  9903. struct br_style cs;
  9904. int node = (int)it[start + k].node;
  9905. int yoff = 0;
  9906. br_style_for(&doc, node, pst, &cs);
  9907. cs.width_kind = 0;
  9908. cs.max_width_kind = 0;
  9909. /* align-items: stretch. With a definite line height
  9910. * the item is laid out at it, so its own children see
  9911. * a definite height; otherwise the measure pass
  9912. * stretches it once the line is known (below). */
  9913. if (!l->draw && row_h > 0 && flex_item_stretches(node,
  9914. &cs, pst))
  9915. flex_set_stretch(node, &cs, row_h, avail);
  9916. {
  9917. int ai = cs.align_self ? cs.align_self - 1 :
  9918. pst->align_items;
  9919. if (l->draw && ai && row_h > block_h[node]) {
  9920. if (ai == 1)
  9921. yoff = (row_h -
  9922. block_h[node]) / 2;
  9923. else if (ai == 2)
  9924. yoff = row_h - block_h[node];
  9925. }
  9926. }
  9927. l->left = x;
  9928. l->right = x + it[start + k].w;
  9929. if (l->right < l->left + 8)
  9930. l->right = l->left + 8;
  9931. l->y = row_top + yoff;
  9932. /* line_left too: a stale one from the previous item
  9933. * made flush_line() see a non-empty line and push
  9934. * every later item down by an empty line's height. */
  9935. l->line_left = l->line_x = l->run_x = l->left;
  9936. l->line_right = l->right;
  9937. l->line_y = l->y;
  9938. l->line_h = 0;
  9939. l->nruns = 0;
  9940. l->space_pending = 0;
  9941. l->align = cs.align;
  9942. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  9943. {
  9944. /* Both passes: a form control item has no
  9945. * block_h of its own, so the draw pass would
  9946. * otherwise end a row of only an <input> at
  9947. * height 0 and pull the content below up. */
  9948. int h = l->y - row_top;
  9949. if (h > row_h)
  9950. row_h = h;
  9951. }
  9952. x += it[start + k].w;
  9953. if (k + 1 < count)
  9954. x += gap + extra;
  9955. }
  9956. if (!l->draw) {
  9957. for (k = 0; k < count; k++) {
  9958. struct br_style cs;
  9959. int node = (int)it[start + k].node;
  9960. br_style_for(&doc, node, pst, &cs);
  9961. if (!flex_item_stretches(node, &cs, pst))
  9962. continue;
  9963. /* To the line's bottom edge from where the
  9964. * item really starts (its top margin, or a
  9965. * line box above it). */
  9966. if (layout_boxes[node].valid)
  9967. flex_set_stretch(node, &cs,
  9968. row_top + row_h -
  9969. layout_boxes[node].y +
  9970. mp_px(&cs, 0, avail), avail);
  9971. else
  9972. flex_set_stretch(node, &cs, row_h, avail);
  9973. }
  9974. }
  9975. if (first_h < 0)
  9976. first_h = row_h;
  9977. row_top += row_h;
  9978. }
  9979. if (bw || aw) {
  9980. int pass;
  9981. for (pass = 0; pass < 2; pass++) {
  9982. const struct br_style *ps = pass ? &aps : &bps;
  9983. int a = pass ? row_right : box_left;
  9984. int b = pass ? box_right : row_left;
  9985. int h = ps->height_kind ?
  9986. style_height_px(ps, box_right - box_left) : 0;
  9987. if (!(pass ? aw : bw))
  9988. continue;
  9989. l->left = l->line_left = l->line_x = l->run_x = a;
  9990. l->right = l->line_right = b;
  9991. l->y = row_top0;
  9992. if (pst->align_items == 1 && first_h > h)
  9993. l->y += (first_h - h) / 2;
  9994. l->line_y = l->y;
  9995. l->line_h = 0;
  9996. l->nruns = 0;
  9997. l->space_pending = 0;
  9998. emit_pseudo_box(l, pst, ps, link);
  9999. flush_line(l);
  10000. /* The box sits inside the first row; it only makes
  10001. * the row taller when it is taller itself. */
  10002. if (row_top0 + h > row_top)
  10003. row_top = row_top0 + h;
  10004. }
  10005. }
  10006. l->left = box_left;
  10007. l->right = box_right;
  10008. l->align = row_align;
  10009. l->y = row_top;
  10010. l->line_left = l->line_x = l->run_x = l->left;
  10011. l->line_right = l->right;
  10012. l->line_y = l->y;
  10013. l->line_h = 0;
  10014. l->nruns = 0;
  10015. l->space_pending = 0;
  10016. }
  10017. /* flex-direction: column. Items stack in order with the gap and never
  10018. * collapse margins. In the draw pass justify-content shares out the free
  10019. * height of the container's measured box (a definite or min-height, or a
  10020. * row stretch), and align-items places each item: stretch (the default)
  10021. * fills the line, start/center/end shrink an item to its content width
  10022. * (a login form's "Log in" button, a centred logo and name). */
  10023. static void layout_flex_column(struct lay *l, unsigned int parent,
  10024. const struct br_style *pst, int depth,
  10025. unsigned short link)
  10026. {
  10027. unsigned int c;
  10028. int box_left = l->left, box_right = l->right;
  10029. int avail = box_right - box_left;
  10030. int gap = pst->grid_gap, y0 = l->y;
  10031. int n = 0, k = 0, total = 0, lead = 0, extra = 0;
  10032. unsigned char row_align = l->align;
  10033. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10034. struct br_node *nd = &doc.nodes[c];
  10035. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd))
  10036. break;
  10037. }
  10038. if (c || avail < 8 || depth > 48) {
  10039. /* Loose text: block flow, with centred lines standing in
  10040. * for align-items: center. */
  10041. struct br_style cst = *pst;
  10042. if (pst->align_items == 1) {
  10043. cst.align = BR_ALIGN_CENTER;
  10044. l->align = BR_ALIGN_CENTER;
  10045. }
  10046. layout_children(l, parent, &cst, depth, link);
  10047. return;
  10048. }
  10049. emit_pseudo(l, parent, pst, 1, link);
  10050. flush_line(l);
  10051. y0 = l->y;
  10052. if (l->draw && parent < BR_MAX_NODES && block_h[parent]) {
  10053. int inner = (int)block_h[parent] - pst->border_w[0] -
  10054. pst->border_w[2] - mp_px(pst, 4, avail) -
  10055. mp_px(pst, 6, avail) - (y0 - l->parent_top -
  10056. pst->border_w[0] - mp_px(pst, 4, avail));
  10057. int free_h;
  10058. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10059. struct br_style cs;
  10060. if (doc.nodes[c].type != BR_NODE_ELEM)
  10061. continue;
  10062. br_style_for(&doc, c, pst, &cs);
  10063. if (cs.display == BR_DISPLAY_NONE || cs.pos == 1 ||
  10064. cs.pos == 2)
  10065. continue;
  10066. total += block_h[c] + mp_px(&cs, 0, avail) +
  10067. mp_px(&cs, 2, avail);
  10068. n++;
  10069. }
  10070. if (n > 1)
  10071. total += gap * (n - 1);
  10072. free_h = inner - total;
  10073. if (n && free_h > 0) {
  10074. if (pst->justify == 1) {
  10075. lead = free_h / 2;
  10076. } else if (pst->justify == 2) {
  10077. lead = free_h;
  10078. } else if (pst->justify == 3) {
  10079. extra = n > 1 ? free_h / (n - 1) : 0;
  10080. } else if (pst->justify == 4) {
  10081. extra = free_h / n;
  10082. lead = extra / 2;
  10083. } else if (pst->justify == 5) {
  10084. extra = free_h / (n + 1);
  10085. lead = extra;
  10086. }
  10087. }
  10088. }
  10089. l->y = y0 + lead;
  10090. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10091. struct br_node *nd = &doc.nodes[c];
  10092. unsigned short lk = (nd->tag == BR_TAG_A && nd->href_off) ?
  10093. (unsigned short)c : link;
  10094. struct br_style cs;
  10095. int ai, left = box_left, right = box_right;
  10096. if (nd->type != BR_NODE_ELEM)
  10097. continue;
  10098. br_style_for(&doc, c, pst, &cs);
  10099. if (cs.display == BR_DISPLAY_NONE)
  10100. continue;
  10101. if ((cs.pos == 1 || cs.pos == 2) &&
  10102. layout_out_of_flow(l, c, &cs, depth, lk))
  10103. continue;
  10104. if (k++)
  10105. l->y += gap + extra;
  10106. ai = cs.align_self ? cs.align_self - 1 : pst->align_items;
  10107. if (ai) {
  10108. int w = flex_clamp_w(&cs, flex_item_width(l, c, &cs,
  10109. avail),
  10110. avail);
  10111. if (ai == 1)
  10112. left += (avail - w) / 2;
  10113. else if (ai == 2)
  10114. left += avail - w;
  10115. right = left + w;
  10116. cs.width_kind = 0;
  10117. cs.max_width_kind = 0;
  10118. }
  10119. l->left = l->line_left = l->line_x = l->run_x = left;
  10120. l->right = l->line_right = right;
  10121. l->line_y = l->y;
  10122. l->line_h = 0;
  10123. l->nruns = 0;
  10124. l->space_pending = 0;
  10125. l->align = cs.align;
  10126. layout_block(l, c, &cs, depth + 1, lk);
  10127. }
  10128. l->left = l->line_left = l->line_x = l->run_x = box_left;
  10129. l->right = l->line_right = box_right;
  10130. l->align = row_align;
  10131. l->line_y = l->y;
  10132. l->line_h = 0;
  10133. l->nruns = 0;
  10134. l->space_pending = 0;
  10135. emit_pseudo(l, parent, pst, 2, link);
  10136. }
  10137. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  10138. * plus the grid-area hints used by site shells (site notice/footer full
  10139. * width, column-start left, page-content right). Anything more elaborate
  10140. * falls back to normal block flow. */
  10141. static int grid_track_width(unsigned char kind, unsigned short val,
  10142. int avail, int other)
  10143. {
  10144. if (kind == 2)
  10145. return avail * (int)val / 100;
  10146. if (kind == 1)
  10147. return val;
  10148. return other;
  10149. }
  10150. static void layout_grid_children(struct lay *l, unsigned int parent,
  10151. const struct br_style *pst, int depth,
  10152. unsigned short link)
  10153. {
  10154. unsigned int n;
  10155. int row_left = l->left, row_right = l->right;
  10156. int avail = row_right - row_left;
  10157. int gap = pst->grid_gap;
  10158. int track_total = avail - gap;
  10159. int col0, col1, x0, x1;
  10160. int row_y, row_bottom, have_left = 0, have_right = 0;
  10161. unsigned int c;
  10162. if (avail < 32 || depth > 48)
  10163. return;
  10164. if (track_total < 16)
  10165. track_total = 16;
  10166. col0 = grid_track_width((unsigned char)(pst->width_kind),
  10167. pst->width, track_total, 0);
  10168. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  10169. pst->max_width, track_total, 0);
  10170. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  10171. int w0 = pst->width ? pst->width : 1;
  10172. int w1 = pst->max_width ? pst->max_width : 1;
  10173. col0 = track_total * w0 / (w0 + w1);
  10174. col1 = track_total - col0;
  10175. } else if (pst->width_kind == 3) {
  10176. col0 = track_total - col1;
  10177. if (col0 < 24)
  10178. col0 = 24;
  10179. } else if (pst->max_width_kind == 3) {
  10180. col1 = track_total - col0;
  10181. if (col1 < 24)
  10182. col1 = 24;
  10183. }
  10184. if (col0 < 24)
  10185. col0 = 24;
  10186. if (col1 < 24)
  10187. col1 = 24;
  10188. if (col0 + col1 > track_total) {
  10189. col1 = track_total - col0;
  10190. if (col1 < 24)
  10191. col1 = 24;
  10192. }
  10193. x0 = row_left;
  10194. x1 = row_left + col0 + gap;
  10195. /* Direct text makes a grid ambiguous; use block flow instead. */
  10196. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10197. struct br_node *nd = &doc.nodes[c];
  10198. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  10199. layout_children(l, parent, pst, depth, link);
  10200. return;
  10201. }
  10202. }
  10203. row_y = row_bottom = l->y;
  10204. n = doc.nodes[parent].first;
  10205. while (n) {
  10206. struct br_node *nd = &doc.nodes[n];
  10207. struct br_style cs;
  10208. unsigned short lk = link;
  10209. int slot, x, w;
  10210. if (nd->type == BR_NODE_TEXT) {
  10211. n = nd->next;
  10212. continue;
  10213. }
  10214. br_style_for(&doc, n, pst, &cs);
  10215. if (cs.display == BR_DISPLAY_NONE) {
  10216. n = nd->next;
  10217. continue;
  10218. }
  10219. if (nd->tag == BR_TAG_A && nd->href_off)
  10220. lk = (unsigned short)n;
  10221. slot = cs.grid_slot;
  10222. if (!slot) {
  10223. if (!have_left)
  10224. slot = 2;
  10225. else if (!have_right)
  10226. slot = 3;
  10227. else
  10228. slot = 2;
  10229. }
  10230. if (slot == 1) {
  10231. if (have_left || have_right) {
  10232. row_y = row_bottom;
  10233. have_left = have_right = 0;
  10234. }
  10235. x = row_left;
  10236. w = avail;
  10237. } else if (slot == 2) {
  10238. if (have_left) {
  10239. row_y = row_bottom;
  10240. have_left = have_right = 0;
  10241. }
  10242. x = x0;
  10243. w = col0;
  10244. have_left = 1;
  10245. } else {
  10246. if (have_right) {
  10247. row_y = row_bottom;
  10248. have_left = have_right = 0;
  10249. }
  10250. x = x1;
  10251. w = col1;
  10252. have_right = 1;
  10253. }
  10254. cs.width_kind = 0;
  10255. cs.max_width_kind = 0;
  10256. l->left = x;
  10257. l->right = x + w;
  10258. if (l->right < l->left + 8)
  10259. l->right = l->left + 8;
  10260. l->y = row_y;
  10261. l->line_left = l->line_x = l->left;
  10262. l->run_x = l->left;
  10263. l->line_y = l->y;
  10264. l->line_h = 0;
  10265. l->nruns = 0;
  10266. l->space_pending = 0;
  10267. l->align = cs.align;
  10268. layout_block(l, n, &cs, depth + 1, lk);
  10269. if (l->y > row_bottom)
  10270. row_bottom = l->y;
  10271. n = nd->next;
  10272. }
  10273. l->left = row_left;
  10274. l->right = row_right;
  10275. l->y = row_bottom;
  10276. l->line_left = l->line_x = l->left;
  10277. l->run_x = l->left;
  10278. l->line_y = l->y;
  10279. l->line_h = 0;
  10280. l->nruns = 0;
  10281. l->space_pending = 0;
  10282. }
  10283. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  10284. * capped at four. Used by the project docs' card grids. A fixed
  10285. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  10286. static void layout_grid_auto(struct lay *l, unsigned int parent,
  10287. const struct br_style *pst, int depth,
  10288. unsigned short link)
  10289. {
  10290. unsigned int n, c;
  10291. int row_left = l->left, row_right = l->right;
  10292. int avail = row_right - row_left;
  10293. int gap = pst->grid_gap;
  10294. int minw = pst->width_kind == 1 ? pst->width : 200;
  10295. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  10296. if (avail < 32 || depth > 48) {
  10297. layout_children(l, parent, pst, depth, link);
  10298. return;
  10299. }
  10300. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10301. struct br_node *nd = &doc.nodes[c];
  10302. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  10303. layout_children(l, parent, pst, depth, link);
  10304. return;
  10305. }
  10306. }
  10307. if (minw < 80)
  10308. minw = 80;
  10309. ncols = (avail + gap) / (minw + gap);
  10310. if (ncols < 1)
  10311. ncols = 1;
  10312. if (ncols > 4)
  10313. ncols = 4;
  10314. if (pst->grid_auto > BR_GRID_FIXED) {
  10315. /* grid-template-columns: repeat(N, 1fr) */
  10316. ncols = pst->grid_auto - BR_GRID_FIXED;
  10317. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  10318. ncols--;
  10319. }
  10320. colw = (avail - gap * (ncols - 1)) / ncols;
  10321. if (colw < 24)
  10322. colw = 24;
  10323. x = row_left;
  10324. n = doc.nodes[parent].first;
  10325. while (n) {
  10326. struct br_node *nd = &doc.nodes[n];
  10327. struct br_style cs;
  10328. unsigned short lk = link;
  10329. int h;
  10330. if (nd->type == BR_NODE_TEXT) {
  10331. n = nd->next;
  10332. continue;
  10333. }
  10334. br_style_for(&doc, n, pst, &cs);
  10335. if (cs.display == BR_DISPLAY_NONE) {
  10336. n = nd->next;
  10337. continue;
  10338. }
  10339. if (nd->tag == BR_TAG_A && nd->href_off)
  10340. lk = (unsigned short)n;
  10341. cs.width_kind = 0;
  10342. cs.max_width_kind = 0;
  10343. l->left = x;
  10344. l->right = x + colw;
  10345. if (l->right < l->left + 8)
  10346. l->right = l->left + 8;
  10347. l->y = y;
  10348. l->line_left = l->line_x = l->left;
  10349. l->run_x = l->left;
  10350. l->line_y = l->y;
  10351. l->line_h = 0;
  10352. l->nruns = 0;
  10353. l->space_pending = 0;
  10354. l->align = cs.align;
  10355. layout_block(l, n, &cs, depth + 1, lk);
  10356. h = l->y - y;
  10357. if (h > row_h)
  10358. row_h = h;
  10359. col++;
  10360. n = nd->next;
  10361. if (col == ncols) {
  10362. y += row_h + gap;
  10363. x = row_left;
  10364. row_h = 0;
  10365. col = 0;
  10366. } else {
  10367. x += colw + gap;
  10368. }
  10369. }
  10370. if (col)
  10371. y += row_h;
  10372. else if (y > start_y)
  10373. y -= gap;
  10374. l->left = row_left;
  10375. l->right = row_right;
  10376. l->y = y;
  10377. l->line_left = l->line_x = l->left;
  10378. l->run_x = l->left;
  10379. l->line_y = l->y;
  10380. l->line_h = 0;
  10381. l->nruns = 0;
  10382. l->space_pending = 0;
  10383. }
  10384. /* Column widths are the widest cell in each column across every row, so all
  10385. * rows line up. The table model is still deliberately basic: no colspan,
  10386. * border-collapse or percentage columns. */
  10387. static void table_columns(struct lay *l, unsigned int table,
  10388. const struct br_style *pst, int avail,
  10389. int *raw, int maxcols, int *out_cols,
  10390. int *out_total)
  10391. {
  10392. unsigned int r, c;
  10393. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  10394. int fixed[12];
  10395. for (c = 0; c < (unsigned int)maxcols; c++) {
  10396. raw[c] = 0;
  10397. fixed[c] = 0;
  10398. }
  10399. /* Intrinsic widths of single-column cells. */
  10400. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10401. struct br_node *rn = &doc.nodes[r];
  10402. int col = 0;
  10403. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10404. continue;
  10405. for (c = rn->first; c; c = doc.nodes[c].next) {
  10406. struct br_node *cn = &doc.nodes[c];
  10407. struct br_style cs;
  10408. int w, span;
  10409. if (cn->type != BR_NODE_ELEM ||
  10410. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10411. continue;
  10412. span = cn->colspan ? cn->colspan : 1;
  10413. br_style_for(&doc, c, pst, &cs);
  10414. if (cs.display == BR_DISPLAY_NONE)
  10415. continue;
  10416. if (col + span > maxcols)
  10417. span = maxcols - col;
  10418. if (span < 1)
  10419. break;
  10420. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  10421. mp_px(&cs, 7, avail) +
  10422. mp_px(&cs, 5, avail) +
  10423. mp_px(&cs, 3, avail) +
  10424. mp_px(&cs, 1, avail) +
  10425. cs.border_w[0] + cs.border_w[1] +
  10426. cs.border_w[2] + cs.border_w[3];
  10427. if (w < 24)
  10428. w = 24;
  10429. if (span == 1) {
  10430. if (w > raw[col])
  10431. raw[col] = w;
  10432. }
  10433. if (col + span > cols)
  10434. cols = col + span;
  10435. col += span;
  10436. }
  10437. }
  10438. /* A colspan cell only has to be as wide as the sum of its columns. */
  10439. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10440. struct br_node *rn = &doc.nodes[r];
  10441. int col = 0;
  10442. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10443. continue;
  10444. for (c = rn->first; c; c = doc.nodes[c].next) {
  10445. struct br_node *cn = &doc.nodes[c];
  10446. struct br_style cs;
  10447. int span, w, sum, i;
  10448. if (cn->type != BR_NODE_ELEM ||
  10449. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10450. continue;
  10451. span = cn->colspan ? cn->colspan : 1;
  10452. if (col + span > maxcols)
  10453. span = maxcols - col;
  10454. if (span < 1)
  10455. break;
  10456. if (span > 1) {
  10457. br_style_for(&doc, c, pst, &cs);
  10458. if (cs.display != BR_DISPLAY_NONE) {
  10459. w = intrinsic_width(l->ui, c, &cs,
  10460. 0, avail) +
  10461. mp_px(&cs, 7, avail) +
  10462. mp_px(&cs, 5, avail) +
  10463. mp_px(&cs, 3, avail) +
  10464. mp_px(&cs, 1, avail) +
  10465. cs.border_w[0] + cs.border_w[1] +
  10466. cs.border_w[2] + cs.border_w[3];
  10467. sum = 0;
  10468. for (i = 0; i < span; i++)
  10469. sum += raw[col + i];
  10470. if (w > sum)
  10471. raw[col + span - 1] += w - sum;
  10472. }
  10473. }
  10474. col += span;
  10475. }
  10476. }
  10477. /* Explicit and percentage widths override intrinsic widths. */
  10478. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10479. struct br_node *rn = &doc.nodes[r];
  10480. int col = 0;
  10481. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10482. continue;
  10483. for (c = rn->first; c; c = doc.nodes[c].next) {
  10484. struct br_node *cn = &doc.nodes[c];
  10485. struct br_style cs;
  10486. int span;
  10487. if (cn->type != BR_NODE_ELEM ||
  10488. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10489. continue;
  10490. span = cn->colspan ? cn->colspan : 1;
  10491. if (col + span > maxcols)
  10492. span = maxcols - col;
  10493. if (span < 1)
  10494. break;
  10495. if (span == 1) {
  10496. br_style_for(&doc, c, pst, &cs);
  10497. if (cs.display != BR_DISPLAY_NONE) {
  10498. if (cs.width_kind == 1) {
  10499. raw[col] = cs.width;
  10500. fixed[col] = 1;
  10501. } else if (cs.width_kind == 2 ||
  10502. cs.width_kind == 3) {
  10503. raw[col] = style_width_px(&cs,
  10504. avail);
  10505. fixed[col] = 1;
  10506. }
  10507. }
  10508. }
  10509. col += span;
  10510. }
  10511. }
  10512. for (c = 0; c < (unsigned int)cols; c++) {
  10513. if (raw[c] < 8)
  10514. raw[c] = 8;
  10515. total += raw[c];
  10516. if (fixed[c])
  10517. fixed_sum += raw[c];
  10518. else {
  10519. free_raw += raw[c];
  10520. free_cols++;
  10521. }
  10522. }
  10523. if (fixed_sum > 0 && fixed_sum < avail) {
  10524. int free_avail = avail - fixed_sum;
  10525. int i;
  10526. if (free_raw > 0) {
  10527. for (i = 0; i < cols; i++)
  10528. if (!fixed[i])
  10529. raw[i] = free_avail * raw[i] /
  10530. free_raw;
  10531. } else if (free_cols > 0) {
  10532. for (i = 0; i < cols; i++)
  10533. if (!fixed[i])
  10534. raw[i] = free_avail / free_cols;
  10535. }
  10536. total = 0;
  10537. for (i = 0; i < cols; i++)
  10538. total += raw[i];
  10539. } else if (total < avail && total > 0) {
  10540. int i;
  10541. for (i = 0; i < cols; i++)
  10542. raw[i] = raw[i] * avail / total;
  10543. total = 0;
  10544. for (i = 0; i < cols; i++)
  10545. total += raw[i];
  10546. }
  10547. *out_cols = cols;
  10548. *out_total = total;
  10549. }
  10550. static void layout_table_row(struct lay *l, unsigned int row,
  10551. const struct br_style *pst, int depth,
  10552. unsigned short link)
  10553. {
  10554. unsigned int n, cell[12];
  10555. int raw[12], colstart[12], colspan[12];
  10556. int prefix[13];
  10557. int ncell = 0, total = 0, cols = 0, col = 0;
  10558. int row_left = l->left, row_right = l->right;
  10559. int avail = row_right - row_left;
  10560. int y = l->y, bottom = l->y;
  10561. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  10562. struct br_node *nd = &doc.nodes[n];
  10563. struct br_style cs;
  10564. int span;
  10565. if (nd->type == BR_NODE_TEXT) {
  10566. if (text_node_blank(nd))
  10567. continue;
  10568. layout_children(l, row, pst, depth, link);
  10569. return;
  10570. }
  10571. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  10572. layout_children(l, row, pst, depth, link);
  10573. return;
  10574. }
  10575. br_style_for(&doc, n, pst, &cs);
  10576. if (cs.display == BR_DISPLAY_NONE)
  10577. continue;
  10578. if (ncell >= 12) {
  10579. layout_children(l, row, pst, depth, link);
  10580. return;
  10581. }
  10582. span = nd->colspan ? nd->colspan : 1;
  10583. if (span > 12 - col)
  10584. span = 12 - col;
  10585. if (span < 1)
  10586. continue;
  10587. cell[ncell] = n;
  10588. colstart[ncell] = col;
  10589. colspan[ncell] = span;
  10590. col += span;
  10591. ncell++;
  10592. }
  10593. if (ncell < 1 || avail < 32) {
  10594. layout_children(l, row, pst, depth, link);
  10595. return;
  10596. }
  10597. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  10598. &total);
  10599. if (cols < 2 || total <= 0) {
  10600. int c;
  10601. total = 0;
  10602. for (c = 0; c < ncell; c++) {
  10603. struct br_style cs;
  10604. br_style_for(&doc, cell[c], pst, &cs);
  10605. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  10606. avail) +
  10607. mp_px(&cs, 7, avail) +
  10608. mp_px(&cs, 5, avail) +
  10609. mp_px(&cs, 3, avail) +
  10610. mp_px(&cs, 1, avail);
  10611. if (raw[c] < 24)
  10612. raw[c] = 24;
  10613. total += raw[c];
  10614. }
  10615. /* A one-column table still has to fill its own width; the
  10616. * intrinsic fallback above otherwise leaves the cell at its
  10617. * text width (HN's outer table and nested story table). */
  10618. if (total > 0 && total < avail) {
  10619. int c;
  10620. for (c = 0; c < ncell; c++)
  10621. raw[c] = raw[c] * avail / total;
  10622. total = avail;
  10623. }
  10624. }
  10625. prefix[0] = row_left;
  10626. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  10627. prefix[n + 1] = prefix[n] + raw[n];
  10628. for (n = 0; n < (unsigned int)ncell; n++) {
  10629. struct br_style cs;
  10630. int start = colstart[n];
  10631. int end = start + colspan[n];
  10632. int w;
  10633. if (end > cols)
  10634. end = cols;
  10635. if (start >= cols)
  10636. continue;
  10637. w = prefix[end] - prefix[start];
  10638. br_style_for(&doc, cell[n], pst, &cs);
  10639. /* The column width already reflects the cell's width property. */
  10640. cs.width_kind = 0;
  10641. cs.max_width_kind = 0;
  10642. if (w < 24)
  10643. w = 24;
  10644. if (w < 8)
  10645. w = 8;
  10646. l->left = prefix[start];
  10647. l->right = l->left + w;
  10648. l->y = y;
  10649. l->line_left = l->line_x = l->left;
  10650. l->run_x = l->left;
  10651. l->line_y = l->y;
  10652. l->line_h = 0;
  10653. l->nruns = 0;
  10654. l->space_pending = 0;
  10655. l->align = cs.align;
  10656. layout_block(l, cell[n], &cs, depth + 1, link);
  10657. if (l->y > bottom)
  10658. bottom = l->y;
  10659. }
  10660. l->left = row_left;
  10661. l->right = row_right;
  10662. l->y = bottom;
  10663. l->line_left = l->line_x = l->left;
  10664. l->run_x = l->left;
  10665. l->line_y = l->y;
  10666. l->line_h = 0;
  10667. l->nruns = 0;
  10668. l->space_pending = 0;
  10669. }
  10670. #define TBL_MAX_ROWS 32
  10671. #define TBL_MAX_COLS 12
  10672. #define TBL_MAX_CELLS 128
  10673. struct tbl_cell {
  10674. unsigned int node;
  10675. unsigned char row, col, rowspan, colspan;
  10676. int height;
  10677. };
  10678. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  10679. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  10680. static int table_active;
  10681. static int table_has_rowspan(unsigned int table)
  10682. {
  10683. unsigned int r, c;
  10684. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10685. struct br_node *rn = &doc.nodes[r];
  10686. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10687. continue;
  10688. for (c = rn->first; c; c = doc.nodes[c].next) {
  10689. struct br_node *cn = &doc.nodes[c];
  10690. if (cn->type == BR_NODE_ELEM &&
  10691. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  10692. cn->rowspan > 1)
  10693. return 1;
  10694. }
  10695. }
  10696. return 0;
  10697. }
  10698. static void table_cell_style(unsigned int row, unsigned int cell,
  10699. const struct br_style *st, struct br_style *out)
  10700. {
  10701. struct br_style trs;
  10702. br_style_for(&doc, row, st, &trs);
  10703. br_style_for(&doc, cell, &trs, out);
  10704. }
  10705. /* Tables that use rowspan need row heights before anything is painted. This
  10706. * path builds a small occupancy grid, measures the natural cell heights, then
  10707. * lays every cell out at its row/column position. Tables without rowspan
  10708. * keep the lighter per-row path in layout_table_row(). */
  10709. static void layout_table(struct lay *l, unsigned int table,
  10710. const struct br_style *st, int depth,
  10711. unsigned short link)
  10712. {
  10713. unsigned int rows[TBL_MAX_ROWS];
  10714. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  10715. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  10716. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  10717. int free_raw = 0, free_cols = 0;
  10718. int table_left = l->left, table_right = l->right;
  10719. int top = l->y, avail = table_right - table_left;
  10720. unsigned int r, c;
  10721. int i, rr, cc;
  10722. if (depth > 48 || table_active) {
  10723. layout_children(l, table, st, depth, link);
  10724. return;
  10725. }
  10726. table_active = 1;
  10727. for (r = doc.nodes[table].first;
  10728. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  10729. struct br_node *rn = &doc.nodes[r];
  10730. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  10731. rows[nrows++] = r;
  10732. }
  10733. if (!nrows) {
  10734. table_active = 0;
  10735. layout_children(l, table, st, depth, link);
  10736. return;
  10737. }
  10738. for (rr = 0; rr < nrows; rr++)
  10739. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  10740. tbl_at[rr][cc] = 0;
  10741. for (rr = 0; rr < nrows; rr++) {
  10742. int col = 0;
  10743. for (c = doc.nodes[rows[rr]].first; c;
  10744. c = doc.nodes[c].next) {
  10745. struct br_node *cn = &doc.nodes[c];
  10746. struct br_style cs;
  10747. int rs, csn;
  10748. if (cn->type != BR_NODE_ELEM ||
  10749. (cn->tag != BR_TAG_TD &&
  10750. cn->tag != BR_TAG_TH))
  10751. continue;
  10752. table_cell_style(rows[rr], c, st, &cs);
  10753. if (cs.display == BR_DISPLAY_NONE)
  10754. continue;
  10755. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  10756. col++;
  10757. if (col >= TBL_MAX_COLS)
  10758. break;
  10759. rs = cn->rowspan ? cn->rowspan : 1;
  10760. csn = cn->colspan ? cn->colspan : 1;
  10761. if (rr + rs > nrows)
  10762. rs = nrows - rr;
  10763. if (col + csn > TBL_MAX_COLS)
  10764. csn = TBL_MAX_COLS - col;
  10765. if (rs < 1 || csn < 1)
  10766. continue;
  10767. if (ncells >= TBL_MAX_CELLS)
  10768. break;
  10769. tbl_cells[ncells].node = c;
  10770. tbl_cells[ncells].row = (unsigned char)rr;
  10771. tbl_cells[ncells].col = (unsigned char)col;
  10772. tbl_cells[ncells].rowspan = (unsigned char)rs;
  10773. tbl_cells[ncells].colspan = (unsigned char)csn;
  10774. tbl_cells[ncells].height = 0;
  10775. for (i = rr; i < rr + rs; i++)
  10776. for (int j = col; j < col + csn; j++)
  10777. tbl_at[i][j] =
  10778. (unsigned short)(ncells + 1);
  10779. ncells++;
  10780. col += csn;
  10781. if (col > cols)
  10782. cols = col;
  10783. }
  10784. }
  10785. if (!ncells || cols < 1) {
  10786. table_active = 0;
  10787. layout_children(l, table, st, depth, link);
  10788. return;
  10789. }
  10790. for (i = 0; i < cols; i++) {
  10791. raw[i] = 0;
  10792. fixed[i] = 0;
  10793. }
  10794. /* Intrinsic widths of single-column cells. */
  10795. for (i = 0; i < ncells; i++) {
  10796. struct br_style cs;
  10797. int w;
  10798. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10799. st, &cs);
  10800. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10801. mp_px(&cs, 7, avail) +
  10802. mp_px(&cs, 5, avail) +
  10803. mp_px(&cs, 3, avail) +
  10804. mp_px(&cs, 1, avail) +
  10805. cs.border_w[0] + cs.border_w[1] +
  10806. cs.border_w[2] + cs.border_w[3];
  10807. if (w < 24)
  10808. w = 24;
  10809. if (tbl_cells[i].colspan == 1) {
  10810. int col = tbl_cells[i].col;
  10811. if (w > raw[col])
  10812. raw[col] = w;
  10813. }
  10814. }
  10815. /* A spanning cell only needs the sum of its columns to be large
  10816. * enough; put the deficit in the last column. */
  10817. for (i = 0; i < ncells; i++) {
  10818. struct br_style cs;
  10819. int w, sum, col, span;
  10820. if (tbl_cells[i].colspan < 2)
  10821. continue;
  10822. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10823. st, &cs);
  10824. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10825. mp_px(&cs, 7, avail) +
  10826. mp_px(&cs, 5, avail) +
  10827. mp_px(&cs, 3, avail) +
  10828. mp_px(&cs, 1, avail) +
  10829. cs.border_w[0] + cs.border_w[1] +
  10830. cs.border_w[2] + cs.border_w[3];
  10831. col = tbl_cells[i].col;
  10832. span = tbl_cells[i].colspan;
  10833. sum = 0;
  10834. for (int j = 0; j < span; j++)
  10835. sum += raw[col + j];
  10836. if (w > sum)
  10837. raw[col + span - 1] += w - sum;
  10838. }
  10839. /* Explicit/percentage widths, as in table_columns(). */
  10840. for (i = 0; i < ncells; i++) {
  10841. struct br_style cs;
  10842. int col;
  10843. if (tbl_cells[i].colspan != 1)
  10844. continue;
  10845. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10846. st, &cs);
  10847. col = tbl_cells[i].col;
  10848. if (cs.width_kind == 1) {
  10849. raw[col] = cs.width;
  10850. fixed[col] = 1;
  10851. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  10852. raw[col] = style_width_px(&cs, avail);
  10853. fixed[col] = 1;
  10854. }
  10855. }
  10856. for (i = 0; i < cols; i++) {
  10857. if (raw[i] < 8)
  10858. raw[i] = 8;
  10859. total += raw[i];
  10860. if (fixed[i])
  10861. fixed_sum += raw[i];
  10862. else {
  10863. free_raw += raw[i];
  10864. free_cols++;
  10865. }
  10866. }
  10867. if (fixed_sum > 0 && fixed_sum < avail) {
  10868. int free_avail = avail - fixed_sum;
  10869. if (free_raw > 0) {
  10870. for (i = 0; i < cols; i++)
  10871. if (!fixed[i])
  10872. raw[i] = free_avail * raw[i] /
  10873. free_raw;
  10874. } else if (free_cols > 0) {
  10875. for (i = 0; i < cols; i++)
  10876. if (!fixed[i])
  10877. raw[i] = free_avail / free_cols;
  10878. }
  10879. } else if (total < avail && total > 0) {
  10880. for (i = 0; i < cols; i++)
  10881. raw[i] = raw[i] * avail / total;
  10882. }
  10883. prefix[0] = table_left;
  10884. for (i = 0; i < cols; i++)
  10885. prefix[i + 1] = prefix[i] + raw[i];
  10886. /* Measure natural cell heights with the column widths. */
  10887. for (i = 0; i < ncells; i++) {
  10888. struct br_style cs;
  10889. int col = tbl_cells[i].col;
  10890. int span = tbl_cells[i].colspan;
  10891. int w = prefix[col + span] - prefix[col];
  10892. int sl = l->left, sr = l->right, sy = l->y;
  10893. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10894. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10895. int sal = l->align, sdraw = l->draw;
  10896. struct ngui *sui = l->ui;
  10897. if (w < 8)
  10898. w = 8;
  10899. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10900. st, &cs);
  10901. cs.width_kind = 0;
  10902. cs.max_width_kind = 0;
  10903. l->draw = 0;
  10904. l->ui = 0;
  10905. l->left = prefix[col];
  10906. l->right = l->left + w;
  10907. l->y = 0;
  10908. l->line_left = l->line_x = l->left;
  10909. l->run_x = l->left;
  10910. l->line_y = 0;
  10911. l->line_h = 0;
  10912. l->nruns = 0;
  10913. l->space_pending = 0;
  10914. l->align = cs.align;
  10915. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10916. tbl_cells[i].height = block_h[tbl_cells[i].node];
  10917. l->left = sl;
  10918. l->right = sr;
  10919. l->y = sy;
  10920. l->line_x = slx;
  10921. l->run_x = srx;
  10922. l->line_y = sly;
  10923. l->line_h = slh;
  10924. l->nruns = snr;
  10925. l->space_pending = ssp;
  10926. l->align = sal;
  10927. l->draw = sdraw;
  10928. l->ui = sui;
  10929. }
  10930. for (i = 0; i < nrows; i++)
  10931. rowh[i] = 0;
  10932. for (i = 0; i < ncells; i++) {
  10933. int row = tbl_cells[i].row;
  10934. if (tbl_cells[i].rowspan == 1) {
  10935. if (tbl_cells[i].height > rowh[row])
  10936. rowh[row] = tbl_cells[i].height;
  10937. }
  10938. }
  10939. for (i = 0; i < ncells; i++) {
  10940. int row = tbl_cells[i].row;
  10941. int span = tbl_cells[i].rowspan;
  10942. int sum = 0;
  10943. if (span < 2)
  10944. continue;
  10945. for (int j = 0; j < span; j++)
  10946. sum += rowh[row + j];
  10947. if (sum < tbl_cells[i].height)
  10948. rowh[row + span - 1] +=
  10949. tbl_cells[i].height - sum;
  10950. }
  10951. for (i = 0; i < nrows; i++)
  10952. if (rowh[i] < 8)
  10953. rowh[i] = 8;
  10954. rowy[0] = top;
  10955. for (i = 1; i < nrows; i++)
  10956. rowy[i] = rowy[i - 1] + rowh[i - 1];
  10957. if (!l->draw) {
  10958. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10959. table_active = 0;
  10960. return;
  10961. }
  10962. for (i = 0; i < ncells; i++) {
  10963. struct br_style cs;
  10964. int col = tbl_cells[i].col;
  10965. int span = tbl_cells[i].colspan;
  10966. int row = tbl_cells[i].row;
  10967. int rspan = tbl_cells[i].rowspan;
  10968. int w = prefix[col + span] - prefix[col];
  10969. int h = 0;
  10970. int sl = l->left, sr = l->right, sy = l->y;
  10971. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10972. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10973. int sal = l->align;
  10974. int deco;
  10975. for (int j = 0; j < rspan; j++)
  10976. h += rowh[row + j];
  10977. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  10978. cs.width_kind = 0;
  10979. cs.max_width_kind = 0;
  10980. cs.box_sizing = 0;
  10981. deco = mp_px(&cs, 4, avail) +
  10982. mp_px(&cs, 6, avail) +
  10983. cs.border_w[0] + cs.border_w[2];
  10984. cs.height_kind = 1;
  10985. cs.height = h > deco ? h - deco : 0;
  10986. /* The block painter reads block_h[] from the measure pass; make
  10987. * the table cell fill its row/rowspan, not just its content. */
  10988. if (h > 0 && h < 65536)
  10989. block_h[tbl_cells[i].node] = (unsigned short)h;
  10990. l->left = prefix[col];
  10991. l->right = l->left + w;
  10992. l->y = rowy[row];
  10993. l->line_left = l->line_x = l->left;
  10994. l->run_x = l->left;
  10995. l->line_y = l->y;
  10996. l->line_h = 0;
  10997. l->nruns = 0;
  10998. l->space_pending = 0;
  10999. l->align = cs.align;
  11000. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  11001. l->left = sl;
  11002. l->right = sr;
  11003. l->y = sy;
  11004. l->line_x = slx;
  11005. l->run_x = srx;
  11006. l->line_y = sly;
  11007. l->line_h = slh;
  11008. l->nruns = snr;
  11009. l->space_pending = ssp;
  11010. l->align = sal;
  11011. }
  11012. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  11013. table_active = 0;
  11014. }
  11015. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  11016. * flow so they sit above it, like CSS painting order. Their flow origin is
  11017. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  11018. struct br_deferred {
  11019. unsigned int node;
  11020. int flow_y, flow_left, flow_right;
  11021. int parent_top; /* the parent box top, for sticky clamping */
  11022. unsigned short link;
  11023. signed short z_index;
  11024. unsigned char z_set;
  11025. unsigned int order;
  11026. };
  11027. /* Positioned boxes painted after the flow. News front pages have one or two
  11028. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  11029. * old 16 entries the rest fell back into the flow, so a hero image landed
  11030. * below its padding-top aspect box instead of on top of it. */
  11031. #define BR_MAX_DEFERRED 256
  11032. static struct br_deferred deferred[BR_MAX_DEFERRED];
  11033. static int ndeferred;
  11034. /* Outer width of an element's empty ::before (pe 1) / ::after (pe 2) icon
  11035. * box, 0 when it has none; *ps receives the pseudo-element's style. */
  11036. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  11037. struct br_style *ps, int base)
  11038. {
  11039. char buf[8];
  11040. int w, h;
  11041. if (!doc.npe_rules ||
  11042. br_pseudo(&doc, node, pe, st, ps, buf, sizeof(buf)) ||
  11043. ps->content != BR_CONTENT_EMPTY || ps->display == BR_DISPLAY_NONE)
  11044. return 0;
  11045. w = ps->width_kind ? style_width_px(ps, base) : 0;
  11046. h = ps->height_kind ? style_height_px(ps, base) : 0;
  11047. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  11048. w = (int)ps->min_width;
  11049. if (w <= 0)
  11050. w = h;
  11051. if (w <= 0 || w > 512)
  11052. return 0;
  11053. return w + (ps->ml_auto ? 0 : mp_px(ps, 3, base)) + mp_px(ps, 1, base);
  11054. }
  11055. /* An empty ::before/::after with a size and a background: one run the
  11056. * size of the box. Only data: background images are drawn (decoded at
  11057. * the background-size); `margin-left: auto` inside a flex parent pushes
  11058. * the box to the line's right edge like the flex row would. */
  11059. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  11060. const struct br_style *ps, unsigned short link)
  11061. {
  11062. struct lay_run *r;
  11063. int lw = l->line_right - l->line_left, w, h, ml, mr, tw, th;
  11064. const char *url = ps->bg_image ? br_bg_image_url(ps->bg_image - 1) : "";
  11065. if (lw < 8)
  11066. lw = 8;
  11067. w = ps->width_kind ? style_width_px(ps, lw) : 0;
  11068. h = ps->height_kind ? style_height_px(ps, lw) : 0;
  11069. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  11070. w = (int)ps->min_width;
  11071. if (w <= 0)
  11072. w = h;
  11073. if (h <= 0)
  11074. h = w;
  11075. if (w <= 0 || w > 512 || h > 512)
  11076. return;
  11077. ml = ps->ml_auto ? 0 : mp_px(ps, 3, lw);
  11078. mr = mp_px(ps, 1, lw);
  11079. if (ml < 0)
  11080. ml = 0;
  11081. if (mr < 0)
  11082. mr = 0;
  11083. if (l->line_x + ml + w > l->line_right &&
  11084. (l->nruns > 0 || l->line_x > l->line_left))
  11085. flush_line(l);
  11086. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  11087. flush_line(l);
  11088. if (l->nruns == 0) {
  11089. l->line_y = l->y;
  11090. l->line_h = 0;
  11091. start_line(l, ps);
  11092. }
  11093. if (ps->ml_auto && parent->display == BR_DISPLAY_FLEX &&
  11094. l->line_right - w - mr > l->line_x)
  11095. l->line_x = l->line_right - w - mr;
  11096. else
  11097. l->line_x += ml;
  11098. r = &l->runs[l->nruns++];
  11099. memset(r, 0, sizeof(*r));
  11100. r->box = l->box_owner;
  11101. r->gap = (unsigned short)(l->line_x > l->run_x ?
  11102. l->line_x - l->run_x : 0);
  11103. r->img = RUN_PBOX;
  11104. r->href = link;
  11105. r->iw = (unsigned short)w;
  11106. r->ih = (unsigned short)h;
  11107. r->w = (unsigned short)w;
  11108. r->font_px = ps->font_px;
  11109. r->pb_has_bg = ps->has_bg;
  11110. r->pb_bg = ps->bg;
  11111. r->pb_img = -1;
  11112. if (ps->transform_set) {
  11113. r->transform_scale = 1;
  11114. r->scale_x = ps->scale_x;
  11115. r->scale_y = ps->scale_y;
  11116. r->rotate_x100 = ps->rotate_x100;
  11117. }
  11118. /* Background size and position, as draw_bg_image() resolves them. */
  11119. tw = w;
  11120. th = h;
  11121. if (ps->bg_size_kind == 1 || ps->bg_size_kind == 2) {
  11122. int bw = ps->bg_size_w, bh = ps->bg_size_h;
  11123. if (ps->bg_size_kind == 2) {
  11124. bw = bw ? w * bw / 100 : 0;
  11125. bh = bh ? h * bh / 100 : 0;
  11126. }
  11127. tw = bw ? bw : (bh ? bh : w);
  11128. th = bh ? bh : tw;
  11129. }
  11130. if (tw > 0 && th > 0 && tw <= 512 && th <= 512 && url[0])
  11131. r->pb_img = (short)data_url_image(url, tw, th);
  11132. r->pb_w = (short)tw;
  11133. r->pb_h = (short)th;
  11134. r->pb_x = (short)(ps->bg_pos_x_kind == 1 ?
  11135. (w - tw) * ps->bg_pos_x / 100 : ps->bg_pos_x);
  11136. r->pb_y = (short)(ps->bg_pos_y_kind == 1 ?
  11137. (h - th) * ps->bg_pos_y / 100 : ps->bg_pos_y);
  11138. l->line_x += w + mr;
  11139. l->run_x = l->line_x;
  11140. if (l->line_h < h)
  11141. l->line_h = h;
  11142. }
  11143. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  11144. * element's line. A block-level pseudo-element gets its own line; its box
  11145. * (margins, padding, background) is not drawn. */
  11146. static void emit_pseudo(struct lay *l, unsigned int node,
  11147. const struct br_style *st, int pe, unsigned short link)
  11148. {
  11149. char buf[160];
  11150. struct br_style ps;
  11151. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  11152. unsigned int i = 0;
  11153. int block, space_w;
  11154. if (!n && ps.content == BR_CONTENT_EMPTY &&
  11155. ps.display != BR_DISPLAY_NONE) {
  11156. emit_pseudo_box(l, st, &ps, link);
  11157. return;
  11158. }
  11159. if (!n)
  11160. return;
  11161. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  11162. if (block)
  11163. flush_line(l);
  11164. if (ps.uppercase)
  11165. for (i = 0; i < n; i++)
  11166. if (buf[i] >= 'a' && buf[i] <= 'z')
  11167. buf[i] = (char)(buf[i] - 'a' + 'A');
  11168. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  11169. if (space_w <= 0)
  11170. space_w = 8;
  11171. i = 0;
  11172. while (i < n) {
  11173. char word[28];
  11174. unsigned int k = 0;
  11175. int w;
  11176. if (buf[i] == ' ') {
  11177. l->space_pending = 1;
  11178. i++;
  11179. continue;
  11180. }
  11181. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  11182. word[k++] = buf[i++];
  11183. word[k] = '\0';
  11184. if (l->space_pending &&
  11185. (l->nruns > 0 || l->line_x > l->line_left) &&
  11186. l->line_x + space_w <= l->line_right)
  11187. l->line_x += space_w;
  11188. l->space_pending = 0;
  11189. w = (int)face_text_width(l->ui, &ps, word, k);
  11190. if (l->line_x + w > l->line_right &&
  11191. (l->nruns > 0 || l->line_x > l->line_left))
  11192. flush_line(l);
  11193. add_run(l, 0, 0, &ps, link, word);
  11194. }
  11195. if (block)
  11196. flush_line(l);
  11197. }
  11198. /* An out-of-flow child (absolute/fixed, or a relative/sticky box with a
  11199. * z-index): measured in place, painted from the deferred stacked pass
  11200. * against its containing block. Shared by block and flex layout, so an
  11201. * absolute icon inside a flex row (a password field's reveal button) is
  11202. * not laid out as one of the row's items. Returns 1 when it handled n. */
  11203. static int layout_out_of_flow(struct lay *l, unsigned int n,
  11204. const struct br_style *cs, int depth,
  11205. unsigned short lk)
  11206. {
  11207. if (!(cs->pos == 1 || cs->pos == 2 ||
  11208. ((cs->pos == 3 || cs->pos == 4) && cs->z_set)))
  11209. return 0;
  11210. if ((cs->pos == 3 || cs->pos == 4) && l->draw &&
  11211. ndeferred < BR_MAX_DEFERRED) {
  11212. /* Relative or sticky z-index (a sticky site
  11213. * header): measure and advance the flow without
  11214. * painting, then paint it in the deferred
  11215. * (stacked) pass, above the content after it. */
  11216. int fy = l->y, fl = l->left, fr = l->right;
  11217. int save_draw = l->draw;
  11218. l->draw = 0;
  11219. layout_block(l, n, cs, depth + 1, lk);
  11220. l->draw = save_draw;
  11221. deferred[ndeferred].node = n;
  11222. deferred[ndeferred].parent_top = l->parent_top;
  11223. deferred[ndeferred].flow_y = fy;
  11224. deferred[ndeferred].flow_left = fl;
  11225. deferred[ndeferred].flow_right = fr;
  11226. deferred[ndeferred].link = lk;
  11227. deferred[ndeferred].z_index = cs->z_index;
  11228. deferred[ndeferred].z_set = cs->z_set;
  11229. deferred[ndeferred].order = (unsigned int)ndeferred;
  11230. ndeferred++;
  11231. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  11232. deferred[ndeferred].node = n;
  11233. deferred[ndeferred].parent_top = l->parent_top;
  11234. deferred[ndeferred].flow_y =
  11235. cs->pos == 1 ? l->cb_top : l->y;
  11236. deferred[ndeferred].flow_left =
  11237. cs->pos == 1 ? l->cb_left : l->left;
  11238. deferred[ndeferred].flow_right =
  11239. cs->pos == 1 ? l->cb_right : l->right;
  11240. deferred[ndeferred].link = lk;
  11241. deferred[ndeferred].z_index = cs->z_index;
  11242. deferred[ndeferred].z_set = cs->z_set;
  11243. deferred[ndeferred].order = (unsigned int)ndeferred;
  11244. ndeferred++;
  11245. } else if (l->draw && cs->pos == 1) {
  11246. /* Deferred list full: paint in place, but still
  11247. * against the containing block, not the flow. */
  11248. int fy = l->y, fl = l->left, fr = l->right;
  11249. l->y = l->cb_top;
  11250. l->left = l->cb_left;
  11251. l->right = l->cb_right;
  11252. layout_block(l, n, cs, depth + 1, lk);
  11253. l->y = fy;
  11254. l->left = fl;
  11255. l->right = fr;
  11256. } else {
  11257. layout_block(l, n, cs, depth + 1, lk);
  11258. }
  11259. if (cs->pos == 1 && block_h[n] &&
  11260. doc.nodes[n].class_off) {
  11261. const char *cl = doc.attrs +
  11262. doc.nodes[n].class_off;
  11263. if ((contains_ci(cl, "poster-wrapper") ||
  11264. contains_ci(cl, "ts-picture")) &&
  11265. !has_skeleton_sibling(n))
  11266. l->y += block_h[n];
  11267. }
  11268. return 1;
  11269. }
  11270. /* An element laid out in the text line (an inline span, or an inline-block
  11271. * that flows like one): its runs are tagged with it, so flush_line() can
  11272. * record its box for getBoundingClientRect() and click targeting. */
  11273. static void layout_inline_box(struct lay *l, unsigned int node,
  11274. const struct br_style *cs, int depth,
  11275. unsigned short link)
  11276. {
  11277. unsigned short saved = l->box_owner;
  11278. if (node < BR_MAX_NODES) {
  11279. inline_box_parent[node] = saved;
  11280. l->box_owner = (unsigned short)(node + 1);
  11281. }
  11282. layout_children(l, node, cs, depth + 1, link);
  11283. l->box_owner = saved;
  11284. }
  11285. static void layout_children(struct lay *l, unsigned int parent,
  11286. const struct br_style *pst, int depth,
  11287. unsigned short link)
  11288. {
  11289. unsigned int n;
  11290. if (depth > 48)
  11291. return;
  11292. emit_pseudo(l, parent, pst, 1, link);
  11293. n = doc.nodes[parent].first;
  11294. while (n) {
  11295. struct br_node *nd = &doc.nodes[n];
  11296. struct br_style cs;
  11297. unsigned short lk = link;
  11298. if (nd->type == BR_NODE_TEXT) {
  11299. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  11300. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  11301. n = nd->next;
  11302. continue;
  11303. }
  11304. br_style_for(&doc, n, pst, &cs);
  11305. if (cs.display == BR_DISPLAY_NONE) {
  11306. n = nd->next;
  11307. continue;
  11308. }
  11309. if (cs.clear && l->float_active) {
  11310. flush_line(l);
  11311. if (l->y < l->float_bottom)
  11312. l->y = l->float_bottom;
  11313. l->float_active = 0;
  11314. l->line_x = l->left;
  11315. l->run_x = l->left;
  11316. l->line_left = l->left;
  11317. l->line_right = l->right;
  11318. l->line_y = l->y;
  11319. l->line_h = 0;
  11320. l->nruns = 0;
  11321. l->space_pending = 0;
  11322. }
  11323. if (nd->tag == BR_TAG_A && nd->href_off)
  11324. lk = (unsigned short)n;
  11325. if (layout_out_of_flow(l, n, &cs, depth, lk)) {
  11326. n = nd->next;
  11327. continue;
  11328. }
  11329. if (nd->tag == BR_TAG_BR) {
  11330. flush_line(l);
  11331. n = nd->next;
  11332. continue;
  11333. }
  11334. if (nd->tag == BR_TAG_HR) {
  11335. flush_line(l);
  11336. if (l->draw)
  11337. ngui_fill_rect(l->ui,
  11338. (struct ngui_rect){l->left, l->y + 2,
  11339. l->right - l->left, 1}, BR_GRAY);
  11340. l->y += 8;
  11341. n = nd->next;
  11342. continue;
  11343. }
  11344. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  11345. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  11346. !button_has_elements(n)) {
  11347. if (!(nd->tag == BR_TAG_INPUT &&
  11348. s_eq(br_type(&doc, n), "hidden"))) {
  11349. form_fill_line = pst->display ==
  11350. BR_DISPLAY_FLEX &&
  11351. pst->flex_col;
  11352. add_form_run(l, n, &cs, lk);
  11353. form_fill_line = 0;
  11354. }
  11355. n = nd->next;
  11356. continue;
  11357. }
  11358. if (nd->tag == BR_TAG_IMG) {
  11359. add_image_run(l, n, &cs, lk);
  11360. n = nd->next;
  11361. continue;
  11362. }
  11363. if (nd->tag == BR_TAG_SVG &&
  11364. (cs.display == BR_DISPLAY_INLINE ||
  11365. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  11366. !cs.float_left) {
  11367. add_svg_run(l, n, &cs, lk);
  11368. n = nd->next;
  11369. continue;
  11370. }
  11371. if (nd->tag == BR_TAG_VIDEO) {
  11372. layout_block(l, n, &cs, depth + 1, lk);
  11373. n = nd->next;
  11374. continue;
  11375. }
  11376. if (cs.float_left) {
  11377. n = layout_float_group(l, n, pst, depth, lk);
  11378. continue;
  11379. }
  11380. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  11381. inline_block_flows(n, &cs, 0)) {
  11382. layout_inline_box(l, n, &cs, depth, lk);
  11383. n = nd->next;
  11384. continue;
  11385. }
  11386. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  11387. n = layout_inline_blocks(l, n, pst, depth, link);
  11388. continue;
  11389. }
  11390. /* A flex container is block-level like any block box even when
  11391. * the element is an inline tag such as <a> (a link card with
  11392. * display:flex is common on news sites). Without the block box
  11393. * its children were laid out in the parent flow with a 0x0 box
  11394. * of their own. */
  11395. /* inline-flex around inline content only ("| mehr" link
  11396. * tails, icon+label pills) stays in the text line. */
  11397. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  11398. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  11399. !flex_wants_row(n, &cs)) {
  11400. layout_children(l, n, &cs, depth + 1, lk);
  11401. } else if (cs.display == BR_DISPLAY_BLOCK ||
  11402. cs.display == BR_DISPLAY_FLEX ||
  11403. br_tag_is_block(nd->tag))
  11404. layout_block(l, n, &cs, depth + 1, lk);
  11405. else if (cs.display == BR_DISPLAY_INLINE &&
  11406. nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH)
  11407. layout_inline_box(l, n, &cs, depth, lk);
  11408. else {
  11409. layout_children(l, n, &cs, depth + 1, lk);
  11410. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  11411. l->space_pending = 1;
  11412. }
  11413. n = nd->next;
  11414. }
  11415. emit_pseudo(l, parent, pst, 2, link);
  11416. }
  11417. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  11418. * runs and a recursive page can otherwise overflow the stack. */
  11419. static struct lay layout_state;
  11420. static int measure_page(int left, int right)
  11421. {
  11422. struct lay *l = &layout_state;
  11423. struct br_style base = base_style();
  11424. unsigned int i;
  11425. for (i = 0; i < BR_MAX_NODES; i++) {
  11426. block_h[i] = 0;
  11427. flex_stretch_h[i] = 0;
  11428. img_top[i] = 0;
  11429. block_top[i] = 0;
  11430. img_h[i] = 0;
  11431. layout_boxes[i].valid = 0;
  11432. }
  11433. memset(li_marker, 0, sizeof(li_marker));
  11434. inline_box_pass_id++;
  11435. l->box_owner = 0;
  11436. l->draw = 0;
  11437. l->ui = &ui;
  11438. l->left = left;
  11439. l->right = right;
  11440. l->y = 0;
  11441. l->line_x = left;
  11442. l->run_x = left;
  11443. l->line_left = left;
  11444. l->line_right = right;
  11445. l->line_y = 0;
  11446. l->line_h = 0;
  11447. l->align = BR_ALIGN_LEFT;
  11448. l->cb_h = layout_view_h;
  11449. l->float_active = 0;
  11450. l->parent_top = 0;
  11451. l->cb_left = left;
  11452. l->cb_right = right;
  11453. l->cb_top = 0;
  11454. l->depth = 0;
  11455. l->nruns = 0;
  11456. l->space_pending = 0;
  11457. base = root_style();
  11458. layout_children(l, doc.root, &base, 0, 0);
  11459. return l->y + 8;
  11460. }
  11461. static int deferred_cmp(const struct br_deferred *a,
  11462. const struct br_deferred *b)
  11463. {
  11464. int az = a->z_set ? a->z_index : 0;
  11465. int bz = b->z_set ? b->z_index : 0;
  11466. if (az != bz)
  11467. return az < bz ? -1 : 1;
  11468. if (a->order != b->order)
  11469. return a->order < b->order ? -1 : 1;
  11470. return 0;
  11471. }
  11472. static void sort_deferred(void)
  11473. {
  11474. int i;
  11475. for (i = 1; i < ndeferred; i++) {
  11476. struct br_deferred key = deferred[i];
  11477. int j = i;
  11478. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  11479. deferred[j] = deferred[j - 1];
  11480. j--;
  11481. }
  11482. deferred[j] = key;
  11483. }
  11484. }
  11485. static void render_page(int left, int right, int y0)
  11486. {
  11487. struct lay *l = &layout_state;
  11488. struct br_style base = base_style();
  11489. inline_box_pass_id++;
  11490. l->box_owner = 0;
  11491. l->draw = 1;
  11492. l->ui = &ui;
  11493. l->left = left;
  11494. l->right = right;
  11495. l->y = y0;
  11496. l->line_x = left;
  11497. l->run_x = left;
  11498. l->line_left = left;
  11499. l->line_right = right;
  11500. l->line_y = y0;
  11501. l->line_h = 0;
  11502. l->align = BR_ALIGN_LEFT;
  11503. l->cb_h = layout_view_h;
  11504. l->float_active = 0;
  11505. l->parent_top = 0;
  11506. l->cb_left = left;
  11507. l->cb_right = right;
  11508. l->cb_top = y0;
  11509. l->depth = 0;
  11510. l->nruns = 0;
  11511. l->space_pending = 0;
  11512. nhits = 0;
  11513. ndeferred = 0;
  11514. base = root_style();
  11515. layout_children(l, doc.root, &base, 0, 0);
  11516. sort_deferred();
  11517. {
  11518. int i;
  11519. for (i = 0; i < ndeferred; i++) {
  11520. struct br_style st;
  11521. int hide;
  11522. br_style_for(&doc, deferred[i].node, &base, &st);
  11523. if (st.display == BR_DISPLAY_NONE)
  11524. continue;
  11525. /* A transparent or visibility:hidden positioned box
  11526. * still gets its boxes (scripts measure it) but no
  11527. * paint and no hit rectangles. */
  11528. hide = st.opacity_hidden || st.vis_hidden;
  11529. l->draw = !hide;
  11530. l->left = deferred[i].flow_left;
  11531. l->right = deferred[i].flow_right;
  11532. l->y = deferred[i].flow_y;
  11533. l->parent_top = deferred[i].parent_top;
  11534. l->line_left = l->line_x = l->left;
  11535. l->run_x = l->left;
  11536. l->line_y = l->y;
  11537. l->line_h = 0;
  11538. l->nruns = 0;
  11539. l->space_pending = 0;
  11540. l->align = st.align;
  11541. if (st.pos == 2 && block_h[deferred[i].node]) {
  11542. struct ngui_rect clip;
  11543. int ch = block_h[deferred[i].node] + 24;
  11544. int pr = page_rect.x + page_rect.w - 12;
  11545. int x0 = page_rect.x, x1 = pr;
  11546. int y0 = page_rect.y;
  11547. /* A box placed by `bottom` (a page footer) is
  11548. * clipped and filled where layout_block puts
  11549. * it, against the bottom edge. */
  11550. if (st.bottom_set && !st.top_set) {
  11551. ch = block_h[deferred[i].node] +
  11552. mp_px(&st, 0, pr - page_rect.x) +
  11553. mp_px(&st, 2, pr - page_rect.x);
  11554. y0 = page_rect.y + page_rect.h -
  11555. st.bottom - ch;
  11556. }
  11557. /* The background pre-fill spans the box's own
  11558. * columns, not the whole page: Docusaurus parks
  11559. * a white "Skip to main content" link at
  11560. * `left: 100%` with a z-index above the navbar,
  11561. * and a full-width fill painted over the bar. */
  11562. if (st.left_set)
  11563. x0 = page_rect.x + st.left;
  11564. else if (!st.right_set)
  11565. x0 = deferred[i].flow_left;
  11566. if (st.width_kind == 1) {
  11567. if (st.right_set && !st.left_set)
  11568. x0 = pr - st.right - st.width;
  11569. x1 = x0 + st.width;
  11570. } else if (st.right_set) {
  11571. x1 = pr - st.right;
  11572. }
  11573. if (x0 >= pr || x1 <= page_rect.x)
  11574. continue; /* entirely off-screen */
  11575. if (x0 < page_rect.x)
  11576. x0 = page_rect.x;
  11577. if (x1 > pr)
  11578. x1 = pr;
  11579. if (y0 < page_rect.y) {
  11580. ch -= page_rect.y - y0;
  11581. y0 = page_rect.y;
  11582. }
  11583. clip.x = x0;
  11584. clip.y = y0;
  11585. clip.w = x1 - x0;
  11586. if (ch > page_rect.h)
  11587. ch = page_rect.h;
  11588. if (ch <= 0)
  11589. continue;
  11590. clip.h = ch;
  11591. ngui_push_clip(&ui, clip);
  11592. if (st.has_bg && !hide)
  11593. ngui_fill_rect(&ui, clip, st.bg);
  11594. layout_block(l, deferred[i].node, &st, 0,
  11595. deferred[i].link);
  11596. ngui_pop_clip(&ui);
  11597. } else {
  11598. layout_block(l, deferred[i].node, &st, 0,
  11599. deferred[i].link);
  11600. }
  11601. }
  11602. }
  11603. }
  11604. /* ---- UI ---- */
  11605. static int find_hit(int x, int y)
  11606. {
  11607. int i;
  11608. for (i = nhits - 1; i >= 0; i--) {
  11609. struct hit *h = &hits[i];
  11610. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  11611. y < h->y + h->h)
  11612. return (int)h->node;
  11613. }
  11614. return 0;
  11615. }
  11616. /* ---- URL-bar autocomplete ----
  11617. *
  11618. * While the address bar has the focus a dropdown lists up to SUG_MAX
  11619. * history entries. An empty bar (a fresh focus, Ctrl+L) shows the most
  11620. * visited/recent sites; typing ranks prefix matches of the URL (with or
  11621. * without the scheme and "www.") above substring matches of the URL, then
  11622. * of the title, and adds visit count and recency. Typing at the end of the
  11623. * text also completes inline to the next '/' of the best prefix match
  11624. * ("clo" -> "cloudron.io/"), with the added part selected so the next
  11625. * keystroke replaces it; Enter on that text opens the history URL it came
  11626. * from (scheme included). Up/Down preview a row in the bar, Delete on a
  11627. * highlighted row forgets it, Esc closes the list (a second Esc leaves the
  11628. * bar), and a click on a row opens it. */
  11629. #define SUG_MAX 6
  11630. #define SUG_ROW_H 36
  11631. static int sug_idx[SUG_MAX];
  11632. static int sug_n, sug_sel = -1, sug_open;
  11633. static char sug_typed[NGUI_INPUT_MAX]; /* what the user typed */
  11634. static char sug_restore[NGUI_INPUT_MAX]; /* bar text before a preview */
  11635. static char ac_text[NGUI_INPUT_MAX]; /* bar text of the inline completion */
  11636. static char ac_url[HIST_URL_MAX]; /* the history URL it stands for */
  11637. static struct ngui_rect url_rect, sug_rect;
  11638. static int url_had_focus;
  11639. static char lc(char c)
  11640. {
  11641. return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
  11642. }
  11643. static int prefix_ci(const char *s, const char *p) /* p is lower case */
  11644. {
  11645. for (; *p; s++, p++)
  11646. if (lc(*s) != *p)
  11647. return 0;
  11648. return 1;
  11649. }
  11650. static unsigned int url_scheme_len(const char *url)
  11651. {
  11652. if (starts_with(url, "https://"))
  11653. return 8;
  11654. if (starts_with(url, "http://"))
  11655. return 7;
  11656. return 0;
  11657. }
  11658. /* Offset in `url` where the lower-case text `t` matches as a prefix: the
  11659. * whole URL, the URL without its scheme, or without scheme and "www.". */
  11660. static int hist_prefix_at(const char *url, const char *t)
  11661. {
  11662. unsigned int s = url_scheme_len(url);
  11663. if (prefix_ci(url, t))
  11664. return 0;
  11665. if (s && prefix_ci(url + s, t))
  11666. return (int)s;
  11667. if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
  11668. return (int)s + 4;
  11669. return -1;
  11670. }
  11671. static int hist_score(const struct hist_ent *e, const char *t,
  11672. unsigned int next)
  11673. {
  11674. unsigned int age = next - e->stamp;
  11675. int sc, at;
  11676. if (!t[0]) {
  11677. sc = 0;
  11678. } else if ((at = hist_prefix_at(e->url, t)) >= 0) {
  11679. /* Shorter rests first: "cloudron.io/" before its subpages. */
  11680. int rest = (int)s_len(e->url + at);
  11681. sc = 4000 - (rest > 400 ? 400 : rest);
  11682. } else if (contains_ci(e->url, t)) {
  11683. sc = 1000;
  11684. } else if (contains_ci(e->title, t)) {
  11685. sc = 600;
  11686. } else {
  11687. return -1;
  11688. }
  11689. sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
  11690. sc += age >= 500 ? 0 : (int)(500 - age);
  11691. return sc;
  11692. }
  11693. static void sug_lower(char *t, unsigned int cap)
  11694. {
  11695. unsigned int k;
  11696. for (k = 0; sug_typed[k] && k + 1 < cap; k++)
  11697. t[k] = lc(sug_typed[k]);
  11698. t[k] = '\0';
  11699. }
  11700. static void sug_refresh(void)
  11701. {
  11702. char t[NGUI_INPUT_MAX];
  11703. int sc[SUG_MAX], i, j;
  11704. unsigned int next = hist_next_stamp();
  11705. sug_lower(t, sizeof(t));
  11706. sug_n = 0;
  11707. for (i = 0; i < hist_n; i++) {
  11708. int s = hist_score(&hist_tab[i], t, next);
  11709. if (s < 0)
  11710. continue;
  11711. j = sug_n;
  11712. if (j == SUG_MAX) {
  11713. if (sc[SUG_MAX - 1] >= s)
  11714. continue;
  11715. j = SUG_MAX - 1;
  11716. }
  11717. while (j > 0 && sc[j - 1] < s) {
  11718. sc[j] = sc[j - 1];
  11719. sug_idx[j] = sug_idx[j - 1];
  11720. j--;
  11721. }
  11722. sc[j] = s;
  11723. sug_idx[j] = i;
  11724. if (sug_n < SUG_MAX)
  11725. sug_n++;
  11726. }
  11727. if (sug_sel >= sug_n)
  11728. sug_sel = -1;
  11729. }
  11730. /* Complete the typed text inline to the next '/' of the best prefix match. */
  11731. static void sug_inline(void)
  11732. {
  11733. char t[NGUI_INPUT_MAX];
  11734. const char *url, *rest;
  11735. unsigned int L, start, end, hs, tn, n = 0;
  11736. unsigned int next = hist_next_stamp();
  11737. int i, best = -1, best_sc = -1, at = 0;
  11738. sug_lower(t, sizeof(t));
  11739. L = s_len(t);
  11740. if (!L)
  11741. return;
  11742. for (i = 0; i < hist_n; i++) {
  11743. int a = hist_prefix_at(hist_tab[i].url, t), s;
  11744. if (a < 0)
  11745. continue;
  11746. s = hist_score(&hist_tab[i], t, next);
  11747. if (s > best_sc) {
  11748. best_sc = s;
  11749. best = i;
  11750. at = a;
  11751. }
  11752. }
  11753. if (best < 0)
  11754. return;
  11755. url = hist_tab[best].url;
  11756. rest = url + at;
  11757. /* Typing the scheme ("htt") completes past "https://", not to it. */
  11758. hs = at == 0 ? url_scheme_len(url) : 0;
  11759. start = L > hs ? L : hs;
  11760. end = start;
  11761. while (rest[end] && rest[end] != '/')
  11762. end++;
  11763. if (rest[end] == '/')
  11764. end++;
  11765. tn = s_len(sug_typed);
  11766. if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
  11767. return;
  11768. s_append(ac_text, &n, sug_typed, sizeof(ac_text));
  11769. for (; L < end && n + 1 < sizeof(ac_text); L++)
  11770. ac_text[n++] = rest[L];
  11771. ac_text[n] = '\0';
  11772. s_copy(ac_url, url, (unsigned int)at + end + 1);
  11773. ngui_input_set(&url_in, ac_text);
  11774. url_in.anchor = tn; /* select the completed part */
  11775. }
  11776. static void sug_close(void)
  11777. {
  11778. sug_open = 0;
  11779. sug_sel = -1;
  11780. ac_text[0] = '\0';
  11781. }
  11782. static int sug_visible(void)
  11783. {
  11784. return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
  11785. }
  11786. /* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
  11787. * start page) lists the top sites until something is typed. */
  11788. static int sug_focus_check(void)
  11789. {
  11790. int focused = ngui_focus(&ui) == ID_URL;
  11791. if (focused && !url_had_focus) {
  11792. sug_typed[0] = '\0';
  11793. sug_close();
  11794. sug_open = 1;
  11795. sug_refresh();
  11796. }
  11797. url_had_focus = focused;
  11798. return focused;
  11799. }
  11800. static void url_submit(unsigned int *action)
  11801. {
  11802. if (ac_text[0] && s_eq(url_in.text, ac_text))
  11803. s_copy(click_url, ac_url, sizeof(click_url));
  11804. *action |= ACT_NAV;
  11805. sug_close();
  11806. }
  11807. /* The bar text changed through typing or editing. */
  11808. static void sug_changed(void)
  11809. {
  11810. unsigned int pl = s_len(sug_typed);
  11811. int grew = url_in.len > pl && url_in.cursor == url_in.len &&
  11812. !memcmp(url_in.text, sug_typed, pl);
  11813. s_copy(sug_typed, url_in.text, sizeof(sug_typed));
  11814. ac_text[0] = '\0';
  11815. sug_sel = -1;
  11816. sug_open = 1;
  11817. sug_refresh();
  11818. if (grew)
  11819. sug_inline();
  11820. }
  11821. /* Keys for the list, taken off the queue before the text field sees them.
  11822. * Only a leading run is handled; the rest goes to the field. */
  11823. static void sug_keys(void)
  11824. {
  11825. int k;
  11826. while ((k = ngui_key_peek(&ui)) != 0) {
  11827. if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
  11828. ngui_key(&ui);
  11829. if (!sug_open) {
  11830. sug_open = 1;
  11831. continue;
  11832. }
  11833. if (sug_sel < 0)
  11834. s_copy(sug_restore, url_in.text,
  11835. sizeof(sug_restore));
  11836. if (k == NGUI_KEY_DOWN)
  11837. sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
  11838. else
  11839. sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
  11840. ngui_input_set(&url_in, sug_sel >= 0 ?
  11841. hist_tab[sug_idx[sug_sel]].url :
  11842. sug_restore);
  11843. } else if (k == NGUI_KEY_ESC && sug_visible()) {
  11844. ngui_key(&ui);
  11845. if (sug_sel >= 0)
  11846. ngui_input_set(&url_in, sug_restore);
  11847. else if (ac_text[0] && s_eq(url_in.text, ac_text))
  11848. ngui_input_set(&url_in, sug_typed);
  11849. sug_close();
  11850. } else if (k == NGUI_KEY_DELETE && sug_visible() &&
  11851. sug_sel >= 0) {
  11852. ngui_key(&ui);
  11853. hist_forget(sug_idx[sug_sel]);
  11854. ngui_input_set(&url_in, sug_restore);
  11855. sug_sel = -1;
  11856. sug_refresh();
  11857. } else {
  11858. break;
  11859. }
  11860. }
  11861. }
  11862. /* A press on a row of last frame's list opens it; any press on the list is
  11863. * swallowed so the page underneath does not see it. */
  11864. static void sug_click(unsigned int *action)
  11865. {
  11866. int row;
  11867. if (!(ui.pressed & 1) || !sug_rect.w ||
  11868. !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
  11869. return;
  11870. row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
  11871. if (row >= 0 && row < sug_n) {
  11872. s_copy(click_url, hist_tab[sug_idx[row]].url,
  11873. sizeof(click_url));
  11874. *action |= ACT_NAV;
  11875. sug_close();
  11876. }
  11877. ui.pressed = 0;
  11878. }
  11879. static void draw_suggest(struct ngui_rect page)
  11880. {
  11881. struct ngui_rect r;
  11882. int i, rows = sug_n, hover = -1;
  11883. r.x = url_rect.x;
  11884. r.y = url_rect.y + url_rect.h + 1;
  11885. r.w = url_rect.w < 320 ? 320 : url_rect.w;
  11886. if (r.x + r.w > ui.w - 2)
  11887. r.w = ui.w - 2 - r.x;
  11888. while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
  11889. rows--;
  11890. if (rows <= 0 || r.w < 60) {
  11891. sug_rect.w = 0;
  11892. return;
  11893. }
  11894. r.h = rows * SUG_ROW_H + 2;
  11895. sug_rect = r;
  11896. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  11897. hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
  11898. ngui_set_cursor(&ui, CURSOR_POINTER);
  11899. }
  11900. ngui_fill_rect(&ui, r, ui.theme.border);
  11901. for (i = 0; i < rows; i++) {
  11902. const struct hist_ent *e = &hist_tab[sug_idx[i]];
  11903. struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
  11904. r.w - 2, SUG_ROW_H};
  11905. struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
  11906. unsigned short bg = i == sug_sel ? ui.theme.selection :
  11907. i == hover ? ui.theme.panel_alt :
  11908. ui.theme.panel;
  11909. ngui_fill_rect(&ui, rr, bg);
  11910. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
  11911. e->title[0] ? e->title : e->url,
  11912. ui.theme.text);
  11913. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
  11914. i == sug_sel ? ui.theme.text :
  11915. ui.theme.text_dim);
  11916. }
  11917. }
  11918. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  11919. {
  11920. int x = r.x + 4, y = r.y + 4, h = 22;
  11921. int compact = r.w < 560;
  11922. int go_w = r.w < 420 ? 32 : 42;
  11923. int in_x, in_w, res;
  11924. ngui_fill_rect(&ui, r, ui.theme.panel);
  11925. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  11926. ui.theme.border);
  11927. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  11928. NGUI_ICON_CHEVRON_LEFT))
  11929. *action |= ACT_BACK;
  11930. x += 32;
  11931. if (!compact) {
  11932. if (ngui_icon_button(&ui, ID_FORWARD,
  11933. (struct ngui_rect){x, y, 28, h},
  11934. NGUI_ICON_CHEVRON_RIGHT))
  11935. *action |= ACT_FORWARD;
  11936. x += 32;
  11937. }
  11938. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  11939. NGUI_ICON_REFRESH))
  11940. *action |= ACT_RELOAD;
  11941. x += 32;
  11942. if (!compact) {
  11943. if (ngui_icon_button(&ui, ID_HOME,
  11944. (struct ngui_rect){x, y, 28, h},
  11945. NGUI_ICON_HOME))
  11946. *action |= ACT_HOME;
  11947. x += 32;
  11948. }
  11949. in_x = x + 2;
  11950. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  11951. if (in_w < 60)
  11952. in_w = 60;
  11953. url_rect = (struct ngui_rect){in_x, y, in_w, h};
  11954. if (sug_focus_check())
  11955. sug_keys();
  11956. res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
  11957. sug_focus_check(); /* a click into the bar focuses it here */
  11958. if (res & NGUI_INPUT_CHANGED)
  11959. sug_changed();
  11960. if (res & NGUI_INPUT_SUBMIT)
  11961. url_submit(action);
  11962. if (res & NGUI_INPUT_CANCEL)
  11963. ngui_set_focus(&ui, 0);
  11964. if (ngui_button(&ui, ID_GO,
  11965. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  11966. "Go"))
  11967. url_submit(action);
  11968. if (!sug_focus_check())
  11969. sug_close();
  11970. }
  11971. static int page_hover_node(void)
  11972. {
  11973. if (!ui.inside)
  11974. return 0;
  11975. if (ui.mouse_x < page_rect.x ||
  11976. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  11977. ui.mouse_y < page_rect.y ||
  11978. ui.mouse_y >= page_rect.y + page_rect.h)
  11979. return 0;
  11980. return find_hit(ui.mouse_x, ui.mouse_y);
  11981. }
  11982. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  11983. {
  11984. int x, y, w = page.w, h = page.h;
  11985. if (!src || w <= 0 || h <= 0)
  11986. return;
  11987. for (y = 0; y < h; y++) {
  11988. unsigned short *s = src + (page.y + y) * sw + page.x;
  11989. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  11990. for (x = 0; x + 1 < w; x += 2) {
  11991. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  11992. }
  11993. if (x < w)
  11994. d[x] = s[x];
  11995. }
  11996. }
  11997. static void draw_page(struct ngui_rect page)
  11998. {
  11999. int left, right, ch;
  12000. int old_panel, old_dim;
  12001. unsigned short *saved_px;
  12002. unsigned short page_bg = ui.theme.bg;
  12003. int saved_w, saved_h, use_buf;
  12004. unsigned int t0 = u_ticks_ms();
  12005. page_rect = page;
  12006. {
  12007. unsigned int root = doc.nnode > 1 ?
  12008. br_find_tag(&doc, BR_TAG_HTML) : 0;
  12009. unsigned int body = doc.nnode > 1 ?
  12010. br_find_tag(&doc, BR_TAG_BODY) : 0;
  12011. struct br_style bs;
  12012. int bg_found = 0;
  12013. if (root) {
  12014. style_for_node(root - 1, &bs);
  12015. if (bs.has_bg) {
  12016. page_bg = bs.bg;
  12017. bg_found = 1;
  12018. }
  12019. }
  12020. if (body) {
  12021. style_for_node(body - 1, &bs);
  12022. if (bs.has_bg) {
  12023. page_bg = bs.bg;
  12024. bg_found = 1;
  12025. }
  12026. }
  12027. /* No canvas colour, but the author made the text dark
  12028. * (Infima's light theme: `--ifm-background-color:
  12029. * transparent` on html, #1c1e21 text): the page expects the
  12030. * white canvas of a normal browser, and dark text on the
  12031. * dark default canvas is unreadable. */
  12032. if (!bg_found && (body || root) && bs.color != ui.theme.text) {
  12033. unsigned int c = bs.color;
  12034. unsigned int lum = ((c >> 11) & 31) * 8 * 299 +
  12035. ((c >> 5) & 63) * 4 * 587 +
  12036. (c & 31) * 8 * 114;
  12037. if (lum < 100 * 1000)
  12038. page_bg = 0xFFFF;
  12039. }
  12040. }
  12041. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  12042. page_cache_valid && layout_valid &&
  12043. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  12044. !(ui.scroll_y &&
  12045. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  12046. page_scroll.offset == page_cache_scroll &&
  12047. page_cache_nnode == doc.nnode &&
  12048. page_cache_x == page.x && page_cache_y == page.y &&
  12049. page_cache_w == page.w && page_cache_h == page.h) {
  12050. blit_page(page, page_backbuf, pagebuf_w);
  12051. if (img_stat_n)
  12052. img_stat_paint += u_ticks_ms() - t0;
  12053. return;
  12054. }
  12055. ngui_fill_rect(&ui, page, page_bg);
  12056. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  12057. const char *s = page_loading ? "Loading..." : "No page";
  12058. int w = (int)ngui_text_width_ui(&ui, s);
  12059. ngui_text(&ui, page.x + (page.w - w) / 2,
  12060. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  12061. page_scroll.content_h = 0;
  12062. page_scroll.view_h = page.h;
  12063. page_cache_valid = 0;
  12064. return;
  12065. }
  12066. if (page.w < 40 || page.h < 40) {
  12067. page_cache_valid = 0;
  12068. return;
  12069. }
  12070. saved_px = ui.px;
  12071. saved_w = ui.w;
  12072. saved_h = ui.h;
  12073. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  12074. if (use_buf) {
  12075. ui.px = page_backbuf;
  12076. ui.w = pagebuf_w;
  12077. ui.h = pagebuf_h;
  12078. ngui_fill_rect(&ui, page, page_bg);
  12079. }
  12080. /* No gutter of our own: the body's UA margin provides it. The
  12081. * right 12 px stay clear for the scrollbar, like every viewport
  12082. * width below (page_rect.w - 12). */
  12083. left = page.x;
  12084. right = page.x + page.w - 12;
  12085. if (!layout_valid || left != layout_left || right != layout_right ||
  12086. layout_nnode != doc.nnode) {
  12087. unsigned int tm = u_ticks_ms();
  12088. layout_view_h = page.h;
  12089. layout_content_h = measure_page(left, right);
  12090. if (img_stat_n)
  12091. img_stat_reflow += u_ticks_ms() - tm;
  12092. layout_valid = 1;
  12093. layout_left = left;
  12094. layout_right = right;
  12095. layout_nnode = doc.nnode;
  12096. /* Scripts that measured before any layout (offsetWidth on
  12097. * mount) get a resize event once real boxes exist, and again
  12098. * whenever the page width changes. */
  12099. if (js_browser_active() && right - left != resize_sent_w)
  12100. resize_pending = 1;
  12101. }
  12102. ch = layout_content_h;
  12103. page_scroll.content_h = ch;
  12104. page_scroll.view_h = page.h;
  12105. t0 = u_ticks_ms();
  12106. ngui_scroll_begin(&ui, page, &page_scroll);
  12107. ngui_scroll_wheel(&ui, page, &page_scroll);
  12108. render_page(left, right, page.y - page_scroll.offset);
  12109. old_panel = ui.theme.panel_alt;
  12110. old_dim = ui.theme.text_dim;
  12111. ui.theme.panel_alt = 0xC618;
  12112. ui.theme.text_dim = 0x8410;
  12113. ngui_scroll_end(&ui, page, &page_scroll);
  12114. ui.theme.panel_alt = old_panel;
  12115. ui.theme.text_dim = old_dim;
  12116. if (use_buf) {
  12117. ui.px = saved_px;
  12118. ui.w = saved_w;
  12119. ui.h = saved_h;
  12120. blit_page(page, page_backbuf, pagebuf_w);
  12121. page_cache_valid = 1;
  12122. page_cache_scroll = page_scroll.offset;
  12123. page_cache_nnode = doc.nnode;
  12124. page_cache_x = page.x;
  12125. page_cache_y = page.y;
  12126. page_cache_w = page.w;
  12127. page_cache_h = page.h;
  12128. } else {
  12129. page_cache_valid = 0;
  12130. }
  12131. if (img_stat_n)
  12132. img_stat_paint += u_ticks_ms() - t0;
  12133. }
  12134. /* Lay the page out now, into the page back buffer, so scripts read real
  12135. * boxes for nodes they just inserted. Absolute/fixed boxes only get their
  12136. * boxes in the painting pass, so this is a full render; the next frame
  12137. * repaints the screen as usual. Skipped while the page has never been
  12138. * drawn (no viewport yet) or without the back buffer. */
  12139. static void js_force_layout(void)
  12140. {
  12141. static int busy;
  12142. unsigned short *saved_px = ui.px;
  12143. int saved_w = ui.w, saved_h = ui.h;
  12144. struct ngui_rect page = page_rect;
  12145. static unsigned int window_t0, spent;
  12146. unsigned int t0 = u_ticks_ms();
  12147. if (busy || !page_backbuf || pagebuf_w != ui.w ||
  12148. pagebuf_h != ui.h || page.w < 40 || page.h < 40 ||
  12149. layout_right <= layout_left)
  12150. return;
  12151. /* Budget: a script that alternates writes and reads (an animation
  12152. * loop) would otherwise re-render the page on every read. Past
  12153. * 40 ms of forced layouts in a 100 ms window it reads the last
  12154. * layout, as before. */
  12155. if (t0 - window_t0 >= 100) {
  12156. window_t0 = t0;
  12157. spent = 0;
  12158. }
  12159. if (spent >= 40)
  12160. return;
  12161. busy = 1;
  12162. ui.px = page_backbuf;
  12163. layout_view_h = page.h;
  12164. layout_content_h = measure_page(layout_left, layout_right);
  12165. layout_valid = 1;
  12166. layout_nnode = doc.nnode;
  12167. ngui_push_clip(&ui, page);
  12168. render_page(layout_left, layout_right, page.y - page_scroll.offset);
  12169. ngui_pop_clip(&ui);
  12170. ui.px = saved_px;
  12171. ui.w = saved_w;
  12172. ui.h = saved_h;
  12173. page_cache_valid = 0;
  12174. ngui_invalidate(&ui);
  12175. spent += u_ticks_ms() - t0;
  12176. busy = 0;
  12177. }
  12178. static void draw_status(struct ngui_rect r)
  12179. {
  12180. static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
  12181. unsigned int n = 0;
  12182. int hover = page_hover_node();
  12183. unsigned short color;
  12184. const char *kind;
  12185. ngui_fill_rect(&ui, r, ui.theme.panel);
  12186. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  12187. ui.theme.border);
  12188. /* Only a real link target is shown: a form control, or an element
  12189. * that is merely clickable through a script listener (google.com's
  12190. * jsaction wrapper around its search field), is not a link. */
  12191. if (hover && !br_href(&doc, (unsigned int)hover))
  12192. hover = 0;
  12193. if (hover) {
  12194. const char *href = br_href(&doc, (unsigned int)hover);
  12195. char url[BR_URL_MAX];
  12196. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  12197. s_append(msg, &n, "Link: ", sizeof(msg));
  12198. s_append(msg, &n, url, sizeof(msg));
  12199. } else {
  12200. s_copy(msg, "Link", sizeof(msg));
  12201. }
  12202. color = ui.theme.accent;
  12203. } else if (status_text[0]) {
  12204. s_copy(msg, status_text, sizeof(msg));
  12205. color = status_error ? ui.theme.error : ui.theme.text;
  12206. } else if (page_title[0]) {
  12207. s_copy(msg, page_title, sizeof(msg));
  12208. color = ui.theme.text;
  12209. } else {
  12210. s_copy(msg, "Ready", sizeof(msg));
  12211. color = ui.theme.text_dim;
  12212. }
  12213. kind = s_eq(page_url, "about:home") ? "HOME" :
  12214. page_is_local ? "FILE" :
  12215. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  12216. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  12217. {
  12218. int kw = (int)ngui_text_width_ui(&ui, kind);
  12219. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  12220. ui.theme.text_dim);
  12221. }
  12222. }
  12223. /* Mouse cursor over the page: the hovered node's CSS `cursor` (inherited);
  12224. * for `auto`, a hand over links, the I-beam over text fields, and the
  12225. * progress arrow anywhere on the page while it is still loading. The
  12226. * toolbar's URL field sets its own I-beam through ngui. */
  12227. static void page_cursor(void)
  12228. {
  12229. int hover = page_hover_node();
  12230. struct br_style st;
  12231. if (!hover) {
  12232. if (page_loading && ui.inside &&
  12233. ngui_rect_contains(&page_rect, ui.mouse_x, ui.mouse_y))
  12234. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  12235. return;
  12236. }
  12237. style_for_node((unsigned int)hover, &st);
  12238. if (st.cursor != BR_CURSOR_AUTO) {
  12239. ngui_set_cursor(&ui, (int)st.cursor - 1);
  12240. return;
  12241. }
  12242. if (br_href(&doc, (unsigned int)hover)) {
  12243. ngui_set_cursor(&ui, CURSOR_POINTER);
  12244. return;
  12245. }
  12246. if (form_is_control((unsigned int)hover)) {
  12247. int k = form_kind_of((unsigned int)hover);
  12248. if (form_disabled((unsigned int)hover))
  12249. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  12250. else if (k == FORM_TEXT || k == FORM_PASSWORD ||
  12251. k == FORM_TEXTAREA)
  12252. ngui_set_cursor(&ui, CURSOR_TEXT);
  12253. return;
  12254. }
  12255. if (page_loading)
  12256. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  12257. }
  12258. static void draw(unsigned int *action)
  12259. {
  12260. struct ngui_rect r = {0, 0, ui.w, ui.h};
  12261. struct ngui_rect toolbar, status, page;
  12262. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  12263. status = ngui_cut_bottom(&r, BR_STATUS_H);
  12264. page = r;
  12265. if (sug_visible())
  12266. sug_click(action);
  12267. draw_toolbar(toolbar, action);
  12268. draw_page(page);
  12269. draw_status(status);
  12270. page_cursor();
  12271. if (sug_visible())
  12272. draw_suggest(page);
  12273. else
  12274. sug_rect.w = 0;
  12275. }
  12276. static void redraw_now(void)
  12277. {
  12278. unsigned int action = 0;
  12279. ngui_begin(&ui);
  12280. draw(&action);
  12281. ngui_end(&ui);
  12282. }
  12283. static void handle_keys(unsigned int *action)
  12284. {
  12285. int k, scrolled = 0;
  12286. if (form_focus >= doc.nnode)
  12287. form_focus = 0;
  12288. if (form_focus && !ngui_focus(&ui)) {
  12289. while ((k = ngui_key(&ui)) != 0)
  12290. form_key(k);
  12291. return;
  12292. }
  12293. /* Batch queued page keys: a slow full-page render must not make a
  12294. * held Page Down advance only once every few frames. */
  12295. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  12296. scrolled++;
  12297. if (scrolled)
  12298. ngui_invalidate(&ui);
  12299. if (ngui_focus(&ui))
  12300. return;
  12301. while ((k = ngui_key(&ui)) != 0) {
  12302. switch (k) {
  12303. case NGUI_KEY_ESC:
  12304. *action |= ACT_CLOSE;
  12305. break;
  12306. case NGUI_KEY_TAB:
  12307. case 0x0C: /* Ctrl+L */
  12308. ngui_set_focus(&ui, ID_URL);
  12309. break;
  12310. case 0x12: /* Ctrl+R */
  12311. *action |= ACT_RELOAD;
  12312. break;
  12313. case NGUI_KEY_BACKSPACE:
  12314. *action |= ACT_BACK;
  12315. break;
  12316. case NGUI_KEY_UP:
  12317. ngui_scroll_to(&page_scroll,
  12318. page_scroll.offset - 24);
  12319. ngui_invalidate(&ui);
  12320. break;
  12321. case NGUI_KEY_DOWN:
  12322. ngui_scroll_to(&page_scroll,
  12323. page_scroll.offset + 24);
  12324. ngui_invalidate(&ui);
  12325. break;
  12326. case NGUI_KEY_HOME:
  12327. ngui_scroll_to(&page_scroll, 0);
  12328. ngui_invalidate(&ui);
  12329. break;
  12330. case NGUI_KEY_END:
  12331. ngui_scroll_to(&page_scroll,
  12332. page_scroll.content_h -
  12333. page_scroll.view_h);
  12334. ngui_invalidate(&ui);
  12335. break;
  12336. default:
  12337. break;
  12338. }
  12339. }
  12340. }
  12341. static unsigned int form_ancestor(unsigned int node)
  12342. {
  12343. unsigned int p = node;
  12344. while (p && p < doc.nnode) {
  12345. if (doc.nodes[p].tag == BR_TAG_FORM &&
  12346. doc.nodes[p].type == BR_NODE_ELEM)
  12347. return p;
  12348. p = doc.nodes[p].parent;
  12349. }
  12350. return 0;
  12351. }
  12352. static int form_descendant(unsigned int node, unsigned int form)
  12353. {
  12354. unsigned int p = node;
  12355. while (p && p < doc.nnode) {
  12356. if (p == form)
  12357. return 1;
  12358. p = doc.nodes[p].parent;
  12359. }
  12360. return 0;
  12361. }
  12362. static void form_reset_form(unsigned int form)
  12363. {
  12364. unsigned int i;
  12365. for (i = 0; i < FORM_MAX; i++)
  12366. if (form_states[i].used &&
  12367. form_descendant(form_states[i].node, form))
  12368. form_states[i].used = 0;
  12369. form_focus = 0;
  12370. }
  12371. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  12372. const char *s)
  12373. {
  12374. static const char hex[] = "0123456789ABCDEF";
  12375. while (s && *s && *n + 1 < cap) {
  12376. unsigned char c = (unsigned char)*s++;
  12377. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  12378. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  12379. c == '.' || c == '~') {
  12380. dst[(*n)++] = (char)c;
  12381. } else if (c == ' ') {
  12382. dst[(*n)++] = '+';
  12383. } else if (*n + 3 < cap) {
  12384. dst[(*n)++] = '%';
  12385. dst[(*n)++] = hex[c >> 4];
  12386. dst[(*n)++] = hex[c & 15];
  12387. }
  12388. }
  12389. dst[*n] = '\0';
  12390. }
  12391. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  12392. const char *name, const char *value, int *first)
  12393. {
  12394. if (!name || !name[0])
  12395. return;
  12396. if (!*first && *n + 1 < cap)
  12397. dst[(*n)++] = '&';
  12398. *first = 0;
  12399. form_url_append(dst, n, cap, name);
  12400. if (*n + 1 < cap)
  12401. dst[(*n)++] = '=';
  12402. form_url_append(dst, n, cap, value ? value : "");
  12403. dst[*n] = '\0';
  12404. }
  12405. static int form_submit_form(unsigned int node, int fire_event)
  12406. {
  12407. unsigned int form = form_ancestor(node);
  12408. char action[BR_URL_MAX], query[2048];
  12409. unsigned int qn = 0, i;
  12410. int first = 1, is_post = 0;
  12411. const char *a, *method;
  12412. if (!form)
  12413. return 0;
  12414. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  12415. return 0;
  12416. method = br_find_attr(&doc, form, "method");
  12417. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  12418. is_post = 1;
  12419. a = br_find_attr(&doc, form, "action");
  12420. if (a && a[0]) {
  12421. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  12422. return 0;
  12423. } else {
  12424. s_copy(action, page_url, sizeof(action));
  12425. }
  12426. query[0] = '\0';
  12427. for (i = 0; i < doc.nnode; i++) {
  12428. struct br_node *nd = &doc.nodes[i];
  12429. struct form_state *fs;
  12430. const char *name;
  12431. const char *value = "";
  12432. if (nd->type != BR_NODE_ELEM || i == form ||
  12433. !form_descendant(i, form))
  12434. continue;
  12435. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  12436. nd->tag != BR_TAG_SELECT)
  12437. continue;
  12438. if (form_disabled(i))
  12439. continue;
  12440. name = br_find_attr(&doc, i, "name");
  12441. if (!name || !name[0])
  12442. continue;
  12443. fs = form_get(i, 1);
  12444. if (!fs)
  12445. continue;
  12446. if (nd->tag == BR_TAG_SELECT) {
  12447. char opt[64];
  12448. if (!form_option_text(i, fs->selected, opt,
  12449. sizeof(opt)))
  12450. s_copy(opt, "", sizeof(opt));
  12451. value = opt;
  12452. {
  12453. unsigned int c, oi = 0;
  12454. for (c = nd->first; c;
  12455. c = doc.nodes[c].next) {
  12456. if (doc.nodes[c].type != BR_NODE_ELEM ||
  12457. doc.nodes[c].tag != BR_TAG_OPTION)
  12458. continue;
  12459. if (oi == fs->selected) {
  12460. const char *v =
  12461. br_value(&doc, c);
  12462. if (v && v[0])
  12463. value = v;
  12464. break;
  12465. }
  12466. oi++;
  12467. }
  12468. }
  12469. } else if (nd->tag == BR_TAG_INPUT) {
  12470. int kind = form_kind_of(i);
  12471. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  12472. if (!fs->checked)
  12473. continue;
  12474. value = br_value(&doc, i);
  12475. if (!value || !value[0])
  12476. value = "on";
  12477. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  12478. kind == FORM_BUTTON) {
  12479. if (i != node)
  12480. continue;
  12481. value = fs->value;
  12482. } else {
  12483. value = fs->value;
  12484. }
  12485. } else {
  12486. value = fs->value;
  12487. }
  12488. form_add_param(query, &qn, sizeof(query), name, value, &first);
  12489. }
  12490. if (is_post) {
  12491. if (action[0] == '/') {
  12492. set_status("POST forms need an HTTP action URL", 1, 4000);
  12493. ngui_invalidate(&ui);
  12494. return 0;
  12495. }
  12496. if (qn >= sizeof(pending_post))
  12497. qn = sizeof(pending_post) - 1;
  12498. if (qn)
  12499. memcpy(pending_post, query, qn);
  12500. pending_post[qn] = '\0';
  12501. pending_post_len = qn;
  12502. pending_post_is = 1;
  12503. } else {
  12504. pending_post_len = 0;
  12505. pending_post_is = 0;
  12506. if (qn) {
  12507. unsigned int an = s_len(action);
  12508. if (an + qn + 2 < sizeof(action)) {
  12509. action[an++] = strchr(action, '?') ? '&' : '?';
  12510. action[an] = '\0';
  12511. s_copy(action + an, query,
  12512. sizeof(action) - an);
  12513. }
  12514. }
  12515. }
  12516. s_copy(pending_url, action, sizeof(pending_url));
  12517. pending_action |= ACT_NAV;
  12518. cancel_fetch = 1;
  12519. ngui_invalidate(&ui);
  12520. return 1;
  12521. }
  12522. static void form_reset_event(unsigned int form)
  12523. {
  12524. if (form && !js_browser_event(form, "reset", 1, 1))
  12525. return;
  12526. if (form)
  12527. form_reset_form(form);
  12528. else
  12529. form_reset_state();
  12530. form_dirty = 0;
  12531. layout_valid = 0;
  12532. ngui_invalidate(&ui);
  12533. }
  12534. static void form_blur(void)
  12535. {
  12536. unsigned int node = form_focus;
  12537. form_focus = 0;
  12538. if (node && form_dirty) {
  12539. form_dirty = 0;
  12540. js_browser_event(node, "change", 1, 0);
  12541. }
  12542. }
  12543. static void form_click(unsigned int node)
  12544. {
  12545. struct form_state *fs;
  12546. int kind, changed = 0;
  12547. if (!form_is_control(node) || form_disabled(node))
  12548. return;
  12549. if (form_focus != node)
  12550. form_blur();
  12551. fs = form_get(node, 1);
  12552. if (!fs)
  12553. return;
  12554. kind = form_kind_of(node);
  12555. /* Focus moves on the press, before `click` is dispatched: a page
  12556. * that cancels the click (a framework's root listener) suppresses
  12557. * the activation behaviour below, never the focus (as in other
  12558. * browsers, where focus follows mousedown). */
  12559. form_focus = node;
  12560. form_dirty = 0;
  12561. if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  12562. kind == FORM_TEXTAREA)
  12563. fs->caret = fs->len;
  12564. layout_valid = 0;
  12565. ngui_invalidate(&ui);
  12566. if (!js_browser_event(node, "click", 1, 1))
  12567. return;
  12568. fs = form_get(node, 0); /* the handler may have changed the DOM */
  12569. if (!fs)
  12570. return;
  12571. if (kind == FORM_CHECKBOX) {
  12572. fs->checked = !fs->checked;
  12573. changed = 1;
  12574. } else if (kind == FORM_RADIO) {
  12575. const char *name = br_find_attr(&doc, node, "name");
  12576. unsigned int i;
  12577. fs->checked = 1;
  12578. changed = 1;
  12579. if (name) {
  12580. for (i = 0; i < FORM_MAX; i++) {
  12581. struct form_state *o = &form_states[i];
  12582. if (!o->used || o->node == node)
  12583. continue;
  12584. if (form_kind_of(o->node) == FORM_RADIO) {
  12585. const char *on = br_find_attr(&doc,
  12586. o->node,
  12587. "name");
  12588. if (on && s_eq(on, name))
  12589. o->checked = 0;
  12590. }
  12591. }
  12592. }
  12593. } else if (kind == FORM_SELECT) {
  12594. unsigned int n = form_option_count(node);
  12595. if (n) {
  12596. fs->selected = (unsigned char)
  12597. ((fs->selected + 1) % n);
  12598. changed = 1;
  12599. }
  12600. } else if (kind == FORM_SUBMIT) {
  12601. form_submit_form(node, 1);
  12602. return;
  12603. } else if (kind == FORM_RESET) {
  12604. form_reset_event(form_ancestor(node));
  12605. return;
  12606. }
  12607. if (changed) {
  12608. js_browser_event(node, "input", 1, 0);
  12609. js_browser_event(node, "change", 1, 0);
  12610. }
  12611. layout_valid = 0;
  12612. ngui_invalidate(&ui);
  12613. }
  12614. static void form_focus_next(void)
  12615. {
  12616. unsigned int start = form_focus ? form_focus + 1 : 0;
  12617. unsigned int i;
  12618. form_blur();
  12619. for (i = start; i < doc.nnode; i++) {
  12620. if (form_is_control(i) && !form_disabled(i) &&
  12621. !s_eq(br_type(&doc, i), "hidden")) {
  12622. form_focus = i;
  12623. layout_valid = 0;
  12624. ngui_invalidate(&ui);
  12625. return;
  12626. }
  12627. }
  12628. form_focus = 0;
  12629. layout_valid = 0;
  12630. ngui_invalidate(&ui);
  12631. }
  12632. static void form_key(int k)
  12633. {
  12634. struct form_state *fs;
  12635. int kind;
  12636. if (!form_focus || form_focus >= doc.nnode) {
  12637. form_focus = 0;
  12638. return;
  12639. }
  12640. fs = form_get(form_focus, 1);
  12641. if (!fs || form_disabled(form_focus))
  12642. return;
  12643. kind = form_kind_of(form_focus);
  12644. if (kind == FORM_SELECT) {
  12645. unsigned int n = form_option_count(form_focus);
  12646. int changed = 0;
  12647. if (k == NGUI_KEY_UP && n) {
  12648. fs->selected = (unsigned char)
  12649. ((fs->selected + n - 1) % n);
  12650. changed = 1;
  12651. } else if (k == NGUI_KEY_DOWN && n) {
  12652. fs->selected = (unsigned char)
  12653. ((fs->selected + 1) % n);
  12654. changed = 1;
  12655. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  12656. form_blur();
  12657. layout_valid = 0;
  12658. ngui_invalidate(&ui);
  12659. return;
  12660. } else {
  12661. return;
  12662. }
  12663. if (changed) {
  12664. js_browser_event(form_focus, "input", 1, 0);
  12665. js_browser_event(form_focus, "change", 1, 0);
  12666. }
  12667. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  12668. if (k == ' ') {
  12669. form_click(form_focus);
  12670. return;
  12671. }
  12672. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  12673. form_blur();
  12674. layout_valid = 0;
  12675. ngui_invalidate(&ui);
  12676. }
  12677. return;
  12678. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  12679. kind == FORM_RESET) {
  12680. if (k == NGUI_KEY_ESC) {
  12681. form_blur();
  12682. layout_valid = 0;
  12683. ngui_invalidate(&ui);
  12684. } else if (k == '\r' || k == '\n' || k == ' ') {
  12685. form_click(form_focus);
  12686. }
  12687. return;
  12688. } else if (k == NGUI_KEY_TAB) {
  12689. form_focus_next();
  12690. return;
  12691. } else if (k == NGUI_KEY_ESC) {
  12692. form_blur();
  12693. layout_valid = 0;
  12694. ngui_invalidate(&ui);
  12695. return;
  12696. } else if (k == '\r' || k == '\n') {
  12697. unsigned int node = form_focus;
  12698. form_blur();
  12699. if (form_ancestor(node))
  12700. form_submit_form(node, 1);
  12701. layout_valid = 0;
  12702. ngui_invalidate(&ui);
  12703. return;
  12704. } else if (k == NGUI_KEY_BACKSPACE) {
  12705. if (fs->caret) {
  12706. unsigned int i = --fs->caret;
  12707. for (; i < fs->len; i++)
  12708. fs->value[i] = fs->value[i + 1];
  12709. if (fs->len)
  12710. fs->len--;
  12711. form_dirty = 1;
  12712. js_browser_event(form_focus, "input", 1, 0);
  12713. }
  12714. } else if (k == NGUI_KEY_DELETE) {
  12715. if (fs->caret < fs->len) {
  12716. unsigned int i;
  12717. for (i = fs->caret; i < fs->len; i++)
  12718. fs->value[i] = fs->value[i + 1];
  12719. fs->len--;
  12720. form_dirty = 1;
  12721. js_browser_event(form_focus, "input", 1, 0);
  12722. }
  12723. } else if (k == NGUI_KEY_LEFT) {
  12724. if (fs->caret)
  12725. fs->caret--;
  12726. } else if (k == NGUI_KEY_RIGHT) {
  12727. if (fs->caret < fs->len)
  12728. fs->caret++;
  12729. } else if (k == NGUI_KEY_HOME) {
  12730. fs->caret = 0;
  12731. } else if (k == NGUI_KEY_END) {
  12732. fs->caret = fs->len;
  12733. } else if (k >= 32 && k < 127) {
  12734. if (fs->len < FORM_VALUE_MAX) {
  12735. unsigned int i;
  12736. for (i = fs->len; i > fs->caret; i--)
  12737. fs->value[i] = fs->value[i - 1];
  12738. fs->value[fs->caret++] = (char)k;
  12739. fs->len++;
  12740. form_dirty = 1;
  12741. js_browser_event(form_focus, "input", 1, 0);
  12742. }
  12743. } else {
  12744. return;
  12745. }
  12746. fs->value[fs->len] = '\0';
  12747. layout_valid = 0;
  12748. ngui_invalidate(&ui);
  12749. }
  12750. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  12751. * a same-document navigation: update the URL and fire hashchange. Returns
  12752. * 1 when handled. */
  12753. static int link_fragment_nav(unsigned int node)
  12754. {
  12755. const char *href = br_href(&doc, node);
  12756. char url[BR_URL_MAX];
  12757. unsigned int n = 0;
  12758. if (!href || !href[0] || !js_browser_active())
  12759. return 0;
  12760. if (href[0] == '#') {
  12761. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  12762. url[n] = page_url[n];
  12763. n++;
  12764. }
  12765. url[n] = '\0';
  12766. s_append(url, &n, href, sizeof(url));
  12767. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  12768. return 0;
  12769. }
  12770. if (!same_doc_fragment(url))
  12771. return href[0] == '#';
  12772. page_set_fragment(url, 1);
  12773. js_browser_hashchange();
  12774. return 1;
  12775. }
  12776. /* A positioned box laid out while transparent or visibility:hidden (or
  12777. * inside one): it has a box for scripts but must not catch the pointer. */
  12778. static int node_invisible(unsigned int n)
  12779. {
  12780. unsigned int guard = 0;
  12781. while (n < doc.nnode && guard++ < 64) {
  12782. struct br_style st;
  12783. style_for_node(n, &st);
  12784. if (st.opacity_hidden || st.vis_hidden)
  12785. return 1;
  12786. if (n == 0)
  12787. break;
  12788. n = doc.nodes[n].parent;
  12789. }
  12790. return 0;
  12791. }
  12792. /* The innermost laid-out box under a screen point: the smallest valid box
  12793. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  12794. * Used to deliver clicks to elements that are neither links nor controls
  12795. * (a Vue <div role="button">, a card with a click listener). */
  12796. static unsigned int find_box_hit(int x, int y)
  12797. {
  12798. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  12799. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  12800. const struct br_layout_box *b = &layout_boxes[i];
  12801. unsigned int area;
  12802. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  12803. x < b->x || y < b->y || x >= b->x + b->w ||
  12804. y >= b->y + b->h)
  12805. continue;
  12806. area = (unsigned int)b->w * (unsigned int)b->h;
  12807. if (area <= best_area && !node_invisible(i)) {
  12808. best = i;
  12809. best_area = area;
  12810. }
  12811. }
  12812. return best;
  12813. }
  12814. /* The element under the pointer for hover events: the innermost laid-out
  12815. * box, or the link/control hit inside it (an inline <a> has no box of its
  12816. * own but a hit rectangle). -1 when none. */
  12817. static int hover_node = -1;
  12818. static int node_contains(unsigned int a, unsigned int n)
  12819. {
  12820. unsigned int guard = 0;
  12821. while (n < doc.nnode && guard++ < BR_MAX_NODES) {
  12822. if (n == a)
  12823. return 1;
  12824. if (n == 0)
  12825. return 0;
  12826. n = doc.nodes[n].parent;
  12827. }
  12828. return 0;
  12829. }
  12830. static int hover_target(void)
  12831. {
  12832. int h, x = ui.mouse_x, y = ui.mouse_y;
  12833. unsigned int b;
  12834. if (!ui.inside || ui.buttons || sug_visible() ||
  12835. x < page_rect.x || x >= page_rect.x + page_rect.w - 12 ||
  12836. y < page_rect.y || y >= page_rect.y + page_rect.h)
  12837. return -1;
  12838. h = find_hit(x, y);
  12839. b = find_box_hit(x, y);
  12840. if (h && (!b || node_contains(b, (unsigned int)h)))
  12841. return h;
  12842. if (b)
  12843. return (int)b;
  12844. return h ? h : -1;
  12845. }
  12846. /* mouseover/mouseout (bubbling, with relatedTarget) at the old and new
  12847. * element, and mouseleave/mouseenter on every ancestor that was left or
  12848. * entered (outermost first for enter), like a browser's boundary events.
  12849. * jQuery 1.11 builds its mouseenter (Bootstrap tooltips) from mouseover
  12850. * and relatedTarget. */
  12851. static void page_hover_events(void)
  12852. {
  12853. int now, old, cx, cy, path[64], np = 0, i;
  12854. unsigned int n;
  12855. if (!js_browser_active()) {
  12856. hover_node = -1;
  12857. return;
  12858. }
  12859. now = hover_target();
  12860. if (now >= (int)doc.nnode)
  12861. now = -1;
  12862. if (now == hover_node)
  12863. return;
  12864. old = hover_node;
  12865. if (old >= (int)doc.nnode)
  12866. old = -1;
  12867. hover_node = now;
  12868. cx = ui.mouse_x - page_rect.x;
  12869. cy = ui.mouse_y - page_rect.y;
  12870. if (old >= 0) {
  12871. js_browser_mouse_event((unsigned int)old, "mouseout", 1, now,
  12872. cx, cy);
  12873. for (n = (unsigned int)old, i = 0;
  12874. n < doc.nnode && i < 64 &&
  12875. !(now >= 0 && node_contains(n, (unsigned int)now)); i++) {
  12876. js_browser_mouse_event(n, "mouseleave", 0, now, cx, cy);
  12877. if (n == 0)
  12878. break;
  12879. n = doc.nodes[n].parent;
  12880. }
  12881. }
  12882. if (now < 0 || now >= (int)doc.nnode)
  12883. return;
  12884. js_browser_mouse_event((unsigned int)now, "mouseover", 1, old, cx, cy);
  12885. for (n = (unsigned int)now;
  12886. n < doc.nnode && np < 64 &&
  12887. !(old >= 0 && node_contains(n, (unsigned int)old));) {
  12888. path[np++] = (int)n;
  12889. if (n == 0)
  12890. break;
  12891. n = doc.nodes[n].parent;
  12892. }
  12893. for (i = np - 1; i >= 0; i--)
  12894. js_browser_mouse_event((unsigned int)path[i], "mouseenter", 0,
  12895. old, cx, cy);
  12896. }
  12897. static void handle_page_click(unsigned int *action)
  12898. {
  12899. int node;
  12900. char url[BR_URL_MAX];
  12901. if (!ui.pressed)
  12902. return;
  12903. if (ui.press_x < page_rect.x ||
  12904. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  12905. ui.press_y < page_rect.y ||
  12906. ui.press_y >= page_rect.y + page_rect.h)
  12907. return;
  12908. node = find_hit(ui.press_x, ui.press_y);
  12909. if (!node) {
  12910. unsigned int box;
  12911. if (!js_browser_active())
  12912. return;
  12913. box = find_box_hit(ui.press_x, ui.press_y);
  12914. if (box) {
  12915. form_blur();
  12916. js_browser_event(box, "click", 1, 1);
  12917. }
  12918. return;
  12919. }
  12920. if (form_is_control((unsigned int)node)) {
  12921. form_click((unsigned int)node);
  12922. return;
  12923. }
  12924. form_blur();
  12925. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  12926. return;
  12927. if (link_fragment_nav((unsigned int)node))
  12928. return;
  12929. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  12930. sizeof(url)) != 0)
  12931. return;
  12932. s_copy(click_url, url, sizeof(click_url));
  12933. *action |= ACT_NAV;
  12934. }
  12935. void _start(const char *arg)
  12936. {
  12937. struct win_info wi;
  12938. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  12939. u_win_create(960, 640, "Browser", &wi) != 0 &&
  12940. u_win_create(780, 540, "Browser", &wi) != 0) {
  12941. u_puts("browser: no graphics window\n");
  12942. u_exit(1);
  12943. }
  12944. ufont_set_arena_bytes(BR_FONT_ARENA);
  12945. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  12946. url_in.placeholder = "http://...";
  12947. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  12948. ui.theme.accent);
  12949. br_set_viewport(wi.width);
  12950. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  12951. s_copy(cwd, "/", sizeof(cwd));
  12952. heap_clear();
  12953. origin_cache_load();
  12954. css_cache_init();
  12955. script_cache_init();
  12956. font_cache_init();
  12957. persist_restore();
  12958. hist_load();
  12959. page_scroll.offset = 0;
  12960. page_scroll.content_h = 0;
  12961. if (arg && arg[0]) {
  12962. navigate(arg, 1);
  12963. } else {
  12964. load_home(1);
  12965. /* Start ready to type: keep the home page, but leave the address
  12966. * bar empty instead of showing "about:home". */
  12967. ngui_input_set(&url_in, "");
  12968. ngui_set_focus(&ui, ID_URL);
  12969. }
  12970. for (;;) {
  12971. unsigned int action = 0;
  12972. unsigned int now;
  12973. click_url[0] = '\0';
  12974. if (pending_action) {
  12975. action |= pending_action & ACT_WAIT_NAV;
  12976. if (pending_url[0])
  12977. s_copy(click_url, pending_url, sizeof(click_url));
  12978. pending_action = 0;
  12979. pending_url[0] = '\0';
  12980. cancel_fetch = 0;
  12981. } else if (preload_active) {
  12982. if (preload_wait)
  12983. preload_wait = 0;
  12984. else
  12985. preload_step();
  12986. } else if ((preload_pending &&
  12987. page_scroll.offset != preload_scroll) ||
  12988. (preload_rescan && layout_valid)) {
  12989. preload_scroll = page_scroll.offset;
  12990. preload_rescan = 0;
  12991. preload_pending = 0;
  12992. preload_node = 0;
  12993. preload_active = 1;
  12994. }
  12995. js_browser_tick();
  12996. if (resize_pending && !pending_action) {
  12997. resize_pending = 0;
  12998. resize_sent_w = layout_right - layout_left;
  12999. js_browser_window_event("resize");
  13000. }
  13001. persist_tick();
  13002. if (pending_action)
  13003. continue;
  13004. now = u_ticks_ms();
  13005. if (status_until && (int)(now - status_until) >= 0) {
  13006. status_text[0] = '\0';
  13007. status_until = 0;
  13008. status_error = 0;
  13009. ngui_invalidate(&ui);
  13010. }
  13011. if (!ngui_begin(&ui)) {
  13012. /* A queued navigation (e.g. Enter in the URL bar during
  13013. * a slow fetch) must be handled even when this frame
  13014. * needs no redraw. */
  13015. if (!action) {
  13016. fetch_workers_stop_if_unfocused();
  13017. u_sleep_ms(10);
  13018. continue;
  13019. }
  13020. } else {
  13021. draw(&action);
  13022. handle_keys(&action);
  13023. handle_page_click(&action);
  13024. page_hover_events();
  13025. ngui_end(&ui);
  13026. }
  13027. if (action & ACT_NAV) {
  13028. if (click_url[0]) {
  13029. navigate(click_url, 1);
  13030. click_url[0] = '\0';
  13031. } else {
  13032. navigate(url_in.text, 1);
  13033. }
  13034. }
  13035. if (action & ACT_BACK) {
  13036. if (hist_pos > 0) {
  13037. hist_pos--;
  13038. if (same_doc_fragment(history[hist_pos])) {
  13039. page_set_fragment(history[hist_pos], 0);
  13040. js_browser_hashchange();
  13041. } else {
  13042. navigate(history[hist_pos], 0);
  13043. }
  13044. }
  13045. }
  13046. if (action & ACT_FORWARD) {
  13047. if (hist_pos + 1 < hist_len) {
  13048. hist_pos++;
  13049. if (same_doc_fragment(history[hist_pos])) {
  13050. page_set_fragment(history[hist_pos], 0);
  13051. js_browser_hashchange();
  13052. } else {
  13053. navigate(history[hist_pos], 0);
  13054. }
  13055. }
  13056. }
  13057. if (action & ACT_RELOAD) {
  13058. if (s_eq(page_url, "about:home"))
  13059. load_home(0);
  13060. else
  13061. navigate(page_url, 0);
  13062. }
  13063. if (action & ACT_HOME)
  13064. load_home(1);
  13065. if (action & ACT_CLOSE)
  13066. quit = 1;
  13067. if (quit)
  13068. break;
  13069. if (pending_action)
  13070. continue;
  13071. fetch_workers_stop_if_unfocused();
  13072. u_sleep_ms(10);
  13073. }
  13074. fetch_workers_stop_all();
  13075. u_win_close();
  13076. u_exit(0);
  13077. }