browser.c 352 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321
  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. #define BR_MAX_SHEETS 6
  71. #define BR_HISTORY 16
  72. #define BR_URL_MAX 4096 /* = UHTTP_PATH_MAX: google.com's JS URL is ~3.7 KB */
  73. #define BR_STATUS_MAX 200
  74. #define BR_IMG_RGB565(r, g, b) \
  75. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  76. #define BR_GRAY 0x8410
  77. enum {
  78. ID_URL = 1,
  79. ID_GO,
  80. ID_BACK,
  81. ID_FORWARD,
  82. ID_RELOAD,
  83. ID_HOME
  84. };
  85. #define ACT_NAV (1u << 0)
  86. #define ACT_BACK (1u << 1)
  87. #define ACT_FORWARD (1u << 2)
  88. #define ACT_RELOAD (1u << 3)
  89. #define ACT_HOME (1u << 4)
  90. #define ACT_CLOSE (1u << 5)
  91. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  92. ACT_HOME | ACT_CLOSE)
  93. struct br_image {
  94. int state; /* 0 empty, 1 ready */
  95. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  96. int native_w, native_h;
  97. unsigned int url_hash; /* <img> source, 0 = not shareable */
  98. char err[32];
  99. /* Display-size cache: the box an image is actually painted in. The
  100. * source bitmap above is deliberately capped at BR_IMG_LAYOUT_W so a
  101. * window resize can re-scale it; the cached copy is exactly dw x dh,
  102. * so every repaint is a 1:1 blit instead of a per-pixel resample. */
  103. struct img_image disp;
  104. unsigned int disp_pixels;
  105. unsigned int disp_last;
  106. };
  107. static struct ngui ui;
  108. static struct ngui_input url_in;
  109. static struct ngui_scroll page_scroll;
  110. static struct br_doc doc;
  111. static struct br_image images[BR_MAX_IMAGES];
  112. static int image_count;
  113. static unsigned int image_pixels;
  114. static unsigned int image_disp_pixels;
  115. static unsigned int image_disp_clock;
  116. /* Per-image pipeline timing for the status line and /share/IMGSTAT. The
  117. * numbers are what decides whether the next work is network, decode or
  118. * display; keep them cheap (one tick read per phase). */
  119. static unsigned int img_stat_start;
  120. static unsigned int img_stat_wall;
  121. static unsigned int img_stat_net;
  122. static unsigned int img_stat_open;
  123. static unsigned int img_stat_first;
  124. static unsigned int img_stat_io;
  125. static unsigned int img_stat_dec;
  126. static unsigned int img_stat_scale;
  127. static unsigned int img_stat_paint;
  128. static unsigned int img_stat_reflow;
  129. static unsigned int img_stat_bytes;
  130. static int img_stat_n;
  131. static unsigned int img_last_dec_ms;
  132. static unsigned int img_last_scale_ms;
  133. static char img_stat_log[BR_IMG_STAT_LOG];
  134. static unsigned int img_stat_log_len;
  135. static unsigned int img_repaint_ms;
  136. static int img_repaint_pending;
  137. /* Painted border boxes, in page/screen coordinates (layout starts at
  138. * page_rect.y + 4 - scroll). getBoundingClientRect() subtracts page_rect. */
  139. struct br_layout_box {
  140. int x, y;
  141. int w, h;
  142. unsigned char valid;
  143. };
  144. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  145. /* Images are loaded one per main-loop iteration so the parsed page stays
  146. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  147. static int preload_active;
  148. static int preload_max_jobs;
  149. static int preload_pending;
  150. static int preload_wait;
  151. static unsigned int preload_node;
  152. static int preload_loaded;
  153. static int preload_scroll;
  154. static int preload_rescan;
  155. static char post_status_text[BR_STATUS_MAX];
  156. static int post_status_error;
  157. static unsigned int post_status_ttl;
  158. /* Content-relative position/height of each <img>, recorded by the measure
  159. * pass so image loading can be deferred until it is near the viewport. */
  160. static unsigned short img_top[BR_MAX_NODES];
  161. static unsigned short img_h[BR_MAX_NODES];
  162. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  163. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  164. * body. Decode arenas are allocated per image instead of living here. */
  165. static unsigned char *image_io_buf;
  166. static struct ufont_face *font_faces[BR_MAX_FACES];
  167. #define image_file_buf (image_io_buf)
  168. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  169. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  170. static struct inflate image_inflate_ws;
  171. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  172. #error "CSS scratch must fit in image_io_buf"
  173. #endif
  174. static char page_url[BR_URL_MAX];
  175. static char page_title[BR_TITLE_MAX];
  176. static char cwd[64];
  177. static int page_is_local;
  178. static int page_loading;
  179. static char status_text[BR_STATUS_MAX];
  180. static unsigned int status_until;
  181. static int status_error;
  182. static char history[BR_HISTORY][BR_URL_MAX];
  183. static int hist_len, hist_pos;
  184. static char click_url[BR_URL_MAX];
  185. static char pending_url[BR_URL_MAX];
  186. #define BR_POST_MAX 4096
  187. static char pending_post[BR_POST_MAX];
  188. static unsigned int pending_post_len;
  189. /* The pending navigation is a POST even when its body is empty (a form
  190. * without fields, e.g. the OIDC consent auto-submit). */
  191. static int pending_post_is;
  192. /* window "resize" bookkeeping: the page width the last event was for. */
  193. static int resize_sent_w = -1;
  194. static int resize_pending;
  195. static unsigned int pending_action;
  196. static int cancel_fetch;
  197. static int quit;
  198. static struct ngui_rect page_rect;
  199. static unsigned short *page_backbuf;
  200. static int pagebuf_w, pagebuf_h;
  201. static int page_cache_valid;
  202. static int page_cache_scroll;
  203. static unsigned int page_cache_nnode;
  204. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  205. static int layout_valid, layout_left, layout_right;
  206. /* Height of the page viewport: what html/body height:100% resolves to. */
  207. static int layout_view_h;
  208. static unsigned int layout_nnode;
  209. static int layout_content_h;
  210. /* layout output */
  211. struct lay_run {
  212. unsigned int off;
  213. unsigned short len;
  214. unsigned short gap;
  215. unsigned short color;
  216. unsigned short href;
  217. char lit[28];
  218. short img;
  219. signed short dy; /* inline image vertical offset */
  220. unsigned short iw, ih;
  221. unsigned short w;
  222. unsigned char font_px, bold, italic, mono, underline, strike;
  223. unsigned char overline, font_face;
  224. unsigned char transform_scale;
  225. unsigned char origin_x_kind, origin_y_kind;
  226. signed short scale_x, scale_y, rotate_x100;
  227. signed short origin_x, origin_y;
  228. unsigned char has_lit;
  229. unsigned int form; /* node + 1, 0 = not a control */
  230. unsigned char form_kind;
  231. unsigned char form_disabled;
  232. /* RUN_PBOX: background colour, background image and its placement
  233. * inside the iw x ih box (relative offsets, drawn size). */
  234. unsigned char pb_has_bg;
  235. unsigned short pb_bg;
  236. short pb_img;
  237. short pb_x, pb_y, pb_w, pb_h;
  238. };
  239. struct lay {
  240. int draw;
  241. struct ngui *ui;
  242. int left, right;
  243. int y;
  244. int line_x, line_y, line_h;
  245. int line_left, line_right;
  246. int parent_top;
  247. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  248. int cb_h; /* definite content height of the containing block for
  249. * percentage heights; 0 = indefinite (auto) */
  250. int run_x;
  251. int align;
  252. int depth;
  253. int space_pending;
  254. unsigned char float_active;
  255. int float_left, float_right, float_bottom;
  256. struct lay_run runs[96];
  257. int nruns;
  258. };
  259. struct hit {
  260. int x, y, w, h;
  261. unsigned short node;
  262. };
  263. /* Live form state; the DOM attributes stay the initial/default value. */
  264. #define FORM_MAX 64
  265. #define FORM_VALUE_MAX 63
  266. enum {
  267. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  268. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  269. };
  270. struct form_state {
  271. unsigned int node;
  272. char value[FORM_VALUE_MAX + 1];
  273. unsigned char len, caret, checked, selected, used;
  274. };
  275. static struct form_state form_states[FORM_MAX];
  276. static unsigned int form_focus;
  277. static unsigned int form_dirty;
  278. static int form_descendant(unsigned int node, unsigned int form);
  279. static int form_submit_form(unsigned int node, int fire_event);
  280. static int link_fragment_nav(unsigned int node);
  281. static void history_push(const char *url);
  282. static void form_reset_event(unsigned int form);
  283. static unsigned int s_len(const char *s);
  284. static int s_eq(const char *a, const char *b);
  285. static void form_key(int k);
  286. static void form_click(unsigned int node);
  287. static void style_for_node(unsigned int node, struct br_style *out);
  288. static int form_author_styled(const struct br_style *st);
  289. static int css_radius(const struct br_style *st, int corner, int w, int h);
  290. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  291. const struct br_style *st, int focused);
  292. static int form_disabled(unsigned int node)
  293. {
  294. struct br_node *n = &doc.nodes[node];
  295. if (n->attr_flags & BR_ATTR_DISABLED)
  296. return 1;
  297. return br_find_attr(&doc, node, "disabled") != 0;
  298. }
  299. static int form_kind_of(unsigned int node)
  300. {
  301. const char *type = br_type(&doc, node);
  302. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  303. return FORM_TEXTAREA;
  304. if (doc.nodes[node].tag == BR_TAG_SELECT)
  305. return FORM_SELECT;
  306. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  307. if (s_eq(type, "reset"))
  308. return FORM_RESET;
  309. if (s_eq(type, "button"))
  310. return FORM_BUTTON;
  311. return FORM_SUBMIT;
  312. }
  313. if (s_eq(type, "password"))
  314. return FORM_PASSWORD;
  315. if (s_eq(type, "checkbox"))
  316. return FORM_CHECKBOX;
  317. if (s_eq(type, "radio"))
  318. return FORM_RADIO;
  319. if (s_eq(type, "submit"))
  320. return FORM_SUBMIT;
  321. if (s_eq(type, "reset"))
  322. return FORM_RESET;
  323. if (s_eq(type, "button"))
  324. return FORM_BUTTON;
  325. return FORM_TEXT;
  326. }
  327. static unsigned int form_option_count(unsigned int node)
  328. {
  329. unsigned int c, n = 0;
  330. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  331. if (doc.nodes[c].type == BR_NODE_ELEM &&
  332. doc.nodes[c].tag == BR_TAG_OPTION)
  333. n++;
  334. return n;
  335. }
  336. static unsigned int form_option_selected(unsigned int node)
  337. {
  338. unsigned int c, i = 0;
  339. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  340. if (doc.nodes[c].type != BR_NODE_ELEM ||
  341. doc.nodes[c].tag != BR_TAG_OPTION)
  342. continue;
  343. if (br_find_attr(&doc, c, "selected"))
  344. return i;
  345. i++;
  346. }
  347. return 0;
  348. }
  349. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  350. char *out, unsigned int cap)
  351. {
  352. unsigned int c, i = 0;
  353. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  354. if (doc.nodes[c].type != BR_NODE_ELEM ||
  355. doc.nodes[c].tag != BR_TAG_OPTION)
  356. continue;
  357. if (i == idx)
  358. return br_text_content(&doc, c, out, cap);
  359. i++;
  360. }
  361. return 0;
  362. }
  363. static int form_is_control(unsigned int node);
  364. static struct form_state *form_get(unsigned int node, int create)
  365. {
  366. struct form_state *slot = 0;
  367. unsigned int i;
  368. for (i = 0; i < FORM_MAX; i++) {
  369. if (form_states[i].used) {
  370. if (form_states[i].node == node)
  371. return &form_states[i];
  372. } else if (!slot) {
  373. slot = &form_states[i];
  374. }
  375. }
  376. if (create && !slot) {
  377. /* Full: a client-side router (Docusaurus' React Router)
  378. * replaces page content without a navigation, so slots of
  379. * controls that left the document pile up until no new
  380. * control can be drawn or focused.
  381. * Reuse those first, then slots of nodes that are no longer
  382. * controls. */
  383. for (i = 0; i < FORM_MAX && !slot; i++)
  384. if (form_states[i].node != form_focus &&
  385. br_node_detached(&doc, form_states[i].node))
  386. slot = &form_states[i];
  387. for (i = 0; i < FORM_MAX && !slot; i++)
  388. if (form_states[i].node != form_focus &&
  389. !form_is_control(form_states[i].node))
  390. slot = &form_states[i];
  391. }
  392. if (!create || !slot)
  393. return 0;
  394. slot->node = node;
  395. slot->len = 0;
  396. slot->caret = 0;
  397. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  398. slot->selected = form_option_selected(node);
  399. slot->used = 1;
  400. {
  401. unsigned int n = 0;
  402. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  403. n = br_text_content(&doc, node, slot->value,
  404. FORM_VALUE_MAX + 1);
  405. } else {
  406. const char *v = br_value(&doc, node);
  407. if (v) {
  408. n = s_len(v);
  409. if (n > FORM_VALUE_MAX)
  410. n = FORM_VALUE_MAX;
  411. for (unsigned int j = 0; j < n; j++)
  412. slot->value[j] = v[j];
  413. }
  414. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  415. n = br_text_content(&doc, node, slot->value,
  416. FORM_VALUE_MAX + 1);
  417. }
  418. if (n > FORM_VALUE_MAX)
  419. n = FORM_VALUE_MAX;
  420. slot->value[n] = '\0';
  421. slot->len = (unsigned char)n;
  422. slot->caret = (unsigned char)n;
  423. }
  424. return slot;
  425. }
  426. static void form_reset_state(void)
  427. {
  428. unsigned int i;
  429. for (i = 0; i < FORM_MAX; i++)
  430. form_states[i].used = 0;
  431. form_focus = 0;
  432. }
  433. /* A <button> with element content (an icon <svg>/<img>, a <span> label)
  434. * is laid out like a normal element so that content shows; only a text or
  435. * empty button is drawn as a native control. Clicks still reach it
  436. * through the box hit test. */
  437. static int button_has_elements(unsigned int node)
  438. {
  439. unsigned int c;
  440. if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
  441. return 0;
  442. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  443. if (doc.nodes[c].type == BR_NODE_ELEM)
  444. return 1;
  445. /* An empty button whose icon is a ::before/::after box (Docusaurus'
  446. * sidebar caret) is laid out as an element so the box is drawn. */
  447. if (!doc.nodes[node].first && doc.npe_rules) {
  448. struct br_style st, ps;
  449. char buf[8];
  450. int pe;
  451. style_for_node(node, &st);
  452. for (pe = 1; pe <= 2; pe++)
  453. if (!br_pseudo(&doc, node, pe, &st, &ps, buf,
  454. sizeof(buf)) &&
  455. ps.content == BR_CONTENT_EMPTY &&
  456. ps.display != BR_DISPLAY_NONE)
  457. return 1;
  458. }
  459. return 0;
  460. }
  461. static int form_is_control(unsigned int node)
  462. {
  463. unsigned int tag;
  464. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  465. return 0;
  466. tag = doc.nodes[node].tag;
  467. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  468. tag == BR_TAG_SELECT ||
  469. (tag == BR_TAG_BUTTON && !button_has_elements(node));
  470. }
  471. #define HIT_MAX 96
  472. static struct hit hits[HIT_MAX];
  473. static int nhits;
  474. static unsigned short block_h[BR_MAX_NODES];
  475. /* Measure-pass top of each block, in the same document coordinates as
  476. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  477. * paint, so it cannot drive the lazy background loader). */
  478. static unsigned short block_top[BR_MAX_NODES];
  479. static char li_marker[BR_MAX_NODES][12];
  480. /* one connection object; the browser fetches one resource at a time */
  481. /* ---- tiny strings ---- */
  482. static unsigned int s_len(const char *s)
  483. {
  484. unsigned int n = 0;
  485. while (s && s[n])
  486. n++;
  487. return n;
  488. }
  489. static void s_copy(char *d, const char *s, unsigned int cap)
  490. {
  491. unsigned int i = 0;
  492. if (!cap)
  493. return;
  494. while (s && s[i] && i + 1 < cap) {
  495. d[i] = s[i];
  496. i++;
  497. }
  498. d[i] = '\0';
  499. }
  500. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  501. {
  502. while (s && *s && *n + 1 < cap)
  503. d[(*n)++] = *s++;
  504. d[*n] = '\0';
  505. }
  506. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  507. unsigned int cap)
  508. {
  509. char tmp[12];
  510. unsigned int i = 0, j;
  511. do {
  512. tmp[i++] = (char)('0' + v % 10);
  513. v /= 10;
  514. } while (v && i < sizeof(tmp));
  515. for (j = 0; j < i && *n + 1 < cap; j++)
  516. d[(*n)++] = tmp[i - 1 - j];
  517. d[*n] = '\0';
  518. }
  519. static int s_eq(const char *a, const char *b)
  520. {
  521. while (*a && *b) {
  522. if (*a != *b)
  523. return 0;
  524. a++;
  525. b++;
  526. }
  527. return *a == *b;
  528. }
  529. static int starts_with(const char *s, const char *p)
  530. {
  531. unsigned int i = 0;
  532. while (p[i]) {
  533. if (s[i] != p[i])
  534. return 0;
  535. i++;
  536. }
  537. return 1;
  538. }
  539. static int contains_ci(const char *s, const char *p)
  540. {
  541. unsigned int i, j;
  542. for (i = 0; s[i]; i++) {
  543. for (j = 0; p[j]; j++) {
  544. char a = s[i + j];
  545. if (a >= 'A' && a <= 'Z')
  546. a = (char)(a - 'A' + 'a');
  547. if (a != p[j])
  548. break;
  549. }
  550. if (!p[j])
  551. return 1;
  552. }
  553. return 0;
  554. }
  555. static char *trim(char *s)
  556. {
  557. unsigned int n;
  558. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  559. s++;
  560. n = s_len(s);
  561. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  562. s[n - 1] == '\r' || s[n - 1] == '\n'))
  563. s[--n] = '\0';
  564. return s;
  565. }
  566. /* ---- per-process heap ---- */
  567. static int heap_start(void)
  568. {
  569. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  570. if (!image_io_buf)
  571. return -1;
  572. page_backbuf = (unsigned short *)malloc(
  573. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  574. pagebuf_w = page_backbuf ? ui.w : 0;
  575. pagebuf_h = page_backbuf ? ui.h : 0;
  576. page_cache_valid = 0;
  577. return 0;
  578. }
  579. static void heap_clear(void)
  580. {
  581. memset(font_faces, 0, sizeof(font_faces));
  582. ngui_font_detach(&ui);
  583. svg_cache_clear();
  584. decode_arena = 0; /* lives in the page heap too */
  585. decode_arena_size = 0;
  586. heap_reset();
  587. /* The document arenas live in that heap; drop the stale pointers so
  588. * the next br_parse_plain() allocates fresh ones. */
  589. doc.nodes = 0;
  590. doc.text = 0;
  591. doc.attrs = 0;
  592. image_io_buf = 0;
  593. page_backbuf = 0;
  594. pagebuf_w = pagebuf_h = 0;
  595. page_cache_valid = 0;
  596. }
  597. static void browser_rules_alloc(void)
  598. {
  599. struct br_rule *rules;
  600. rules = (struct br_rule *)malloc(
  601. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  602. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  603. }
  604. /* ---- status ---- */
  605. static void set_status(const char *s, int err, unsigned int ttl_ms)
  606. {
  607. s_copy(status_text, s, sizeof(status_text));
  608. status_error = err;
  609. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  610. ngui_invalidate(&ui);
  611. }
  612. /* Update the status text without forcing a frame; the throttled image
  613. * repaint picks it up. Starting one helper per image used to invalidate the
  614. * whole page before every decode. */
  615. static void set_status_quiet(const char *s)
  616. {
  617. s_copy(status_text, s, sizeof(status_text));
  618. status_error = 0;
  619. status_until = 0;
  620. }
  621. /* ---- JavaScript ---- */
  622. static int resolve_link(const char *base, const char *href, char *out,
  623. unsigned int cap);
  624. static char js_last_status[BR_STATUS_MAX];
  625. static int js_last_error;
  626. static void js_host_status(const char *msg, int error)
  627. {
  628. s_copy(js_last_status, msg, sizeof(js_last_status));
  629. js_last_error = error;
  630. set_status(msg, error, 6000);
  631. }
  632. static void js_host_report(const char *msg)
  633. {
  634. u_puts("[js] ");
  635. u_puts(msg);
  636. u_putc('\n');
  637. s_copy(js_last_status, msg, sizeof(js_last_status));
  638. js_last_error = 1;
  639. set_status(msg, 1, 8000);
  640. }
  641. static void js_host_navigate(const char *url)
  642. {
  643. char resolved[BR_URL_MAX];
  644. if (!url || !url[0])
  645. return;
  646. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  647. return;
  648. s_copy(pending_url, resolved, sizeof(pending_url));
  649. pending_action |= ACT_NAV;
  650. cancel_fetch = 1;
  651. }
  652. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  653. * back/forward between fragments): the page URL, address bar and history
  654. * follow, nothing is reloaded. `push` adds a history entry. */
  655. static int page_set_fragment(const char *url, int push)
  656. {
  657. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  658. return -1;
  659. s_copy(page_url, url, sizeof(page_url));
  660. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  661. url_in.len = s_len(url_in.text);
  662. url_in.cursor = url_in.len;
  663. url_in.scroll = 0;
  664. if (push)
  665. history_push(page_url);
  666. ngui_invalidate(&ui);
  667. return 0;
  668. }
  669. static int js_host_set_hash(const char *url)
  670. {
  671. return page_set_fragment(url, 1);
  672. }
  673. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  674. * the page, so a hash router can react). */
  675. static int same_doc_fragment(const char *url)
  676. {
  677. unsigned int a = 0, b = 0;
  678. if (!js_browser_active() || !url)
  679. return 0;
  680. while (url[a] && url[a] != '#')
  681. a++;
  682. while (page_url[b] && page_url[b] != '#')
  683. b++;
  684. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  685. !s_eq(url, page_url);
  686. }
  687. static void js_host_changed(void)
  688. {
  689. /* Class/style/attribute mutations change computed styles, not just the
  690. * text: drop the per-node style cache before the next layout. */
  691. br_reset_styles(&doc);
  692. layout_valid = 0;
  693. /* Script-built content (Angular's ng-repeat cards) brings new images
  694. * and inline background styles: rescan once the main loop is idle. */
  695. preload_rescan = 1;
  696. ngui_invalidate(&ui);
  697. }
  698. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  699. {
  700. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  701. return 0;
  702. *x = layout_boxes[node].x - page_rect.x;
  703. *y = layout_boxes[node].y - page_rect.y;
  704. *w = layout_boxes[node].w;
  705. *h = layout_boxes[node].h;
  706. return 1;
  707. }
  708. static void form_copy_out(const char *s, char *buf, int cap)
  709. {
  710. int i = 0;
  711. if (!buf || cap <= 0)
  712. return;
  713. while (s && s[i] && i + 1 < cap) {
  714. buf[i] = s[i];
  715. i++;
  716. }
  717. buf[i] = '\0';
  718. }
  719. static int js_host_form_value(unsigned int node, char *buf, int cap)
  720. {
  721. struct form_state *fs;
  722. int kind;
  723. if (!form_is_control(node))
  724. return 0;
  725. kind = form_kind_of(node);
  726. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  727. return 0;
  728. if (kind == FORM_SELECT) {
  729. char opt[64] = "";
  730. unsigned int c, i = 0;
  731. fs = form_get(node, 1);
  732. if (!fs)
  733. return 0;
  734. form_option_text(node, fs->selected, opt, sizeof(opt));
  735. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  736. if (doc.nodes[c].type != BR_NODE_ELEM ||
  737. doc.nodes[c].tag != BR_TAG_OPTION)
  738. continue;
  739. if (i == fs->selected) {
  740. const char *v = br_value(&doc, c);
  741. if (v && v[0])
  742. form_copy_out(v, buf, cap);
  743. else
  744. form_copy_out(opt, buf, cap);
  745. return 1;
  746. }
  747. i++;
  748. }
  749. form_copy_out(opt, buf, cap);
  750. return 1;
  751. }
  752. fs = form_get(node, 1);
  753. if (!fs)
  754. return 0;
  755. form_copy_out(fs->value, buf, cap);
  756. return 1;
  757. }
  758. static int js_host_form_checked(unsigned int node)
  759. {
  760. struct form_state *fs;
  761. int kind;
  762. if (!form_is_control(node))
  763. return -1;
  764. kind = form_kind_of(node);
  765. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  766. return -1;
  767. fs = form_get(node, 1);
  768. return fs ? fs->checked : 0;
  769. }
  770. static int js_host_form_selected(unsigned int node)
  771. {
  772. struct form_state *fs;
  773. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  774. return -1;
  775. fs = form_get(node, 1);
  776. return fs ? fs->selected : 0;
  777. }
  778. static int js_host_form_set_value(unsigned int node, const char *value)
  779. {
  780. struct form_state *fs;
  781. unsigned int n;
  782. if (!form_is_control(node))
  783. return 0;
  784. fs = form_get(node, 1);
  785. if (!fs)
  786. return 0;
  787. n = s_len(value ? value : "");
  788. if (n > FORM_VALUE_MAX)
  789. n = FORM_VALUE_MAX;
  790. for (unsigned int i = 0; i < n; i++)
  791. fs->value[i] = value[i];
  792. fs->value[n] = '\0';
  793. fs->len = (unsigned char)n;
  794. fs->caret = (unsigned char)n;
  795. layout_valid = 0;
  796. ngui_invalidate(&ui);
  797. return 1;
  798. }
  799. static int js_host_form_set_checked(unsigned int node, int checked)
  800. {
  801. struct form_state *fs;
  802. int kind;
  803. if (!form_is_control(node))
  804. return 0;
  805. kind = form_kind_of(node);
  806. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  807. return 0;
  808. fs = form_get(node, 1);
  809. if (!fs)
  810. return 0;
  811. fs->checked = (unsigned char)(checked != 0);
  812. layout_valid = 0;
  813. ngui_invalidate(&ui);
  814. return 1;
  815. }
  816. static int js_host_form_set_selected(unsigned int node, int index)
  817. {
  818. struct form_state *fs;
  819. unsigned int n;
  820. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  821. return 0;
  822. fs = form_get(node, 1);
  823. if (!fs)
  824. return 0;
  825. n = form_option_count(node);
  826. if (index < 0)
  827. index = 0;
  828. if (n && (unsigned int)index >= n)
  829. index = (int)n - 1;
  830. fs->selected = (unsigned char)index;
  831. layout_valid = 0;
  832. ngui_invalidate(&ui);
  833. return 1;
  834. }
  835. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  836. {
  837. unsigned int i;
  838. int n = 0;
  839. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  840. doc.nodes[form].tag != BR_TAG_FORM)
  841. return 0;
  842. for (i = 0; i < doc.nnode && n < cap; i++) {
  843. struct br_node *nd = &doc.nodes[i];
  844. if (i == form || nd->type != BR_NODE_ELEM)
  845. continue;
  846. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  847. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  848. continue;
  849. if (!form_descendant(i, form))
  850. continue;
  851. out[n++] = i;
  852. }
  853. return n;
  854. }
  855. static int js_host_form_submit(unsigned int form)
  856. {
  857. form_submit_form(form, 0);
  858. return 1;
  859. }
  860. static int js_host_form_reset(unsigned int form)
  861. {
  862. form_reset_event(form);
  863. return 1;
  864. }
  865. static void css_computed_name(const char *p, char *out, int cap)
  866. {
  867. int n = 0;
  868. for (; p && *p && n + 2 < cap; p++) {
  869. char c = *p;
  870. if (c >= 'A' && c <= 'Z') {
  871. out[n++] = '-';
  872. c = (char)(c - 'A' + 'a');
  873. } else if (c == '_') {
  874. c = '-';
  875. } else if (c >= 'a' && c <= 'z') {
  876. /* keep */
  877. }
  878. out[n++] = c;
  879. }
  880. out[n] = '\0';
  881. if (!strcmp(out, "css-float"))
  882. strcpy(out, "float");
  883. }
  884. static void css_rgb(unsigned short c, char *buf, int cap)
  885. {
  886. int r = ((c >> 11) & 31) * 255 / 31;
  887. int g = ((c >> 5) & 63) * 255 / 63;
  888. int b = (c & 31) * 255 / 31;
  889. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  890. }
  891. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  892. int font_px)
  893. {
  894. if (unit == 4) {
  895. snprintf(buf, cap, "auto");
  896. } else if (unit == 0) {
  897. snprintf(buf, cap, "%dpx", raw);
  898. } else if (unit == 1) {
  899. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  900. } else if (unit == 2) {
  901. /* Chrome's getComputedStyle() reports used pixel values. */
  902. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  903. } else if (unit == 3) {
  904. snprintf(buf, cap, "%dpx",
  905. (int)br_root_font_px() * raw / 100);
  906. } else {
  907. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  908. raw / 100, raw % 100, px);
  909. }
  910. }
  911. static int js_host_computed(unsigned int node, const char *property,
  912. char *buf, int cap)
  913. {
  914. struct br_style st;
  915. char name[40];
  916. /* Node 0 is a real element when the page starts with <html>. */
  917. if (!buf || cap <= 0 || node >= doc.nnode ||
  918. (node == 0 && doc.nodes[0].type != BR_NODE_ELEM))
  919. return 0;
  920. buf[0] = '\0';
  921. css_computed_name(property, name, sizeof(name));
  922. style_for_node(node, &st);
  923. if (!strcmp(name, "display")) {
  924. const char *v = "inline";
  925. if (st.display == BR_DISPLAY_BLOCK)
  926. v = "block";
  927. else if (st.display == BR_DISPLAY_NONE)
  928. v = "none";
  929. else if (st.display == BR_DISPLAY_FLEX)
  930. v = "flex";
  931. else if (st.display == BR_DISPLAY_GRID)
  932. v = "grid";
  933. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  934. v = "inline-block";
  935. snprintf(buf, cap, "%s", v);
  936. } else if (!strcmp(name, "position")) {
  937. static const char *pos[] = {
  938. "static", "absolute", "fixed", "relative", "sticky"
  939. };
  940. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  941. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  942. int is_w = name[0] == 'w';
  943. int kind = is_w ? st.width_kind : st.height_kind;
  944. int val = is_w ? st.width : st.height;
  945. if (kind == 3) {
  946. if (is_w)
  947. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  948. st.width_calc_pct / 100,
  949. st.width_calc_pct % 100,
  950. st.width_calc_px);
  951. else
  952. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  953. st.height_calc_pct / 100,
  954. st.height_calc_pct % 100,
  955. st.height_calc_px);
  956. } else if (kind == 1) {
  957. snprintf(buf, cap, "%dpx", val);
  958. } else if (kind == 2) {
  959. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  960. } else {
  961. snprintf(buf, cap, "auto");
  962. }
  963. } else if (!strcmp(name, "color") ||
  964. !strcmp(name, "background-color")) {
  965. if (!strcmp(name, "background-color") && !st.has_bg)
  966. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  967. else
  968. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  969. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  970. int is_fill = name[0] == 'f';
  971. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  972. if (mode == BR_PAINT_COLOR)
  973. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  974. else if (mode == BR_PAINT_CURRENT)
  975. css_rgb(st.color, buf, cap);
  976. else if (mode == BR_PAINT_UNSET && is_fill)
  977. snprintf(buf, cap, "rgb(0, 0, 0)");
  978. else if (mode == BR_PAINT_URL)
  979. snprintf(buf, cap, "url()");
  980. else
  981. snprintf(buf, cap, "none");
  982. } else if (!strcmp(name, "font-size")) {
  983. snprintf(buf, cap, "%dpx", st.font_px);
  984. } else if (!strcmp(name, "font-weight")) {
  985. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  986. } else if (!strcmp(name, "font-style")) {
  987. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  988. } else if (!strcmp(name, "font-family")) {
  989. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  990. br_font_face_family(st.font_face)[0])
  991. snprintf(buf, cap, "%s",
  992. br_font_face_family(st.font_face));
  993. else
  994. snprintf(buf, cap, "%s",
  995. st.mono ? "monospace" : "sans-serif");
  996. } else if (!strcmp(name, "text-align")) {
  997. static const char *al[] = { "left", "center", "right", "justify" };
  998. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  999. } else if (!strcmp(name, "float")) {
  1000. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  1001. st.float_left == 2 ? "right" : "none");
  1002. } else if (!strcmp(name, "clear")) {
  1003. static const char *cl[] = { "none", "left", "right", "both" };
  1004. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  1005. } else if (!strcmp(name, "opacity")) {
  1006. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  1007. } else if (!strcmp(name, "visibility")) {
  1008. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  1009. } else if (!strcmp(name, "overflow")) {
  1010. snprintf(buf, cap, "%s",
  1011. st.overflow_hidden ? "hidden" : "visible");
  1012. } else if (!strcmp(name, "white-space")) {
  1013. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  1014. } else if (!strcmp(name, "text-transform")) {
  1015. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  1016. } else if (!strcmp(name, "box-sizing")) {
  1017. snprintf(buf, cap, "%s",
  1018. st.box_sizing ? "border-box" : "content-box");
  1019. } else if (!strcmp(name, "line-height")) {
  1020. if (st.line_h_px)
  1021. snprintf(buf, cap, "%dpx", st.line_h_px);
  1022. else if (st.line_h_pct)
  1023. snprintf(buf, cap, "%d%%", st.line_h_pct);
  1024. else
  1025. snprintf(buf, cap, "normal");
  1026. } else if (!strcmp(name, "z-index")) {
  1027. if (st.z_set)
  1028. snprintf(buf, cap, "%d", st.z_index);
  1029. else
  1030. snprintf(buf, cap, "auto");
  1031. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  1032. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  1033. int set = name[0] == 't' ? st.top_set :
  1034. name[0] == 'l' ? st.left_set :
  1035. name[0] == 'r' ? st.right_set : st.bottom_set;
  1036. int v = name[0] == 't' ? st.top :
  1037. name[0] == 'l' ? st.left :
  1038. name[0] == 'r' ? st.right : st.bottom;
  1039. if (set)
  1040. snprintf(buf, cap, "%dpx", v);
  1041. else
  1042. snprintf(buf, cap, "auto");
  1043. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  1044. !strcmp(name, "margin-bottom") ||
  1045. !strcmp(name, "margin-left") ||
  1046. !strcmp(name, "padding-top") ||
  1047. !strcmp(name, "padding-right") ||
  1048. !strcmp(name, "padding-bottom") ||
  1049. !strcmp(name, "padding-left")) {
  1050. int is_pad = name[0] == 'p';
  1051. int side = name[strlen(name) - 1] == 'p' ? 0 :
  1052. name[strlen(name) - 1] == 't' ? 1 :
  1053. name[strlen(name) - 1] == 'm' ? 2 : 3;
  1054. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  1055. if (!strcmp(name, "margin-right") ||
  1056. !strcmp(name, "padding-right"))
  1057. side = 1;
  1058. else if (!strcmp(name, "margin-bottom") ||
  1059. !strcmp(name, "padding-bottom"))
  1060. side = 2;
  1061. else if (!strcmp(name, "margin-left") ||
  1062. !strcmp(name, "padding-left"))
  1063. side = 3;
  1064. else
  1065. side = 0;
  1066. side += is_pad ? 4 : 0;
  1067. css_mp_value(buf, cap,
  1068. side == 0 ? st.mt : side == 1 ? st.mr :
  1069. side == 2 ? st.mb : side == 3 ? st.ml :
  1070. side == 4 ? st.pt : side == 5 ? st.pr :
  1071. side == 6 ? st.pb : st.pl,
  1072. st.mp_unit[side], st.mp_calc_px[side],
  1073. st.font_px);
  1074. } else if (!strcmp(name, "border-top-width") ||
  1075. !strcmp(name, "border-right-width") ||
  1076. !strcmp(name, "border-bottom-width") ||
  1077. !strcmp(name, "border-left-width")) {
  1078. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1079. name[7] == 'b' ? 2 : 3;
  1080. snprintf(buf, cap, "%dpx", st.border_w[side]);
  1081. } else if (!strcmp(name, "border-top-color") ||
  1082. !strcmp(name, "border-right-color") ||
  1083. !strcmp(name, "border-bottom-color") ||
  1084. !strcmp(name, "border-left-color")) {
  1085. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1086. name[7] == 'b' ? 2 : 3;
  1087. if (st.border_w[side] && !st.border_t[side])
  1088. css_rgb(st.border_c[side], buf, cap);
  1089. else
  1090. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1091. } else if (!strcmp(name, "background-image")) {
  1092. if (st.bg_image)
  1093. snprintf(buf, cap, "url(\"%s\")",
  1094. br_bg_image_url(st.bg_image - 1));
  1095. else
  1096. snprintf(buf, cap, "none");
  1097. } else if (!strcmp(name, "background-repeat")) {
  1098. static const char *rp[] = {
  1099. "repeat", "no-repeat", "repeat-x", "repeat-y"
  1100. };
  1101. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  1102. st.bg_repeat : 0]);
  1103. } else if (!strcmp(name, "background-position")) {
  1104. if (st.bg_pos_x_kind == 1)
  1105. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  1106. st.bg_pos_y);
  1107. else
  1108. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1109. st.bg_pos_y);
  1110. } else if (!strcmp(name, "background-size")) {
  1111. if (st.bg_size_kind == 3)
  1112. snprintf(buf, cap, "cover");
  1113. else if (st.bg_size_kind == 4)
  1114. snprintf(buf, cap, "contain");
  1115. else if (st.bg_size_kind == 1)
  1116. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1117. st.bg_size_h);
  1118. else if (st.bg_size_kind == 2)
  1119. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1120. st.bg_size_h);
  1121. else
  1122. snprintf(buf, cap, "auto");
  1123. } else if (!strcmp(name, "transform")) {
  1124. char tmp[128];
  1125. unsigned int n = 0;
  1126. if (!st.transform_set) {
  1127. snprintf(buf, cap, "none");
  1128. } else {
  1129. tmp[0] = '\0';
  1130. if (st.tx || st.ty) {
  1131. snprintf(tmp + n, sizeof(tmp) - n,
  1132. "translate(%dpx, %dpx)", st.tx, st.ty);
  1133. n = (unsigned int)strlen(tmp);
  1134. }
  1135. if (st.transform_scale) {
  1136. snprintf(tmp + n, sizeof(tmp) - n,
  1137. "%sscale(%d.%02d, %d.%02d)",
  1138. n ? " " : "", st.scale_x / 100,
  1139. st.scale_x % 100, st.scale_y / 100,
  1140. st.scale_y % 100);
  1141. n = (unsigned int)strlen(tmp);
  1142. if (st.rotate_x100) {
  1143. snprintf(tmp + n, sizeof(tmp) - n,
  1144. " rotate(%d.%02ddeg)",
  1145. st.rotate_x100 / 100,
  1146. st.rotate_x100 % 100);
  1147. }
  1148. } else if (st.rotate_x100) {
  1149. snprintf(tmp + n, sizeof(tmp) - n,
  1150. "%srotate(%d.%02ddeg)",
  1151. n ? " " : "", st.rotate_x100 / 100,
  1152. st.rotate_x100 % 100);
  1153. }
  1154. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1155. }
  1156. } else {
  1157. return 0;
  1158. }
  1159. return buf[0] != '\0';
  1160. }
  1161. static int js_host_click(unsigned int node)
  1162. {
  1163. char url[BR_URL_MAX];
  1164. const char *href;
  1165. if (node >= doc.nnode)
  1166. return 0;
  1167. if (form_is_control(node)) {
  1168. form_click(node); /* dispatches its own click event */
  1169. return 1;
  1170. }
  1171. /* element.click() fires a bubbling, cancelable click before the
  1172. * default action, like a real click (delegated list handlers). */
  1173. if (!js_browser_event(node, "click", 1, 1))
  1174. return 1;
  1175. if (link_fragment_nav(node))
  1176. return 1;
  1177. href = br_href(&doc, node);
  1178. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1179. return 0;
  1180. s_copy(pending_url, url, sizeof(pending_url));
  1181. pending_action |= ACT_NAV;
  1182. cancel_fetch = 1;
  1183. ngui_invalidate(&ui);
  1184. return 1;
  1185. }
  1186. static int fetch_script_text(const char *url, unsigned char **out,
  1187. unsigned int *outlen, char *err,
  1188. unsigned int errcap);
  1189. struct fetch_worker;
  1190. static struct fetch_worker *fetch_worker_alloc(void);
  1191. static void fetch_worker_release(struct fetch_worker *w);
  1192. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1193. unsigned int cap, const char *post,
  1194. unsigned int post_len, unsigned int node,
  1195. int bg, char *err, unsigned int errcap);
  1196. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1197. unsigned int errcap);
  1198. static int fetch_worker_read_body(struct fetch_worker *w,
  1199. unsigned char *plain,
  1200. unsigned int plaincap,
  1201. unsigned char *comp,
  1202. unsigned int compcap,
  1203. int *truncated, char *err,
  1204. unsigned int errcap);
  1205. static void fetch_workers_stop_all(void);
  1206. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1207. unsigned int cap, const char *method,
  1208. const char *ctype, const char *post,
  1209. unsigned int post_len, unsigned int node,
  1210. int bg, unsigned int dec_w,
  1211. unsigned int dec_h, char *err,
  1212. unsigned int errcap);
  1213. static int script_cache_has(const char *url);
  1214. static void script_cache_put(const char *url, const unsigned char *data,
  1215. unsigned int len);
  1216. static unsigned int script_cache_hash(const char *s);
  1217. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1218. unsigned int errcap);
  1219. static void fetch_workers_cancel_busy(void);
  1220. static void worker_wait_ui(void);
  1221. static int fetch_worker_status(const struct fetch_worker *w);
  1222. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1223. * module load: the wait must not pump input, or a click would dispatch DOM
  1224. * events into the middle of the running script. */
  1225. static int fetch_wait_passive;
  1226. static void script_error(const char *what, const char *url, const char *why)
  1227. {
  1228. char msg[192];
  1229. unsigned int n = 0;
  1230. s_append(msg, &n, what, sizeof(msg));
  1231. if (url && url[0]) {
  1232. s_append(msg, &n, " ", sizeof(msg));
  1233. s_append(msg, &n, url, sizeof(msg));
  1234. }
  1235. if (why && why[0]) {
  1236. s_append(msg, &n, ": ", sizeof(msg));
  1237. s_append(msg, &n, why, sizeof(msg));
  1238. }
  1239. js_host_report(msg);
  1240. }
  1241. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1242. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1243. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1244. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1245. #define JS_HTTP_POST_MAX (16u * 1024u)
  1246. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1247. static int js_worker_http(const char *method, const char *url,
  1248. const char *ctype, const char *body,
  1249. unsigned int body_len, struct js_http_resp *r,
  1250. char *err, int errcap);
  1251. static int js_host_http(const char *method, const char *url,
  1252. const char *ctype, const char *body,
  1253. unsigned int body_len, struct js_http_resp *r,
  1254. char *err, int errcap)
  1255. {
  1256. if (pending_action) {
  1257. s_copy(err, "page is navigating", (unsigned int)errcap);
  1258. return -1;
  1259. }
  1260. if (url[0] == '/') {
  1261. /* Local file: GET only. */
  1262. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1263. int rv;
  1264. if (!buf) {
  1265. s_copy(err, "out of memory", (unsigned int)errcap);
  1266. return -1;
  1267. }
  1268. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1269. (int)JS_HTTP_MAX);
  1270. r->status = rv < 0 ? 404 : 200;
  1271. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1272. buf[r->len] = '\0';
  1273. r->body = (char *)buf;
  1274. s_copy(r->url, url, sizeof(r->url));
  1275. if (contains_ci(url, ".json"))
  1276. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1277. return 0;
  1278. }
  1279. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1280. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1281. return -1;
  1282. }
  1283. if (body_len > JS_HTTP_POST_MAX) {
  1284. s_copy(err, "request body too large", (unsigned int)errcap);
  1285. return -1;
  1286. }
  1287. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1288. errcap);
  1289. }
  1290. /* Module source for the engine's loader: the boot script cache first, then
  1291. * one blocking fetch with input pumping disabled (the loader runs inside
  1292. * JavaScript). */
  1293. static char *js_host_load_script(const char *url, unsigned int *len)
  1294. {
  1295. unsigned char *data = 0;
  1296. char err[64];
  1297. int rv;
  1298. fetch_wait_passive++;
  1299. set_status("Loading module...", 0, 0);
  1300. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1301. fetch_wait_passive--;
  1302. if (rv != 0) {
  1303. script_error("Cannot load module", url,
  1304. rv == FETCH_ABORT ? "navigation" : err);
  1305. return 0;
  1306. }
  1307. return (char *)data;
  1308. }
  1309. /* Web Storage lives in /share, outside the page heap that every navigation
  1310. * resets: localStorage per origin for the boot, sessionStorage per origin
  1311. * and browser window. */
  1312. #define JS_ORIGIN_MAX 160
  1313. /* scheme://host[:port] of the page (a local page's whole path). */
  1314. static void js_page_origin(char *origin, unsigned int cap)
  1315. {
  1316. unsigned int i = 0, slashes = 0;
  1317. while (page_url[i] && i + 1 < cap) {
  1318. if (page_url[i] == '/' && ++slashes == 3)
  1319. break;
  1320. origin[i] = page_url[i];
  1321. i++;
  1322. }
  1323. origin[i] = '\0';
  1324. }
  1325. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1326. {
  1327. unsigned int n = 0;
  1328. s_append(out, &n, "/share/bls", cap);
  1329. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1330. }
  1331. static void js_storage_path(int kind, char *out, unsigned int cap)
  1332. {
  1333. char origin[JS_ORIGIN_MAX];
  1334. unsigned int n = 0;
  1335. js_page_origin(origin, sizeof(origin));
  1336. if (!kind) {
  1337. js_origin_path(origin, out, cap);
  1338. return;
  1339. }
  1340. s_append(out, &n, "/share/bss", cap);
  1341. if (kind) {
  1342. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1343. s_append(out, &n, "-", cap);
  1344. }
  1345. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1346. }
  1347. static void persist_mark_origin(const char *origin);
  1348. static int persist_store_lookup(const char *origin, char *out, int cap);
  1349. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1350. {
  1351. char path[48], origin[JS_ORIGIN_MAX];
  1352. int rv;
  1353. js_storage_path(kind, path, sizeof(path));
  1354. if (set) {
  1355. if (kind) {
  1356. if (!set[0] || !strcmp(set, "{}")) {
  1357. u_syscall1(SYS_UNLINK, (int)path);
  1358. return 0;
  1359. }
  1360. } else {
  1361. /* localStorage keeps an explicit "{}" rather than no
  1362. * file: a missing /share file means "not loaded from
  1363. * /data yet", and a cleared store must not come back
  1364. * from the disk copy before it is flushed. */
  1365. if (!set[0])
  1366. set = "{}";
  1367. js_page_origin(origin, sizeof(origin));
  1368. persist_mark_origin(origin);
  1369. }
  1370. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1371. (int)strlen(set)) < 0 ? -1 : 0;
  1372. }
  1373. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1374. if (rv < 0 && !kind) {
  1375. /* First use this boot: the persistent copy on /data. */
  1376. js_page_origin(origin, sizeof(origin));
  1377. rv = persist_store_lookup(origin, out, cap);
  1378. if (rv >= 0)
  1379. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1380. }
  1381. if (rv < 0)
  1382. return -1;
  1383. out[rv] = '\0';
  1384. return rv;
  1385. }
  1386. /* ---- persistence on /data ----
  1387. *
  1388. * /share is the working copy (RAM, shared by every helper and window); the
  1389. * installed disk's /data volume keeps the cookie jar and localStorage
  1390. * across reboots when it is mounted. The browser owns the disk copies: at
  1391. * start it restores the jar into /share, and its main loop writes back
  1392. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1393. * setItem updates costs one FAT write. The helpers only touch /share (they
  1394. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1395. * /data mount every disk access simply fails. Both files are plaintext
  1396. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1397. #define PERSIST_MS 3000u
  1398. #define SHARE_COOKIES "/share/bcookies"
  1399. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1400. #define DATA_STORE "/data/BSTORE.DAT"
  1401. #define DATA_STORE_MAGIC "NBLS1\n"
  1402. #define DATA_STORE_MAX (192u * 1024u)
  1403. #define PERSIST_DIRTY_MAX 8
  1404. static unsigned int persist_due;
  1405. static unsigned int cookie_sum_saved;
  1406. static int cookie_sum_valid;
  1407. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1408. static int persist_ndirty;
  1409. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1410. {
  1411. unsigned int h = 2166136261u, i;
  1412. for (i = 0; i < n; i++)
  1413. h = (h ^ p[i]) * 16777619u;
  1414. return h;
  1415. }
  1416. /* Called once at startup, before any helper runs. */
  1417. static void persist_restore(void)
  1418. {
  1419. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1420. int n;
  1421. if (!jar)
  1422. return;
  1423. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1424. (int)sizeof(struct uhttp_jar));
  1425. if (n != (int)sizeof(struct uhttp_jar)) {
  1426. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1427. (int)sizeof(struct uhttp_jar));
  1428. if (n == (int)sizeof(struct uhttp_jar)) {
  1429. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1430. (int)jar, n);
  1431. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1432. cookie_sum_valid = 1;
  1433. }
  1434. }
  1435. free(jar);
  1436. persist_due = u_ticks_ms() + PERSIST_MS;
  1437. }
  1438. static void persist_mark_origin(const char *origin)
  1439. {
  1440. int i;
  1441. for (i = 0; i < persist_ndirty; i++)
  1442. if (s_eq(persist_dirty[i], origin))
  1443. return;
  1444. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1445. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1446. }
  1447. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1448. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1449. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1450. unsigned int *o_off, unsigned int *o_len,
  1451. unsigned int *d_off, unsigned int *d_len,
  1452. unsigned int *rec_end)
  1453. {
  1454. unsigned int p = *pos, v = 0;
  1455. if (p >= len)
  1456. return 0;
  1457. *o_off = p;
  1458. while (p < len && buf[p] != '\n')
  1459. p++;
  1460. if (p >= len)
  1461. return 0;
  1462. *o_len = p - *o_off;
  1463. p++;
  1464. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1465. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1466. if (p >= len || buf[p] != '\n')
  1467. return 0;
  1468. p++;
  1469. if (v > len - p)
  1470. return 0;
  1471. *d_off = p;
  1472. *d_len = v;
  1473. p += v;
  1474. if (p < len && buf[p] == '\n')
  1475. p++;
  1476. *rec_end = p;
  1477. *pos = p;
  1478. return 1;
  1479. }
  1480. static int store_load(char **out)
  1481. {
  1482. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1483. int n;
  1484. *out = buf;
  1485. if (!buf)
  1486. return -1;
  1487. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1488. (int)DATA_STORE_MAX);
  1489. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1490. !starts_with(buf, DATA_STORE_MAGIC))
  1491. return 0;
  1492. return n;
  1493. }
  1494. static int persist_store_lookup(const char *origin, char *out, int cap)
  1495. {
  1496. char *buf;
  1497. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1498. unsigned int olen = s_len(origin);
  1499. int n = store_load(&buf), rv = -1;
  1500. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1501. &dl, &e)) {
  1502. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1503. if ((int)dl < cap) {
  1504. memcpy(out, buf + d, dl);
  1505. out[dl] = '\0';
  1506. rv = (int)dl;
  1507. }
  1508. break;
  1509. }
  1510. }
  1511. free(buf);
  1512. return rv;
  1513. }
  1514. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1515. static void persist_store_flush(void)
  1516. {
  1517. char *old, *nb, path[48];
  1518. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1519. int n = store_load(&old), i, w;
  1520. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1521. if (n < 0 || !nb) {
  1522. free(old);
  1523. free(nb);
  1524. return;
  1525. }
  1526. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1527. /* Untouched origins first, in their old order. */
  1528. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1529. &dl, &e)) {
  1530. int dirty = 0;
  1531. for (i = 0; i < persist_ndirty; i++)
  1532. if (s_len(persist_dirty[i]) == ol &&
  1533. !memcmp(persist_dirty[i], old + oo, ol))
  1534. dirty = 1;
  1535. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1536. continue;
  1537. memcpy(nb + nn, old + oo, e - oo);
  1538. nn += e - oo;
  1539. }
  1540. /* Then the changed ones (an emptied store is dropped). */
  1541. for (i = 0; i < persist_ndirty; i++) {
  1542. char num[12];
  1543. unsigned int k = 0;
  1544. js_origin_path(persist_dirty[i], path, sizeof(path));
  1545. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1546. (int)DATA_STORE_MAX);
  1547. if (w <= 2) /* missing or "{}" */
  1548. continue;
  1549. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1550. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1551. DATA_STORE_MAX) {
  1552. set_status("Saved site data is full; a site's "
  1553. "localStorage was not saved", 1, 6000);
  1554. continue;
  1555. }
  1556. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1557. nb[nn++] = '\n';
  1558. s_append(nb, &nn, num, DATA_STORE_MAX);
  1559. nb[nn++] = '\n';
  1560. memcpy(nb + nn, old, (unsigned int)w);
  1561. nn += (unsigned int)w;
  1562. nb[nn++] = '\n';
  1563. }
  1564. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1565. persist_ndirty = 0;
  1566. free(old);
  1567. free(nb);
  1568. }
  1569. static void persist_cookies_flush(void)
  1570. {
  1571. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1572. unsigned int sum;
  1573. int n;
  1574. if (!jar)
  1575. return;
  1576. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1577. (int)sizeof(struct uhttp_jar));
  1578. if (n == (int)sizeof(struct uhttp_jar)) {
  1579. sum = persist_sum(jar, (unsigned int)n);
  1580. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1581. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1582. (int)jar, n) >= 0) {
  1583. cookie_sum_saved = sum;
  1584. cookie_sum_valid = 1;
  1585. }
  1586. }
  1587. }
  1588. free(jar);
  1589. }
  1590. /* ---- visit history (URL-bar autocomplete) ----
  1591. *
  1592. * Every page that finishes loading is recorded with its title, a visit
  1593. * count and a stamp: a counter that only grows and travels with the file,
  1594. * so it orders visits across windows and boots without a wall clock. The
  1595. * table lives in BSS, because the page heap is reset on every navigation.
  1596. * The boot's browser windows share it through /share/bhist (rewritten on
  1597. * every visit) and it is persisted to /data/BHIST.DAT from persist_tick()
  1598. * at most every PERSIST_MS, like the cookie jar. A save re-reads
  1599. * /share/bhist and merges it first, so two windows add to one history
  1600. * instead of overwriting each other. File format: "NBHIST1\n", then
  1601. * "<visits> <stamp> <url>\t<title>\n" per entry. Plaintext, like the
  1602. * other browser state on /data. */
  1603. #define HIST_MAX 128
  1604. #define HIST_URL_MAX 512
  1605. #define HIST_FILE_MAX (HIST_MAX * (HIST_URL_MAX + BR_TITLE_MAX + 24) + 16)
  1606. #define HIST_MAGIC "NBHIST1\n"
  1607. #define SHARE_HIST "/share/bhist"
  1608. #define DATA_HIST "/data/BHIST.DAT"
  1609. #define HIST_FORGET_MAX 16
  1610. struct hist_ent {
  1611. unsigned int visits;
  1612. unsigned int stamp;
  1613. char url[HIST_URL_MAX];
  1614. char title[BR_TITLE_MAX];
  1615. };
  1616. static struct hist_ent hist_tab[HIST_MAX];
  1617. static int hist_n;
  1618. static int hist_share_dirty, hist_data_dirty;
  1619. /* URLs removed in this process: a merge must not bring them back. */
  1620. static unsigned int hist_forgot[HIST_FORGET_MAX];
  1621. static int hist_nforgot;
  1622. static unsigned int hist_hash(const char *s)
  1623. {
  1624. return persist_sum((const unsigned char *)s, s_len(s));
  1625. }
  1626. static int hist_is_forgotten(const char *url)
  1627. {
  1628. unsigned int h = hist_hash(url);
  1629. int i;
  1630. for (i = 0; i < hist_nforgot; i++)
  1631. if (hist_forgot[i] == h)
  1632. return 1;
  1633. return 0;
  1634. }
  1635. static int hist_find(const char *url)
  1636. {
  1637. int i;
  1638. for (i = 0; i < hist_n; i++)
  1639. if (s_eq(hist_tab[i].url, url))
  1640. return i;
  1641. return -1;
  1642. }
  1643. static unsigned int hist_next_stamp(void)
  1644. {
  1645. unsigned int m = 0;
  1646. int i;
  1647. for (i = 0; i < hist_n; i++)
  1648. if (hist_tab[i].stamp > m)
  1649. m = hist_tab[i].stamp;
  1650. return m + 1;
  1651. }
  1652. /* Copy a title, turning tabs/newlines (the file separators) into spaces. */
  1653. static void hist_copy_title(char *d, const char *s, unsigned int n)
  1654. {
  1655. unsigned int i;
  1656. for (i = 0; i + 1 < BR_TITLE_MAX && i < n && s[i]; i++)
  1657. d[i] = (unsigned char)s[i] < 0x20 ? ' ' : s[i];
  1658. d[i] = '\0';
  1659. }
  1660. /* Insert or update an entry; the newer stamp wins the title, the larger
  1661. * visit count is kept. A full table evicts the least recent entry, unless
  1662. * the new one is older still. Returns NULL when nothing was stored. */
  1663. static struct hist_ent *hist_put(const char *url, const char *title,
  1664. unsigned int visits, unsigned int stamp)
  1665. {
  1666. struct hist_ent *e;
  1667. int i = hist_find(url);
  1668. if (i < 0) {
  1669. if (hist_n < HIST_MAX) {
  1670. i = hist_n++;
  1671. } else {
  1672. int j;
  1673. i = 0;
  1674. for (j = 1; j < hist_n; j++)
  1675. if (hist_tab[j].stamp < hist_tab[i].stamp)
  1676. i = j;
  1677. if (hist_tab[i].stamp >= stamp)
  1678. return 0;
  1679. }
  1680. e = &hist_tab[i];
  1681. e->visits = 0;
  1682. e->stamp = 0;
  1683. e->title[0] = '\0';
  1684. s_copy(e->url, url, sizeof(e->url));
  1685. }
  1686. e = &hist_tab[i];
  1687. if (visits > e->visits)
  1688. e->visits = visits;
  1689. if (stamp >= e->stamp) {
  1690. e->stamp = stamp;
  1691. if (title && title[0])
  1692. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1693. } else if (!e->title[0] && title) {
  1694. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1695. }
  1696. return e;
  1697. }
  1698. static unsigned int hist_parse_dec(const char *b, int n, int *pos)
  1699. {
  1700. unsigned int v = 0;
  1701. while (*pos < n && b[*pos] >= '0' && b[*pos] <= '9')
  1702. v = v * 10 + (unsigned int)(b[(*pos)++] - '0');
  1703. return v;
  1704. }
  1705. static void hist_merge_buf(const char *b, int n)
  1706. {
  1707. int pos = (int)s_len(HIST_MAGIC);
  1708. char url[HIST_URL_MAX], title[BR_TITLE_MAX];
  1709. if (n < pos || memcmp(b, HIST_MAGIC, (unsigned int)pos))
  1710. return;
  1711. while (pos < n) {
  1712. unsigned int visits, stamp, ul = 0;
  1713. int t0, t1;
  1714. visits = hist_parse_dec(b, n, &pos);
  1715. if (pos < n && b[pos] == ' ')
  1716. pos++;
  1717. stamp = hist_parse_dec(b, n, &pos);
  1718. if (pos < n && b[pos] == ' ')
  1719. pos++;
  1720. while (pos < n && b[pos] != '\t' && b[pos] != '\n') {
  1721. if (ul + 1 < sizeof(url))
  1722. url[ul++] = b[pos];
  1723. pos++;
  1724. }
  1725. url[ul] = '\0';
  1726. t0 = t1 = pos < n && b[pos] == '\t' ? pos + 1 : pos;
  1727. while (t1 < n && b[t1] != '\n')
  1728. t1++;
  1729. pos = t1 + 1;
  1730. hist_copy_title(title, b + t0, (unsigned int)(t1 - t0));
  1731. if (ul && ul + 1 < sizeof(url) && !hist_is_forgotten(url))
  1732. hist_put(url, title, visits, stamp);
  1733. }
  1734. }
  1735. static int hist_serialize(char *b, unsigned int cap)
  1736. {
  1737. unsigned int n = 0;
  1738. int i;
  1739. s_append(b, &n, HIST_MAGIC, cap);
  1740. for (i = 0; i < hist_n; i++) {
  1741. struct hist_ent *e = &hist_tab[i];
  1742. if (n + s_len(e->url) + s_len(e->title) + 26 >= cap)
  1743. break;
  1744. s_append_dec(b, &n, e->visits, cap);
  1745. b[n++] = ' ';
  1746. s_append_dec(b, &n, e->stamp, cap);
  1747. b[n++] = ' ';
  1748. s_append(b, &n, e->url, cap);
  1749. b[n++] = '\t';
  1750. s_append(b, &n, e->title, cap);
  1751. b[n++] = '\n';
  1752. }
  1753. return (int)n;
  1754. }
  1755. /* Merge /share/bhist, then write it back (and /data when asked). */
  1756. static void hist_sync(int to_data)
  1757. {
  1758. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1759. int n;
  1760. if (!b)
  1761. return;
  1762. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1763. (int)HIST_FILE_MAX);
  1764. if (n > 0)
  1765. hist_merge_buf(b, n);
  1766. n = hist_serialize(b, HIST_FILE_MAX);
  1767. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1768. hist_share_dirty = 0;
  1769. if (to_data) {
  1770. /* No /data mount: the write fails, and there is nothing to
  1771. * retry until the next visit. */
  1772. u_syscall3(SYS_WRITE_FILE, (int)DATA_HIST, (int)b, n);
  1773. hist_data_dirty = 0;
  1774. }
  1775. free(b);
  1776. }
  1777. /* Startup: the boot's shared copy, else the saved one from /data. */
  1778. static void hist_load(void)
  1779. {
  1780. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1781. int n;
  1782. if (!b)
  1783. return;
  1784. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1785. (int)HIST_FILE_MAX);
  1786. if (n <= 0) {
  1787. n = u_syscall3(SYS_READ_FILE, (int)DATA_HIST, (int)b,
  1788. (int)HIST_FILE_MAX);
  1789. if (n > 0)
  1790. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1791. }
  1792. if (n > 0)
  1793. hist_merge_buf(b, n);
  1794. free(b);
  1795. }
  1796. static void hist_visit(const char *url, const char *title)
  1797. {
  1798. struct hist_ent *e;
  1799. unsigned int i;
  1800. if (!url[0] || starts_with(url, "about:") ||
  1801. s_len(url) >= HIST_URL_MAX)
  1802. return;
  1803. for (i = 0; url[i]; i++)
  1804. if ((unsigned char)url[i] < 0x20)
  1805. return;
  1806. e = hist_put(url, title, 0, hist_next_stamp());
  1807. if (!e)
  1808. return;
  1809. e->visits++;
  1810. hist_data_dirty = 1;
  1811. hist_sync(0);
  1812. }
  1813. static void hist_forget(int i)
  1814. {
  1815. if (i < 0 || i >= hist_n)
  1816. return;
  1817. if (hist_nforgot < HIST_FORGET_MAX)
  1818. hist_forgot[hist_nforgot++] = hist_hash(hist_tab[i].url);
  1819. hist_n--;
  1820. for (; i < hist_n; i++)
  1821. hist_tab[i] = hist_tab[i + 1];
  1822. hist_data_dirty = 1;
  1823. hist_sync(0);
  1824. }
  1825. static void hist_tick(void)
  1826. {
  1827. if (hist_share_dirty || hist_data_dirty)
  1828. hist_sync(hist_data_dirty);
  1829. }
  1830. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1831. static void persist_tick(void)
  1832. {
  1833. unsigned int now = u_ticks_ms();
  1834. if ((int)(now - persist_due) < 0)
  1835. return;
  1836. persist_due = now + PERSIST_MS;
  1837. persist_cookies_flush();
  1838. if (persist_ndirty)
  1839. persist_store_flush();
  1840. hist_tick();
  1841. }
  1842. /* <link rel="modulepreload">: download the page's module graph on all
  1843. * helpers at once into the boot script cache, before any script runs. The
  1844. * engine's module loader is sequential (one blocking fetch per import), so
  1845. * without this a Vite app with a dozen chunks pays every round trip in a
  1846. * row. Failures are ignored; the loader fetches what is missing. */
  1847. #define MODULE_PRELOAD_MAX 24
  1848. static void prefetch_module_preloads(void)
  1849. {
  1850. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1851. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1852. unsigned int count = 0, next = 0, done = 0, i;
  1853. char err[64];
  1854. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1855. struct br_node *nd = &doc.nodes[i];
  1856. const char *rel, *href;
  1857. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1858. continue;
  1859. rel = br_rel(&doc, i);
  1860. href = br_href(&doc, i);
  1861. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1862. continue;
  1863. if (resolve_link(page_url, href, urls[count],
  1864. sizeof(urls[count])) != 0 ||
  1865. urls[count][0] == '/' || script_cache_has(urls[count]))
  1866. continue;
  1867. slot[count++] = 0;
  1868. }
  1869. if (!count)
  1870. return;
  1871. set_status("Loading modules...", 0, 0);
  1872. while (done < count) {
  1873. struct fetch_worker *w;
  1874. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1875. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1876. 0, 0, 0, err,
  1877. sizeof(err)) != 0) {
  1878. fetch_worker_release(w);
  1879. done++;
  1880. } else {
  1881. slot[next] = w;
  1882. }
  1883. next++;
  1884. }
  1885. worker_wait_ui();
  1886. if (cancel_fetch || pending_action) {
  1887. fetch_workers_cancel_busy();
  1888. return;
  1889. }
  1890. for (i = 0; i < next; i++) {
  1891. unsigned char *body;
  1892. int rv, tr = 0;
  1893. if (!slot[i])
  1894. continue;
  1895. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1896. if (rv == 0)
  1897. continue;
  1898. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1899. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1900. if (body) {
  1901. rv = fetch_worker_read_body(slot[i], body,
  1902. BR_SCRIPT_MAX, image_io_buf,
  1903. BR_PAGE_COMP_MAX, &tr, err,
  1904. sizeof(err));
  1905. if (rv > 0 && !tr)
  1906. script_cache_put(urls[i], body,
  1907. (unsigned int)rv);
  1908. free(body);
  1909. }
  1910. fetch_worker_release(slot[i]);
  1911. slot[i] = 0;
  1912. done++;
  1913. }
  1914. u_sleep_ms(10);
  1915. }
  1916. }
  1917. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1918. * submitted to helper workers ahead of time, but scripts still execute in
  1919. * document order. */
  1920. #define SCRIPT_INLINE 0
  1921. #define SCRIPT_LOCAL 1
  1922. #define SCRIPT_REMOTE 2
  1923. #define SCRIPT_ERROR 3
  1924. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1925. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1926. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1927. static void script_submit_window(unsigned int *next, char *err,
  1928. unsigned int errcap)
  1929. {
  1930. while (*next < doc.nscripts) {
  1931. struct fetch_worker *w;
  1932. if (script_kind[*next] != SCRIPT_REMOTE) {
  1933. (*next)++;
  1934. continue;
  1935. }
  1936. w = fetch_worker_alloc();
  1937. if (!w)
  1938. return;
  1939. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1940. 0, 0, 0, 0, err, errcap) != 0) {
  1941. fetch_worker_release(w);
  1942. script_kind[*next] = SCRIPT_ERROR;
  1943. (*next)++;
  1944. continue;
  1945. }
  1946. script_slot[*next] = w;
  1947. (*next)++;
  1948. }
  1949. }
  1950. /* Run the page's scripts in document order. External bodies are prefetched
  1951. * in parallel so downloading script N+1 overlaps executing script N; inline
  1952. * bodies are copied because the engine needs NUL-terminated text. */
  1953. static void run_page_scripts(void)
  1954. {
  1955. struct js_browser_host host;
  1956. unsigned int i, next = 0;
  1957. char err[64], ferr[64];
  1958. if (!doc.nscripts)
  1959. return;
  1960. host.status = js_host_status;
  1961. host.report = js_host_report;
  1962. host.navigate = js_host_navigate;
  1963. host.changed = js_host_changed;
  1964. host.rect = js_host_rect;
  1965. host.form_value = js_host_form_value;
  1966. host.form_checked = js_host_form_checked;
  1967. host.form_selected = js_host_form_selected;
  1968. host.form_set_value = js_host_form_set_value;
  1969. host.form_set_checked = js_host_form_set_checked;
  1970. host.form_set_selected = js_host_form_set_selected;
  1971. host.form_elements = js_host_form_elements;
  1972. host.form_submit = js_host_form_submit;
  1973. host.form_reset = js_host_form_reset;
  1974. host.click = js_host_click;
  1975. host.computed = js_host_computed;
  1976. host.http = js_host_http;
  1977. host.load_script = js_host_load_script;
  1978. host.storage = js_host_storage;
  1979. host.set_hash = js_host_set_hash;
  1980. host.page_url = page_url;
  1981. host.width = ui.w;
  1982. host.height = ui.h;
  1983. if (js_browser_start(&doc, &host) != 0) {
  1984. js_host_status("JavaScript: out of memory", 1);
  1985. return;
  1986. }
  1987. resize_sent_w = -1;
  1988. resize_pending = 0;
  1989. prefetch_module_preloads();
  1990. for (i = 0; i < doc.nscripts; i++) {
  1991. struct br_script *script = &doc.scripts[i];
  1992. const char *src_attr = script->src_off ?
  1993. doc.attrs + script->src_off : "";
  1994. script_slot[i] = 0;
  1995. if (!script->src_off) {
  1996. script_kind[i] = SCRIPT_INLINE;
  1997. continue;
  1998. }
  1999. if (!src_attr[0] ||
  2000. resolve_link(page_url, src_attr, script_urls[i],
  2001. sizeof(script_urls[i])) != 0) {
  2002. script_urls[i][0] = '\0';
  2003. script_kind[i] = SCRIPT_ERROR;
  2004. continue;
  2005. }
  2006. if (script_urls[i][0] == '/' ||
  2007. script_cache_has(script_urls[i]))
  2008. script_kind[i] = SCRIPT_LOCAL;
  2009. else
  2010. script_kind[i] = SCRIPT_REMOTE;
  2011. }
  2012. script_submit_window(&next, ferr, sizeof(ferr));
  2013. for (i = 0; i < doc.nscripts; i++) {
  2014. struct br_script *script = &doc.scripts[i];
  2015. /* document.currentScript for classic scripts (null for modules) */
  2016. js_browser_set_current_script(script->module ? 0 : script->node);
  2017. if (script_kind[i] == SCRIPT_INLINE) {
  2018. unsigned int off = script->off;
  2019. unsigned int len = script->len;
  2020. unsigned int k;
  2021. char *src = (char *)malloc(len + 1);
  2022. if (!src) {
  2023. js_host_status("JavaScript: out of memory", 1);
  2024. break;
  2025. }
  2026. for (k = 0; k < len; k++)
  2027. src[k] = doc.script_src[off + k];
  2028. src[len] = '\0';
  2029. if (script->module) {
  2030. /* A distinct module name per inline module
  2031. * (QuickJS registers modules by name); the
  2032. * fragment keeps relative imports resolving
  2033. * against the page. */
  2034. char mname[BR_URL_MAX + 16];
  2035. unsigned int mn = 0;
  2036. s_append(mname, &mn, page_url, sizeof(mname));
  2037. s_append(mname, &mn, "#module", sizeof(mname));
  2038. s_append_dec(mname, &mn, i, sizeof(mname));
  2039. js_browser_run_module(src, mname);
  2040. } else {
  2041. js_browser_run(src, page_url);
  2042. }
  2043. free(src);
  2044. } else if (script->src_off) {
  2045. const char *src_attr = doc.attrs + script->src_off;
  2046. if (script_kind[i] == SCRIPT_ERROR) {
  2047. script_error("Cannot load script", src_attr,
  2048. script_urls[i][0] ?
  2049. "network busy" :
  2050. "unsupported URL");
  2051. continue;
  2052. }
  2053. if (script_kind[i] == SCRIPT_LOCAL) {
  2054. unsigned char *data = 0;
  2055. unsigned int len = 0;
  2056. int rv;
  2057. set_status("Loading script...", 0, 0);
  2058. rv = fetch_script_text(script_urls[i], &data,
  2059. &len, err, sizeof(err));
  2060. if (rv == FETCH_ABORT)
  2061. break;
  2062. if (rv != 0) {
  2063. script_error("Cannot load script",
  2064. script_urls[i], err);
  2065. continue;
  2066. }
  2067. if (script->module)
  2068. js_browser_run_module(
  2069. (const char *)data,
  2070. script_urls[i]);
  2071. else
  2072. js_browser_run((const char *)data,
  2073. script_urls[i]);
  2074. free(data);
  2075. } else {
  2076. struct fetch_worker *w = script_slot[i];
  2077. unsigned char *body = 0;
  2078. int tr = 0, rv;
  2079. if (!w) {
  2080. w = fetch_worker_alloc();
  2081. if (!w)
  2082. continue;
  2083. if (fetch_worker_submit(w,
  2084. script_urls[i],
  2085. BR_SCRIPT_MAX,
  2086. 0, 0, 0, 0, err,
  2087. sizeof(err)) != 0) {
  2088. fetch_worker_release(w);
  2089. script_kind[i] = SCRIPT_ERROR;
  2090. if (i == next)
  2091. next++;
  2092. continue;
  2093. }
  2094. script_slot[i] = w;
  2095. if (i == next)
  2096. next++;
  2097. }
  2098. set_status("Loading script...", 0, 0);
  2099. rv = fetch_worker_wait(w, err, sizeof(err));
  2100. if (rv == FETCH_ABORT) {
  2101. fetch_workers_stop_all();
  2102. break;
  2103. }
  2104. /* The body gets its own buffer (scripts are up
  2105. * to 2 MB); image_io_buf takes the gzip
  2106. * stream. */
  2107. body = rv == 0 ? (unsigned char *)malloc(
  2108. BR_SCRIPT_MAX + 1) : 0;
  2109. if (body)
  2110. rv = fetch_worker_read_body(w, body,
  2111. BR_SCRIPT_MAX, image_io_buf,
  2112. BR_PAGE_COMP_MAX, &tr, err,
  2113. sizeof(err));
  2114. else {
  2115. if (rv == 0)
  2116. s_copy(err, "out of memory",
  2117. sizeof(err));
  2118. rv = -1;
  2119. }
  2120. fetch_worker_release(w);
  2121. script_slot[i] = 0;
  2122. script_submit_window(&next, ferr, sizeof(ferr));
  2123. if (rv <= 0)
  2124. script_error("Cannot load script",
  2125. script_urls[i], err);
  2126. else if (tr || (unsigned int)rv >=
  2127. BR_SCRIPT_MAX)
  2128. script_error("Cannot load script",
  2129. script_urls[i],
  2130. "script is too large");
  2131. else {
  2132. body[rv] = '\0';
  2133. script_cache_put(script_urls[i], body,
  2134. (unsigned int)rv);
  2135. if (script->module)
  2136. js_browser_run_module(
  2137. (const char *)body,
  2138. script_urls[i]);
  2139. else
  2140. js_browser_run(
  2141. (const char *)body,
  2142. script_urls[i]);
  2143. }
  2144. free(body);
  2145. }
  2146. }
  2147. if (pending_action)
  2148. break;
  2149. }
  2150. js_browser_set_current_script(0);
  2151. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  2152. * load_home() stop it before the next navigation. */
  2153. if (doc.scripts_truncated && !js_last_error)
  2154. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  2155. 1);
  2156. }
  2157. /* ---- images ---- */
  2158. /* data: images that failed to decode (key = data_img_key()), so a layout
  2159. * pass does not retry them on every frame. */
  2160. #define DATA_IMG_FAIL_MAX 32
  2161. static unsigned int data_img_fail[DATA_IMG_FAIL_MAX];
  2162. static int data_img_nfail;
  2163. static void image_reset(void)
  2164. {
  2165. int i;
  2166. for (i = 0; i < BR_MAX_IMAGES; i++) {
  2167. images[i].state = 0;
  2168. images[i].native_w = images[i].native_h = 0;
  2169. images[i].err[0] = '\0';
  2170. /* heap_clear() ran before us, so these pointers are stale: drop
  2171. * them without calling free(). */
  2172. memset(&images[i].disp, 0, sizeof(images[i].disp));
  2173. images[i].disp_pixels = 0;
  2174. images[i].disp_last = 0;
  2175. }
  2176. image_count = 0;
  2177. data_img_nfail = 0;
  2178. image_pixels = 0;
  2179. image_disp_pixels = 0;
  2180. image_disp_clock = 0;
  2181. memset(img_stat_log, 0, sizeof(img_stat_log));
  2182. img_stat_log_len = 0;
  2183. img_stat_start = 0;
  2184. img_stat_wall = 0;
  2185. img_stat_net = img_stat_open = img_stat_first = 0;
  2186. img_stat_io = img_stat_dec = img_stat_scale = 0;
  2187. img_stat_paint = img_stat_reflow = 0;
  2188. img_stat_bytes = 0;
  2189. img_stat_n = 0;
  2190. img_last_dec_ms = img_last_scale_ms = 0;
  2191. img_repaint_ms = 0;
  2192. img_repaint_pending = 0;
  2193. preload_active = 0;
  2194. preload_pending = 0;
  2195. preload_wait = 0;
  2196. preload_node = 0;
  2197. preload_loaded = 0;
  2198. }
  2199. /* Ask for a repaint, but not more often than BR_IMG_REPAINT_MS while images
  2200. * are arriving. The main loop draws once per dirty frame; without this a
  2201. * page of N images did N full layout+paint passes. */
  2202. static void image_repaint(void)
  2203. {
  2204. unsigned int now = u_ticks_ms();
  2205. if (!img_repaint_ms || (now - img_repaint_ms) >= BR_IMG_REPAINT_MS) {
  2206. img_repaint_ms = now;
  2207. img_repaint_pending = 0;
  2208. ngui_invalidate(&ui);
  2209. } else {
  2210. img_repaint_pending = 1;
  2211. }
  2212. }
  2213. static void image_disp_drop(struct br_image *bi)
  2214. {
  2215. if (bi->disp.px)
  2216. free(bi->disp.px);
  2217. if (bi->disp.alpha)
  2218. free(bi->disp.alpha);
  2219. memset(&bi->disp, 0, sizeof(bi->disp));
  2220. if (bi->disp_pixels) {
  2221. if (image_disp_pixels >= bi->disp_pixels)
  2222. image_disp_pixels -= bi->disp_pixels;
  2223. bi->disp_pixels = 0;
  2224. }
  2225. }
  2226. /* Free the least recently used display caches until need pixels fit. The
  2227. * source bitmap (bi->img) is never evicted; a later draw rescales it again. */
  2228. static int image_disp_room(unsigned int need)
  2229. {
  2230. while (image_disp_pixels + need > BR_IMG_DISP_BUDGET) {
  2231. unsigned int oldest = ~0u;
  2232. int i, victim = -1;
  2233. for (i = 0; i < image_count; i++) {
  2234. if (!images[i].disp.px)
  2235. continue;
  2236. if (images[i].disp_last < oldest) {
  2237. oldest = images[i].disp_last;
  2238. victim = i;
  2239. }
  2240. }
  2241. if (victim < 0)
  2242. return -1;
  2243. image_disp_drop(&images[victim]);
  2244. }
  2245. return 0;
  2246. }
  2247. /* Return a bitmap at exactly dw x dh, building it once from the capped source
  2248. * bitmap. Callers then draw with scale 1 and img_draw's copy fast path. */
  2249. static struct img_image *image_display_get(struct br_image *bi, int dw, int dh)
  2250. {
  2251. struct img_blit b;
  2252. unsigned int px;
  2253. if (!bi || bi->state != 1 || !bi->img.px || dw < 1 || dh < 1)
  2254. return 0;
  2255. if (dw == (int)bi->img.w && dh == (int)bi->img.h)
  2256. return &bi->img;
  2257. if (dw > 4096 || dh > 4096)
  2258. return &bi->img;
  2259. if (bi->disp.px && bi->disp.w == (unsigned int)dw &&
  2260. bi->disp.h == (unsigned int)dh) {
  2261. bi->disp_last = ++image_disp_clock;
  2262. return &bi->disp;
  2263. }
  2264. px = (unsigned int)dw * (unsigned int)dh;
  2265. if (px > BR_IMG_DISP_BUDGET || image_disp_room(px) != 0)
  2266. return &bi->img;
  2267. image_disp_drop(bi);
  2268. bi->disp.px = (unsigned short *)malloc(px * 2u);
  2269. if (!bi->disp.px)
  2270. return &bi->img;
  2271. if (bi->img.alpha) {
  2272. bi->disp.alpha = (unsigned char *)malloc(px);
  2273. if (!bi->disp.alpha) {
  2274. free(bi->disp.px);
  2275. bi->disp.px = 0;
  2276. return &bi->img;
  2277. }
  2278. }
  2279. bi->disp.w = (unsigned int)dw;
  2280. bi->disp.h = (unsigned int)dh;
  2281. bi->disp.format = bi->img.format;
  2282. bi->disp.flags = 0;
  2283. memset(&b, 0, sizeof(b));
  2284. b.dst = bi->disp.px;
  2285. b.dst_w = dw;
  2286. b.dst_h = dh;
  2287. b.clip_w = dw;
  2288. b.clip_h = dh;
  2289. b.scale = ((unsigned int)dw << 16) / bi->img.w;
  2290. b.dst_a = bi->disp.alpha;
  2291. b.flags = bi->disp.alpha ? IMG_BLIT_SAVE_ALPHA : 0;
  2292. img_draw(&bi->img, &b);
  2293. bi->disp_pixels = px;
  2294. image_disp_pixels += px;
  2295. bi->disp_last = ++image_disp_clock;
  2296. return &bi->disp;
  2297. }
  2298. /* Decode into the shared arena, then copy/scale the result into a display
  2299. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  2300. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  2301. * pixels. Transparent edges are composited over white. */
  2302. /* One decode scratch arena per page, reused across images. Allocating and
  2303. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  2304. * each small display bitmap landed in the hole the previous arena left, so
  2305. * the next arena no longer fit and the heap ratcheted up until an app
  2306. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  2307. * still released right after their one image. */
  2308. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  2309. static unsigned char *decode_arena_get(unsigned int bytes)
  2310. {
  2311. if (decode_arena && decode_arena_size >= bytes)
  2312. return decode_arena;
  2313. free(decode_arena);
  2314. decode_arena = (unsigned char *)malloc(bytes);
  2315. decode_arena_size = decode_arena ? bytes : 0;
  2316. return decode_arena;
  2317. }
  2318. static void decode_arena_put(void)
  2319. {
  2320. if (decode_arena_size > DECODE_ARENA_KEEP) {
  2321. free(decode_arena);
  2322. decode_arena = 0;
  2323. decode_arena_size = 0;
  2324. }
  2325. }
  2326. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  2327. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  2328. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  2329. static int svg_text_sniff(const unsigned char *d, unsigned int len);
  2330. static int svg_decode_image(const unsigned char *data, unsigned int len,
  2331. struct br_image *bi, int box_w, int box_h);
  2332. static int decode_image_data(const unsigned char *data, unsigned int len,
  2333. struct br_image *bi, int box_w, int box_h,
  2334. int fit_w, int fit_h)
  2335. {
  2336. struct img_info info;
  2337. struct img_options opt;
  2338. struct img_mem mem;
  2339. struct img_image decoded;
  2340. unsigned char *arena;
  2341. unsigned int est, bytes, i;
  2342. unsigned int t0;
  2343. unsigned short *px;
  2344. unsigned char *alpha = 0;
  2345. int dw, dh, r;
  2346. bi->url_hash = 0;
  2347. img_last_dec_ms = 0;
  2348. img_last_scale_ms = 0;
  2349. if (img_sniff(data, len, &info) != 0) {
  2350. if (svg_text_sniff(data, len))
  2351. return svg_decode_image(data, len, bi,
  2352. box_w > 0 && box_h > 0 ? box_w : fit_w,
  2353. box_w > 0 && box_h > 0 ? box_h : fit_h);
  2354. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  2355. return -1;
  2356. }
  2357. est = img_estimate(&info);
  2358. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  2359. s_copy(bi->err, "image too large", sizeof(bi->err));
  2360. return -1;
  2361. }
  2362. arena = decode_arena_get(est);
  2363. if (!arena) {
  2364. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2365. return -1;
  2366. }
  2367. img_mem_init(&mem, arena, est);
  2368. opt.max_pixels = BR_IMG_PIX_MAX;
  2369. opt.max_w = fit_w > 0 ? (unsigned int)fit_w :
  2370. (box_w > 0 ? (unsigned int)box_w : 0);
  2371. opt.max_h = fit_h > 0 ? (unsigned int)fit_h :
  2372. (box_h > 0 ? (unsigned int)box_h : 0);
  2373. t0 = u_ticks_ms();
  2374. r = img_decode(data, len, &opt, &mem, &decoded);
  2375. img_last_dec_ms = u_ticks_ms() - t0;
  2376. if (r != 0) {
  2377. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  2378. goto fail;
  2379. }
  2380. if (decoded.w == 0 || decoded.h == 0) {
  2381. s_copy(bi->err, "empty image", sizeof(bi->err));
  2382. goto fail;
  2383. }
  2384. /* The JPEG decoder may have reduced the IDCT output; the layout still
  2385. * needs the intrinsic dimensions from the header. */
  2386. bi->native_w = info.width ? (int)info.width : (int)decoded.w;
  2387. bi->native_h = info.height ? (int)info.height : (int)decoded.h;
  2388. dw = (int)decoded.w;
  2389. dh = (int)decoded.h;
  2390. /* An <img> with a CSS/attribute box only ever needs a bitmap that big:
  2391. * decoding 1200x800 and then box-filtering it to 1000x666, only to
  2392. * paint it at 400x267, doubled the decode-time scaling work. cap both
  2393. * axes with one scale so the aspect ratio is preserved. */
  2394. if (fit_w > 0 || fit_h > 0) {
  2395. unsigned int scw = fit_w > 0 ?
  2396. ((unsigned int)fit_w << 16) / decoded.w : ~0u;
  2397. unsigned int sch = fit_h > 0 ?
  2398. ((unsigned int)fit_h << 16) / decoded.h : ~0u;
  2399. unsigned int sc = scw < sch ? scw : sch;
  2400. if (sc < 0x10000u) {
  2401. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2402. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2403. if (dw < 1)
  2404. dw = 1;
  2405. if (dh < 1)
  2406. dh = 1;
  2407. }
  2408. }
  2409. if (box_w > 0 && box_h > 0) {
  2410. /* cover: scale so both box sides are filled, never up */
  2411. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  2412. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  2413. unsigned int sc = sw > sh ? sw : sh;
  2414. if (sc < 0x10000u) {
  2415. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2416. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2417. }
  2418. }
  2419. if (dw > BR_IMG_LAYOUT_W) {
  2420. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  2421. dw = BR_IMG_LAYOUT_W;
  2422. }
  2423. if (dh < 1)
  2424. dh = 1;
  2425. if (dw < 1)
  2426. dw = 1;
  2427. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  2428. BR_IMG_PIXEL_BUDGET) {
  2429. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  2430. goto fail;
  2431. }
  2432. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  2433. px = (unsigned short *)malloc(bytes);
  2434. if (!px) {
  2435. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2436. goto fail;
  2437. }
  2438. /* Keep the alpha plane for the scaled image so transparent logos and
  2439. * icons composite over the page instead of the browser's dark theme
  2440. * background. Very large alpha images stay flattened to bound the
  2441. * heap use. */
  2442. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  2443. alpha = (unsigned char *)malloc((unsigned int)dw *
  2444. (unsigned int)dh);
  2445. if (alpha) {
  2446. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2447. alpha[i] = 255;
  2448. }
  2449. }
  2450. /* With an alpha plane the colour under transparent pixels only shows
  2451. * through partially covered edge pixels of the downscale: use white,
  2452. * as documented above, not the dark browser theme (which left a dark
  2453. * fringe around scaled app icons). */
  2454. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2455. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  2456. {
  2457. struct img_blit b;
  2458. b.dst = px;
  2459. b.dst_w = dw;
  2460. b.dst_h = dh;
  2461. b.clip_x = 0;
  2462. b.clip_y = 0;
  2463. b.clip_w = dw;
  2464. b.clip_h = dh;
  2465. b.x = 0;
  2466. b.y = 0;
  2467. b.scale = ((unsigned int)dw << 16) / decoded.w;
  2468. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  2469. b.bg2 = b.bg;
  2470. b.dst_a = alpha;
  2471. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  2472. t0 = u_ticks_ms();
  2473. img_draw(&decoded, &b);
  2474. img_last_scale_ms = u_ticks_ms() - t0;
  2475. }
  2476. bi->img.format = decoded.format;
  2477. bi->img.w = (unsigned int)dw;
  2478. bi->img.h = (unsigned int)dh;
  2479. bi->img.px = px;
  2480. bi->img.alpha = alpha;
  2481. bi->img.flags = 0;
  2482. bi->state = 1;
  2483. image_pixels += (unsigned int)dw * (unsigned int)dh;
  2484. decode_arena_put();
  2485. return 0;
  2486. fail:
  2487. decode_arena_put();
  2488. return -1;
  2489. }
  2490. /* ---- URL / local path handling ---- */
  2491. static int is_http(const char *s)
  2492. {
  2493. return starts_with(s, "http://") || starts_with(s, "https://");
  2494. }
  2495. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  2496. static int normalize_abs(const char *in, char *out, unsigned int cap)
  2497. {
  2498. char seg[64];
  2499. unsigned int i = 0, o = 1;
  2500. int depth = 0;
  2501. int trailing;
  2502. if (!in || in[0] != '/' || cap < 2)
  2503. return -1;
  2504. trailing = 0;
  2505. {
  2506. unsigned int n = s_len(in);
  2507. if (n > 1 && in[n - 1] == '/')
  2508. trailing = 1;
  2509. }
  2510. out[0] = '/';
  2511. while (in[i]) {
  2512. unsigned int n = 0;
  2513. while (in[i] == '/')
  2514. i++;
  2515. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  2516. if (n + 1 < sizeof(seg))
  2517. seg[n++] = in[i];
  2518. i++;
  2519. }
  2520. seg[n] = '\0';
  2521. if (n == 0)
  2522. break;
  2523. if (s_eq(seg, "."))
  2524. continue;
  2525. if (s_eq(seg, "..")) {
  2526. if (depth > 0) {
  2527. while (o > 1 && out[o - 1] != '/')
  2528. o--;
  2529. if (o > 1)
  2530. o--;
  2531. depth--;
  2532. }
  2533. continue;
  2534. }
  2535. if (o > 1) {
  2536. if (o + 1 >= cap)
  2537. return -1;
  2538. out[o++] = '/';
  2539. }
  2540. if (o + n + 1 >= cap)
  2541. return -1;
  2542. {
  2543. unsigned int j;
  2544. for (j = 0; j < n; j++)
  2545. out[o++] = seg[j];
  2546. }
  2547. depth++;
  2548. }
  2549. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2550. if (o + 1 >= cap)
  2551. return -1;
  2552. out[o++] = '/';
  2553. }
  2554. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2555. if (in[i] == '?' || in[i] == '#') {
  2556. while (in[i]) {
  2557. if (o + 1 >= cap)
  2558. return -1;
  2559. out[o++] = in[i++];
  2560. }
  2561. }
  2562. out[o] = '\0';
  2563. return 0;
  2564. }
  2565. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2566. {
  2567. char joined[BR_URL_MAX];
  2568. if (!in || !in[0]) {
  2569. s_copy(out, cwd[0] ? cwd : "/", cap);
  2570. return;
  2571. }
  2572. if (in[0] == '/') {
  2573. if (normalize_abs(in, out, cap) != 0)
  2574. s_copy(out, in, cap);
  2575. return;
  2576. }
  2577. {
  2578. unsigned int n = 0;
  2579. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2580. s_append(joined, &n, "/", sizeof(joined));
  2581. s_append(joined, &n, in, sizeof(joined));
  2582. }
  2583. if (normalize_abs(joined, out, cap) != 0)
  2584. s_copy(out, joined, cap);
  2585. }
  2586. /* ---- canonical origin cache ---- *
  2587. *
  2588. * Sites commonly redirect http://host to https://host and then to
  2589. * https://www.host. Remember the final scheme/host of the last navigation so
  2590. * a bare domain typed again goes straight there instead of paying for two
  2591. * more connections and TLS handshakes. Only default-port requests are
  2592. * rewritten; explicit ports are left alone. */
  2593. #define ORIGIN_CACHE_MAX 8
  2594. #define ORIGIN_FILE "/share/borigins"
  2595. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2596. UHTTP_HOST_MAX + 2))
  2597. struct origin_cache_entry {
  2598. char host[UHTTP_HOST_MAX];
  2599. char origin[UHTTP_HOST_MAX + 16];
  2600. };
  2601. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2602. static int origin_count;
  2603. static char origin_buf[ORIGIN_BUF_SIZE];
  2604. static int default_port(const struct uhttp_url *u)
  2605. {
  2606. return u->secure ? u->port == 443 : u->port == 80;
  2607. }
  2608. static void url_origin(const struct uhttp_url *u, char *out,
  2609. unsigned int cap)
  2610. {
  2611. unsigned int n = 0;
  2612. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2613. s_append(out, &n, u->host, cap);
  2614. if (!default_port(u)) {
  2615. s_append(out, &n, ":", cap);
  2616. s_append_dec(out, &n, u->port, cap);
  2617. }
  2618. }
  2619. static void origin_cache_apply(char *url, unsigned int cap)
  2620. {
  2621. struct uhttp_url u;
  2622. char out[BR_URL_MAX];
  2623. unsigned int n = 0;
  2624. int i;
  2625. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2626. return;
  2627. for (i = 0; i < origin_count; i++) {
  2628. if (!s_eq(u.host, origins[i].host))
  2629. continue;
  2630. s_append(out, &n, origins[i].origin, sizeof(out));
  2631. s_append(out, &n, u.path, sizeof(out));
  2632. s_copy(url, out, cap);
  2633. return;
  2634. }
  2635. }
  2636. static void origin_cache_save(void)
  2637. {
  2638. unsigned int n = 0;
  2639. int i;
  2640. for (i = 0; i < origin_count; i++) {
  2641. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2642. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2643. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2644. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2645. }
  2646. if (n)
  2647. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2648. (int)origin_buf, (int)n);
  2649. }
  2650. static void origin_cache_load(void)
  2651. {
  2652. char *p;
  2653. int rn;
  2654. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2655. (int)(sizeof(origin_buf) - 1));
  2656. if (rn <= 0)
  2657. return;
  2658. origin_buf[rn] = '\0';
  2659. p = origin_buf;
  2660. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2661. char *line = p, *origin;
  2662. while (*p && *p != '\n')
  2663. p++;
  2664. if (*p)
  2665. *p++ = '\0';
  2666. if (!line[0])
  2667. continue;
  2668. origin = line;
  2669. while (*origin && *origin != ' ')
  2670. origin++;
  2671. if (!*origin)
  2672. continue;
  2673. *origin++ = '\0';
  2674. if (!line[0] || !is_http(origin))
  2675. continue;
  2676. {
  2677. struct uhttp_url uo;
  2678. if (uhttp_parse_url(origin, &uo) != 0 ||
  2679. !s_eq(uo.path, "/"))
  2680. continue;
  2681. }
  2682. s_copy(origins[origin_count].host, line,
  2683. sizeof(origins[origin_count].host));
  2684. s_copy(origins[origin_count].origin, origin,
  2685. sizeof(origins[origin_count].origin));
  2686. origin_count++;
  2687. }
  2688. }
  2689. static int host_is_www_of(const char *host, const char *base)
  2690. {
  2691. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2692. host[3] == '.' && s_eq(host + 4, base);
  2693. }
  2694. static void origin_cache_learn(const char *requested, const char *final)
  2695. {
  2696. struct uhttp_url from, to;
  2697. char origin[UHTTP_HOST_MAX + 16];
  2698. int i;
  2699. if (!is_http(requested) || !is_http(final))
  2700. return;
  2701. if (uhttp_parse_url(requested, &from) != 0 ||
  2702. uhttp_parse_url(final, &to) != 0)
  2703. return;
  2704. if (!default_port(&from))
  2705. return;
  2706. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2707. from.port == to.port)
  2708. return;
  2709. /* Only remember origin-level canonicalisation: the same path, and
  2710. * either the same host or its www./apex sibling. A path- or
  2711. * host-specific redirect (a shortener, a login page) must not poison
  2712. * every request to the typed host. */
  2713. if (!s_eq(from.path, to.path))
  2714. return;
  2715. if (!s_eq(from.host, to.host) &&
  2716. !host_is_www_of(to.host, from.host) &&
  2717. !host_is_www_of(from.host, to.host))
  2718. return;
  2719. url_origin(&to, origin, sizeof(origin));
  2720. for (i = 0; i < origin_count; i++) {
  2721. if (s_eq(origins[i].host, from.host)) {
  2722. if (!s_eq(origins[i].origin, origin)) {
  2723. s_copy(origins[i].origin, origin,
  2724. sizeof(origins[i].origin));
  2725. origin_cache_save();
  2726. }
  2727. return;
  2728. }
  2729. }
  2730. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2731. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2732. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2733. origin_cache_save();
  2734. }
  2735. static int path_dir(const char *path, char *out, unsigned int cap)
  2736. {
  2737. unsigned int i, last = 0;
  2738. for (i = 0; path[i]; i++)
  2739. if (path[i] == '/')
  2740. last = i;
  2741. if (last == 0) {
  2742. if (cap < 2)
  2743. return -1;
  2744. out[0] = '/';
  2745. out[1] = '\0';
  2746. return 0;
  2747. }
  2748. if (last + 1 >= cap)
  2749. return -1;
  2750. {
  2751. unsigned int j;
  2752. for (j = 0; j < last; j++)
  2753. out[j] = path[j];
  2754. out[last] = '\0';
  2755. }
  2756. return 0;
  2757. }
  2758. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2759. static int resolve_link(const char *base, const char *href, char *out,
  2760. unsigned int cap)
  2761. {
  2762. static char joined[BR_URL_MAX]; /* leaf: off the stack */
  2763. if (!href || !href[0] || href[0] == '#')
  2764. return -1;
  2765. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2766. starts_with(href, "data:") || starts_with(href, "tel:"))
  2767. return -1;
  2768. if (starts_with(href, "about:")) {
  2769. s_copy(out, href, cap);
  2770. return 0;
  2771. }
  2772. if (is_http(href)) {
  2773. s_copy(out, href, cap);
  2774. return 0;
  2775. }
  2776. if (starts_with(href, "//")) {
  2777. if (is_http(base)) {
  2778. unsigned int n = 0;
  2779. s_append(out, &n, starts_with(base, "https:") ?
  2780. "https:" : "http:", cap);
  2781. s_append(out, &n, href, cap);
  2782. return 0;
  2783. }
  2784. return -1;
  2785. }
  2786. if (is_http(base)) {
  2787. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2788. }
  2789. /* local page */
  2790. if (href[0] == '/') {
  2791. if (normalize_abs(href, out, cap) != 0)
  2792. return -1;
  2793. return 0;
  2794. }
  2795. {
  2796. static char dir[BR_URL_MAX];
  2797. unsigned int n = 0;
  2798. if (s_eq(base, "about:home"))
  2799. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2800. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2801. s_copy(dir, "/", sizeof(dir));
  2802. s_append(joined, &n, dir, sizeof(joined));
  2803. if (n == 0 || joined[n - 1] != '/')
  2804. s_append(joined, &n, "/", sizeof(joined));
  2805. s_append(joined, &n, href, sizeof(joined));
  2806. }
  2807. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2808. }
  2809. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2810. * rest instead of failing when a page or stylesheet is larger than the
  2811. * buffer. The stream is still walked to the end, so a normal page is
  2812. * verified; a truncated compressed input still returns whatever was decoded
  2813. * so far. */
  2814. struct trunc_buf {
  2815. unsigned char *dst;
  2816. unsigned int cap, pos;
  2817. int full;
  2818. };
  2819. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2820. {
  2821. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2822. if (len > m->cap - m->pos) {
  2823. unsigned int room = m->cap - m->pos;
  2824. if (room) {
  2825. unsigned int i;
  2826. for (i = 0; i < room; i++)
  2827. m->dst[m->pos + i] = data[i];
  2828. m->pos += room;
  2829. }
  2830. m->full = 1;
  2831. return 0;
  2832. }
  2833. {
  2834. unsigned int i;
  2835. for (i = 0; i < len; i++)
  2836. m->dst[m->pos + i] = data[i];
  2837. }
  2838. m->pos += len;
  2839. return 0;
  2840. }
  2841. static void worker_wait_ui(void);
  2842. static void inflate_ui_pump(void *ctx)
  2843. {
  2844. static unsigned int last;
  2845. unsigned int now = u_ticks_ms();
  2846. (void)ctx;
  2847. if ((int)(now - last) >= 50) {
  2848. last = now;
  2849. worker_wait_ui();
  2850. }
  2851. }
  2852. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2853. unsigned char *dst, unsigned int cap,
  2854. unsigned int *outlen, int gzip, int *truncated)
  2855. {
  2856. struct inflate_src in;
  2857. struct inflate_sink sink;
  2858. struct trunc_buf m;
  2859. unsigned int got = 0;
  2860. int r;
  2861. in.p = src;
  2862. in.len = len;
  2863. in.more = 0;
  2864. in.ctx = 0;
  2865. m.dst = dst;
  2866. m.cap = cap;
  2867. m.pos = 0;
  2868. m.full = 0;
  2869. sink.write = trunc_write;
  2870. sink.ctx = &m;
  2871. inflate_init(&image_inflate_ws, &in, &sink);
  2872. image_inflate_ws.progress = inflate_ui_pump;
  2873. image_inflate_ws.progress_ctx = 0;
  2874. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2875. inflate_zlib(&image_inflate_ws, &got);
  2876. *outlen = m.pos;
  2877. *truncated = m.full || r != 0;
  2878. if (r != 0 && m.pos == 0)
  2879. return -1;
  2880. return 0;
  2881. }
  2882. /* ---- headless fetch workers ------------------------------------------ *
  2883. *
  2884. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2885. * writes the raw response, a small metadata file and a done marker under
  2886. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2887. * or a multi-megabyte body never freezes the UI and images download in
  2888. * parallel.
  2889. */
  2890. struct fetch_meta {
  2891. int status;
  2892. int error;
  2893. int trunc;
  2894. unsigned int len;
  2895. unsigned int open_ms;
  2896. unsigned int first_ms;
  2897. unsigned int total_ms;
  2898. /* Optional decoded bitmap produced by the helper (image jobs). */
  2899. unsigned int dw, dh, nw, nh;
  2900. unsigned int alpha;
  2901. unsigned int px_len;
  2902. unsigned int dec_ms;
  2903. int dec_err;
  2904. char encoding[16];
  2905. char ctype[64];
  2906. char final[BR_URL_MAX];
  2907. };
  2908. static void draw(unsigned int *action);
  2909. static void handle_keys(unsigned int *action);
  2910. static void handle_page_click(unsigned int *action);
  2911. #define FETCH_WORKERS 4
  2912. #define FETCH_PATH_MAX 32
  2913. /* One long-lived curl __serve helper per worker. Each worker has its own
  2914. * request/body/meta/done files under /share so several downloads can be in
  2915. * flight at once; the keep-alive connection stays in the helper process, so
  2916. * tls.c's per-process state remains valid. */
  2917. struct fetch_worker {
  2918. int pid;
  2919. int slot;
  2920. int busy;
  2921. int ready;
  2922. int image_job;
  2923. unsigned int seq;
  2924. unsigned int deadline;
  2925. int retried;
  2926. unsigned int dec_w, dec_h;
  2927. int dec_retried;
  2928. char req[FETCH_PATH_MAX];
  2929. char body[FETCH_PATH_MAX];
  2930. char meta[FETCH_PATH_MAX];
  2931. char done[FETCH_PATH_MAX];
  2932. char post[FETCH_PATH_MAX];
  2933. char px[FETCH_PATH_MAX];
  2934. /* Optional preload job attached to this worker. */
  2935. unsigned int node;
  2936. int bg;
  2937. char url[BR_URL_MAX];
  2938. struct fetch_meta m;
  2939. };
  2940. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2941. static int fetch_tty = -2;
  2942. static void fetch_tty_drain(void);
  2943. static unsigned int fetch_session;
  2944. static unsigned int fetch_seq;
  2945. static struct fetch_meta fetch_meta;
  2946. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2947. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2948. static int fetch_last_error;
  2949. static unsigned int meta_uint(char **pp)
  2950. {
  2951. char *p = *pp;
  2952. unsigned int v = 0;
  2953. while (*p >= '0' && *p <= '9') {
  2954. v = v * 10 + (unsigned int)(*p - '0');
  2955. p++;
  2956. }
  2957. while (*p && *p != '\n')
  2958. p++;
  2959. if (*p == '\n')
  2960. p++;
  2961. *pp = p;
  2962. return v;
  2963. }
  2964. static void meta_str(char **pp, char *out, unsigned int cap)
  2965. {
  2966. char *p = *pp;
  2967. unsigned int n = 0;
  2968. while (*p && *p != '\n' && n + 1 < cap)
  2969. out[n++] = *p++;
  2970. out[n] = '\0';
  2971. while (*p && *p != '\n')
  2972. p++;
  2973. if (*p == '\n')
  2974. p++;
  2975. *pp = p;
  2976. }
  2977. static void worker_wait_ui(void)
  2978. {
  2979. unsigned int action = 0;
  2980. if (!ngui_begin(&ui))
  2981. return;
  2982. draw(&action);
  2983. handle_keys(&action);
  2984. handle_page_click(&action);
  2985. if (action & ACT_WAIT_NAV) {
  2986. pending_action |= action & ACT_WAIT_NAV;
  2987. if ((action & ACT_NAV) && click_url[0])
  2988. s_copy(pending_url, click_url, sizeof(pending_url));
  2989. click_url[0] = '\0';
  2990. cancel_fetch = 1;
  2991. }
  2992. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  2993. ngui_invalidate(&ui);
  2994. ngui_end(&ui);
  2995. }
  2996. static void fetch_path(char *out, unsigned int cap, const char *kind,
  2997. unsigned int session, int slot)
  2998. {
  2999. unsigned int n = 0;
  3000. s_append(out, &n, "/share/bf", cap);
  3001. s_append_dec(out, &n, session, cap);
  3002. s_append(out, &n, "_", cap);
  3003. s_append_dec(out, &n, (unsigned int)slot, cap);
  3004. s_append(out, &n, kind, cap);
  3005. }
  3006. static void fetch_pool_init(void)
  3007. {
  3008. static int ready;
  3009. int i;
  3010. if (ready)
  3011. return;
  3012. ready = 1;
  3013. fetch_session = ((unsigned int)u_getpid() << 16) ^
  3014. (u_ticks_ms() & 0xFFFFu);
  3015. if (!fetch_session)
  3016. fetch_session = 1;
  3017. for (i = 0; i < FETCH_WORKERS; i++) {
  3018. struct fetch_worker *w = &fetch_workers[i];
  3019. w->pid = -1;
  3020. w->slot = i;
  3021. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  3022. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  3023. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  3024. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  3025. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  3026. fetch_path(w->px, sizeof(w->px), "px", fetch_session, i);
  3027. }
  3028. }
  3029. static void fetch_worker_stop(struct fetch_worker *w)
  3030. {
  3031. int i;
  3032. /* An abandoned image job leaves its node loadable again. */
  3033. if (w->busy && w->image_job && w->node < doc.nnode) {
  3034. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  3035. doc.nodes[w->node].bg_img_index = -1;
  3036. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  3037. doc.nodes[w->node].img_index = -1;
  3038. }
  3039. if (w->pid > 0) {
  3040. u_kill((unsigned int)w->pid);
  3041. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  3042. u_sleep_ms(5);
  3043. /* Let the reaper close the socket before we reuse the slot. */
  3044. u_sleep_ms(10);
  3045. }
  3046. w->pid = -1;
  3047. w->busy = 0;
  3048. w->ready = 0;
  3049. w->image_job = 0;
  3050. if (w->req[0]) {
  3051. u_syscall1(SYS_UNLINK, (int)w->done);
  3052. u_syscall1(SYS_UNLINK, (int)w->meta);
  3053. u_syscall1(SYS_UNLINK, (int)w->body);
  3054. u_syscall1(SYS_UNLINK, (int)w->post);
  3055. u_syscall1(SYS_UNLINK, (int)w->req);
  3056. }
  3057. }
  3058. static void fetch_workers_stop_all(void)
  3059. {
  3060. int i;
  3061. for (i = 0; i < FETCH_WORKERS; i++)
  3062. fetch_worker_stop(&fetch_workers[i]);
  3063. }
  3064. /* Abandon the transfers of the current page but keep idle helpers and their
  3065. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  3066. * because its response would otherwise land in a reused /share slot. */
  3067. static void fetch_workers_cancel_busy(void)
  3068. {
  3069. int i;
  3070. for (i = 0; i < FETCH_WORKERS; i++)
  3071. if (fetch_workers[i].busy)
  3072. fetch_worker_stop(&fetch_workers[i]);
  3073. }
  3074. static void fetch_workers_prepare_nav(const char *url)
  3075. {
  3076. int i;
  3077. (void)url;
  3078. for (i = 0; i < FETCH_WORKERS; i++) {
  3079. struct fetch_worker *w = &fetch_workers[i];
  3080. if (w->pid <= 0)
  3081. continue;
  3082. /* Only an in-flight transfer must be aborted. Idle helpers
  3083. * stay warm across origins: there are just FETCH_WORKERS of
  3084. * them, and uhttp_open drops the old connection when the
  3085. * next job is for another host. Killing and respawning all
  3086. * four on every navigation churned processes and sockets
  3087. * while images were still loading. */
  3088. if (w->busy)
  3089. fetch_worker_stop(w);
  3090. }
  3091. }
  3092. /* The browser is no longer the active window and no fetch is running: give
  3093. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  3094. static void fetch_workers_stop_if_unfocused(void)
  3095. {
  3096. int i;
  3097. fetch_tty_drain();
  3098. if (ui.focused || page_loading || preload_active)
  3099. return;
  3100. for (i = 0; i < FETCH_WORKERS; i++)
  3101. if (fetch_workers[i].pid > 0) {
  3102. fetch_workers_stop_all();
  3103. return;
  3104. }
  3105. }
  3106. /* The helpers (and this process, since u_tty_create() rebinds our own
  3107. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  3108. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  3109. * a dozen TLS connections every helper hung in its next log line, so the
  3110. * following cross-origin navigation sat at "Loading..." until it timed out.
  3111. * Drain and discard it from every wait/poll loop. */
  3112. static void fetch_tty_drain(void)
  3113. {
  3114. char sink[512];
  3115. int i;
  3116. if (fetch_tty <= 0)
  3117. return;
  3118. for (i = 0; i < 16; i++)
  3119. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  3120. break;
  3121. }
  3122. static int fetch_worker_start(struct fetch_worker *w, char *err,
  3123. unsigned int errcap)
  3124. {
  3125. char arg[40];
  3126. unsigned int n = 0;
  3127. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  3128. return 0;
  3129. w->pid = -1;
  3130. fetch_pool_init();
  3131. if (fetch_tty == -2) {
  3132. int t = u_tty_create();
  3133. fetch_tty = t > 0 ? t : 0;
  3134. }
  3135. s_append(arg, &n, "__serve ", sizeof(arg));
  3136. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  3137. s_append(arg, &n, " ", sizeof(arg));
  3138. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  3139. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  3140. if (w->pid <= 0) {
  3141. w->pid = -1;
  3142. s_copy(err, "cannot start network helper", errcap);
  3143. return -1;
  3144. }
  3145. return 0;
  3146. }
  3147. static struct fetch_worker *fetch_worker_alloc(void)
  3148. {
  3149. int i;
  3150. fetch_pool_init();
  3151. for (i = 0; i < FETCH_WORKERS; i++)
  3152. if (!fetch_workers[i].busy)
  3153. return &fetch_workers[i];
  3154. return 0;
  3155. }
  3156. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3157. unsigned int cap, const char *method,
  3158. const char *ctype, const char *post,
  3159. unsigned int post_len, unsigned int node,
  3160. int bg, unsigned int dec_w,
  3161. unsigned int dec_h, char *err,
  3162. unsigned int errcap);
  3163. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  3164. unsigned int cap, const char *post,
  3165. unsigned int post_len, unsigned int node,
  3166. int bg, char *err, unsigned int errcap)
  3167. {
  3168. /* A body pointer with no bytes is still a POST: the classic request
  3169. * line would turn it into a GET. */
  3170. if (post && !post_len)
  3171. return fetch_worker_submit_req(w, url, cap, "POST",
  3172. "application/x-www-form-urlencoded", post, 0, node,
  3173. bg, 0, 0, err, errcap);
  3174. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  3175. node, bg, 0, 0, err, errcap);
  3176. }
  3177. /* Image job: ask the helper to decode at these display bounds as well. */
  3178. static int fetch_worker_submit_image(struct fetch_worker *w, const char *url,
  3179. unsigned int cap, unsigned int node,
  3180. int bg, unsigned int dec_w,
  3181. unsigned int dec_h, char *err,
  3182. unsigned int errcap)
  3183. {
  3184. return fetch_worker_submit_req(w, url, cap, 0, 0, 0, 0, node, bg,
  3185. dec_w, dec_h, err, errcap);
  3186. }
  3187. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  3188. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  3189. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3190. unsigned int cap, const char *method,
  3191. const char *ctype, const char *post,
  3192. unsigned int post_len, unsigned int node,
  3193. int bg, unsigned int dec_w,
  3194. unsigned int dec_h, char *err,
  3195. unsigned int errcap)
  3196. {
  3197. static char req[BR_URL_MAX + 256];
  3198. unsigned int n = 0;
  3199. fetch_seq++;
  3200. if (!fetch_seq)
  3201. fetch_seq = 1;
  3202. w->seq = fetch_seq;
  3203. w->ready = 0;
  3204. w->image_job = 0;
  3205. w->retried = 0;
  3206. w->m.error = 0;
  3207. w->node = node;
  3208. w->bg = bg;
  3209. w->dec_w = dec_w;
  3210. w->dec_h = dec_h;
  3211. w->dec_retried = 0;
  3212. s_copy(w->url, url, sizeof(w->url));
  3213. s_append_dec(req, &n, w->seq, sizeof(req));
  3214. s_append(req, &n, " ", sizeof(req));
  3215. s_append_dec(req, &n, cap, sizeof(req));
  3216. s_append(req, &n, " ", sizeof(req));
  3217. if (dec_w || dec_h) {
  3218. s_append(req, &n, "D ", sizeof(req));
  3219. s_append_dec(req, &n, dec_w, sizeof(req));
  3220. s_append(req, &n, " ", sizeof(req));
  3221. s_append_dec(req, &n, dec_h, sizeof(req));
  3222. s_append(req, &n, " ", sizeof(req));
  3223. } else if (method) {
  3224. unsigned int k;
  3225. s_append(req, &n, "X ", sizeof(req));
  3226. s_append(req, &n, method, sizeof(req));
  3227. s_append(req, &n, " ", sizeof(req));
  3228. s_append_dec(req, &n, post_len, sizeof(req));
  3229. s_append(req, &n, " ", sizeof(req));
  3230. if (!ctype || !ctype[0])
  3231. s_append(req, &n, "-", sizeof(req));
  3232. /* One token on the request line: drop the spaces
  3233. * ("application/json; charset=utf-8" stays valid). */
  3234. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  3235. if (ctype[k] != ' ')
  3236. req[n++] = ctype[k];
  3237. req[n] = '\0';
  3238. s_append(req, &n, " ", sizeof(req));
  3239. } else if (post_len) {
  3240. s_append(req, &n, "POST ", sizeof(req));
  3241. s_append_dec(req, &n, post_len, sizeof(req));
  3242. s_append(req, &n, " ", sizeof(req));
  3243. }
  3244. s_append(req, &n, url, sizeof(req));
  3245. s_append(req, &n, "\n", sizeof(req));
  3246. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  3247. (int)post, (int)post_len) < 0) {
  3248. s_copy(err, "cannot queue form body", errcap);
  3249. return -1;
  3250. }
  3251. u_syscall1(SYS_UNLINK, (int)w->done);
  3252. u_syscall1(SYS_UNLINK, (int)w->meta);
  3253. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  3254. s_copy(err, "cannot queue network request", errcap);
  3255. return -1;
  3256. }
  3257. if (fetch_worker_start(w, err, errcap) != 0)
  3258. return -1;
  3259. w->busy = 1;
  3260. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  3261. return 0;
  3262. }
  3263. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  3264. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  3265. unsigned int errcap)
  3266. {
  3267. static char meta[BR_URL_MAX + 1024];
  3268. char *p;
  3269. int rn, mseq;
  3270. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  3271. (int)(sizeof(meta) - 1));
  3272. if (rn <= 0) {
  3273. s_copy(err, "network helper failed", errcap);
  3274. return -1;
  3275. }
  3276. meta[rn] = '\0';
  3277. p = meta;
  3278. mseq = (int)meta_uint(&p);
  3279. if (mseq != (int)w->seq) {
  3280. s_copy(err, "stale network response", errcap);
  3281. return -1;
  3282. }
  3283. w->m.status = (int)meta_uint(&p);
  3284. w->m.error = (int)meta_uint(&p);
  3285. w->m.trunc = (int)meta_uint(&p);
  3286. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  3287. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  3288. meta_str(&p, w->m.final, sizeof(w->m.final));
  3289. w->m.len = meta_uint(&p);
  3290. w->m.open_ms = 0;
  3291. w->m.first_ms = 0;
  3292. w->m.total_ms = 0;
  3293. if (*p) {
  3294. w->m.open_ms = meta_uint(&p);
  3295. w->m.first_ms = meta_uint(&p);
  3296. w->m.total_ms = meta_uint(&p);
  3297. }
  3298. w->m.dw = w->m.dh = w->m.nw = w->m.nh = 0;
  3299. w->m.alpha = w->m.px_len = w->m.dec_ms = 0;
  3300. w->m.dec_err = 0;
  3301. if (*p) {
  3302. w->m.dw = meta_uint(&p);
  3303. w->m.dh = meta_uint(&p);
  3304. w->m.nw = meta_uint(&p);
  3305. w->m.nh = meta_uint(&p);
  3306. w->m.alpha = meta_uint(&p);
  3307. w->m.px_len = meta_uint(&p);
  3308. w->m.dec_err = (int)meta_uint(&p);
  3309. w->m.dec_ms = meta_uint(&p);
  3310. }
  3311. if (w->m.error) {
  3312. s_copy(err, uhttp_error_string(w->m.error), errcap);
  3313. return -1;
  3314. }
  3315. w->ready = 1;
  3316. return 0;
  3317. }
  3318. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  3319. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  3320. unsigned int errcap)
  3321. {
  3322. static char done[24];
  3323. char *p;
  3324. int rn, mseq;
  3325. fetch_tty_drain();
  3326. if (!w->busy)
  3327. return -1;
  3328. if (w->ready)
  3329. return 1;
  3330. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  3331. (int)(sizeof(done) - 1));
  3332. if (rn > 0) {
  3333. done[rn] = '\0';
  3334. p = done;
  3335. mseq = (int)meta_uint(&p);
  3336. if (mseq == (int)w->seq) {
  3337. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  3338. fetch_worker_stop(w);
  3339. return -1;
  3340. }
  3341. return 1;
  3342. }
  3343. }
  3344. if (!u_alive((unsigned int)w->pid)) {
  3345. w->pid = -1;
  3346. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  3347. w->retried = 1;
  3348. return 0;
  3349. }
  3350. s_copy(err, "network helper stopped", errcap);
  3351. fetch_worker_stop(w);
  3352. return -1;
  3353. }
  3354. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  3355. s_copy(err, "network request timed out", errcap);
  3356. fetch_worker_stop(w);
  3357. return -1;
  3358. }
  3359. return 0;
  3360. }
  3361. /* Copy the completed body, inflating it if the server ignored our identity
  3362. * request. Mirrors the old fetch_remote body path. */
  3363. static int fetch_worker_read_body(struct fetch_worker *w,
  3364. unsigned char *plain,
  3365. unsigned int plaincap,
  3366. unsigned char *comp,
  3367. unsigned int compcap,
  3368. int *truncated, char *err,
  3369. unsigned int errcap)
  3370. {
  3371. int rv, zr, was_trunc;
  3372. if (contains_ci(w->m.encoding, "gzip") ||
  3373. contains_ci(w->m.encoding, "deflate")) {
  3374. unsigned int comp_len = 0, plen = 0;
  3375. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  3376. (int)compcap);
  3377. if (rv < 0) {
  3378. s_copy(err, "empty response", errcap);
  3379. return -1;
  3380. }
  3381. comp_len = (unsigned int)rv;
  3382. if (comp_len < w->m.len) {
  3383. s_copy(err, "compressed response is too large", errcap);
  3384. return -1;
  3385. }
  3386. if (contains_ci(w->m.encoding, "deflate"))
  3387. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3388. &plen, 0, &was_trunc);
  3389. else
  3390. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3391. &plen, 1, &was_trunc);
  3392. if (zr != 0) {
  3393. s_copy(err, "compressed response is corrupt", errcap);
  3394. return -1;
  3395. }
  3396. *truncated = w->m.trunc || was_trunc;
  3397. return (int)plen;
  3398. }
  3399. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  3400. if (rv < 0) {
  3401. s_copy(err, "empty response", errcap);
  3402. return -1;
  3403. }
  3404. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  3405. return rv;
  3406. }
  3407. static void fetch_worker_release(struct fetch_worker *w)
  3408. {
  3409. u_syscall1(SYS_UNLINK, (int)w->done);
  3410. u_syscall1(SYS_UNLINK, (int)w->meta);
  3411. u_syscall1(SYS_UNLINK, (int)w->body);
  3412. u_syscall1(SYS_UNLINK, (int)w->post);
  3413. u_syscall1(SYS_UNLINK, (int)w->px);
  3414. u_syscall1(SYS_UNLINK, (int)w->req);
  3415. w->busy = 0;
  3416. w->ready = 0;
  3417. w->image_job = 0;
  3418. w->dec_w = 0;
  3419. w->dec_h = 0;
  3420. w->dec_retried = 0;
  3421. }
  3422. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  3423. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  3424. unsigned int errcap)
  3425. {
  3426. for (;;) {
  3427. int rv;
  3428. if (!fetch_wait_passive)
  3429. worker_wait_ui();
  3430. if (cancel_fetch || pending_action) {
  3431. fetch_workers_cancel_busy();
  3432. return FETCH_ABORT;
  3433. }
  3434. rv = fetch_worker_poll(w, err, errcap);
  3435. if (rv != 0)
  3436. return rv == 1 ? 0 : -1;
  3437. u_sleep_ms(10);
  3438. }
  3439. }
  3440. static int fetch_remote(const char *url, unsigned int cap,
  3441. const char *post, unsigned int post_len,
  3442. unsigned char *plain, unsigned int plaincap,
  3443. unsigned char *comp, unsigned int compcap,
  3444. struct fetch_meta *m, int *truncated,
  3445. char *err, unsigned int errcap)
  3446. {
  3447. struct fetch_worker *w = fetch_worker_alloc();
  3448. int rv;
  3449. fetch_last_error = 0;
  3450. if (!w) {
  3451. s_copy(err, "network busy", errcap);
  3452. return -1;
  3453. }
  3454. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  3455. err, errcap) != 0) {
  3456. fetch_worker_release(w);
  3457. return -1;
  3458. }
  3459. rv = fetch_worker_wait(w, err, errcap);
  3460. if (rv == FETCH_ABORT) {
  3461. fetch_worker_release(w);
  3462. return FETCH_ABORT;
  3463. }
  3464. if (rv != 0) {
  3465. fetch_last_error = w->m.error;
  3466. fetch_worker_release(w);
  3467. return -1;
  3468. }
  3469. *m = w->m;
  3470. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  3471. truncated, err, errcap);
  3472. fetch_worker_release(w);
  3473. if (rv >= 0 && (cancel_fetch || pending_action))
  3474. return FETCH_ABORT;
  3475. return rv;
  3476. }
  3477. static int fetch_worker_status(const struct fetch_worker *w)
  3478. {
  3479. return w->m.status;
  3480. }
  3481. /* fetch()/XHR through a helper: one request, the status and body come back
  3482. * whatever the HTTP status (a 401 is an answer, not a network error). */
  3483. static int js_worker_http(const char *method, const char *url,
  3484. const char *ctype, const char *body,
  3485. unsigned int body_len, struct js_http_resp *r,
  3486. char *err, int errcap)
  3487. {
  3488. struct fetch_worker *w = fetch_worker_alloc();
  3489. unsigned char *plain;
  3490. int rv, tr = 0;
  3491. if (!w) {
  3492. s_copy(err, "network busy", (unsigned int)errcap);
  3493. return -1;
  3494. }
  3495. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  3496. body_len, 0, 0, 0, 0, err,
  3497. (unsigned int)errcap) != 0) {
  3498. fetch_worker_release(w);
  3499. return -1;
  3500. }
  3501. fetch_wait_passive++;
  3502. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  3503. fetch_wait_passive--;
  3504. if (rv != 0) {
  3505. if (rv == FETCH_ABORT)
  3506. s_copy(err, "page is navigating", (unsigned int)errcap);
  3507. fetch_worker_release(w);
  3508. return -1;
  3509. }
  3510. r->status = w->m.status;
  3511. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  3512. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  3513. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  3514. if (!plain) {
  3515. fetch_worker_release(w);
  3516. s_copy(err, "out of memory", (unsigned int)errcap);
  3517. return -1;
  3518. }
  3519. if (w->m.len == 0) {
  3520. rv = 0; /* 204, an empty 200: no body file */
  3521. } else {
  3522. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  3523. image_io_buf, BR_PAGE_COMP_MAX,
  3524. &tr, err, (unsigned int)errcap);
  3525. }
  3526. fetch_worker_release(w);
  3527. if (rv < 0) {
  3528. free(plain);
  3529. return -1;
  3530. }
  3531. plain[rv] = '\0';
  3532. r->body = (char *)plain;
  3533. r->len = (unsigned int)rv;
  3534. return 0;
  3535. }
  3536. /* ---- HTTP / file fetch ---- */
  3537. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  3538. unsigned int *outlen, int *is_local, char *ctype,
  3539. unsigned int ctcap, char *final, unsigned int finalcap,
  3540. char *err, unsigned int errcap, int *truncated,
  3541. const char *post, unsigned int post_len)
  3542. {
  3543. unsigned char *buf;
  3544. unsigned int len;
  3545. int tr = 0;
  3546. int rv;
  3547. *out = 0;
  3548. *outlen = 0;
  3549. *truncated = 0;
  3550. if (final && finalcap)
  3551. final[0] = '\0';
  3552. if (ctype && ctcap)
  3553. ctype[0] = '\0';
  3554. if (url[0] == '/') {
  3555. char pathbuf[BR_URL_MAX];
  3556. const char *open_url = url;
  3557. unsigned int i = 0;
  3558. /* A local form GET keeps ?query in the address bar but the
  3559. * file lookup uses the path alone, like a real browser. */
  3560. while (url[i] && url[i] != '?' && url[i] != '#')
  3561. i++;
  3562. if (url[i]) {
  3563. s_copy(pathbuf, url, i + 1);
  3564. open_url = pathbuf;
  3565. }
  3566. buf = (unsigned char *)malloc(cap);
  3567. if (!buf) {
  3568. s_copy(err, "out of memory", errcap);
  3569. return -1;
  3570. }
  3571. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  3572. if (rv < 0) {
  3573. free(buf);
  3574. s_copy(err, "file not found", errcap);
  3575. return -1;
  3576. }
  3577. *out = buf;
  3578. *outlen = (unsigned int)rv;
  3579. *is_local = 1;
  3580. if (ctype)
  3581. s_copy(ctype, "text/html", ctcap);
  3582. if (final)
  3583. s_copy(final, url, finalcap);
  3584. if ((unsigned int)rv == cap)
  3585. *truncated = 1;
  3586. return 0;
  3587. }
  3588. buf = (unsigned char *)malloc(cap);
  3589. if (!buf) {
  3590. s_copy(err, "out of memory", errcap);
  3591. return -1;
  3592. }
  3593. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3594. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3595. if (rv == FETCH_ABORT) {
  3596. free(buf);
  3597. return FETCH_ABORT;
  3598. }
  3599. if (rv < 0) {
  3600. free(buf);
  3601. return -1;
  3602. }
  3603. len = (unsigned int)rv;
  3604. if (len == 0) {
  3605. free(buf);
  3606. s_copy(err, "empty response", errcap);
  3607. return -1;
  3608. }
  3609. if (ctype)
  3610. s_copy(ctype, fetch_meta.ctype, ctcap);
  3611. if (final && fetch_meta.final[0])
  3612. s_copy(final, fetch_meta.final, finalcap);
  3613. *is_local = 0;
  3614. *out = buf;
  3615. *outlen = len;
  3616. *truncated = tr;
  3617. return 0;
  3618. }
  3619. /* Load every @font-face the parser registered. Local files go through
  3620. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  3621. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  3622. * to the built-in regular/bold/italic/mono set. */
  3623. static void load_font_faces(void)
  3624. {
  3625. unsigned int i;
  3626. memset(font_faces, 0, sizeof(font_faces));
  3627. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  3628. i <= BR_MAX_FACES; i++) {
  3629. const char *url = br_font_face_url((int)i);
  3630. const char *base = br_font_face_base((int)i);
  3631. char abs[BR_URL_MAX];
  3632. if (!url || !url[0])
  3633. continue;
  3634. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  3635. sizeof(abs)) != 0)
  3636. continue;
  3637. if (abs[0] == '/') {
  3638. font_faces[i - 1] = ufont_face_open_path(abs);
  3639. } else if (is_http(abs)) {
  3640. unsigned char *buf;
  3641. char err[64];
  3642. int rv, tr = 0;
  3643. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  3644. if (!buf)
  3645. continue;
  3646. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3647. UFONT_MAX_FILE, image_io_buf,
  3648. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  3649. err, sizeof(err));
  3650. if (rv > 0)
  3651. font_faces[i - 1] = ufont_face_open_mem(buf,
  3652. rv);
  3653. free(buf);
  3654. }
  3655. }
  3656. }
  3657. /* Remote scripts are cached under /share for the current boot, like the
  3658. * stylesheet cache, so reloads and later visits skip the network. */
  3659. static int script_cache_count;
  3660. static unsigned int script_cache_hash(const char *s)
  3661. {
  3662. unsigned int h = 2166136261u;
  3663. while (*s) {
  3664. h ^= (unsigned char)*s++;
  3665. h *= 16777619u;
  3666. }
  3667. return h;
  3668. }
  3669. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3670. {
  3671. unsigned int n = 0;
  3672. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3673. s_append_dec(out, &n, script_cache_hash(url), cap);
  3674. }
  3675. static void script_cache_clear(void)
  3676. {
  3677. struct sys_dirent d;
  3678. char path[96];
  3679. for (;;) {
  3680. int i, found = 0;
  3681. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3682. (int)&d) == 1; i++) {
  3683. unsigned int n = 0;
  3684. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3685. continue;
  3686. s_append(path, &n, "/share/", sizeof(path));
  3687. s_append(path, &n, d.name, sizeof(path));
  3688. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3689. return;
  3690. found = 1;
  3691. break;
  3692. }
  3693. if (!found)
  3694. break;
  3695. }
  3696. script_cache_count = 0;
  3697. }
  3698. static void script_cache_init(void)
  3699. {
  3700. struct sys_dirent d;
  3701. int i, count = 0;
  3702. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3703. (int)&d) == 1; i++)
  3704. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3705. count++;
  3706. if (count >= SCRIPT_CACHE_MAX) {
  3707. script_cache_clear();
  3708. return;
  3709. }
  3710. script_cache_count = count;
  3711. }
  3712. static int script_cache_get(const char *url, unsigned char **out,
  3713. unsigned int *outlen)
  3714. {
  3715. char path[96];
  3716. struct sys_stat st;
  3717. unsigned char *buf;
  3718. int rn;
  3719. script_cache_path(url, path, sizeof(path));
  3720. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3721. st.size >= SCRIPT_CACHE_FILE_MAX)
  3722. return 0;
  3723. buf = (unsigned char *)malloc(st.size + 1);
  3724. if (!buf)
  3725. return 0;
  3726. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3727. if (rn != (int)st.size) {
  3728. free(buf);
  3729. return 0;
  3730. }
  3731. buf[st.size] = '\0';
  3732. *out = buf;
  3733. *outlen = st.size;
  3734. return 1;
  3735. }
  3736. static void script_cache_put(const char *url, const unsigned char *data,
  3737. unsigned int len)
  3738. {
  3739. char path[96];
  3740. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3741. len >= SCRIPT_CACHE_FILE_MAX)
  3742. return;
  3743. script_cache_path(url, path, sizeof(path));
  3744. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3745. (int)len) >= 0)
  3746. script_cache_count++;
  3747. }
  3748. static int script_cache_has(const char *url)
  3749. {
  3750. char path[96];
  3751. struct sys_stat st;
  3752. script_cache_path(url, path, sizeof(path));
  3753. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3754. st.size < SCRIPT_CACHE_FILE_MAX;
  3755. }
  3756. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3757. static int fetch_script_text(const char *url, unsigned char **out,
  3758. unsigned int *outlen, char *err,
  3759. unsigned int errcap)
  3760. {
  3761. unsigned char *buf;
  3762. unsigned int len;
  3763. int local, truncated = 0;
  3764. char ctype[64], final[BR_URL_MAX];
  3765. int rv;
  3766. *out = 0;
  3767. *outlen = 0;
  3768. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3769. return 0;
  3770. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3771. sizeof(ctype), final, sizeof(final), err, errcap,
  3772. &truncated, 0, 0);
  3773. if (rv != 0)
  3774. return rv;
  3775. if (truncated || len >= BR_SCRIPT_MAX) {
  3776. free(buf);
  3777. s_copy(err, "script is too large", errcap);
  3778. return -1;
  3779. }
  3780. buf[len] = '\0';
  3781. if (!local)
  3782. script_cache_put(url, buf, len);
  3783. *out = buf;
  3784. *outlen = len;
  3785. return 0;
  3786. }
  3787. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  3788. * the heap, so images must not allocate their file body from it as well. */
  3789. static int fetch_image(const char *url, unsigned int cap,
  3790. unsigned char **out, unsigned int *outlen,
  3791. char *err, unsigned int errcap)
  3792. {
  3793. unsigned int len;
  3794. int tr = 0;
  3795. int rv;
  3796. *out = 0;
  3797. *outlen = 0;
  3798. if (cap > BR_IMG_FILE_MAX)
  3799. cap = BR_IMG_FILE_MAX;
  3800. if (url[0] == '/') {
  3801. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  3802. (int)cap);
  3803. if (rv < 0) {
  3804. s_copy(err, "file not found", errcap);
  3805. return -1;
  3806. }
  3807. *out = image_file_buf;
  3808. *outlen = (unsigned int)rv;
  3809. return 0;
  3810. }
  3811. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  3812. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  3813. if (rv == FETCH_ABORT)
  3814. return FETCH_ABORT;
  3815. if (rv < 0)
  3816. return -1;
  3817. len = (unsigned int)rv;
  3818. if (len == 0) {
  3819. s_copy(err, "empty image", errcap);
  3820. return -1;
  3821. }
  3822. *out = image_file_buf;
  3823. *outlen = len;
  3824. return 0;
  3825. }
  3826. /* Remote stylesheets are immutable enough for the current boot: keep
  3827. * successful responses under /share so a reload, a second visit or a fresh
  3828. * browser launch does not fetch the same five sheets over the network again.
  3829. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  3830. static int css_cache_count;
  3831. static unsigned int css_cache_hash(const char *s)
  3832. {
  3833. unsigned int h = 2166136261u;
  3834. while (*s) {
  3835. h ^= (unsigned char)*s++;
  3836. h *= 16777619u;
  3837. }
  3838. return h;
  3839. }
  3840. static void css_cache_path(const char *url, char *out, unsigned int cap)
  3841. {
  3842. unsigned int n = 0;
  3843. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  3844. s_append_dec(out, &n, css_cache_hash(url), cap);
  3845. }
  3846. static void css_cache_clear(void)
  3847. {
  3848. struct sys_dirent d;
  3849. char path[96];
  3850. for (;;) {
  3851. int i, found = 0;
  3852. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3853. (int)&d) == 1; i++) {
  3854. unsigned int n = 0;
  3855. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  3856. continue;
  3857. s_append(path, &n, "/share/", sizeof(path));
  3858. s_append(path, &n, d.name, sizeof(path));
  3859. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3860. return;
  3861. found = 1;
  3862. break;
  3863. }
  3864. if (!found)
  3865. break;
  3866. }
  3867. css_cache_count = 0;
  3868. }
  3869. static void css_cache_init(void)
  3870. {
  3871. struct sys_dirent d;
  3872. int i, count = 0;
  3873. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3874. (int)&d) == 1; i++)
  3875. if (starts_with(d.name, CSS_CACHE_PREFIX))
  3876. count++;
  3877. if (count >= CSS_CACHE_MAX) {
  3878. css_cache_clear();
  3879. return;
  3880. }
  3881. css_cache_count = count;
  3882. }
  3883. static int css_cache_get(const char *url, unsigned char **out,
  3884. unsigned int *outlen)
  3885. {
  3886. char path[96];
  3887. int rn;
  3888. css_cache_path(url, path, sizeof(path));
  3889. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  3890. (int)CSS_CACHE_FILE_MAX);
  3891. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  3892. return 0;
  3893. *out = image_io_buf;
  3894. *outlen = (unsigned int)rn;
  3895. return 1;
  3896. }
  3897. static void css_cache_put(const char *url, const unsigned char *data,
  3898. unsigned int len)
  3899. {
  3900. char path[96];
  3901. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  3902. len >= CSS_CACHE_FILE_MAX)
  3903. return;
  3904. css_cache_path(url, path, sizeof(path));
  3905. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3906. (int)len) >= 0)
  3907. css_cache_count++;
  3908. }
  3909. static int css_cache_has(const char *url)
  3910. {
  3911. char path[96];
  3912. struct sys_stat st;
  3913. css_cache_path(url, path, sizeof(path));
  3914. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3915. st.size < CSS_CACHE_FILE_MAX;
  3916. }
  3917. /* Read one stylesheet into the shared static buffer. CSS is parsed
  3918. * immediately, so it does not need the page heap; this leaves the heap for
  3919. * the 2 MB page body, the rules and the scaled image bitmaps. */
  3920. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  3921. char *err, unsigned int errcap)
  3922. {
  3923. unsigned int len;
  3924. int tr = 0;
  3925. int rv;
  3926. *out = 0;
  3927. *outlen = 0;
  3928. if (url[0] == '/') {
  3929. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  3930. (int)BR_CSS_MAX);
  3931. if (rv < 0) {
  3932. s_copy(err, "stylesheet not found", errcap);
  3933. return -1;
  3934. }
  3935. *out = image_io_buf;
  3936. *outlen = (unsigned int)rv;
  3937. return 0;
  3938. }
  3939. if (css_cache_get(url, out, outlen))
  3940. return 0;
  3941. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  3942. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  3943. &fetch_meta, &tr, err, errcap);
  3944. if (rv == FETCH_ABORT)
  3945. return FETCH_ABORT;
  3946. if (rv < 0)
  3947. return -1;
  3948. len = (unsigned int)rv;
  3949. if (len == 0) {
  3950. s_copy(err, "empty stylesheet", errcap);
  3951. return -1;
  3952. }
  3953. *out = image_io_buf;
  3954. *outlen = len;
  3955. css_cache_put(url, image_io_buf, len);
  3956. return 0;
  3957. }
  3958. static void redraw_now(void);
  3959. static char error_page[1024];
  3960. static void show_error(const char *title, const char *detail)
  3961. {
  3962. char *page = error_page;
  3963. unsigned int n = 0;
  3964. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  3965. s_append(page, &n, title, sizeof(error_page));
  3966. s_append(page, &n, "</h2><p>", sizeof(error_page));
  3967. {
  3968. const char *p = detail;
  3969. while (*p && n + 1 < sizeof(error_page)) {
  3970. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  3971. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  3972. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  3973. else page[n++] = *p;
  3974. p++;
  3975. }
  3976. }
  3977. page[n] = '\0';
  3978. s_append(page, &n, "</p><p>", sizeof(error_page));
  3979. s_append(page, &n, page_url, sizeof(error_page));
  3980. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  3981. sizeof(error_page));
  3982. br_parse(&doc, page, n);
  3983. layout_valid = 0;
  3984. preload_active = 0;
  3985. preload_pending = 0;
  3986. preload_wait = 0;
  3987. fetch_workers_cancel_busy();
  3988. s_copy(page_title, title, sizeof(page_title));
  3989. page_loading = 0;
  3990. set_status(title, 1, 0);
  3991. ngui_invalidate(&ui);
  3992. }
  3993. static int decode_direct_image(const unsigned char *data, unsigned int len,
  3994. unsigned int node)
  3995. {
  3996. if (image_count >= BR_MAX_IMAGES)
  3997. return -1;
  3998. if (decode_image_data(data, len, &images[0], 0, 0, 0, 0) != 0)
  3999. return -1;
  4000. doc.nodes[node].img_index = 0;
  4001. image_count = 1;
  4002. return 0;
  4003. }
  4004. static int ancestor_is(unsigned int node, unsigned int tag)
  4005. {
  4006. unsigned int p = doc.nodes[node].parent;
  4007. while (p) {
  4008. if (doc.nodes[p].tag == tag)
  4009. return 1;
  4010. p = doc.nodes[p].parent;
  4011. }
  4012. return 0;
  4013. }
  4014. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  4015. * parallel but parsed in document order, so the cascade is unchanged. */
  4016. static int load_stylesheets(void)
  4017. {
  4018. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  4019. static unsigned char remote[BR_MAX_SHEETS];
  4020. struct fetch_worker *slot[BR_MAX_SHEETS];
  4021. unsigned int i, n = 0, next = 0, k;
  4022. char err[64];
  4023. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  4024. struct br_node *nd = &doc.nodes[i];
  4025. const char *rel, *href;
  4026. char url[BR_URL_MAX];
  4027. int dup = 0;
  4028. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  4029. continue;
  4030. rel = br_rel(&doc, i);
  4031. if (!contains_ci(rel, "stylesheet"))
  4032. continue;
  4033. href = br_href(&doc, i);
  4034. if (!href[0])
  4035. continue;
  4036. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  4037. continue;
  4038. for (k = 0; k < n; k++)
  4039. if (s_eq(urls[k], url)) {
  4040. dup = 1;
  4041. break;
  4042. }
  4043. if (dup)
  4044. continue;
  4045. s_copy(urls[n], url, BR_URL_MAX);
  4046. remote[n] = url[0] != '/' && !css_cache_has(url);
  4047. n++;
  4048. }
  4049. for (i = 0; i < BR_MAX_SHEETS; i++)
  4050. slot[i] = 0;
  4051. /* Start as many remote sheets as there are free workers. */
  4052. for (; next < n; next++) {
  4053. struct fetch_worker *w;
  4054. if (!remote[next])
  4055. continue;
  4056. w = fetch_worker_alloc();
  4057. if (!w)
  4058. break;
  4059. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  4060. err, sizeof(err)) != 0) {
  4061. fetch_worker_release(w);
  4062. remote[next] = 0;
  4063. continue;
  4064. }
  4065. slot[next] = w;
  4066. }
  4067. for (i = 0; i < n; i++) {
  4068. unsigned char *data = 0;
  4069. unsigned int len = 0;
  4070. int rv;
  4071. if (!remote[i]) {
  4072. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  4073. if (rv == FETCH_ABORT) {
  4074. fetch_workers_stop_all();
  4075. return FETCH_ABORT;
  4076. }
  4077. if (rv != 0 || !len)
  4078. continue;
  4079. } else {
  4080. struct fetch_worker *w = slot[i];
  4081. int tr = 0;
  4082. if (!w) {
  4083. w = fetch_worker_alloc();
  4084. if (!w) {
  4085. rv = -1;
  4086. goto css_failed;
  4087. }
  4088. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  4089. 0, 0, 0, 0, err,
  4090. sizeof(err)) != 0) {
  4091. fetch_worker_release(w);
  4092. remote[i] = 0;
  4093. if (i == next)
  4094. next++;
  4095. continue;
  4096. }
  4097. slot[i] = w;
  4098. if (i == next)
  4099. next++;
  4100. }
  4101. rv = fetch_worker_wait(w, err, sizeof(err));
  4102. if (rv == FETCH_ABORT) {
  4103. fetch_workers_stop_all();
  4104. return FETCH_ABORT;
  4105. }
  4106. if (rv == 0)
  4107. rv = fetch_worker_read_body(w, image_io_buf,
  4108. BR_CSS_MAX,
  4109. image_io_buf + BR_CSS_MAX,
  4110. BR_CSS_COMP_MAX, &tr,
  4111. err, sizeof(err));
  4112. else
  4113. rv = -1;
  4114. fetch_worker_release(w);
  4115. slot[i] = 0;
  4116. /* Refill the worker window before parsing this sheet. */
  4117. for (; next < n; next++) {
  4118. struct fetch_worker *nw;
  4119. if (!remote[next])
  4120. continue;
  4121. nw = fetch_worker_alloc();
  4122. if (!nw)
  4123. break;
  4124. if (fetch_worker_submit(nw, urls[next],
  4125. BR_CSS_MAX, 0, 0, 0, 0,
  4126. err, sizeof(err)) != 0) {
  4127. fetch_worker_release(nw);
  4128. remote[next] = 0;
  4129. continue;
  4130. }
  4131. slot[next] = nw;
  4132. }
  4133. css_failed:
  4134. if (rv <= 0) {
  4135. /* One synchronous retry: a dropped sheet leaves the
  4136. * whole page unstyled (seen intermittently on
  4137. * arstechnica's CDN). */
  4138. u_puts("[css] retry ");
  4139. u_puts(urls[i]);
  4140. u_puts(": ");
  4141. u_puts(err[0] ? err : "no worker/empty body");
  4142. u_putc('\n');
  4143. err[0] = '\0';
  4144. rv = fetch_css(urls[i], &data, &len, err,
  4145. sizeof(err));
  4146. if (rv == FETCH_ABORT) {
  4147. fetch_workers_stop_all();
  4148. return FETCH_ABORT;
  4149. }
  4150. if (rv != 0 || !len) {
  4151. u_puts("[css] failed: ");
  4152. u_puts(err);
  4153. u_putc('\n');
  4154. continue;
  4155. }
  4156. } else {
  4157. len = (unsigned int)rv;
  4158. data = image_io_buf;
  4159. css_cache_put(urls[i], data, len);
  4160. }
  4161. }
  4162. if (len) {
  4163. br_set_font_base(urls[i]);
  4164. br_parse_css_text(&doc, (const char *)data, len);
  4165. }
  4166. }
  4167. br_set_font_base(page_url);
  4168. br_parse_inline_css(&doc);
  4169. load_font_faces();
  4170. br_reset_styles(&doc);
  4171. layout_valid = 0;
  4172. return 0;
  4173. }
  4174. static void preload_begin(void)
  4175. {
  4176. preload_active = 1;
  4177. preload_pending = 0;
  4178. preload_wait = 1;
  4179. preload_max_jobs = FETCH_WORKERS;
  4180. preload_node = 0;
  4181. preload_loaded = 0;
  4182. preload_scroll = 0;
  4183. img_stat_start = u_ticks_ms();
  4184. img_stat_wall = 0;
  4185. img_stat_net = img_stat_open = img_stat_first = 0;
  4186. img_stat_io = img_stat_dec = img_stat_scale = 0;
  4187. img_stat_paint = img_stat_reflow = 0;
  4188. img_stat_bytes = 0;
  4189. img_stat_n = 0;
  4190. img_stat_log_len = 0;
  4191. if (img_stat_log[0])
  4192. img_stat_log[0] = '\0';
  4193. img_repaint_ms = 0;
  4194. img_repaint_pending = 0;
  4195. }
  4196. /* Styles are computed top-down during layout, but images inside a hidden
  4197. * menu/carousel are never visited and keep img_top == 0. Without this check
  4198. * the preloader walks the DOM in node order and spends the whole image
  4199. * budget on logos and off-canvas thumbnails the reader cannot see. */
  4200. static struct br_style base_style(void);
  4201. static int node_hidden(unsigned int node)
  4202. {
  4203. unsigned int path[32], n = 0, p = node, i;
  4204. struct br_style st, parent;
  4205. while (p && n < sizeof(path) / sizeof(path[0])) {
  4206. path[n++] = p;
  4207. p = doc.nodes[p].parent;
  4208. }
  4209. /* Node 0 is the <html> element when the page starts with one: it
  4210. * is an ancestor too. Styles are cached per node, so the chain
  4211. * must start from the same base as style_for_node(); seeding it
  4212. * with a zeroed style left <body> cached with black text and no
  4213. * line-height once an image job ran (docs.cloudron.io). */
  4214. if (!p && n && n < sizeof(path) / sizeof(path[0]) &&
  4215. doc.nodes[0].type == BR_NODE_ELEM &&
  4216. doc.nodes[0].tag == BR_TAG_HTML &&
  4217. !(doc.nodes[path[n - 1]].flags & BR_NODE_DETACHED))
  4218. path[n++] = 0;
  4219. parent = base_style();
  4220. for (i = n; i > 0; i--) {
  4221. br_style_for(&doc, path[i - 1], &parent, &st);
  4222. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  4223. st.opacity_hidden)
  4224. return 1;
  4225. parent = st;
  4226. }
  4227. return 0;
  4228. }
  4229. static struct br_style base_style(void);
  4230. static int style_width_px(const struct br_style *st, int base);
  4231. static int style_height_px(const struct br_style *st, int base);
  4232. static void style_for_node(unsigned int node, struct br_style *out)
  4233. {
  4234. unsigned int p = doc.nodes[node].parent;
  4235. struct br_style parent;
  4236. /* Parent index 0 is ambiguous: it is the <html> element when the page
  4237. * starts with one (see root_style()), but also the parent field of a
  4238. * detached subtree root. */
  4239. if (p || (node != 0 && doc.nodes[0].type == BR_NODE_ELEM &&
  4240. doc.nodes[0].tag == BR_TAG_HTML &&
  4241. !(doc.nodes[node].flags & BR_NODE_DETACHED))) {
  4242. style_for_node(p, &parent);
  4243. br_style_for(&doc, node, &parent, out);
  4244. } else {
  4245. parent = base_style();
  4246. br_style_for(&doc, node, &parent, out);
  4247. }
  4248. }
  4249. /* ---- parallel image preloading ---- *
  4250. *
  4251. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  4252. * preload_step() only starts jobs and harvests completed ones; the browser
  4253. * main loop keeps drawing between calls, instead of blocking on one fetch.
  4254. */
  4255. static int preload_active_jobs(void)
  4256. {
  4257. int i, n = 0;
  4258. for (i = 0; i < FETCH_WORKERS; i++)
  4259. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  4260. n++;
  4261. return n;
  4262. }
  4263. static void preload_job_error(struct fetch_worker *w)
  4264. {
  4265. if (w->node < doc.nnode) {
  4266. if (w->bg)
  4267. doc.nodes[w->node].bg_img_index = -2;
  4268. else
  4269. doc.nodes[w->node].img_index = -2;
  4270. image_repaint();
  4271. }
  4272. }
  4273. /* Is the image's box anywhere near the visible page? A decode below the
  4274. * fold changes the layout (scroll extent) but not a single on-screen pixel,
  4275. * so it does not need a repaint. top/h come from the last layout; treat an
  4276. * unknown box as visible to stay safe. */
  4277. static int image_preload_visible(unsigned int node, int bg)
  4278. {
  4279. int top, h, scroll;
  4280. if (node >= BR_MAX_NODES || node >= doc.nnode || page_rect.h <= 0)
  4281. return 1;
  4282. if (bg) {
  4283. top = (int)block_top[node];
  4284. h = (int)block_h[node];
  4285. } else {
  4286. top = (int)img_top[node];
  4287. h = (int)img_h[node];
  4288. }
  4289. if (!top && !h)
  4290. return 1;
  4291. scroll = (int)page_scroll.offset;
  4292. if (top > scroll + page_rect.h + 160)
  4293. return 0;
  4294. if (top + h + 160 < scroll)
  4295. return 0;
  4296. return 1;
  4297. }
  4298. /* Upper bounds for the bitmap an <img> will paint. Zero means "unbounded";
  4299. * decode_image_data applies one scale to both axes so the aspect ratio is
  4300. * preserved. This is what keeps a 1200x800 photo that CSS paints at 400 px
  4301. * from being decoded and box-filtered to the 1000 px layout cap first. */
  4302. static void image_fit_size(unsigned int node, int *out_w, int *out_h)
  4303. {
  4304. struct br_style st;
  4305. struct br_node *nd;
  4306. unsigned int p;
  4307. int cw, w = 0, h = 0;
  4308. *out_w = *out_h = 0;
  4309. if (node >= doc.nnode)
  4310. return;
  4311. nd = &doc.nodes[node];
  4312. style_for_node(node, &st);
  4313. cw = page_rect.w > 24 ? page_rect.w - 24 : 0;
  4314. p = doc.nodes[node].parent;
  4315. if (p && p < BR_MAX_NODES && layout_boxes[p].valid &&
  4316. layout_boxes[p].w > 0 && layout_boxes[p].w < cw)
  4317. cw = layout_boxes[p].w;
  4318. if (st.width_kind)
  4319. w = style_width_px(&st, cw);
  4320. else if (nd->width_attr)
  4321. w = nd->width_pct ? cw * (int)nd->width_attr / 100 :
  4322. (int)nd->width_attr;
  4323. if (st.height_kind)
  4324. h = style_height_px(&st, cw);
  4325. else if (nd->height_attr)
  4326. h = nd->height_pct ? cw * (int)nd->height_attr / 100 :
  4327. (int)nd->height_attr;
  4328. if (st.max_width_kind) {
  4329. int mw = st.max_width_kind == 3 ?
  4330. cw * st.max_width_calc_pct / 100 +
  4331. st.max_width_calc_px :
  4332. st.max_width_kind == 2 ?
  4333. cw * (int)st.max_width / 100 :
  4334. (int)st.max_width;
  4335. if (mw > 0 && (w == 0 || w > mw))
  4336. w = mw;
  4337. }
  4338. if (st.max_height_kind) {
  4339. int mh = st.max_height_kind == 3 ?
  4340. cw * st.max_height_calc_pct / 100 +
  4341. st.max_height_calc_px :
  4342. st.max_height_kind == 2 ?
  4343. cw * (int)st.max_height / 100 :
  4344. (int)st.max_height;
  4345. if (mh > 0 && (h == 0 || h > mh))
  4346. h = mh;
  4347. }
  4348. if (w > BR_IMG_LAYOUT_W)
  4349. w = BR_IMG_LAYOUT_W;
  4350. if (h > 4096)
  4351. h = 4096;
  4352. if (w < 0)
  4353. w = 0;
  4354. if (h < 0)
  4355. h = 0;
  4356. *out_w = w;
  4357. *out_h = h;
  4358. }
  4359. static void preload_accept_image(unsigned int node, int bg, const char *url)
  4360. {
  4361. /* An <img> bitmap only depends on its URL, so the next <img> with the
  4362. * same source reuses it (heise repeats one comment icon 85 times).
  4363. * Backgrounds are scaled to their box and are not shared. */
  4364. images[image_count].url_hash =
  4365. !bg && url ? script_cache_hash(url) | 1u : 0;
  4366. if (bg)
  4367. doc.nodes[node].bg_img_index = (short)image_count;
  4368. else
  4369. doc.nodes[node].img_index = (short)image_count;
  4370. image_count++;
  4371. preload_loaded++;
  4372. /* A background bitmap never changes its box, so keep the (expensive)
  4373. * measured layout and only repaint the pixels. */
  4374. if (bg)
  4375. page_cache_valid = 0;
  4376. else
  4377. layout_valid = 0;
  4378. if (image_preload_visible(node, bg))
  4379. image_repaint();
  4380. }
  4381. /* Install a bitmap decoded by the fetch helper. The helper already applied
  4382. * the display bounds (and the JPEG reduced IDCT), so this is a read + copy
  4383. * on the UI thread instead of a decode. */
  4384. static int preload_store_helper(unsigned int node, int bg,
  4385. unsigned char *px, unsigned int pxlen,
  4386. unsigned int dw, unsigned int dh,
  4387. int alpha, unsigned int nw, unsigned int nh,
  4388. const char *url)
  4389. {
  4390. struct br_image *bi;
  4391. unsigned int npx;
  4392. if (image_count >= BR_MAX_IMAGES || !px || !dw || !dh ||
  4393. dw > 4096 || dh > 4096) {
  4394. free(px);
  4395. return -1;
  4396. }
  4397. npx = dw * dh;
  4398. if (image_pixels + npx > BR_IMG_PIXEL_BUDGET ||
  4399. pxlen < npx * 2u + (alpha ? npx : 0)) {
  4400. free(px);
  4401. return -1;
  4402. }
  4403. bi = &images[image_count];
  4404. bi->img.format = 0;
  4405. bi->img.w = dw;
  4406. bi->img.h = dh;
  4407. bi->img.px = (unsigned short *)px;
  4408. bi->img.alpha = alpha ? px + npx * 2u : 0;
  4409. bi->img.flags = 0;
  4410. bi->native_w = nw ? (int)nw : (int)dw;
  4411. bi->native_h = nh ? (int)nh : (int)dh;
  4412. bi->state = 1;
  4413. image_pixels += npx;
  4414. preload_accept_image(node, bg, url);
  4415. return 0;
  4416. }
  4417. static void preload_decode(unsigned int node, int bg,
  4418. const unsigned char *data, unsigned int len,
  4419. const char *url)
  4420. {
  4421. int fit_w = 0, fit_h = 0;
  4422. if (image_count >= BR_MAX_IMAGES) {
  4423. if (bg)
  4424. doc.nodes[node].bg_img_index = -2;
  4425. else
  4426. doc.nodes[node].img_index = -2;
  4427. return;
  4428. }
  4429. if (!bg)
  4430. image_fit_size(node, &fit_w, &fit_h);
  4431. if (decode_image_data(data, len, &images[image_count],
  4432. bg && node < BR_MAX_NODES &&
  4433. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  4434. bg && node < BR_MAX_NODES &&
  4435. layout_boxes[node].valid ? layout_boxes[node].h : 0,
  4436. fit_w, fit_h) == 0) {
  4437. preload_accept_image(node, bg, url);
  4438. } else {
  4439. if (bg)
  4440. doc.nodes[node].bg_img_index = -2;
  4441. else
  4442. doc.nodes[node].img_index = -2;
  4443. layout_valid = 0;
  4444. }
  4445. if (image_preload_visible(node, bg))
  4446. image_repaint();
  4447. }
  4448. /* ---- data: URLs ----
  4449. *
  4450. * `data:[<type>][;base64],<payload>` decoded to bytes from the page heap
  4451. * (the caller frees them). The payload is percent-decoded, then base64-
  4452. * decoded when the header says so. Infima's menu chevron and many icon
  4453. * fonts' fallbacks are inline SVGs written this way. */
  4454. static int b64_val(int c)
  4455. {
  4456. if (c >= 'A' && c <= 'Z') return c - 'A';
  4457. if (c >= 'a' && c <= 'z') return c - 'a' + 26;
  4458. if (c >= '0' && c <= '9') return c - '0' + 52;
  4459. if (c == '+' || c == '-') return 62;
  4460. if (c == '/' || c == '_') return 63;
  4461. return -1;
  4462. }
  4463. static int hex_val(int c)
  4464. {
  4465. if (c >= '0' && c <= '9') return c - '0';
  4466. c |= 32;
  4467. if (c >= 'a' && c <= 'f') return c - 'a' + 10;
  4468. return -1;
  4469. }
  4470. static int data_url_decode(const char *url, unsigned char **out,
  4471. unsigned int *out_len)
  4472. {
  4473. const char *comma, *p;
  4474. unsigned int n = 0, len, i;
  4475. unsigned char *buf;
  4476. int base64 = 0;
  4477. *out = 0;
  4478. *out_len = 0;
  4479. if (!starts_with(url, "data:"))
  4480. return -1;
  4481. comma = url + 5;
  4482. while (*comma && *comma != ',')
  4483. comma++;
  4484. if (!*comma)
  4485. return -1;
  4486. for (p = url + 5; p + 7 <= comma; p++)
  4487. if (!strncmp(p, ";base64", 7))
  4488. base64 = 1;
  4489. len = s_len(comma + 1);
  4490. buf = (unsigned char *)malloc(len + 1);
  4491. if (!buf)
  4492. return -1;
  4493. for (i = 0, p = comma + 1; i < len; i++) {
  4494. int c = (unsigned char)p[i];
  4495. if (c == '%' && i + 2 < len &&
  4496. hex_val(p[i + 1]) >= 0 && hex_val(p[i + 2]) >= 0) {
  4497. c = hex_val(p[i + 1]) * 16 + hex_val(p[i + 2]);
  4498. i += 2;
  4499. }
  4500. buf[n++] = (unsigned char)c;
  4501. }
  4502. if (base64) {
  4503. unsigned int acc = 0, o = 0;
  4504. int bits = 0;
  4505. for (i = 0; i < n; i++) {
  4506. int v = b64_val(buf[i]);
  4507. if (v < 0)
  4508. continue; /* padding, whitespace */
  4509. acc = (acc << 6) | (unsigned int)v;
  4510. bits += 6;
  4511. if (bits >= 8) {
  4512. bits -= 8;
  4513. buf[o++] = (unsigned char)(acc >> bits);
  4514. }
  4515. }
  4516. n = o;
  4517. }
  4518. buf[n] = 0;
  4519. *out = buf;
  4520. *out_len = n;
  4521. return 0;
  4522. }
  4523. static unsigned int data_img_key(const char *url, int w, int h)
  4524. {
  4525. return (script_cache_hash(url) ^ ((unsigned int)w * 2654435761u) ^
  4526. ((unsigned int)h * 40503u)) | 1u;
  4527. }
  4528. /* The image index of a data: URL decoded for a w x h box (an SVG is
  4529. * rasterized at that size), decoding it on first use; -1 on failure.
  4530. * Decoded bitmaps are found again through url_hash, which is distinct
  4531. * from the <img> sharing hash because it mixes in the size. */
  4532. static int data_url_image(const char *url, int w, int h)
  4533. {
  4534. unsigned int key, len;
  4535. unsigned char *data;
  4536. int i;
  4537. if (!starts_with(url, "data:") || w <= 0 || h <= 0)
  4538. return -1;
  4539. key = data_img_key(url, w, h);
  4540. for (i = 0; i < image_count; i++)
  4541. if (images[i].state == 1 && images[i].url_hash == key)
  4542. return i;
  4543. for (i = 0; i < data_img_nfail; i++)
  4544. if (data_img_fail[i] == key)
  4545. return -1;
  4546. if (image_count < BR_MAX_IMAGES &&
  4547. data_url_decode(url, &data, &len) == 0) {
  4548. int r = decode_image_data(data, len, &images[image_count],
  4549. w, h, w, h);
  4550. free(data);
  4551. if (r == 0) {
  4552. images[image_count].url_hash = key;
  4553. return image_count++;
  4554. }
  4555. }
  4556. if (data_img_nfail < DATA_IMG_FAIL_MAX)
  4557. data_img_fail[data_img_nfail++] = key;
  4558. return -1;
  4559. }
  4560. /* A local file image bypasses the helpers: count its decode so a page opened
  4561. * from /share or /data still produces the same timing breakdown. */
  4562. static void img_stat_local(int before, unsigned int bytes, unsigned int io_ms)
  4563. {
  4564. img_stat_n++;
  4565. img_stat_bytes += bytes;
  4566. img_stat_io += io_ms;
  4567. if (image_count > before) {
  4568. struct br_image *bi = &images[image_count - 1];
  4569. img_stat_dec += img_last_dec_ms;
  4570. img_stat_scale += img_last_scale_ms;
  4571. if (img_stat_log_len + 100 < sizeof(img_stat_log)) {
  4572. unsigned int n = img_stat_log_len;
  4573. s_append(img_stat_log, &n, "local ", sizeof(img_stat_log));
  4574. s_append_dec(img_stat_log, &n, bytes,
  4575. sizeof(img_stat_log));
  4576. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4577. s_append_dec(img_stat_log, &n, img_last_dec_ms,
  4578. sizeof(img_stat_log));
  4579. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4580. s_append_dec(img_stat_log, &n, img_last_scale_ms,
  4581. sizeof(img_stat_log));
  4582. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4583. s_append_dec(img_stat_log, &n,
  4584. (unsigned int)bi->native_w,
  4585. sizeof(img_stat_log));
  4586. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4587. s_append_dec(img_stat_log, &n,
  4588. (unsigned int)bi->native_h,
  4589. sizeof(img_stat_log));
  4590. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4591. s_append_dec(img_stat_log, &n, bi->img.w,
  4592. sizeof(img_stat_log));
  4593. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4594. s_append_dec(img_stat_log, &n, bi->img.h,
  4595. sizeof(img_stat_log));
  4596. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4597. s_append_dec(img_stat_log, &n,
  4598. bi->img.alpha ? 1u : 0u,
  4599. sizeof(img_stat_log));
  4600. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4601. img_stat_log_len = n;
  4602. }
  4603. }
  4604. }
  4605. /* Harvest one completed worker. Returns 1 when a job was finished. */
  4606. static int preload_finish_worker(struct fetch_worker *w)
  4607. {
  4608. char err[64];
  4609. int rv, tr = 0;
  4610. unsigned int t0, io_ms;
  4611. int before;
  4612. int used_px = 0;
  4613. rv = fetch_worker_poll(w, err, sizeof(err));
  4614. if (rv < 0) {
  4615. /* A helper from an older pack does not understand the image
  4616. * decode request; retry once without it and decode in-process. */
  4617. if (w->image_job && w->dec_w && !w->dec_retried &&
  4618. fetch_worker_submit_req(w, w->url, BR_IMG_FILE_MAX,
  4619. 0, 0, 0, 0, w->node, w->bg,
  4620. 0, 0, err, sizeof(err)) == 0) {
  4621. w->image_job = 1;
  4622. w->dec_retried = 1;
  4623. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4624. return 0;
  4625. }
  4626. preload_job_error(w);
  4627. if (img_stat_log_len + 64 < sizeof(img_stat_log)) {
  4628. unsigned int n = img_stat_log_len;
  4629. char u[48];
  4630. s_copy(u, w->url, sizeof(u));
  4631. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4632. s_append(img_stat_log, &n, " error\n",
  4633. sizeof(img_stat_log));
  4634. img_stat_log_len = n;
  4635. }
  4636. img_stat_n++;
  4637. fetch_worker_release(w);
  4638. return 1;
  4639. }
  4640. if (rv == 0)
  4641. return 0;
  4642. t0 = u_ticks_ms();
  4643. rv = -1;
  4644. before = image_count;
  4645. if (w->m.px_len && !w->m.dec_err && w->m.dw && w->m.dh &&
  4646. w->m.px_len <= 8u * 1024u * 1024u) {
  4647. unsigned char *px = (unsigned char *)malloc(w->m.px_len);
  4648. int pr = -1;
  4649. if (px)
  4650. pr = u_syscall3(SYS_READ_FILE, (int)w->px, (int)px,
  4651. (int)w->m.px_len);
  4652. if (pr == (int)w->m.px_len) {
  4653. if (preload_store_helper(w->node, w->bg, px,
  4654. w->m.px_len, w->m.dw,
  4655. w->m.dh, (int)w->m.alpha,
  4656. w->m.nw, w->m.nh,
  4657. w->url) == 0) {
  4658. rv = (int)w->m.len;
  4659. img_last_dec_ms = w->m.dec_ms;
  4660. img_last_scale_ms = 0;
  4661. used_px = 1;
  4662. } else {
  4663. px = 0; /* the helper freed it */
  4664. }
  4665. }
  4666. if (px && !(pr == (int)w->m.px_len))
  4667. free(px);
  4668. }
  4669. io_ms = u_ticks_ms() - t0;
  4670. if (rv < 0) {
  4671. t0 = u_ticks_ms();
  4672. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  4673. image_comp_buf, BR_IMG_FILE_MAX,
  4674. &tr, err, sizeof(err));
  4675. io_ms += u_ticks_ms() - t0;
  4676. before = image_count;
  4677. if (rv >= 0)
  4678. preload_decode(w->node, w->bg, image_file_buf,
  4679. (unsigned int)rv, w->url);
  4680. else
  4681. preload_job_error(w);
  4682. }
  4683. img_stat_n++;
  4684. img_stat_net += w->m.total_ms;
  4685. img_stat_open += w->m.open_ms;
  4686. img_stat_first += w->m.first_ms;
  4687. img_stat_io += io_ms;
  4688. img_stat_bytes += rv > 0 ? (unsigned int)rv : 0;
  4689. img_stat_dec += w->m.dec_ms;
  4690. if (rv >= 0 && !used_px) {
  4691. img_stat_dec += img_last_dec_ms;
  4692. img_stat_scale += img_last_scale_ms;
  4693. }
  4694. if (img_stat_log_len + 160 < sizeof(img_stat_log)) {
  4695. unsigned int n = img_stat_log_len;
  4696. char u[48];
  4697. s_copy(u, w->url, sizeof(u));
  4698. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4699. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4700. s_append_dec(img_stat_log, &n,
  4701. rv > 0 ? (unsigned int)rv : 0,
  4702. sizeof(img_stat_log));
  4703. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4704. s_append_dec(img_stat_log, &n, w->m.open_ms,
  4705. sizeof(img_stat_log));
  4706. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4707. s_append_dec(img_stat_log, &n, w->m.first_ms,
  4708. sizeof(img_stat_log));
  4709. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4710. s_append_dec(img_stat_log, &n, w->m.total_ms,
  4711. sizeof(img_stat_log));
  4712. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4713. s_append_dec(img_stat_log, &n, io_ms, sizeof(img_stat_log));
  4714. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4715. s_append_dec(img_stat_log, &n,
  4716. rv >= 0 ? img_last_dec_ms : 0,
  4717. sizeof(img_stat_log));
  4718. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4719. s_append_dec(img_stat_log, &n,
  4720. rv >= 0 ? img_last_scale_ms : 0,
  4721. sizeof(img_stat_log));
  4722. if (image_count > before) {
  4723. struct br_image *bi = &images[image_count - 1];
  4724. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4725. s_append_dec(img_stat_log, &n,
  4726. (unsigned int)bi->native_w,
  4727. sizeof(img_stat_log));
  4728. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4729. s_append_dec(img_stat_log, &n,
  4730. (unsigned int)bi->native_h,
  4731. sizeof(img_stat_log));
  4732. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4733. s_append_dec(img_stat_log, &n, bi->img.w,
  4734. sizeof(img_stat_log));
  4735. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4736. s_append_dec(img_stat_log, &n, bi->img.h,
  4737. sizeof(img_stat_log));
  4738. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4739. s_append_dec(img_stat_log, &n,
  4740. bi->img.alpha ? 1u : 0u,
  4741. sizeof(img_stat_log));
  4742. }
  4743. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4744. img_stat_log_len = n;
  4745. }
  4746. fetch_worker_release(w);
  4747. return 1;
  4748. }
  4749. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  4750. * the number of jobs started. */
  4751. static int preload_fill_jobs(void)
  4752. {
  4753. int started = 0;
  4754. char err[64];
  4755. while (preload_active && preload_node < doc.nnode) {
  4756. unsigned int i = preload_node;
  4757. struct br_node *nd = &doc.nodes[i];
  4758. const char *src;
  4759. char url[BR_URL_MAX];
  4760. struct fetch_worker *w;
  4761. if (preload_active_jobs() >= preload_max_jobs)
  4762. break;
  4763. if (nd->type != BR_NODE_ELEM) {
  4764. preload_node++;
  4765. continue;
  4766. }
  4767. if (nd->tag != BR_TAG_IMG) {
  4768. if (nd->bg_img_index == -1) {
  4769. struct br_style bs;
  4770. style_for_node(i, &bs);
  4771. if (bs.display != BR_DISPLAY_NONE &&
  4772. !bs.vis_hidden && bs.bg_image) {
  4773. const char *bsrc =
  4774. br_bg_image_url(bs.bg_image - 1);
  4775. /* Lazy like <img>: a background box
  4776. * below the viewport (or not laid
  4777. * out yet) waits for the next scan. */
  4778. if (bsrc[0] &&
  4779. (!layout_boxes[i].valid ||
  4780. block_top[i] >
  4781. (unsigned int)(page_scroll.offset +
  4782. page_rect.h + 160))) {
  4783. preload_pending = 1;
  4784. preload_node++;
  4785. continue;
  4786. }
  4787. if (starts_with(bsrc, "data:")) {
  4788. /* Inline image: decode now,
  4789. * no fetch helper. */
  4790. unsigned char *data;
  4791. unsigned int len;
  4792. preload_node = i + 1;
  4793. if (data_url_decode(bsrc, &data,
  4794. &len) == 0) {
  4795. preload_decode(i, 1, data,
  4796. len, 0);
  4797. free(data);
  4798. } else {
  4799. nd->bg_img_index = -2;
  4800. }
  4801. continue;
  4802. }
  4803. if (bsrc[0] &&
  4804. resolve_link(page_url, bsrc, url,
  4805. sizeof(url)) == 0) {
  4806. if (image_count +
  4807. preload_active_jobs() >=
  4808. BR_MAX_IMAGES) {
  4809. preload_node = doc.nnode;
  4810. break;
  4811. }
  4812. if (url[0] == '/') {
  4813. unsigned char *data = 0;
  4814. unsigned int len = 0;
  4815. unsigned int t0;
  4816. int before;
  4817. preload_node = i + 1;
  4818. before = image_count;
  4819. t0 = u_ticks_ms();
  4820. if (fetch_image(url,
  4821. BR_IMG_FILE_MAX,
  4822. &data, &len,
  4823. err,
  4824. sizeof(err)) == 0) {
  4825. preload_decode(i, 1, data, len, 0);
  4826. img_stat_local(before, len,
  4827. u_ticks_ms() - t0);
  4828. } else {
  4829. nd->bg_img_index = -2;
  4830. }
  4831. continue;
  4832. }
  4833. w = fetch_worker_alloc();
  4834. if (!w)
  4835. return started;
  4836. preload_node = i + 1;
  4837. if (fetch_worker_submit(w, url,
  4838. BR_IMG_FILE_MAX,
  4839. 0, 0, i, 1,
  4840. err,
  4841. sizeof(err)) != 0) {
  4842. nd->bg_img_index = -2;
  4843. fetch_worker_release(w);
  4844. continue;
  4845. }
  4846. w->image_job = 1;
  4847. w->deadline = u_ticks_ms() +
  4848. BR_IMG_JOB_TIMEOUT_MS;
  4849. /* in flight: rescans skip it */
  4850. nd->bg_img_index = -3;
  4851. started++;
  4852. continue;
  4853. }
  4854. }
  4855. nd->bg_img_index = -2;
  4856. }
  4857. preload_node++;
  4858. continue;
  4859. }
  4860. if (nd->img_index != -1) {
  4861. preload_node++;
  4862. continue;
  4863. }
  4864. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  4865. preload_node++;
  4866. continue;
  4867. }
  4868. src = br_src(&doc, i);
  4869. if (starts_with(src, "data:")) {
  4870. unsigned char *data;
  4871. unsigned int len;
  4872. preload_node = i + 1;
  4873. if (data_url_decode(src, &data, &len) == 0) {
  4874. preload_decode(i, 0, data, len, 0);
  4875. free(data);
  4876. } else {
  4877. doc.nodes[i].img_index = -2;
  4878. }
  4879. continue;
  4880. }
  4881. if (!src[0]) {
  4882. preload_node++;
  4883. continue;
  4884. }
  4885. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  4886. preload_node++;
  4887. continue;
  4888. }
  4889. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  4890. preload_node = doc.nnode;
  4891. break;
  4892. }
  4893. /* Do not stop at the first below-fold image: DOM order is
  4894. * not visual order, and a footer/ad image early in the DOM
  4895. * used to hide every later article image from the loader. */
  4896. if (img_top[i] >
  4897. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  4898. preload_pending = 1;
  4899. preload_node++;
  4900. continue;
  4901. }
  4902. {
  4903. unsigned int uh = script_cache_hash(url) | 1u;
  4904. int k;
  4905. for (k = 0; k < image_count; k++)
  4906. if (images[k].state == 1 &&
  4907. images[k].url_hash == uh)
  4908. break;
  4909. if (k < image_count) {
  4910. nd->img_index = (short)k;
  4911. layout_valid = 0;
  4912. preload_node = i + 1;
  4913. image_repaint();
  4914. continue;
  4915. }
  4916. }
  4917. if (url[0] == '/') {
  4918. unsigned char *data = 0;
  4919. unsigned int len = 0;
  4920. unsigned int t0;
  4921. int before;
  4922. preload_node = i + 1;
  4923. before = image_count;
  4924. t0 = u_ticks_ms();
  4925. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  4926. err, sizeof(err)) == 0) {
  4927. preload_decode(i, 0, data, len, url);
  4928. img_stat_local(before, len, u_ticks_ms() - t0);
  4929. } else {
  4930. nd->img_index = -2;
  4931. }
  4932. continue;
  4933. }
  4934. w = fetch_worker_alloc();
  4935. if (!w)
  4936. return started;
  4937. preload_node = i + 1;
  4938. {
  4939. char msg[64];
  4940. unsigned int n = 0;
  4941. s_append(msg, &n, "Loading images ", sizeof(msg));
  4942. s_append_dec(msg, &n,
  4943. (unsigned int)preload_loaded + 1,
  4944. sizeof(msg));
  4945. s_append(msg, &n, "...", sizeof(msg));
  4946. set_status_quiet(msg);
  4947. image_repaint();
  4948. }
  4949. {
  4950. int fit_w = 0, fit_h = 0;
  4951. image_fit_size(i, &fit_w, &fit_h);
  4952. if (!fit_w)
  4953. fit_w = BR_IMG_LAYOUT_W;
  4954. if (fetch_worker_submit_image(w, url, BR_IMG_FILE_MAX,
  4955. i, 0,
  4956. (unsigned int)fit_w,
  4957. (unsigned int)fit_h,
  4958. err, sizeof(err)) != 0) {
  4959. nd->img_index = -2;
  4960. fetch_worker_release(w);
  4961. continue;
  4962. }
  4963. }
  4964. w->image_job = 1;
  4965. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4966. nd->img_index = -3; /* in flight: rescans skip it */
  4967. started++;
  4968. }
  4969. return started;
  4970. }
  4971. /* Report where the image batch spent its time: status bar for the headline,
  4972. * /share/IMGSTAT for the per-image breakdown (cat it from a terminal). */
  4973. static void img_stats_report(void)
  4974. {
  4975. char msg[80];
  4976. static char out[BR_IMG_STAT_LOG + 512];
  4977. unsigned int n = 0, o = 0;
  4978. if (!img_stat_n)
  4979. return;
  4980. img_stat_wall = img_stat_start ?
  4981. u_ticks_ms() - img_stat_start : 1;
  4982. if (!img_stat_wall)
  4983. img_stat_wall = 1;
  4984. /* Compact on-screen form; /share/IMGSTAT has the full breakdown. */
  4985. s_append(msg, &n, "img ", sizeof(msg));
  4986. s_append_dec(msg, &n, (unsigned int)img_stat_n, sizeof(msg));
  4987. s_append(msg, &n, " ", sizeof(msg));
  4988. s_append_dec(msg, &n, img_stat_wall, sizeof(msg));
  4989. s_append(msg, &n, "ms net ", sizeof(msg));
  4990. s_append_dec(msg, &n, img_stat_net, sizeof(msg));
  4991. s_append(msg, &n, " dec ", sizeof(msg));
  4992. s_append_dec(msg, &n, img_stat_dec, sizeof(msg));
  4993. s_append(msg, &n, " sc ", sizeof(msg));
  4994. s_append_dec(msg, &n, img_stat_scale, sizeof(msg));
  4995. s_append(msg, &n, " paint ", sizeof(msg));
  4996. s_append_dec(msg, &n, img_stat_paint, sizeof(msg));
  4997. /* Keep the page's phase breakdown and append the image summary when
  4998. * it fits; never hide a JS error or a truncation notice. */
  4999. if (!post_status_error && !contains_ci(post_status_text, "truncated")) {
  5000. unsigned int plen = s_len(post_status_text);
  5001. if (!plen) {
  5002. s_copy(post_status_text, msg, sizeof(post_status_text));
  5003. } else if (plen + s_len(msg) + 4 < sizeof(post_status_text)) {
  5004. unsigned int pn = plen;
  5005. s_append(post_status_text, &pn, " | ",
  5006. sizeof(post_status_text));
  5007. s_append(post_status_text, &pn, msg,
  5008. sizeof(post_status_text));
  5009. } else {
  5010. s_copy(post_status_text, msg, sizeof(post_status_text));
  5011. }
  5012. post_status_ttl = 12000;
  5013. }
  5014. s_append(out, &o, "browser image stats\n", sizeof(out));
  5015. s_append(out, &o, "n=", sizeof(out));
  5016. s_append_dec(out, &o, (unsigned int)img_stat_n, sizeof(out));
  5017. s_append(out, &o, " wall=", sizeof(out));
  5018. s_append_dec(out, &o, img_stat_wall, sizeof(out));
  5019. s_append(out, &o, " net=", sizeof(out));
  5020. s_append_dec(out, &o, img_stat_net, sizeof(out));
  5021. s_append(out, &o, " open=", sizeof(out));
  5022. s_append_dec(out, &o, img_stat_open, sizeof(out));
  5023. s_append(out, &o, " first=", sizeof(out));
  5024. s_append_dec(out, &o, img_stat_first, sizeof(out));
  5025. s_append(out, &o, " io=", sizeof(out));
  5026. s_append_dec(out, &o, img_stat_io, sizeof(out));
  5027. s_append(out, &o, " dec=", sizeof(out));
  5028. s_append_dec(out, &o, img_stat_dec, sizeof(out));
  5029. s_append(out, &o, " scale=", sizeof(out));
  5030. s_append_dec(out, &o, img_stat_scale, sizeof(out));
  5031. s_append(out, &o, " paint=", sizeof(out));
  5032. s_append_dec(out, &o, img_stat_paint, sizeof(out));
  5033. s_append(out, &o, " reflow=", sizeof(out));
  5034. s_append_dec(out, &o, img_stat_reflow, sizeof(out));
  5035. s_append(out, &o, " bytes=", sizeof(out));
  5036. s_append_dec(out, &o, img_stat_bytes, sizeof(out));
  5037. s_append(out, &o, "\nurl bytes open first total io dec scale native bitmap\n",
  5038. sizeof(out));
  5039. s_append(out, &o, img_stat_log, sizeof(out));
  5040. u_syscall3(SYS_WRITE_FILE, (int)"/share/IMGSTAT", (int)out,
  5041. (int)s_len(out));
  5042. }
  5043. static void preload_step(void)
  5044. {
  5045. int i;
  5046. unsigned int t0;
  5047. if (!preload_active)
  5048. return;
  5049. if (cancel_fetch || pending_action) {
  5050. preload_active = 0;
  5051. preload_pending = 0;
  5052. fetch_workers_cancel_busy();
  5053. return;
  5054. }
  5055. preload_fill_jobs();
  5056. /* Decode completed images in a short batch instead of one per pass.
  5057. * A pass used to decode one image and then sleep 10 ms, so a page of
  5058. * small icons trickled in at the decode rate. The budget keeps a
  5059. * single huge JPEG from monopolising the UI while small images
  5060. * finish together. */
  5061. t0 = u_ticks_ms();
  5062. for (i = 0; i < FETCH_WORKERS; i++) {
  5063. if (!fetch_workers[i].busy)
  5064. continue;
  5065. if (preload_finish_worker(&fetch_workers[i]) &&
  5066. u_ticks_ms() - t0 >= BR_IMG_DECODE_BUDGET_MS)
  5067. break;
  5068. }
  5069. if (preload_active && preload_node >= doc.nnode &&
  5070. preload_active_jobs() == 0) {
  5071. preload_active = 0;
  5072. if (preload_pending)
  5073. preload_scroll = page_scroll.offset;
  5074. else
  5075. preload_pending = 0;
  5076. /* Keep the now idle helpers and their connections; a later
  5077. * navigation reuses them. They exit after ten idle seconds,
  5078. * and losing window focus stops them at once. */
  5079. if (img_repaint_pending) {
  5080. img_repaint_pending = 0;
  5081. ngui_invalidate(&ui);
  5082. }
  5083. img_stats_report();
  5084. set_status(post_status_text, post_status_error, post_status_ttl);
  5085. ngui_invalidate(&ui);
  5086. }
  5087. }
  5088. /* Set by navigate() when it turned a typed bare host into https://; the next
  5089. * load_page() consumes it and may retry over http. */
  5090. static int nav_https_upgraded;
  5091. /* Errors that mean "https is not served here" rather than "the site is
  5092. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  5093. static int https_fallback_error(int e)
  5094. {
  5095. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  5096. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  5097. e == UHTTP_ERR_RESET;
  5098. }
  5099. static void history_push(const char *url)
  5100. {
  5101. if (!url || !url[0])
  5102. return;
  5103. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  5104. s_eq(history[hist_pos], url))
  5105. return;
  5106. if (hist_len > 0 && hist_pos + 1 < hist_len)
  5107. hist_len = hist_pos + 1;
  5108. if (hist_len < BR_HISTORY) {
  5109. s_copy(history[hist_len], url, BR_URL_MAX);
  5110. hist_pos = hist_len;
  5111. hist_len++;
  5112. } else {
  5113. int i;
  5114. for (i = 1; i < BR_HISTORY; i++)
  5115. s_copy(history[i - 1], history[i], BR_URL_MAX);
  5116. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  5117. hist_pos = BR_HISTORY - 1;
  5118. }
  5119. }
  5120. static void load_page(const char *url, int local, int push)
  5121. {
  5122. unsigned char *body = 0;
  5123. unsigned int len = 0;
  5124. int truncated = 0;
  5125. struct img_info image_info;
  5126. char ctype[64];
  5127. char final[BR_URL_MAX];
  5128. char err[80];
  5129. const char *detail = 0;
  5130. const char *post = pending_post_is ? pending_post : 0;
  5131. unsigned int post_len = pending_post_len;
  5132. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  5133. /* Phase timings for the status line: where a slow load spends it. */
  5134. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  5135. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  5136. int upgraded = nav_https_upgraded;
  5137. int retried = 0;
  5138. int rv;
  5139. nav_https_upgraded = 0;
  5140. final[0] = '\0';
  5141. pending_post_len = 0;
  5142. pending_post_is = 0;
  5143. cancel_fetch = 0;
  5144. preload_active = 0;
  5145. preload_pending = 0;
  5146. fetch_workers_prepare_nav(url);
  5147. js_browser_stop();
  5148. js_last_status[0] = '\0';
  5149. js_last_error = 0;
  5150. heap_clear();
  5151. image_reset();
  5152. form_reset_state();
  5153. layout_valid = 0;
  5154. page_scroll.offset = 0;
  5155. page_scroll.dragging = 0;
  5156. page_title[0] = '\0';
  5157. page_loading = 1;
  5158. page_is_local = local;
  5159. s_copy(page_url, url, sizeof(page_url));
  5160. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5161. url_in.len = s_len(url_in.text);
  5162. url_in.cursor = url_in.len;
  5163. url_in.scroll = 0;
  5164. ngui_set_focus(&ui, 0);
  5165. if (final[0])
  5166. final[0] = '\0';
  5167. if (push)
  5168. history_push(url);
  5169. set_status("Loading...", 0, 0);
  5170. ngui_invalidate(&ui);
  5171. /* heap_clear() detaches the fonts, so attach them again before the
  5172. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  5173. if (heap_start() != 0) {
  5174. show_error("Out of memory", "Cannot allocate the page buffer");
  5175. return;
  5176. }
  5177. br_parse_plain(&doc, "", 0); /* blank while loading */
  5178. ngui_font_attach(&ui);
  5179. redraw_now();
  5180. browser_rules_alloc();
  5181. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5182. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  5183. &truncated, post, post_len);
  5184. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  5185. fetch_last_error == UHTTP_ERR_DNS) {
  5186. /* A busy previous page can leave the receiver ring full just
  5187. * long enough to lose a DNS reply. Tear the old helpers down
  5188. * and try once more before giving up. */
  5189. retried = 1;
  5190. fetch_workers_stop_all();
  5191. u_sleep_ms(500);
  5192. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5193. sizeof(ctype), final, sizeof(final), err,
  5194. sizeof(err), &truncated, post, post_len);
  5195. }
  5196. if (rv == FETCH_ABORT)
  5197. return;
  5198. t_fetch = u_ticks_ms() - t_start;
  5199. /* Capture the page timing before CSS/script/image fetches overwrite the
  5200. * shared fetch_meta block. */
  5201. if (rv == 0 && !local) {
  5202. page_open_ms = fetch_meta.open_ms;
  5203. page_first_ms = fetch_meta.first_ms;
  5204. page_total_ms = fetch_meta.total_ms;
  5205. }
  5206. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  5207. https_fallback_error(fetch_last_error)) {
  5208. char http_url[BR_URL_MAX];
  5209. unsigned int n = 0;
  5210. s_append(http_url, &n, "http://", sizeof(http_url));
  5211. s_append(http_url, &n, url + 8, sizeof(http_url));
  5212. /* Replace the https entry instead of adding a second one. */
  5213. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  5214. s_eq(history[hist_pos], url))
  5215. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  5216. load_page(http_url, 0, 0);
  5217. return;
  5218. }
  5219. if (rv != 0) {
  5220. detail = err;
  5221. show_error("Cannot load this page", detail);
  5222. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5223. url_in.len = s_len(url_in.text);
  5224. url_in.cursor = url_in.len;
  5225. url_in.scroll = 0;
  5226. return;
  5227. }
  5228. if (!local)
  5229. origin_cache_learn(url, final[0] ? final : url);
  5230. page_is_local = local;
  5231. if (final[0]) {
  5232. s_copy(page_url, final, sizeof(page_url));
  5233. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5234. url_in.len = s_len(url_in.text);
  5235. url_in.cursor = url_in.len;
  5236. url_in.scroll = 0;
  5237. }
  5238. if (contains_ci(ctype, "text/plain")) {
  5239. br_parse_plain(&doc, (const char *)body, len);
  5240. } else if (contains_ci(ctype, "image/") ||
  5241. (!contains_ci(ctype, "text/html") &&
  5242. img_sniff(body, len, &image_info) == 0)) {
  5243. unsigned int node = br_parse_image_doc(&doc, page_url);
  5244. if (node)
  5245. decode_direct_image(body, len, node);
  5246. s_copy(page_title, "Image", sizeof(page_title));
  5247. } else {
  5248. br_set_viewport(ui.w);
  5249. t_mark = u_ticks_ms();
  5250. br_parse(&doc, (const char *)body, len);
  5251. t_parse = u_ticks_ms() - t_mark;
  5252. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  5253. sizeof(page_title));
  5254. t_mark = u_ticks_ms();
  5255. if (load_stylesheets() == FETCH_ABORT)
  5256. return;
  5257. t_css = u_ticks_ms() - t_mark;
  5258. if (pending_action)
  5259. return;
  5260. }
  5261. preload_begin();
  5262. page_loading = 0;
  5263. hist_visit(page_url, page_title);
  5264. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5265. url_in.len = s_len(url_in.text);
  5266. url_in.cursor = url_in.len;
  5267. url_in.scroll = 0;
  5268. ngui_set_focus(&ui, 0);
  5269. /* Paint the parsed page before fetching/running scripts. A slow
  5270. * remote <script src> then does not hide the page behind the loading
  5271. * screen; the fetch helper pumps this UI while it waits. */
  5272. set_status("Loading scripts...", 0, 0);
  5273. t_mark = u_ticks_ms();
  5274. redraw_now();
  5275. t_paint = u_ticks_ms() - t_mark;
  5276. /* Start one image download before the scripts. The other workers
  5277. * fetch the external script bodies in parallel, and the remaining
  5278. * images start as soon as the script phase ends. */
  5279. preload_max_jobs = 1;
  5280. preload_fill_jobs();
  5281. preload_wait = 0;
  5282. t_mark = u_ticks_ms();
  5283. run_page_scripts();
  5284. t_js = u_ticks_ms() - t_mark;
  5285. preload_max_jobs = FETCH_WORKERS;
  5286. if (pending_action)
  5287. return;
  5288. post_status_text[0] = '\0';
  5289. post_status_error = 0;
  5290. post_status_ttl = 0;
  5291. if (js_last_status[0]) {
  5292. s_copy(post_status_text, js_last_status,
  5293. sizeof(post_status_text));
  5294. post_status_error = js_last_error;
  5295. post_status_ttl = 8000;
  5296. } else if (truncated) {
  5297. s_copy(post_status_text, "Page truncated at the buffer limit",
  5298. sizeof(post_status_text));
  5299. post_status_ttl = 6000;
  5300. } else if (doc.truncated) {
  5301. s_copy(post_status_text, "Page truncated by the parser",
  5302. sizeof(post_status_text));
  5303. post_status_ttl = 6000;
  5304. } else if (page_total_ms) {
  5305. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  5306. * paint 220, js 1750" -- the phases of this load. */
  5307. unsigned int n = 0;
  5308. static const char *const names[] = {
  5309. ", parse ", ", css ", ", paint ", ", js "
  5310. };
  5311. unsigned int vals[4];
  5312. int k;
  5313. vals[0] = t_parse;
  5314. vals[1] = t_css;
  5315. vals[2] = t_paint;
  5316. vals[3] = t_js;
  5317. (void)page_first_ms;
  5318. if (starts_with(page_url, "https://"))
  5319. s_append(post_status_text, &n,
  5320. "HTTPS (not verified), ",
  5321. sizeof(post_status_text));
  5322. s_append(post_status_text, &n, "Loaded in ",
  5323. sizeof(post_status_text));
  5324. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  5325. sizeof(post_status_text));
  5326. s_append(post_status_text, &n, " ms: page ",
  5327. sizeof(post_status_text));
  5328. s_append_dec(post_status_text, &n, t_fetch,
  5329. sizeof(post_status_text));
  5330. s_append(post_status_text, &n, " (headers ",
  5331. sizeof(post_status_text));
  5332. s_append_dec(post_status_text, &n, page_open_ms,
  5333. sizeof(post_status_text));
  5334. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  5335. for (k = 0; k < 4; k++) {
  5336. s_append(post_status_text, &n, names[k],
  5337. sizeof(post_status_text));
  5338. s_append_dec(post_status_text, &n, vals[k],
  5339. sizeof(post_status_text));
  5340. }
  5341. post_status_ttl = 12000;
  5342. } else if (starts_with(page_url, "https://")) {
  5343. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  5344. sizeof(post_status_text));
  5345. post_status_ttl = 6000;
  5346. }
  5347. set_status(post_status_text, post_status_error, post_status_ttl);
  5348. ngui_invalidate(&ui);
  5349. }
  5350. static void load_home(int push)
  5351. {
  5352. pending_post_len = 0;
  5353. pending_post_is = 0;
  5354. cancel_fetch = 0;
  5355. preload_active = 0;
  5356. preload_pending = 0;
  5357. js_browser_stop();
  5358. js_last_status[0] = '\0';
  5359. js_last_error = 0;
  5360. heap_clear();
  5361. image_reset();
  5362. form_reset_state();
  5363. layout_valid = 0;
  5364. page_scroll.offset = 0;
  5365. page_scroll.dragging = 0;
  5366. page_loading = 1;
  5367. page_is_local = 0;
  5368. s_copy(page_url, "about:home", sizeof(page_url));
  5369. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5370. url_in.len = s_len(url_in.text);
  5371. url_in.cursor = url_in.len;
  5372. url_in.scroll = 0;
  5373. ngui_set_focus(&ui, 0);
  5374. if (push)
  5375. history_push(page_url);
  5376. ngui_invalidate(&ui);
  5377. /* See load_page(): reattach the fonts before the first redraw. */
  5378. if (heap_start() != 0) {
  5379. show_error("Out of memory", "Cannot allocate the browser heap");
  5380. return;
  5381. }
  5382. br_parse_plain(&doc, "", 0);
  5383. ngui_font_attach(&ui);
  5384. redraw_now();
  5385. browser_rules_alloc();
  5386. {
  5387. static const char home[] =
  5388. "<html><head><title>NebOS Browser</title><style>"
  5389. "body { margin: 10px; color: #e4e6f0; }"
  5390. "h1 { color: #7fb0ff; }"
  5391. ".box { background-color: #262b3a; margin: 12px; "
  5392. "padding: 10px; }"
  5393. "a { color: #7fb0ff; }"
  5394. "pre { background-color: #32384a; }"
  5395. "</style></head><body>"
  5396. "<h1>NebOS Browser</h1>"
  5397. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  5398. "shared HTTP client and the image library.</p>"
  5399. "<div class=\"box\"><b>Try:</b>"
  5400. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  5401. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  5402. "<li><a href=\"/floppy1/JS.HTM\">/"
  5403. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  5404. "<li><a href=\"http://10.0.2.2:8000/\">"
  5405. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  5406. "<li><a href=\"https://example.com/\">"
  5407. "https://example.com/</a> (TLS, not verified)</li>"
  5408. "</ul></div>"
  5409. "<p>Type a URL in the bar above. Esc closes the "
  5410. "window, Ctrl+L focuses the address bar.</p>"
  5411. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  5412. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  5413. "</body></html>";
  5414. br_set_viewport(ui.w);
  5415. br_parse(&doc, home, sizeof(home) - 1);
  5416. br_parse_inline_css(&doc);
  5417. br_reset_styles(&doc);
  5418. s_copy(page_title, doc.title, sizeof(page_title));
  5419. }
  5420. post_status_text[0] = '\0';
  5421. post_status_error = 0;
  5422. post_status_ttl = 0;
  5423. page_loading = 0;
  5424. set_status("", 0, 0);
  5425. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5426. url_in.len = s_len(url_in.text);
  5427. url_in.cursor = url_in.len;
  5428. url_in.scroll = 0;
  5429. ngui_set_focus(&ui, 0);
  5430. ngui_invalidate(&ui);
  5431. }
  5432. /* Extensions the browser opens from the local filesystem. A dotted input
  5433. * with one of these still resolves relative to the cwd. */
  5434. static int local_file_ext(const char *s)
  5435. {
  5436. static const char *const exts[] = {
  5437. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  5438. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  5439. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  5440. "cfg", "conf", 0
  5441. };
  5442. unsigned int i = 0, start = 0, len = 0, e;
  5443. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  5444. s[i] != '#') {
  5445. if (s[i] == '.') {
  5446. start = i + 1;
  5447. len = 0;
  5448. } else if (start) {
  5449. len++;
  5450. }
  5451. i++;
  5452. }
  5453. if (!len)
  5454. return 0;
  5455. for (e = 0; exts[e]; e++) {
  5456. const char *x = exts[e];
  5457. unsigned int xn = s_len(x), k;
  5458. if (xn != len)
  5459. continue;
  5460. for (k = 0; k < len; k++) {
  5461. char a = s[start + k];
  5462. if (a >= 'A' && a <= 'Z')
  5463. a = (char)(a - 'A' + 'a');
  5464. if (a != x[k])
  5465. break;
  5466. }
  5467. if (k == len)
  5468. return 1;
  5469. }
  5470. return 0;
  5471. }
  5472. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  5473. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  5474. * Enter to the first network request. */
  5475. static int looks_like_host(const char *s)
  5476. {
  5477. unsigned int i = 0;
  5478. int dot = 0;
  5479. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  5480. s[i] != ':') {
  5481. char c = s[i];
  5482. if (c == '.') {
  5483. dot = 1;
  5484. } else if (!((c >= 'a' && c <= 'z') ||
  5485. (c >= 'A' && c <= 'Z') ||
  5486. (c >= '0' && c <= '9') ||
  5487. c == '-' || c == '_')) {
  5488. return 0;
  5489. }
  5490. i++;
  5491. }
  5492. return dot && i > 0 && !local_file_ext(s);
  5493. }
  5494. static void load_remote(const char *url, int push)
  5495. {
  5496. char canon[BR_URL_MAX];
  5497. s_copy(canon, url, sizeof(canon));
  5498. origin_cache_apply(canon, sizeof(canon));
  5499. load_page(canon, 0, push);
  5500. }
  5501. static void navigate(const char *input, int push)
  5502. {
  5503. char target[BR_URL_MAX];
  5504. char *t;
  5505. if (!input)
  5506. return;
  5507. s_copy(target, input, sizeof(target));
  5508. t = trim(target);
  5509. if (!t[0])
  5510. return;
  5511. if (s_eq(t, "about:home")) {
  5512. load_home(push);
  5513. return;
  5514. }
  5515. if (starts_with(t, "file://")) {
  5516. make_abs_local(t + 7, target, sizeof(target));
  5517. load_page(target, 1, push);
  5518. return;
  5519. }
  5520. if (is_http(t)) {
  5521. load_remote(t, push);
  5522. return;
  5523. }
  5524. if (t[0] == '/') {
  5525. make_abs_local(t, target, sizeof(target));
  5526. load_page(target, 1, push);
  5527. return;
  5528. }
  5529. if (!looks_like_host(t)) {
  5530. struct sys_stat st;
  5531. if (u_stat(t, &st) == 0 && !st.is_dir) {
  5532. make_abs_local(t, target, sizeof(target));
  5533. load_page(target, 1, push);
  5534. return;
  5535. }
  5536. }
  5537. {
  5538. /* A typed bare host tries https first: nearly every site
  5539. * redirects http -> https anyway, and that hop costs a whole
  5540. * extra connection. load_page() falls back to http when the
  5541. * https connection itself fails. */
  5542. char with_scheme[BR_URL_MAX];
  5543. unsigned int n = 0;
  5544. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  5545. s_append(with_scheme, &n, t, sizeof(with_scheme));
  5546. nav_https_upgraded = 1;
  5547. load_remote(with_scheme, push);
  5548. }
  5549. }
  5550. /* ---- layout ---- */
  5551. static struct ufont_face *style_face(const struct br_style *st)
  5552. {
  5553. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  5554. return font_faces[st->font_face - 1];
  5555. return 0;
  5556. }
  5557. static struct ufont_face *run_face(const struct lay_run *r)
  5558. {
  5559. if (r->font_face && r->font_face <= BR_MAX_FACES)
  5560. return font_faces[r->font_face - 1];
  5561. return 0;
  5562. }
  5563. static unsigned int face_text_width(struct ngui *gui,
  5564. const struct br_style *st,
  5565. const char *s, unsigned int n)
  5566. {
  5567. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  5568. st->bold, st->italic, st->mono);
  5569. }
  5570. static int face_line_height(struct ngui *gui, const struct br_style *st)
  5571. {
  5572. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  5573. st->mono);
  5574. }
  5575. static unsigned int run_text_width(struct ngui *gui,
  5576. const struct lay_run *r,
  5577. const char *s, unsigned int n)
  5578. {
  5579. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  5580. r->bold, r->italic, r->mono);
  5581. }
  5582. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  5583. {
  5584. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  5585. r->mono);
  5586. }
  5587. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  5588. {
  5589. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  5590. }
  5591. static struct br_style base_style(void)
  5592. {
  5593. struct br_style s = { 0 };
  5594. s.color = ui.theme.text;
  5595. s.bg = ui.theme.bg;
  5596. s.has_bg = 0;
  5597. for (int i = 0; i < 4; i++) {
  5598. s.border_c[i] = 0;
  5599. s.border_w[i] = 0;
  5600. s.border_s[i] = BR_BORDER_SOLID;
  5601. }
  5602. s.font_px = 16;
  5603. s.bold = 0;
  5604. s.italic = 0;
  5605. s.mono = 0;
  5606. s.underline = 0;
  5607. s.strike = 0;
  5608. s.overline = 0;
  5609. s.align = BR_ALIGN_LEFT;
  5610. s.display = BR_DISPLAY_BLOCK;
  5611. s.no_bullet = 0;
  5612. s.list_style = BR_LIST_AUTO;
  5613. s.uppercase = 0;
  5614. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  5615. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  5616. s.width = s.max_width = s.min_width = 0;
  5617. s.height = s.min_height = s.max_height = 0;
  5618. s.box_sizing = 0;
  5619. s.ml_auto = s.mr_auto = 0;
  5620. s.line_h_pct = 0;
  5621. s.line_h_px = 0;
  5622. s.mt = s.mb = s.ml = s.mr = 0;
  5623. s.pt = s.pb = s.pl = s.pr = 0;
  5624. return s;
  5625. }
  5626. /* The style node 0's children inherit. Node 0 is the first parsed node:
  5627. * a minified page that starts `<!doctype html><html ...>` makes it the
  5628. * <html> element itself, and the layout walks only its children, so its
  5629. * own cascade (html { color; font } -- Docusaurus/Infima put the page
  5630. * colour and font there) used to be skipped and the theme defaults showed
  5631. * through. Only inherited properties are taken: the root's box (margins,
  5632. * display, background) is not a container style for its children here. */
  5633. static struct br_style root_style(void)
  5634. {
  5635. struct br_style base = base_style(), st;
  5636. if (!doc.nnode || doc.nodes[doc.root].type != BR_NODE_ELEM ||
  5637. doc.nodes[doc.root].tag != BR_TAG_HTML)
  5638. return base;
  5639. br_style_for(&doc, doc.root, &base, &st);
  5640. base.color = st.color;
  5641. base.font_px = st.font_px;
  5642. base.bold = st.bold;
  5643. base.italic = st.italic;
  5644. base.mono = st.mono;
  5645. base.font_face = st.font_face;
  5646. base.align = st.align;
  5647. base.line_h_pct = st.line_h_pct;
  5648. base.line_h_px = st.line_h_px;
  5649. base.nowrap = st.nowrap;
  5650. base.uppercase = st.uppercase;
  5651. base.cursor = st.cursor;
  5652. base.vis_hidden = st.vis_hidden;
  5653. base.fill_mode = st.fill_mode;
  5654. base.fill = st.fill;
  5655. base.stroke_mode = st.stroke_mode;
  5656. base.stroke = st.stroke;
  5657. base.stroke_w = st.stroke_w;
  5658. base.fill_evenodd = st.fill_evenodd;
  5659. return base;
  5660. }
  5661. /* Resolve a margin/padding raw value. Percentages use the containing
  5662. * block width for all four sides, as CSS specifies. */
  5663. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  5664. {
  5665. if (unit == 1)
  5666. return base * v / 10000;
  5667. if (unit == 2)
  5668. return st->font_px * v / 100;
  5669. if (unit == 3)
  5670. return (int)br_root_font_px() * v / 100;
  5671. if (unit == 4)
  5672. return 0;
  5673. return v;
  5674. }
  5675. static int mp_px(const struct br_style *st, int side, int base)
  5676. {
  5677. int raw;
  5678. switch (side) {
  5679. case 0: raw = st->mt; break;
  5680. case 1: raw = st->mr; break;
  5681. case 2: raw = st->mb; break;
  5682. case 3: raw = st->ml; break;
  5683. case 4: raw = st->pt; break;
  5684. case 5: raw = st->pr; break;
  5685. case 6: raw = st->pb; break;
  5686. default: raw = st->pl; break;
  5687. }
  5688. if (st->mp_unit[side] == 5)
  5689. return base * raw / 100 + st->mp_calc_px[side];
  5690. return css_mp_px(st, raw, st->mp_unit[side], base);
  5691. }
  5692. static int style_width_px(const struct br_style *st, int base)
  5693. {
  5694. if (st->width_kind == 1)
  5695. return st->width;
  5696. if (st->width_kind == 2)
  5697. return base * (int)st->width / 100;
  5698. if (st->width_kind == 3)
  5699. return base * st->width_calc_pct / 100 + st->width_calc_px;
  5700. return 0;
  5701. }
  5702. static int style_height_px(const struct br_style *st, int base)
  5703. {
  5704. if (st->height_kind == 1)
  5705. return st->height;
  5706. if (st->height_kind == 2)
  5707. return base * (int)st->height / 100;
  5708. if (st->height_kind == 3)
  5709. return base * st->height_calc_pct / 100 + st->height_calc_px;
  5710. return 0;
  5711. }
  5712. static int css_size(unsigned char kind, int val, int base)
  5713. {
  5714. if (kind == 1)
  5715. return val;
  5716. if (kind == 2)
  5717. return base * val / 100;
  5718. return -1;
  5719. }
  5720. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  5721. int thick, int horizontal, unsigned short color,
  5722. unsigned char style)
  5723. {
  5724. int pos;
  5725. if (len <= 0 || thick <= 0)
  5726. return;
  5727. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  5728. if (horizontal)
  5729. ngui_fill_rect(ui, (struct ngui_rect){
  5730. x, y, len, thick}, color);
  5731. else
  5732. ngui_fill_rect(ui, (struct ngui_rect){
  5733. x, y, thick, len}, color);
  5734. return;
  5735. }
  5736. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  5737. int seg = len - pos;
  5738. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  5739. seg = style == BR_BORDER_DASHED ? 4 : 2;
  5740. if (horizontal)
  5741. ngui_fill_rect(ui, (struct ngui_rect){
  5742. x + pos, y, seg, thick}, color);
  5743. else
  5744. ngui_fill_rect(ui, (struct ngui_rect){
  5745. x, y + pos, thick, seg}, color);
  5746. }
  5747. }
  5748. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  5749. const struct br_style *st)
  5750. {
  5751. int top = st->border_w[0], right = st->border_w[1];
  5752. int bottom = st->border_w[2], left = st->border_w[3];
  5753. if (r.w <= 0 || r.h <= 0)
  5754. return;
  5755. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  5756. int i;
  5757. for (i = 0; i < 4; i++)
  5758. if (st->border_w[i] && !st->border_t[i]) {
  5759. ngui_fill_rect(ui, r, st->border_c[i]);
  5760. break;
  5761. }
  5762. return;
  5763. }
  5764. if (top && !st->border_t[0])
  5765. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  5766. st->border_c[0], st->border_s[0]);
  5767. if (bottom && !st->border_t[2])
  5768. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  5769. st->border_c[2], st->border_s[2]);
  5770. if (left && !st->border_t[3])
  5771. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  5772. left, 0, st->border_c[3], st->border_s[3]);
  5773. if (right && !st->border_t[1])
  5774. draw_border_side(ui, r.x + r.w - right, r.y + top,
  5775. r.h - top - bottom, right, 0,
  5776. st->border_c[1], st->border_s[1]);
  5777. }
  5778. static void transform_origin(const struct br_style *st, int w, int h,
  5779. int *ox, int *oy)
  5780. {
  5781. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  5782. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  5783. }
  5784. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  5785. unsigned int a)
  5786. {
  5787. unsigned int dr, dg, db, sr, sg, sb;
  5788. if (a >= 255)
  5789. return s;
  5790. dr = (d >> 11) & 31;
  5791. dg = (d >> 5) & 63;
  5792. db = d & 31;
  5793. sr = (s >> 11) & 31;
  5794. sg = (s >> 5) & 63;
  5795. sb = s & 31;
  5796. dr = (dr * (255 - a) + sr * a) / 255;
  5797. dg = (dg * (255 - a) + sg * a) / 255;
  5798. db = (db * (255 - a) + sb * a) / 255;
  5799. return (unsigned short)((dr << 11) | (dg << 5) | db);
  5800. }
  5801. /* Paint a solid box through scale()/rotate() around transform-origin. This
  5802. * transforms the element's own background box; text and descendants keep
  5803. * their layout (documented approximation). */
  5804. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  5805. unsigned short color,
  5806. const struct br_style *st)
  5807. {
  5808. double sx = st->scale_x / 100.0;
  5809. double sy = st->scale_y / 100.0;
  5810. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  5811. double c = cos(th), sn = sin(th);
  5812. int ox, oy, minx, miny, maxx, maxy, x, y;
  5813. double ax, ay;
  5814. double px[4], py[4];
  5815. int cx1, cy1, cx2, cy2, i;
  5816. if (sx == 0)
  5817. sx = 0.01;
  5818. if (sy == 0)
  5819. sy = 0.01;
  5820. transform_origin(st, box.w, box.h, &ox, &oy);
  5821. ax = box.x + ox;
  5822. ay = box.y + oy;
  5823. px[0] = -ox; py[0] = -oy;
  5824. px[1] = box.w - ox; py[1] = -oy;
  5825. px[2] = box.w - ox; py[2] = box.h - oy;
  5826. px[3] = -ox; py[3] = box.h - oy;
  5827. minx = miny = 1000000;
  5828. maxx = maxy = -1000000;
  5829. for (i = 0; i < 4; i++) {
  5830. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  5831. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  5832. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5833. if (dx < minx) minx = dx;
  5834. if (dx > maxx) maxx = dx;
  5835. if (dy < miny) miny = dy;
  5836. if (dy > maxy) maxy = dy;
  5837. }
  5838. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5839. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5840. cx2 = page_rect.x + page_rect.w - 12;
  5841. cy2 = page_rect.y + page_rect.h;
  5842. if (cx2 > gui->w) cx2 = gui->w;
  5843. if (cy2 > gui->h) cy2 = gui->h;
  5844. if (minx < cx1) minx = cx1;
  5845. if (miny < cy1) miny = cy1;
  5846. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5847. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5848. for (y = miny; y <= maxy; y++) {
  5849. for (x = minx; x <= maxx; x++) {
  5850. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  5851. double rx = dx * c + dy * sn;
  5852. double ry = -dx * sn + dy * c;
  5853. double bx = rx / sx + ox;
  5854. double by = ry / sy + oy;
  5855. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  5856. gui->px[y * gui->w + x] = color;
  5857. }
  5858. }
  5859. }
  5860. static void draw_image_transformed(struct ngui *gui,
  5861. const struct img_image *im,
  5862. int x, int y, int w, int h,
  5863. int sx100, int sy100, int rot100,
  5864. int origin_x, int origin_y,
  5865. int origin_x_kind, int origin_y_kind)
  5866. {
  5867. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  5868. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  5869. double c = cos(th), sn = sin(th);
  5870. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  5871. double ax, ay;
  5872. double bx[4], by[4];
  5873. int cx1, cy1, cx2, cy2;
  5874. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  5875. return;
  5876. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  5877. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  5878. ax = x + ox;
  5879. ay = y + oy;
  5880. bx[0] = -ox; by[0] = -oy;
  5881. bx[1] = w - ox; by[1] = -oy;
  5882. bx[2] = w - ox; by[2] = h - oy;
  5883. bx[3] = -ox; by[3] = h - oy;
  5884. minx = miny = 1000000;
  5885. maxx = maxy = -1000000;
  5886. for (i = 0; i < 4; i++) {
  5887. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  5888. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  5889. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5890. if (dx < minx) minx = dx;
  5891. if (dx > maxx) maxx = dx;
  5892. if (dy < miny) miny = dy;
  5893. if (dy > maxy) maxy = dy;
  5894. }
  5895. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5896. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5897. cx2 = page_rect.x + page_rect.w - 12;
  5898. cy2 = page_rect.y + page_rect.h;
  5899. if (cx2 > gui->w) cx2 = gui->w;
  5900. if (cy2 > gui->h) cy2 = gui->h;
  5901. if (minx < cx1) minx = cx1;
  5902. if (miny < cy1) miny = cy1;
  5903. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5904. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5905. for (py = miny; py <= maxy; py++) {
  5906. for (px = minx; px <= maxx; px++) {
  5907. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  5908. double rx = dx * c + dy * sn;
  5909. double ry = -dx * sn + dy * c;
  5910. double fx = rx / sx + ox;
  5911. double fy = ry / sy + oy;
  5912. int ix, iy;
  5913. unsigned int si, a;
  5914. unsigned short src;
  5915. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  5916. continue;
  5917. ix = (int)(fx * (double)im->w / w);
  5918. iy = (int)(fy * (double)im->h / h);
  5919. if (ix < 0 || ix >= (int)im->w ||
  5920. iy < 0 || iy >= (int)im->h)
  5921. continue;
  5922. si = (unsigned int)iy * im->w + (unsigned int)ix;
  5923. src = im->px[si];
  5924. a = im->alpha ? im->alpha[si] : 255;
  5925. gui->px[py * gui->w + px] =
  5926. a >= 255 ? src :
  5927. blend_rgb565(gui->px[py * gui->w + px],
  5928. src, a);
  5929. }
  5930. }
  5931. }
  5932. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5933. unsigned int node, const struct br_style *st);
  5934. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  5935. * first and every pixel outside a corner's arc is restored afterwards. */
  5936. #define BG_ROUND_MAX 64
  5937. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  5938. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  5939. unsigned int node, const struct br_style *st,
  5940. int rtl, int rtr, int rbr, int rbl)
  5941. {
  5942. struct ngui *ui = l->ui;
  5943. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  5944. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  5945. if (ui->nclip > 0)
  5946. clip = ui->clip[ui->nclip - 1];
  5947. for (c = 0; c < 4; c++) {
  5948. if (r[c] > BG_ROUND_MAX)
  5949. r[c] = BG_ROUND_MAX;
  5950. if (r[c] > box.w / 2)
  5951. r[c] = box.w / 2;
  5952. if (r[c] > box.h / 2)
  5953. r[c] = box.h / 2;
  5954. }
  5955. for (c = 0; c < 4; c++) {
  5956. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5957. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5958. for (dy = 0; dy < r[c]; dy++)
  5959. for (dx = 0; dx < r[c]; dx++) {
  5960. int px = ox + dx, py = oy + dy;
  5961. if (px >= clip.x && py >= clip.y &&
  5962. px < clip.x + clip.w && py < clip.y + clip.h)
  5963. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  5964. ui->px[py * ui->w + px];
  5965. }
  5966. }
  5967. draw_bg_image(l, box, node, st);
  5968. for (c = 0; c < 4; c++) {
  5969. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5970. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5971. /* arc centre, in corner-square coordinates */
  5972. int cx = (c == 1 || c == 2) ? 0 : r[c];
  5973. int cy = (c >= 2) ? 0 : r[c];
  5974. for (dy = 0; dy < r[c]; dy++)
  5975. for (dx = 0; dx < r[c]; dx++) {
  5976. int px = ox + dx, py = oy + dy;
  5977. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  5978. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  5979. continue;
  5980. if (px >= clip.x && py >= clip.y &&
  5981. px < clip.x + clip.w && py < clip.y + clip.h)
  5982. ui->px[py * ui->w + px] =
  5983. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  5984. }
  5985. }
  5986. }
  5987. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5988. unsigned int node, const struct br_style *st)
  5989. {
  5990. struct br_image *bi;
  5991. struct img_blit b;
  5992. int tw, th, x, y, rep_x, rep_y, posx, posy;
  5993. unsigned int scale = 65536;
  5994. int legacy, tiles = 0, rows = 0;
  5995. int cx1, cy1, cx2, cy2;
  5996. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  5997. return;
  5998. if (doc.nodes[node].bg_img_index < 0 ||
  5999. doc.nodes[node].bg_img_index >= image_count)
  6000. return;
  6001. bi = &images[doc.nodes[node].bg_img_index];
  6002. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  6003. return;
  6004. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  6005. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  6006. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  6007. if (legacy) {
  6008. scale = ((unsigned int)box.w << 16) / bi->img.w;
  6009. tw = box.w;
  6010. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6011. x = box.x;
  6012. y = box.y;
  6013. rep_x = rep_y = 0;
  6014. } else {
  6015. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  6016. unsigned int sx = ((unsigned int)box.w << 16) /
  6017. bi->img.w;
  6018. unsigned int sy = ((unsigned int)box.h << 16) /
  6019. bi->img.h;
  6020. scale = st->bg_size_kind == 3 ?
  6021. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  6022. } else if (st->bg_size_kind == 1 ||
  6023. st->bg_size_kind == 2) {
  6024. int w = st->bg_size_w;
  6025. int h = st->bg_size_h;
  6026. if (st->bg_size_kind == 2) {
  6027. if (w)
  6028. w = box.w * w / 100;
  6029. if (h)
  6030. h = box.h * h / 100;
  6031. }
  6032. if (w)
  6033. scale = ((unsigned int)w << 16) / bi->img.w;
  6034. else if (h)
  6035. scale = ((unsigned int)h << 16) / bi->img.h;
  6036. }
  6037. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  6038. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6039. if (tw < 1)
  6040. tw = 1;
  6041. if (th < 1)
  6042. th = 1;
  6043. posx = st->bg_pos_x_kind == 1 ?
  6044. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  6045. posy = st->bg_pos_y_kind == 1 ?
  6046. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  6047. x = box.x + posx;
  6048. y = box.y + posy;
  6049. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  6050. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  6051. if (rep_x) {
  6052. int m = (x - box.x) % tw;
  6053. if (m > 0)
  6054. m -= tw;
  6055. x = box.x + m;
  6056. }
  6057. if (rep_y) {
  6058. int m = (y - box.y) % th;
  6059. if (m > 0)
  6060. m -= th;
  6061. y = box.y + m;
  6062. }
  6063. }
  6064. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  6065. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  6066. cx2 = box.x + box.w;
  6067. cy2 = box.y + box.h;
  6068. if (cx2 > page_rect.x + page_rect.w - 12)
  6069. cx2 = page_rect.x + page_rect.w - 12;
  6070. if (cy2 > page_rect.y + page_rect.h)
  6071. cy2 = page_rect.y + page_rect.h;
  6072. if (cx1 >= cx2 || cy1 >= cy2)
  6073. return;
  6074. b.dst = l->ui->px;
  6075. b.dst_w = l->ui->w;
  6076. b.dst_h = l->ui->h;
  6077. b.clip_x = cx1;
  6078. b.clip_y = cy1;
  6079. b.clip_w = cx2 - cx1;
  6080. b.clip_h = cy2 - cy1;
  6081. b.bg = ui.theme.bg;
  6082. b.bg2 = ui.theme.bg;
  6083. b.dst_a = 0;
  6084. {
  6085. struct img_image *src = image_display_get(bi, tw, th);
  6086. int row_x;
  6087. if (!src)
  6088. src = &bi->img;
  6089. b.scale = ((unsigned int)tw << 16) / src->w;
  6090. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  6091. row_x = x;
  6092. for (;;) {
  6093. for (;;) {
  6094. b.x = x;
  6095. b.y = y;
  6096. img_draw(src, &b);
  6097. if (!rep_x || ++tiles > 512)
  6098. break;
  6099. x += tw;
  6100. if (x >= box.x + box.w)
  6101. break;
  6102. }
  6103. if (!rep_y || ++rows > 64)
  6104. break;
  6105. y += th;
  6106. if (y >= box.y + box.h)
  6107. break;
  6108. x = row_x;
  6109. }
  6110. }
  6111. }
  6112. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  6113. int *out_w, int *out_h);
  6114. static void svg_paint_box(struct ngui *ui, unsigned int node,
  6115. const struct br_style *st, int x, int y, int w,
  6116. int h);
  6117. /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
  6118. * RUN_SVG an inline <svg> icon (its node in off), RUN_PBOX an empty
  6119. * ::before/::after box with a background (Infima's menu chevrons). */
  6120. #define RUN_SVG (-3)
  6121. #define RUN_PBOX (-4)
  6122. static int run_width(const struct lay_run *r)
  6123. {
  6124. if (r->img >= 0)
  6125. return r->iw;
  6126. if (r->img == -2 || r->img == RUN_SVG || r->img == RUN_PBOX)
  6127. return r->iw;
  6128. return (int)r->w;
  6129. }
  6130. static void start_line(struct lay *l, const struct br_style *st)
  6131. {
  6132. (void)st;
  6133. if (l->nruns == 0) {
  6134. l->line_y = l->y;
  6135. l->line_h = 0;
  6136. }
  6137. l->line_left = l->left;
  6138. l->line_right = l->right;
  6139. if (l->float_active && l->line_y < l->float_bottom) {
  6140. if (l->float_left > l->line_left)
  6141. l->line_left = l->float_left;
  6142. if (l->float_right < l->line_right)
  6143. l->line_right = l->float_right;
  6144. }
  6145. if (l->line_right < l->line_left + 8)
  6146. l->line_right = l->line_left + 8;
  6147. l->line_x = l->line_left;
  6148. l->run_x = l->line_left;
  6149. }
  6150. static void flush_line(struct lay *l)
  6151. {
  6152. int total, x, i, vis;
  6153. if (!l->nruns && l->line_x == l->line_left) {
  6154. l->line_h = 0;
  6155. return;
  6156. }
  6157. total = l->line_x - l->line_left;
  6158. x = l->line_left;
  6159. vis = 1;
  6160. if (l->draw) {
  6161. int lh = l->line_h ? l->line_h : 16;
  6162. vis = l->line_y + lh >= page_rect.y &&
  6163. l->line_y <= page_rect.y + page_rect.h;
  6164. }
  6165. if (l->align == BR_ALIGN_CENTER)
  6166. x += (l->line_right - l->line_left - total) / 2;
  6167. else if (l->align == BR_ALIGN_RIGHT)
  6168. x = l->line_right - total;
  6169. if (x < l->line_left)
  6170. x = l->line_left;
  6171. for (i = 0; i < l->nruns; i++) {
  6172. struct lay_run *r = &l->runs[i];
  6173. int w = run_width(r);
  6174. int ry = l->line_y + r->dy;
  6175. x += r->gap;
  6176. if (l->draw && vis) {
  6177. if (r->form) {
  6178. unsigned int node = r->form - 1;
  6179. struct form_state *fs = form_get(node, 1);
  6180. int hh = r->ih ? r->ih : 20;
  6181. int focused = form_focus == node;
  6182. int disabled = r->form_disabled;
  6183. unsigned short bg = l->ui->theme.panel_alt;
  6184. unsigned short fg = disabled ? 0x8410 : r->color;
  6185. struct ngui_rect box = {x, ry, w, hh};
  6186. if (r->form_kind == FORM_CHECKBOX ||
  6187. r->form_kind == FORM_RADIO) {
  6188. ngui_fill_rect(l->ui, box, bg);
  6189. ngui_frame(l->ui, box,
  6190. focused ? l->ui->theme.accent :
  6191. l->ui->theme.border);
  6192. if (fs && fs->checked) {
  6193. struct ngui_rect dot = {
  6194. x + 4, ry + 4,
  6195. w > 8 ? w - 8 : 1,
  6196. hh > 8 ? hh - 8 : 1
  6197. };
  6198. if (r->form_kind == FORM_RADIO)
  6199. ngui_fill_round_rect(
  6200. l->ui, dot, 4,
  6201. 4, 4, 4,
  6202. l->ui->theme.accent);
  6203. else
  6204. ngui_fill_rect(l->ui,
  6205. dot,
  6206. l->ui->theme.accent);
  6207. }
  6208. } else {
  6209. int editable =
  6210. r->form_kind == FORM_TEXT ||
  6211. r->form_kind == FORM_PASSWORD ||
  6212. r->form_kind == FORM_TEXTAREA;
  6213. int scroll = 0;
  6214. /* Editable fields draw the live value
  6215. * (r->lit is a short copy). */
  6216. static char shown[FORM_VALUE_MAX + 1];
  6217. const char *txt = r->lit;
  6218. unsigned int tl = s_len(r->lit);
  6219. if (editable && fs && fs->len) {
  6220. unsigned int k;
  6221. if (r->form_kind == FORM_PASSWORD) {
  6222. for (k = 0; k < fs->len; k++)
  6223. shown[k] = '*';
  6224. shown[k] = '\0';
  6225. txt = shown;
  6226. } else {
  6227. txt = fs->value;
  6228. }
  6229. tl = fs->len;
  6230. }
  6231. struct br_style fst;
  6232. int author, tx = x + 6, pr = 6;
  6233. style_for_node(node, &fst);
  6234. author = form_author_styled(&fst);
  6235. if (author) {
  6236. /* The page styled the control:
  6237. * its background, border, radius
  6238. * and text colour. */
  6239. form_paint_author(l->ui, box, &fst,
  6240. focused);
  6241. tx = x + fst.border_w[3] +
  6242. mp_px(&fst, 7, w);
  6243. pr = fst.border_w[1] +
  6244. mp_px(&fst, 5, w);
  6245. if (tx < x + 2 && !editable)
  6246. tx = x + 2;
  6247. if (!disabled)
  6248. fg = editable && fs &&
  6249. !fs->len ?
  6250. 0x8410 : fst.color;
  6251. if (!editable) {
  6252. int tw0 = (int)
  6253. run_text_width(l->ui,
  6254. r, txt, tl);
  6255. tx = x + (w - tw0) / 2;
  6256. }
  6257. } else {
  6258. /* The box is drawn in theme colours, so
  6259. * the text is too: the page's CSS colour
  6260. * (dark on a light page) would vanish on
  6261. * the dark field. */
  6262. if (!disabled)
  6263. fg = editable && fs && !fs->len ?
  6264. l->ui->theme.text_dim :
  6265. l->ui->theme.text;
  6266. ngui_fill_rect(l->ui, box, bg);
  6267. ngui_frame(l->ui, box,
  6268. focused ? l->ui->theme.accent :
  6269. l->ui->theme.border);
  6270. }
  6271. /* A value wider than the field shows its
  6272. * tail (where typing happens). */
  6273. if (editable && fs && fs->len &&
  6274. w > (tx - x) + pr) {
  6275. int tw = (int)run_text_width(l->ui,
  6276. r, txt, tl);
  6277. int room = w - (tx - x) - pr;
  6278. if (tw > room)
  6279. scroll = tw - room;
  6280. }
  6281. ngui_push_clip(l->ui, (struct ngui_rect){
  6282. x + 1, ry + 1,
  6283. w > 2 ? w - 2 : 1,
  6284. hh > 2 ? hh - 2 : 1 });
  6285. ngui_text_px_face(l->ui, run_face(r),
  6286. tx - scroll,
  6287. ry + (hh - r->font_px) / 2 - 1,
  6288. txt, tl, fg, r->font_px,
  6289. r->bold, r->italic, r->mono);
  6290. if (focused && fs && editable) {
  6291. int cw = 0;
  6292. if (fs->len && fs->caret)
  6293. cw = (int)run_text_width(
  6294. l->ui, r, txt,
  6295. fs->caret < fs->len ?
  6296. fs->caret : fs->len);
  6297. ngui_fill_rect(l->ui,
  6298. (struct ngui_rect){
  6299. tx + cw - scroll,
  6300. ry + 4, 1,
  6301. hh > 8 ? hh - 8 : 1
  6302. },
  6303. l->ui->theme.accent);
  6304. }
  6305. ngui_pop_clip(l->ui);
  6306. if (r->form_kind == FORM_SELECT) {
  6307. ngui_text_px(l->ui, x + w - 12,
  6308. ry + 2, "v", 1, fg,
  6309. r->font_px, 0, 0, 0);
  6310. }
  6311. }
  6312. } else if (r->img == RUN_PBOX) {
  6313. struct ngui_rect bx = { x, ry, w, r->ih };
  6314. ngui_push_clip(l->ui, bx);
  6315. if (r->pb_has_bg)
  6316. ngui_fill_rect(l->ui, bx, r->pb_bg);
  6317. if (r->pb_img >= 0 && r->pb_img < image_count &&
  6318. images[r->pb_img].state == 1) {
  6319. /* Rotate about the box centre: the
  6320. * image is centred in it here. */
  6321. draw_image_transformed(l->ui,
  6322. &images[r->pb_img].img,
  6323. x + r->pb_x, ry + r->pb_y,
  6324. r->pb_w, r->pb_h,
  6325. r->transform_scale ?
  6326. r->scale_x : 100,
  6327. r->transform_scale ?
  6328. r->scale_y : 100,
  6329. r->transform_scale ?
  6330. r->rotate_x100 : 0,
  6331. 50, 50, 1, 1);
  6332. }
  6333. ngui_pop_clip(l->ui);
  6334. } else if (r->img == RUN_SVG) {
  6335. struct br_style sst;
  6336. style_for_node(r->off, &sst);
  6337. svg_paint_box(l->ui, r->off, &sst, x, ry, w,
  6338. r->ih);
  6339. } else if (r->img == -2) {
  6340. int hh = r->ih ? r->ih : 20;
  6341. ngui_fill_rect(l->ui,
  6342. (struct ngui_rect){x, ry, w, hh},
  6343. l->ui->theme.panel_alt);
  6344. ngui_frame(l->ui,
  6345. (struct ngui_rect){x, ry, w, hh},
  6346. l->ui->theme.border);
  6347. ngui_text_px_face(l->ui, run_face(r),
  6348. x + 6, ry + 2, r->lit,
  6349. s_len(r->lit), r->color,
  6350. r->font_px, r->bold, r->italic,
  6351. r->mono);
  6352. } else if (r->img >= 0) {
  6353. struct br_image *bi = &images[r->img];
  6354. if (bi->state == 1 && r->transform_scale) {
  6355. draw_image_transformed(l->ui, &bi->img,
  6356. x, ry, r->iw, r->ih,
  6357. r->scale_x, r->scale_y,
  6358. r->rotate_x100, r->origin_x,
  6359. r->origin_y, r->origin_x_kind,
  6360. r->origin_y_kind);
  6361. } else if (bi->state == 1) {
  6362. struct img_image *src =
  6363. image_display_get(bi, r->iw, r->ih);
  6364. struct img_blit b;
  6365. if (!src)
  6366. src = &bi->img;
  6367. b.dst = l->ui->px;
  6368. b.dst_w = l->ui->w;
  6369. b.dst_h = l->ui->h;
  6370. b.clip_x = page_rect.x;
  6371. b.clip_y = page_rect.y;
  6372. b.clip_w = page_rect.w - 12;
  6373. b.clip_h = page_rect.h;
  6374. b.x = x;
  6375. b.y = ry;
  6376. b.scale = ((unsigned int)r->iw << 16) /
  6377. src->w;
  6378. b.bg = ui.theme.bg;
  6379. b.bg2 = ui.theme.bg;
  6380. b.dst_a = 0;
  6381. b.flags = src->alpha ?
  6382. IMG_BLIT_OVER_DST : 0;
  6383. img_draw(src, &b);
  6384. }
  6385. } else {
  6386. const char *s = r->has_lit ? r->lit :
  6387. doc.text + r->off;
  6388. unsigned int n = r->has_lit ? s_len(r->lit) :
  6389. r->len;
  6390. ngui_text_px_face(l->ui, run_face(r), x, ry,
  6391. s, n, r->color, r->font_px,
  6392. r->bold, r->italic, r->mono);
  6393. if (r->underline)
  6394. ngui_fill_rect(l->ui,
  6395. (struct ngui_rect){x,
  6396. ry + run_ascent(l->ui, r) + 2,
  6397. w, 1}, r->color);
  6398. if (r->strike)
  6399. ngui_fill_rect(l->ui,
  6400. (struct ngui_rect){x,
  6401. ry + run_ascent(l->ui, r) -
  6402. (r->font_px > 3 ?
  6403. r->font_px / 3 : 1),
  6404. w, 1}, r->color);
  6405. if (r->overline)
  6406. ngui_fill_rect(l->ui,
  6407. (struct ngui_rect){x, ry,
  6408. w, 1}, r->color);
  6409. }
  6410. if (r->form || r->href) {
  6411. if (nhits < HIT_MAX) {
  6412. struct hit *h = &hits[nhits];
  6413. unsigned int target = r->form ?
  6414. r->form - 1 : r->href;
  6415. int hh = (r->form || r->img >= 0 ||
  6416. r->img == RUN_SVG) ?
  6417. r->ih :
  6418. run_line_height(l->ui, r);
  6419. int merge = nhits > 0 &&
  6420. hits[nhits - 1].node == target &&
  6421. hits[nhits - 1].y == ry &&
  6422. hits[nhits - 1].h == hh &&
  6423. x <= hits[nhits - 1].x +
  6424. hits[nhits - 1].w + 2;
  6425. if (merge) {
  6426. struct hit *p = &hits[nhits - 1];
  6427. int end = x + w;
  6428. if (end > p->x + p->w)
  6429. p->w = end - p->x;
  6430. } else {
  6431. h->x = x;
  6432. h->y = ry;
  6433. h->w = w;
  6434. h->h = hh;
  6435. h->node = (unsigned short)target;
  6436. nhits++;
  6437. }
  6438. }
  6439. }
  6440. }
  6441. x += w;
  6442. }
  6443. l->y += l->line_h + 2;
  6444. if (l->float_active && l->y >= l->float_bottom)
  6445. l->float_active = 0;
  6446. l->nruns = 0;
  6447. l->line_x = l->left;
  6448. l->run_x = l->left;
  6449. l->line_left = l->left;
  6450. l->line_right = l->right;
  6451. l->line_h = 0;
  6452. l->space_pending = 0;
  6453. }
  6454. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  6455. const struct br_style *st, unsigned short href,
  6456. const char *lit)
  6457. {
  6458. unsigned int n = lit ? s_len(lit) : len;
  6459. const char *tp = lit ? lit : doc.text + off;
  6460. int w = (int)face_text_width(l->ui, st, tp, n);
  6461. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6462. flush_line(l);
  6463. if (l->nruns == 0) {
  6464. l->line_y = l->y;
  6465. l->line_h = 0;
  6466. start_line(l, st);
  6467. }
  6468. {
  6469. struct lay_run *r = &l->runs[l->nruns++];
  6470. int gap = l->line_x - l->run_x;
  6471. if (gap < 0)
  6472. gap = 0;
  6473. r->gap = (unsigned short)gap;
  6474. r->off = off;
  6475. r->len = len;
  6476. r->color = st->color;
  6477. r->href = href;
  6478. r->dy = 0;
  6479. r->has_lit = 0;
  6480. r->form = 0;
  6481. r->form_kind = 0;
  6482. r->form_disabled = 0;
  6483. r->lit[0] = '\0';
  6484. if (lit && lit[0]) {
  6485. unsigned int i;
  6486. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  6487. r->lit[i] = lit[i];
  6488. r->lit[i] = '\0';
  6489. r->has_lit = 1;
  6490. }
  6491. r->img = -1;
  6492. r->iw = r->ih = 0;
  6493. r->font_px = st->font_px;
  6494. r->bold = st->bold;
  6495. r->italic = st->italic;
  6496. r->mono = st->mono;
  6497. r->font_face = st->font_face;
  6498. /* A control with its own background is a button, not body copy;
  6499. * an inherited link underline would strike through the fill. */
  6500. r->underline = st->underline && !st->has_bg;
  6501. r->strike = st->strike && !st->has_bg;
  6502. r->overline = st->overline && !st->has_bg;
  6503. r->w = (unsigned short)w;
  6504. if (r->has_lit)
  6505. r->w = (unsigned short)run_text_width(
  6506. l->ui, r, r->lit, s_len(r->lit));
  6507. w = r->w;
  6508. }
  6509. l->line_x += w;
  6510. l->run_x = l->line_x;
  6511. {
  6512. int lh = face_line_height(l->ui, st);
  6513. if (st->line_h_px)
  6514. lh = st->line_h_px;
  6515. else if (st->line_h_pct)
  6516. lh = st->font_px * st->line_h_pct / 100;
  6517. if (lh < face_line_height(l->ui, st))
  6518. lh = face_line_height(l->ui, st);
  6519. if (l->line_h < lh)
  6520. l->line_h = lh;
  6521. }
  6522. }
  6523. static void add_image_run(struct lay *l, unsigned int node,
  6524. const struct br_style *st, unsigned short href)
  6525. {
  6526. struct br_image *bi = 0;
  6527. int idx = doc.nodes[node].img_index;
  6528. int dw, dh, maxw;
  6529. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  6530. bi = &images[idx];
  6531. if (l->nruns == 0)
  6532. start_line(l, st);
  6533. if (l->space_pending &&
  6534. (l->nruns > 0 || l->line_x > l->line_left)) {
  6535. int sp = (int)face_text_width(l->ui, st, " ", 1);
  6536. if (l->line_x + sp <= l->line_right)
  6537. l->line_x += sp;
  6538. }
  6539. l->space_pending = 0;
  6540. if (!bi) {
  6541. const char *alt = br_alt(&doc, node);
  6542. struct br_style gs = *st;
  6543. char tmp[96];
  6544. unsigned int n = 0;
  6545. int w;
  6546. gs.color = BR_GRAY;
  6547. gs.underline = 0;
  6548. s_append(tmp, &n, "[", sizeof(tmp));
  6549. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  6550. s_append(tmp, &n, "]", sizeof(tmp));
  6551. w = (int)face_text_width(l->ui, &gs, tmp, n);
  6552. if (l->line_x + w > l->line_right &&
  6553. (l->nruns > 0 || l->line_x > l->line_left))
  6554. flush_line(l);
  6555. add_run(l, 0, 0, &gs, href, tmp);
  6556. if (!l->draw) {
  6557. int t = l->line_y < 0 ? 0 : l->line_y;
  6558. int hh = face_line_height(l->ui, &gs);
  6559. if (t > 65535)
  6560. t = 65535;
  6561. if (hh > 65535)
  6562. hh = 65535;
  6563. img_top[node] = (unsigned short)t;
  6564. img_h[node] = (unsigned short)hh;
  6565. }
  6566. return;
  6567. }
  6568. maxw = l->line_right - l->line_left;
  6569. if (maxw < 8)
  6570. maxw = 8;
  6571. {
  6572. int iw = bi->native_w, ih = bi->native_h;
  6573. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  6574. if (iw <= 0 || ih <= 0) {
  6575. iw = (int)bi->img.w;
  6576. ih = (int)bi->img.h;
  6577. }
  6578. dw = iw;
  6579. dh = ih;
  6580. if (doc.nodes[node].width_attr) {
  6581. int want = doc.nodes[node].width_attr;
  6582. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  6583. have_w = 1;
  6584. }
  6585. if (doc.nodes[node].height_attr) {
  6586. int want = doc.nodes[node].height_attr;
  6587. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  6588. have_h = 1;
  6589. }
  6590. if (have_w && !have_h)
  6591. dh = ih ? ih * dw / iw : 0;
  6592. if (have_h && !have_w)
  6593. dw = iw ? iw * dh / ih : 0;
  6594. if (st->width_kind) {
  6595. css_w = 1;
  6596. if (st->width_kind == 3)
  6597. dw = maxw * st->width_calc_pct / 100 +
  6598. st->width_calc_px;
  6599. else
  6600. dw = st->width_kind == 2 ?
  6601. maxw * (int)st->width / 100 :
  6602. (int)st->width;
  6603. }
  6604. /* Percentage heights resolve against the containing block's
  6605. * definite height (Docusaurus' logo: `.navbar__logo { height:
  6606. * 2rem }` holding an `img { height: 100% }`), and are auto
  6607. * when it has none; they used to use the width. */
  6608. if (st->height_kind == 1 ||
  6609. ((st->height_kind == 2 || st->height_kind == 3) &&
  6610. l->cb_h > 0)) {
  6611. css_h = 1;
  6612. if (st->height_kind == 3)
  6613. dh = l->cb_h * st->height_calc_pct / 100 +
  6614. st->height_calc_px;
  6615. else
  6616. dh = st->height_kind == 2 ?
  6617. l->cb_h * (int)st->height / 100 :
  6618. (int)st->height;
  6619. }
  6620. if (css_w && !css_h)
  6621. dh = ih ? ih * dw / iw : 0;
  6622. if (css_h && !css_w)
  6623. dw = iw ? iw * dh / ih : 0;
  6624. if (st->max_width_kind) {
  6625. int mw = st->max_width_kind == 3 ?
  6626. maxw * st->max_width_calc_pct / 100 +
  6627. st->max_width_calc_px :
  6628. st->max_width_kind == 2 ?
  6629. maxw * (int)st->max_width / 100 :
  6630. (int)st->max_width;
  6631. if (mw > 0 && dw > mw) {
  6632. dh = iw ? ih * mw / iw : 0;
  6633. dw = mw;
  6634. }
  6635. }
  6636. }
  6637. if (dw < 8)
  6638. dw = 8;
  6639. if (dh < 8)
  6640. dh = 8;
  6641. if (dw > maxw) {
  6642. dh = dw ? dh * maxw / dw : dh;
  6643. dw = maxw;
  6644. }
  6645. if (!l->draw) {
  6646. int t = l->line_y < 0 ? 0 : l->line_y;
  6647. if (t > 65535)
  6648. t = 65535;
  6649. if (dh > 65535)
  6650. dh = 65535;
  6651. img_top[node] = (unsigned short)t;
  6652. img_h[node] = (unsigned short)dh;
  6653. }
  6654. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  6655. l->line_x > l->line_left))
  6656. flush_line(l);
  6657. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6658. flush_line(l);
  6659. if (l->nruns == 0) {
  6660. l->line_y = l->y;
  6661. l->line_h = 0;
  6662. start_line(l, st);
  6663. }
  6664. {
  6665. struct lay_run *r = &l->runs[l->nruns++];
  6666. int gap = l->line_x - l->run_x;
  6667. if (gap < 0)
  6668. gap = 0;
  6669. r->gap = (unsigned short)gap;
  6670. r->off = 0;
  6671. r->len = 0;
  6672. r->color = 0;
  6673. r->href = href;
  6674. r->form = 0;
  6675. r->form_kind = 0;
  6676. r->form_disabled = 0;
  6677. /* Inline replaced elements honour their vertical margins; this
  6678. * is how Bootstrap's negative logo margins centre the wordmark. */
  6679. {
  6680. int idy = mp_px(st, 0, l->right - l->left);
  6681. if (idy < -2048)
  6682. idy = -2048;
  6683. if (idy > 2048)
  6684. idy = 2048;
  6685. r->dy = (signed short)idy;
  6686. }
  6687. r->has_lit = 0;
  6688. r->lit[0] = '\0';
  6689. r->img = (short)idx;
  6690. r->iw = (unsigned short)dw;
  6691. r->ih = (unsigned short)dh;
  6692. r->w = (unsigned short)dw;
  6693. r->font_px = st->font_px;
  6694. r->bold = st->bold;
  6695. r->italic = st->italic;
  6696. r->mono = st->mono;
  6697. r->font_face = st->font_face;
  6698. r->transform_scale = st->transform_scale;
  6699. r->scale_x = st->scale_x;
  6700. r->scale_y = st->scale_y;
  6701. r->rotate_x100 = st->rotate_x100;
  6702. r->origin_x = st->origin_x;
  6703. r->origin_y = st->origin_y;
  6704. r->origin_x_kind = st->origin_x_kind;
  6705. r->origin_y_kind = st->origin_y_kind;
  6706. r->underline = 0;
  6707. }
  6708. if (node < BR_MAX_NODES) {
  6709. layout_boxes[node].x = l->line_x;
  6710. layout_boxes[node].y = l->line_y +
  6711. mp_px(st, 0, l->right - l->left);
  6712. layout_boxes[node].w = dw;
  6713. layout_boxes[node].h = dh;
  6714. layout_boxes[node].valid = 1;
  6715. }
  6716. l->line_x += dw;
  6717. l->run_x = l->line_x;
  6718. if (l->line_h < dh)
  6719. l->line_h = dh;
  6720. }
  6721. /* An inline (or inline-block) <svg> is a replaced element in the text
  6722. * line, like an <img>: comment bubbles and arrows sit next to their label
  6723. * instead of starting a block of their own. */
  6724. static void add_svg_run(struct lay *l, unsigned int node,
  6725. const struct br_style *st, unsigned short href)
  6726. {
  6727. struct lay_run *r;
  6728. int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
  6729. if (lw < 8)
  6730. lw = 8;
  6731. cw = st->width_kind ? style_width_px(st, lw) : lw;
  6732. if (cw < 1)
  6733. cw = 1;
  6734. svg_size(node, st, cw, &dw, &dh);
  6735. if (dw > lw)
  6736. dw = lw;
  6737. ml = mp_px(st, 3, lw);
  6738. mr = mp_px(st, 1, lw);
  6739. if (ml < 0)
  6740. ml = 0;
  6741. if (mr < 0)
  6742. mr = 0;
  6743. if (l->line_x + ml + dw > l->line_right &&
  6744. (l->nruns > 0 || l->line_x > l->line_left))
  6745. flush_line(l);
  6746. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6747. flush_line(l);
  6748. if (l->nruns == 0) {
  6749. l->line_y = l->y;
  6750. l->line_h = 0;
  6751. start_line(l, st);
  6752. }
  6753. l->line_x += ml;
  6754. r = &l->runs[l->nruns++];
  6755. memset(r, 0, sizeof(*r));
  6756. r->gap = (unsigned short)(l->line_x > l->run_x ?
  6757. l->line_x - l->run_x : 0);
  6758. r->off = node;
  6759. r->color = st->color;
  6760. r->href = href;
  6761. r->img = RUN_SVG;
  6762. r->iw = (unsigned short)dw;
  6763. r->ih = (unsigned short)dh;
  6764. r->w = (unsigned short)dw;
  6765. r->font_px = st->font_px;
  6766. if (node < BR_MAX_NODES) {
  6767. layout_boxes[node].x = l->line_x;
  6768. layout_boxes[node].y = l->line_y;
  6769. layout_boxes[node].w = dw;
  6770. layout_boxes[node].h = dh;
  6771. layout_boxes[node].valid = 1;
  6772. }
  6773. l->line_x += dw + mr;
  6774. l->run_x = l->line_x;
  6775. if (l->line_h < dh)
  6776. l->line_h = dh;
  6777. }
  6778. static int text_width(struct lay *l, const char *s, unsigned int n,
  6779. const struct br_style *st)
  6780. {
  6781. return (int)face_text_width(l->ui, st, s, n);
  6782. }
  6783. /* Longest prefix that fits in maxw, at least one byte. */
  6784. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  6785. const struct br_style *st, int maxw)
  6786. {
  6787. unsigned int take = 0;
  6788. while (take < n) {
  6789. if (text_width(l, s, take + 1, st) > maxw)
  6790. break;
  6791. take++;
  6792. }
  6793. return take ? take : 1;
  6794. }
  6795. static void emit_word(struct lay *l, const char *s, unsigned int start,
  6796. unsigned int n, unsigned int base,
  6797. const struct br_style *st, unsigned short href)
  6798. {
  6799. int avail;
  6800. int w = text_width(l, s + start, n, st);
  6801. unsigned int off = start;
  6802. if (l->nruns == 0)
  6803. start_line(l, st);
  6804. avail = l->line_right - l->line_left;
  6805. if (st->nowrap) {
  6806. if (n)
  6807. add_run(l, base + start,
  6808. (unsigned short)n, st, href, 0);
  6809. return;
  6810. }
  6811. /* A padded/bordered one-word button can be a few pixels wider than
  6812. * the content box; keep it on one line instead of splitting it. */
  6813. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  6814. add_run(l, base + start,
  6815. (unsigned short)n, st, href, 0);
  6816. return;
  6817. }
  6818. if (l->line_x + w > l->line_right &&
  6819. (l->nruns > 0 || l->line_x > l->line_left)) {
  6820. flush_line(l);
  6821. start_line(l, st);
  6822. avail = l->line_right - l->line_left;
  6823. }
  6824. if (w <= avail) {
  6825. if (n)
  6826. add_run(l, base + start,
  6827. (unsigned short)n, st, href, 0);
  6828. return;
  6829. }
  6830. while (n > 0) {
  6831. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  6832. add_run(l, base + off,
  6833. (unsigned short)take, st, href, 0);
  6834. off += take;
  6835. n -= take;
  6836. if (n) {
  6837. flush_line(l);
  6838. start_line(l, st);
  6839. avail = l->line_right - l->line_left;
  6840. }
  6841. }
  6842. }
  6843. static void emit_text(struct lay *l, const char *s, unsigned int len,
  6844. const struct br_style *st, unsigned short href, int pre)
  6845. {
  6846. unsigned int i = 0;
  6847. unsigned int base;
  6848. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  6849. if (!s || !len)
  6850. return;
  6851. if (space_w <= 0)
  6852. space_w = 8;
  6853. if (l->nruns == 0)
  6854. start_line(l, st);
  6855. base = (unsigned int)(s - doc.text);
  6856. if (st->uppercase) {
  6857. char *p = (char *)s;
  6858. unsigned int j;
  6859. for (j = 0; j < len; j++)
  6860. if (p[j] >= 'a' && p[j] <= 'z')
  6861. p[j] = (char)(p[j] - 'a' + 'A');
  6862. }
  6863. if (pre) {
  6864. while (i < len) {
  6865. unsigned int start;
  6866. if (s[i] == '\n') {
  6867. flush_line(l);
  6868. start_line(l, st);
  6869. i++;
  6870. continue;
  6871. }
  6872. if (s[i] == ' ') {
  6873. if (l->line_x + space_w > l->line_right &&
  6874. (l->nruns > 0 || l->line_x > l->line_left)) {
  6875. flush_line(l);
  6876. start_line(l, st);
  6877. } else {
  6878. l->line_x += space_w;
  6879. }
  6880. i++;
  6881. continue;
  6882. }
  6883. start = i;
  6884. while (i < len && s[i] != ' ' && s[i] != '\n')
  6885. i++;
  6886. emit_word(l, s, start, i - start, base, st, href);
  6887. }
  6888. return;
  6889. }
  6890. while (i < len) {
  6891. unsigned int start, n;
  6892. if (s[i] == ' ') {
  6893. l->space_pending = 1;
  6894. i++;
  6895. continue;
  6896. }
  6897. start = i;
  6898. while (i < len && s[i] != ' ')
  6899. i++;
  6900. n = i - start;
  6901. if (l->space_pending &&
  6902. (l->nruns > 0 || l->line_x > l->line_left)) {
  6903. if (st->nowrap ||
  6904. l->line_x + space_w <= l->line_right)
  6905. l->line_x += space_w;
  6906. }
  6907. l->space_pending = 0;
  6908. emit_word(l, s, start, n, base, st, href);
  6909. }
  6910. }
  6911. static int list_index(unsigned int parent, unsigned int node)
  6912. {
  6913. unsigned int n = 0, i;
  6914. for (i = doc.nodes[parent].first; i && i != node;
  6915. i = doc.nodes[i].next)
  6916. if (doc.nodes[i].tag == BR_TAG_LI)
  6917. n++;
  6918. return (int)n + 1;
  6919. }
  6920. static void list_roman(char *m, unsigned int *n, int v, int upper,
  6921. unsigned int cap)
  6922. {
  6923. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  6924. 50, 40, 10, 9, 5, 4, 1 };
  6925. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  6926. "l", "xl", "x", "ix", "v", "iv", "i" };
  6927. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  6928. "L", "XL", "X", "IX", "V", "IV", "I" };
  6929. unsigned int i;
  6930. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  6931. while (v >= val[i] && *n + 1 < cap) {
  6932. const char *s = upper ? up[i] : lo[i];
  6933. while (*s && *n + 1 < cap)
  6934. m[(*n)++] = *s++;
  6935. v -= val[i];
  6936. }
  6937. }
  6938. }
  6939. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  6940. {
  6941. unsigned int n = 0;
  6942. if (style == BR_LIST_DISC) {
  6943. m[n++] = '-';
  6944. } else if (style == BR_LIST_CIRCLE) {
  6945. m[n++] = 'o';
  6946. } else if (style == BR_LIST_SQUARE) {
  6947. m[n++] = '+';
  6948. } else if (style == BR_LIST_LOWER_ALPHA ||
  6949. style == BR_LIST_UPPER_ALPHA) {
  6950. if (idx >= 1 && idx <= 26)
  6951. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  6952. 'A' : 'a') + idx - 1);
  6953. else
  6954. m[n++] = '?';
  6955. m[n++] = '.';
  6956. } else if (style == BR_LIST_LOWER_ROMAN ||
  6957. style == BR_LIST_UPPER_ROMAN) {
  6958. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  6959. if (n + 1 < cap)
  6960. m[n++] = '.';
  6961. } else {
  6962. s_append_dec(m, &n, (unsigned int)idx, cap);
  6963. if (n + 1 < cap)
  6964. m[n++] = '.';
  6965. }
  6966. m[n] = '\0';
  6967. }
  6968. /* A control the page styled itself (background, border or radius in author
  6969. * CSS -- `background:transparent;border:none` counts) is painted with that
  6970. * style, sized from its padding/height and keeps the page's text colour.
  6971. * Unstyled controls keep the ngui theme look. */
  6972. static int form_author_styled(const struct br_style *st)
  6973. {
  6974. int i;
  6975. if (st->bg_set)
  6976. return 1;
  6977. for (i = 0; i < 4; i++)
  6978. if (st->border_w[i] || st->radius[i])
  6979. return 1;
  6980. return 0;
  6981. }
  6982. /* Set by the layout when the control is stretched to its line: a flex item
  6983. * (its box width was assigned by the flex row) or a child of a flex column,
  6984. * whose default align-items: stretch makes inputs full width. */
  6985. static int form_fill_line;
  6986. static void add_form_run(struct lay *l, unsigned int node,
  6987. const struct br_style *st, unsigned short href)
  6988. {
  6989. struct form_state *fs = form_get(node, 1);
  6990. char shown[FORM_VALUE_MAX + 1];
  6991. char opt[64];
  6992. const char *text = "";
  6993. struct lay_run *r;
  6994. int kind = form_kind_of(node);
  6995. int disabled = form_disabled(node);
  6996. int author = form_author_styled(st);
  6997. int tw, w = 120, h = 20, i, line_w, pad_x, pad_y;
  6998. int ml = 0, mr = 0, mt = 0, mb = 0;
  6999. if (!fs)
  7000. return;
  7001. if (l->nruns == 0)
  7002. start_line(l, st);
  7003. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  7004. text = "";
  7005. w = 16;
  7006. h = 16;
  7007. } else if (kind == FORM_SELECT) {
  7008. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  7009. s_copy(opt, "Select", sizeof(opt));
  7010. text = opt;
  7011. w = 120;
  7012. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  7013. kind == FORM_RESET) {
  7014. if (fs->len)
  7015. text = fs->value;
  7016. else if (doc.nodes[node].tag == BR_TAG_BUTTON)
  7017. /* A <button>'s label is its content: an empty one
  7018. * (Docusaurus' sidebar caret, drawn by a CSS
  7019. * ::before icon) shows none. Only <input> buttons
  7020. * get the UA's default label. */
  7021. text = "";
  7022. else
  7023. text = kind == FORM_SUBMIT ? "Submit" :
  7024. kind == FORM_RESET ? "Reset" : "Button";
  7025. } else if (kind == FORM_PASSWORD) {
  7026. for (i = 0; i < fs->len; i++)
  7027. shown[i] = '*';
  7028. shown[fs->len] = '\0';
  7029. text = fs->len ? shown : br_placeholder(&doc, node);
  7030. } else {
  7031. if (fs->len)
  7032. text = fs->value;
  7033. else
  7034. text = br_placeholder(&doc, node);
  7035. if (kind == FORM_TEXTAREA) {
  7036. w = 180;
  7037. h = 40;
  7038. }
  7039. }
  7040. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  7041. line_w = l->line_right - l->line_left;
  7042. pad_x = mp_px(st, 7, line_w) + mp_px(st, 5, line_w) +
  7043. st->border_w[1] + st->border_w[3];
  7044. pad_y = mp_px(st, 4, line_w) + mp_px(st, 6, line_w) +
  7045. st->border_w[0] + st->border_w[2];
  7046. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  7047. /* Buttons are border-box in every UA stylesheet: an
  7048. * explicit width/height is the whole box. */
  7049. if (author || pad_x) {
  7050. w = tw + pad_x;
  7051. } else {
  7052. w = tw + 18;
  7053. if (w < 64)
  7054. w = 64;
  7055. }
  7056. if (st->width_kind)
  7057. w = style_width_px(st, line_w);
  7058. if (st->min_width_kind == 1 && w < (int)st->min_width)
  7059. w = st->min_width;
  7060. if (st->height_kind == 1)
  7061. h = st->height;
  7062. else if (author)
  7063. h = st->font_px + 6 + pad_y;
  7064. else
  7065. h = 22;
  7066. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  7067. kind == FORM_TEXTAREA) {
  7068. int fill = form_fill_line || st->display == BR_DISPLAY_BLOCK ||
  7069. st->display == BR_DISPLAY_FLEX;
  7070. int boxed = st->box_sizing ? 0 : pad_x;
  7071. if (st->width_kind)
  7072. w = style_width_px(st, line_w) + boxed;
  7073. else if (fill)
  7074. w = line_w - (l->line_x - l->line_left);
  7075. else
  7076. w = kind == FORM_TEXTAREA ? 180 : 120;
  7077. if (kind == FORM_TEXTAREA) {
  7078. const char *ra = br_find_attr(&doc, node, "rows");
  7079. int rows = 0;
  7080. int lh = st->line_h_px ? st->line_h_px :
  7081. st->font_px * 5 / 4;
  7082. while (ra && *ra >= '0' && *ra <= '9')
  7083. rows = rows * 10 + (*ra++ - '0');
  7084. if (rows < 1 || rows > 40)
  7085. rows = 2;
  7086. h = author ? rows * lh + pad_y : 40;
  7087. } else if (author) {
  7088. h = st->font_px + 8 + pad_y;
  7089. } else if (st->font_px + 8 > h) {
  7090. /* Taller fields for large text (min-height/padding
  7091. * on login pages): keep the box around the glyphs. */
  7092. h = st->font_px + 8;
  7093. }
  7094. if (st->height_kind == 1)
  7095. h = st->height + (st->box_sizing ? 0 : pad_y);
  7096. if (st->min_height_kind == 1 && h < (int)st->min_height)
  7097. h = st->min_height;
  7098. } else if (kind == FORM_SELECT) {
  7099. w = st->width_kind == 1 ? st->width : 120;
  7100. }
  7101. if (author) {
  7102. /* Inline margins (Google's `margin:11px 4px` between its
  7103. * two submit buttons). */
  7104. ml = mp_px(st, 3, line_w);
  7105. mr = mp_px(st, 1, line_w);
  7106. mt = mp_px(st, 0, line_w);
  7107. mb = mp_px(st, 2, line_w);
  7108. if (ml < 0 || ml > 64) ml = 0;
  7109. if (mr < 0 || mr > 64) mr = 0;
  7110. if (mt < 0 || mt > 64) mt = 0;
  7111. if (mb < 0 || mb > 64) mb = 0;
  7112. }
  7113. if (w > line_w - ml - mr)
  7114. w = line_w - ml - mr;
  7115. if (w < 8)
  7116. w = 8;
  7117. if (h > 400)
  7118. h = 400;
  7119. if (l->line_x + ml + w > l->line_right &&
  7120. (l->nruns > 0 || l->line_x > l->line_left))
  7121. flush_line(l);
  7122. if (l->nruns >= 96)
  7123. return;
  7124. if (l->nruns == 0) {
  7125. l->line_y = l->y;
  7126. l->line_h = 0;
  7127. start_line(l, st);
  7128. }
  7129. l->line_x += ml;
  7130. r = &l->runs[l->nruns++];
  7131. r->gap = (unsigned short)(l->line_x - l->run_x);
  7132. r->off = r->len = 0;
  7133. r->color = st->color;
  7134. r->href = href;
  7135. r->dy = (signed short)mt;
  7136. r->has_lit = 1;
  7137. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  7138. r->lit[i] = text[i];
  7139. r->lit[i] = '\0';
  7140. r->img = -2;
  7141. r->iw = (unsigned short)w;
  7142. r->ih = (unsigned short)h;
  7143. r->w = (unsigned short)w;
  7144. r->font_px = st->font_px;
  7145. r->bold = st->bold;
  7146. r->italic = st->italic;
  7147. r->mono = st->mono;
  7148. r->font_face = st->font_face;
  7149. r->underline = 0;
  7150. r->form = node + 1;
  7151. r->form_kind = (unsigned char)kind;
  7152. r->form_disabled = (unsigned char)disabled;
  7153. if (node < BR_MAX_NODES) {
  7154. layout_boxes[node].x = l->line_x;
  7155. layout_boxes[node].y = l->line_y + mt;
  7156. layout_boxes[node].w = w;
  7157. layout_boxes[node].h = h;
  7158. layout_boxes[node].valid = 1;
  7159. }
  7160. l->line_x += w;
  7161. l->run_x = l->line_x;
  7162. l->line_x += mr;
  7163. if (l->line_h < h + mt + mb)
  7164. l->line_h = h + mt + mb;
  7165. }
  7166. /* Background, border and corner radius of an author-styled control, the
  7167. * same decoration rules as a block box. */
  7168. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  7169. const struct br_style *st, int focused)
  7170. {
  7171. int rtl = css_radius(st, 0, box.w, box.h);
  7172. int rtr = css_radius(st, 1, box.w, box.h);
  7173. int rbr = css_radius(st, 2, box.w, box.h);
  7174. int rbl = css_radius(st, 3, box.w, box.h);
  7175. int bw = st->border_t[0] ? 0 : st->border_w[0];
  7176. (void)focused;
  7177. if (box.w <= 0 || box.h <= 0)
  7178. return;
  7179. if (rtl || rtr || rbr || rbl) {
  7180. if (bw > 0 && st->has_bg && st->border_c[0] != st->bg &&
  7181. box.w > bw * 2 && box.h > bw * 2) {
  7182. struct ngui_rect in = { box.x + bw, box.y + bw,
  7183. box.w - bw * 2,
  7184. box.h - bw * 2 };
  7185. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  7186. st->border_c[0]);
  7187. ngui_fill_round_rect(ui, in,
  7188. rtl > bw ? rtl - bw : 0,
  7189. rtr > bw ? rtr - bw : 0,
  7190. rbr > bw ? rbr - bw : 0,
  7191. rbl > bw ? rbl - bw : 0, st->bg);
  7192. } else if (st->has_bg) {
  7193. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  7194. st->bg);
  7195. } else if (bw > 0) {
  7196. ngui_frame_round(ui, box, rtl, rtr, rbr, rbl, bw,
  7197. st->border_c[0]);
  7198. }
  7199. return;
  7200. }
  7201. if (st->has_bg)
  7202. ngui_fill_rect(ui, box, st->bg);
  7203. if (st->border_w[0] || st->border_w[1] || st->border_w[2] ||
  7204. st->border_w[3])
  7205. draw_border_box(ui, box, st);
  7206. }
  7207. /* A poster wrapper is absolutely positioned over the media slot; the
  7208. * measured height of its picture is normally added back to the flow. When a
  7209. * loading-skeleton sibling already reserves that slot, adding both doubles
  7210. * the media height and pushes the article text a full screen down. */
  7211. static int has_skeleton_sibling(unsigned int node)
  7212. {
  7213. unsigned int p = doc.nodes[node].parent, c;
  7214. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  7215. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  7216. continue;
  7217. if (doc.nodes[c].class_off &&
  7218. contains_ci(doc.attrs + doc.nodes[c].class_off,
  7219. "skeleton"))
  7220. return 1;
  7221. }
  7222. return 0;
  7223. }
  7224. static void layout_children(struct lay *l, unsigned int parent,
  7225. const struct br_style *pst, int depth,
  7226. unsigned short link);
  7227. static void layout_flex_children(struct lay *l, unsigned int parent,
  7228. const struct br_style *pst, int depth,
  7229. unsigned short link);
  7230. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  7231. struct br_style *ps, int base);
  7232. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  7233. const struct br_style *ps, unsigned short link);
  7234. static void layout_grid_children(struct lay *l, unsigned int parent,
  7235. const struct br_style *pst, int depth,
  7236. unsigned short link);
  7237. static void layout_grid_auto(struct lay *l, unsigned int parent,
  7238. const struct br_style *pst, int depth,
  7239. unsigned short link);
  7240. static int flex_item_width(struct lay *l, unsigned int n,
  7241. const struct br_style *cs, int avail);
  7242. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  7243. const struct br_style *pst, int depth,
  7244. unsigned short link);
  7245. static void layout_table_row(struct lay *l, unsigned int row,
  7246. const struct br_style *pst, int depth,
  7247. unsigned short link);
  7248. static int table_has_rowspan(unsigned int table);
  7249. static void layout_table(struct lay *l, unsigned int table,
  7250. const struct br_style *st, int depth,
  7251. unsigned short link);
  7252. /* A flex container whose items are only inline spans is usually just a
  7253. * heading/icon pair. Our flex row positions such items without emitting
  7254. * their inline text in some deep page contexts; normal inline flow renders
  7255. * the same content correctly. */
  7256. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  7257. {
  7258. unsigned int c;
  7259. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7260. struct br_node *nd = &doc.nodes[c];
  7261. struct br_style cs;
  7262. if (nd->type == BR_NODE_TEXT)
  7263. continue;
  7264. br_style_for(&doc, c, pst, &cs);
  7265. if (cs.display == BR_DISPLAY_NONE)
  7266. continue;
  7267. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  7268. cs.width_kind || cs.has_bg ||
  7269. cs.border_w[0] || cs.border_w[1] ||
  7270. cs.border_w[2] || cs.border_w[3] ||
  7271. nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG)
  7272. return 1;
  7273. }
  7274. return 0;
  7275. }
  7276. static int css_radius(const struct br_style *st, int corner,
  7277. int w, int h)
  7278. {
  7279. int r = st->radius[corner];
  7280. if (r <= 0)
  7281. return 0;
  7282. if (r > w / 2)
  7283. r = w / 2;
  7284. if (r > h / 2)
  7285. r = h / 2;
  7286. return r;
  7287. }
  7288. /* ---- inline SVG ----
  7289. *
  7290. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  7291. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  7292. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  7293. * opacity and solid paint; a gradient paints the average of its stops) and
  7294. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  7295. #define SVG_CACHE_MAX 48
  7296. #define SVG_CACHE_PIXELS (640 * 1024)
  7297. #define SVG_MAX_POINTS 24576
  7298. struct svg_cache_ent {
  7299. unsigned int node;
  7300. int w, h;
  7301. unsigned short *px;
  7302. unsigned char *a;
  7303. unsigned int stamp;
  7304. };
  7305. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  7306. static unsigned int svg_cache_pixels, svg_cache_clock;
  7307. static struct svgr svg_geom;
  7308. static void *svg_geom_buf;
  7309. /* Current viewport in user units: percentage lengths resolve against it
  7310. * (the viewBox size, not the device pixels). */
  7311. static double svg_vp_w = 300, svg_vp_h = 150;
  7312. /* The layers live in the page heap: forget them before heap_reset(). */
  7313. static void svg_cache_clear(void)
  7314. {
  7315. memset(svg_cache, 0, sizeof(svg_cache));
  7316. svg_cache_pixels = 0;
  7317. svg_geom_buf = 0;
  7318. }
  7319. static int svg_name_is(const char *a, const char *b)
  7320. {
  7321. while (*a && *b) {
  7322. char x = *a, y = *b;
  7323. if (x >= 'A' && x <= 'Z')
  7324. x = (char)(x - 'A' + 'a');
  7325. if (x != y)
  7326. return 0;
  7327. a++;
  7328. b++;
  7329. }
  7330. return *a == *b;
  7331. }
  7332. static const char *svg_elem_name(unsigned int node)
  7333. {
  7334. const struct br_node *nd = &doc.nodes[node];
  7335. if (nd->name_off)
  7336. return doc.attrs + nd->name_off;
  7337. return br_tag_name(nd->tag);
  7338. }
  7339. /* A numeric attribute; a percentage resolves against `base`. */
  7340. static double svg_attr_num(unsigned int node, const char *name, double def,
  7341. double base)
  7342. {
  7343. const char *v = br_find_attr(&doc, node, name);
  7344. const char *p = v;
  7345. int ok = 0;
  7346. double x;
  7347. if (!v)
  7348. return def;
  7349. x = svgr_num(&p, &ok);
  7350. if (!ok)
  7351. return def;
  7352. if (*p == '%')
  7353. x = x * base / 100.0;
  7354. return x;
  7355. }
  7356. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  7357. static int svg_viewbox4(unsigned int node, double vb[4])
  7358. {
  7359. const char *v = br_find_attr(&doc, node, "viewbox");
  7360. const char *p = v;
  7361. int i, ok = 1;
  7362. if (!v)
  7363. return 0;
  7364. for (i = 0; i < 4 && ok; i++)
  7365. vb[i] = svgr_num(&p, &ok);
  7366. return ok && vb[2] > 0 && vb[3] > 0;
  7367. }
  7368. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  7369. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  7370. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  7371. double w, double h, double m[6])
  7372. {
  7373. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  7374. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  7375. int ax = 1, ay = 1;
  7376. if (par && contains_ci(par, "none")) {
  7377. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  7378. m[4] = -vb[0] * sx;
  7379. m[5] = -vb[1] * sy;
  7380. return;
  7381. }
  7382. if (par) {
  7383. if (contains_ci(par, "xmin"))
  7384. ax = 0;
  7385. else if (contains_ci(par, "xmax"))
  7386. ax = 2;
  7387. if (contains_ci(par, "ymin"))
  7388. ay = 0;
  7389. else if (contains_ci(par, "ymax"))
  7390. ay = 2;
  7391. }
  7392. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  7393. (sx < sy ? sx : sy);
  7394. tx = (w - vb[2] * s) * ax / 2.0;
  7395. ty = (h - vb[3] * s) * ay / 2.0;
  7396. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  7397. m[4] = tx - vb[0] * s;
  7398. m[5] = ty - vb[1] * s;
  7399. }
  7400. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  7401. * the paint attribute, then average the gradient's stops. */
  7402. static int svg_url_paint(unsigned int node, const char *attr,
  7403. unsigned short *color, unsigned int *alpha)
  7404. {
  7405. const char *v = 0, *h;
  7406. char id[64];
  7407. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  7408. for (k = 0; node && k < 32 && !v; k++) {
  7409. v = br_find_attr(&doc, node, attr);
  7410. if (!v) {
  7411. const char *style = br_find_attr(&doc, node, "style");
  7412. if (style && contains_ci(style, "url(#"))
  7413. v = strstr(style, "url(#");
  7414. }
  7415. if (v && !contains_ci(v, "url("))
  7416. v = 0;
  7417. node = doc.nodes[node].parent;
  7418. }
  7419. if (!v || !(h = strstr(v, "#")))
  7420. return 0;
  7421. h++;
  7422. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  7423. id[n++] = *h++;
  7424. id[n] = '\0';
  7425. g = br_find_id(&doc, id);
  7426. /* Follow href chains (a gradient that only references another one's
  7427. * stops), at most a few hops. */
  7428. for (k = 0; g && k < 4; k++) {
  7429. unsigned int gi = g - 1;
  7430. const char *ref;
  7431. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  7432. const char *nm, *sc, *so;
  7433. unsigned short col = 0;
  7434. double op = 1;
  7435. if (doc.nodes[c].type != BR_NODE_ELEM)
  7436. continue;
  7437. nm = svg_elem_name(c);
  7438. if (!svg_name_is(nm, "stop"))
  7439. continue;
  7440. sc = br_find_attr(&doc, c, "stop-color");
  7441. so = br_find_attr(&doc, c, "stop-opacity");
  7442. {
  7443. const char *st = br_find_attr(&doc, c, "style");
  7444. const char *q;
  7445. if (st && (q = strstr(st, "stop-color:")) != 0)
  7446. sc = q + 11;
  7447. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  7448. so = q + 13;
  7449. }
  7450. if (sc) {
  7451. unsigned int L = 0;
  7452. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  7453. L++;
  7454. if (!br_parse_color(sc, L, &col))
  7455. col = 0;
  7456. }
  7457. if (so) {
  7458. const char *p = so;
  7459. int ok = 0;
  7460. double x = svgr_num(&p, &ok);
  7461. if (ok)
  7462. op = x < 0 ? 0 : x > 1 ? 1 : x;
  7463. }
  7464. sr += (col >> 11) & 31;
  7465. sg += (col >> 5) & 63;
  7466. sb += col & 31;
  7467. sa += (unsigned int)(op * 255);
  7468. cnt++;
  7469. }
  7470. if (cnt)
  7471. break;
  7472. ref = br_find_attr(&doc, gi, "href");
  7473. if (!ref)
  7474. ref = br_find_attr(&doc, gi, "xlink:href");
  7475. if (!ref || ref[0] != '#')
  7476. break;
  7477. g = br_find_id(&doc, ref + 1);
  7478. }
  7479. if (!cnt)
  7480. return 0;
  7481. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  7482. (sb / cnt));
  7483. *alpha = sa / cnt;
  7484. return 1;
  7485. }
  7486. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  7487. unsigned short *color, unsigned int *alpha)
  7488. {
  7489. int mode = fill ? st->fill_mode : st->stroke_mode;
  7490. const char *op = br_find_attr(&doc, node,
  7491. fill ? "fill-opacity" : "stroke-opacity");
  7492. *alpha = 255;
  7493. switch (mode) {
  7494. case BR_PAINT_UNSET:
  7495. if (!fill)
  7496. return 0;
  7497. *color = 0;
  7498. break;
  7499. case BR_PAINT_COLOR:
  7500. *color = fill ? st->fill : st->stroke;
  7501. break;
  7502. case BR_PAINT_CURRENT:
  7503. *color = st->color;
  7504. break;
  7505. case BR_PAINT_URL:
  7506. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  7507. alpha))
  7508. return 0;
  7509. break;
  7510. default:
  7511. return 0;
  7512. }
  7513. if (op) {
  7514. const char *p = op;
  7515. int ok = 0;
  7516. double x = svgr_num(&p, &ok);
  7517. if (ok)
  7518. *alpha = (unsigned int)(*alpha *
  7519. (x < 0 ? 0 : x > 1 ? 1 : x));
  7520. }
  7521. return *alpha > 0;
  7522. }
  7523. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7524. const double m[6], const struct br_style *pst,
  7525. unsigned int alpha, int depth);
  7526. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  7527. const double m[6], const struct br_style *st,
  7528. unsigned int alpha, int depth)
  7529. {
  7530. unsigned int c;
  7531. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  7532. if (doc.nodes[c].type == BR_NODE_ELEM)
  7533. svg_draw_node(L, c, m, st, alpha, depth + 1);
  7534. }
  7535. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7536. const double pm[6], const struct br_style *pst,
  7537. unsigned int alpha, int depth)
  7538. {
  7539. struct br_style st;
  7540. const char *nm = svg_elem_name(node);
  7541. const char *tf;
  7542. double m[6];
  7543. unsigned short color;
  7544. unsigned int pa;
  7545. int shape = 0, fillable = 1;
  7546. if (depth > 24 || !nm)
  7547. return;
  7548. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  7549. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  7550. svg_name_is(nm, "lineargradient") ||
  7551. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  7552. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  7553. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  7554. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  7555. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  7556. svg_name_is(nm, "foreignobject"))
  7557. return;
  7558. br_style_for(&doc, node, pst, &st);
  7559. if (st.display == BR_DISPLAY_NONE)
  7560. return;
  7561. memcpy(m, pm, sizeof(m));
  7562. tf = br_find_attr(&doc, node, "transform");
  7563. if (tf)
  7564. svgr_transform(m, tf);
  7565. {
  7566. const char *op = br_find_attr(&doc, node, "opacity");
  7567. if (op) {
  7568. const char *p = op;
  7569. int ok = 0;
  7570. double x = svgr_num(&p, &ok);
  7571. if (ok)
  7572. alpha = (unsigned int)(alpha *
  7573. (x < 0 ? 0 :
  7574. x > 1 ? 1 : x));
  7575. }
  7576. }
  7577. if (!alpha)
  7578. return;
  7579. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  7580. svg_name_is(nm, "switch")) {
  7581. svg_draw_children(L, node, m, &st, alpha, depth);
  7582. return;
  7583. }
  7584. if (svg_name_is(nm, "svg")) {
  7585. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  7586. y = svg_attr_num(node, "y", 0, 0);
  7587. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7588. t[4] = x;
  7589. t[5] = y;
  7590. svgr_mat_mul(m, m, t);
  7591. double ow = svg_vp_w, oh = svg_vp_h;
  7592. if (svg_viewbox4(node, vb)) {
  7593. double w = svg_attr_num(node, "width", vb[2], ow);
  7594. double h = svg_attr_num(node, "height", vb[3], oh);
  7595. double vm[6];
  7596. svg_viewport_matrix(node, vb, w, h, vm);
  7597. svgr_mat_mul(m, m, vm);
  7598. svg_vp_w = vb[2];
  7599. svg_vp_h = vb[3];
  7600. }
  7601. svg_draw_children(L, node, m, &st, alpha, depth);
  7602. svg_vp_w = ow;
  7603. svg_vp_h = oh;
  7604. return;
  7605. }
  7606. if (svg_name_is(nm, "use")) {
  7607. const char *ref = br_find_attr(&doc, node, "href");
  7608. unsigned int tgt;
  7609. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7610. if (!ref)
  7611. ref = br_find_attr(&doc, node, "xlink:href");
  7612. if (!ref || ref[0] != '#')
  7613. return;
  7614. tgt = br_find_id(&doc, ref + 1);
  7615. if (!tgt || tgt - 1 == node)
  7616. return;
  7617. tgt--;
  7618. t[4] = svg_attr_num(node, "x", 0, 0);
  7619. t[5] = svg_attr_num(node, "y", 0, 0);
  7620. svgr_mat_mul(m, m, t);
  7621. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  7622. double vb[4];
  7623. double ow = svg_vp_w, oh = svg_vp_h;
  7624. if (svg_viewbox4(tgt, vb)) {
  7625. /* A <use> without width/height sizes the
  7626. * symbol to 100% of the viewport: Docusaurus'
  7627. * 13.5px external-link icon references a
  7628. * 24-unit symbol and showed only its corner. */
  7629. double w = svg_attr_num(node, "width",
  7630. ow > 0 ? ow : vb[2], ow);
  7631. double h = svg_attr_num(node, "height",
  7632. oh > 0 ? oh : vb[3], oh);
  7633. double vm[6];
  7634. svg_viewport_matrix(tgt, vb, w, h, vm);
  7635. svgr_mat_mul(m, m, vm);
  7636. svg_vp_w = vb[2];
  7637. svg_vp_h = vb[3];
  7638. }
  7639. svg_draw_children(L, tgt, m, &st, alpha, depth);
  7640. svg_vp_w = ow;
  7641. svg_vp_h = oh;
  7642. } else {
  7643. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  7644. }
  7645. return;
  7646. }
  7647. svgr_reset(&svg_geom, m);
  7648. if (svg_name_is(nm, "path")) {
  7649. const char *d = br_find_attr(&doc, node, "d");
  7650. if (d) {
  7651. svgr_path(&svg_geom, d);
  7652. shape = 1;
  7653. }
  7654. } else if (svg_name_is(nm, "rect")) {
  7655. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  7656. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  7657. double rx = svg_attr_num(node, "rx", -1, w);
  7658. double ry = svg_attr_num(node, "ry", -1, h);
  7659. if (rx < 0)
  7660. rx = ry < 0 ? 0 : ry;
  7661. if (ry < 0)
  7662. ry = rx;
  7663. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  7664. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  7665. shape = 1;
  7666. } else if (svg_name_is(nm, "circle")) {
  7667. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  7668. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7669. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  7670. shape = 1;
  7671. } else if (svg_name_is(nm, "ellipse")) {
  7672. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7673. svg_attr_num(node, "cy", 0, svg_vp_h),
  7674. svg_attr_num(node, "rx", 0, svg_vp_w),
  7675. svg_attr_num(node, "ry", 0, svg_vp_h));
  7676. shape = 1;
  7677. } else if (svg_name_is(nm, "line")) {
  7678. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  7679. svg_attr_num(node, "y1", 0, svg_vp_h));
  7680. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  7681. svg_attr_num(node, "y2", 0, svg_vp_h));
  7682. shape = 1;
  7683. fillable = 0;
  7684. } else if (svg_name_is(nm, "polyline") ||
  7685. svg_name_is(nm, "polygon")) {
  7686. const char *pts = br_find_attr(&doc, node, "points");
  7687. if (pts) {
  7688. svgr_points(&svg_geom, pts,
  7689. svg_name_is(nm, "polygon"));
  7690. shape = 1;
  7691. }
  7692. }
  7693. if (!shape)
  7694. return;
  7695. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  7696. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  7697. st.fill_evenodd);
  7698. if (svg_paint(node, &st, 0, &color, &pa)) {
  7699. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  7700. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7701. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  7702. }
  7703. }
  7704. /* <text> elements: drawn straight onto the page every frame (the glyph
  7705. * renderer targets the ngui canvas, not a layer). x/y map through the
  7706. * accumulated transform; the font size scales with it. */
  7707. static void svg_draw_text(struct ngui *ui, unsigned int node,
  7708. const double pm[6], const struct br_style *pst,
  7709. int ox, int oy, int depth)
  7710. {
  7711. unsigned int c;
  7712. if (depth > 24)
  7713. return;
  7714. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7715. struct br_style st;
  7716. const char *nm, *tf;
  7717. double m[6];
  7718. if (doc.nodes[c].type != BR_NODE_ELEM)
  7719. continue;
  7720. nm = svg_elem_name(c);
  7721. if (!nm || svg_name_is(nm, "defs") ||
  7722. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  7723. svg_name_is(nm, "clippath"))
  7724. continue;
  7725. br_style_for(&doc, c, pst, &st);
  7726. if (st.display == BR_DISPLAY_NONE)
  7727. continue;
  7728. memcpy(m, pm, sizeof(m));
  7729. tf = br_find_attr(&doc, c, "transform");
  7730. if (tf)
  7731. svgr_transform(m, tf);
  7732. if (svg_name_is(nm, "text")) {
  7733. unsigned int t = doc.nodes[c].first;
  7734. const char *s;
  7735. unsigned int n, tw;
  7736. double x = svg_attr_num(c, "x", 0, 0),
  7737. y = svg_attr_num(c, "y", 0, 0);
  7738. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7739. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  7740. int tx, ty, anchor;
  7741. unsigned short col;
  7742. unsigned int pa;
  7743. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  7744. continue;
  7745. if (px < 6)
  7746. px = 6;
  7747. if (px > 72)
  7748. px = 72;
  7749. if (!svg_paint(c, &st, 1, &col, &pa))
  7750. continue;
  7751. s = doc.text + doc.nodes[t].text_off;
  7752. n = doc.nodes[t].text_len;
  7753. st.font_px = (unsigned char)px;
  7754. tw = face_text_width(ui, &st, s, n);
  7755. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  7756. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  7757. ngui_text_ascent_face(ui, style_face(&st), px,
  7758. st.mono);
  7759. anchor = st.align;
  7760. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  7761. anchor = BR_ALIGN_CENTER;
  7762. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  7763. anchor = BR_ALIGN_RIGHT;
  7764. if (anchor == BR_ALIGN_CENTER)
  7765. tx -= (int)tw / 2;
  7766. else if (anchor == BR_ALIGN_RIGHT)
  7767. tx -= (int)tw;
  7768. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  7769. col, px, st.bold, st.italic,
  7770. st.mono);
  7771. } else {
  7772. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  7773. }
  7774. }
  7775. }
  7776. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  7777. {
  7778. double vb[4];
  7779. if (svg_viewbox4(node, vb)) {
  7780. svg_viewport_matrix(node, vb, w, h, m);
  7781. } else {
  7782. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  7783. }
  7784. }
  7785. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  7786. const struct br_style *st)
  7787. {
  7788. struct svg_cache_ent *e = 0;
  7789. struct svgr_layer L;
  7790. double m[6];
  7791. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  7792. svg_cache_clock++;
  7793. for (i = 0; i < SVG_CACHE_MAX; i++)
  7794. if (svg_cache[i].px && svg_cache[i].node == node &&
  7795. svg_cache[i].w == w && svg_cache[i].h == h) {
  7796. svg_cache[i].stamp = svg_cache_clock;
  7797. return &svg_cache[i];
  7798. }
  7799. if (need > SVG_CACHE_PIXELS)
  7800. return 0;
  7801. /* Evict least recently used layers until this one fits. */
  7802. for (;;) {
  7803. struct svg_cache_ent *lru = 0, *free_slot = 0;
  7804. for (i = 0; i < SVG_CACHE_MAX; i++) {
  7805. if (!svg_cache[i].px) {
  7806. if (!free_slot)
  7807. free_slot = &svg_cache[i];
  7808. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  7809. lru = &svg_cache[i];
  7810. }
  7811. }
  7812. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  7813. e = free_slot;
  7814. break;
  7815. }
  7816. if (!lru)
  7817. return 0;
  7818. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  7819. free(lru->px);
  7820. free(lru->a);
  7821. memset(lru, 0, sizeof(*lru));
  7822. }
  7823. if (!svg_geom_buf) {
  7824. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7825. if (!svg_geom_buf)
  7826. return 0;
  7827. }
  7828. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  7829. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  7830. e->a = (unsigned char *)calloc(need, 1);
  7831. if (!e->px || !e->a) {
  7832. free(e->px);
  7833. free(e->a);
  7834. memset(e, 0, sizeof(*e));
  7835. return 0;
  7836. }
  7837. e->node = node;
  7838. e->w = w;
  7839. e->h = h;
  7840. e->stamp = svg_cache_clock;
  7841. svg_cache_pixels += need;
  7842. L.px = e->px;
  7843. L.a = e->a;
  7844. L.w = w;
  7845. L.h = h;
  7846. svg_root_matrix(node, w, h, m);
  7847. {
  7848. double vb[4];
  7849. if (svg_viewbox4(node, vb)) {
  7850. svg_vp_w = vb[2];
  7851. svg_vp_h = vb[3];
  7852. } else {
  7853. svg_vp_w = w;
  7854. svg_vp_h = h;
  7855. }
  7856. }
  7857. svg_draw_children(&L, node, m, st, 255, 0);
  7858. return e;
  7859. }
  7860. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  7861. *
  7862. * The markup is parsed into a detached subtree of the page document and
  7863. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  7864. * bitmap, which then behaves like any decoded image. currentColor is
  7865. * black (an image has no inherited text colour); <text> is not drawn. */
  7866. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  7867. {
  7868. unsigned int i = 0;
  7869. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  7870. i = 3;
  7871. while (i < len) {
  7872. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  7873. d[i] == '\r' || d[i] == '\n'))
  7874. i++;
  7875. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  7876. return 1;
  7877. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  7878. i += 4;
  7879. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  7880. i++;
  7881. i += 3;
  7882. continue;
  7883. }
  7884. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  7885. while (i < len && d[i] != '>')
  7886. i++;
  7887. i++;
  7888. continue;
  7889. }
  7890. return 0;
  7891. }
  7892. return 0;
  7893. }
  7894. static int svg_len_attr(unsigned int node, const char *name)
  7895. {
  7896. const char *v = br_find_attr(&doc, node, name);
  7897. int n = 0, any = 0;
  7898. if (!v)
  7899. return 0;
  7900. while (*v == ' ')
  7901. v++;
  7902. while (*v >= '0' && *v <= '9') {
  7903. n = n * 10 + (*v++ - '0');
  7904. any = 1;
  7905. }
  7906. if (*v == '.')
  7907. while (*++v >= '0' && *v <= '9')
  7908. ;
  7909. if (!any || *v == '%')
  7910. return 0;
  7911. return n;
  7912. }
  7913. static int svg_decode_image(const unsigned char *data, unsigned int len,
  7914. struct br_image *bi, int box_w, int box_h)
  7915. {
  7916. unsigned int holder, svg = 0, c, need, i;
  7917. struct br_style base = base_style(), st;
  7918. struct svgr_layer L;
  7919. double vb[4], m[6];
  7920. int w, h, have_vb, nat_w, nat_h;
  7921. holder = br_create_element(&doc, "div", 3);
  7922. if (!holder) {
  7923. s_copy(bi->err, "page is full", sizeof(bi->err));
  7924. return -1;
  7925. }
  7926. holder--;
  7927. br_set_inner_html(&doc, holder, (const char *)data, len);
  7928. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  7929. if (doc.nodes[c].type == BR_NODE_ELEM &&
  7930. doc.nodes[c].tag == BR_TAG_SVG) {
  7931. svg = c;
  7932. break;
  7933. }
  7934. if (!svg) {
  7935. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  7936. return -1;
  7937. }
  7938. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  7939. w = svg_len_attr(svg, "width");
  7940. h = svg_len_attr(svg, "height");
  7941. if (box_w > 0 && box_h > 0) {
  7942. w = box_w;
  7943. h = box_h;
  7944. } else if (!w && !h) {
  7945. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  7946. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  7947. } else if (!w) {
  7948. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  7949. } else if (!h) {
  7950. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  7951. }
  7952. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  7953. * so CSS scaling stays crisp. */
  7954. nat_w = w;
  7955. nat_h = h;
  7956. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  7957. w *= 2;
  7958. h *= 2;
  7959. }
  7960. if (w > BR_IMG_LAYOUT_W) {
  7961. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  7962. w = BR_IMG_LAYOUT_W;
  7963. }
  7964. if (h > 2048)
  7965. h = 2048;
  7966. if (w < 1)
  7967. w = 1;
  7968. if (h < 1)
  7969. h = 1;
  7970. need = (unsigned int)w * (unsigned int)h;
  7971. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  7972. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  7973. return -1;
  7974. }
  7975. if (!svg_geom_buf) {
  7976. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7977. if (!svg_geom_buf) {
  7978. s_copy(bi->err, "out of memory", sizeof(bi->err));
  7979. return -1;
  7980. }
  7981. }
  7982. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  7983. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  7984. L.a = (unsigned char *)calloc(need, 1);
  7985. if (!L.px || !L.a) {
  7986. free(L.px);
  7987. free(L.a);
  7988. s_copy(bi->err, "out of memory", sizeof(bi->err));
  7989. return -1;
  7990. }
  7991. for (i = 0; i < need; i++)
  7992. L.px[i] = 0xFFFF;
  7993. L.w = w;
  7994. L.h = h;
  7995. base.color = 0x0000;
  7996. br_style_for(&doc, svg, &base, &st);
  7997. svg_root_matrix(svg, w, h, m);
  7998. if (!have_vb && nat_w > 0 && nat_h > 0) {
  7999. /* No viewBox: user units are CSS pixels of the natural size,
  8000. * so the up-to-4x raster (and a box size) must scale them.
  8001. * A 40x20 icon used to fill only the top-left quarter of its
  8002. * 160x80 bitmap and was drawn at a quarter of its size. */
  8003. m[0] = (double)w / nat_w;
  8004. m[3] = (double)h / nat_h;
  8005. }
  8006. svg_vp_w = have_vb ? vb[2] : nat_w;
  8007. svg_vp_h = have_vb ? vb[3] : nat_h;
  8008. svg_draw_children(&L, svg, m, &st, 255, 0);
  8009. bi->native_w = nat_w;
  8010. bi->native_h = nat_h;
  8011. bi->img.format = 0;
  8012. bi->img.w = (unsigned int)w;
  8013. bi->img.h = (unsigned int)h;
  8014. bi->img.px = L.px;
  8015. bi->img.alpha = L.a;
  8016. bi->img.flags = 0;
  8017. bi->state = 1;
  8018. image_pixels += need;
  8019. return 0;
  8020. }
  8021. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  8022. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  8023. int *out_w, int *out_h)
  8024. {
  8025. double vb[4];
  8026. int has_vb = svg_viewbox4(node, vb);
  8027. double aw = svg_attr_num(node, "width", -1, cw);
  8028. double ah = svg_attr_num(node, "height", -1, 0);
  8029. int w, h;
  8030. if (st->width_kind)
  8031. w = cw;
  8032. else if (aw > 0)
  8033. w = (int)(aw + 0.5);
  8034. else if (st->height_kind == 1 && has_vb)
  8035. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  8036. else if (ah > 0 && has_vb)
  8037. w = (int)(ah * vb[2] / vb[3] + 0.5);
  8038. else if (has_vb)
  8039. w = cw;
  8040. else
  8041. w = 300;
  8042. if (st->max_width_kind == 1 && w > st->max_width)
  8043. w = st->max_width;
  8044. if (w > cw && cw > 0 && !(aw > 0))
  8045. w = cw;
  8046. if (w < 1)
  8047. w = 1;
  8048. if (w > 2000)
  8049. w = 2000;
  8050. if (st->height_kind == 1)
  8051. h = st->height;
  8052. else if (ah > 0)
  8053. h = (int)(ah + 0.5);
  8054. else if (has_vb)
  8055. h = (int)(w * vb[3] / vb[2] + 0.5);
  8056. else
  8057. h = 150;
  8058. if (h < 1)
  8059. h = 1;
  8060. if (h > 1400)
  8061. h = 1400;
  8062. *out_w = w;
  8063. *out_h = h;
  8064. }
  8065. static void svg_paint_box(struct ngui *ui, unsigned int node,
  8066. const struct br_style *st, int x, int y, int w, int h)
  8067. {
  8068. struct svg_cache_ent *e;
  8069. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  8070. int cx0, cy0, cx1, cy1, px, py;
  8071. double m[6];
  8072. if (ui->nclip > 0)
  8073. clip = ui->clip[ui->nclip - 1];
  8074. cx0 = r.x > clip.x ? r.x : clip.x;
  8075. cy0 = r.y > clip.y ? r.y : clip.y;
  8076. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  8077. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  8078. if (cx0 >= cx1 || cy0 >= cy1)
  8079. return;
  8080. e = svg_layer(node, w, h, st);
  8081. if (e) {
  8082. for (py = cy0; py < cy1; py++) {
  8083. unsigned int srow = (unsigned int)(py - y) *
  8084. (unsigned int)w;
  8085. unsigned short *dst = ui->px + py * ui->w;
  8086. for (px = cx0; px < cx1; px++) {
  8087. unsigned int si = srow + (unsigned int)(px - x);
  8088. unsigned int a = e->a[si];
  8089. if (!a)
  8090. continue;
  8091. dst[px] = a >= 255 ? e->px[si] :
  8092. blend_rgb565(dst[px], e->px[si], a);
  8093. }
  8094. }
  8095. }
  8096. svg_root_matrix(node, w, h, m);
  8097. ngui_push_clip(ui, r);
  8098. svg_draw_text(ui, node, m, st, x, y, 0);
  8099. ngui_pop_clip(ui);
  8100. }
  8101. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  8102. * keep using add_image_run(); this covers the CSS `position:absolute;
  8103. * width:100%` poster pattern used by news sites. */
  8104. static void image_block_size(unsigned int node, const struct br_style *st,
  8105. int cbw, int *out_w, int *out_h)
  8106. {
  8107. struct br_node *nd = &doc.nodes[node];
  8108. int idx = nd->img_index;
  8109. int iw = 0, ih = 0, w, h, aw, ah;
  8110. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  8111. iw = (int)images[idx].img.w;
  8112. ih = (int)images[idx].img.h;
  8113. if (iw <= 0 || ih <= 0) {
  8114. iw = (int)images[idx].native_w;
  8115. ih = (int)images[idx].native_h;
  8116. }
  8117. }
  8118. if (st->width_kind)
  8119. w = style_width_px(st, cbw);
  8120. else if (nd->width_attr)
  8121. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  8122. (int)nd->width_attr;
  8123. else if (nd->height_attr && !nd->height_pct && iw && ih)
  8124. w = iw * (int)nd->height_attr / ih;
  8125. else if (iw)
  8126. w = iw;
  8127. else
  8128. w = 64;
  8129. /* max-width/min-width against the containing block: Tailwind's
  8130. * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
  8131. * 300x300 thumbnail to its 75 px avatar box. */
  8132. if (st->max_width_kind) {
  8133. int mw = st->max_width_kind == 3 ?
  8134. cbw * st->max_width_calc_pct / 100 +
  8135. st->max_width_calc_px :
  8136. st->max_width_kind == 2 ?
  8137. cbw * (int)st->max_width / 100 : (int)st->max_width;
  8138. if (mw > 0 && w > mw)
  8139. w = mw;
  8140. }
  8141. if (st->min_width_kind) {
  8142. int mn = st->min_width_kind == 3 ?
  8143. cbw * st->min_width_calc_pct / 100 +
  8144. st->min_width_calc_px :
  8145. st->min_width_kind == 2 ?
  8146. cbw * (int)st->min_width / 100 : (int)st->min_width;
  8147. if (mn > w)
  8148. w = mn;
  8149. }
  8150. if (w < 8)
  8151. w = 8;
  8152. if (cbw > 0 && w > cbw)
  8153. w = cbw;
  8154. /* Without a CSS height the attributes (or the bitmap) only give the
  8155. * aspect ratio: a width clamped by max-width scales the height too,
  8156. * instead of letterboxing the image into its attribute height. */
  8157. aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
  8158. ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
  8159. if (st->height_kind)
  8160. h = style_height_px(st, cbw);
  8161. else if (aw > 0 && ah > 0)
  8162. h = w * ah / aw;
  8163. else if (nd->height_attr)
  8164. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  8165. (int)nd->height_attr;
  8166. else
  8167. h = 64;
  8168. if (h < 8)
  8169. h = 8;
  8170. *out_w = w;
  8171. *out_h = h;
  8172. }
  8173. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  8174. int dw, int dh)
  8175. {
  8176. int idx = doc.nodes[node].img_index;
  8177. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  8178. struct img_image *src = image_display_get(&images[idx], dw, dh);
  8179. struct img_blit b;
  8180. if (!src)
  8181. src = &images[idx].img;
  8182. b.dst = l->ui->px;
  8183. b.dst_w = l->ui->w;
  8184. b.dst_h = l->ui->h;
  8185. b.clip_x = page_rect.x;
  8186. b.clip_y = page_rect.y;
  8187. b.clip_w = page_rect.w - 12;
  8188. b.clip_h = page_rect.h;
  8189. b.x = x;
  8190. b.y = y;
  8191. b.scale = ((unsigned int)dw << 16) / src->w;
  8192. b.bg = ui.theme.bg;
  8193. b.bg2 = ui.theme.bg;
  8194. b.dst_a = 0;
  8195. /* OVER_DST is only needed for an alpha source; an opaque one can
  8196. * take img_draw's 1:1 copy path. */
  8197. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  8198. img_draw(src, &b);
  8199. } else if (l->draw) {
  8200. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  8201. 0xD69A);
  8202. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  8203. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  8204. }
  8205. }
  8206. static void layout_block(struct lay *l, unsigned int node,
  8207. const struct br_style *st, int depth,
  8208. unsigned short link)
  8209. {
  8210. int old_left = l->left, old_right = l->right, old_align = l->align;
  8211. int parent_cb_h = l->cb_h;
  8212. int saved_parent_top = l->parent_top;
  8213. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  8214. int saved_cb_top = l->cb_top;
  8215. int top, l0, r0;
  8216. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  8217. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  8218. int deco_w, deco_h, content_w, content_h, box_h;
  8219. int img_dh = 0;
  8220. int definite_w = 0;
  8221. int normal_top = 0;
  8222. int rel_dx = 0, rel_dy = 0;
  8223. int clip_pushed = 0;
  8224. struct ngui_rect clip_rect;
  8225. /* A DOM level costs about two depth units (layout_block ->
  8226. * layout_children), so 48 covers a ~24-level page. Real news pages
  8227. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  8228. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  8229. return;
  8230. flow_y = l->y;
  8231. flow_left = l->left;
  8232. flow_right = l->right;
  8233. positioned = st->pos == 1 || st->pos == 2;
  8234. relative = st->pos == 3;
  8235. sticky = st->pos == 4;
  8236. shifted = relative || sticky || st->transform_set;
  8237. if (positioned) {
  8238. int def_w = st->width_kind == 1 ? st->width : -1;
  8239. if (st->pos == 2) {
  8240. int avail_w = page_rect.w - 12;
  8241. if (st->right_set && def_w >= 0)
  8242. l->left = page_rect.x + avail_w - st->right -
  8243. def_w;
  8244. else
  8245. l->left = page_rect.x +
  8246. (st->left_set ? st->left : 0);
  8247. l->right = def_w >= 0 ? l->left + def_w :
  8248. page_rect.x + avail_w;
  8249. if (st->bottom_set && st->height_kind)
  8250. l->y = page_rect.y + page_rect.h -
  8251. st->bottom -
  8252. style_height_px(st, page_rect.w);
  8253. else
  8254. l->y = page_rect.y +
  8255. (st->top_set ? st->top : 0);
  8256. } else {
  8257. int left = flow_left + (st->left_set ? st->left : 0);
  8258. unsigned int parent = doc.nodes[node].parent;
  8259. if (st->right_set && def_w >= 0)
  8260. left = flow_right - st->right - def_w;
  8261. l->left = left;
  8262. l->right = def_w >= 0 ? left + def_w :
  8263. flow_right +
  8264. (st->left_set ? st->left : 0);
  8265. l->y = flow_y + (st->top_set ? st->top : 0);
  8266. if (st->bottom_set && st->height_kind &&
  8267. parent < BR_MAX_NODES && block_h[parent] > 0)
  8268. l->y = flow_y + block_h[parent] - st->bottom -
  8269. style_height_px(st, old_right - old_left);
  8270. }
  8271. /* `left: 100%` parks a box (Docusaurus' "Skip to main
  8272. * content" link) past the containing block's right edge
  8273. * until it is focused. An auto width then has no room: it
  8274. * used to collapse to 8 px and wrap one word per line into a
  8275. * tall column painted over the page. Lay it out at the
  8276. * containing block's width so it stays one line and
  8277. * overflows (off-screen) like in a real browser. */
  8278. if (def_w < 0 && l->right - l->left < 8) {
  8279. int avail = st->pos == 2 ? page_rect.w - 12 :
  8280. flow_right - flow_left;
  8281. l->right = l->left + (avail > 8 ? avail : 8);
  8282. }
  8283. old_left = l->left;
  8284. old_right = l->right;
  8285. } else if (relative) {
  8286. rel_dx = st->left_set ? st->left :
  8287. (st->right_set ? -st->right : 0);
  8288. rel_dy = st->top_set ? st->top :
  8289. (st->bottom_set ? -st->bottom : 0);
  8290. }
  8291. if (st->transform_set) {
  8292. rel_dx += st->tx;
  8293. rel_dy += st->ty;
  8294. }
  8295. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  8296. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  8297. doc.nodes[node].tag == BR_TAG_SELECT ||
  8298. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  8299. !button_has_elements(node)) {
  8300. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  8301. s_eq(br_type(&doc, node), "hidden"))
  8302. return;
  8303. /* Reached as a block-level box (a flex item): the control
  8304. * fills the box the caller assigned, and its line is flushed
  8305. * here; flex layout resets the run list for the next item, so
  8306. * a queued run would never be drawn. */
  8307. form_fill_line = 1;
  8308. add_form_run(l, node, st, link);
  8309. form_fill_line = 0;
  8310. flush_line(l);
  8311. return;
  8312. }
  8313. flush_line(l);
  8314. cbw = old_right - old_left;
  8315. if (cbw < 8)
  8316. cbw = 8;
  8317. l->y += mp_px(st, 0, cbw);
  8318. top = l->y;
  8319. ml = mp_px(st, 3, cbw);
  8320. mr = mp_px(st, 1, cbw);
  8321. bl = st->border_w[3];
  8322. br = st->border_w[1];
  8323. pl = mp_px(st, 7, cbw);
  8324. pr = mp_px(st, 5, cbw);
  8325. bt = st->border_w[0];
  8326. bb = st->border_w[2];
  8327. pt = mp_px(st, 4, cbw);
  8328. pb = mp_px(st, 6, cbw);
  8329. deco_w = bl + br + pl + pr;
  8330. deco_h = bt + bb + pt + pb;
  8331. if (st->width_kind) {
  8332. int w;
  8333. if (st->width_kind == 3)
  8334. w = cbw * st->width_calc_pct / 100 +
  8335. st->width_calc_px;
  8336. else
  8337. w = css_size(st->width_kind, st->width, cbw);
  8338. if (w < 0)
  8339. w = 0;
  8340. content_w = st->box_sizing ? w - deco_w : w;
  8341. definite_w = 1;
  8342. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  8343. doc.nodes[node].tag == BR_TAG_TD ||
  8344. doc.nodes[node].tag == BR_TAG_TH) &&
  8345. doc.nodes[node].width_attr) {
  8346. /* Legacy table/cell width attributes: percentages resolve
  8347. * against the containing block, bare numbers are pixels. */
  8348. int w = doc.nodes[node].width_pct ?
  8349. cbw * doc.nodes[node].width_attr / 100 :
  8350. doc.nodes[node].width_attr;
  8351. if (w < 0)
  8352. w = 0;
  8353. content_w = st->box_sizing ? w - deco_w : w;
  8354. definite_w = 1;
  8355. } else {
  8356. content_w = cbw - ml - mr - deco_w;
  8357. }
  8358. if (content_w < 0)
  8359. content_w = 0;
  8360. if (st->max_width_kind) {
  8361. int mw = st->max_width_kind == 3 ?
  8362. cbw * st->max_width_calc_pct / 100 +
  8363. st->max_width_calc_px :
  8364. css_size(st->max_width_kind, st->max_width, cbw);
  8365. int max_box = st->box_sizing ? mw : mw + deco_w;
  8366. /* A clamped auto width is used as the width, so auto
  8367. * margins share the rest (Google's 688 px search box). */
  8368. if (content_w + deco_w > max_box) {
  8369. content_w = max_box - deco_w;
  8370. definite_w = 1;
  8371. }
  8372. }
  8373. if (st->min_width_kind) {
  8374. int mw = st->min_width_kind == 3 ?
  8375. cbw * st->min_width_calc_pct / 100 +
  8376. st->min_width_calc_px :
  8377. css_size(st->min_width_kind, st->min_width, cbw);
  8378. int min_box = st->box_sizing ? mw : mw + deco_w;
  8379. if (content_w + deco_w < min_box) {
  8380. content_w = min_box - deco_w;
  8381. definite_w = 1;
  8382. }
  8383. }
  8384. if (content_w < 8)
  8385. content_w = 8;
  8386. if (definite_w) {
  8387. int free_w = cbw - ml - mr - deco_w - content_w;
  8388. if (free_w < 0)
  8389. free_w = 0;
  8390. if (st->ml_auto && st->mr_auto) {
  8391. ml = free_w / 2;
  8392. mr = free_w - ml;
  8393. } else if (st->ml_auto) {
  8394. ml = free_w;
  8395. } else if (st->mr_auto) {
  8396. mr = free_w;
  8397. }
  8398. }
  8399. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8400. int iw, ih;
  8401. image_block_size(node, st, cbw, &iw, &ih);
  8402. content_w = iw;
  8403. img_dh = ih;
  8404. }
  8405. l0 = old_left + ml;
  8406. r0 = l0 + deco_w + content_w;
  8407. if (r0 < l0 + 8)
  8408. r0 = l0 + 8;
  8409. normal_top = top;
  8410. if (sticky) {
  8411. if (st->top_set) {
  8412. int stick = page_rect.y + 4 + st->top;
  8413. if (normal_top < stick)
  8414. rel_dy += stick - normal_top;
  8415. } else if (st->bottom_set && block_h[node]) {
  8416. int stick = page_rect.y + page_rect.h - st->bottom -
  8417. block_h[node];
  8418. if (normal_top > stick)
  8419. rel_dy += stick - normal_top;
  8420. }
  8421. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  8422. block_h[doc.nodes[node].parent]) {
  8423. unsigned int p = doc.nodes[node].parent;
  8424. int ptop = l->parent_top;
  8425. int pbottom = ptop + block_h[p];
  8426. int eh = block_h[node];
  8427. int moved_top = normal_top + rel_dy;
  8428. int moved_bottom = moved_top + eh;
  8429. if (moved_bottom > pbottom)
  8430. rel_dy -= moved_bottom - pbottom;
  8431. moved_top = normal_top + rel_dy;
  8432. if (moved_top < ptop)
  8433. rel_dy += ptop - moved_top;
  8434. }
  8435. }
  8436. if (shifted && l->draw) {
  8437. top += rel_dy;
  8438. l0 += rel_dx;
  8439. r0 += rel_dx;
  8440. }
  8441. l->parent_top = top;
  8442. if (st->pos != 0) {
  8443. /* Positioned boxes establish the containing block for their
  8444. * absolutely positioned descendants. */
  8445. l->cb_left = l0;
  8446. l->cb_right = r0;
  8447. l->cb_top = top;
  8448. }
  8449. if (l->draw && block_h[node] &&
  8450. top < page_rect.y + page_rect.h &&
  8451. top + block_h[node] > page_rect.y) {
  8452. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  8453. int rtl = css_radius(st, 0, box.w, box.h);
  8454. int rtr = css_radius(st, 1, box.w, box.h);
  8455. int rbr = css_radius(st, 2, box.w, box.h);
  8456. int rbl = css_radius(st, 3, box.w, box.h);
  8457. if (st->transform_scale) {
  8458. if (st->has_bg)
  8459. fill_transformed_rect(l->ui, box, st->bg, st);
  8460. } else if (rtl || rtr || rbr || rbl) {
  8461. if (st->has_bg) {
  8462. int bw = st->border_w[0];
  8463. if (bw > 0 && !st->border_t[0] &&
  8464. st->border_c[0] != st->bg &&
  8465. box.w > bw * 2 && box.h > bw * 2) {
  8466. struct ngui_rect inner = {
  8467. box.x + bw, box.y + bw,
  8468. box.w - bw * 2, box.h - bw * 2
  8469. };
  8470. int itl = rtl > bw ? rtl - bw : 0;
  8471. int itr = rtr > bw ? rtr - bw : 0;
  8472. int ibr = rbr > bw ? rbr - bw : 0;
  8473. int ibl = rbl > bw ? rbl - bw : 0;
  8474. ngui_fill_round_rect(l->ui, box, rtl,
  8475. rtr, rbr, rbl,
  8476. st->border_c[0]);
  8477. ngui_fill_round_rect(l->ui, inner,
  8478. itl, itr, ibr,
  8479. ibl, st->bg);
  8480. } else {
  8481. ngui_fill_round_rect(l->ui, box, rtl,
  8482. rtr, rbr, rbl,
  8483. st->bg);
  8484. }
  8485. } else if (st->border_w[0] && !st->border_t[0]) {
  8486. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  8487. rbl, st->border_w[0],
  8488. st->border_c[0]);
  8489. }
  8490. /* Rounded boxes paint their background image too
  8491. * (app icons are rounded squares), kept inside the
  8492. * corner arcs. */
  8493. if (st->bg_image)
  8494. draw_bg_image_round(l, box, node, st, rtl, rtr,
  8495. rbr, rbl);
  8496. } else {
  8497. if (st->has_bg)
  8498. ngui_fill_rect(l->ui, box, st->bg);
  8499. if (st->bg_image)
  8500. draw_bg_image(l, box, node, st);
  8501. if (st->border_w[0] || st->border_w[1] ||
  8502. st->border_w[2] || st->border_w[3])
  8503. draw_border_box(l->ui, box, st);
  8504. }
  8505. }
  8506. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  8507. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  8508. content_w, img_dh);
  8509. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  8510. l->ui && l->ui->nclip < 4) {
  8511. clip_rect.x = l0 + bl;
  8512. clip_rect.y = top + bt;
  8513. clip_rect.w = (r0 - l0) - bl - br;
  8514. clip_rect.h = (int)block_h[node] - bt - bb;
  8515. if (clip_rect.w > 0 && clip_rect.h > 0) {
  8516. ngui_push_clip(l->ui, clip_rect);
  8517. clip_pushed = 1;
  8518. }
  8519. }
  8520. l->left = l0 + bl + pl;
  8521. l->right = l->left + content_w;
  8522. if (l->right < l->left + 8)
  8523. l->right = l->left + 8;
  8524. l->align = st->align;
  8525. l->line_left = l->left;
  8526. l->line_right = l->right;
  8527. l->y = top + bt + pt;
  8528. if (doc.nodes[node].tag == BR_TAG_HR) {
  8529. if (l->draw)
  8530. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  8531. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  8532. l->y += 8;
  8533. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  8534. int vw = l->right - l->left;
  8535. int vh;
  8536. if (doc.nodes[node].width_pct)
  8537. vw = vw * doc.nodes[node].width_attr / 100;
  8538. else if (doc.nodes[node].width_attr)
  8539. vw = doc.nodes[node].width_attr;
  8540. if (vw > l->right - l->left)
  8541. vw = l->right - l->left;
  8542. if (vw < 8)
  8543. vw = 8;
  8544. vh = vw * 9 / 16;
  8545. if (vh > 240)
  8546. vh = 240;
  8547. if (vh < 80)
  8548. vh = 80;
  8549. if (l->draw) {
  8550. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  8551. vw, vh}, 0xD69A);
  8552. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  8553. vw, vh}, 0x8410);
  8554. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  8555. 0x4208);
  8556. }
  8557. l->y += vh + 4;
  8558. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  8559. int dw, dh, cw = l->right - l->left;
  8560. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  8561. if (l->draw && l->y < page_rect.y + page_rect.h &&
  8562. l->y + dh > page_rect.y)
  8563. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  8564. l->y += dh;
  8565. } else {
  8566. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  8567. !st->no_bullet) {
  8568. char *m = li_marker[node];
  8569. if (!m[0]) {
  8570. unsigned int parent = doc.nodes[node].parent;
  8571. int style = st->list_style;
  8572. int idx = parent ? list_index(parent, node) : 1;
  8573. if (style == BR_LIST_AUTO)
  8574. style = (parent &&
  8575. doc.nodes[parent].tag ==
  8576. BR_TAG_OL) ?
  8577. BR_LIST_DECIMAL : BR_LIST_DISC;
  8578. list_marker_text(m, sizeof(li_marker[node]),
  8579. style, idx);
  8580. }
  8581. if (l->draw && m[0]) {
  8582. int mw = (int)ngui_text_width_ui(l->ui, m);
  8583. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  8584. st->color);
  8585. }
  8586. }
  8587. /* This box's definite content height, for its children's
  8588. * percentage heights. */
  8589. if (doc.nodes[node].tag == BR_TAG_HTML ||
  8590. doc.nodes[node].tag == BR_TAG_BODY)
  8591. l->cb_h = layout_view_h;
  8592. else if (st->height_kind == 1)
  8593. l->cb_h = (int)st->height -
  8594. (st->box_sizing ? deco_h : 0);
  8595. else if (st->height_kind == 2 && parent_cb_h > 0)
  8596. l->cb_h = parent_cb_h * (int)st->height / 100 -
  8597. (st->box_sizing ? deco_h : 0);
  8598. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  8599. l->cb_h = content_w * (int)st->aspect_h /
  8600. (int)st->aspect_w;
  8601. else
  8602. l->cb_h = 0;
  8603. if (l->cb_h < 0)
  8604. l->cb_h = 0;
  8605. if (doc.nodes[node].tag == BR_TAG_TR)
  8606. layout_table_row(l, node, st, depth + 1, link);
  8607. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  8608. table_has_rowspan(node))
  8609. layout_table(l, node, st, depth + 1, link);
  8610. else if (st->grid_auto)
  8611. layout_grid_auto(l, node, st, depth + 1, link);
  8612. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  8613. st->grid_gap > 0)
  8614. layout_grid_children(l, node, st, depth + 1, link);
  8615. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  8616. flex_wants_row(node, st))
  8617. layout_flex_children(l, node, st, depth + 1, link);
  8618. else if (st->display == BR_DISPLAY_FLEX && st->flex_col &&
  8619. st->align_items == 1) {
  8620. /* align-items: center in a column: the items' lines
  8621. * (an app card's icon and label) are centred; a child
  8622. * with its own text-align keeps it. */
  8623. struct br_style cst = *st;
  8624. cst.align = BR_ALIGN_CENTER;
  8625. l->align = BR_ALIGN_CENTER;
  8626. layout_children(l, node, &cst, depth + 1, link);
  8627. } else
  8628. layout_children(l, node, st, depth + 1, link);
  8629. l->cb_h = parent_cb_h;
  8630. }
  8631. flush_line(l);
  8632. if (clip_pushed)
  8633. ngui_pop_clip(l->ui);
  8634. if (l->float_active) {
  8635. if (l->y < l->float_bottom)
  8636. l->y = l->float_bottom;
  8637. l->float_active = 0;
  8638. }
  8639. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8640. content_h = img_dh;
  8641. } else if (st->height_kind == 2 &&
  8642. doc.nodes[node].tag != BR_TAG_HTML &&
  8643. doc.nodes[node].tag != BR_TAG_BODY) {
  8644. /* A percentage of the containing block's definite height, or
  8645. * auto when it has none (it used to resolve against the
  8646. * width). The result is a minimum: without scrollable inner
  8647. * boxes, an app shell's height:100%; overflow:hidden column
  8648. * would otherwise clip everything past the first screen. */
  8649. int auto_h = l->y - (top + bt + pt);
  8650. content_h = parent_cb_h > 0 ?
  8651. parent_cb_h * (int)st->height / 100 -
  8652. (st->box_sizing ? deco_h : 0) : 0;
  8653. if (content_h < auto_h)
  8654. content_h = auto_h;
  8655. } else if (st->height_kind &&
  8656. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8657. doc.nodes[node].tag == BR_TAG_BODY) &&
  8658. st->height_kind == 2)) {
  8659. content_h = style_height_px(st, cbw);
  8660. if (st->box_sizing)
  8661. content_h -= deco_h;
  8662. } else {
  8663. /* Percentage heights on html/body resolve against the
  8664. * viewport, but their content still defines the document
  8665. * scroll height. Treating them as auto avoids collapsing
  8666. * the measured page to the containing block width. */
  8667. content_h = l->y - (top + bt + pt);
  8668. /* aspect-ratio: the preferred height of an auto-height box
  8669. * (Tailwind aspect-video image frames); content can still
  8670. * make it taller, as with min-height: auto. */
  8671. if (st->aspect_w && st->aspect_h && content_w > 0) {
  8672. int ah = content_w * (int)st->aspect_h /
  8673. (int)st->aspect_w;
  8674. if (content_h < ah)
  8675. content_h = ah;
  8676. }
  8677. }
  8678. if (content_h < 0)
  8679. content_h = 0;
  8680. if (st->max_height_kind) {
  8681. int mh = st->max_height_kind == 3 ?
  8682. cbw * st->max_height_calc_pct / 100 +
  8683. st->max_height_calc_px :
  8684. css_size(st->max_height_kind, st->max_height, cbw);
  8685. int max_box = st->box_sizing ? mh : mh + deco_h;
  8686. if (content_h + deco_h > max_box)
  8687. content_h = max_box - deco_h;
  8688. }
  8689. if (st->min_height_kind &&
  8690. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8691. doc.nodes[node].tag == BR_TAG_BODY) &&
  8692. st->min_height_kind == 2)) {
  8693. int mh = st->min_height_kind == 3 ?
  8694. cbw * st->min_height_calc_pct / 100 +
  8695. st->min_height_calc_px :
  8696. css_size(st->min_height_kind, st->min_height, cbw);
  8697. int min_box = st->box_sizing ? mh : mh + deco_h;
  8698. if (content_h + deco_h < min_box)
  8699. content_h = min_box - deco_h;
  8700. }
  8701. if (content_h < 0)
  8702. content_h = 0;
  8703. box_h = deco_h + content_h;
  8704. if (box_h < 0)
  8705. box_h = 0;
  8706. l->y = (shifted ? normal_top : top) + box_h;
  8707. if (node < BR_MAX_NODES) {
  8708. layout_boxes[node].x = l0;
  8709. layout_boxes[node].y = top;
  8710. layout_boxes[node].w = r0 - l0;
  8711. layout_boxes[node].h = box_h;
  8712. layout_boxes[node].valid = r0 > l0;
  8713. }
  8714. l->left = old_left;
  8715. l->right = old_right;
  8716. l->align = old_align;
  8717. l->y += mp_px(st, 2, cbw);
  8718. if (!l->draw) {
  8719. if (box_h > 65535)
  8720. box_h = 65535;
  8721. block_h[node] = (unsigned short)box_h;
  8722. block_top[node] = (unsigned short)(top < 0 ? 0 :
  8723. top > 65535 ? 65535 : top);
  8724. }
  8725. if (positioned) {
  8726. l->y = flow_y;
  8727. l->left = flow_left;
  8728. l->right = flow_right;
  8729. }
  8730. l->parent_top = saved_parent_top;
  8731. l->cb_left = saved_cb_left;
  8732. l->cb_right = saved_cb_right;
  8733. l->cb_top = saved_cb_top;
  8734. }
  8735. static int text_node_blank(const struct br_node *nd)
  8736. {
  8737. const char *t = doc.text + nd->text_off;
  8738. unsigned int i;
  8739. for (i = 0; i < nd->text_len; i++)
  8740. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  8741. t[i] != '\r')
  8742. return 0;
  8743. return 1;
  8744. }
  8745. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  8746. * text/image widths in the subtree, plus padding and margins. This keeps
  8747. * Bootstrap's floated nav items on one line instead of giving each the whole
  8748. * row. */
  8749. static int text_space(char c)
  8750. {
  8751. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  8752. }
  8753. static int intrinsic_width(struct ngui *ui, unsigned int node,
  8754. const struct br_style *pst, int depth, int base)
  8755. {
  8756. unsigned int c;
  8757. int line_w = 0, max_w = 0;
  8758. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  8759. if (depth > 32)
  8760. return 0;
  8761. if (doc.npe_rules) {
  8762. struct br_style ps;
  8763. /* Icon boxes (::before/::after with a size) are inline
  8764. * content of the element. */
  8765. line_w += pseudo_box_w(node, pst, 1, &ps, base) +
  8766. pseudo_box_w(node, pst, 2, &ps, base);
  8767. }
  8768. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8769. struct br_node *nd = &doc.nodes[c];
  8770. struct br_style cs;
  8771. if (nd->type == BR_NODE_TEXT) {
  8772. const char *t = doc.text + nd->text_off;
  8773. unsigned int tn = nd->text_len;
  8774. if (doc.nodes[node].tag == BR_TAG_PRE) {
  8775. line_w += (int)face_text_width(ui, pst, t, tn);
  8776. } else {
  8777. unsigned int ti = 0;
  8778. int first = 1;
  8779. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  8780. int sp = (int)face_text_width(ui, pst, " ", 1);
  8781. while (ti < tn) {
  8782. unsigned int ts;
  8783. while (ti < tn && text_space(t[ti]))
  8784. ti++;
  8785. ts = ti;
  8786. while (ti < tn && !text_space(t[ti]))
  8787. ti++;
  8788. if (ti == ts)
  8789. break;
  8790. if (!first || lead)
  8791. line_w += sp;
  8792. lead = 0;
  8793. line_w += (int)face_text_width(ui, pst,
  8794. t + ts, ti - ts);
  8795. first = 0;
  8796. }
  8797. }
  8798. continue;
  8799. }
  8800. br_style_for(&doc, c, pst, &cs);
  8801. if (cs.display == BR_DISPLAY_NONE)
  8802. continue;
  8803. if (nd->tag == BR_TAG_BR) {
  8804. if (line_w > max_w)
  8805. max_w = line_w;
  8806. line_w = 0;
  8807. continue;
  8808. }
  8809. if (nd->tag == BR_TAG_IMG) {
  8810. /* Measure the image as layout will draw it: a CSS or
  8811. * attribute height keeps the intrinsic aspect ratio, and
  8812. * a CSS width overrides the native pixel width. Bootstrap
  8813. * sizes the Cloudron logo with height:40px only. */
  8814. int idx = nd->img_index;
  8815. int iw = 0, ih = 0;
  8816. if (idx >= 0 && idx < image_count &&
  8817. images[idx].state == 1) {
  8818. iw = (int)images[idx].native_w;
  8819. ih = (int)images[idx].native_h;
  8820. if (iw <= 0 || ih <= 0) {
  8821. iw = (int)images[idx].img.w;
  8822. ih = (int)images[idx].img.h;
  8823. }
  8824. }
  8825. if (cs.width_kind) {
  8826. int ww = style_width_px(&cs, base);
  8827. line_w += ww > 0 ? ww : 64;
  8828. } else if (nd->width_attr) {
  8829. line_w += nd->width_attr;
  8830. } else if (nd->height_attr && iw && ih) {
  8831. line_w += iw * (int)nd->height_attr / ih;
  8832. } else if (cs.height_kind && iw && ih) {
  8833. /* A percentage height needs the parent's
  8834. * definite height (the logo's 2rem box), as in
  8835. * add_image_run(); otherwise it is auto. */
  8836. int hh = cs.height_kind == 1 ?
  8837. style_height_px(&cs, base) :
  8838. cs.height_kind == 2 &&
  8839. pst->height_kind == 1 ?
  8840. (int)pst->height * (int)cs.height / 100 :
  8841. 0;
  8842. line_w += hh > 0 ? iw * hh / ih : iw;
  8843. } else if (iw) {
  8844. line_w += iw;
  8845. } else {
  8846. line_w += 64;
  8847. }
  8848. continue;
  8849. }
  8850. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  8851. nd->tag == BR_TAG_TEXTAREA) &&
  8852. !s_eq(br_type(&doc, c), "hidden")) {
  8853. /* Form controls are replaced: CSS width applies even
  8854. * when they are inline (add_form_run's sizes). */
  8855. int fw = cs.width_kind ? style_width_px(&cs, base) :
  8856. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  8857. if (s_eq(br_type(&doc, c), "checkbox") ||
  8858. s_eq(br_type(&doc, c), "radio"))
  8859. fw = 16;
  8860. line_w += (fw > 0 ? fw : 120) +
  8861. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  8862. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  8863. continue;
  8864. }
  8865. if (nd->tag == BR_TAG_SVG) {
  8866. /* A replaced element: its own size, like add_svg_run()
  8867. * (its path children have no width). */
  8868. int sw, sh, sb = cs.width_kind ?
  8869. style_width_px(&cs, base) : base;
  8870. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  8871. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  8872. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  8873. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8874. line_w += sw;
  8875. } else {
  8876. if (line_w > max_w)
  8877. max_w = line_w;
  8878. line_w = 0;
  8879. if (sw > max_w)
  8880. max_w = sw;
  8881. }
  8882. continue;
  8883. }
  8884. {
  8885. int cw = mp_px(&cs, 7, base) +
  8886. mp_px(&cs, 5, base) +
  8887. mp_px(&cs, 3, base) +
  8888. mp_px(&cs, 1, base) +
  8889. cs.border_w[1] + cs.border_w[3];
  8890. /* width/height do not apply to non-replaced inline
  8891. * boxes. The tagesschau home label is an inline span
  8892. * with width:1px for the mobile icon-only header; using
  8893. * that width made the whole subnav collapse to a
  8894. * one-character column. */
  8895. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  8896. cw += cs.width_kind == 1 ? cs.width :
  8897. style_width_px(&cs, base);
  8898. else
  8899. cw += intrinsic_width(ui, c, &cs, depth + 1,
  8900. base);
  8901. if (flex_row || cs.float_left ||
  8902. cs.display == BR_DISPLAY_INLINE ||
  8903. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8904. line_w += cw;
  8905. } else {
  8906. if (line_w > max_w)
  8907. max_w = line_w;
  8908. line_w = 0;
  8909. if (cw > max_w)
  8910. max_w = cw;
  8911. }
  8912. }
  8913. if (line_w > 4096 || max_w > 4096)
  8914. break;
  8915. }
  8916. return line_w > max_w ? line_w : max_w;
  8917. }
  8918. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  8919. * the main user: .row > .col-md-* with float:left and a percentage width.
  8920. * Each column is laid out with its own left/right edge and the row advances
  8921. * to the tallest column. Returns the first child not consumed. */
  8922. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  8923. const struct br_style *pst, int depth,
  8924. unsigned short link)
  8925. {
  8926. unsigned int n = first;
  8927. int row_left = l->left, row_right = l->right;
  8928. int row_top, row_bottom, xl, xr, any = 0;
  8929. int fl_left = row_left, fl_right = row_right, fl_bottom;
  8930. flush_line(l);
  8931. row_top = l->y;
  8932. row_bottom = l->y;
  8933. fl_bottom = row_top;
  8934. xl = row_left;
  8935. xr = row_right;
  8936. while (n) {
  8937. struct br_node *nd = &doc.nodes[n];
  8938. struct br_style cs;
  8939. unsigned short lk = link;
  8940. int colw, right;
  8941. if (nd->type == BR_NODE_TEXT) {
  8942. if (text_node_blank(nd)) {
  8943. n = nd->next;
  8944. continue;
  8945. }
  8946. break;
  8947. }
  8948. br_style_for(&doc, n, pst, &cs);
  8949. if (cs.display == BR_DISPLAY_NONE) {
  8950. n = nd->next;
  8951. continue;
  8952. }
  8953. /* A float blockifies its box: Bootstrap floats inline
  8954. * anchors too (the navbar brand and its text links), and
  8955. * their padding must be honoured. */
  8956. if (!cs.float_left)
  8957. break;
  8958. if (nd->tag == BR_TAG_A && nd->href_off)
  8959. lk = (unsigned short)n;
  8960. right = cs.float_left == 2;
  8961. if (cs.width_kind == 1 || cs.width_kind == 2 ||
  8962. cs.width_kind == 3) {
  8963. /* The column is the margin box: `width` is the
  8964. * content (or, with border-box, the border) box,
  8965. * and layout_block() takes margins, padding and
  8966. * borders back out of the column. A 200px float
  8967. * with margin-right:20px used to get 180px of
  8968. * content. */
  8969. int base = row_right - row_left;
  8970. colw = cs.width_kind == 1 ? (int)cs.width :
  8971. style_width_px(&cs, base);
  8972. colw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  8973. if (!cs.box_sizing)
  8974. colw += mp_px(&cs, 7, base) +
  8975. mp_px(&cs, 5, base) +
  8976. cs.border_w[1] + cs.border_w[3];
  8977. } else {
  8978. int base = row_right - row_left;
  8979. /* Shrink-to-fit outer width: borders too (Google's
  8980. * 1px-bordered "Anmelden" pill wrapped otherwise). */
  8981. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  8982. mp_px(&cs, 7, base) +
  8983. mp_px(&cs, 5, base) +
  8984. mp_px(&cs, 3, base) +
  8985. mp_px(&cs, 1, base) +
  8986. cs.border_w[1] + cs.border_w[3];
  8987. if (colw < 8)
  8988. colw = 8;
  8989. }
  8990. if (colw < 8)
  8991. colw = 8;
  8992. if (colw > row_right - row_left)
  8993. colw = row_right - row_left;
  8994. /* The float column width is already resolved. */
  8995. cs.width_kind = 0;
  8996. cs.max_width_kind = 0;
  8997. if (right) {
  8998. if (any && xr - colw < xl) {
  8999. row_top = row_bottom;
  9000. row_bottom = row_top;
  9001. xl = row_left;
  9002. xr = row_right;
  9003. }
  9004. if (xr - colw < xl)
  9005. colw = xr - xl;
  9006. if (colw < 8)
  9007. colw = 8;
  9008. l->left = xr - colw;
  9009. if (l->left < row_left)
  9010. l->left = row_left;
  9011. l->right = xr;
  9012. xr = l->left;
  9013. if (xr < fl_right)
  9014. fl_right = xr;
  9015. } else {
  9016. if (any && xl + colw > xr) {
  9017. row_top = row_bottom;
  9018. row_bottom = row_top;
  9019. xl = row_left;
  9020. xr = row_right;
  9021. }
  9022. l->left = xl;
  9023. l->right = xl + colw;
  9024. xl += colw;
  9025. if (xl > fl_left)
  9026. fl_left = xl;
  9027. }
  9028. if (l->right < l->left + 8)
  9029. l->right = l->left + 8;
  9030. l->y = row_top;
  9031. l->line_x = l->left;
  9032. l->run_x = l->left;
  9033. l->line_y = l->y;
  9034. l->line_h = 0;
  9035. l->nruns = 0;
  9036. l->space_pending = 0;
  9037. l->align = cs.align;
  9038. layout_block(l, n, &cs, depth + 1, lk);
  9039. if (l->y > row_bottom)
  9040. row_bottom = l->y;
  9041. if (l->y > fl_bottom)
  9042. fl_bottom = l->y;
  9043. any = 1;
  9044. n = nd->next;
  9045. }
  9046. l->left = row_left;
  9047. l->right = row_right;
  9048. if (n && any) {
  9049. struct br_node *nd = &doc.nodes[n];
  9050. int inline_next = 0;
  9051. if (nd->type == BR_NODE_TEXT) {
  9052. inline_next = 1;
  9053. } else if (nd->type == BR_NODE_ELEM) {
  9054. struct br_style cs;
  9055. br_style_for(&doc, n, pst, &cs);
  9056. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  9057. cs.display != BR_DISPLAY_NONE &&
  9058. !br_tag_is_block(nd->tag);
  9059. }
  9060. if (inline_next) {
  9061. if (l->float_active) {
  9062. if (l->float_left > fl_left)
  9063. fl_left = l->float_left;
  9064. if (l->float_right < fl_right)
  9065. fl_right = l->float_right;
  9066. if (l->float_bottom > fl_bottom)
  9067. fl_bottom = l->float_bottom;
  9068. }
  9069. l->float_active = 1;
  9070. l->float_left = fl_left;
  9071. l->float_right = fl_right;
  9072. l->float_bottom = fl_bottom;
  9073. l->y = row_top;
  9074. } else {
  9075. l->float_active = 0;
  9076. l->y = row_bottom;
  9077. }
  9078. } else {
  9079. l->float_active = 0;
  9080. l->y = row_bottom;
  9081. }
  9082. l->line_x = l->left;
  9083. l->run_x = l->left;
  9084. l->line_left = l->left;
  9085. l->line_right = l->right;
  9086. l->line_y = l->y;
  9087. l->line_h = 0;
  9088. l->nruns = 0;
  9089. l->space_pending = 0;
  9090. return n;
  9091. }
  9092. static int flex_item_width(struct lay *l, unsigned int n,
  9093. const struct br_style *cs, int avail)
  9094. {
  9095. struct br_node *nd = &doc.nodes[n];
  9096. (void)l;
  9097. int w;
  9098. if (cs->width_kind == 2 || cs->width_kind == 3)
  9099. w = style_width_px(cs, avail);
  9100. else if (cs->width_kind == 1)
  9101. w = (int)cs->width;
  9102. else if (nd->tag == BR_TAG_IMG) {
  9103. int idx = nd->img_index;
  9104. if (idx >= 0 && idx < image_count &&
  9105. images[idx].state == 1)
  9106. w = (int)images[idx].img.w;
  9107. else if (nd->width_attr)
  9108. w = (int)nd->width_attr;
  9109. else
  9110. w = 64;
  9111. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  9112. nd->tag == BR_TAG_TEXTAREA) {
  9113. /* A control has no content to measure: its default size
  9114. * (a search field in a filter bar). */
  9115. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  9116. } else {
  9117. w = intrinsic_width(l->ui, n, cs, 0, avail);
  9118. }
  9119. /* Explicit widths are content-box sizes; the flex item's outer width
  9120. * must include padding, borders and margins. */
  9121. w += mp_px(cs, 7, avail);
  9122. w += mp_px(cs, 5, avail);
  9123. w += mp_px(cs, 3, avail);
  9124. w += mp_px(cs, 1, avail);
  9125. w += cs->border_w[1] + cs->border_w[3];
  9126. if (w < 24)
  9127. w = 24;
  9128. if (w > avail)
  9129. w = avail;
  9130. return w;
  9131. }
  9132. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  9133. int depth);
  9134. /* An inline child of a text-only inline-block: the same test minus the
  9135. * display check (an inline <span> may have padding/background in CSS, but
  9136. * the inline path paints those for spans anyway). */
  9137. static int inline_block_flows_inline(unsigned int node,
  9138. const struct br_style *cs, int depth)
  9139. {
  9140. unsigned int c;
  9141. if (depth > 3 || cs->pos)
  9142. return 0;
  9143. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9144. const struct br_node *nd = &doc.nodes[c];
  9145. struct br_style ch;
  9146. if (nd->type != BR_NODE_ELEM)
  9147. continue;
  9148. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  9149. br_tag_is_block(nd->tag))
  9150. return 0;
  9151. br_style_for(&doc, c, cs, &ch);
  9152. if (ch.display == BR_DISPLAY_NONE)
  9153. continue;
  9154. if (ch.display != BR_DISPLAY_INLINE ||
  9155. !inline_block_flows_inline(c, &ch, depth + 1))
  9156. return 0;
  9157. }
  9158. return 1;
  9159. }
  9160. /* An inline-block that is only text in a line (a <time> in a byline, a
  9161. * label) with no box of its own -- no size, background, border or padding
  9162. * -- lays out exactly like an inline element, so it stays in the text line
  9163. * instead of ending it. Boxes with any of those keep the row path. */
  9164. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  9165. int depth)
  9166. {
  9167. unsigned int c;
  9168. int i;
  9169. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  9170. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  9171. cs->pos || depth > 3)
  9172. return 0;
  9173. for (i = 0; i < 4; i++)
  9174. if (cs->border_w[i])
  9175. return 0;
  9176. for (i = 4; i < 8; i++)
  9177. if (mp_px(cs, i, 0) > 0)
  9178. return 0;
  9179. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9180. const struct br_node *nd = &doc.nodes[c];
  9181. struct br_style ch;
  9182. if (nd->type != BR_NODE_ELEM)
  9183. continue;
  9184. if (nd->tag == BR_TAG_SVG) {
  9185. /* An icon box (Docusaurus' admonition heading:
  9186. * `<span inline-block><svg/></span>Note`): the SVG
  9187. * is an inline replaced run, so the box can stay in
  9188. * the text line. */
  9189. br_style_for(&doc, c, cs, &ch);
  9190. if (ch.display == BR_DISPLAY_NONE ||
  9191. ch.display == BR_DISPLAY_INLINE ||
  9192. ch.display == BR_DISPLAY_INLINE_BLOCK)
  9193. continue;
  9194. return 0;
  9195. }
  9196. if (nd->tag == BR_TAG_IMG || br_tag_is_block(nd->tag))
  9197. return 0;
  9198. br_style_for(&doc, c, cs, &ch);
  9199. if (ch.display == BR_DISPLAY_NONE)
  9200. continue;
  9201. if (ch.display != BR_DISPLAY_INLINE ||
  9202. !inline_block_flows_inline(c, &ch, depth + 1))
  9203. return 0;
  9204. }
  9205. return 1;
  9206. }
  9207. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  9208. * on one line, not one full-width block each. Place intrinsic widths from
  9209. * left to right and wrap when the row is full. */
  9210. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  9211. const struct br_style *pst, int depth,
  9212. unsigned short link)
  9213. {
  9214. unsigned int n = first;
  9215. int row_left = l->left, row_right = l->right;
  9216. int avail = row_right - row_left;
  9217. int x = row_left, y = l->y, row_h = 0, any = 0;
  9218. /* Each box sets l->align from its own style; the text after the row
  9219. * must keep the container's (a centred .fa-fw icon centred the menu
  9220. * label that followed it). */
  9221. unsigned char row_align = l->align;
  9222. flush_line(l);
  9223. y = l->y;
  9224. while (n) {
  9225. struct br_node *nd = &doc.nodes[n];
  9226. struct br_style cs;
  9227. unsigned short lk = link;
  9228. int colw, h;
  9229. if (nd->type == BR_NODE_TEXT) {
  9230. if (!text_node_blank(nd))
  9231. break;
  9232. if (any)
  9233. x += 4;
  9234. n = nd->next;
  9235. continue;
  9236. }
  9237. br_style_for(&doc, n, pst, &cs);
  9238. if (cs.display == BR_DISPLAY_NONE) {
  9239. n = nd->next;
  9240. continue;
  9241. }
  9242. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  9243. break;
  9244. if (nd->tag == BR_TAG_A && nd->href_off)
  9245. lk = (unsigned short)n;
  9246. colw = flex_item_width(l, n, &cs, avail);
  9247. /* A few pixels of slack keep a single long token (boot.S)
  9248. * from wrapping at the exact content width. */
  9249. colw += 8;
  9250. if (colw > avail)
  9251. colw = avail;
  9252. cs.width_kind = 0;
  9253. cs.max_width_kind = 0;
  9254. if (any && x + colw > row_right) {
  9255. y += row_h + 2;
  9256. x = row_left;
  9257. row_h = 0;
  9258. any = 0;
  9259. }
  9260. if (any && x > row_left)
  9261. x += 4;
  9262. l->left = x;
  9263. l->right = x + colw;
  9264. if (l->right < l->left + 8)
  9265. l->right = l->left + 8;
  9266. l->y = y;
  9267. l->line_x = l->left;
  9268. l->run_x = l->left;
  9269. l->line_y = l->y;
  9270. l->line_h = 0;
  9271. l->nruns = 0;
  9272. l->space_pending = 0;
  9273. l->align = cs.align;
  9274. layout_block(l, n, &cs, depth + 1, lk);
  9275. h = l->y - y;
  9276. if (h > row_h)
  9277. row_h = h;
  9278. x += colw;
  9279. any = 1;
  9280. n = nd->next;
  9281. }
  9282. if (any)
  9283. y += row_h;
  9284. l->left = row_left;
  9285. l->right = row_right;
  9286. l->align = row_align;
  9287. l->y = y;
  9288. l->line_x = l->left;
  9289. l->run_x = l->left;
  9290. l->line_y = l->y;
  9291. l->line_h = 0;
  9292. l->nruns = 0;
  9293. l->space_pending = 0;
  9294. return n;
  9295. }
  9296. struct flex_item {
  9297. unsigned int node;
  9298. unsigned short link;
  9299. int w;
  9300. };
  9301. /* An item's min-width/max-width as outer (margin-box) widths in the flex
  9302. * row, or -1 when unset. Percentages and calc() resolve against the
  9303. * container width. */
  9304. static int flex_limit_w(const struct br_style *cs, int which_max, int avail)
  9305. {
  9306. unsigned char kind = which_max ? cs->max_width_kind :
  9307. cs->min_width_kind;
  9308. int w;
  9309. if (kind == 3)
  9310. w = which_max ?
  9311. avail * cs->max_width_calc_pct / 100 +
  9312. cs->max_width_calc_px :
  9313. avail * cs->min_width_calc_pct / 100 +
  9314. cs->min_width_calc_px;
  9315. else
  9316. w = css_size(kind, which_max ? cs->max_width : cs->min_width,
  9317. avail);
  9318. if (w < 0)
  9319. return -1;
  9320. if (!cs->box_sizing)
  9321. w += mp_px(cs, 7, avail) + mp_px(cs, 5, avail) +
  9322. cs->border_w[1] + cs->border_w[3];
  9323. return w + mp_px(cs, 3, avail) + mp_px(cs, 1, avail);
  9324. }
  9325. static int flex_clamp_w(const struct br_style *cs, int w, int avail)
  9326. {
  9327. int mx = flex_limit_w(cs, 1, avail), mn = flex_limit_w(cs, 0, avail);
  9328. if (mx >= 0 && w > mx)
  9329. w = mx;
  9330. if (mn >= 0 && w < mn)
  9331. w = mn;
  9332. return w;
  9333. }
  9334. static void layout_flex_children(struct lay *l, unsigned int parent,
  9335. const struct br_style *pst, int depth,
  9336. unsigned short link)
  9337. {
  9338. struct flex_item it[32];
  9339. unsigned int c;
  9340. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  9341. int grow_need = 0; /* growing items at their content width */
  9342. int row_left = l->left, row_right = l->right;
  9343. int avail = row_right - row_left;
  9344. int idx, row_top;
  9345. unsigned char row_align = l->align;
  9346. int box_left = l->left, box_right = l->right, row_top0 = l->y;
  9347. int bw = 0, aw = 0, first_h = -1;
  9348. struct br_style bps, aps;
  9349. if (avail < 8 || depth > 48) {
  9350. layout_children(l, parent, pst, depth, link);
  9351. return;
  9352. }
  9353. /* If direct text is not just whitespace, normal block flow handles it
  9354. * better than pretending it is a flex item. */
  9355. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9356. struct br_node *nd = &doc.nodes[c];
  9357. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9358. layout_children(l, parent, pst, depth, link);
  9359. return;
  9360. }
  9361. }
  9362. /* ::before/::after icon boxes are the row's first and last items
  9363. * (Docusaurus' sidebar chevron): reserve their columns. */
  9364. if (doc.npe_rules) {
  9365. bw = pseudo_box_w(parent, pst, 1, &bps, avail);
  9366. aw = pseudo_box_w(parent, pst, 2, &aps, avail);
  9367. if (bw + aw > avail - 8) {
  9368. bw = 0;
  9369. aw = 0;
  9370. }
  9371. row_left += bw;
  9372. row_right -= aw;
  9373. avail = row_right - row_left;
  9374. }
  9375. for (c = doc.nodes[parent].first;
  9376. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  9377. c = doc.nodes[c].next) {
  9378. struct br_node *nd = &doc.nodes[c];
  9379. struct br_style cs;
  9380. if (nd->type == BR_NODE_TEXT)
  9381. continue;
  9382. br_style_for(&doc, c, pst, &cs);
  9383. if (cs.display == BR_DISPLAY_NONE)
  9384. continue;
  9385. it[nitem].node = c;
  9386. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  9387. (unsigned short)c : link;
  9388. it[nitem].w = 0;
  9389. if (cs.flex_grow && !cs.width_kind) {
  9390. grow_count++;
  9391. grow_need += flex_item_width(l, c, &cs, avail);
  9392. } else
  9393. fixed += flex_clamp_w(&cs,
  9394. flex_item_width(l, c, &cs, avail),
  9395. avail);
  9396. nitem++;
  9397. }
  9398. /* A narrow container (an icon row sized to its content, Google's
  9399. * mic + lens buttons) is still a row when its items fit; only a
  9400. * narrow one that would overflow or squeeze growing items falls
  9401. * back to block flow. */
  9402. if (avail < 160 && fixed + grow_need > avail) {
  9403. layout_children(l, parent, pst, depth, link);
  9404. return;
  9405. }
  9406. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  9407. /* A growing item capped by max-width (Docusaurus' doc column,
  9408. * `max-width: 75%`; its main container, `calc(100% - 300px)`)
  9409. * keeps its cap and leaves the rest of the free space to the other
  9410. * growing items. */
  9411. if (grow_count) {
  9412. int pass, capped[32] = { 0 };
  9413. for (pass = 0; pass < nitem; pass++) {
  9414. int changed = 0;
  9415. for (idx = 0; idx < nitem; idx++) {
  9416. struct br_style cs;
  9417. int lim;
  9418. if (capped[idx])
  9419. continue;
  9420. br_style_for(&doc, it[idx].node, pst, &cs);
  9421. if (!cs.flex_grow || cs.width_kind)
  9422. continue;
  9423. lim = flex_clamp_w(&cs, grow_w, avail);
  9424. if (lim == grow_w)
  9425. continue;
  9426. capped[idx] = lim + 1;
  9427. fixed += lim;
  9428. grow_count--;
  9429. changed = 1;
  9430. }
  9431. if (!changed || !grow_count)
  9432. break;
  9433. grow_w = (avail - fixed) / grow_count;
  9434. }
  9435. for (idx = 0; idx < nitem; idx++)
  9436. it[idx].w = capped[idx] ? capped[idx] - 1 : 0;
  9437. }
  9438. if (grow_w < 96 && avail >= 160)
  9439. grow_w = 96;
  9440. for (idx = 0; idx < nitem; idx++) {
  9441. struct br_style cs;
  9442. if (it[idx].w)
  9443. continue; /* capped growing item */
  9444. br_style_for(&doc, it[idx].node, pst, &cs);
  9445. if (cs.flex_grow && !cs.width_kind)
  9446. it[idx].w = grow_w;
  9447. else
  9448. it[idx].w = flex_clamp_w(&cs,
  9449. flex_item_width(l,
  9450. it[idx].node,
  9451. &cs, avail),
  9452. avail);
  9453. if (it[idx].w > avail)
  9454. it[idx].w = avail;
  9455. if (it[idx].w < 8)
  9456. it[idx].w = 8;
  9457. }
  9458. row_top = l->y;
  9459. idx = 0;
  9460. while (idx < nitem) {
  9461. int start = idx, count = 0, row_w = 0;
  9462. int free_w, x, extra = 0, row_h = 0, k;
  9463. while (idx < nitem) {
  9464. int add = it[idx].w + (count ? gap : 0);
  9465. /* CSS default is nowrap; only flex-wrap: wrap (1)
  9466. * starts a new row. */
  9467. if (count && pst->flex_wrap == 1 &&
  9468. row_w + add > avail)
  9469. break;
  9470. row_w += add;
  9471. count++;
  9472. idx++;
  9473. }
  9474. if (!count) {
  9475. count = 1;
  9476. row_w = it[start].w;
  9477. idx = start + 1;
  9478. }
  9479. free_w = avail - row_w;
  9480. if (free_w < 0)
  9481. free_w = 0;
  9482. x = row_left;
  9483. if (pst->justify == 1) {
  9484. x += free_w / 2;
  9485. } else if (pst->justify == 2) {
  9486. x += free_w;
  9487. } else if (pst->justify == 3) {
  9488. extra = count > 1 ? free_w / (count - 1) : 0;
  9489. } else if (pst->justify == 4) {
  9490. extra = count ? free_w / count : 0;
  9491. x += extra / 2;
  9492. } else if (pst->justify == 5) {
  9493. extra = count ? free_w / (count + 1) : 0;
  9494. x += extra;
  9495. }
  9496. for (k = 0; k < count; k++) {
  9497. int node = (int)it[start + k].node;
  9498. int h = block_h[node];
  9499. if (h > row_h)
  9500. row_h = h;
  9501. }
  9502. if (pst->height_kind) {
  9503. int hh = style_height_px(pst, avail);
  9504. if (hh > row_h)
  9505. row_h = hh;
  9506. }
  9507. for (k = 0; k < count; k++) {
  9508. struct br_style cs;
  9509. int node = (int)it[start + k].node;
  9510. int yoff = 0;
  9511. br_style_for(&doc, node, pst, &cs);
  9512. cs.width_kind = 0;
  9513. cs.max_width_kind = 0;
  9514. {
  9515. int ai = cs.align_self ? cs.align_self - 1 :
  9516. pst->align_items;
  9517. if (l->draw && ai && row_h > block_h[node]) {
  9518. if (ai == 1)
  9519. yoff = (row_h -
  9520. block_h[node]) / 2;
  9521. else if (ai == 2)
  9522. yoff = row_h - block_h[node];
  9523. }
  9524. }
  9525. l->left = x;
  9526. l->right = x + it[start + k].w;
  9527. if (l->right < l->left + 8)
  9528. l->right = l->left + 8;
  9529. l->y = row_top + yoff;
  9530. l->line_x = l->left;
  9531. l->run_x = l->left;
  9532. l->line_y = l->y;
  9533. l->line_h = 0;
  9534. l->nruns = 0;
  9535. l->space_pending = 0;
  9536. l->align = cs.align;
  9537. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  9538. if (!l->draw) {
  9539. int h = l->y - row_top;
  9540. if (h > row_h)
  9541. row_h = h;
  9542. }
  9543. x += it[start + k].w;
  9544. if (k + 1 < count)
  9545. x += gap + extra;
  9546. }
  9547. if (first_h < 0)
  9548. first_h = row_h;
  9549. row_top += row_h;
  9550. }
  9551. if (bw || aw) {
  9552. int pass;
  9553. for (pass = 0; pass < 2; pass++) {
  9554. const struct br_style *ps = pass ? &aps : &bps;
  9555. int a = pass ? row_right : box_left;
  9556. int b = pass ? box_right : row_left;
  9557. int h = ps->height_kind ?
  9558. style_height_px(ps, box_right - box_left) : 0;
  9559. if (!(pass ? aw : bw))
  9560. continue;
  9561. l->left = l->line_left = l->line_x = l->run_x = a;
  9562. l->right = l->line_right = b;
  9563. l->y = row_top0;
  9564. if (pst->align_items == 1 && first_h > h)
  9565. l->y += (first_h - h) / 2;
  9566. l->line_y = l->y;
  9567. l->line_h = 0;
  9568. l->nruns = 0;
  9569. l->space_pending = 0;
  9570. emit_pseudo_box(l, pst, ps, link);
  9571. flush_line(l);
  9572. /* The box sits inside the first row; it only makes
  9573. * the row taller when it is taller itself. */
  9574. if (row_top0 + h > row_top)
  9575. row_top = row_top0 + h;
  9576. }
  9577. }
  9578. l->left = box_left;
  9579. l->right = box_right;
  9580. l->align = row_align;
  9581. l->y = row_top;
  9582. l->line_x = l->left;
  9583. l->run_x = l->left;
  9584. l->line_y = l->y;
  9585. l->line_h = 0;
  9586. l->nruns = 0;
  9587. l->space_pending = 0;
  9588. }
  9589. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  9590. * plus the grid-area hints used by site shells (site notice/footer full
  9591. * width, column-start left, page-content right). Anything more elaborate
  9592. * falls back to normal block flow. */
  9593. static int grid_track_width(unsigned char kind, unsigned short val,
  9594. int avail, int other)
  9595. {
  9596. if (kind == 2)
  9597. return avail * (int)val / 100;
  9598. if (kind == 1)
  9599. return val;
  9600. return other;
  9601. }
  9602. static void layout_grid_children(struct lay *l, unsigned int parent,
  9603. const struct br_style *pst, int depth,
  9604. unsigned short link)
  9605. {
  9606. unsigned int n;
  9607. int row_left = l->left, row_right = l->right;
  9608. int avail = row_right - row_left;
  9609. int gap = pst->grid_gap;
  9610. int track_total = avail - gap;
  9611. int col0, col1, x0, x1;
  9612. int row_y, row_bottom, have_left = 0, have_right = 0;
  9613. unsigned int c;
  9614. if (avail < 32 || depth > 48)
  9615. return;
  9616. if (track_total < 16)
  9617. track_total = 16;
  9618. col0 = grid_track_width((unsigned char)(pst->width_kind),
  9619. pst->width, track_total, 0);
  9620. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  9621. pst->max_width, track_total, 0);
  9622. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  9623. int w0 = pst->width ? pst->width : 1;
  9624. int w1 = pst->max_width ? pst->max_width : 1;
  9625. col0 = track_total * w0 / (w0 + w1);
  9626. col1 = track_total - col0;
  9627. } else if (pst->width_kind == 3) {
  9628. col0 = track_total - col1;
  9629. if (col0 < 24)
  9630. col0 = 24;
  9631. } else if (pst->max_width_kind == 3) {
  9632. col1 = track_total - col0;
  9633. if (col1 < 24)
  9634. col1 = 24;
  9635. }
  9636. if (col0 < 24)
  9637. col0 = 24;
  9638. if (col1 < 24)
  9639. col1 = 24;
  9640. if (col0 + col1 > track_total) {
  9641. col1 = track_total - col0;
  9642. if (col1 < 24)
  9643. col1 = 24;
  9644. }
  9645. x0 = row_left;
  9646. x1 = row_left + col0 + gap;
  9647. /* Direct text makes a grid ambiguous; use block flow instead. */
  9648. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9649. struct br_node *nd = &doc.nodes[c];
  9650. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9651. layout_children(l, parent, pst, depth, link);
  9652. return;
  9653. }
  9654. }
  9655. row_y = row_bottom = l->y;
  9656. n = doc.nodes[parent].first;
  9657. while (n) {
  9658. struct br_node *nd = &doc.nodes[n];
  9659. struct br_style cs;
  9660. unsigned short lk = link;
  9661. int slot, x, w;
  9662. if (nd->type == BR_NODE_TEXT) {
  9663. n = nd->next;
  9664. continue;
  9665. }
  9666. br_style_for(&doc, n, pst, &cs);
  9667. if (cs.display == BR_DISPLAY_NONE) {
  9668. n = nd->next;
  9669. continue;
  9670. }
  9671. if (nd->tag == BR_TAG_A && nd->href_off)
  9672. lk = (unsigned short)n;
  9673. slot = cs.grid_slot;
  9674. if (!slot) {
  9675. if (!have_left)
  9676. slot = 2;
  9677. else if (!have_right)
  9678. slot = 3;
  9679. else
  9680. slot = 2;
  9681. }
  9682. if (slot == 1) {
  9683. if (have_left || have_right) {
  9684. row_y = row_bottom;
  9685. have_left = have_right = 0;
  9686. }
  9687. x = row_left;
  9688. w = avail;
  9689. } else if (slot == 2) {
  9690. if (have_left) {
  9691. row_y = row_bottom;
  9692. have_left = have_right = 0;
  9693. }
  9694. x = x0;
  9695. w = col0;
  9696. have_left = 1;
  9697. } else {
  9698. if (have_right) {
  9699. row_y = row_bottom;
  9700. have_left = have_right = 0;
  9701. }
  9702. x = x1;
  9703. w = col1;
  9704. have_right = 1;
  9705. }
  9706. cs.width_kind = 0;
  9707. cs.max_width_kind = 0;
  9708. l->left = x;
  9709. l->right = x + w;
  9710. if (l->right < l->left + 8)
  9711. l->right = l->left + 8;
  9712. l->y = row_y;
  9713. l->line_x = l->left;
  9714. l->run_x = l->left;
  9715. l->line_y = l->y;
  9716. l->line_h = 0;
  9717. l->nruns = 0;
  9718. l->space_pending = 0;
  9719. l->align = cs.align;
  9720. layout_block(l, n, &cs, depth + 1, lk);
  9721. if (l->y > row_bottom)
  9722. row_bottom = l->y;
  9723. n = nd->next;
  9724. }
  9725. l->left = row_left;
  9726. l->right = row_right;
  9727. l->y = row_bottom;
  9728. l->line_x = l->left;
  9729. l->run_x = l->left;
  9730. l->line_y = l->y;
  9731. l->line_h = 0;
  9732. l->nruns = 0;
  9733. l->space_pending = 0;
  9734. }
  9735. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  9736. * capped at four. Used by the project docs' card grids. A fixed
  9737. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  9738. static void layout_grid_auto(struct lay *l, unsigned int parent,
  9739. const struct br_style *pst, int depth,
  9740. unsigned short link)
  9741. {
  9742. unsigned int n, c;
  9743. int row_left = l->left, row_right = l->right;
  9744. int avail = row_right - row_left;
  9745. int gap = pst->grid_gap;
  9746. int minw = pst->width_kind == 1 ? pst->width : 200;
  9747. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  9748. if (avail < 32 || depth > 48) {
  9749. layout_children(l, parent, pst, depth, link);
  9750. return;
  9751. }
  9752. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9753. struct br_node *nd = &doc.nodes[c];
  9754. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9755. layout_children(l, parent, pst, depth, link);
  9756. return;
  9757. }
  9758. }
  9759. if (minw < 80)
  9760. minw = 80;
  9761. ncols = (avail + gap) / (minw + gap);
  9762. if (ncols < 1)
  9763. ncols = 1;
  9764. if (ncols > 4)
  9765. ncols = 4;
  9766. if (pst->grid_auto > BR_GRID_FIXED) {
  9767. /* grid-template-columns: repeat(N, 1fr) */
  9768. ncols = pst->grid_auto - BR_GRID_FIXED;
  9769. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  9770. ncols--;
  9771. }
  9772. colw = (avail - gap * (ncols - 1)) / ncols;
  9773. if (colw < 24)
  9774. colw = 24;
  9775. x = row_left;
  9776. n = doc.nodes[parent].first;
  9777. while (n) {
  9778. struct br_node *nd = &doc.nodes[n];
  9779. struct br_style cs;
  9780. unsigned short lk = link;
  9781. int h;
  9782. if (nd->type == BR_NODE_TEXT) {
  9783. n = nd->next;
  9784. continue;
  9785. }
  9786. br_style_for(&doc, n, pst, &cs);
  9787. if (cs.display == BR_DISPLAY_NONE) {
  9788. n = nd->next;
  9789. continue;
  9790. }
  9791. if (nd->tag == BR_TAG_A && nd->href_off)
  9792. lk = (unsigned short)n;
  9793. cs.width_kind = 0;
  9794. cs.max_width_kind = 0;
  9795. l->left = x;
  9796. l->right = x + colw;
  9797. if (l->right < l->left + 8)
  9798. l->right = l->left + 8;
  9799. l->y = y;
  9800. l->line_x = l->left;
  9801. l->run_x = l->left;
  9802. l->line_y = l->y;
  9803. l->line_h = 0;
  9804. l->nruns = 0;
  9805. l->space_pending = 0;
  9806. l->align = cs.align;
  9807. layout_block(l, n, &cs, depth + 1, lk);
  9808. h = l->y - y;
  9809. if (h > row_h)
  9810. row_h = h;
  9811. col++;
  9812. n = nd->next;
  9813. if (col == ncols) {
  9814. y += row_h + gap;
  9815. x = row_left;
  9816. row_h = 0;
  9817. col = 0;
  9818. } else {
  9819. x += colw + gap;
  9820. }
  9821. }
  9822. if (col)
  9823. y += row_h;
  9824. else if (y > start_y)
  9825. y -= gap;
  9826. l->left = row_left;
  9827. l->right = row_right;
  9828. l->y = y;
  9829. l->line_x = l->left;
  9830. l->run_x = l->left;
  9831. l->line_y = l->y;
  9832. l->line_h = 0;
  9833. l->nruns = 0;
  9834. l->space_pending = 0;
  9835. }
  9836. /* Column widths are the widest cell in each column across every row, so all
  9837. * rows line up. The table model is still deliberately basic: no colspan,
  9838. * border-collapse or percentage columns. */
  9839. static void table_columns(struct lay *l, unsigned int table,
  9840. const struct br_style *pst, int avail,
  9841. int *raw, int maxcols, int *out_cols,
  9842. int *out_total)
  9843. {
  9844. unsigned int r, c;
  9845. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  9846. int fixed[12];
  9847. for (c = 0; c < (unsigned int)maxcols; c++) {
  9848. raw[c] = 0;
  9849. fixed[c] = 0;
  9850. }
  9851. /* Intrinsic widths of single-column cells. */
  9852. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9853. struct br_node *rn = &doc.nodes[r];
  9854. int col = 0;
  9855. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9856. continue;
  9857. for (c = rn->first; c; c = doc.nodes[c].next) {
  9858. struct br_node *cn = &doc.nodes[c];
  9859. struct br_style cs;
  9860. int w, span;
  9861. if (cn->type != BR_NODE_ELEM ||
  9862. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9863. continue;
  9864. span = cn->colspan ? cn->colspan : 1;
  9865. br_style_for(&doc, c, pst, &cs);
  9866. if (cs.display == BR_DISPLAY_NONE)
  9867. continue;
  9868. if (col + span > maxcols)
  9869. span = maxcols - col;
  9870. if (span < 1)
  9871. break;
  9872. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  9873. mp_px(&cs, 7, avail) +
  9874. mp_px(&cs, 5, avail) +
  9875. mp_px(&cs, 3, avail) +
  9876. mp_px(&cs, 1, avail) +
  9877. cs.border_w[0] + cs.border_w[1] +
  9878. cs.border_w[2] + cs.border_w[3];
  9879. if (w < 24)
  9880. w = 24;
  9881. if (span == 1) {
  9882. if (w > raw[col])
  9883. raw[col] = w;
  9884. }
  9885. if (col + span > cols)
  9886. cols = col + span;
  9887. col += span;
  9888. }
  9889. }
  9890. /* A colspan cell only has to be as wide as the sum of its columns. */
  9891. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9892. struct br_node *rn = &doc.nodes[r];
  9893. int col = 0;
  9894. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9895. continue;
  9896. for (c = rn->first; c; c = doc.nodes[c].next) {
  9897. struct br_node *cn = &doc.nodes[c];
  9898. struct br_style cs;
  9899. int span, w, sum, i;
  9900. if (cn->type != BR_NODE_ELEM ||
  9901. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9902. continue;
  9903. span = cn->colspan ? cn->colspan : 1;
  9904. if (col + span > maxcols)
  9905. span = maxcols - col;
  9906. if (span < 1)
  9907. break;
  9908. if (span > 1) {
  9909. br_style_for(&doc, c, pst, &cs);
  9910. if (cs.display != BR_DISPLAY_NONE) {
  9911. w = intrinsic_width(l->ui, c, &cs,
  9912. 0, avail) +
  9913. mp_px(&cs, 7, avail) +
  9914. mp_px(&cs, 5, avail) +
  9915. mp_px(&cs, 3, avail) +
  9916. mp_px(&cs, 1, avail) +
  9917. cs.border_w[0] + cs.border_w[1] +
  9918. cs.border_w[2] + cs.border_w[3];
  9919. sum = 0;
  9920. for (i = 0; i < span; i++)
  9921. sum += raw[col + i];
  9922. if (w > sum)
  9923. raw[col + span - 1] += w - sum;
  9924. }
  9925. }
  9926. col += span;
  9927. }
  9928. }
  9929. /* Explicit and percentage widths override intrinsic widths. */
  9930. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9931. struct br_node *rn = &doc.nodes[r];
  9932. int col = 0;
  9933. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9934. continue;
  9935. for (c = rn->first; c; c = doc.nodes[c].next) {
  9936. struct br_node *cn = &doc.nodes[c];
  9937. struct br_style cs;
  9938. int span;
  9939. if (cn->type != BR_NODE_ELEM ||
  9940. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9941. continue;
  9942. span = cn->colspan ? cn->colspan : 1;
  9943. if (col + span > maxcols)
  9944. span = maxcols - col;
  9945. if (span < 1)
  9946. break;
  9947. if (span == 1) {
  9948. br_style_for(&doc, c, pst, &cs);
  9949. if (cs.display != BR_DISPLAY_NONE) {
  9950. if (cs.width_kind == 1) {
  9951. raw[col] = cs.width;
  9952. fixed[col] = 1;
  9953. } else if (cs.width_kind == 2 ||
  9954. cs.width_kind == 3) {
  9955. raw[col] = style_width_px(&cs,
  9956. avail);
  9957. fixed[col] = 1;
  9958. }
  9959. }
  9960. }
  9961. col += span;
  9962. }
  9963. }
  9964. for (c = 0; c < (unsigned int)cols; c++) {
  9965. if (raw[c] < 8)
  9966. raw[c] = 8;
  9967. total += raw[c];
  9968. if (fixed[c])
  9969. fixed_sum += raw[c];
  9970. else {
  9971. free_raw += raw[c];
  9972. free_cols++;
  9973. }
  9974. }
  9975. if (fixed_sum > 0 && fixed_sum < avail) {
  9976. int free_avail = avail - fixed_sum;
  9977. int i;
  9978. if (free_raw > 0) {
  9979. for (i = 0; i < cols; i++)
  9980. if (!fixed[i])
  9981. raw[i] = free_avail * raw[i] /
  9982. free_raw;
  9983. } else if (free_cols > 0) {
  9984. for (i = 0; i < cols; i++)
  9985. if (!fixed[i])
  9986. raw[i] = free_avail / free_cols;
  9987. }
  9988. total = 0;
  9989. for (i = 0; i < cols; i++)
  9990. total += raw[i];
  9991. } else if (total < avail && total > 0) {
  9992. int i;
  9993. for (i = 0; i < cols; i++)
  9994. raw[i] = raw[i] * avail / total;
  9995. total = 0;
  9996. for (i = 0; i < cols; i++)
  9997. total += raw[i];
  9998. }
  9999. *out_cols = cols;
  10000. *out_total = total;
  10001. }
  10002. static void layout_table_row(struct lay *l, unsigned int row,
  10003. const struct br_style *pst, int depth,
  10004. unsigned short link)
  10005. {
  10006. unsigned int n, cell[12];
  10007. int raw[12], colstart[12], colspan[12];
  10008. int prefix[13];
  10009. int ncell = 0, total = 0, cols = 0, col = 0;
  10010. int row_left = l->left, row_right = l->right;
  10011. int avail = row_right - row_left;
  10012. int y = l->y, bottom = l->y;
  10013. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  10014. struct br_node *nd = &doc.nodes[n];
  10015. struct br_style cs;
  10016. int span;
  10017. if (nd->type == BR_NODE_TEXT) {
  10018. if (text_node_blank(nd))
  10019. continue;
  10020. layout_children(l, row, pst, depth, link);
  10021. return;
  10022. }
  10023. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  10024. layout_children(l, row, pst, depth, link);
  10025. return;
  10026. }
  10027. br_style_for(&doc, n, pst, &cs);
  10028. if (cs.display == BR_DISPLAY_NONE)
  10029. continue;
  10030. if (ncell >= 12) {
  10031. layout_children(l, row, pst, depth, link);
  10032. return;
  10033. }
  10034. span = nd->colspan ? nd->colspan : 1;
  10035. if (span > 12 - col)
  10036. span = 12 - col;
  10037. if (span < 1)
  10038. continue;
  10039. cell[ncell] = n;
  10040. colstart[ncell] = col;
  10041. colspan[ncell] = span;
  10042. col += span;
  10043. ncell++;
  10044. }
  10045. if (ncell < 1 || avail < 32) {
  10046. layout_children(l, row, pst, depth, link);
  10047. return;
  10048. }
  10049. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  10050. &total);
  10051. if (cols < 2 || total <= 0) {
  10052. int c;
  10053. total = 0;
  10054. for (c = 0; c < ncell; c++) {
  10055. struct br_style cs;
  10056. br_style_for(&doc, cell[c], pst, &cs);
  10057. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  10058. avail) +
  10059. mp_px(&cs, 7, avail) +
  10060. mp_px(&cs, 5, avail) +
  10061. mp_px(&cs, 3, avail) +
  10062. mp_px(&cs, 1, avail);
  10063. if (raw[c] < 24)
  10064. raw[c] = 24;
  10065. total += raw[c];
  10066. }
  10067. /* A one-column table still has to fill its own width; the
  10068. * intrinsic fallback above otherwise leaves the cell at its
  10069. * text width (HN's outer table and nested story table). */
  10070. if (total > 0 && total < avail) {
  10071. int c;
  10072. for (c = 0; c < ncell; c++)
  10073. raw[c] = raw[c] * avail / total;
  10074. total = avail;
  10075. }
  10076. }
  10077. prefix[0] = row_left;
  10078. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  10079. prefix[n + 1] = prefix[n] + raw[n];
  10080. for (n = 0; n < (unsigned int)ncell; n++) {
  10081. struct br_style cs;
  10082. int start = colstart[n];
  10083. int end = start + colspan[n];
  10084. int w;
  10085. if (end > cols)
  10086. end = cols;
  10087. if (start >= cols)
  10088. continue;
  10089. w = prefix[end] - prefix[start];
  10090. br_style_for(&doc, cell[n], pst, &cs);
  10091. /* The column width already reflects the cell's width property. */
  10092. cs.width_kind = 0;
  10093. cs.max_width_kind = 0;
  10094. if (w < 24)
  10095. w = 24;
  10096. if (w < 8)
  10097. w = 8;
  10098. l->left = prefix[start];
  10099. l->right = l->left + w;
  10100. l->y = y;
  10101. l->line_x = l->left;
  10102. l->run_x = l->left;
  10103. l->line_y = l->y;
  10104. l->line_h = 0;
  10105. l->nruns = 0;
  10106. l->space_pending = 0;
  10107. l->align = cs.align;
  10108. layout_block(l, cell[n], &cs, depth + 1, link);
  10109. if (l->y > bottom)
  10110. bottom = l->y;
  10111. }
  10112. l->left = row_left;
  10113. l->right = row_right;
  10114. l->y = bottom;
  10115. l->line_x = l->left;
  10116. l->run_x = l->left;
  10117. l->line_y = l->y;
  10118. l->line_h = 0;
  10119. l->nruns = 0;
  10120. l->space_pending = 0;
  10121. }
  10122. #define TBL_MAX_ROWS 32
  10123. #define TBL_MAX_COLS 12
  10124. #define TBL_MAX_CELLS 128
  10125. struct tbl_cell {
  10126. unsigned int node;
  10127. unsigned char row, col, rowspan, colspan;
  10128. int height;
  10129. };
  10130. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  10131. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  10132. static int table_active;
  10133. static int table_has_rowspan(unsigned int table)
  10134. {
  10135. unsigned int r, c;
  10136. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10137. struct br_node *rn = &doc.nodes[r];
  10138. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10139. continue;
  10140. for (c = rn->first; c; c = doc.nodes[c].next) {
  10141. struct br_node *cn = &doc.nodes[c];
  10142. if (cn->type == BR_NODE_ELEM &&
  10143. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  10144. cn->rowspan > 1)
  10145. return 1;
  10146. }
  10147. }
  10148. return 0;
  10149. }
  10150. static void table_cell_style(unsigned int row, unsigned int cell,
  10151. const struct br_style *st, struct br_style *out)
  10152. {
  10153. struct br_style trs;
  10154. br_style_for(&doc, row, st, &trs);
  10155. br_style_for(&doc, cell, &trs, out);
  10156. }
  10157. /* Tables that use rowspan need row heights before anything is painted. This
  10158. * path builds a small occupancy grid, measures the natural cell heights, then
  10159. * lays every cell out at its row/column position. Tables without rowspan
  10160. * keep the lighter per-row path in layout_table_row(). */
  10161. static void layout_table(struct lay *l, unsigned int table,
  10162. const struct br_style *st, int depth,
  10163. unsigned short link)
  10164. {
  10165. unsigned int rows[TBL_MAX_ROWS];
  10166. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  10167. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  10168. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  10169. int free_raw = 0, free_cols = 0;
  10170. int table_left = l->left, table_right = l->right;
  10171. int top = l->y, avail = table_right - table_left;
  10172. unsigned int r, c;
  10173. int i, rr, cc;
  10174. if (depth > 48 || table_active) {
  10175. layout_children(l, table, st, depth, link);
  10176. return;
  10177. }
  10178. table_active = 1;
  10179. for (r = doc.nodes[table].first;
  10180. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  10181. struct br_node *rn = &doc.nodes[r];
  10182. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  10183. rows[nrows++] = r;
  10184. }
  10185. if (!nrows) {
  10186. table_active = 0;
  10187. layout_children(l, table, st, depth, link);
  10188. return;
  10189. }
  10190. for (rr = 0; rr < nrows; rr++)
  10191. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  10192. tbl_at[rr][cc] = 0;
  10193. for (rr = 0; rr < nrows; rr++) {
  10194. int col = 0;
  10195. for (c = doc.nodes[rows[rr]].first; c;
  10196. c = doc.nodes[c].next) {
  10197. struct br_node *cn = &doc.nodes[c];
  10198. struct br_style cs;
  10199. int rs, csn;
  10200. if (cn->type != BR_NODE_ELEM ||
  10201. (cn->tag != BR_TAG_TD &&
  10202. cn->tag != BR_TAG_TH))
  10203. continue;
  10204. table_cell_style(rows[rr], c, st, &cs);
  10205. if (cs.display == BR_DISPLAY_NONE)
  10206. continue;
  10207. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  10208. col++;
  10209. if (col >= TBL_MAX_COLS)
  10210. break;
  10211. rs = cn->rowspan ? cn->rowspan : 1;
  10212. csn = cn->colspan ? cn->colspan : 1;
  10213. if (rr + rs > nrows)
  10214. rs = nrows - rr;
  10215. if (col + csn > TBL_MAX_COLS)
  10216. csn = TBL_MAX_COLS - col;
  10217. if (rs < 1 || csn < 1)
  10218. continue;
  10219. if (ncells >= TBL_MAX_CELLS)
  10220. break;
  10221. tbl_cells[ncells].node = c;
  10222. tbl_cells[ncells].row = (unsigned char)rr;
  10223. tbl_cells[ncells].col = (unsigned char)col;
  10224. tbl_cells[ncells].rowspan = (unsigned char)rs;
  10225. tbl_cells[ncells].colspan = (unsigned char)csn;
  10226. tbl_cells[ncells].height = 0;
  10227. for (i = rr; i < rr + rs; i++)
  10228. for (int j = col; j < col + csn; j++)
  10229. tbl_at[i][j] =
  10230. (unsigned short)(ncells + 1);
  10231. ncells++;
  10232. col += csn;
  10233. if (col > cols)
  10234. cols = col;
  10235. }
  10236. }
  10237. if (!ncells || cols < 1) {
  10238. table_active = 0;
  10239. layout_children(l, table, st, depth, link);
  10240. return;
  10241. }
  10242. for (i = 0; i < cols; i++) {
  10243. raw[i] = 0;
  10244. fixed[i] = 0;
  10245. }
  10246. /* Intrinsic widths of single-column cells. */
  10247. for (i = 0; i < ncells; i++) {
  10248. struct br_style cs;
  10249. int w;
  10250. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10251. st, &cs);
  10252. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10253. mp_px(&cs, 7, avail) +
  10254. mp_px(&cs, 5, avail) +
  10255. mp_px(&cs, 3, avail) +
  10256. mp_px(&cs, 1, avail) +
  10257. cs.border_w[0] + cs.border_w[1] +
  10258. cs.border_w[2] + cs.border_w[3];
  10259. if (w < 24)
  10260. w = 24;
  10261. if (tbl_cells[i].colspan == 1) {
  10262. int col = tbl_cells[i].col;
  10263. if (w > raw[col])
  10264. raw[col] = w;
  10265. }
  10266. }
  10267. /* A spanning cell only needs the sum of its columns to be large
  10268. * enough; put the deficit in the last column. */
  10269. for (i = 0; i < ncells; i++) {
  10270. struct br_style cs;
  10271. int w, sum, col, span;
  10272. if (tbl_cells[i].colspan < 2)
  10273. continue;
  10274. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10275. st, &cs);
  10276. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10277. mp_px(&cs, 7, avail) +
  10278. mp_px(&cs, 5, avail) +
  10279. mp_px(&cs, 3, avail) +
  10280. mp_px(&cs, 1, avail) +
  10281. cs.border_w[0] + cs.border_w[1] +
  10282. cs.border_w[2] + cs.border_w[3];
  10283. col = tbl_cells[i].col;
  10284. span = tbl_cells[i].colspan;
  10285. sum = 0;
  10286. for (int j = 0; j < span; j++)
  10287. sum += raw[col + j];
  10288. if (w > sum)
  10289. raw[col + span - 1] += w - sum;
  10290. }
  10291. /* Explicit/percentage widths, as in table_columns(). */
  10292. for (i = 0; i < ncells; i++) {
  10293. struct br_style cs;
  10294. int col;
  10295. if (tbl_cells[i].colspan != 1)
  10296. continue;
  10297. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10298. st, &cs);
  10299. col = tbl_cells[i].col;
  10300. if (cs.width_kind == 1) {
  10301. raw[col] = cs.width;
  10302. fixed[col] = 1;
  10303. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  10304. raw[col] = style_width_px(&cs, avail);
  10305. fixed[col] = 1;
  10306. }
  10307. }
  10308. for (i = 0; i < cols; i++) {
  10309. if (raw[i] < 8)
  10310. raw[i] = 8;
  10311. total += raw[i];
  10312. if (fixed[i])
  10313. fixed_sum += raw[i];
  10314. else {
  10315. free_raw += raw[i];
  10316. free_cols++;
  10317. }
  10318. }
  10319. if (fixed_sum > 0 && fixed_sum < avail) {
  10320. int free_avail = avail - fixed_sum;
  10321. if (free_raw > 0) {
  10322. for (i = 0; i < cols; i++)
  10323. if (!fixed[i])
  10324. raw[i] = free_avail * raw[i] /
  10325. free_raw;
  10326. } else if (free_cols > 0) {
  10327. for (i = 0; i < cols; i++)
  10328. if (!fixed[i])
  10329. raw[i] = free_avail / free_cols;
  10330. }
  10331. } else if (total < avail && total > 0) {
  10332. for (i = 0; i < cols; i++)
  10333. raw[i] = raw[i] * avail / total;
  10334. }
  10335. prefix[0] = table_left;
  10336. for (i = 0; i < cols; i++)
  10337. prefix[i + 1] = prefix[i] + raw[i];
  10338. /* Measure natural cell heights with the column widths. */
  10339. for (i = 0; i < ncells; i++) {
  10340. struct br_style cs;
  10341. int col = tbl_cells[i].col;
  10342. int span = tbl_cells[i].colspan;
  10343. int w = prefix[col + span] - prefix[col];
  10344. int sl = l->left, sr = l->right, sy = l->y;
  10345. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10346. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10347. int sal = l->align, sdraw = l->draw;
  10348. struct ngui *sui = l->ui;
  10349. if (w < 8)
  10350. w = 8;
  10351. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10352. st, &cs);
  10353. cs.width_kind = 0;
  10354. cs.max_width_kind = 0;
  10355. l->draw = 0;
  10356. l->ui = 0;
  10357. l->left = prefix[col];
  10358. l->right = l->left + w;
  10359. l->y = 0;
  10360. l->line_x = l->left;
  10361. l->run_x = l->left;
  10362. l->line_y = 0;
  10363. l->line_h = 0;
  10364. l->nruns = 0;
  10365. l->space_pending = 0;
  10366. l->align = cs.align;
  10367. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10368. tbl_cells[i].height = block_h[tbl_cells[i].node];
  10369. l->left = sl;
  10370. l->right = sr;
  10371. l->y = sy;
  10372. l->line_x = slx;
  10373. l->run_x = srx;
  10374. l->line_y = sly;
  10375. l->line_h = slh;
  10376. l->nruns = snr;
  10377. l->space_pending = ssp;
  10378. l->align = sal;
  10379. l->draw = sdraw;
  10380. l->ui = sui;
  10381. }
  10382. for (i = 0; i < nrows; i++)
  10383. rowh[i] = 0;
  10384. for (i = 0; i < ncells; i++) {
  10385. int row = tbl_cells[i].row;
  10386. if (tbl_cells[i].rowspan == 1) {
  10387. if (tbl_cells[i].height > rowh[row])
  10388. rowh[row] = tbl_cells[i].height;
  10389. }
  10390. }
  10391. for (i = 0; i < ncells; i++) {
  10392. int row = tbl_cells[i].row;
  10393. int span = tbl_cells[i].rowspan;
  10394. int sum = 0;
  10395. if (span < 2)
  10396. continue;
  10397. for (int j = 0; j < span; j++)
  10398. sum += rowh[row + j];
  10399. if (sum < tbl_cells[i].height)
  10400. rowh[row + span - 1] +=
  10401. tbl_cells[i].height - sum;
  10402. }
  10403. for (i = 0; i < nrows; i++)
  10404. if (rowh[i] < 8)
  10405. rowh[i] = 8;
  10406. rowy[0] = top;
  10407. for (i = 1; i < nrows; i++)
  10408. rowy[i] = rowy[i - 1] + rowh[i - 1];
  10409. if (!l->draw) {
  10410. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10411. table_active = 0;
  10412. return;
  10413. }
  10414. for (i = 0; i < ncells; i++) {
  10415. struct br_style cs;
  10416. int col = tbl_cells[i].col;
  10417. int span = tbl_cells[i].colspan;
  10418. int row = tbl_cells[i].row;
  10419. int rspan = tbl_cells[i].rowspan;
  10420. int w = prefix[col + span] - prefix[col];
  10421. int h = 0;
  10422. int sl = l->left, sr = l->right, sy = l->y;
  10423. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10424. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10425. int sal = l->align;
  10426. int deco;
  10427. for (int j = 0; j < rspan; j++)
  10428. h += rowh[row + j];
  10429. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  10430. cs.width_kind = 0;
  10431. cs.max_width_kind = 0;
  10432. cs.box_sizing = 0;
  10433. deco = mp_px(&cs, 4, avail) +
  10434. mp_px(&cs, 6, avail) +
  10435. cs.border_w[0] + cs.border_w[2];
  10436. cs.height_kind = 1;
  10437. cs.height = h > deco ? h - deco : 0;
  10438. /* The block painter reads block_h[] from the measure pass; make
  10439. * the table cell fill its row/rowspan, not just its content. */
  10440. if (h > 0 && h < 65536)
  10441. block_h[tbl_cells[i].node] = (unsigned short)h;
  10442. l->left = prefix[col];
  10443. l->right = l->left + w;
  10444. l->y = rowy[row];
  10445. l->line_x = l->left;
  10446. l->run_x = l->left;
  10447. l->line_y = l->y;
  10448. l->line_h = 0;
  10449. l->nruns = 0;
  10450. l->space_pending = 0;
  10451. l->align = cs.align;
  10452. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10453. l->left = sl;
  10454. l->right = sr;
  10455. l->y = sy;
  10456. l->line_x = slx;
  10457. l->run_x = srx;
  10458. l->line_y = sly;
  10459. l->line_h = slh;
  10460. l->nruns = snr;
  10461. l->space_pending = ssp;
  10462. l->align = sal;
  10463. }
  10464. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10465. table_active = 0;
  10466. }
  10467. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  10468. * flow so they sit above it, like CSS painting order. Their flow origin is
  10469. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  10470. struct br_deferred {
  10471. unsigned int node;
  10472. int flow_y, flow_left, flow_right;
  10473. int parent_top; /* the parent box top, for sticky clamping */
  10474. unsigned short link;
  10475. signed short z_index;
  10476. unsigned char z_set;
  10477. unsigned int order;
  10478. };
  10479. /* Positioned boxes painted after the flow. News front pages have one or two
  10480. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  10481. * old 16 entries the rest fell back into the flow, so a hero image landed
  10482. * below its padding-top aspect box instead of on top of it. */
  10483. #define BR_MAX_DEFERRED 256
  10484. static struct br_deferred deferred[BR_MAX_DEFERRED];
  10485. static int ndeferred;
  10486. /* Outer width of an element's empty ::before (pe 1) / ::after (pe 2) icon
  10487. * box, 0 when it has none; *ps receives the pseudo-element's style. */
  10488. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  10489. struct br_style *ps, int base)
  10490. {
  10491. char buf[8];
  10492. int w, h;
  10493. if (!doc.npe_rules ||
  10494. br_pseudo(&doc, node, pe, st, ps, buf, sizeof(buf)) ||
  10495. ps->content != BR_CONTENT_EMPTY || ps->display == BR_DISPLAY_NONE)
  10496. return 0;
  10497. w = ps->width_kind ? style_width_px(ps, base) : 0;
  10498. h = ps->height_kind ? style_height_px(ps, base) : 0;
  10499. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  10500. w = (int)ps->min_width;
  10501. if (w <= 0)
  10502. w = h;
  10503. if (w <= 0 || w > 512)
  10504. return 0;
  10505. return w + (ps->ml_auto ? 0 : mp_px(ps, 3, base)) + mp_px(ps, 1, base);
  10506. }
  10507. /* An empty ::before/::after with a size and a background: one run the
  10508. * size of the box. Only data: background images are drawn (decoded at
  10509. * the background-size); `margin-left: auto` inside a flex parent pushes
  10510. * the box to the line's right edge like the flex row would. */
  10511. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  10512. const struct br_style *ps, unsigned short link)
  10513. {
  10514. struct lay_run *r;
  10515. int lw = l->line_right - l->line_left, w, h, ml, mr, tw, th;
  10516. const char *url = ps->bg_image ? br_bg_image_url(ps->bg_image - 1) : "";
  10517. if (lw < 8)
  10518. lw = 8;
  10519. w = ps->width_kind ? style_width_px(ps, lw) : 0;
  10520. h = ps->height_kind ? style_height_px(ps, lw) : 0;
  10521. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  10522. w = (int)ps->min_width;
  10523. if (w <= 0)
  10524. w = h;
  10525. if (h <= 0)
  10526. h = w;
  10527. if (w <= 0 || w > 512 || h > 512)
  10528. return;
  10529. ml = ps->ml_auto ? 0 : mp_px(ps, 3, lw);
  10530. mr = mp_px(ps, 1, lw);
  10531. if (ml < 0)
  10532. ml = 0;
  10533. if (mr < 0)
  10534. mr = 0;
  10535. if (l->line_x + ml + w > l->line_right &&
  10536. (l->nruns > 0 || l->line_x > l->line_left))
  10537. flush_line(l);
  10538. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  10539. flush_line(l);
  10540. if (l->nruns == 0) {
  10541. l->line_y = l->y;
  10542. l->line_h = 0;
  10543. start_line(l, ps);
  10544. }
  10545. if (ps->ml_auto && parent->display == BR_DISPLAY_FLEX &&
  10546. l->line_right - w - mr > l->line_x)
  10547. l->line_x = l->line_right - w - mr;
  10548. else
  10549. l->line_x += ml;
  10550. r = &l->runs[l->nruns++];
  10551. memset(r, 0, sizeof(*r));
  10552. r->gap = (unsigned short)(l->line_x > l->run_x ?
  10553. l->line_x - l->run_x : 0);
  10554. r->img = RUN_PBOX;
  10555. r->href = link;
  10556. r->iw = (unsigned short)w;
  10557. r->ih = (unsigned short)h;
  10558. r->w = (unsigned short)w;
  10559. r->font_px = ps->font_px;
  10560. r->pb_has_bg = ps->has_bg;
  10561. r->pb_bg = ps->bg;
  10562. r->pb_img = -1;
  10563. if (ps->transform_set) {
  10564. r->transform_scale = 1;
  10565. r->scale_x = ps->scale_x;
  10566. r->scale_y = ps->scale_y;
  10567. r->rotate_x100 = ps->rotate_x100;
  10568. }
  10569. /* Background size and position, as draw_bg_image() resolves them. */
  10570. tw = w;
  10571. th = h;
  10572. if (ps->bg_size_kind == 1 || ps->bg_size_kind == 2) {
  10573. int bw = ps->bg_size_w, bh = ps->bg_size_h;
  10574. if (ps->bg_size_kind == 2) {
  10575. bw = bw ? w * bw / 100 : 0;
  10576. bh = bh ? h * bh / 100 : 0;
  10577. }
  10578. tw = bw ? bw : (bh ? bh : w);
  10579. th = bh ? bh : tw;
  10580. }
  10581. if (tw > 0 && th > 0 && tw <= 512 && th <= 512 && url[0])
  10582. r->pb_img = (short)data_url_image(url, tw, th);
  10583. r->pb_w = (short)tw;
  10584. r->pb_h = (short)th;
  10585. r->pb_x = (short)(ps->bg_pos_x_kind == 1 ?
  10586. (w - tw) * ps->bg_pos_x / 100 : ps->bg_pos_x);
  10587. r->pb_y = (short)(ps->bg_pos_y_kind == 1 ?
  10588. (h - th) * ps->bg_pos_y / 100 : ps->bg_pos_y);
  10589. l->line_x += w + mr;
  10590. l->run_x = l->line_x;
  10591. if (l->line_h < h)
  10592. l->line_h = h;
  10593. }
  10594. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  10595. * element's line. A block-level pseudo-element gets its own line; its box
  10596. * (margins, padding, background) is not drawn. */
  10597. static void emit_pseudo(struct lay *l, unsigned int node,
  10598. const struct br_style *st, int pe, unsigned short link)
  10599. {
  10600. char buf[160];
  10601. struct br_style ps;
  10602. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  10603. unsigned int i = 0;
  10604. int block, space_w;
  10605. if (!n && ps.content == BR_CONTENT_EMPTY &&
  10606. ps.display != BR_DISPLAY_NONE) {
  10607. emit_pseudo_box(l, st, &ps, link);
  10608. return;
  10609. }
  10610. if (!n)
  10611. return;
  10612. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  10613. if (block)
  10614. flush_line(l);
  10615. if (ps.uppercase)
  10616. for (i = 0; i < n; i++)
  10617. if (buf[i] >= 'a' && buf[i] <= 'z')
  10618. buf[i] = (char)(buf[i] - 'a' + 'A');
  10619. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  10620. if (space_w <= 0)
  10621. space_w = 8;
  10622. i = 0;
  10623. while (i < n) {
  10624. char word[28];
  10625. unsigned int k = 0;
  10626. int w;
  10627. if (buf[i] == ' ') {
  10628. l->space_pending = 1;
  10629. i++;
  10630. continue;
  10631. }
  10632. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  10633. word[k++] = buf[i++];
  10634. word[k] = '\0';
  10635. if (l->space_pending &&
  10636. (l->nruns > 0 || l->line_x > l->line_left) &&
  10637. l->line_x + space_w <= l->line_right)
  10638. l->line_x += space_w;
  10639. l->space_pending = 0;
  10640. w = (int)face_text_width(l->ui, &ps, word, k);
  10641. if (l->line_x + w > l->line_right &&
  10642. (l->nruns > 0 || l->line_x > l->line_left))
  10643. flush_line(l);
  10644. add_run(l, 0, 0, &ps, link, word);
  10645. }
  10646. if (block)
  10647. flush_line(l);
  10648. }
  10649. static void layout_children(struct lay *l, unsigned int parent,
  10650. const struct br_style *pst, int depth,
  10651. unsigned short link)
  10652. {
  10653. unsigned int n;
  10654. if (depth > 48)
  10655. return;
  10656. emit_pseudo(l, parent, pst, 1, link);
  10657. n = doc.nodes[parent].first;
  10658. while (n) {
  10659. struct br_node *nd = &doc.nodes[n];
  10660. struct br_style cs;
  10661. unsigned short lk = link;
  10662. if (nd->type == BR_NODE_TEXT) {
  10663. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  10664. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  10665. n = nd->next;
  10666. continue;
  10667. }
  10668. br_style_for(&doc, n, pst, &cs);
  10669. if (cs.display == BR_DISPLAY_NONE) {
  10670. n = nd->next;
  10671. continue;
  10672. }
  10673. if (cs.clear && l->float_active) {
  10674. flush_line(l);
  10675. if (l->y < l->float_bottom)
  10676. l->y = l->float_bottom;
  10677. l->float_active = 0;
  10678. l->line_x = l->left;
  10679. l->run_x = l->left;
  10680. l->line_left = l->left;
  10681. l->line_right = l->right;
  10682. l->line_y = l->y;
  10683. l->line_h = 0;
  10684. l->nruns = 0;
  10685. l->space_pending = 0;
  10686. }
  10687. if (nd->tag == BR_TAG_A && nd->href_off)
  10688. lk = (unsigned short)n;
  10689. if (cs.pos == 1 || cs.pos == 2 ||
  10690. ((cs.pos == 3 || cs.pos == 4) && cs.z_set)) {
  10691. if ((cs.pos == 3 || cs.pos == 4) && l->draw &&
  10692. ndeferred < BR_MAX_DEFERRED) {
  10693. /* Relative or sticky z-index (a sticky site
  10694. * header): measure and advance the flow without
  10695. * painting, then paint it in the deferred
  10696. * (stacked) pass, above the content after it. */
  10697. int fy = l->y, fl = l->left, fr = l->right;
  10698. int save_draw = l->draw;
  10699. l->draw = 0;
  10700. layout_block(l, n, &cs, depth + 1, lk);
  10701. l->draw = save_draw;
  10702. deferred[ndeferred].node = n;
  10703. deferred[ndeferred].parent_top = l->parent_top;
  10704. deferred[ndeferred].flow_y = fy;
  10705. deferred[ndeferred].flow_left = fl;
  10706. deferred[ndeferred].flow_right = fr;
  10707. deferred[ndeferred].link = lk;
  10708. deferred[ndeferred].z_index = cs.z_index;
  10709. deferred[ndeferred].z_set = cs.z_set;
  10710. deferred[ndeferred].order = (unsigned int)ndeferred;
  10711. ndeferred++;
  10712. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  10713. deferred[ndeferred].node = n;
  10714. deferred[ndeferred].parent_top = l->parent_top;
  10715. deferred[ndeferred].flow_y =
  10716. cs.pos == 1 ? l->cb_top : l->y;
  10717. deferred[ndeferred].flow_left =
  10718. cs.pos == 1 ? l->cb_left : l->left;
  10719. deferred[ndeferred].flow_right =
  10720. cs.pos == 1 ? l->cb_right : l->right;
  10721. deferred[ndeferred].link = lk;
  10722. deferred[ndeferred].z_index = cs.z_index;
  10723. deferred[ndeferred].z_set = cs.z_set;
  10724. deferred[ndeferred].order = (unsigned int)ndeferred;
  10725. ndeferred++;
  10726. } else if (l->draw && cs.pos == 1) {
  10727. /* Deferred list full: paint in place, but still
  10728. * against the containing block, not the flow. */
  10729. int fy = l->y, fl = l->left, fr = l->right;
  10730. l->y = l->cb_top;
  10731. l->left = l->cb_left;
  10732. l->right = l->cb_right;
  10733. layout_block(l, n, &cs, depth + 1, lk);
  10734. l->y = fy;
  10735. l->left = fl;
  10736. l->right = fr;
  10737. } else {
  10738. layout_block(l, n, &cs, depth + 1, lk);
  10739. }
  10740. if (cs.pos == 1 && block_h[n] &&
  10741. doc.nodes[n].class_off) {
  10742. const char *cl = doc.attrs +
  10743. doc.nodes[n].class_off;
  10744. if ((contains_ci(cl, "poster-wrapper") ||
  10745. contains_ci(cl, "ts-picture")) &&
  10746. !has_skeleton_sibling(n))
  10747. l->y += block_h[n];
  10748. }
  10749. n = nd->next;
  10750. continue;
  10751. }
  10752. if (nd->tag == BR_TAG_BR) {
  10753. flush_line(l);
  10754. n = nd->next;
  10755. continue;
  10756. }
  10757. if (nd->tag == BR_TAG_HR) {
  10758. flush_line(l);
  10759. if (l->draw)
  10760. ngui_fill_rect(l->ui,
  10761. (struct ngui_rect){l->left, l->y + 2,
  10762. l->right - l->left, 1}, BR_GRAY);
  10763. l->y += 8;
  10764. n = nd->next;
  10765. continue;
  10766. }
  10767. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  10768. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  10769. !button_has_elements(n)) {
  10770. if (!(nd->tag == BR_TAG_INPUT &&
  10771. s_eq(br_type(&doc, n), "hidden"))) {
  10772. form_fill_line = pst->display ==
  10773. BR_DISPLAY_FLEX &&
  10774. pst->flex_col;
  10775. add_form_run(l, n, &cs, lk);
  10776. form_fill_line = 0;
  10777. }
  10778. n = nd->next;
  10779. continue;
  10780. }
  10781. if (nd->tag == BR_TAG_IMG) {
  10782. add_image_run(l, n, &cs, lk);
  10783. n = nd->next;
  10784. continue;
  10785. }
  10786. if (nd->tag == BR_TAG_SVG &&
  10787. (cs.display == BR_DISPLAY_INLINE ||
  10788. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  10789. !cs.float_left) {
  10790. add_svg_run(l, n, &cs, lk);
  10791. n = nd->next;
  10792. continue;
  10793. }
  10794. if (nd->tag == BR_TAG_VIDEO) {
  10795. layout_block(l, n, &cs, depth + 1, lk);
  10796. n = nd->next;
  10797. continue;
  10798. }
  10799. if (cs.float_left) {
  10800. n = layout_float_group(l, n, pst, depth, lk);
  10801. continue;
  10802. }
  10803. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  10804. inline_block_flows(n, &cs, 0)) {
  10805. layout_children(l, n, &cs, depth + 1, lk);
  10806. n = nd->next;
  10807. continue;
  10808. }
  10809. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  10810. n = layout_inline_blocks(l, n, pst, depth, link);
  10811. continue;
  10812. }
  10813. /* A flex container is block-level like any block box even when
  10814. * the element is an inline tag such as <a> (a link card with
  10815. * display:flex is common on news sites). Without the block box
  10816. * its children were laid out in the parent flow with a 0x0 box
  10817. * of their own. */
  10818. /* inline-flex around inline content only ("| mehr" link
  10819. * tails, icon+label pills) stays in the text line. */
  10820. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  10821. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  10822. !flex_wants_row(n, &cs)) {
  10823. layout_children(l, n, &cs, depth + 1, lk);
  10824. } else if (cs.display == BR_DISPLAY_BLOCK ||
  10825. cs.display == BR_DISPLAY_FLEX ||
  10826. br_tag_is_block(nd->tag))
  10827. layout_block(l, n, &cs, depth + 1, lk);
  10828. else {
  10829. layout_children(l, n, &cs, depth + 1, lk);
  10830. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  10831. l->space_pending = 1;
  10832. }
  10833. n = nd->next;
  10834. }
  10835. emit_pseudo(l, parent, pst, 2, link);
  10836. }
  10837. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  10838. * runs and a recursive page can otherwise overflow the stack. */
  10839. static struct lay layout_state;
  10840. static int measure_page(int left, int right)
  10841. {
  10842. struct lay *l = &layout_state;
  10843. struct br_style base = base_style();
  10844. unsigned int i;
  10845. for (i = 0; i < BR_MAX_NODES; i++) {
  10846. block_h[i] = 0;
  10847. img_top[i] = 0;
  10848. block_top[i] = 0;
  10849. img_h[i] = 0;
  10850. layout_boxes[i].valid = 0;
  10851. }
  10852. memset(li_marker, 0, sizeof(li_marker));
  10853. l->draw = 0;
  10854. l->ui = &ui;
  10855. l->left = left;
  10856. l->right = right;
  10857. l->y = 0;
  10858. l->line_x = left;
  10859. l->run_x = left;
  10860. l->line_left = left;
  10861. l->line_right = right;
  10862. l->line_y = 0;
  10863. l->line_h = 0;
  10864. l->align = BR_ALIGN_LEFT;
  10865. l->cb_h = layout_view_h;
  10866. l->float_active = 0;
  10867. l->parent_top = 0;
  10868. l->cb_left = left;
  10869. l->cb_right = right;
  10870. l->cb_top = 0;
  10871. l->depth = 0;
  10872. l->nruns = 0;
  10873. l->space_pending = 0;
  10874. base = root_style();
  10875. layout_children(l, doc.root, &base, 0, 0);
  10876. return l->y + 8;
  10877. }
  10878. static int deferred_cmp(const struct br_deferred *a,
  10879. const struct br_deferred *b)
  10880. {
  10881. int az = a->z_set ? a->z_index : 0;
  10882. int bz = b->z_set ? b->z_index : 0;
  10883. if (az != bz)
  10884. return az < bz ? -1 : 1;
  10885. if (a->order != b->order)
  10886. return a->order < b->order ? -1 : 1;
  10887. return 0;
  10888. }
  10889. static void sort_deferred(void)
  10890. {
  10891. int i;
  10892. for (i = 1; i < ndeferred; i++) {
  10893. struct br_deferred key = deferred[i];
  10894. int j = i;
  10895. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  10896. deferred[j] = deferred[j - 1];
  10897. j--;
  10898. }
  10899. deferred[j] = key;
  10900. }
  10901. }
  10902. static void render_page(int left, int right, int y0)
  10903. {
  10904. struct lay *l = &layout_state;
  10905. struct br_style base = base_style();
  10906. l->draw = 1;
  10907. l->ui = &ui;
  10908. l->left = left;
  10909. l->right = right;
  10910. l->y = y0;
  10911. l->line_x = left;
  10912. l->run_x = left;
  10913. l->line_left = left;
  10914. l->line_right = right;
  10915. l->line_y = y0;
  10916. l->line_h = 0;
  10917. l->align = BR_ALIGN_LEFT;
  10918. l->cb_h = layout_view_h;
  10919. l->float_active = 0;
  10920. l->parent_top = 0;
  10921. l->cb_left = left;
  10922. l->cb_right = right;
  10923. l->cb_top = y0;
  10924. l->depth = 0;
  10925. l->nruns = 0;
  10926. l->space_pending = 0;
  10927. nhits = 0;
  10928. ndeferred = 0;
  10929. base = root_style();
  10930. layout_children(l, doc.root, &base, 0, 0);
  10931. sort_deferred();
  10932. {
  10933. int i;
  10934. for (i = 0; i < ndeferred; i++) {
  10935. struct br_style st;
  10936. br_style_for(&doc, deferred[i].node, &base, &st);
  10937. if (st.display == BR_DISPLAY_NONE)
  10938. continue;
  10939. l->draw = 1;
  10940. l->left = deferred[i].flow_left;
  10941. l->right = deferred[i].flow_right;
  10942. l->y = deferred[i].flow_y;
  10943. l->parent_top = deferred[i].parent_top;
  10944. l->line_x = l->left;
  10945. l->run_x = l->left;
  10946. l->line_y = l->y;
  10947. l->line_h = 0;
  10948. l->nruns = 0;
  10949. l->space_pending = 0;
  10950. l->align = st.align;
  10951. if (st.pos == 2 && block_h[deferred[i].node]) {
  10952. struct ngui_rect clip;
  10953. int ch = block_h[deferred[i].node] + 24;
  10954. int pr = page_rect.x + page_rect.w - 12;
  10955. int x0 = page_rect.x, x1 = pr;
  10956. /* The background pre-fill spans the box's own
  10957. * columns, not the whole page: Docusaurus parks
  10958. * a white "Skip to main content" link at
  10959. * `left: 100%` with a z-index above the navbar,
  10960. * and a full-width fill painted over the bar. */
  10961. if (st.left_set)
  10962. x0 = page_rect.x + st.left;
  10963. if (st.width_kind == 1) {
  10964. if (st.right_set && !st.left_set)
  10965. x0 = pr - st.right - st.width;
  10966. x1 = x0 + st.width;
  10967. } else if (st.right_set) {
  10968. x1 = pr - st.right;
  10969. }
  10970. if (x0 >= pr || x1 <= page_rect.x)
  10971. continue; /* entirely off-screen */
  10972. if (x0 < page_rect.x)
  10973. x0 = page_rect.x;
  10974. if (x1 > pr)
  10975. x1 = pr;
  10976. clip.x = x0;
  10977. clip.y = page_rect.y;
  10978. clip.w = x1 - x0;
  10979. if (ch > page_rect.h)
  10980. ch = page_rect.h;
  10981. clip.h = ch;
  10982. ngui_push_clip(&ui, clip);
  10983. if (st.has_bg)
  10984. ngui_fill_rect(&ui, clip, st.bg);
  10985. layout_block(l, deferred[i].node, &st, 0,
  10986. deferred[i].link);
  10987. ngui_pop_clip(&ui);
  10988. } else {
  10989. layout_block(l, deferred[i].node, &st, 0,
  10990. deferred[i].link);
  10991. }
  10992. }
  10993. }
  10994. }
  10995. /* ---- UI ---- */
  10996. static int find_hit(int x, int y)
  10997. {
  10998. int i;
  10999. for (i = nhits - 1; i >= 0; i--) {
  11000. struct hit *h = &hits[i];
  11001. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  11002. y < h->y + h->h)
  11003. return (int)h->node;
  11004. }
  11005. return 0;
  11006. }
  11007. /* ---- URL-bar autocomplete ----
  11008. *
  11009. * While the address bar has the focus a dropdown lists up to SUG_MAX
  11010. * history entries. An empty bar (a fresh focus, Ctrl+L) shows the most
  11011. * visited/recent sites; typing ranks prefix matches of the URL (with or
  11012. * without the scheme and "www.") above substring matches of the URL, then
  11013. * of the title, and adds visit count and recency. Typing at the end of the
  11014. * text also completes inline to the next '/' of the best prefix match
  11015. * ("clo" -> "cloudron.io/"), with the added part selected so the next
  11016. * keystroke replaces it; Enter on that text opens the history URL it came
  11017. * from (scheme included). Up/Down preview a row in the bar, Delete on a
  11018. * highlighted row forgets it, Esc closes the list (a second Esc leaves the
  11019. * bar), and a click on a row opens it. */
  11020. #define SUG_MAX 6
  11021. #define SUG_ROW_H 36
  11022. static int sug_idx[SUG_MAX];
  11023. static int sug_n, sug_sel = -1, sug_open;
  11024. static char sug_typed[NGUI_INPUT_MAX]; /* what the user typed */
  11025. static char sug_restore[NGUI_INPUT_MAX]; /* bar text before a preview */
  11026. static char ac_text[NGUI_INPUT_MAX]; /* bar text of the inline completion */
  11027. static char ac_url[HIST_URL_MAX]; /* the history URL it stands for */
  11028. static struct ngui_rect url_rect, sug_rect;
  11029. static int url_had_focus;
  11030. static char lc(char c)
  11031. {
  11032. return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
  11033. }
  11034. static int prefix_ci(const char *s, const char *p) /* p is lower case */
  11035. {
  11036. for (; *p; s++, p++)
  11037. if (lc(*s) != *p)
  11038. return 0;
  11039. return 1;
  11040. }
  11041. static unsigned int url_scheme_len(const char *url)
  11042. {
  11043. if (starts_with(url, "https://"))
  11044. return 8;
  11045. if (starts_with(url, "http://"))
  11046. return 7;
  11047. return 0;
  11048. }
  11049. /* Offset in `url` where the lower-case text `t` matches as a prefix: the
  11050. * whole URL, the URL without its scheme, or without scheme and "www.". */
  11051. static int hist_prefix_at(const char *url, const char *t)
  11052. {
  11053. unsigned int s = url_scheme_len(url);
  11054. if (prefix_ci(url, t))
  11055. return 0;
  11056. if (s && prefix_ci(url + s, t))
  11057. return (int)s;
  11058. if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
  11059. return (int)s + 4;
  11060. return -1;
  11061. }
  11062. static int hist_score(const struct hist_ent *e, const char *t,
  11063. unsigned int next)
  11064. {
  11065. unsigned int age = next - e->stamp;
  11066. int sc, at;
  11067. if (!t[0]) {
  11068. sc = 0;
  11069. } else if ((at = hist_prefix_at(e->url, t)) >= 0) {
  11070. /* Shorter rests first: "cloudron.io/" before its subpages. */
  11071. int rest = (int)s_len(e->url + at);
  11072. sc = 4000 - (rest > 400 ? 400 : rest);
  11073. } else if (contains_ci(e->url, t)) {
  11074. sc = 1000;
  11075. } else if (contains_ci(e->title, t)) {
  11076. sc = 600;
  11077. } else {
  11078. return -1;
  11079. }
  11080. sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
  11081. sc += age >= 500 ? 0 : (int)(500 - age);
  11082. return sc;
  11083. }
  11084. static void sug_lower(char *t, unsigned int cap)
  11085. {
  11086. unsigned int k;
  11087. for (k = 0; sug_typed[k] && k + 1 < cap; k++)
  11088. t[k] = lc(sug_typed[k]);
  11089. t[k] = '\0';
  11090. }
  11091. static void sug_refresh(void)
  11092. {
  11093. char t[NGUI_INPUT_MAX];
  11094. int sc[SUG_MAX], i, j;
  11095. unsigned int next = hist_next_stamp();
  11096. sug_lower(t, sizeof(t));
  11097. sug_n = 0;
  11098. for (i = 0; i < hist_n; i++) {
  11099. int s = hist_score(&hist_tab[i], t, next);
  11100. if (s < 0)
  11101. continue;
  11102. j = sug_n;
  11103. if (j == SUG_MAX) {
  11104. if (sc[SUG_MAX - 1] >= s)
  11105. continue;
  11106. j = SUG_MAX - 1;
  11107. }
  11108. while (j > 0 && sc[j - 1] < s) {
  11109. sc[j] = sc[j - 1];
  11110. sug_idx[j] = sug_idx[j - 1];
  11111. j--;
  11112. }
  11113. sc[j] = s;
  11114. sug_idx[j] = i;
  11115. if (sug_n < SUG_MAX)
  11116. sug_n++;
  11117. }
  11118. if (sug_sel >= sug_n)
  11119. sug_sel = -1;
  11120. }
  11121. /* Complete the typed text inline to the next '/' of the best prefix match. */
  11122. static void sug_inline(void)
  11123. {
  11124. char t[NGUI_INPUT_MAX];
  11125. const char *url, *rest;
  11126. unsigned int L, start, end, hs, tn, n = 0;
  11127. unsigned int next = hist_next_stamp();
  11128. int i, best = -1, best_sc = -1, at = 0;
  11129. sug_lower(t, sizeof(t));
  11130. L = s_len(t);
  11131. if (!L)
  11132. return;
  11133. for (i = 0; i < hist_n; i++) {
  11134. int a = hist_prefix_at(hist_tab[i].url, t), s;
  11135. if (a < 0)
  11136. continue;
  11137. s = hist_score(&hist_tab[i], t, next);
  11138. if (s > best_sc) {
  11139. best_sc = s;
  11140. best = i;
  11141. at = a;
  11142. }
  11143. }
  11144. if (best < 0)
  11145. return;
  11146. url = hist_tab[best].url;
  11147. rest = url + at;
  11148. /* Typing the scheme ("htt") completes past "https://", not to it. */
  11149. hs = at == 0 ? url_scheme_len(url) : 0;
  11150. start = L > hs ? L : hs;
  11151. end = start;
  11152. while (rest[end] && rest[end] != '/')
  11153. end++;
  11154. if (rest[end] == '/')
  11155. end++;
  11156. tn = s_len(sug_typed);
  11157. if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
  11158. return;
  11159. s_append(ac_text, &n, sug_typed, sizeof(ac_text));
  11160. for (; L < end && n + 1 < sizeof(ac_text); L++)
  11161. ac_text[n++] = rest[L];
  11162. ac_text[n] = '\0';
  11163. s_copy(ac_url, url, (unsigned int)at + end + 1);
  11164. ngui_input_set(&url_in, ac_text);
  11165. url_in.anchor = tn; /* select the completed part */
  11166. }
  11167. static void sug_close(void)
  11168. {
  11169. sug_open = 0;
  11170. sug_sel = -1;
  11171. ac_text[0] = '\0';
  11172. }
  11173. static int sug_visible(void)
  11174. {
  11175. return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
  11176. }
  11177. /* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
  11178. * start page) lists the top sites until something is typed. */
  11179. static int sug_focus_check(void)
  11180. {
  11181. int focused = ngui_focus(&ui) == ID_URL;
  11182. if (focused && !url_had_focus) {
  11183. sug_typed[0] = '\0';
  11184. sug_close();
  11185. sug_open = 1;
  11186. sug_refresh();
  11187. }
  11188. url_had_focus = focused;
  11189. return focused;
  11190. }
  11191. static void url_submit(unsigned int *action)
  11192. {
  11193. if (ac_text[0] && s_eq(url_in.text, ac_text))
  11194. s_copy(click_url, ac_url, sizeof(click_url));
  11195. *action |= ACT_NAV;
  11196. sug_close();
  11197. }
  11198. /* The bar text changed through typing or editing. */
  11199. static void sug_changed(void)
  11200. {
  11201. unsigned int pl = s_len(sug_typed);
  11202. int grew = url_in.len > pl && url_in.cursor == url_in.len &&
  11203. !memcmp(url_in.text, sug_typed, pl);
  11204. s_copy(sug_typed, url_in.text, sizeof(sug_typed));
  11205. ac_text[0] = '\0';
  11206. sug_sel = -1;
  11207. sug_open = 1;
  11208. sug_refresh();
  11209. if (grew)
  11210. sug_inline();
  11211. }
  11212. /* Keys for the list, taken off the queue before the text field sees them.
  11213. * Only a leading run is handled; the rest goes to the field. */
  11214. static void sug_keys(void)
  11215. {
  11216. int k;
  11217. while ((k = ngui_key_peek(&ui)) != 0) {
  11218. if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
  11219. ngui_key(&ui);
  11220. if (!sug_open) {
  11221. sug_open = 1;
  11222. continue;
  11223. }
  11224. if (sug_sel < 0)
  11225. s_copy(sug_restore, url_in.text,
  11226. sizeof(sug_restore));
  11227. if (k == NGUI_KEY_DOWN)
  11228. sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
  11229. else
  11230. sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
  11231. ngui_input_set(&url_in, sug_sel >= 0 ?
  11232. hist_tab[sug_idx[sug_sel]].url :
  11233. sug_restore);
  11234. } else if (k == NGUI_KEY_ESC && sug_visible()) {
  11235. ngui_key(&ui);
  11236. if (sug_sel >= 0)
  11237. ngui_input_set(&url_in, sug_restore);
  11238. else if (ac_text[0] && s_eq(url_in.text, ac_text))
  11239. ngui_input_set(&url_in, sug_typed);
  11240. sug_close();
  11241. } else if (k == NGUI_KEY_DELETE && sug_visible() &&
  11242. sug_sel >= 0) {
  11243. ngui_key(&ui);
  11244. hist_forget(sug_idx[sug_sel]);
  11245. ngui_input_set(&url_in, sug_restore);
  11246. sug_sel = -1;
  11247. sug_refresh();
  11248. } else {
  11249. break;
  11250. }
  11251. }
  11252. }
  11253. /* A press on a row of last frame's list opens it; any press on the list is
  11254. * swallowed so the page underneath does not see it. */
  11255. static void sug_click(unsigned int *action)
  11256. {
  11257. int row;
  11258. if (!(ui.pressed & 1) || !sug_rect.w ||
  11259. !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
  11260. return;
  11261. row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
  11262. if (row >= 0 && row < sug_n) {
  11263. s_copy(click_url, hist_tab[sug_idx[row]].url,
  11264. sizeof(click_url));
  11265. *action |= ACT_NAV;
  11266. sug_close();
  11267. }
  11268. ui.pressed = 0;
  11269. }
  11270. static void draw_suggest(struct ngui_rect page)
  11271. {
  11272. struct ngui_rect r;
  11273. int i, rows = sug_n, hover = -1;
  11274. r.x = url_rect.x;
  11275. r.y = url_rect.y + url_rect.h + 1;
  11276. r.w = url_rect.w < 320 ? 320 : url_rect.w;
  11277. if (r.x + r.w > ui.w - 2)
  11278. r.w = ui.w - 2 - r.x;
  11279. while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
  11280. rows--;
  11281. if (rows <= 0 || r.w < 60) {
  11282. sug_rect.w = 0;
  11283. return;
  11284. }
  11285. r.h = rows * SUG_ROW_H + 2;
  11286. sug_rect = r;
  11287. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  11288. hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
  11289. ngui_set_cursor(&ui, CURSOR_POINTER);
  11290. }
  11291. ngui_fill_rect(&ui, r, ui.theme.border);
  11292. for (i = 0; i < rows; i++) {
  11293. const struct hist_ent *e = &hist_tab[sug_idx[i]];
  11294. struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
  11295. r.w - 2, SUG_ROW_H};
  11296. struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
  11297. unsigned short bg = i == sug_sel ? ui.theme.selection :
  11298. i == hover ? ui.theme.panel_alt :
  11299. ui.theme.panel;
  11300. ngui_fill_rect(&ui, rr, bg);
  11301. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
  11302. e->title[0] ? e->title : e->url,
  11303. ui.theme.text);
  11304. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
  11305. i == sug_sel ? ui.theme.text :
  11306. ui.theme.text_dim);
  11307. }
  11308. }
  11309. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  11310. {
  11311. int x = r.x + 4, y = r.y + 4, h = 22;
  11312. int compact = r.w < 560;
  11313. int go_w = r.w < 420 ? 32 : 42;
  11314. int in_x, in_w, res;
  11315. ngui_fill_rect(&ui, r, ui.theme.panel);
  11316. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  11317. ui.theme.border);
  11318. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  11319. NGUI_ICON_CHEVRON_LEFT))
  11320. *action |= ACT_BACK;
  11321. x += 32;
  11322. if (!compact) {
  11323. if (ngui_icon_button(&ui, ID_FORWARD,
  11324. (struct ngui_rect){x, y, 28, h},
  11325. NGUI_ICON_CHEVRON_RIGHT))
  11326. *action |= ACT_FORWARD;
  11327. x += 32;
  11328. }
  11329. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  11330. NGUI_ICON_REFRESH))
  11331. *action |= ACT_RELOAD;
  11332. x += 32;
  11333. if (!compact) {
  11334. if (ngui_icon_button(&ui, ID_HOME,
  11335. (struct ngui_rect){x, y, 28, h},
  11336. NGUI_ICON_HOME))
  11337. *action |= ACT_HOME;
  11338. x += 32;
  11339. }
  11340. in_x = x + 2;
  11341. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  11342. if (in_w < 60)
  11343. in_w = 60;
  11344. url_rect = (struct ngui_rect){in_x, y, in_w, h};
  11345. if (sug_focus_check())
  11346. sug_keys();
  11347. res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
  11348. sug_focus_check(); /* a click into the bar focuses it here */
  11349. if (res & NGUI_INPUT_CHANGED)
  11350. sug_changed();
  11351. if (res & NGUI_INPUT_SUBMIT)
  11352. url_submit(action);
  11353. if (res & NGUI_INPUT_CANCEL)
  11354. ngui_set_focus(&ui, 0);
  11355. if (ngui_button(&ui, ID_GO,
  11356. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  11357. "Go"))
  11358. url_submit(action);
  11359. if (!sug_focus_check())
  11360. sug_close();
  11361. }
  11362. static int page_hover_node(void)
  11363. {
  11364. if (!ui.inside)
  11365. return 0;
  11366. if (ui.mouse_x < page_rect.x ||
  11367. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  11368. ui.mouse_y < page_rect.y ||
  11369. ui.mouse_y >= page_rect.y + page_rect.h)
  11370. return 0;
  11371. return find_hit(ui.mouse_x, ui.mouse_y);
  11372. }
  11373. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  11374. {
  11375. int x, y, w = page.w, h = page.h;
  11376. if (!src || w <= 0 || h <= 0)
  11377. return;
  11378. for (y = 0; y < h; y++) {
  11379. unsigned short *s = src + (page.y + y) * sw + page.x;
  11380. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  11381. for (x = 0; x + 1 < w; x += 2) {
  11382. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  11383. }
  11384. if (x < w)
  11385. d[x] = s[x];
  11386. }
  11387. }
  11388. static void draw_page(struct ngui_rect page)
  11389. {
  11390. int left, right, ch;
  11391. int old_panel, old_dim;
  11392. unsigned short *saved_px;
  11393. unsigned short page_bg = ui.theme.bg;
  11394. int saved_w, saved_h, use_buf;
  11395. unsigned int t0 = u_ticks_ms();
  11396. page_rect = page;
  11397. {
  11398. unsigned int root = doc.nnode > 1 ?
  11399. br_find_tag(&doc, BR_TAG_HTML) : 0;
  11400. unsigned int body = doc.nnode > 1 ?
  11401. br_find_tag(&doc, BR_TAG_BODY) : 0;
  11402. struct br_style bs;
  11403. int bg_found = 0;
  11404. if (root) {
  11405. style_for_node(root - 1, &bs);
  11406. if (bs.has_bg) {
  11407. page_bg = bs.bg;
  11408. bg_found = 1;
  11409. }
  11410. }
  11411. if (body) {
  11412. style_for_node(body - 1, &bs);
  11413. if (bs.has_bg) {
  11414. page_bg = bs.bg;
  11415. bg_found = 1;
  11416. }
  11417. }
  11418. /* No canvas colour, but the author made the text dark
  11419. * (Infima's light theme: `--ifm-background-color:
  11420. * transparent` on html, #1c1e21 text): the page expects the
  11421. * white canvas of a normal browser, and dark text on the
  11422. * dark default canvas is unreadable. */
  11423. if (!bg_found && (body || root) && bs.color != ui.theme.text) {
  11424. unsigned int c = bs.color;
  11425. unsigned int lum = ((c >> 11) & 31) * 8 * 299 +
  11426. ((c >> 5) & 63) * 4 * 587 +
  11427. (c & 31) * 8 * 114;
  11428. if (lum < 100 * 1000)
  11429. page_bg = 0xFFFF;
  11430. }
  11431. }
  11432. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  11433. page_cache_valid && layout_valid &&
  11434. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  11435. !(ui.scroll_y &&
  11436. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  11437. page_scroll.offset == page_cache_scroll &&
  11438. page_cache_nnode == doc.nnode &&
  11439. page_cache_x == page.x && page_cache_y == page.y &&
  11440. page_cache_w == page.w && page_cache_h == page.h) {
  11441. blit_page(page, page_backbuf, pagebuf_w);
  11442. if (img_stat_n)
  11443. img_stat_paint += u_ticks_ms() - t0;
  11444. return;
  11445. }
  11446. ngui_fill_rect(&ui, page, page_bg);
  11447. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  11448. const char *s = page_loading ? "Loading..." : "No page";
  11449. int w = (int)ngui_text_width_ui(&ui, s);
  11450. ngui_text(&ui, page.x + (page.w - w) / 2,
  11451. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  11452. page_scroll.content_h = 0;
  11453. page_scroll.view_h = page.h;
  11454. page_cache_valid = 0;
  11455. return;
  11456. }
  11457. if (page.w < 40 || page.h < 40) {
  11458. page_cache_valid = 0;
  11459. return;
  11460. }
  11461. saved_px = ui.px;
  11462. saved_w = ui.w;
  11463. saved_h = ui.h;
  11464. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  11465. if (use_buf) {
  11466. ui.px = page_backbuf;
  11467. ui.w = pagebuf_w;
  11468. ui.h = pagebuf_h;
  11469. ngui_fill_rect(&ui, page, page_bg);
  11470. }
  11471. left = page.x + 8;
  11472. right = page.x + page.w - 16;
  11473. if (!layout_valid || left != layout_left || right != layout_right ||
  11474. layout_nnode != doc.nnode) {
  11475. unsigned int tm = u_ticks_ms();
  11476. layout_view_h = page.h - 8;
  11477. layout_content_h = measure_page(left, right);
  11478. if (img_stat_n)
  11479. img_stat_reflow += u_ticks_ms() - tm;
  11480. layout_valid = 1;
  11481. layout_left = left;
  11482. layout_right = right;
  11483. layout_nnode = doc.nnode;
  11484. /* Scripts that measured before any layout (offsetWidth on
  11485. * mount) get a resize event once real boxes exist, and again
  11486. * whenever the page width changes. */
  11487. if (js_browser_active() && right - left != resize_sent_w)
  11488. resize_pending = 1;
  11489. }
  11490. ch = layout_content_h;
  11491. page_scroll.content_h = ch;
  11492. page_scroll.view_h = page.h;
  11493. t0 = u_ticks_ms();
  11494. ngui_scroll_begin(&ui, page, &page_scroll);
  11495. ngui_scroll_wheel(&ui, page, &page_scroll);
  11496. render_page(left, right, page.y + 4 - page_scroll.offset);
  11497. old_panel = ui.theme.panel_alt;
  11498. old_dim = ui.theme.text_dim;
  11499. ui.theme.panel_alt = 0xC618;
  11500. ui.theme.text_dim = 0x8410;
  11501. ngui_scroll_end(&ui, page, &page_scroll);
  11502. ui.theme.panel_alt = old_panel;
  11503. ui.theme.text_dim = old_dim;
  11504. if (use_buf) {
  11505. ui.px = saved_px;
  11506. ui.w = saved_w;
  11507. ui.h = saved_h;
  11508. blit_page(page, page_backbuf, pagebuf_w);
  11509. page_cache_valid = 1;
  11510. page_cache_scroll = page_scroll.offset;
  11511. page_cache_nnode = doc.nnode;
  11512. page_cache_x = page.x;
  11513. page_cache_y = page.y;
  11514. page_cache_w = page.w;
  11515. page_cache_h = page.h;
  11516. } else {
  11517. page_cache_valid = 0;
  11518. }
  11519. if (img_stat_n)
  11520. img_stat_paint += u_ticks_ms() - t0;
  11521. }
  11522. static void draw_status(struct ngui_rect r)
  11523. {
  11524. static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
  11525. unsigned int n = 0;
  11526. int hover = page_hover_node();
  11527. unsigned short color;
  11528. const char *kind;
  11529. ngui_fill_rect(&ui, r, ui.theme.panel);
  11530. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  11531. ui.theme.border);
  11532. /* A form control under the pointer is not a link. */
  11533. if (hover && !br_href(&doc, (unsigned int)hover) &&
  11534. form_is_control((unsigned int)hover))
  11535. hover = 0;
  11536. if (hover) {
  11537. const char *href = br_href(&doc, (unsigned int)hover);
  11538. char url[BR_URL_MAX];
  11539. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  11540. s_append(msg, &n, "Link: ", sizeof(msg));
  11541. s_append(msg, &n, url, sizeof(msg));
  11542. } else {
  11543. s_copy(msg, "Link", sizeof(msg));
  11544. }
  11545. color = ui.theme.accent;
  11546. } else if (status_text[0]) {
  11547. s_copy(msg, status_text, sizeof(msg));
  11548. color = status_error ? ui.theme.error : ui.theme.text;
  11549. } else if (page_title[0]) {
  11550. s_copy(msg, page_title, sizeof(msg));
  11551. color = ui.theme.text;
  11552. } else {
  11553. s_copy(msg, "Ready", sizeof(msg));
  11554. color = ui.theme.text_dim;
  11555. }
  11556. kind = s_eq(page_url, "about:home") ? "HOME" :
  11557. page_is_local ? "FILE" :
  11558. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  11559. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  11560. {
  11561. int kw = (int)ngui_text_width_ui(&ui, kind);
  11562. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  11563. ui.theme.text_dim);
  11564. }
  11565. }
  11566. /* Mouse cursor over the page: the hovered node's CSS `cursor` (inherited);
  11567. * for `auto`, a hand over links, the I-beam over text fields, and the
  11568. * progress arrow anywhere on the page while it is still loading. The
  11569. * toolbar's URL field sets its own I-beam through ngui. */
  11570. static void page_cursor(void)
  11571. {
  11572. int hover = page_hover_node();
  11573. struct br_style st;
  11574. if (!hover) {
  11575. if (page_loading && ui.inside &&
  11576. ngui_rect_contains(&page_rect, ui.mouse_x, ui.mouse_y))
  11577. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  11578. return;
  11579. }
  11580. style_for_node((unsigned int)hover, &st);
  11581. if (st.cursor != BR_CURSOR_AUTO) {
  11582. ngui_set_cursor(&ui, (int)st.cursor - 1);
  11583. return;
  11584. }
  11585. if (br_href(&doc, (unsigned int)hover)) {
  11586. ngui_set_cursor(&ui, CURSOR_POINTER);
  11587. return;
  11588. }
  11589. if (form_is_control((unsigned int)hover)) {
  11590. int k = form_kind_of((unsigned int)hover);
  11591. if (form_disabled((unsigned int)hover))
  11592. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  11593. else if (k == FORM_TEXT || k == FORM_PASSWORD ||
  11594. k == FORM_TEXTAREA)
  11595. ngui_set_cursor(&ui, CURSOR_TEXT);
  11596. return;
  11597. }
  11598. if (page_loading)
  11599. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  11600. }
  11601. static void draw(unsigned int *action)
  11602. {
  11603. struct ngui_rect r = {0, 0, ui.w, ui.h};
  11604. struct ngui_rect toolbar, status, page;
  11605. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  11606. status = ngui_cut_bottom(&r, BR_STATUS_H);
  11607. page = r;
  11608. if (sug_visible())
  11609. sug_click(action);
  11610. draw_toolbar(toolbar, action);
  11611. draw_page(page);
  11612. draw_status(status);
  11613. page_cursor();
  11614. if (sug_visible())
  11615. draw_suggest(page);
  11616. else
  11617. sug_rect.w = 0;
  11618. }
  11619. static void redraw_now(void)
  11620. {
  11621. unsigned int action = 0;
  11622. ngui_begin(&ui);
  11623. draw(&action);
  11624. ngui_end(&ui);
  11625. }
  11626. static void handle_keys(unsigned int *action)
  11627. {
  11628. int k, scrolled = 0;
  11629. if (form_focus >= doc.nnode)
  11630. form_focus = 0;
  11631. if (form_focus && !ngui_focus(&ui)) {
  11632. while ((k = ngui_key(&ui)) != 0)
  11633. form_key(k);
  11634. return;
  11635. }
  11636. /* Batch queued page keys: a slow full-page render must not make a
  11637. * held Page Down advance only once every few frames. */
  11638. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  11639. scrolled++;
  11640. if (scrolled)
  11641. ngui_invalidate(&ui);
  11642. if (ngui_focus(&ui))
  11643. return;
  11644. while ((k = ngui_key(&ui)) != 0) {
  11645. switch (k) {
  11646. case NGUI_KEY_ESC:
  11647. *action |= ACT_CLOSE;
  11648. break;
  11649. case NGUI_KEY_TAB:
  11650. case 0x0C: /* Ctrl+L */
  11651. ngui_set_focus(&ui, ID_URL);
  11652. break;
  11653. case 0x12: /* Ctrl+R */
  11654. *action |= ACT_RELOAD;
  11655. break;
  11656. case NGUI_KEY_BACKSPACE:
  11657. *action |= ACT_BACK;
  11658. break;
  11659. case NGUI_KEY_UP:
  11660. ngui_scroll_to(&page_scroll,
  11661. page_scroll.offset - 24);
  11662. ngui_invalidate(&ui);
  11663. break;
  11664. case NGUI_KEY_DOWN:
  11665. ngui_scroll_to(&page_scroll,
  11666. page_scroll.offset + 24);
  11667. ngui_invalidate(&ui);
  11668. break;
  11669. case NGUI_KEY_HOME:
  11670. ngui_scroll_to(&page_scroll, 0);
  11671. ngui_invalidate(&ui);
  11672. break;
  11673. case NGUI_KEY_END:
  11674. ngui_scroll_to(&page_scroll,
  11675. page_scroll.content_h -
  11676. page_scroll.view_h);
  11677. ngui_invalidate(&ui);
  11678. break;
  11679. default:
  11680. break;
  11681. }
  11682. }
  11683. }
  11684. static unsigned int form_ancestor(unsigned int node)
  11685. {
  11686. unsigned int p = node;
  11687. while (p && p < doc.nnode) {
  11688. if (doc.nodes[p].tag == BR_TAG_FORM &&
  11689. doc.nodes[p].type == BR_NODE_ELEM)
  11690. return p;
  11691. p = doc.nodes[p].parent;
  11692. }
  11693. return 0;
  11694. }
  11695. static int form_descendant(unsigned int node, unsigned int form)
  11696. {
  11697. unsigned int p = node;
  11698. while (p && p < doc.nnode) {
  11699. if (p == form)
  11700. return 1;
  11701. p = doc.nodes[p].parent;
  11702. }
  11703. return 0;
  11704. }
  11705. static void form_reset_form(unsigned int form)
  11706. {
  11707. unsigned int i;
  11708. for (i = 0; i < FORM_MAX; i++)
  11709. if (form_states[i].used &&
  11710. form_descendant(form_states[i].node, form))
  11711. form_states[i].used = 0;
  11712. form_focus = 0;
  11713. }
  11714. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  11715. const char *s)
  11716. {
  11717. static const char hex[] = "0123456789ABCDEF";
  11718. while (s && *s && *n + 1 < cap) {
  11719. unsigned char c = (unsigned char)*s++;
  11720. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  11721. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  11722. c == '.' || c == '~') {
  11723. dst[(*n)++] = (char)c;
  11724. } else if (c == ' ') {
  11725. dst[(*n)++] = '+';
  11726. } else if (*n + 3 < cap) {
  11727. dst[(*n)++] = '%';
  11728. dst[(*n)++] = hex[c >> 4];
  11729. dst[(*n)++] = hex[c & 15];
  11730. }
  11731. }
  11732. dst[*n] = '\0';
  11733. }
  11734. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  11735. const char *name, const char *value, int *first)
  11736. {
  11737. if (!name || !name[0])
  11738. return;
  11739. if (!*first && *n + 1 < cap)
  11740. dst[(*n)++] = '&';
  11741. *first = 0;
  11742. form_url_append(dst, n, cap, name);
  11743. if (*n + 1 < cap)
  11744. dst[(*n)++] = '=';
  11745. form_url_append(dst, n, cap, value ? value : "");
  11746. dst[*n] = '\0';
  11747. }
  11748. static int form_submit_form(unsigned int node, int fire_event)
  11749. {
  11750. unsigned int form = form_ancestor(node);
  11751. char action[BR_URL_MAX], query[2048];
  11752. unsigned int qn = 0, i;
  11753. int first = 1, is_post = 0;
  11754. const char *a, *method;
  11755. if (!form)
  11756. return 0;
  11757. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  11758. return 0;
  11759. method = br_find_attr(&doc, form, "method");
  11760. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  11761. is_post = 1;
  11762. a = br_find_attr(&doc, form, "action");
  11763. if (a && a[0]) {
  11764. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  11765. return 0;
  11766. } else {
  11767. s_copy(action, page_url, sizeof(action));
  11768. }
  11769. query[0] = '\0';
  11770. for (i = 0; i < doc.nnode; i++) {
  11771. struct br_node *nd = &doc.nodes[i];
  11772. struct form_state *fs;
  11773. const char *name;
  11774. const char *value = "";
  11775. if (nd->type != BR_NODE_ELEM || i == form ||
  11776. !form_descendant(i, form))
  11777. continue;
  11778. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  11779. nd->tag != BR_TAG_SELECT)
  11780. continue;
  11781. if (form_disabled(i))
  11782. continue;
  11783. name = br_find_attr(&doc, i, "name");
  11784. if (!name || !name[0])
  11785. continue;
  11786. fs = form_get(i, 1);
  11787. if (!fs)
  11788. continue;
  11789. if (nd->tag == BR_TAG_SELECT) {
  11790. char opt[64];
  11791. if (!form_option_text(i, fs->selected, opt,
  11792. sizeof(opt)))
  11793. s_copy(opt, "", sizeof(opt));
  11794. value = opt;
  11795. {
  11796. unsigned int c, oi = 0;
  11797. for (c = nd->first; c;
  11798. c = doc.nodes[c].next) {
  11799. if (doc.nodes[c].type != BR_NODE_ELEM ||
  11800. doc.nodes[c].tag != BR_TAG_OPTION)
  11801. continue;
  11802. if (oi == fs->selected) {
  11803. const char *v =
  11804. br_value(&doc, c);
  11805. if (v && v[0])
  11806. value = v;
  11807. break;
  11808. }
  11809. oi++;
  11810. }
  11811. }
  11812. } else if (nd->tag == BR_TAG_INPUT) {
  11813. int kind = form_kind_of(i);
  11814. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  11815. if (!fs->checked)
  11816. continue;
  11817. value = br_value(&doc, i);
  11818. if (!value || !value[0])
  11819. value = "on";
  11820. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  11821. kind == FORM_BUTTON) {
  11822. if (i != node)
  11823. continue;
  11824. value = fs->value;
  11825. } else {
  11826. value = fs->value;
  11827. }
  11828. } else {
  11829. value = fs->value;
  11830. }
  11831. form_add_param(query, &qn, sizeof(query), name, value, &first);
  11832. }
  11833. if (is_post) {
  11834. if (action[0] == '/') {
  11835. set_status("POST forms need an HTTP action URL", 1, 4000);
  11836. ngui_invalidate(&ui);
  11837. return 0;
  11838. }
  11839. if (qn >= sizeof(pending_post))
  11840. qn = sizeof(pending_post) - 1;
  11841. if (qn)
  11842. memcpy(pending_post, query, qn);
  11843. pending_post[qn] = '\0';
  11844. pending_post_len = qn;
  11845. pending_post_is = 1;
  11846. } else {
  11847. pending_post_len = 0;
  11848. pending_post_is = 0;
  11849. if (qn) {
  11850. unsigned int an = s_len(action);
  11851. if (an + qn + 2 < sizeof(action)) {
  11852. action[an++] = strchr(action, '?') ? '&' : '?';
  11853. action[an] = '\0';
  11854. s_copy(action + an, query,
  11855. sizeof(action) - an);
  11856. }
  11857. }
  11858. }
  11859. s_copy(pending_url, action, sizeof(pending_url));
  11860. pending_action |= ACT_NAV;
  11861. cancel_fetch = 1;
  11862. ngui_invalidate(&ui);
  11863. return 1;
  11864. }
  11865. static void form_reset_event(unsigned int form)
  11866. {
  11867. if (form && !js_browser_event(form, "reset", 1, 1))
  11868. return;
  11869. if (form)
  11870. form_reset_form(form);
  11871. else
  11872. form_reset_state();
  11873. form_dirty = 0;
  11874. layout_valid = 0;
  11875. ngui_invalidate(&ui);
  11876. }
  11877. static void form_blur(void)
  11878. {
  11879. unsigned int node = form_focus;
  11880. form_focus = 0;
  11881. if (node && form_dirty) {
  11882. form_dirty = 0;
  11883. js_browser_event(node, "change", 1, 0);
  11884. }
  11885. }
  11886. static void form_click(unsigned int node)
  11887. {
  11888. struct form_state *fs;
  11889. int kind, changed = 0;
  11890. if (!form_is_control(node) || form_disabled(node))
  11891. return;
  11892. if (form_focus != node)
  11893. form_blur();
  11894. fs = form_get(node, 1);
  11895. if (!fs)
  11896. return;
  11897. kind = form_kind_of(node);
  11898. /* Focus moves on the press, before `click` is dispatched: a page
  11899. * that cancels the click (a framework's root listener) suppresses
  11900. * the activation behaviour below, never the focus (as in other
  11901. * browsers, where focus follows mousedown). */
  11902. form_focus = node;
  11903. form_dirty = 0;
  11904. if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  11905. kind == FORM_TEXTAREA)
  11906. fs->caret = fs->len;
  11907. layout_valid = 0;
  11908. ngui_invalidate(&ui);
  11909. if (!js_browser_event(node, "click", 1, 1))
  11910. return;
  11911. fs = form_get(node, 0); /* the handler may have changed the DOM */
  11912. if (!fs)
  11913. return;
  11914. if (kind == FORM_CHECKBOX) {
  11915. fs->checked = !fs->checked;
  11916. changed = 1;
  11917. } else if (kind == FORM_RADIO) {
  11918. const char *name = br_find_attr(&doc, node, "name");
  11919. unsigned int i;
  11920. fs->checked = 1;
  11921. changed = 1;
  11922. if (name) {
  11923. for (i = 0; i < FORM_MAX; i++) {
  11924. struct form_state *o = &form_states[i];
  11925. if (!o->used || o->node == node)
  11926. continue;
  11927. if (form_kind_of(o->node) == FORM_RADIO) {
  11928. const char *on = br_find_attr(&doc,
  11929. o->node,
  11930. "name");
  11931. if (on && s_eq(on, name))
  11932. o->checked = 0;
  11933. }
  11934. }
  11935. }
  11936. } else if (kind == FORM_SELECT) {
  11937. unsigned int n = form_option_count(node);
  11938. if (n) {
  11939. fs->selected = (unsigned char)
  11940. ((fs->selected + 1) % n);
  11941. changed = 1;
  11942. }
  11943. } else if (kind == FORM_SUBMIT) {
  11944. form_submit_form(node, 1);
  11945. return;
  11946. } else if (kind == FORM_RESET) {
  11947. form_reset_event(form_ancestor(node));
  11948. return;
  11949. }
  11950. if (changed) {
  11951. js_browser_event(node, "input", 1, 0);
  11952. js_browser_event(node, "change", 1, 0);
  11953. }
  11954. layout_valid = 0;
  11955. ngui_invalidate(&ui);
  11956. }
  11957. static void form_focus_next(void)
  11958. {
  11959. unsigned int start = form_focus ? form_focus + 1 : 0;
  11960. unsigned int i;
  11961. form_blur();
  11962. for (i = start; i < doc.nnode; i++) {
  11963. if (form_is_control(i) && !form_disabled(i) &&
  11964. !s_eq(br_type(&doc, i), "hidden")) {
  11965. form_focus = i;
  11966. layout_valid = 0;
  11967. ngui_invalidate(&ui);
  11968. return;
  11969. }
  11970. }
  11971. form_focus = 0;
  11972. layout_valid = 0;
  11973. ngui_invalidate(&ui);
  11974. }
  11975. static void form_key(int k)
  11976. {
  11977. struct form_state *fs;
  11978. int kind;
  11979. if (!form_focus || form_focus >= doc.nnode) {
  11980. form_focus = 0;
  11981. return;
  11982. }
  11983. fs = form_get(form_focus, 1);
  11984. if (!fs || form_disabled(form_focus))
  11985. return;
  11986. kind = form_kind_of(form_focus);
  11987. if (kind == FORM_SELECT) {
  11988. unsigned int n = form_option_count(form_focus);
  11989. int changed = 0;
  11990. if (k == NGUI_KEY_UP && n) {
  11991. fs->selected = (unsigned char)
  11992. ((fs->selected + n - 1) % n);
  11993. changed = 1;
  11994. } else if (k == NGUI_KEY_DOWN && n) {
  11995. fs->selected = (unsigned char)
  11996. ((fs->selected + 1) % n);
  11997. changed = 1;
  11998. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  11999. form_blur();
  12000. layout_valid = 0;
  12001. ngui_invalidate(&ui);
  12002. return;
  12003. } else {
  12004. return;
  12005. }
  12006. if (changed) {
  12007. js_browser_event(form_focus, "input", 1, 0);
  12008. js_browser_event(form_focus, "change", 1, 0);
  12009. }
  12010. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  12011. if (k == ' ') {
  12012. form_click(form_focus);
  12013. return;
  12014. }
  12015. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  12016. form_blur();
  12017. layout_valid = 0;
  12018. ngui_invalidate(&ui);
  12019. }
  12020. return;
  12021. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  12022. kind == FORM_RESET) {
  12023. if (k == NGUI_KEY_ESC) {
  12024. form_blur();
  12025. layout_valid = 0;
  12026. ngui_invalidate(&ui);
  12027. } else if (k == '\r' || k == '\n' || k == ' ') {
  12028. form_click(form_focus);
  12029. }
  12030. return;
  12031. } else if (k == NGUI_KEY_TAB) {
  12032. form_focus_next();
  12033. return;
  12034. } else if (k == NGUI_KEY_ESC) {
  12035. form_blur();
  12036. layout_valid = 0;
  12037. ngui_invalidate(&ui);
  12038. return;
  12039. } else if (k == '\r' || k == '\n') {
  12040. unsigned int node = form_focus;
  12041. form_blur();
  12042. if (form_ancestor(node))
  12043. form_submit_form(node, 1);
  12044. layout_valid = 0;
  12045. ngui_invalidate(&ui);
  12046. return;
  12047. } else if (k == NGUI_KEY_BACKSPACE) {
  12048. if (fs->caret) {
  12049. unsigned int i = --fs->caret;
  12050. for (; i < fs->len; i++)
  12051. fs->value[i] = fs->value[i + 1];
  12052. if (fs->len)
  12053. fs->len--;
  12054. form_dirty = 1;
  12055. js_browser_event(form_focus, "input", 1, 0);
  12056. }
  12057. } else if (k == NGUI_KEY_DELETE) {
  12058. if (fs->caret < fs->len) {
  12059. unsigned int i;
  12060. for (i = fs->caret; i < fs->len; i++)
  12061. fs->value[i] = fs->value[i + 1];
  12062. fs->len--;
  12063. form_dirty = 1;
  12064. js_browser_event(form_focus, "input", 1, 0);
  12065. }
  12066. } else if (k == NGUI_KEY_LEFT) {
  12067. if (fs->caret)
  12068. fs->caret--;
  12069. } else if (k == NGUI_KEY_RIGHT) {
  12070. if (fs->caret < fs->len)
  12071. fs->caret++;
  12072. } else if (k == NGUI_KEY_HOME) {
  12073. fs->caret = 0;
  12074. } else if (k == NGUI_KEY_END) {
  12075. fs->caret = fs->len;
  12076. } else if (k >= 32 && k < 127) {
  12077. if (fs->len < FORM_VALUE_MAX) {
  12078. unsigned int i;
  12079. for (i = fs->len; i > fs->caret; i--)
  12080. fs->value[i] = fs->value[i - 1];
  12081. fs->value[fs->caret++] = (char)k;
  12082. fs->len++;
  12083. form_dirty = 1;
  12084. js_browser_event(form_focus, "input", 1, 0);
  12085. }
  12086. } else {
  12087. return;
  12088. }
  12089. fs->value[fs->len] = '\0';
  12090. layout_valid = 0;
  12091. ngui_invalidate(&ui);
  12092. }
  12093. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  12094. * a same-document navigation: update the URL and fire hashchange. Returns
  12095. * 1 when handled. */
  12096. static int link_fragment_nav(unsigned int node)
  12097. {
  12098. const char *href = br_href(&doc, node);
  12099. char url[BR_URL_MAX];
  12100. unsigned int n = 0;
  12101. if (!href || !href[0] || !js_browser_active())
  12102. return 0;
  12103. if (href[0] == '#') {
  12104. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  12105. url[n] = page_url[n];
  12106. n++;
  12107. }
  12108. url[n] = '\0';
  12109. s_append(url, &n, href, sizeof(url));
  12110. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  12111. return 0;
  12112. }
  12113. if (!same_doc_fragment(url))
  12114. return href[0] == '#';
  12115. page_set_fragment(url, 1);
  12116. js_browser_hashchange();
  12117. return 1;
  12118. }
  12119. /* The innermost laid-out box under a screen point: the smallest valid box
  12120. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  12121. * Used to deliver clicks to elements that are neither links nor controls
  12122. * (a Vue <div role="button">, a card with a click listener). */
  12123. static unsigned int find_box_hit(int x, int y)
  12124. {
  12125. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  12126. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  12127. const struct br_layout_box *b = &layout_boxes[i];
  12128. unsigned int area;
  12129. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  12130. x < b->x || y < b->y || x >= b->x + b->w ||
  12131. y >= b->y + b->h)
  12132. continue;
  12133. area = (unsigned int)b->w * (unsigned int)b->h;
  12134. if (area <= best_area) {
  12135. best = i;
  12136. best_area = area;
  12137. }
  12138. }
  12139. return best;
  12140. }
  12141. static void handle_page_click(unsigned int *action)
  12142. {
  12143. int node;
  12144. char url[BR_URL_MAX];
  12145. if (!ui.pressed)
  12146. return;
  12147. if (ui.press_x < page_rect.x ||
  12148. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  12149. ui.press_y < page_rect.y ||
  12150. ui.press_y >= page_rect.y + page_rect.h)
  12151. return;
  12152. node = find_hit(ui.press_x, ui.press_y);
  12153. if (!node) {
  12154. unsigned int box;
  12155. if (!js_browser_active())
  12156. return;
  12157. box = find_box_hit(ui.press_x, ui.press_y);
  12158. if (box) {
  12159. form_blur();
  12160. js_browser_event(box, "click", 1, 1);
  12161. }
  12162. return;
  12163. }
  12164. if (form_is_control((unsigned int)node)) {
  12165. form_click((unsigned int)node);
  12166. return;
  12167. }
  12168. form_blur();
  12169. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  12170. return;
  12171. if (link_fragment_nav((unsigned int)node))
  12172. return;
  12173. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  12174. sizeof(url)) != 0)
  12175. return;
  12176. s_copy(click_url, url, sizeof(click_url));
  12177. *action |= ACT_NAV;
  12178. }
  12179. void _start(const char *arg)
  12180. {
  12181. struct win_info wi;
  12182. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  12183. u_win_create(960, 640, "Browser", &wi) != 0 &&
  12184. u_win_create(780, 540, "Browser", &wi) != 0) {
  12185. u_puts("browser: no graphics window\n");
  12186. u_exit(1);
  12187. }
  12188. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  12189. url_in.placeholder = "http://...";
  12190. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  12191. ui.theme.accent);
  12192. br_set_viewport(wi.width);
  12193. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  12194. s_copy(cwd, "/", sizeof(cwd));
  12195. heap_clear();
  12196. origin_cache_load();
  12197. css_cache_init();
  12198. script_cache_init();
  12199. persist_restore();
  12200. hist_load();
  12201. page_scroll.offset = 0;
  12202. page_scroll.content_h = 0;
  12203. if (arg && arg[0]) {
  12204. navigate(arg, 1);
  12205. } else {
  12206. load_home(1);
  12207. /* Start ready to type: keep the home page, but leave the address
  12208. * bar empty instead of showing "about:home". */
  12209. ngui_input_set(&url_in, "");
  12210. ngui_set_focus(&ui, ID_URL);
  12211. }
  12212. for (;;) {
  12213. unsigned int action = 0;
  12214. unsigned int now;
  12215. click_url[0] = '\0';
  12216. if (pending_action) {
  12217. action |= pending_action & ACT_WAIT_NAV;
  12218. if (pending_url[0])
  12219. s_copy(click_url, pending_url, sizeof(click_url));
  12220. pending_action = 0;
  12221. pending_url[0] = '\0';
  12222. cancel_fetch = 0;
  12223. } else if (preload_active) {
  12224. if (preload_wait)
  12225. preload_wait = 0;
  12226. else
  12227. preload_step();
  12228. } else if ((preload_pending &&
  12229. page_scroll.offset != preload_scroll) ||
  12230. (preload_rescan && layout_valid)) {
  12231. preload_scroll = page_scroll.offset;
  12232. preload_rescan = 0;
  12233. preload_pending = 0;
  12234. preload_node = 0;
  12235. preload_active = 1;
  12236. }
  12237. js_browser_tick();
  12238. if (resize_pending && !pending_action) {
  12239. resize_pending = 0;
  12240. resize_sent_w = layout_right - layout_left;
  12241. js_browser_window_event("resize");
  12242. }
  12243. persist_tick();
  12244. if (pending_action)
  12245. continue;
  12246. now = u_ticks_ms();
  12247. if (status_until && (int)(now - status_until) >= 0) {
  12248. status_text[0] = '\0';
  12249. status_until = 0;
  12250. status_error = 0;
  12251. ngui_invalidate(&ui);
  12252. }
  12253. if (!ngui_begin(&ui)) {
  12254. /* A queued navigation (e.g. Enter in the URL bar during
  12255. * a slow fetch) must be handled even when this frame
  12256. * needs no redraw. */
  12257. if (!action) {
  12258. fetch_workers_stop_if_unfocused();
  12259. u_sleep_ms(10);
  12260. continue;
  12261. }
  12262. } else {
  12263. draw(&action);
  12264. handle_keys(&action);
  12265. handle_page_click(&action);
  12266. ngui_end(&ui);
  12267. }
  12268. if (action & ACT_NAV) {
  12269. if (click_url[0]) {
  12270. navigate(click_url, 1);
  12271. click_url[0] = '\0';
  12272. } else {
  12273. navigate(url_in.text, 1);
  12274. }
  12275. }
  12276. if (action & ACT_BACK) {
  12277. if (hist_pos > 0) {
  12278. hist_pos--;
  12279. if (same_doc_fragment(history[hist_pos])) {
  12280. page_set_fragment(history[hist_pos], 0);
  12281. js_browser_hashchange();
  12282. } else {
  12283. navigate(history[hist_pos], 0);
  12284. }
  12285. }
  12286. }
  12287. if (action & ACT_FORWARD) {
  12288. if (hist_pos + 1 < hist_len) {
  12289. hist_pos++;
  12290. if (same_doc_fragment(history[hist_pos])) {
  12291. page_set_fragment(history[hist_pos], 0);
  12292. js_browser_hashchange();
  12293. } else {
  12294. navigate(history[hist_pos], 0);
  12295. }
  12296. }
  12297. }
  12298. if (action & ACT_RELOAD) {
  12299. if (s_eq(page_url, "about:home"))
  12300. load_home(0);
  12301. else
  12302. navigate(page_url, 0);
  12303. }
  12304. if (action & ACT_HOME)
  12305. load_home(1);
  12306. if (action & ACT_CLOSE)
  12307. quit = 1;
  12308. if (quit)
  12309. break;
  12310. if (pending_action)
  12311. continue;
  12312. fetch_workers_stop_if_unfocused();
  12313. u_sleep_ms(10);
  12314. }
  12315. fetch_workers_stop_all();
  12316. u_win_close();
  12317. u_exit(0);
  12318. }