browser.c 332 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658
  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. };
  233. struct lay {
  234. int draw;
  235. struct ngui *ui;
  236. int left, right;
  237. int y;
  238. int line_x, line_y, line_h;
  239. int line_left, line_right;
  240. int parent_top;
  241. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  242. int cb_h; /* definite content height of the containing block for
  243. * percentage heights; 0 = indefinite (auto) */
  244. int run_x;
  245. int align;
  246. int depth;
  247. int space_pending;
  248. unsigned char float_active;
  249. int float_left, float_right, float_bottom;
  250. struct lay_run runs[96];
  251. int nruns;
  252. };
  253. struct hit {
  254. int x, y, w, h;
  255. unsigned short node;
  256. };
  257. /* Live form state; the DOM attributes stay the initial/default value. */
  258. #define FORM_MAX 64
  259. #define FORM_VALUE_MAX 63
  260. enum {
  261. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  262. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  263. };
  264. struct form_state {
  265. unsigned int node;
  266. char value[FORM_VALUE_MAX + 1];
  267. unsigned char len, caret, checked, selected, used;
  268. };
  269. static struct form_state form_states[FORM_MAX];
  270. static unsigned int form_focus;
  271. static unsigned int form_dirty;
  272. static int form_descendant(unsigned int node, unsigned int form);
  273. static int form_submit_form(unsigned int node, int fire_event);
  274. static int link_fragment_nav(unsigned int node);
  275. static void history_push(const char *url);
  276. static void form_reset_event(unsigned int form);
  277. static unsigned int s_len(const char *s);
  278. static int s_eq(const char *a, const char *b);
  279. static void form_key(int k);
  280. static void form_click(unsigned int node);
  281. static void style_for_node(unsigned int node, struct br_style *out);
  282. static int form_author_styled(const struct br_style *st);
  283. static int css_radius(const struct br_style *st, int corner, int w, int h);
  284. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  285. const struct br_style *st, int focused);
  286. static int form_disabled(unsigned int node)
  287. {
  288. struct br_node *n = &doc.nodes[node];
  289. if (n->attr_flags & BR_ATTR_DISABLED)
  290. return 1;
  291. return br_find_attr(&doc, node, "disabled") != 0;
  292. }
  293. static int form_kind_of(unsigned int node)
  294. {
  295. const char *type = br_type(&doc, node);
  296. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  297. return FORM_TEXTAREA;
  298. if (doc.nodes[node].tag == BR_TAG_SELECT)
  299. return FORM_SELECT;
  300. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  301. if (s_eq(type, "reset"))
  302. return FORM_RESET;
  303. if (s_eq(type, "button"))
  304. return FORM_BUTTON;
  305. return FORM_SUBMIT;
  306. }
  307. if (s_eq(type, "password"))
  308. return FORM_PASSWORD;
  309. if (s_eq(type, "checkbox"))
  310. return FORM_CHECKBOX;
  311. if (s_eq(type, "radio"))
  312. return FORM_RADIO;
  313. if (s_eq(type, "submit"))
  314. return FORM_SUBMIT;
  315. if (s_eq(type, "reset"))
  316. return FORM_RESET;
  317. if (s_eq(type, "button"))
  318. return FORM_BUTTON;
  319. return FORM_TEXT;
  320. }
  321. static unsigned int form_option_count(unsigned int node)
  322. {
  323. unsigned int c, n = 0;
  324. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  325. if (doc.nodes[c].type == BR_NODE_ELEM &&
  326. doc.nodes[c].tag == BR_TAG_OPTION)
  327. n++;
  328. return n;
  329. }
  330. static unsigned int form_option_selected(unsigned int node)
  331. {
  332. unsigned int c, i = 0;
  333. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  334. if (doc.nodes[c].type != BR_NODE_ELEM ||
  335. doc.nodes[c].tag != BR_TAG_OPTION)
  336. continue;
  337. if (br_find_attr(&doc, c, "selected"))
  338. return i;
  339. i++;
  340. }
  341. return 0;
  342. }
  343. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  344. char *out, unsigned int cap)
  345. {
  346. unsigned int c, i = 0;
  347. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  348. if (doc.nodes[c].type != BR_NODE_ELEM ||
  349. doc.nodes[c].tag != BR_TAG_OPTION)
  350. continue;
  351. if (i == idx)
  352. return br_text_content(&doc, c, out, cap);
  353. i++;
  354. }
  355. return 0;
  356. }
  357. static struct form_state *form_get(unsigned int node, int create)
  358. {
  359. struct form_state *slot = 0;
  360. unsigned int i;
  361. for (i = 0; i < FORM_MAX; i++) {
  362. if (form_states[i].used) {
  363. if (form_states[i].node == node)
  364. return &form_states[i];
  365. } else if (!slot) {
  366. slot = &form_states[i];
  367. }
  368. }
  369. if (!create || !slot)
  370. return 0;
  371. slot->node = node;
  372. slot->len = 0;
  373. slot->caret = 0;
  374. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  375. slot->selected = form_option_selected(node);
  376. slot->used = 1;
  377. {
  378. unsigned int n = 0;
  379. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  380. n = br_text_content(&doc, node, slot->value,
  381. FORM_VALUE_MAX + 1);
  382. } else {
  383. const char *v = br_value(&doc, node);
  384. if (v) {
  385. n = s_len(v);
  386. if (n > FORM_VALUE_MAX)
  387. n = FORM_VALUE_MAX;
  388. for (unsigned int j = 0; j < n; j++)
  389. slot->value[j] = v[j];
  390. }
  391. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  392. n = br_text_content(&doc, node, slot->value,
  393. FORM_VALUE_MAX + 1);
  394. }
  395. if (n > FORM_VALUE_MAX)
  396. n = FORM_VALUE_MAX;
  397. slot->value[n] = '\0';
  398. slot->len = (unsigned char)n;
  399. slot->caret = (unsigned char)n;
  400. }
  401. return slot;
  402. }
  403. static void form_reset_state(void)
  404. {
  405. unsigned int i;
  406. for (i = 0; i < FORM_MAX; i++)
  407. form_states[i].used = 0;
  408. form_focus = 0;
  409. }
  410. /* A <button> with element content (an icon <svg>/<img>, a <span> label)
  411. * is laid out like a normal element so that content shows; only a text or
  412. * empty button is drawn as a native control. Clicks still reach it
  413. * through the box hit test. */
  414. static int button_has_elements(unsigned int node)
  415. {
  416. unsigned int c;
  417. if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
  418. return 0;
  419. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  420. if (doc.nodes[c].type == BR_NODE_ELEM)
  421. return 1;
  422. return 0;
  423. }
  424. static int form_is_control(unsigned int node)
  425. {
  426. unsigned int tag;
  427. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  428. return 0;
  429. tag = doc.nodes[node].tag;
  430. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  431. tag == BR_TAG_SELECT ||
  432. (tag == BR_TAG_BUTTON && !button_has_elements(node));
  433. }
  434. #define HIT_MAX 96
  435. static struct hit hits[HIT_MAX];
  436. static int nhits;
  437. static unsigned short block_h[BR_MAX_NODES];
  438. /* Measure-pass top of each block, in the same document coordinates as
  439. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  440. * paint, so it cannot drive the lazy background loader). */
  441. static unsigned short block_top[BR_MAX_NODES];
  442. static char li_marker[BR_MAX_NODES][12];
  443. /* one connection object; the browser fetches one resource at a time */
  444. /* ---- tiny strings ---- */
  445. static unsigned int s_len(const char *s)
  446. {
  447. unsigned int n = 0;
  448. while (s && s[n])
  449. n++;
  450. return n;
  451. }
  452. static void s_copy(char *d, const char *s, unsigned int cap)
  453. {
  454. unsigned int i = 0;
  455. if (!cap)
  456. return;
  457. while (s && s[i] && i + 1 < cap) {
  458. d[i] = s[i];
  459. i++;
  460. }
  461. d[i] = '\0';
  462. }
  463. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  464. {
  465. while (s && *s && *n + 1 < cap)
  466. d[(*n)++] = *s++;
  467. d[*n] = '\0';
  468. }
  469. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  470. unsigned int cap)
  471. {
  472. char tmp[12];
  473. unsigned int i = 0, j;
  474. do {
  475. tmp[i++] = (char)('0' + v % 10);
  476. v /= 10;
  477. } while (v && i < sizeof(tmp));
  478. for (j = 0; j < i && *n + 1 < cap; j++)
  479. d[(*n)++] = tmp[i - 1 - j];
  480. d[*n] = '\0';
  481. }
  482. static int s_eq(const char *a, const char *b)
  483. {
  484. while (*a && *b) {
  485. if (*a != *b)
  486. return 0;
  487. a++;
  488. b++;
  489. }
  490. return *a == *b;
  491. }
  492. static int starts_with(const char *s, const char *p)
  493. {
  494. unsigned int i = 0;
  495. while (p[i]) {
  496. if (s[i] != p[i])
  497. return 0;
  498. i++;
  499. }
  500. return 1;
  501. }
  502. static int contains_ci(const char *s, const char *p)
  503. {
  504. unsigned int i, j;
  505. for (i = 0; s[i]; i++) {
  506. for (j = 0; p[j]; j++) {
  507. char a = s[i + j];
  508. if (a >= 'A' && a <= 'Z')
  509. a = (char)(a - 'A' + 'a');
  510. if (a != p[j])
  511. break;
  512. }
  513. if (!p[j])
  514. return 1;
  515. }
  516. return 0;
  517. }
  518. static char *trim(char *s)
  519. {
  520. unsigned int n;
  521. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  522. s++;
  523. n = s_len(s);
  524. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  525. s[n - 1] == '\r' || s[n - 1] == '\n'))
  526. s[--n] = '\0';
  527. return s;
  528. }
  529. /* ---- per-process heap ---- */
  530. static int heap_start(void)
  531. {
  532. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  533. if (!image_io_buf)
  534. return -1;
  535. page_backbuf = (unsigned short *)malloc(
  536. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  537. pagebuf_w = page_backbuf ? ui.w : 0;
  538. pagebuf_h = page_backbuf ? ui.h : 0;
  539. page_cache_valid = 0;
  540. return 0;
  541. }
  542. static void heap_clear(void)
  543. {
  544. memset(font_faces, 0, sizeof(font_faces));
  545. ngui_font_detach(&ui);
  546. svg_cache_clear();
  547. decode_arena = 0; /* lives in the page heap too */
  548. decode_arena_size = 0;
  549. heap_reset();
  550. /* The document arenas live in that heap; drop the stale pointers so
  551. * the next br_parse_plain() allocates fresh ones. */
  552. doc.nodes = 0;
  553. doc.text = 0;
  554. doc.attrs = 0;
  555. image_io_buf = 0;
  556. page_backbuf = 0;
  557. pagebuf_w = pagebuf_h = 0;
  558. page_cache_valid = 0;
  559. }
  560. static void browser_rules_alloc(void)
  561. {
  562. struct br_rule *rules;
  563. rules = (struct br_rule *)malloc(
  564. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  565. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  566. }
  567. /* ---- status ---- */
  568. static void set_status(const char *s, int err, unsigned int ttl_ms)
  569. {
  570. s_copy(status_text, s, sizeof(status_text));
  571. status_error = err;
  572. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  573. ngui_invalidate(&ui);
  574. }
  575. /* Update the status text without forcing a frame; the throttled image
  576. * repaint picks it up. Starting one helper per image used to invalidate the
  577. * whole page before every decode. */
  578. static void set_status_quiet(const char *s)
  579. {
  580. s_copy(status_text, s, sizeof(status_text));
  581. status_error = 0;
  582. status_until = 0;
  583. }
  584. /* ---- JavaScript ---- */
  585. static int resolve_link(const char *base, const char *href, char *out,
  586. unsigned int cap);
  587. static char js_last_status[BR_STATUS_MAX];
  588. static int js_last_error;
  589. static void js_host_status(const char *msg, int error)
  590. {
  591. s_copy(js_last_status, msg, sizeof(js_last_status));
  592. js_last_error = error;
  593. set_status(msg, error, 6000);
  594. }
  595. static void js_host_report(const char *msg)
  596. {
  597. u_puts("[js] ");
  598. u_puts(msg);
  599. u_putc('\n');
  600. s_copy(js_last_status, msg, sizeof(js_last_status));
  601. js_last_error = 1;
  602. set_status(msg, 1, 8000);
  603. }
  604. static void js_host_navigate(const char *url)
  605. {
  606. char resolved[BR_URL_MAX];
  607. if (!url || !url[0])
  608. return;
  609. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  610. return;
  611. s_copy(pending_url, resolved, sizeof(pending_url));
  612. pending_action |= ACT_NAV;
  613. cancel_fetch = 1;
  614. }
  615. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  616. * back/forward between fragments): the page URL, address bar and history
  617. * follow, nothing is reloaded. `push` adds a history entry. */
  618. static int page_set_fragment(const char *url, int push)
  619. {
  620. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  621. return -1;
  622. s_copy(page_url, url, sizeof(page_url));
  623. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  624. url_in.len = s_len(url_in.text);
  625. url_in.cursor = url_in.len;
  626. url_in.scroll = 0;
  627. if (push)
  628. history_push(page_url);
  629. ngui_invalidate(&ui);
  630. return 0;
  631. }
  632. static int js_host_set_hash(const char *url)
  633. {
  634. return page_set_fragment(url, 1);
  635. }
  636. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  637. * the page, so a hash router can react). */
  638. static int same_doc_fragment(const char *url)
  639. {
  640. unsigned int a = 0, b = 0;
  641. if (!js_browser_active() || !url)
  642. return 0;
  643. while (url[a] && url[a] != '#')
  644. a++;
  645. while (page_url[b] && page_url[b] != '#')
  646. b++;
  647. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  648. !s_eq(url, page_url);
  649. }
  650. static void js_host_changed(void)
  651. {
  652. /* Class/style/attribute mutations change computed styles, not just the
  653. * text: drop the per-node style cache before the next layout. */
  654. br_reset_styles(&doc);
  655. layout_valid = 0;
  656. /* Script-built content (Angular's ng-repeat cards) brings new images
  657. * and inline background styles: rescan once the main loop is idle. */
  658. preload_rescan = 1;
  659. ngui_invalidate(&ui);
  660. }
  661. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  662. {
  663. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  664. return 0;
  665. *x = layout_boxes[node].x - page_rect.x;
  666. *y = layout_boxes[node].y - page_rect.y;
  667. *w = layout_boxes[node].w;
  668. *h = layout_boxes[node].h;
  669. return 1;
  670. }
  671. static void form_copy_out(const char *s, char *buf, int cap)
  672. {
  673. int i = 0;
  674. if (!buf || cap <= 0)
  675. return;
  676. while (s && s[i] && i + 1 < cap) {
  677. buf[i] = s[i];
  678. i++;
  679. }
  680. buf[i] = '\0';
  681. }
  682. static int js_host_form_value(unsigned int node, char *buf, int cap)
  683. {
  684. struct form_state *fs;
  685. int kind;
  686. if (!form_is_control(node))
  687. return 0;
  688. kind = form_kind_of(node);
  689. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  690. return 0;
  691. if (kind == FORM_SELECT) {
  692. char opt[64] = "";
  693. unsigned int c, i = 0;
  694. fs = form_get(node, 1);
  695. if (!fs)
  696. return 0;
  697. form_option_text(node, fs->selected, opt, sizeof(opt));
  698. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  699. if (doc.nodes[c].type != BR_NODE_ELEM ||
  700. doc.nodes[c].tag != BR_TAG_OPTION)
  701. continue;
  702. if (i == fs->selected) {
  703. const char *v = br_value(&doc, c);
  704. if (v && v[0])
  705. form_copy_out(v, buf, cap);
  706. else
  707. form_copy_out(opt, buf, cap);
  708. return 1;
  709. }
  710. i++;
  711. }
  712. form_copy_out(opt, buf, cap);
  713. return 1;
  714. }
  715. fs = form_get(node, 1);
  716. if (!fs)
  717. return 0;
  718. form_copy_out(fs->value, buf, cap);
  719. return 1;
  720. }
  721. static int js_host_form_checked(unsigned int node)
  722. {
  723. struct form_state *fs;
  724. int kind;
  725. if (!form_is_control(node))
  726. return -1;
  727. kind = form_kind_of(node);
  728. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  729. return -1;
  730. fs = form_get(node, 1);
  731. return fs ? fs->checked : 0;
  732. }
  733. static int js_host_form_selected(unsigned int node)
  734. {
  735. struct form_state *fs;
  736. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  737. return -1;
  738. fs = form_get(node, 1);
  739. return fs ? fs->selected : 0;
  740. }
  741. static int js_host_form_set_value(unsigned int node, const char *value)
  742. {
  743. struct form_state *fs;
  744. unsigned int n;
  745. if (!form_is_control(node))
  746. return 0;
  747. fs = form_get(node, 1);
  748. if (!fs)
  749. return 0;
  750. n = s_len(value ? value : "");
  751. if (n > FORM_VALUE_MAX)
  752. n = FORM_VALUE_MAX;
  753. for (unsigned int i = 0; i < n; i++)
  754. fs->value[i] = value[i];
  755. fs->value[n] = '\0';
  756. fs->len = (unsigned char)n;
  757. fs->caret = (unsigned char)n;
  758. layout_valid = 0;
  759. ngui_invalidate(&ui);
  760. return 1;
  761. }
  762. static int js_host_form_set_checked(unsigned int node, int checked)
  763. {
  764. struct form_state *fs;
  765. int kind;
  766. if (!form_is_control(node))
  767. return 0;
  768. kind = form_kind_of(node);
  769. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  770. return 0;
  771. fs = form_get(node, 1);
  772. if (!fs)
  773. return 0;
  774. fs->checked = (unsigned char)(checked != 0);
  775. layout_valid = 0;
  776. ngui_invalidate(&ui);
  777. return 1;
  778. }
  779. static int js_host_form_set_selected(unsigned int node, int index)
  780. {
  781. struct form_state *fs;
  782. unsigned int n;
  783. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  784. return 0;
  785. fs = form_get(node, 1);
  786. if (!fs)
  787. return 0;
  788. n = form_option_count(node);
  789. if (index < 0)
  790. index = 0;
  791. if (n && (unsigned int)index >= n)
  792. index = (int)n - 1;
  793. fs->selected = (unsigned char)index;
  794. layout_valid = 0;
  795. ngui_invalidate(&ui);
  796. return 1;
  797. }
  798. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  799. {
  800. unsigned int i;
  801. int n = 0;
  802. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  803. doc.nodes[form].tag != BR_TAG_FORM)
  804. return 0;
  805. for (i = 0; i < doc.nnode && n < cap; i++) {
  806. struct br_node *nd = &doc.nodes[i];
  807. if (i == form || nd->type != BR_NODE_ELEM)
  808. continue;
  809. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  810. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  811. continue;
  812. if (!form_descendant(i, form))
  813. continue;
  814. out[n++] = i;
  815. }
  816. return n;
  817. }
  818. static int js_host_form_submit(unsigned int form)
  819. {
  820. form_submit_form(form, 0);
  821. return 1;
  822. }
  823. static int js_host_form_reset(unsigned int form)
  824. {
  825. form_reset_event(form);
  826. return 1;
  827. }
  828. static void css_computed_name(const char *p, char *out, int cap)
  829. {
  830. int n = 0;
  831. for (; p && *p && n + 2 < cap; p++) {
  832. char c = *p;
  833. if (c >= 'A' && c <= 'Z') {
  834. out[n++] = '-';
  835. c = (char)(c - 'A' + 'a');
  836. } else if (c == '_') {
  837. c = '-';
  838. } else if (c >= 'a' && c <= 'z') {
  839. /* keep */
  840. }
  841. out[n++] = c;
  842. }
  843. out[n] = '\0';
  844. if (!strcmp(out, "css-float"))
  845. strcpy(out, "float");
  846. }
  847. static void css_rgb(unsigned short c, char *buf, int cap)
  848. {
  849. int r = ((c >> 11) & 31) * 255 / 31;
  850. int g = ((c >> 5) & 63) * 255 / 63;
  851. int b = (c & 31) * 255 / 31;
  852. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  853. }
  854. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  855. int font_px)
  856. {
  857. if (unit == 4) {
  858. snprintf(buf, cap, "auto");
  859. } else if (unit == 0) {
  860. snprintf(buf, cap, "%dpx", raw);
  861. } else if (unit == 1) {
  862. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  863. } else if (unit == 2) {
  864. /* Chrome's getComputedStyle() reports used pixel values. */
  865. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  866. } else if (unit == 3) {
  867. snprintf(buf, cap, "%dpx",
  868. (int)br_root_font_px() * raw / 100);
  869. } else {
  870. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  871. raw / 100, raw % 100, px);
  872. }
  873. }
  874. static int js_host_computed(unsigned int node, const char *property,
  875. char *buf, int cap)
  876. {
  877. struct br_style st;
  878. char name[40];
  879. if (!buf || cap <= 0 || node >= doc.nnode || node == 0)
  880. return 0;
  881. buf[0] = '\0';
  882. css_computed_name(property, name, sizeof(name));
  883. style_for_node(node, &st);
  884. if (!strcmp(name, "display")) {
  885. const char *v = "inline";
  886. if (st.display == BR_DISPLAY_BLOCK)
  887. v = "block";
  888. else if (st.display == BR_DISPLAY_NONE)
  889. v = "none";
  890. else if (st.display == BR_DISPLAY_FLEX)
  891. v = "flex";
  892. else if (st.display == BR_DISPLAY_GRID)
  893. v = "grid";
  894. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  895. v = "inline-block";
  896. snprintf(buf, cap, "%s", v);
  897. } else if (!strcmp(name, "position")) {
  898. static const char *pos[] = {
  899. "static", "absolute", "fixed", "relative", "sticky"
  900. };
  901. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  902. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  903. int is_w = name[0] == 'w';
  904. int kind = is_w ? st.width_kind : st.height_kind;
  905. int val = is_w ? st.width : st.height;
  906. if (kind == 3) {
  907. if (is_w)
  908. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  909. st.width_calc_pct / 100,
  910. st.width_calc_pct % 100,
  911. st.width_calc_px);
  912. else
  913. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  914. st.height_calc_pct / 100,
  915. st.height_calc_pct % 100,
  916. st.height_calc_px);
  917. } else if (kind == 1) {
  918. snprintf(buf, cap, "%dpx", val);
  919. } else if (kind == 2) {
  920. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  921. } else {
  922. snprintf(buf, cap, "auto");
  923. }
  924. } else if (!strcmp(name, "color") ||
  925. !strcmp(name, "background-color")) {
  926. if (!strcmp(name, "background-color") && !st.has_bg)
  927. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  928. else
  929. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  930. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  931. int is_fill = name[0] == 'f';
  932. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  933. if (mode == BR_PAINT_COLOR)
  934. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  935. else if (mode == BR_PAINT_CURRENT)
  936. css_rgb(st.color, buf, cap);
  937. else if (mode == BR_PAINT_UNSET && is_fill)
  938. snprintf(buf, cap, "rgb(0, 0, 0)");
  939. else if (mode == BR_PAINT_URL)
  940. snprintf(buf, cap, "url()");
  941. else
  942. snprintf(buf, cap, "none");
  943. } else if (!strcmp(name, "font-size")) {
  944. snprintf(buf, cap, "%dpx", st.font_px);
  945. } else if (!strcmp(name, "font-weight")) {
  946. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  947. } else if (!strcmp(name, "font-style")) {
  948. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  949. } else if (!strcmp(name, "font-family")) {
  950. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  951. br_font_face_family(st.font_face)[0])
  952. snprintf(buf, cap, "%s",
  953. br_font_face_family(st.font_face));
  954. else
  955. snprintf(buf, cap, "%s",
  956. st.mono ? "monospace" : "sans-serif");
  957. } else if (!strcmp(name, "text-align")) {
  958. static const char *al[] = { "left", "center", "right", "justify" };
  959. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  960. } else if (!strcmp(name, "float")) {
  961. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  962. st.float_left == 2 ? "right" : "none");
  963. } else if (!strcmp(name, "clear")) {
  964. static const char *cl[] = { "none", "left", "right", "both" };
  965. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  966. } else if (!strcmp(name, "opacity")) {
  967. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  968. } else if (!strcmp(name, "visibility")) {
  969. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  970. } else if (!strcmp(name, "overflow")) {
  971. snprintf(buf, cap, "%s",
  972. st.overflow_hidden ? "hidden" : "visible");
  973. } else if (!strcmp(name, "white-space")) {
  974. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  975. } else if (!strcmp(name, "text-transform")) {
  976. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  977. } else if (!strcmp(name, "box-sizing")) {
  978. snprintf(buf, cap, "%s",
  979. st.box_sizing ? "border-box" : "content-box");
  980. } else if (!strcmp(name, "line-height")) {
  981. if (st.line_h_px)
  982. snprintf(buf, cap, "%dpx", st.line_h_px);
  983. else if (st.line_h_pct)
  984. snprintf(buf, cap, "%d%%", st.line_h_pct);
  985. else
  986. snprintf(buf, cap, "normal");
  987. } else if (!strcmp(name, "z-index")) {
  988. if (st.z_set)
  989. snprintf(buf, cap, "%d", st.z_index);
  990. else
  991. snprintf(buf, cap, "auto");
  992. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  993. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  994. int set = name[0] == 't' ? st.top_set :
  995. name[0] == 'l' ? st.left_set :
  996. name[0] == 'r' ? st.right_set : st.bottom_set;
  997. int v = name[0] == 't' ? st.top :
  998. name[0] == 'l' ? st.left :
  999. name[0] == 'r' ? st.right : st.bottom;
  1000. if (set)
  1001. snprintf(buf, cap, "%dpx", v);
  1002. else
  1003. snprintf(buf, cap, "auto");
  1004. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  1005. !strcmp(name, "margin-bottom") ||
  1006. !strcmp(name, "margin-left") ||
  1007. !strcmp(name, "padding-top") ||
  1008. !strcmp(name, "padding-right") ||
  1009. !strcmp(name, "padding-bottom") ||
  1010. !strcmp(name, "padding-left")) {
  1011. int is_pad = name[0] == 'p';
  1012. int side = name[strlen(name) - 1] == 'p' ? 0 :
  1013. name[strlen(name) - 1] == 't' ? 1 :
  1014. name[strlen(name) - 1] == 'm' ? 2 : 3;
  1015. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  1016. if (!strcmp(name, "margin-right") ||
  1017. !strcmp(name, "padding-right"))
  1018. side = 1;
  1019. else if (!strcmp(name, "margin-bottom") ||
  1020. !strcmp(name, "padding-bottom"))
  1021. side = 2;
  1022. else if (!strcmp(name, "margin-left") ||
  1023. !strcmp(name, "padding-left"))
  1024. side = 3;
  1025. else
  1026. side = 0;
  1027. side += is_pad ? 4 : 0;
  1028. css_mp_value(buf, cap,
  1029. side == 0 ? st.mt : side == 1 ? st.mr :
  1030. side == 2 ? st.mb : side == 3 ? st.ml :
  1031. side == 4 ? st.pt : side == 5 ? st.pr :
  1032. side == 6 ? st.pb : st.pl,
  1033. st.mp_unit[side], st.mp_calc_px[side],
  1034. st.font_px);
  1035. } else if (!strcmp(name, "border-top-width") ||
  1036. !strcmp(name, "border-right-width") ||
  1037. !strcmp(name, "border-bottom-width") ||
  1038. !strcmp(name, "border-left-width")) {
  1039. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1040. name[7] == 'b' ? 2 : 3;
  1041. snprintf(buf, cap, "%dpx", st.border_w[side]);
  1042. } else if (!strcmp(name, "border-top-color") ||
  1043. !strcmp(name, "border-right-color") ||
  1044. !strcmp(name, "border-bottom-color") ||
  1045. !strcmp(name, "border-left-color")) {
  1046. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1047. name[7] == 'b' ? 2 : 3;
  1048. if (st.border_w[side] && !st.border_t[side])
  1049. css_rgb(st.border_c[side], buf, cap);
  1050. else
  1051. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1052. } else if (!strcmp(name, "background-image")) {
  1053. if (st.bg_image)
  1054. snprintf(buf, cap, "url(\"%s\")",
  1055. br_bg_image_url(st.bg_image - 1));
  1056. else
  1057. snprintf(buf, cap, "none");
  1058. } else if (!strcmp(name, "background-repeat")) {
  1059. static const char *rp[] = {
  1060. "repeat", "no-repeat", "repeat-x", "repeat-y"
  1061. };
  1062. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  1063. st.bg_repeat : 0]);
  1064. } else if (!strcmp(name, "background-position")) {
  1065. if (st.bg_pos_x_kind == 1)
  1066. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  1067. st.bg_pos_y);
  1068. else
  1069. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1070. st.bg_pos_y);
  1071. } else if (!strcmp(name, "background-size")) {
  1072. if (st.bg_size_kind == 3)
  1073. snprintf(buf, cap, "cover");
  1074. else if (st.bg_size_kind == 4)
  1075. snprintf(buf, cap, "contain");
  1076. else if (st.bg_size_kind == 1)
  1077. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1078. st.bg_size_h);
  1079. else if (st.bg_size_kind == 2)
  1080. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1081. st.bg_size_h);
  1082. else
  1083. snprintf(buf, cap, "auto");
  1084. } else if (!strcmp(name, "transform")) {
  1085. char tmp[128];
  1086. unsigned int n = 0;
  1087. if (!st.transform_set) {
  1088. snprintf(buf, cap, "none");
  1089. } else {
  1090. tmp[0] = '\0';
  1091. if (st.tx || st.ty) {
  1092. snprintf(tmp + n, sizeof(tmp) - n,
  1093. "translate(%dpx, %dpx)", st.tx, st.ty);
  1094. n = (unsigned int)strlen(tmp);
  1095. }
  1096. if (st.transform_scale) {
  1097. snprintf(tmp + n, sizeof(tmp) - n,
  1098. "%sscale(%d.%02d, %d.%02d)",
  1099. n ? " " : "", st.scale_x / 100,
  1100. st.scale_x % 100, st.scale_y / 100,
  1101. st.scale_y % 100);
  1102. n = (unsigned int)strlen(tmp);
  1103. if (st.rotate_x100) {
  1104. snprintf(tmp + n, sizeof(tmp) - n,
  1105. " rotate(%d.%02ddeg)",
  1106. st.rotate_x100 / 100,
  1107. st.rotate_x100 % 100);
  1108. }
  1109. } else if (st.rotate_x100) {
  1110. snprintf(tmp + n, sizeof(tmp) - n,
  1111. "%srotate(%d.%02ddeg)",
  1112. n ? " " : "", st.rotate_x100 / 100,
  1113. st.rotate_x100 % 100);
  1114. }
  1115. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1116. }
  1117. } else {
  1118. return 0;
  1119. }
  1120. return buf[0] != '\0';
  1121. }
  1122. static int js_host_click(unsigned int node)
  1123. {
  1124. char url[BR_URL_MAX];
  1125. const char *href;
  1126. if (node >= doc.nnode)
  1127. return 0;
  1128. if (form_is_control(node)) {
  1129. form_click(node); /* dispatches its own click event */
  1130. return 1;
  1131. }
  1132. /* element.click() fires a bubbling, cancelable click before the
  1133. * default action, like a real click (delegated list handlers). */
  1134. if (!js_browser_event(node, "click", 1, 1))
  1135. return 1;
  1136. if (link_fragment_nav(node))
  1137. return 1;
  1138. href = br_href(&doc, node);
  1139. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1140. return 0;
  1141. s_copy(pending_url, url, sizeof(pending_url));
  1142. pending_action |= ACT_NAV;
  1143. cancel_fetch = 1;
  1144. ngui_invalidate(&ui);
  1145. return 1;
  1146. }
  1147. static int fetch_script_text(const char *url, unsigned char **out,
  1148. unsigned int *outlen, char *err,
  1149. unsigned int errcap);
  1150. struct fetch_worker;
  1151. static struct fetch_worker *fetch_worker_alloc(void);
  1152. static void fetch_worker_release(struct fetch_worker *w);
  1153. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1154. unsigned int cap, const char *post,
  1155. unsigned int post_len, unsigned int node,
  1156. int bg, char *err, unsigned int errcap);
  1157. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1158. unsigned int errcap);
  1159. static int fetch_worker_read_body(struct fetch_worker *w,
  1160. unsigned char *plain,
  1161. unsigned int plaincap,
  1162. unsigned char *comp,
  1163. unsigned int compcap,
  1164. int *truncated, char *err,
  1165. unsigned int errcap);
  1166. static void fetch_workers_stop_all(void);
  1167. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1168. unsigned int cap, const char *method,
  1169. const char *ctype, const char *post,
  1170. unsigned int post_len, unsigned int node,
  1171. int bg, unsigned int dec_w,
  1172. unsigned int dec_h, char *err,
  1173. unsigned int errcap);
  1174. static int script_cache_has(const char *url);
  1175. static void script_cache_put(const char *url, const unsigned char *data,
  1176. unsigned int len);
  1177. static unsigned int script_cache_hash(const char *s);
  1178. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1179. unsigned int errcap);
  1180. static void fetch_workers_cancel_busy(void);
  1181. static void worker_wait_ui(void);
  1182. static int fetch_worker_status(const struct fetch_worker *w);
  1183. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1184. * module load: the wait must not pump input, or a click would dispatch DOM
  1185. * events into the middle of the running script. */
  1186. static int fetch_wait_passive;
  1187. static void script_error(const char *what, const char *url, const char *why)
  1188. {
  1189. char msg[192];
  1190. unsigned int n = 0;
  1191. s_append(msg, &n, what, sizeof(msg));
  1192. if (url && url[0]) {
  1193. s_append(msg, &n, " ", sizeof(msg));
  1194. s_append(msg, &n, url, sizeof(msg));
  1195. }
  1196. if (why && why[0]) {
  1197. s_append(msg, &n, ": ", sizeof(msg));
  1198. s_append(msg, &n, why, sizeof(msg));
  1199. }
  1200. js_host_report(msg);
  1201. }
  1202. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1203. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1204. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1205. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1206. #define JS_HTTP_POST_MAX (16u * 1024u)
  1207. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1208. static int js_worker_http(const char *method, const char *url,
  1209. const char *ctype, const char *body,
  1210. unsigned int body_len, struct js_http_resp *r,
  1211. char *err, int errcap);
  1212. static int js_host_http(const char *method, const char *url,
  1213. const char *ctype, const char *body,
  1214. unsigned int body_len, struct js_http_resp *r,
  1215. char *err, int errcap)
  1216. {
  1217. if (pending_action) {
  1218. s_copy(err, "page is navigating", (unsigned int)errcap);
  1219. return -1;
  1220. }
  1221. if (url[0] == '/') {
  1222. /* Local file: GET only. */
  1223. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1224. int rv;
  1225. if (!buf) {
  1226. s_copy(err, "out of memory", (unsigned int)errcap);
  1227. return -1;
  1228. }
  1229. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1230. (int)JS_HTTP_MAX);
  1231. r->status = rv < 0 ? 404 : 200;
  1232. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1233. buf[r->len] = '\0';
  1234. r->body = (char *)buf;
  1235. s_copy(r->url, url, sizeof(r->url));
  1236. if (contains_ci(url, ".json"))
  1237. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1238. return 0;
  1239. }
  1240. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1241. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1242. return -1;
  1243. }
  1244. if (body_len > JS_HTTP_POST_MAX) {
  1245. s_copy(err, "request body too large", (unsigned int)errcap);
  1246. return -1;
  1247. }
  1248. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1249. errcap);
  1250. }
  1251. /* Module source for the engine's loader: the boot script cache first, then
  1252. * one blocking fetch with input pumping disabled (the loader runs inside
  1253. * JavaScript). */
  1254. static char *js_host_load_script(const char *url, unsigned int *len)
  1255. {
  1256. unsigned char *data = 0;
  1257. char err[64];
  1258. int rv;
  1259. fetch_wait_passive++;
  1260. set_status("Loading module...", 0, 0);
  1261. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1262. fetch_wait_passive--;
  1263. if (rv != 0) {
  1264. script_error("Cannot load module", url,
  1265. rv == FETCH_ABORT ? "navigation" : err);
  1266. return 0;
  1267. }
  1268. return (char *)data;
  1269. }
  1270. /* Web Storage lives in /share, outside the page heap that every navigation
  1271. * resets: localStorage per origin for the boot, sessionStorage per origin
  1272. * and browser window. */
  1273. #define JS_ORIGIN_MAX 160
  1274. /* scheme://host[:port] of the page (a local page's whole path). */
  1275. static void js_page_origin(char *origin, unsigned int cap)
  1276. {
  1277. unsigned int i = 0, slashes = 0;
  1278. while (page_url[i] && i + 1 < cap) {
  1279. if (page_url[i] == '/' && ++slashes == 3)
  1280. break;
  1281. origin[i] = page_url[i];
  1282. i++;
  1283. }
  1284. origin[i] = '\0';
  1285. }
  1286. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1287. {
  1288. unsigned int n = 0;
  1289. s_append(out, &n, "/share/bls", cap);
  1290. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1291. }
  1292. static void js_storage_path(int kind, char *out, unsigned int cap)
  1293. {
  1294. char origin[JS_ORIGIN_MAX];
  1295. unsigned int n = 0;
  1296. js_page_origin(origin, sizeof(origin));
  1297. if (!kind) {
  1298. js_origin_path(origin, out, cap);
  1299. return;
  1300. }
  1301. s_append(out, &n, "/share/bss", cap);
  1302. if (kind) {
  1303. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1304. s_append(out, &n, "-", cap);
  1305. }
  1306. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1307. }
  1308. static void persist_mark_origin(const char *origin);
  1309. static int persist_store_lookup(const char *origin, char *out, int cap);
  1310. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1311. {
  1312. char path[48], origin[JS_ORIGIN_MAX];
  1313. int rv;
  1314. js_storage_path(kind, path, sizeof(path));
  1315. if (set) {
  1316. if (kind) {
  1317. if (!set[0] || !strcmp(set, "{}")) {
  1318. u_syscall1(SYS_UNLINK, (int)path);
  1319. return 0;
  1320. }
  1321. } else {
  1322. /* localStorage keeps an explicit "{}" rather than no
  1323. * file: a missing /share file means "not loaded from
  1324. * /data yet", and a cleared store must not come back
  1325. * from the disk copy before it is flushed. */
  1326. if (!set[0])
  1327. set = "{}";
  1328. js_page_origin(origin, sizeof(origin));
  1329. persist_mark_origin(origin);
  1330. }
  1331. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1332. (int)strlen(set)) < 0 ? -1 : 0;
  1333. }
  1334. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1335. if (rv < 0 && !kind) {
  1336. /* First use this boot: the persistent copy on /data. */
  1337. js_page_origin(origin, sizeof(origin));
  1338. rv = persist_store_lookup(origin, out, cap);
  1339. if (rv >= 0)
  1340. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1341. }
  1342. if (rv < 0)
  1343. return -1;
  1344. out[rv] = '\0';
  1345. return rv;
  1346. }
  1347. /* ---- persistence on /data ----
  1348. *
  1349. * /share is the working copy (RAM, shared by every helper and window); the
  1350. * installed disk's /data volume keeps the cookie jar and localStorage
  1351. * across reboots when it is mounted. The browser owns the disk copies: at
  1352. * start it restores the jar into /share, and its main loop writes back
  1353. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1354. * setItem updates costs one FAT write. The helpers only touch /share (they
  1355. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1356. * /data mount every disk access simply fails. Both files are plaintext
  1357. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1358. #define PERSIST_MS 3000u
  1359. #define SHARE_COOKIES "/share/bcookies"
  1360. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1361. #define DATA_STORE "/data/BSTORE.DAT"
  1362. #define DATA_STORE_MAGIC "NBLS1\n"
  1363. #define DATA_STORE_MAX (192u * 1024u)
  1364. #define PERSIST_DIRTY_MAX 8
  1365. static unsigned int persist_due;
  1366. static unsigned int cookie_sum_saved;
  1367. static int cookie_sum_valid;
  1368. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1369. static int persist_ndirty;
  1370. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1371. {
  1372. unsigned int h = 2166136261u, i;
  1373. for (i = 0; i < n; i++)
  1374. h = (h ^ p[i]) * 16777619u;
  1375. return h;
  1376. }
  1377. /* Called once at startup, before any helper runs. */
  1378. static void persist_restore(void)
  1379. {
  1380. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1381. int n;
  1382. if (!jar)
  1383. return;
  1384. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1385. (int)sizeof(struct uhttp_jar));
  1386. if (n != (int)sizeof(struct uhttp_jar)) {
  1387. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1388. (int)sizeof(struct uhttp_jar));
  1389. if (n == (int)sizeof(struct uhttp_jar)) {
  1390. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1391. (int)jar, n);
  1392. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1393. cookie_sum_valid = 1;
  1394. }
  1395. }
  1396. free(jar);
  1397. persist_due = u_ticks_ms() + PERSIST_MS;
  1398. }
  1399. static void persist_mark_origin(const char *origin)
  1400. {
  1401. int i;
  1402. for (i = 0; i < persist_ndirty; i++)
  1403. if (s_eq(persist_dirty[i], origin))
  1404. return;
  1405. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1406. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1407. }
  1408. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1409. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1410. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1411. unsigned int *o_off, unsigned int *o_len,
  1412. unsigned int *d_off, unsigned int *d_len,
  1413. unsigned int *rec_end)
  1414. {
  1415. unsigned int p = *pos, v = 0;
  1416. if (p >= len)
  1417. return 0;
  1418. *o_off = p;
  1419. while (p < len && buf[p] != '\n')
  1420. p++;
  1421. if (p >= len)
  1422. return 0;
  1423. *o_len = p - *o_off;
  1424. p++;
  1425. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1426. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1427. if (p >= len || buf[p] != '\n')
  1428. return 0;
  1429. p++;
  1430. if (v > len - p)
  1431. return 0;
  1432. *d_off = p;
  1433. *d_len = v;
  1434. p += v;
  1435. if (p < len && buf[p] == '\n')
  1436. p++;
  1437. *rec_end = p;
  1438. *pos = p;
  1439. return 1;
  1440. }
  1441. static int store_load(char **out)
  1442. {
  1443. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1444. int n;
  1445. *out = buf;
  1446. if (!buf)
  1447. return -1;
  1448. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1449. (int)DATA_STORE_MAX);
  1450. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1451. !starts_with(buf, DATA_STORE_MAGIC))
  1452. return 0;
  1453. return n;
  1454. }
  1455. static int persist_store_lookup(const char *origin, char *out, int cap)
  1456. {
  1457. char *buf;
  1458. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1459. unsigned int olen = s_len(origin);
  1460. int n = store_load(&buf), rv = -1;
  1461. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1462. &dl, &e)) {
  1463. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1464. if ((int)dl < cap) {
  1465. memcpy(out, buf + d, dl);
  1466. out[dl] = '\0';
  1467. rv = (int)dl;
  1468. }
  1469. break;
  1470. }
  1471. }
  1472. free(buf);
  1473. return rv;
  1474. }
  1475. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1476. static void persist_store_flush(void)
  1477. {
  1478. char *old, *nb, path[48];
  1479. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1480. int n = store_load(&old), i, w;
  1481. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1482. if (n < 0 || !nb) {
  1483. free(old);
  1484. free(nb);
  1485. return;
  1486. }
  1487. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1488. /* Untouched origins first, in their old order. */
  1489. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1490. &dl, &e)) {
  1491. int dirty = 0;
  1492. for (i = 0; i < persist_ndirty; i++)
  1493. if (s_len(persist_dirty[i]) == ol &&
  1494. !memcmp(persist_dirty[i], old + oo, ol))
  1495. dirty = 1;
  1496. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1497. continue;
  1498. memcpy(nb + nn, old + oo, e - oo);
  1499. nn += e - oo;
  1500. }
  1501. /* Then the changed ones (an emptied store is dropped). */
  1502. for (i = 0; i < persist_ndirty; i++) {
  1503. char num[12];
  1504. unsigned int k = 0;
  1505. js_origin_path(persist_dirty[i], path, sizeof(path));
  1506. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1507. (int)DATA_STORE_MAX);
  1508. if (w <= 2) /* missing or "{}" */
  1509. continue;
  1510. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1511. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1512. DATA_STORE_MAX) {
  1513. set_status("Saved site data is full; a site's "
  1514. "localStorage was not saved", 1, 6000);
  1515. continue;
  1516. }
  1517. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1518. nb[nn++] = '\n';
  1519. s_append(nb, &nn, num, DATA_STORE_MAX);
  1520. nb[nn++] = '\n';
  1521. memcpy(nb + nn, old, (unsigned int)w);
  1522. nn += (unsigned int)w;
  1523. nb[nn++] = '\n';
  1524. }
  1525. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1526. persist_ndirty = 0;
  1527. free(old);
  1528. free(nb);
  1529. }
  1530. static void persist_cookies_flush(void)
  1531. {
  1532. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1533. unsigned int sum;
  1534. int n;
  1535. if (!jar)
  1536. return;
  1537. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1538. (int)sizeof(struct uhttp_jar));
  1539. if (n == (int)sizeof(struct uhttp_jar)) {
  1540. sum = persist_sum(jar, (unsigned int)n);
  1541. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1542. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1543. (int)jar, n) >= 0) {
  1544. cookie_sum_saved = sum;
  1545. cookie_sum_valid = 1;
  1546. }
  1547. }
  1548. }
  1549. free(jar);
  1550. }
  1551. /* ---- visit history (URL-bar autocomplete) ----
  1552. *
  1553. * Every page that finishes loading is recorded with its title, a visit
  1554. * count and a stamp: a counter that only grows and travels with the file,
  1555. * so it orders visits across windows and boots without a wall clock. The
  1556. * table lives in BSS, because the page heap is reset on every navigation.
  1557. * The boot's browser windows share it through /share/bhist (rewritten on
  1558. * every visit) and it is persisted to /data/BHIST.DAT from persist_tick()
  1559. * at most every PERSIST_MS, like the cookie jar. A save re-reads
  1560. * /share/bhist and merges it first, so two windows add to one history
  1561. * instead of overwriting each other. File format: "NBHIST1\n", then
  1562. * "<visits> <stamp> <url>\t<title>\n" per entry. Plaintext, like the
  1563. * other browser state on /data. */
  1564. #define HIST_MAX 128
  1565. #define HIST_URL_MAX 512
  1566. #define HIST_FILE_MAX (HIST_MAX * (HIST_URL_MAX + BR_TITLE_MAX + 24) + 16)
  1567. #define HIST_MAGIC "NBHIST1\n"
  1568. #define SHARE_HIST "/share/bhist"
  1569. #define DATA_HIST "/data/BHIST.DAT"
  1570. #define HIST_FORGET_MAX 16
  1571. struct hist_ent {
  1572. unsigned int visits;
  1573. unsigned int stamp;
  1574. char url[HIST_URL_MAX];
  1575. char title[BR_TITLE_MAX];
  1576. };
  1577. static struct hist_ent hist_tab[HIST_MAX];
  1578. static int hist_n;
  1579. static int hist_share_dirty, hist_data_dirty;
  1580. /* URLs removed in this process: a merge must not bring them back. */
  1581. static unsigned int hist_forgot[HIST_FORGET_MAX];
  1582. static int hist_nforgot;
  1583. static unsigned int hist_hash(const char *s)
  1584. {
  1585. return persist_sum((const unsigned char *)s, s_len(s));
  1586. }
  1587. static int hist_is_forgotten(const char *url)
  1588. {
  1589. unsigned int h = hist_hash(url);
  1590. int i;
  1591. for (i = 0; i < hist_nforgot; i++)
  1592. if (hist_forgot[i] == h)
  1593. return 1;
  1594. return 0;
  1595. }
  1596. static int hist_find(const char *url)
  1597. {
  1598. int i;
  1599. for (i = 0; i < hist_n; i++)
  1600. if (s_eq(hist_tab[i].url, url))
  1601. return i;
  1602. return -1;
  1603. }
  1604. static unsigned int hist_next_stamp(void)
  1605. {
  1606. unsigned int m = 0;
  1607. int i;
  1608. for (i = 0; i < hist_n; i++)
  1609. if (hist_tab[i].stamp > m)
  1610. m = hist_tab[i].stamp;
  1611. return m + 1;
  1612. }
  1613. /* Copy a title, turning tabs/newlines (the file separators) into spaces. */
  1614. static void hist_copy_title(char *d, const char *s, unsigned int n)
  1615. {
  1616. unsigned int i;
  1617. for (i = 0; i + 1 < BR_TITLE_MAX && i < n && s[i]; i++)
  1618. d[i] = (unsigned char)s[i] < 0x20 ? ' ' : s[i];
  1619. d[i] = '\0';
  1620. }
  1621. /* Insert or update an entry; the newer stamp wins the title, the larger
  1622. * visit count is kept. A full table evicts the least recent entry, unless
  1623. * the new one is older still. Returns NULL when nothing was stored. */
  1624. static struct hist_ent *hist_put(const char *url, const char *title,
  1625. unsigned int visits, unsigned int stamp)
  1626. {
  1627. struct hist_ent *e;
  1628. int i = hist_find(url);
  1629. if (i < 0) {
  1630. if (hist_n < HIST_MAX) {
  1631. i = hist_n++;
  1632. } else {
  1633. int j;
  1634. i = 0;
  1635. for (j = 1; j < hist_n; j++)
  1636. if (hist_tab[j].stamp < hist_tab[i].stamp)
  1637. i = j;
  1638. if (hist_tab[i].stamp >= stamp)
  1639. return 0;
  1640. }
  1641. e = &hist_tab[i];
  1642. e->visits = 0;
  1643. e->stamp = 0;
  1644. e->title[0] = '\0';
  1645. s_copy(e->url, url, sizeof(e->url));
  1646. }
  1647. e = &hist_tab[i];
  1648. if (visits > e->visits)
  1649. e->visits = visits;
  1650. if (stamp >= e->stamp) {
  1651. e->stamp = stamp;
  1652. if (title && title[0])
  1653. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1654. } else if (!e->title[0] && title) {
  1655. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1656. }
  1657. return e;
  1658. }
  1659. static unsigned int hist_parse_dec(const char *b, int n, int *pos)
  1660. {
  1661. unsigned int v = 0;
  1662. while (*pos < n && b[*pos] >= '0' && b[*pos] <= '9')
  1663. v = v * 10 + (unsigned int)(b[(*pos)++] - '0');
  1664. return v;
  1665. }
  1666. static void hist_merge_buf(const char *b, int n)
  1667. {
  1668. int pos = (int)s_len(HIST_MAGIC);
  1669. char url[HIST_URL_MAX], title[BR_TITLE_MAX];
  1670. if (n < pos || memcmp(b, HIST_MAGIC, (unsigned int)pos))
  1671. return;
  1672. while (pos < n) {
  1673. unsigned int visits, stamp, ul = 0;
  1674. int t0, t1;
  1675. visits = hist_parse_dec(b, n, &pos);
  1676. if (pos < n && b[pos] == ' ')
  1677. pos++;
  1678. stamp = hist_parse_dec(b, n, &pos);
  1679. if (pos < n && b[pos] == ' ')
  1680. pos++;
  1681. while (pos < n && b[pos] != '\t' && b[pos] != '\n') {
  1682. if (ul + 1 < sizeof(url))
  1683. url[ul++] = b[pos];
  1684. pos++;
  1685. }
  1686. url[ul] = '\0';
  1687. t0 = t1 = pos < n && b[pos] == '\t' ? pos + 1 : pos;
  1688. while (t1 < n && b[t1] != '\n')
  1689. t1++;
  1690. pos = t1 + 1;
  1691. hist_copy_title(title, b + t0, (unsigned int)(t1 - t0));
  1692. if (ul && ul + 1 < sizeof(url) && !hist_is_forgotten(url))
  1693. hist_put(url, title, visits, stamp);
  1694. }
  1695. }
  1696. static int hist_serialize(char *b, unsigned int cap)
  1697. {
  1698. unsigned int n = 0;
  1699. int i;
  1700. s_append(b, &n, HIST_MAGIC, cap);
  1701. for (i = 0; i < hist_n; i++) {
  1702. struct hist_ent *e = &hist_tab[i];
  1703. if (n + s_len(e->url) + s_len(e->title) + 26 >= cap)
  1704. break;
  1705. s_append_dec(b, &n, e->visits, cap);
  1706. b[n++] = ' ';
  1707. s_append_dec(b, &n, e->stamp, cap);
  1708. b[n++] = ' ';
  1709. s_append(b, &n, e->url, cap);
  1710. b[n++] = '\t';
  1711. s_append(b, &n, e->title, cap);
  1712. b[n++] = '\n';
  1713. }
  1714. return (int)n;
  1715. }
  1716. /* Merge /share/bhist, then write it back (and /data when asked). */
  1717. static void hist_sync(int to_data)
  1718. {
  1719. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1720. int n;
  1721. if (!b)
  1722. return;
  1723. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1724. (int)HIST_FILE_MAX);
  1725. if (n > 0)
  1726. hist_merge_buf(b, n);
  1727. n = hist_serialize(b, HIST_FILE_MAX);
  1728. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1729. hist_share_dirty = 0;
  1730. if (to_data) {
  1731. /* No /data mount: the write fails, and there is nothing to
  1732. * retry until the next visit. */
  1733. u_syscall3(SYS_WRITE_FILE, (int)DATA_HIST, (int)b, n);
  1734. hist_data_dirty = 0;
  1735. }
  1736. free(b);
  1737. }
  1738. /* Startup: the boot's shared copy, else the saved one from /data. */
  1739. static void hist_load(void)
  1740. {
  1741. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1742. int n;
  1743. if (!b)
  1744. return;
  1745. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1746. (int)HIST_FILE_MAX);
  1747. if (n <= 0) {
  1748. n = u_syscall3(SYS_READ_FILE, (int)DATA_HIST, (int)b,
  1749. (int)HIST_FILE_MAX);
  1750. if (n > 0)
  1751. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1752. }
  1753. if (n > 0)
  1754. hist_merge_buf(b, n);
  1755. free(b);
  1756. }
  1757. static void hist_visit(const char *url, const char *title)
  1758. {
  1759. struct hist_ent *e;
  1760. unsigned int i;
  1761. if (!url[0] || starts_with(url, "about:") ||
  1762. s_len(url) >= HIST_URL_MAX)
  1763. return;
  1764. for (i = 0; url[i]; i++)
  1765. if ((unsigned char)url[i] < 0x20)
  1766. return;
  1767. e = hist_put(url, title, 0, hist_next_stamp());
  1768. if (!e)
  1769. return;
  1770. e->visits++;
  1771. hist_data_dirty = 1;
  1772. hist_sync(0);
  1773. }
  1774. static void hist_forget(int i)
  1775. {
  1776. if (i < 0 || i >= hist_n)
  1777. return;
  1778. if (hist_nforgot < HIST_FORGET_MAX)
  1779. hist_forgot[hist_nforgot++] = hist_hash(hist_tab[i].url);
  1780. hist_n--;
  1781. for (; i < hist_n; i++)
  1782. hist_tab[i] = hist_tab[i + 1];
  1783. hist_data_dirty = 1;
  1784. hist_sync(0);
  1785. }
  1786. static void hist_tick(void)
  1787. {
  1788. if (hist_share_dirty || hist_data_dirty)
  1789. hist_sync(hist_data_dirty);
  1790. }
  1791. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1792. static void persist_tick(void)
  1793. {
  1794. unsigned int now = u_ticks_ms();
  1795. if ((int)(now - persist_due) < 0)
  1796. return;
  1797. persist_due = now + PERSIST_MS;
  1798. persist_cookies_flush();
  1799. if (persist_ndirty)
  1800. persist_store_flush();
  1801. hist_tick();
  1802. }
  1803. /* <link rel="modulepreload">: download the page's module graph on all
  1804. * helpers at once into the boot script cache, before any script runs. The
  1805. * engine's module loader is sequential (one blocking fetch per import), so
  1806. * without this a Vite app with a dozen chunks pays every round trip in a
  1807. * row. Failures are ignored; the loader fetches what is missing. */
  1808. #define MODULE_PRELOAD_MAX 24
  1809. static void prefetch_module_preloads(void)
  1810. {
  1811. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1812. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1813. unsigned int count = 0, next = 0, done = 0, i;
  1814. char err[64];
  1815. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1816. struct br_node *nd = &doc.nodes[i];
  1817. const char *rel, *href;
  1818. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1819. continue;
  1820. rel = br_rel(&doc, i);
  1821. href = br_href(&doc, i);
  1822. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1823. continue;
  1824. if (resolve_link(page_url, href, urls[count],
  1825. sizeof(urls[count])) != 0 ||
  1826. urls[count][0] == '/' || script_cache_has(urls[count]))
  1827. continue;
  1828. slot[count++] = 0;
  1829. }
  1830. if (!count)
  1831. return;
  1832. set_status("Loading modules...", 0, 0);
  1833. while (done < count) {
  1834. struct fetch_worker *w;
  1835. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1836. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1837. 0, 0, 0, err,
  1838. sizeof(err)) != 0) {
  1839. fetch_worker_release(w);
  1840. done++;
  1841. } else {
  1842. slot[next] = w;
  1843. }
  1844. next++;
  1845. }
  1846. worker_wait_ui();
  1847. if (cancel_fetch || pending_action) {
  1848. fetch_workers_cancel_busy();
  1849. return;
  1850. }
  1851. for (i = 0; i < next; i++) {
  1852. unsigned char *body;
  1853. int rv, tr = 0;
  1854. if (!slot[i])
  1855. continue;
  1856. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1857. if (rv == 0)
  1858. continue;
  1859. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1860. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1861. if (body) {
  1862. rv = fetch_worker_read_body(slot[i], body,
  1863. BR_SCRIPT_MAX, image_io_buf,
  1864. BR_PAGE_COMP_MAX, &tr, err,
  1865. sizeof(err));
  1866. if (rv > 0 && !tr)
  1867. script_cache_put(urls[i], body,
  1868. (unsigned int)rv);
  1869. free(body);
  1870. }
  1871. fetch_worker_release(slot[i]);
  1872. slot[i] = 0;
  1873. done++;
  1874. }
  1875. u_sleep_ms(10);
  1876. }
  1877. }
  1878. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1879. * submitted to helper workers ahead of time, but scripts still execute in
  1880. * document order. */
  1881. #define SCRIPT_INLINE 0
  1882. #define SCRIPT_LOCAL 1
  1883. #define SCRIPT_REMOTE 2
  1884. #define SCRIPT_ERROR 3
  1885. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1886. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1887. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1888. static void script_submit_window(unsigned int *next, char *err,
  1889. unsigned int errcap)
  1890. {
  1891. while (*next < doc.nscripts) {
  1892. struct fetch_worker *w;
  1893. if (script_kind[*next] != SCRIPT_REMOTE) {
  1894. (*next)++;
  1895. continue;
  1896. }
  1897. w = fetch_worker_alloc();
  1898. if (!w)
  1899. return;
  1900. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1901. 0, 0, 0, 0, err, errcap) != 0) {
  1902. fetch_worker_release(w);
  1903. script_kind[*next] = SCRIPT_ERROR;
  1904. (*next)++;
  1905. continue;
  1906. }
  1907. script_slot[*next] = w;
  1908. (*next)++;
  1909. }
  1910. }
  1911. /* Run the page's scripts in document order. External bodies are prefetched
  1912. * in parallel so downloading script N+1 overlaps executing script N; inline
  1913. * bodies are copied because the engine needs NUL-terminated text. */
  1914. static void run_page_scripts(void)
  1915. {
  1916. struct js_browser_host host;
  1917. unsigned int i, next = 0;
  1918. char err[64], ferr[64];
  1919. if (!doc.nscripts)
  1920. return;
  1921. host.status = js_host_status;
  1922. host.report = js_host_report;
  1923. host.navigate = js_host_navigate;
  1924. host.changed = js_host_changed;
  1925. host.rect = js_host_rect;
  1926. host.form_value = js_host_form_value;
  1927. host.form_checked = js_host_form_checked;
  1928. host.form_selected = js_host_form_selected;
  1929. host.form_set_value = js_host_form_set_value;
  1930. host.form_set_checked = js_host_form_set_checked;
  1931. host.form_set_selected = js_host_form_set_selected;
  1932. host.form_elements = js_host_form_elements;
  1933. host.form_submit = js_host_form_submit;
  1934. host.form_reset = js_host_form_reset;
  1935. host.click = js_host_click;
  1936. host.computed = js_host_computed;
  1937. host.http = js_host_http;
  1938. host.load_script = js_host_load_script;
  1939. host.storage = js_host_storage;
  1940. host.set_hash = js_host_set_hash;
  1941. host.page_url = page_url;
  1942. host.width = ui.w;
  1943. host.height = ui.h;
  1944. if (js_browser_start(&doc, &host) != 0) {
  1945. js_host_status("JavaScript: out of memory", 1);
  1946. return;
  1947. }
  1948. resize_sent_w = -1;
  1949. resize_pending = 0;
  1950. prefetch_module_preloads();
  1951. for (i = 0; i < doc.nscripts; i++) {
  1952. struct br_script *script = &doc.scripts[i];
  1953. const char *src_attr = script->src_off ?
  1954. doc.attrs + script->src_off : "";
  1955. script_slot[i] = 0;
  1956. if (!script->src_off) {
  1957. script_kind[i] = SCRIPT_INLINE;
  1958. continue;
  1959. }
  1960. if (!src_attr[0] ||
  1961. resolve_link(page_url, src_attr, script_urls[i],
  1962. sizeof(script_urls[i])) != 0) {
  1963. script_urls[i][0] = '\0';
  1964. script_kind[i] = SCRIPT_ERROR;
  1965. continue;
  1966. }
  1967. if (script_urls[i][0] == '/' ||
  1968. script_cache_has(script_urls[i]))
  1969. script_kind[i] = SCRIPT_LOCAL;
  1970. else
  1971. script_kind[i] = SCRIPT_REMOTE;
  1972. }
  1973. script_submit_window(&next, ferr, sizeof(ferr));
  1974. for (i = 0; i < doc.nscripts; i++) {
  1975. struct br_script *script = &doc.scripts[i];
  1976. /* document.currentScript for classic scripts (null for modules) */
  1977. js_browser_set_current_script(script->module ? 0 : script->node);
  1978. if (script_kind[i] == SCRIPT_INLINE) {
  1979. unsigned int off = script->off;
  1980. unsigned int len = script->len;
  1981. unsigned int k;
  1982. char *src = (char *)malloc(len + 1);
  1983. if (!src) {
  1984. js_host_status("JavaScript: out of memory", 1);
  1985. break;
  1986. }
  1987. for (k = 0; k < len; k++)
  1988. src[k] = doc.script_src[off + k];
  1989. src[len] = '\0';
  1990. if (script->module) {
  1991. /* A distinct module name per inline module
  1992. * (QuickJS registers modules by name); the
  1993. * fragment keeps relative imports resolving
  1994. * against the page. */
  1995. char mname[BR_URL_MAX + 16];
  1996. unsigned int mn = 0;
  1997. s_append(mname, &mn, page_url, sizeof(mname));
  1998. s_append(mname, &mn, "#module", sizeof(mname));
  1999. s_append_dec(mname, &mn, i, sizeof(mname));
  2000. js_browser_run_module(src, mname);
  2001. } else {
  2002. js_browser_run(src, page_url);
  2003. }
  2004. free(src);
  2005. } else if (script->src_off) {
  2006. const char *src_attr = doc.attrs + script->src_off;
  2007. if (script_kind[i] == SCRIPT_ERROR) {
  2008. script_error("Cannot load script", src_attr,
  2009. script_urls[i][0] ?
  2010. "network busy" :
  2011. "unsupported URL");
  2012. continue;
  2013. }
  2014. if (script_kind[i] == SCRIPT_LOCAL) {
  2015. unsigned char *data = 0;
  2016. unsigned int len = 0;
  2017. int rv;
  2018. set_status("Loading script...", 0, 0);
  2019. rv = fetch_script_text(script_urls[i], &data,
  2020. &len, err, sizeof(err));
  2021. if (rv == FETCH_ABORT)
  2022. break;
  2023. if (rv != 0) {
  2024. script_error("Cannot load script",
  2025. script_urls[i], err);
  2026. continue;
  2027. }
  2028. if (script->module)
  2029. js_browser_run_module(
  2030. (const char *)data,
  2031. script_urls[i]);
  2032. else
  2033. js_browser_run((const char *)data,
  2034. script_urls[i]);
  2035. free(data);
  2036. } else {
  2037. struct fetch_worker *w = script_slot[i];
  2038. unsigned char *body = 0;
  2039. int tr = 0, rv;
  2040. if (!w) {
  2041. w = fetch_worker_alloc();
  2042. if (!w)
  2043. continue;
  2044. if (fetch_worker_submit(w,
  2045. script_urls[i],
  2046. BR_SCRIPT_MAX,
  2047. 0, 0, 0, 0, err,
  2048. sizeof(err)) != 0) {
  2049. fetch_worker_release(w);
  2050. script_kind[i] = SCRIPT_ERROR;
  2051. if (i == next)
  2052. next++;
  2053. continue;
  2054. }
  2055. script_slot[i] = w;
  2056. if (i == next)
  2057. next++;
  2058. }
  2059. set_status("Loading script...", 0, 0);
  2060. rv = fetch_worker_wait(w, err, sizeof(err));
  2061. if (rv == FETCH_ABORT) {
  2062. fetch_workers_stop_all();
  2063. break;
  2064. }
  2065. /* The body gets its own buffer (scripts are up
  2066. * to 2 MB); image_io_buf takes the gzip
  2067. * stream. */
  2068. body = rv == 0 ? (unsigned char *)malloc(
  2069. BR_SCRIPT_MAX + 1) : 0;
  2070. if (body)
  2071. rv = fetch_worker_read_body(w, body,
  2072. BR_SCRIPT_MAX, image_io_buf,
  2073. BR_PAGE_COMP_MAX, &tr, err,
  2074. sizeof(err));
  2075. else {
  2076. if (rv == 0)
  2077. s_copy(err, "out of memory",
  2078. sizeof(err));
  2079. rv = -1;
  2080. }
  2081. fetch_worker_release(w);
  2082. script_slot[i] = 0;
  2083. script_submit_window(&next, ferr, sizeof(ferr));
  2084. if (rv <= 0)
  2085. script_error("Cannot load script",
  2086. script_urls[i], err);
  2087. else if (tr || (unsigned int)rv >=
  2088. BR_SCRIPT_MAX)
  2089. script_error("Cannot load script",
  2090. script_urls[i],
  2091. "script is too large");
  2092. else {
  2093. body[rv] = '\0';
  2094. script_cache_put(script_urls[i], body,
  2095. (unsigned int)rv);
  2096. if (script->module)
  2097. js_browser_run_module(
  2098. (const char *)body,
  2099. script_urls[i]);
  2100. else
  2101. js_browser_run(
  2102. (const char *)body,
  2103. script_urls[i]);
  2104. }
  2105. free(body);
  2106. }
  2107. }
  2108. if (pending_action)
  2109. break;
  2110. }
  2111. js_browser_set_current_script(0);
  2112. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  2113. * load_home() stop it before the next navigation. */
  2114. if (doc.scripts_truncated && !js_last_error)
  2115. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  2116. 1);
  2117. }
  2118. /* ---- images ---- */
  2119. static void image_reset(void)
  2120. {
  2121. int i;
  2122. for (i = 0; i < BR_MAX_IMAGES; i++) {
  2123. images[i].state = 0;
  2124. images[i].native_w = images[i].native_h = 0;
  2125. images[i].err[0] = '\0';
  2126. /* heap_clear() ran before us, so these pointers are stale: drop
  2127. * them without calling free(). */
  2128. memset(&images[i].disp, 0, sizeof(images[i].disp));
  2129. images[i].disp_pixels = 0;
  2130. images[i].disp_last = 0;
  2131. }
  2132. image_count = 0;
  2133. image_pixels = 0;
  2134. image_disp_pixels = 0;
  2135. image_disp_clock = 0;
  2136. memset(img_stat_log, 0, sizeof(img_stat_log));
  2137. img_stat_log_len = 0;
  2138. img_stat_start = 0;
  2139. img_stat_wall = 0;
  2140. img_stat_net = img_stat_open = img_stat_first = 0;
  2141. img_stat_io = img_stat_dec = img_stat_scale = 0;
  2142. img_stat_paint = img_stat_reflow = 0;
  2143. img_stat_bytes = 0;
  2144. img_stat_n = 0;
  2145. img_last_dec_ms = img_last_scale_ms = 0;
  2146. img_repaint_ms = 0;
  2147. img_repaint_pending = 0;
  2148. preload_active = 0;
  2149. preload_pending = 0;
  2150. preload_wait = 0;
  2151. preload_node = 0;
  2152. preload_loaded = 0;
  2153. }
  2154. /* Ask for a repaint, but not more often than BR_IMG_REPAINT_MS while images
  2155. * are arriving. The main loop draws once per dirty frame; without this a
  2156. * page of N images did N full layout+paint passes. */
  2157. static void image_repaint(void)
  2158. {
  2159. unsigned int now = u_ticks_ms();
  2160. if (!img_repaint_ms || (now - img_repaint_ms) >= BR_IMG_REPAINT_MS) {
  2161. img_repaint_ms = now;
  2162. img_repaint_pending = 0;
  2163. ngui_invalidate(&ui);
  2164. } else {
  2165. img_repaint_pending = 1;
  2166. }
  2167. }
  2168. static void image_disp_drop(struct br_image *bi)
  2169. {
  2170. if (bi->disp.px)
  2171. free(bi->disp.px);
  2172. if (bi->disp.alpha)
  2173. free(bi->disp.alpha);
  2174. memset(&bi->disp, 0, sizeof(bi->disp));
  2175. if (bi->disp_pixels) {
  2176. if (image_disp_pixels >= bi->disp_pixels)
  2177. image_disp_pixels -= bi->disp_pixels;
  2178. bi->disp_pixels = 0;
  2179. }
  2180. }
  2181. /* Free the least recently used display caches until need pixels fit. The
  2182. * source bitmap (bi->img) is never evicted; a later draw rescales it again. */
  2183. static int image_disp_room(unsigned int need)
  2184. {
  2185. while (image_disp_pixels + need > BR_IMG_DISP_BUDGET) {
  2186. unsigned int oldest = ~0u;
  2187. int i, victim = -1;
  2188. for (i = 0; i < image_count; i++) {
  2189. if (!images[i].disp.px)
  2190. continue;
  2191. if (images[i].disp_last < oldest) {
  2192. oldest = images[i].disp_last;
  2193. victim = i;
  2194. }
  2195. }
  2196. if (victim < 0)
  2197. return -1;
  2198. image_disp_drop(&images[victim]);
  2199. }
  2200. return 0;
  2201. }
  2202. /* Return a bitmap at exactly dw x dh, building it once from the capped source
  2203. * bitmap. Callers then draw with scale 1 and img_draw's copy fast path. */
  2204. static struct img_image *image_display_get(struct br_image *bi, int dw, int dh)
  2205. {
  2206. struct img_blit b;
  2207. unsigned int px;
  2208. if (!bi || bi->state != 1 || !bi->img.px || dw < 1 || dh < 1)
  2209. return 0;
  2210. if (dw == (int)bi->img.w && dh == (int)bi->img.h)
  2211. return &bi->img;
  2212. if (dw > 4096 || dh > 4096)
  2213. return &bi->img;
  2214. if (bi->disp.px && bi->disp.w == (unsigned int)dw &&
  2215. bi->disp.h == (unsigned int)dh) {
  2216. bi->disp_last = ++image_disp_clock;
  2217. return &bi->disp;
  2218. }
  2219. px = (unsigned int)dw * (unsigned int)dh;
  2220. if (px > BR_IMG_DISP_BUDGET || image_disp_room(px) != 0)
  2221. return &bi->img;
  2222. image_disp_drop(bi);
  2223. bi->disp.px = (unsigned short *)malloc(px * 2u);
  2224. if (!bi->disp.px)
  2225. return &bi->img;
  2226. if (bi->img.alpha) {
  2227. bi->disp.alpha = (unsigned char *)malloc(px);
  2228. if (!bi->disp.alpha) {
  2229. free(bi->disp.px);
  2230. bi->disp.px = 0;
  2231. return &bi->img;
  2232. }
  2233. }
  2234. bi->disp.w = (unsigned int)dw;
  2235. bi->disp.h = (unsigned int)dh;
  2236. bi->disp.format = bi->img.format;
  2237. bi->disp.flags = 0;
  2238. memset(&b, 0, sizeof(b));
  2239. b.dst = bi->disp.px;
  2240. b.dst_w = dw;
  2241. b.dst_h = dh;
  2242. b.clip_w = dw;
  2243. b.clip_h = dh;
  2244. b.scale = ((unsigned int)dw << 16) / bi->img.w;
  2245. b.dst_a = bi->disp.alpha;
  2246. b.flags = bi->disp.alpha ? IMG_BLIT_SAVE_ALPHA : 0;
  2247. img_draw(&bi->img, &b);
  2248. bi->disp_pixels = px;
  2249. image_disp_pixels += px;
  2250. bi->disp_last = ++image_disp_clock;
  2251. return &bi->disp;
  2252. }
  2253. /* Decode into the shared arena, then copy/scale the result into a display
  2254. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  2255. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  2256. * pixels. Transparent edges are composited over white. */
  2257. /* One decode scratch arena per page, reused across images. Allocating and
  2258. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  2259. * each small display bitmap landed in the hole the previous arena left, so
  2260. * the next arena no longer fit and the heap ratcheted up until an app
  2261. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  2262. * still released right after their one image. */
  2263. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  2264. static unsigned char *decode_arena_get(unsigned int bytes)
  2265. {
  2266. if (decode_arena && decode_arena_size >= bytes)
  2267. return decode_arena;
  2268. free(decode_arena);
  2269. decode_arena = (unsigned char *)malloc(bytes);
  2270. decode_arena_size = decode_arena ? bytes : 0;
  2271. return decode_arena;
  2272. }
  2273. static void decode_arena_put(void)
  2274. {
  2275. if (decode_arena_size > DECODE_ARENA_KEEP) {
  2276. free(decode_arena);
  2277. decode_arena = 0;
  2278. decode_arena_size = 0;
  2279. }
  2280. }
  2281. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  2282. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  2283. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  2284. static int svg_text_sniff(const unsigned char *d, unsigned int len);
  2285. static int svg_decode_image(const unsigned char *data, unsigned int len,
  2286. struct br_image *bi, int box_w, int box_h);
  2287. static int decode_image_data(const unsigned char *data, unsigned int len,
  2288. struct br_image *bi, int box_w, int box_h,
  2289. int fit_w, int fit_h)
  2290. {
  2291. struct img_info info;
  2292. struct img_options opt;
  2293. struct img_mem mem;
  2294. struct img_image decoded;
  2295. unsigned char *arena;
  2296. unsigned int est, bytes, i;
  2297. unsigned int t0;
  2298. unsigned short *px;
  2299. unsigned char *alpha = 0;
  2300. int dw, dh, r;
  2301. bi->url_hash = 0;
  2302. img_last_dec_ms = 0;
  2303. img_last_scale_ms = 0;
  2304. if (img_sniff(data, len, &info) != 0) {
  2305. if (svg_text_sniff(data, len))
  2306. return svg_decode_image(data, len, bi,
  2307. box_w > 0 && box_h > 0 ? box_w : fit_w,
  2308. box_w > 0 && box_h > 0 ? box_h : fit_h);
  2309. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  2310. return -1;
  2311. }
  2312. est = img_estimate(&info);
  2313. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  2314. s_copy(bi->err, "image too large", sizeof(bi->err));
  2315. return -1;
  2316. }
  2317. arena = decode_arena_get(est);
  2318. if (!arena) {
  2319. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2320. return -1;
  2321. }
  2322. img_mem_init(&mem, arena, est);
  2323. opt.max_pixels = BR_IMG_PIX_MAX;
  2324. opt.max_w = fit_w > 0 ? (unsigned int)fit_w :
  2325. (box_w > 0 ? (unsigned int)box_w : 0);
  2326. opt.max_h = fit_h > 0 ? (unsigned int)fit_h :
  2327. (box_h > 0 ? (unsigned int)box_h : 0);
  2328. t0 = u_ticks_ms();
  2329. r = img_decode(data, len, &opt, &mem, &decoded);
  2330. img_last_dec_ms = u_ticks_ms() - t0;
  2331. if (r != 0) {
  2332. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  2333. goto fail;
  2334. }
  2335. if (decoded.w == 0 || decoded.h == 0) {
  2336. s_copy(bi->err, "empty image", sizeof(bi->err));
  2337. goto fail;
  2338. }
  2339. /* The JPEG decoder may have reduced the IDCT output; the layout still
  2340. * needs the intrinsic dimensions from the header. */
  2341. bi->native_w = info.width ? (int)info.width : (int)decoded.w;
  2342. bi->native_h = info.height ? (int)info.height : (int)decoded.h;
  2343. dw = (int)decoded.w;
  2344. dh = (int)decoded.h;
  2345. /* An <img> with a CSS/attribute box only ever needs a bitmap that big:
  2346. * decoding 1200x800 and then box-filtering it to 1000x666, only to
  2347. * paint it at 400x267, doubled the decode-time scaling work. cap both
  2348. * axes with one scale so the aspect ratio is preserved. */
  2349. if (fit_w > 0 || fit_h > 0) {
  2350. unsigned int scw = fit_w > 0 ?
  2351. ((unsigned int)fit_w << 16) / decoded.w : ~0u;
  2352. unsigned int sch = fit_h > 0 ?
  2353. ((unsigned int)fit_h << 16) / decoded.h : ~0u;
  2354. unsigned int sc = scw < sch ? scw : sch;
  2355. if (sc < 0x10000u) {
  2356. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2357. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2358. if (dw < 1)
  2359. dw = 1;
  2360. if (dh < 1)
  2361. dh = 1;
  2362. }
  2363. }
  2364. if (box_w > 0 && box_h > 0) {
  2365. /* cover: scale so both box sides are filled, never up */
  2366. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  2367. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  2368. unsigned int sc = sw > sh ? sw : sh;
  2369. if (sc < 0x10000u) {
  2370. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2371. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2372. }
  2373. }
  2374. if (dw > BR_IMG_LAYOUT_W) {
  2375. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  2376. dw = BR_IMG_LAYOUT_W;
  2377. }
  2378. if (dh < 1)
  2379. dh = 1;
  2380. if (dw < 1)
  2381. dw = 1;
  2382. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  2383. BR_IMG_PIXEL_BUDGET) {
  2384. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  2385. goto fail;
  2386. }
  2387. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  2388. px = (unsigned short *)malloc(bytes);
  2389. if (!px) {
  2390. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2391. goto fail;
  2392. }
  2393. /* Keep the alpha plane for the scaled image so transparent logos and
  2394. * icons composite over the page instead of the browser's dark theme
  2395. * background. Very large alpha images stay flattened to bound the
  2396. * heap use. */
  2397. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  2398. alpha = (unsigned char *)malloc((unsigned int)dw *
  2399. (unsigned int)dh);
  2400. if (alpha) {
  2401. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2402. alpha[i] = 255;
  2403. }
  2404. }
  2405. /* With an alpha plane the colour under transparent pixels only shows
  2406. * through partially covered edge pixels of the downscale: use white,
  2407. * as documented above, not the dark browser theme (which left a dark
  2408. * fringe around scaled app icons). */
  2409. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2410. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  2411. {
  2412. struct img_blit b;
  2413. b.dst = px;
  2414. b.dst_w = dw;
  2415. b.dst_h = dh;
  2416. b.clip_x = 0;
  2417. b.clip_y = 0;
  2418. b.clip_w = dw;
  2419. b.clip_h = dh;
  2420. b.x = 0;
  2421. b.y = 0;
  2422. b.scale = ((unsigned int)dw << 16) / decoded.w;
  2423. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  2424. b.bg2 = b.bg;
  2425. b.dst_a = alpha;
  2426. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  2427. t0 = u_ticks_ms();
  2428. img_draw(&decoded, &b);
  2429. img_last_scale_ms = u_ticks_ms() - t0;
  2430. }
  2431. bi->img.format = decoded.format;
  2432. bi->img.w = (unsigned int)dw;
  2433. bi->img.h = (unsigned int)dh;
  2434. bi->img.px = px;
  2435. bi->img.alpha = alpha;
  2436. bi->img.flags = 0;
  2437. bi->state = 1;
  2438. image_pixels += (unsigned int)dw * (unsigned int)dh;
  2439. decode_arena_put();
  2440. return 0;
  2441. fail:
  2442. decode_arena_put();
  2443. return -1;
  2444. }
  2445. /* ---- URL / local path handling ---- */
  2446. static int is_http(const char *s)
  2447. {
  2448. return starts_with(s, "http://") || starts_with(s, "https://");
  2449. }
  2450. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  2451. static int normalize_abs(const char *in, char *out, unsigned int cap)
  2452. {
  2453. char seg[64];
  2454. unsigned int i = 0, o = 1;
  2455. int depth = 0;
  2456. int trailing;
  2457. if (!in || in[0] != '/' || cap < 2)
  2458. return -1;
  2459. trailing = 0;
  2460. {
  2461. unsigned int n = s_len(in);
  2462. if (n > 1 && in[n - 1] == '/')
  2463. trailing = 1;
  2464. }
  2465. out[0] = '/';
  2466. while (in[i]) {
  2467. unsigned int n = 0;
  2468. while (in[i] == '/')
  2469. i++;
  2470. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  2471. if (n + 1 < sizeof(seg))
  2472. seg[n++] = in[i];
  2473. i++;
  2474. }
  2475. seg[n] = '\0';
  2476. if (n == 0)
  2477. break;
  2478. if (s_eq(seg, "."))
  2479. continue;
  2480. if (s_eq(seg, "..")) {
  2481. if (depth > 0) {
  2482. while (o > 1 && out[o - 1] != '/')
  2483. o--;
  2484. if (o > 1)
  2485. o--;
  2486. depth--;
  2487. }
  2488. continue;
  2489. }
  2490. if (o > 1) {
  2491. if (o + 1 >= cap)
  2492. return -1;
  2493. out[o++] = '/';
  2494. }
  2495. if (o + n + 1 >= cap)
  2496. return -1;
  2497. {
  2498. unsigned int j;
  2499. for (j = 0; j < n; j++)
  2500. out[o++] = seg[j];
  2501. }
  2502. depth++;
  2503. }
  2504. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2505. if (o + 1 >= cap)
  2506. return -1;
  2507. out[o++] = '/';
  2508. }
  2509. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2510. if (in[i] == '?' || in[i] == '#') {
  2511. while (in[i]) {
  2512. if (o + 1 >= cap)
  2513. return -1;
  2514. out[o++] = in[i++];
  2515. }
  2516. }
  2517. out[o] = '\0';
  2518. return 0;
  2519. }
  2520. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2521. {
  2522. char joined[BR_URL_MAX];
  2523. if (!in || !in[0]) {
  2524. s_copy(out, cwd[0] ? cwd : "/", cap);
  2525. return;
  2526. }
  2527. if (in[0] == '/') {
  2528. if (normalize_abs(in, out, cap) != 0)
  2529. s_copy(out, in, cap);
  2530. return;
  2531. }
  2532. {
  2533. unsigned int n = 0;
  2534. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2535. s_append(joined, &n, "/", sizeof(joined));
  2536. s_append(joined, &n, in, sizeof(joined));
  2537. }
  2538. if (normalize_abs(joined, out, cap) != 0)
  2539. s_copy(out, joined, cap);
  2540. }
  2541. /* ---- canonical origin cache ---- *
  2542. *
  2543. * Sites commonly redirect http://host to https://host and then to
  2544. * https://www.host. Remember the final scheme/host of the last navigation so
  2545. * a bare domain typed again goes straight there instead of paying for two
  2546. * more connections and TLS handshakes. Only default-port requests are
  2547. * rewritten; explicit ports are left alone. */
  2548. #define ORIGIN_CACHE_MAX 8
  2549. #define ORIGIN_FILE "/share/borigins"
  2550. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2551. UHTTP_HOST_MAX + 2))
  2552. struct origin_cache_entry {
  2553. char host[UHTTP_HOST_MAX];
  2554. char origin[UHTTP_HOST_MAX + 16];
  2555. };
  2556. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2557. static int origin_count;
  2558. static char origin_buf[ORIGIN_BUF_SIZE];
  2559. static int default_port(const struct uhttp_url *u)
  2560. {
  2561. return u->secure ? u->port == 443 : u->port == 80;
  2562. }
  2563. static void url_origin(const struct uhttp_url *u, char *out,
  2564. unsigned int cap)
  2565. {
  2566. unsigned int n = 0;
  2567. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2568. s_append(out, &n, u->host, cap);
  2569. if (!default_port(u)) {
  2570. s_append(out, &n, ":", cap);
  2571. s_append_dec(out, &n, u->port, cap);
  2572. }
  2573. }
  2574. static void origin_cache_apply(char *url, unsigned int cap)
  2575. {
  2576. struct uhttp_url u;
  2577. char out[BR_URL_MAX];
  2578. unsigned int n = 0;
  2579. int i;
  2580. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2581. return;
  2582. for (i = 0; i < origin_count; i++) {
  2583. if (!s_eq(u.host, origins[i].host))
  2584. continue;
  2585. s_append(out, &n, origins[i].origin, sizeof(out));
  2586. s_append(out, &n, u.path, sizeof(out));
  2587. s_copy(url, out, cap);
  2588. return;
  2589. }
  2590. }
  2591. static void origin_cache_save(void)
  2592. {
  2593. unsigned int n = 0;
  2594. int i;
  2595. for (i = 0; i < origin_count; i++) {
  2596. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2597. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2598. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2599. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2600. }
  2601. if (n)
  2602. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2603. (int)origin_buf, (int)n);
  2604. }
  2605. static void origin_cache_load(void)
  2606. {
  2607. char *p;
  2608. int rn;
  2609. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2610. (int)(sizeof(origin_buf) - 1));
  2611. if (rn <= 0)
  2612. return;
  2613. origin_buf[rn] = '\0';
  2614. p = origin_buf;
  2615. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2616. char *line = p, *origin;
  2617. while (*p && *p != '\n')
  2618. p++;
  2619. if (*p)
  2620. *p++ = '\0';
  2621. if (!line[0])
  2622. continue;
  2623. origin = line;
  2624. while (*origin && *origin != ' ')
  2625. origin++;
  2626. if (!*origin)
  2627. continue;
  2628. *origin++ = '\0';
  2629. if (!line[0] || !is_http(origin))
  2630. continue;
  2631. {
  2632. struct uhttp_url uo;
  2633. if (uhttp_parse_url(origin, &uo) != 0 ||
  2634. !s_eq(uo.path, "/"))
  2635. continue;
  2636. }
  2637. s_copy(origins[origin_count].host, line,
  2638. sizeof(origins[origin_count].host));
  2639. s_copy(origins[origin_count].origin, origin,
  2640. sizeof(origins[origin_count].origin));
  2641. origin_count++;
  2642. }
  2643. }
  2644. static int host_is_www_of(const char *host, const char *base)
  2645. {
  2646. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2647. host[3] == '.' && s_eq(host + 4, base);
  2648. }
  2649. static void origin_cache_learn(const char *requested, const char *final)
  2650. {
  2651. struct uhttp_url from, to;
  2652. char origin[UHTTP_HOST_MAX + 16];
  2653. int i;
  2654. if (!is_http(requested) || !is_http(final))
  2655. return;
  2656. if (uhttp_parse_url(requested, &from) != 0 ||
  2657. uhttp_parse_url(final, &to) != 0)
  2658. return;
  2659. if (!default_port(&from))
  2660. return;
  2661. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2662. from.port == to.port)
  2663. return;
  2664. /* Only remember origin-level canonicalisation: the same path, and
  2665. * either the same host or its www./apex sibling. A path- or
  2666. * host-specific redirect (a shortener, a login page) must not poison
  2667. * every request to the typed host. */
  2668. if (!s_eq(from.path, to.path))
  2669. return;
  2670. if (!s_eq(from.host, to.host) &&
  2671. !host_is_www_of(to.host, from.host) &&
  2672. !host_is_www_of(from.host, to.host))
  2673. return;
  2674. url_origin(&to, origin, sizeof(origin));
  2675. for (i = 0; i < origin_count; i++) {
  2676. if (s_eq(origins[i].host, from.host)) {
  2677. if (!s_eq(origins[i].origin, origin)) {
  2678. s_copy(origins[i].origin, origin,
  2679. sizeof(origins[i].origin));
  2680. origin_cache_save();
  2681. }
  2682. return;
  2683. }
  2684. }
  2685. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2686. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2687. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2688. origin_cache_save();
  2689. }
  2690. static int path_dir(const char *path, char *out, unsigned int cap)
  2691. {
  2692. unsigned int i, last = 0;
  2693. for (i = 0; path[i]; i++)
  2694. if (path[i] == '/')
  2695. last = i;
  2696. if (last == 0) {
  2697. if (cap < 2)
  2698. return -1;
  2699. out[0] = '/';
  2700. out[1] = '\0';
  2701. return 0;
  2702. }
  2703. if (last + 1 >= cap)
  2704. return -1;
  2705. {
  2706. unsigned int j;
  2707. for (j = 0; j < last; j++)
  2708. out[j] = path[j];
  2709. out[last] = '\0';
  2710. }
  2711. return 0;
  2712. }
  2713. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2714. static int resolve_link(const char *base, const char *href, char *out,
  2715. unsigned int cap)
  2716. {
  2717. static char joined[BR_URL_MAX]; /* leaf: off the stack */
  2718. if (!href || !href[0] || href[0] == '#')
  2719. return -1;
  2720. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2721. starts_with(href, "data:") || starts_with(href, "tel:"))
  2722. return -1;
  2723. if (starts_with(href, "about:")) {
  2724. s_copy(out, href, cap);
  2725. return 0;
  2726. }
  2727. if (is_http(href)) {
  2728. s_copy(out, href, cap);
  2729. return 0;
  2730. }
  2731. if (starts_with(href, "//")) {
  2732. if (is_http(base)) {
  2733. unsigned int n = 0;
  2734. s_append(out, &n, starts_with(base, "https:") ?
  2735. "https:" : "http:", cap);
  2736. s_append(out, &n, href, cap);
  2737. return 0;
  2738. }
  2739. return -1;
  2740. }
  2741. if (is_http(base)) {
  2742. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2743. }
  2744. /* local page */
  2745. if (href[0] == '/') {
  2746. if (normalize_abs(href, out, cap) != 0)
  2747. return -1;
  2748. return 0;
  2749. }
  2750. {
  2751. static char dir[BR_URL_MAX];
  2752. unsigned int n = 0;
  2753. if (s_eq(base, "about:home"))
  2754. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2755. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2756. s_copy(dir, "/", sizeof(dir));
  2757. s_append(joined, &n, dir, sizeof(joined));
  2758. if (n == 0 || joined[n - 1] != '/')
  2759. s_append(joined, &n, "/", sizeof(joined));
  2760. s_append(joined, &n, href, sizeof(joined));
  2761. }
  2762. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2763. }
  2764. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2765. * rest instead of failing when a page or stylesheet is larger than the
  2766. * buffer. The stream is still walked to the end, so a normal page is
  2767. * verified; a truncated compressed input still returns whatever was decoded
  2768. * so far. */
  2769. struct trunc_buf {
  2770. unsigned char *dst;
  2771. unsigned int cap, pos;
  2772. int full;
  2773. };
  2774. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2775. {
  2776. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2777. if (len > m->cap - m->pos) {
  2778. unsigned int room = m->cap - m->pos;
  2779. if (room) {
  2780. unsigned int i;
  2781. for (i = 0; i < room; i++)
  2782. m->dst[m->pos + i] = data[i];
  2783. m->pos += room;
  2784. }
  2785. m->full = 1;
  2786. return 0;
  2787. }
  2788. {
  2789. unsigned int i;
  2790. for (i = 0; i < len; i++)
  2791. m->dst[m->pos + i] = data[i];
  2792. }
  2793. m->pos += len;
  2794. return 0;
  2795. }
  2796. static void worker_wait_ui(void);
  2797. static void inflate_ui_pump(void *ctx)
  2798. {
  2799. static unsigned int last;
  2800. unsigned int now = u_ticks_ms();
  2801. (void)ctx;
  2802. if ((int)(now - last) >= 50) {
  2803. last = now;
  2804. worker_wait_ui();
  2805. }
  2806. }
  2807. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2808. unsigned char *dst, unsigned int cap,
  2809. unsigned int *outlen, int gzip, int *truncated)
  2810. {
  2811. struct inflate_src in;
  2812. struct inflate_sink sink;
  2813. struct trunc_buf m;
  2814. unsigned int got = 0;
  2815. int r;
  2816. in.p = src;
  2817. in.len = len;
  2818. in.more = 0;
  2819. in.ctx = 0;
  2820. m.dst = dst;
  2821. m.cap = cap;
  2822. m.pos = 0;
  2823. m.full = 0;
  2824. sink.write = trunc_write;
  2825. sink.ctx = &m;
  2826. inflate_init(&image_inflate_ws, &in, &sink);
  2827. image_inflate_ws.progress = inflate_ui_pump;
  2828. image_inflate_ws.progress_ctx = 0;
  2829. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2830. inflate_zlib(&image_inflate_ws, &got);
  2831. *outlen = m.pos;
  2832. *truncated = m.full || r != 0;
  2833. if (r != 0 && m.pos == 0)
  2834. return -1;
  2835. return 0;
  2836. }
  2837. /* ---- headless fetch workers ------------------------------------------ *
  2838. *
  2839. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2840. * writes the raw response, a small metadata file and a done marker under
  2841. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2842. * or a multi-megabyte body never freezes the UI and images download in
  2843. * parallel.
  2844. */
  2845. struct fetch_meta {
  2846. int status;
  2847. int error;
  2848. int trunc;
  2849. unsigned int len;
  2850. unsigned int open_ms;
  2851. unsigned int first_ms;
  2852. unsigned int total_ms;
  2853. /* Optional decoded bitmap produced by the helper (image jobs). */
  2854. unsigned int dw, dh, nw, nh;
  2855. unsigned int alpha;
  2856. unsigned int px_len;
  2857. unsigned int dec_ms;
  2858. int dec_err;
  2859. char encoding[16];
  2860. char ctype[64];
  2861. char final[BR_URL_MAX];
  2862. };
  2863. static void draw(unsigned int *action);
  2864. static void handle_keys(unsigned int *action);
  2865. static void handle_page_click(unsigned int *action);
  2866. #define FETCH_WORKERS 4
  2867. #define FETCH_PATH_MAX 32
  2868. /* One long-lived curl __serve helper per worker. Each worker has its own
  2869. * request/body/meta/done files under /share so several downloads can be in
  2870. * flight at once; the keep-alive connection stays in the helper process, so
  2871. * tls.c's per-process state remains valid. */
  2872. struct fetch_worker {
  2873. int pid;
  2874. int slot;
  2875. int busy;
  2876. int ready;
  2877. int image_job;
  2878. unsigned int seq;
  2879. unsigned int deadline;
  2880. int retried;
  2881. unsigned int dec_w, dec_h;
  2882. int dec_retried;
  2883. char req[FETCH_PATH_MAX];
  2884. char body[FETCH_PATH_MAX];
  2885. char meta[FETCH_PATH_MAX];
  2886. char done[FETCH_PATH_MAX];
  2887. char post[FETCH_PATH_MAX];
  2888. char px[FETCH_PATH_MAX];
  2889. /* Optional preload job attached to this worker. */
  2890. unsigned int node;
  2891. int bg;
  2892. char url[BR_URL_MAX];
  2893. struct fetch_meta m;
  2894. };
  2895. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2896. static int fetch_tty = -2;
  2897. static void fetch_tty_drain(void);
  2898. static unsigned int fetch_session;
  2899. static unsigned int fetch_seq;
  2900. static struct fetch_meta fetch_meta;
  2901. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2902. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2903. static int fetch_last_error;
  2904. static unsigned int meta_uint(char **pp)
  2905. {
  2906. char *p = *pp;
  2907. unsigned int v = 0;
  2908. while (*p >= '0' && *p <= '9') {
  2909. v = v * 10 + (unsigned int)(*p - '0');
  2910. p++;
  2911. }
  2912. while (*p && *p != '\n')
  2913. p++;
  2914. if (*p == '\n')
  2915. p++;
  2916. *pp = p;
  2917. return v;
  2918. }
  2919. static void meta_str(char **pp, char *out, unsigned int cap)
  2920. {
  2921. char *p = *pp;
  2922. unsigned int n = 0;
  2923. while (*p && *p != '\n' && n + 1 < cap)
  2924. out[n++] = *p++;
  2925. out[n] = '\0';
  2926. while (*p && *p != '\n')
  2927. p++;
  2928. if (*p == '\n')
  2929. p++;
  2930. *pp = p;
  2931. }
  2932. static void worker_wait_ui(void)
  2933. {
  2934. unsigned int action = 0;
  2935. if (!ngui_begin(&ui))
  2936. return;
  2937. draw(&action);
  2938. handle_keys(&action);
  2939. handle_page_click(&action);
  2940. if (action & ACT_WAIT_NAV) {
  2941. pending_action |= action & ACT_WAIT_NAV;
  2942. if ((action & ACT_NAV) && click_url[0])
  2943. s_copy(pending_url, click_url, sizeof(pending_url));
  2944. click_url[0] = '\0';
  2945. cancel_fetch = 1;
  2946. }
  2947. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  2948. ngui_invalidate(&ui);
  2949. ngui_end(&ui);
  2950. }
  2951. static void fetch_path(char *out, unsigned int cap, const char *kind,
  2952. unsigned int session, int slot)
  2953. {
  2954. unsigned int n = 0;
  2955. s_append(out, &n, "/share/bf", cap);
  2956. s_append_dec(out, &n, session, cap);
  2957. s_append(out, &n, "_", cap);
  2958. s_append_dec(out, &n, (unsigned int)slot, cap);
  2959. s_append(out, &n, kind, cap);
  2960. }
  2961. static void fetch_pool_init(void)
  2962. {
  2963. static int ready;
  2964. int i;
  2965. if (ready)
  2966. return;
  2967. ready = 1;
  2968. fetch_session = ((unsigned int)u_getpid() << 16) ^
  2969. (u_ticks_ms() & 0xFFFFu);
  2970. if (!fetch_session)
  2971. fetch_session = 1;
  2972. for (i = 0; i < FETCH_WORKERS; i++) {
  2973. struct fetch_worker *w = &fetch_workers[i];
  2974. w->pid = -1;
  2975. w->slot = i;
  2976. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  2977. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  2978. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  2979. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  2980. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  2981. fetch_path(w->px, sizeof(w->px), "px", fetch_session, i);
  2982. }
  2983. }
  2984. static void fetch_worker_stop(struct fetch_worker *w)
  2985. {
  2986. int i;
  2987. /* An abandoned image job leaves its node loadable again. */
  2988. if (w->busy && w->image_job && w->node < doc.nnode) {
  2989. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  2990. doc.nodes[w->node].bg_img_index = -1;
  2991. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  2992. doc.nodes[w->node].img_index = -1;
  2993. }
  2994. if (w->pid > 0) {
  2995. u_kill((unsigned int)w->pid);
  2996. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  2997. u_sleep_ms(5);
  2998. /* Let the reaper close the socket before we reuse the slot. */
  2999. u_sleep_ms(10);
  3000. }
  3001. w->pid = -1;
  3002. w->busy = 0;
  3003. w->ready = 0;
  3004. w->image_job = 0;
  3005. if (w->req[0]) {
  3006. u_syscall1(SYS_UNLINK, (int)w->done);
  3007. u_syscall1(SYS_UNLINK, (int)w->meta);
  3008. u_syscall1(SYS_UNLINK, (int)w->body);
  3009. u_syscall1(SYS_UNLINK, (int)w->post);
  3010. u_syscall1(SYS_UNLINK, (int)w->req);
  3011. }
  3012. }
  3013. static void fetch_workers_stop_all(void)
  3014. {
  3015. int i;
  3016. for (i = 0; i < FETCH_WORKERS; i++)
  3017. fetch_worker_stop(&fetch_workers[i]);
  3018. }
  3019. /* Abandon the transfers of the current page but keep idle helpers and their
  3020. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  3021. * because its response would otherwise land in a reused /share slot. */
  3022. static void fetch_workers_cancel_busy(void)
  3023. {
  3024. int i;
  3025. for (i = 0; i < FETCH_WORKERS; i++)
  3026. if (fetch_workers[i].busy)
  3027. fetch_worker_stop(&fetch_workers[i]);
  3028. }
  3029. static void fetch_workers_prepare_nav(const char *url)
  3030. {
  3031. int i;
  3032. (void)url;
  3033. for (i = 0; i < FETCH_WORKERS; i++) {
  3034. struct fetch_worker *w = &fetch_workers[i];
  3035. if (w->pid <= 0)
  3036. continue;
  3037. /* Only an in-flight transfer must be aborted. Idle helpers
  3038. * stay warm across origins: there are just FETCH_WORKERS of
  3039. * them, and uhttp_open drops the old connection when the
  3040. * next job is for another host. Killing and respawning all
  3041. * four on every navigation churned processes and sockets
  3042. * while images were still loading. */
  3043. if (w->busy)
  3044. fetch_worker_stop(w);
  3045. }
  3046. }
  3047. /* The browser is no longer the active window and no fetch is running: give
  3048. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  3049. static void fetch_workers_stop_if_unfocused(void)
  3050. {
  3051. int i;
  3052. fetch_tty_drain();
  3053. if (ui.focused || page_loading || preload_active)
  3054. return;
  3055. for (i = 0; i < FETCH_WORKERS; i++)
  3056. if (fetch_workers[i].pid > 0) {
  3057. fetch_workers_stop_all();
  3058. return;
  3059. }
  3060. }
  3061. /* The helpers (and this process, since u_tty_create() rebinds our own
  3062. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  3063. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  3064. * a dozen TLS connections every helper hung in its next log line, so the
  3065. * following cross-origin navigation sat at "Loading..." until it timed out.
  3066. * Drain and discard it from every wait/poll loop. */
  3067. static void fetch_tty_drain(void)
  3068. {
  3069. char sink[512];
  3070. int i;
  3071. if (fetch_tty <= 0)
  3072. return;
  3073. for (i = 0; i < 16; i++)
  3074. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  3075. break;
  3076. }
  3077. static int fetch_worker_start(struct fetch_worker *w, char *err,
  3078. unsigned int errcap)
  3079. {
  3080. char arg[40];
  3081. unsigned int n = 0;
  3082. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  3083. return 0;
  3084. w->pid = -1;
  3085. fetch_pool_init();
  3086. if (fetch_tty == -2) {
  3087. int t = u_tty_create();
  3088. fetch_tty = t > 0 ? t : 0;
  3089. }
  3090. s_append(arg, &n, "__serve ", sizeof(arg));
  3091. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  3092. s_append(arg, &n, " ", sizeof(arg));
  3093. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  3094. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  3095. if (w->pid <= 0) {
  3096. w->pid = -1;
  3097. s_copy(err, "cannot start network helper", errcap);
  3098. return -1;
  3099. }
  3100. return 0;
  3101. }
  3102. static struct fetch_worker *fetch_worker_alloc(void)
  3103. {
  3104. int i;
  3105. fetch_pool_init();
  3106. for (i = 0; i < FETCH_WORKERS; i++)
  3107. if (!fetch_workers[i].busy)
  3108. return &fetch_workers[i];
  3109. return 0;
  3110. }
  3111. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3112. unsigned int cap, const char *method,
  3113. const char *ctype, const char *post,
  3114. unsigned int post_len, unsigned int node,
  3115. int bg, unsigned int dec_w,
  3116. unsigned int dec_h, char *err,
  3117. unsigned int errcap);
  3118. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  3119. unsigned int cap, const char *post,
  3120. unsigned int post_len, unsigned int node,
  3121. int bg, char *err, unsigned int errcap)
  3122. {
  3123. /* A body pointer with no bytes is still a POST: the classic request
  3124. * line would turn it into a GET. */
  3125. if (post && !post_len)
  3126. return fetch_worker_submit_req(w, url, cap, "POST",
  3127. "application/x-www-form-urlencoded", post, 0, node,
  3128. bg, 0, 0, err, errcap);
  3129. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  3130. node, bg, 0, 0, err, errcap);
  3131. }
  3132. /* Image job: ask the helper to decode at these display bounds as well. */
  3133. static int fetch_worker_submit_image(struct fetch_worker *w, const char *url,
  3134. unsigned int cap, unsigned int node,
  3135. int bg, unsigned int dec_w,
  3136. unsigned int dec_h, char *err,
  3137. unsigned int errcap)
  3138. {
  3139. return fetch_worker_submit_req(w, url, cap, 0, 0, 0, 0, node, bg,
  3140. dec_w, dec_h, err, errcap);
  3141. }
  3142. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  3143. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  3144. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3145. unsigned int cap, const char *method,
  3146. const char *ctype, const char *post,
  3147. unsigned int post_len, unsigned int node,
  3148. int bg, unsigned int dec_w,
  3149. unsigned int dec_h, char *err,
  3150. unsigned int errcap)
  3151. {
  3152. static char req[BR_URL_MAX + 256];
  3153. unsigned int n = 0;
  3154. fetch_seq++;
  3155. if (!fetch_seq)
  3156. fetch_seq = 1;
  3157. w->seq = fetch_seq;
  3158. w->ready = 0;
  3159. w->image_job = 0;
  3160. w->retried = 0;
  3161. w->m.error = 0;
  3162. w->node = node;
  3163. w->bg = bg;
  3164. w->dec_w = dec_w;
  3165. w->dec_h = dec_h;
  3166. w->dec_retried = 0;
  3167. s_copy(w->url, url, sizeof(w->url));
  3168. s_append_dec(req, &n, w->seq, sizeof(req));
  3169. s_append(req, &n, " ", sizeof(req));
  3170. s_append_dec(req, &n, cap, sizeof(req));
  3171. s_append(req, &n, " ", sizeof(req));
  3172. if (dec_w || dec_h) {
  3173. s_append(req, &n, "D ", sizeof(req));
  3174. s_append_dec(req, &n, dec_w, sizeof(req));
  3175. s_append(req, &n, " ", sizeof(req));
  3176. s_append_dec(req, &n, dec_h, sizeof(req));
  3177. s_append(req, &n, " ", sizeof(req));
  3178. } else if (method) {
  3179. unsigned int k;
  3180. s_append(req, &n, "X ", sizeof(req));
  3181. s_append(req, &n, method, sizeof(req));
  3182. s_append(req, &n, " ", sizeof(req));
  3183. s_append_dec(req, &n, post_len, sizeof(req));
  3184. s_append(req, &n, " ", sizeof(req));
  3185. if (!ctype || !ctype[0])
  3186. s_append(req, &n, "-", sizeof(req));
  3187. /* One token on the request line: drop the spaces
  3188. * ("application/json; charset=utf-8" stays valid). */
  3189. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  3190. if (ctype[k] != ' ')
  3191. req[n++] = ctype[k];
  3192. req[n] = '\0';
  3193. s_append(req, &n, " ", sizeof(req));
  3194. } else if (post_len) {
  3195. s_append(req, &n, "POST ", sizeof(req));
  3196. s_append_dec(req, &n, post_len, sizeof(req));
  3197. s_append(req, &n, " ", sizeof(req));
  3198. }
  3199. s_append(req, &n, url, sizeof(req));
  3200. s_append(req, &n, "\n", sizeof(req));
  3201. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  3202. (int)post, (int)post_len) < 0) {
  3203. s_copy(err, "cannot queue form body", errcap);
  3204. return -1;
  3205. }
  3206. u_syscall1(SYS_UNLINK, (int)w->done);
  3207. u_syscall1(SYS_UNLINK, (int)w->meta);
  3208. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  3209. s_copy(err, "cannot queue network request", errcap);
  3210. return -1;
  3211. }
  3212. if (fetch_worker_start(w, err, errcap) != 0)
  3213. return -1;
  3214. w->busy = 1;
  3215. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  3216. return 0;
  3217. }
  3218. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  3219. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  3220. unsigned int errcap)
  3221. {
  3222. static char meta[BR_URL_MAX + 1024];
  3223. char *p;
  3224. int rn, mseq;
  3225. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  3226. (int)(sizeof(meta) - 1));
  3227. if (rn <= 0) {
  3228. s_copy(err, "network helper failed", errcap);
  3229. return -1;
  3230. }
  3231. meta[rn] = '\0';
  3232. p = meta;
  3233. mseq = (int)meta_uint(&p);
  3234. if (mseq != (int)w->seq) {
  3235. s_copy(err, "stale network response", errcap);
  3236. return -1;
  3237. }
  3238. w->m.status = (int)meta_uint(&p);
  3239. w->m.error = (int)meta_uint(&p);
  3240. w->m.trunc = (int)meta_uint(&p);
  3241. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  3242. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  3243. meta_str(&p, w->m.final, sizeof(w->m.final));
  3244. w->m.len = meta_uint(&p);
  3245. w->m.open_ms = 0;
  3246. w->m.first_ms = 0;
  3247. w->m.total_ms = 0;
  3248. if (*p) {
  3249. w->m.open_ms = meta_uint(&p);
  3250. w->m.first_ms = meta_uint(&p);
  3251. w->m.total_ms = meta_uint(&p);
  3252. }
  3253. w->m.dw = w->m.dh = w->m.nw = w->m.nh = 0;
  3254. w->m.alpha = w->m.px_len = w->m.dec_ms = 0;
  3255. w->m.dec_err = 0;
  3256. if (*p) {
  3257. w->m.dw = meta_uint(&p);
  3258. w->m.dh = meta_uint(&p);
  3259. w->m.nw = meta_uint(&p);
  3260. w->m.nh = meta_uint(&p);
  3261. w->m.alpha = meta_uint(&p);
  3262. w->m.px_len = meta_uint(&p);
  3263. w->m.dec_err = (int)meta_uint(&p);
  3264. w->m.dec_ms = meta_uint(&p);
  3265. }
  3266. if (w->m.error) {
  3267. s_copy(err, uhttp_error_string(w->m.error), errcap);
  3268. return -1;
  3269. }
  3270. w->ready = 1;
  3271. return 0;
  3272. }
  3273. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  3274. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  3275. unsigned int errcap)
  3276. {
  3277. static char done[24];
  3278. char *p;
  3279. int rn, mseq;
  3280. fetch_tty_drain();
  3281. if (!w->busy)
  3282. return -1;
  3283. if (w->ready)
  3284. return 1;
  3285. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  3286. (int)(sizeof(done) - 1));
  3287. if (rn > 0) {
  3288. done[rn] = '\0';
  3289. p = done;
  3290. mseq = (int)meta_uint(&p);
  3291. if (mseq == (int)w->seq) {
  3292. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  3293. fetch_worker_stop(w);
  3294. return -1;
  3295. }
  3296. return 1;
  3297. }
  3298. }
  3299. if (!u_alive((unsigned int)w->pid)) {
  3300. w->pid = -1;
  3301. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  3302. w->retried = 1;
  3303. return 0;
  3304. }
  3305. s_copy(err, "network helper stopped", errcap);
  3306. fetch_worker_stop(w);
  3307. return -1;
  3308. }
  3309. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  3310. s_copy(err, "network request timed out", errcap);
  3311. fetch_worker_stop(w);
  3312. return -1;
  3313. }
  3314. return 0;
  3315. }
  3316. /* Copy the completed body, inflating it if the server ignored our identity
  3317. * request. Mirrors the old fetch_remote body path. */
  3318. static int fetch_worker_read_body(struct fetch_worker *w,
  3319. unsigned char *plain,
  3320. unsigned int plaincap,
  3321. unsigned char *comp,
  3322. unsigned int compcap,
  3323. int *truncated, char *err,
  3324. unsigned int errcap)
  3325. {
  3326. int rv, zr, was_trunc;
  3327. if (contains_ci(w->m.encoding, "gzip") ||
  3328. contains_ci(w->m.encoding, "deflate")) {
  3329. unsigned int comp_len = 0, plen = 0;
  3330. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  3331. (int)compcap);
  3332. if (rv < 0) {
  3333. s_copy(err, "empty response", errcap);
  3334. return -1;
  3335. }
  3336. comp_len = (unsigned int)rv;
  3337. if (comp_len < w->m.len) {
  3338. s_copy(err, "compressed response is too large", errcap);
  3339. return -1;
  3340. }
  3341. if (contains_ci(w->m.encoding, "deflate"))
  3342. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3343. &plen, 0, &was_trunc);
  3344. else
  3345. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3346. &plen, 1, &was_trunc);
  3347. if (zr != 0) {
  3348. s_copy(err, "compressed response is corrupt", errcap);
  3349. return -1;
  3350. }
  3351. *truncated = w->m.trunc || was_trunc;
  3352. return (int)plen;
  3353. }
  3354. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  3355. if (rv < 0) {
  3356. s_copy(err, "empty response", errcap);
  3357. return -1;
  3358. }
  3359. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  3360. return rv;
  3361. }
  3362. static void fetch_worker_release(struct fetch_worker *w)
  3363. {
  3364. u_syscall1(SYS_UNLINK, (int)w->done);
  3365. u_syscall1(SYS_UNLINK, (int)w->meta);
  3366. u_syscall1(SYS_UNLINK, (int)w->body);
  3367. u_syscall1(SYS_UNLINK, (int)w->post);
  3368. u_syscall1(SYS_UNLINK, (int)w->px);
  3369. u_syscall1(SYS_UNLINK, (int)w->req);
  3370. w->busy = 0;
  3371. w->ready = 0;
  3372. w->image_job = 0;
  3373. w->dec_w = 0;
  3374. w->dec_h = 0;
  3375. w->dec_retried = 0;
  3376. }
  3377. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  3378. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  3379. unsigned int errcap)
  3380. {
  3381. for (;;) {
  3382. int rv;
  3383. if (!fetch_wait_passive)
  3384. worker_wait_ui();
  3385. if (cancel_fetch || pending_action) {
  3386. fetch_workers_cancel_busy();
  3387. return FETCH_ABORT;
  3388. }
  3389. rv = fetch_worker_poll(w, err, errcap);
  3390. if (rv != 0)
  3391. return rv == 1 ? 0 : -1;
  3392. u_sleep_ms(10);
  3393. }
  3394. }
  3395. static int fetch_remote(const char *url, unsigned int cap,
  3396. const char *post, unsigned int post_len,
  3397. unsigned char *plain, unsigned int plaincap,
  3398. unsigned char *comp, unsigned int compcap,
  3399. struct fetch_meta *m, int *truncated,
  3400. char *err, unsigned int errcap)
  3401. {
  3402. struct fetch_worker *w = fetch_worker_alloc();
  3403. int rv;
  3404. fetch_last_error = 0;
  3405. if (!w) {
  3406. s_copy(err, "network busy", errcap);
  3407. return -1;
  3408. }
  3409. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  3410. err, errcap) != 0) {
  3411. fetch_worker_release(w);
  3412. return -1;
  3413. }
  3414. rv = fetch_worker_wait(w, err, errcap);
  3415. if (rv == FETCH_ABORT) {
  3416. fetch_worker_release(w);
  3417. return FETCH_ABORT;
  3418. }
  3419. if (rv != 0) {
  3420. fetch_last_error = w->m.error;
  3421. fetch_worker_release(w);
  3422. return -1;
  3423. }
  3424. *m = w->m;
  3425. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  3426. truncated, err, errcap);
  3427. fetch_worker_release(w);
  3428. if (rv >= 0 && (cancel_fetch || pending_action))
  3429. return FETCH_ABORT;
  3430. return rv;
  3431. }
  3432. static int fetch_worker_status(const struct fetch_worker *w)
  3433. {
  3434. return w->m.status;
  3435. }
  3436. /* fetch()/XHR through a helper: one request, the status and body come back
  3437. * whatever the HTTP status (a 401 is an answer, not a network error). */
  3438. static int js_worker_http(const char *method, const char *url,
  3439. const char *ctype, const char *body,
  3440. unsigned int body_len, struct js_http_resp *r,
  3441. char *err, int errcap)
  3442. {
  3443. struct fetch_worker *w = fetch_worker_alloc();
  3444. unsigned char *plain;
  3445. int rv, tr = 0;
  3446. if (!w) {
  3447. s_copy(err, "network busy", (unsigned int)errcap);
  3448. return -1;
  3449. }
  3450. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  3451. body_len, 0, 0, 0, 0, err,
  3452. (unsigned int)errcap) != 0) {
  3453. fetch_worker_release(w);
  3454. return -1;
  3455. }
  3456. fetch_wait_passive++;
  3457. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  3458. fetch_wait_passive--;
  3459. if (rv != 0) {
  3460. if (rv == FETCH_ABORT)
  3461. s_copy(err, "page is navigating", (unsigned int)errcap);
  3462. fetch_worker_release(w);
  3463. return -1;
  3464. }
  3465. r->status = w->m.status;
  3466. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  3467. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  3468. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  3469. if (!plain) {
  3470. fetch_worker_release(w);
  3471. s_copy(err, "out of memory", (unsigned int)errcap);
  3472. return -1;
  3473. }
  3474. if (w->m.len == 0) {
  3475. rv = 0; /* 204, an empty 200: no body file */
  3476. } else {
  3477. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  3478. image_io_buf, BR_PAGE_COMP_MAX,
  3479. &tr, err, (unsigned int)errcap);
  3480. }
  3481. fetch_worker_release(w);
  3482. if (rv < 0) {
  3483. free(plain);
  3484. return -1;
  3485. }
  3486. plain[rv] = '\0';
  3487. r->body = (char *)plain;
  3488. r->len = (unsigned int)rv;
  3489. return 0;
  3490. }
  3491. /* ---- HTTP / file fetch ---- */
  3492. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  3493. unsigned int *outlen, int *is_local, char *ctype,
  3494. unsigned int ctcap, char *final, unsigned int finalcap,
  3495. char *err, unsigned int errcap, int *truncated,
  3496. const char *post, unsigned int post_len)
  3497. {
  3498. unsigned char *buf;
  3499. unsigned int len;
  3500. int tr = 0;
  3501. int rv;
  3502. *out = 0;
  3503. *outlen = 0;
  3504. *truncated = 0;
  3505. if (final && finalcap)
  3506. final[0] = '\0';
  3507. if (ctype && ctcap)
  3508. ctype[0] = '\0';
  3509. if (url[0] == '/') {
  3510. char pathbuf[BR_URL_MAX];
  3511. const char *open_url = url;
  3512. unsigned int i = 0;
  3513. /* A local form GET keeps ?query in the address bar but the
  3514. * file lookup uses the path alone, like a real browser. */
  3515. while (url[i] && url[i] != '?' && url[i] != '#')
  3516. i++;
  3517. if (url[i]) {
  3518. s_copy(pathbuf, url, i + 1);
  3519. open_url = pathbuf;
  3520. }
  3521. buf = (unsigned char *)malloc(cap);
  3522. if (!buf) {
  3523. s_copy(err, "out of memory", errcap);
  3524. return -1;
  3525. }
  3526. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  3527. if (rv < 0) {
  3528. free(buf);
  3529. s_copy(err, "file not found", errcap);
  3530. return -1;
  3531. }
  3532. *out = buf;
  3533. *outlen = (unsigned int)rv;
  3534. *is_local = 1;
  3535. if (ctype)
  3536. s_copy(ctype, "text/html", ctcap);
  3537. if (final)
  3538. s_copy(final, url, finalcap);
  3539. if ((unsigned int)rv == cap)
  3540. *truncated = 1;
  3541. return 0;
  3542. }
  3543. buf = (unsigned char *)malloc(cap);
  3544. if (!buf) {
  3545. s_copy(err, "out of memory", errcap);
  3546. return -1;
  3547. }
  3548. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3549. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3550. if (rv == FETCH_ABORT) {
  3551. free(buf);
  3552. return FETCH_ABORT;
  3553. }
  3554. if (rv < 0) {
  3555. free(buf);
  3556. return -1;
  3557. }
  3558. len = (unsigned int)rv;
  3559. if (len == 0) {
  3560. free(buf);
  3561. s_copy(err, "empty response", errcap);
  3562. return -1;
  3563. }
  3564. if (ctype)
  3565. s_copy(ctype, fetch_meta.ctype, ctcap);
  3566. if (final && fetch_meta.final[0])
  3567. s_copy(final, fetch_meta.final, finalcap);
  3568. *is_local = 0;
  3569. *out = buf;
  3570. *outlen = len;
  3571. *truncated = tr;
  3572. return 0;
  3573. }
  3574. /* Load every @font-face the parser registered. Local files go through
  3575. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  3576. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  3577. * to the built-in regular/bold/italic/mono set. */
  3578. static void load_font_faces(void)
  3579. {
  3580. unsigned int i;
  3581. memset(font_faces, 0, sizeof(font_faces));
  3582. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  3583. i <= BR_MAX_FACES; i++) {
  3584. const char *url = br_font_face_url((int)i);
  3585. const char *base = br_font_face_base((int)i);
  3586. char abs[BR_URL_MAX];
  3587. if (!url || !url[0])
  3588. continue;
  3589. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  3590. sizeof(abs)) != 0)
  3591. continue;
  3592. if (abs[0] == '/') {
  3593. font_faces[i - 1] = ufont_face_open_path(abs);
  3594. } else if (is_http(abs)) {
  3595. unsigned char *buf;
  3596. char err[64];
  3597. int rv, tr = 0;
  3598. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  3599. if (!buf)
  3600. continue;
  3601. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3602. UFONT_MAX_FILE, image_io_buf,
  3603. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  3604. err, sizeof(err));
  3605. if (rv > 0)
  3606. font_faces[i - 1] = ufont_face_open_mem(buf,
  3607. rv);
  3608. free(buf);
  3609. }
  3610. }
  3611. }
  3612. /* Remote scripts are cached under /share for the current boot, like the
  3613. * stylesheet cache, so reloads and later visits skip the network. */
  3614. static int script_cache_count;
  3615. static unsigned int script_cache_hash(const char *s)
  3616. {
  3617. unsigned int h = 2166136261u;
  3618. while (*s) {
  3619. h ^= (unsigned char)*s++;
  3620. h *= 16777619u;
  3621. }
  3622. return h;
  3623. }
  3624. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3625. {
  3626. unsigned int n = 0;
  3627. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3628. s_append_dec(out, &n, script_cache_hash(url), cap);
  3629. }
  3630. static void script_cache_clear(void)
  3631. {
  3632. struct sys_dirent d;
  3633. char path[96];
  3634. for (;;) {
  3635. int i, found = 0;
  3636. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3637. (int)&d) == 1; i++) {
  3638. unsigned int n = 0;
  3639. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3640. continue;
  3641. s_append(path, &n, "/share/", sizeof(path));
  3642. s_append(path, &n, d.name, sizeof(path));
  3643. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3644. return;
  3645. found = 1;
  3646. break;
  3647. }
  3648. if (!found)
  3649. break;
  3650. }
  3651. script_cache_count = 0;
  3652. }
  3653. static void script_cache_init(void)
  3654. {
  3655. struct sys_dirent d;
  3656. int i, count = 0;
  3657. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3658. (int)&d) == 1; i++)
  3659. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3660. count++;
  3661. if (count >= SCRIPT_CACHE_MAX) {
  3662. script_cache_clear();
  3663. return;
  3664. }
  3665. script_cache_count = count;
  3666. }
  3667. static int script_cache_get(const char *url, unsigned char **out,
  3668. unsigned int *outlen)
  3669. {
  3670. char path[96];
  3671. struct sys_stat st;
  3672. unsigned char *buf;
  3673. int rn;
  3674. script_cache_path(url, path, sizeof(path));
  3675. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3676. st.size >= SCRIPT_CACHE_FILE_MAX)
  3677. return 0;
  3678. buf = (unsigned char *)malloc(st.size + 1);
  3679. if (!buf)
  3680. return 0;
  3681. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3682. if (rn != (int)st.size) {
  3683. free(buf);
  3684. return 0;
  3685. }
  3686. buf[st.size] = '\0';
  3687. *out = buf;
  3688. *outlen = st.size;
  3689. return 1;
  3690. }
  3691. static void script_cache_put(const char *url, const unsigned char *data,
  3692. unsigned int len)
  3693. {
  3694. char path[96];
  3695. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3696. len >= SCRIPT_CACHE_FILE_MAX)
  3697. return;
  3698. script_cache_path(url, path, sizeof(path));
  3699. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3700. (int)len) >= 0)
  3701. script_cache_count++;
  3702. }
  3703. static int script_cache_has(const char *url)
  3704. {
  3705. char path[96];
  3706. struct sys_stat st;
  3707. script_cache_path(url, path, sizeof(path));
  3708. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3709. st.size < SCRIPT_CACHE_FILE_MAX;
  3710. }
  3711. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3712. static int fetch_script_text(const char *url, unsigned char **out,
  3713. unsigned int *outlen, char *err,
  3714. unsigned int errcap)
  3715. {
  3716. unsigned char *buf;
  3717. unsigned int len;
  3718. int local, truncated = 0;
  3719. char ctype[64], final[BR_URL_MAX];
  3720. int rv;
  3721. *out = 0;
  3722. *outlen = 0;
  3723. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3724. return 0;
  3725. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3726. sizeof(ctype), final, sizeof(final), err, errcap,
  3727. &truncated, 0, 0);
  3728. if (rv != 0)
  3729. return rv;
  3730. if (truncated || len >= BR_SCRIPT_MAX) {
  3731. free(buf);
  3732. s_copy(err, "script is too large", errcap);
  3733. return -1;
  3734. }
  3735. buf[len] = '\0';
  3736. if (!local)
  3737. script_cache_put(url, buf, len);
  3738. *out = buf;
  3739. *outlen = len;
  3740. return 0;
  3741. }
  3742. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  3743. * the heap, so images must not allocate their file body from it as well. */
  3744. static int fetch_image(const char *url, unsigned int cap,
  3745. unsigned char **out, unsigned int *outlen,
  3746. char *err, unsigned int errcap)
  3747. {
  3748. unsigned int len;
  3749. int tr = 0;
  3750. int rv;
  3751. *out = 0;
  3752. *outlen = 0;
  3753. if (cap > BR_IMG_FILE_MAX)
  3754. cap = BR_IMG_FILE_MAX;
  3755. if (url[0] == '/') {
  3756. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  3757. (int)cap);
  3758. if (rv < 0) {
  3759. s_copy(err, "file not found", errcap);
  3760. return -1;
  3761. }
  3762. *out = image_file_buf;
  3763. *outlen = (unsigned int)rv;
  3764. return 0;
  3765. }
  3766. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  3767. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  3768. if (rv == FETCH_ABORT)
  3769. return FETCH_ABORT;
  3770. if (rv < 0)
  3771. return -1;
  3772. len = (unsigned int)rv;
  3773. if (len == 0) {
  3774. s_copy(err, "empty image", errcap);
  3775. return -1;
  3776. }
  3777. *out = image_file_buf;
  3778. *outlen = len;
  3779. return 0;
  3780. }
  3781. /* Remote stylesheets are immutable enough for the current boot: keep
  3782. * successful responses under /share so a reload, a second visit or a fresh
  3783. * browser launch does not fetch the same five sheets over the network again.
  3784. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  3785. static int css_cache_count;
  3786. static unsigned int css_cache_hash(const char *s)
  3787. {
  3788. unsigned int h = 2166136261u;
  3789. while (*s) {
  3790. h ^= (unsigned char)*s++;
  3791. h *= 16777619u;
  3792. }
  3793. return h;
  3794. }
  3795. static void css_cache_path(const char *url, char *out, unsigned int cap)
  3796. {
  3797. unsigned int n = 0;
  3798. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  3799. s_append_dec(out, &n, css_cache_hash(url), cap);
  3800. }
  3801. static void css_cache_clear(void)
  3802. {
  3803. struct sys_dirent d;
  3804. char path[96];
  3805. for (;;) {
  3806. int i, found = 0;
  3807. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3808. (int)&d) == 1; i++) {
  3809. unsigned int n = 0;
  3810. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  3811. continue;
  3812. s_append(path, &n, "/share/", sizeof(path));
  3813. s_append(path, &n, d.name, sizeof(path));
  3814. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3815. return;
  3816. found = 1;
  3817. break;
  3818. }
  3819. if (!found)
  3820. break;
  3821. }
  3822. css_cache_count = 0;
  3823. }
  3824. static void css_cache_init(void)
  3825. {
  3826. struct sys_dirent d;
  3827. int i, count = 0;
  3828. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3829. (int)&d) == 1; i++)
  3830. if (starts_with(d.name, CSS_CACHE_PREFIX))
  3831. count++;
  3832. if (count >= CSS_CACHE_MAX) {
  3833. css_cache_clear();
  3834. return;
  3835. }
  3836. css_cache_count = count;
  3837. }
  3838. static int css_cache_get(const char *url, unsigned char **out,
  3839. unsigned int *outlen)
  3840. {
  3841. char path[96];
  3842. int rn;
  3843. css_cache_path(url, path, sizeof(path));
  3844. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  3845. (int)CSS_CACHE_FILE_MAX);
  3846. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  3847. return 0;
  3848. *out = image_io_buf;
  3849. *outlen = (unsigned int)rn;
  3850. return 1;
  3851. }
  3852. static void css_cache_put(const char *url, const unsigned char *data,
  3853. unsigned int len)
  3854. {
  3855. char path[96];
  3856. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  3857. len >= CSS_CACHE_FILE_MAX)
  3858. return;
  3859. css_cache_path(url, path, sizeof(path));
  3860. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3861. (int)len) >= 0)
  3862. css_cache_count++;
  3863. }
  3864. static int css_cache_has(const char *url)
  3865. {
  3866. char path[96];
  3867. struct sys_stat st;
  3868. css_cache_path(url, path, sizeof(path));
  3869. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3870. st.size < CSS_CACHE_FILE_MAX;
  3871. }
  3872. /* Read one stylesheet into the shared static buffer. CSS is parsed
  3873. * immediately, so it does not need the page heap; this leaves the heap for
  3874. * the 2 MB page body, the rules and the scaled image bitmaps. */
  3875. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  3876. char *err, unsigned int errcap)
  3877. {
  3878. unsigned int len;
  3879. int tr = 0;
  3880. int rv;
  3881. *out = 0;
  3882. *outlen = 0;
  3883. if (url[0] == '/') {
  3884. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  3885. (int)BR_CSS_MAX);
  3886. if (rv < 0) {
  3887. s_copy(err, "stylesheet not found", errcap);
  3888. return -1;
  3889. }
  3890. *out = image_io_buf;
  3891. *outlen = (unsigned int)rv;
  3892. return 0;
  3893. }
  3894. if (css_cache_get(url, out, outlen))
  3895. return 0;
  3896. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  3897. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  3898. &fetch_meta, &tr, err, errcap);
  3899. if (rv == FETCH_ABORT)
  3900. return FETCH_ABORT;
  3901. if (rv < 0)
  3902. return -1;
  3903. len = (unsigned int)rv;
  3904. if (len == 0) {
  3905. s_copy(err, "empty stylesheet", errcap);
  3906. return -1;
  3907. }
  3908. *out = image_io_buf;
  3909. *outlen = len;
  3910. css_cache_put(url, image_io_buf, len);
  3911. return 0;
  3912. }
  3913. static void redraw_now(void);
  3914. static char error_page[1024];
  3915. static void show_error(const char *title, const char *detail)
  3916. {
  3917. char *page = error_page;
  3918. unsigned int n = 0;
  3919. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  3920. s_append(page, &n, title, sizeof(error_page));
  3921. s_append(page, &n, "</h2><p>", sizeof(error_page));
  3922. {
  3923. const char *p = detail;
  3924. while (*p && n + 1 < sizeof(error_page)) {
  3925. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  3926. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  3927. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  3928. else page[n++] = *p;
  3929. p++;
  3930. }
  3931. }
  3932. page[n] = '\0';
  3933. s_append(page, &n, "</p><p>", sizeof(error_page));
  3934. s_append(page, &n, page_url, sizeof(error_page));
  3935. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  3936. sizeof(error_page));
  3937. br_parse(&doc, page, n);
  3938. layout_valid = 0;
  3939. preload_active = 0;
  3940. preload_pending = 0;
  3941. preload_wait = 0;
  3942. fetch_workers_cancel_busy();
  3943. s_copy(page_title, title, sizeof(page_title));
  3944. page_loading = 0;
  3945. set_status(title, 1, 0);
  3946. ngui_invalidate(&ui);
  3947. }
  3948. static int decode_direct_image(const unsigned char *data, unsigned int len,
  3949. unsigned int node)
  3950. {
  3951. if (image_count >= BR_MAX_IMAGES)
  3952. return -1;
  3953. if (decode_image_data(data, len, &images[0], 0, 0, 0, 0) != 0)
  3954. return -1;
  3955. doc.nodes[node].img_index = 0;
  3956. image_count = 1;
  3957. return 0;
  3958. }
  3959. static int ancestor_is(unsigned int node, unsigned int tag)
  3960. {
  3961. unsigned int p = doc.nodes[node].parent;
  3962. while (p) {
  3963. if (doc.nodes[p].tag == tag)
  3964. return 1;
  3965. p = doc.nodes[p].parent;
  3966. }
  3967. return 0;
  3968. }
  3969. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  3970. * parallel but parsed in document order, so the cascade is unchanged. */
  3971. static int load_stylesheets(void)
  3972. {
  3973. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  3974. static unsigned char remote[BR_MAX_SHEETS];
  3975. struct fetch_worker *slot[BR_MAX_SHEETS];
  3976. unsigned int i, n = 0, next = 0, k;
  3977. char err[64];
  3978. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  3979. struct br_node *nd = &doc.nodes[i];
  3980. const char *rel, *href;
  3981. char url[BR_URL_MAX];
  3982. int dup = 0;
  3983. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  3984. continue;
  3985. rel = br_rel(&doc, i);
  3986. if (!contains_ci(rel, "stylesheet"))
  3987. continue;
  3988. href = br_href(&doc, i);
  3989. if (!href[0])
  3990. continue;
  3991. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  3992. continue;
  3993. for (k = 0; k < n; k++)
  3994. if (s_eq(urls[k], url)) {
  3995. dup = 1;
  3996. break;
  3997. }
  3998. if (dup)
  3999. continue;
  4000. s_copy(urls[n], url, BR_URL_MAX);
  4001. remote[n] = url[0] != '/' && !css_cache_has(url);
  4002. n++;
  4003. }
  4004. for (i = 0; i < BR_MAX_SHEETS; i++)
  4005. slot[i] = 0;
  4006. /* Start as many remote sheets as there are free workers. */
  4007. for (; next < n; next++) {
  4008. struct fetch_worker *w;
  4009. if (!remote[next])
  4010. continue;
  4011. w = fetch_worker_alloc();
  4012. if (!w)
  4013. break;
  4014. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  4015. err, sizeof(err)) != 0) {
  4016. fetch_worker_release(w);
  4017. remote[next] = 0;
  4018. continue;
  4019. }
  4020. slot[next] = w;
  4021. }
  4022. for (i = 0; i < n; i++) {
  4023. unsigned char *data = 0;
  4024. unsigned int len = 0;
  4025. int rv;
  4026. if (!remote[i]) {
  4027. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  4028. if (rv == FETCH_ABORT) {
  4029. fetch_workers_stop_all();
  4030. return FETCH_ABORT;
  4031. }
  4032. if (rv != 0 || !len)
  4033. continue;
  4034. } else {
  4035. struct fetch_worker *w = slot[i];
  4036. int tr = 0;
  4037. if (!w) {
  4038. w = fetch_worker_alloc();
  4039. if (!w) {
  4040. rv = -1;
  4041. goto css_failed;
  4042. }
  4043. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  4044. 0, 0, 0, 0, err,
  4045. sizeof(err)) != 0) {
  4046. fetch_worker_release(w);
  4047. remote[i] = 0;
  4048. if (i == next)
  4049. next++;
  4050. continue;
  4051. }
  4052. slot[i] = w;
  4053. if (i == next)
  4054. next++;
  4055. }
  4056. rv = fetch_worker_wait(w, err, sizeof(err));
  4057. if (rv == FETCH_ABORT) {
  4058. fetch_workers_stop_all();
  4059. return FETCH_ABORT;
  4060. }
  4061. if (rv == 0)
  4062. rv = fetch_worker_read_body(w, image_io_buf,
  4063. BR_CSS_MAX,
  4064. image_io_buf + BR_CSS_MAX,
  4065. BR_CSS_COMP_MAX, &tr,
  4066. err, sizeof(err));
  4067. else
  4068. rv = -1;
  4069. fetch_worker_release(w);
  4070. slot[i] = 0;
  4071. /* Refill the worker window before parsing this sheet. */
  4072. for (; next < n; next++) {
  4073. struct fetch_worker *nw;
  4074. if (!remote[next])
  4075. continue;
  4076. nw = fetch_worker_alloc();
  4077. if (!nw)
  4078. break;
  4079. if (fetch_worker_submit(nw, urls[next],
  4080. BR_CSS_MAX, 0, 0, 0, 0,
  4081. err, sizeof(err)) != 0) {
  4082. fetch_worker_release(nw);
  4083. remote[next] = 0;
  4084. continue;
  4085. }
  4086. slot[next] = nw;
  4087. }
  4088. css_failed:
  4089. if (rv <= 0) {
  4090. /* One synchronous retry: a dropped sheet leaves the
  4091. * whole page unstyled (seen intermittently on
  4092. * arstechnica's CDN). */
  4093. u_puts("[css] retry ");
  4094. u_puts(urls[i]);
  4095. u_puts(": ");
  4096. u_puts(err[0] ? err : "no worker/empty body");
  4097. u_putc('\n');
  4098. err[0] = '\0';
  4099. rv = fetch_css(urls[i], &data, &len, err,
  4100. sizeof(err));
  4101. if (rv == FETCH_ABORT) {
  4102. fetch_workers_stop_all();
  4103. return FETCH_ABORT;
  4104. }
  4105. if (rv != 0 || !len) {
  4106. u_puts("[css] failed: ");
  4107. u_puts(err);
  4108. u_putc('\n');
  4109. continue;
  4110. }
  4111. } else {
  4112. len = (unsigned int)rv;
  4113. data = image_io_buf;
  4114. css_cache_put(urls[i], data, len);
  4115. }
  4116. }
  4117. if (len) {
  4118. br_set_font_base(urls[i]);
  4119. br_parse_css_text(&doc, (const char *)data, len);
  4120. }
  4121. }
  4122. br_set_font_base(page_url);
  4123. br_parse_inline_css(&doc);
  4124. load_font_faces();
  4125. br_reset_styles(&doc);
  4126. layout_valid = 0;
  4127. return 0;
  4128. }
  4129. static void preload_begin(void)
  4130. {
  4131. preload_active = 1;
  4132. preload_pending = 0;
  4133. preload_wait = 1;
  4134. preload_max_jobs = FETCH_WORKERS;
  4135. preload_node = 0;
  4136. preload_loaded = 0;
  4137. preload_scroll = 0;
  4138. img_stat_start = u_ticks_ms();
  4139. img_stat_wall = 0;
  4140. img_stat_net = img_stat_open = img_stat_first = 0;
  4141. img_stat_io = img_stat_dec = img_stat_scale = 0;
  4142. img_stat_paint = img_stat_reflow = 0;
  4143. img_stat_bytes = 0;
  4144. img_stat_n = 0;
  4145. img_stat_log_len = 0;
  4146. if (img_stat_log[0])
  4147. img_stat_log[0] = '\0';
  4148. img_repaint_ms = 0;
  4149. img_repaint_pending = 0;
  4150. }
  4151. /* Styles are computed top-down during layout, but images inside a hidden
  4152. * menu/carousel are never visited and keep img_top == 0. Without this check
  4153. * the preloader walks the DOM in node order and spends the whole image
  4154. * budget on logos and off-canvas thumbnails the reader cannot see. */
  4155. static int node_hidden(unsigned int node)
  4156. {
  4157. unsigned int path[32], n = 0, p = node, i;
  4158. struct br_style st, parent;
  4159. while (p && n < sizeof(path) / sizeof(path[0])) {
  4160. path[n++] = p;
  4161. p = doc.nodes[p].parent;
  4162. }
  4163. parent = (struct br_style){0};
  4164. parent.font_px = 16;
  4165. parent.display = BR_DISPLAY_BLOCK;
  4166. for (i = n; i > 0; i--) {
  4167. br_style_for(&doc, path[i - 1], &parent, &st);
  4168. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  4169. st.opacity_hidden)
  4170. return 1;
  4171. parent = st;
  4172. }
  4173. return 0;
  4174. }
  4175. static struct br_style base_style(void);
  4176. static int style_width_px(const struct br_style *st, int base);
  4177. static int style_height_px(const struct br_style *st, int base);
  4178. static void style_for_node(unsigned int node, struct br_style *out)
  4179. {
  4180. unsigned int p = doc.nodes[node].parent;
  4181. struct br_style parent;
  4182. if (p) {
  4183. style_for_node(p, &parent);
  4184. br_style_for(&doc, node, &parent, out);
  4185. } else {
  4186. parent = base_style();
  4187. br_style_for(&doc, node, &parent, out);
  4188. }
  4189. }
  4190. /* ---- parallel image preloading ---- *
  4191. *
  4192. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  4193. * preload_step() only starts jobs and harvests completed ones; the browser
  4194. * main loop keeps drawing between calls, instead of blocking on one fetch.
  4195. */
  4196. static int preload_active_jobs(void)
  4197. {
  4198. int i, n = 0;
  4199. for (i = 0; i < FETCH_WORKERS; i++)
  4200. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  4201. n++;
  4202. return n;
  4203. }
  4204. static void preload_job_error(struct fetch_worker *w)
  4205. {
  4206. if (w->node < doc.nnode) {
  4207. if (w->bg)
  4208. doc.nodes[w->node].bg_img_index = -2;
  4209. else
  4210. doc.nodes[w->node].img_index = -2;
  4211. image_repaint();
  4212. }
  4213. }
  4214. /* Is the image's box anywhere near the visible page? A decode below the
  4215. * fold changes the layout (scroll extent) but not a single on-screen pixel,
  4216. * so it does not need a repaint. top/h come from the last layout; treat an
  4217. * unknown box as visible to stay safe. */
  4218. static int image_preload_visible(unsigned int node, int bg)
  4219. {
  4220. int top, h, scroll;
  4221. if (node >= BR_MAX_NODES || node >= doc.nnode || page_rect.h <= 0)
  4222. return 1;
  4223. if (bg) {
  4224. top = (int)block_top[node];
  4225. h = (int)block_h[node];
  4226. } else {
  4227. top = (int)img_top[node];
  4228. h = (int)img_h[node];
  4229. }
  4230. if (!top && !h)
  4231. return 1;
  4232. scroll = (int)page_scroll.offset;
  4233. if (top > scroll + page_rect.h + 160)
  4234. return 0;
  4235. if (top + h + 160 < scroll)
  4236. return 0;
  4237. return 1;
  4238. }
  4239. /* Upper bounds for the bitmap an <img> will paint. Zero means "unbounded";
  4240. * decode_image_data applies one scale to both axes so the aspect ratio is
  4241. * preserved. This is what keeps a 1200x800 photo that CSS paints at 400 px
  4242. * from being decoded and box-filtered to the 1000 px layout cap first. */
  4243. static void image_fit_size(unsigned int node, int *out_w, int *out_h)
  4244. {
  4245. struct br_style st;
  4246. struct br_node *nd;
  4247. unsigned int p;
  4248. int cw, w = 0, h = 0;
  4249. *out_w = *out_h = 0;
  4250. if (node >= doc.nnode)
  4251. return;
  4252. nd = &doc.nodes[node];
  4253. style_for_node(node, &st);
  4254. cw = page_rect.w > 24 ? page_rect.w - 24 : 0;
  4255. p = doc.nodes[node].parent;
  4256. if (p && p < BR_MAX_NODES && layout_boxes[p].valid &&
  4257. layout_boxes[p].w > 0 && layout_boxes[p].w < cw)
  4258. cw = layout_boxes[p].w;
  4259. if (st.width_kind)
  4260. w = style_width_px(&st, cw);
  4261. else if (nd->width_attr)
  4262. w = nd->width_pct ? cw * (int)nd->width_attr / 100 :
  4263. (int)nd->width_attr;
  4264. if (st.height_kind)
  4265. h = style_height_px(&st, cw);
  4266. else if (nd->height_attr)
  4267. h = nd->height_pct ? cw * (int)nd->height_attr / 100 :
  4268. (int)nd->height_attr;
  4269. if (st.max_width_kind) {
  4270. int mw = st.max_width_kind == 3 ?
  4271. cw * st.max_width_calc_pct / 100 +
  4272. st.max_width_calc_px :
  4273. st.max_width_kind == 2 ?
  4274. cw * (int)st.max_width / 100 :
  4275. (int)st.max_width;
  4276. if (mw > 0 && (w == 0 || w > mw))
  4277. w = mw;
  4278. }
  4279. if (st.max_height_kind) {
  4280. int mh = st.max_height_kind == 3 ?
  4281. cw * st.max_height_calc_pct / 100 +
  4282. st.max_height_calc_px :
  4283. st.max_height_kind == 2 ?
  4284. cw * (int)st.max_height / 100 :
  4285. (int)st.max_height;
  4286. if (mh > 0 && (h == 0 || h > mh))
  4287. h = mh;
  4288. }
  4289. if (w > BR_IMG_LAYOUT_W)
  4290. w = BR_IMG_LAYOUT_W;
  4291. if (h > 4096)
  4292. h = 4096;
  4293. if (w < 0)
  4294. w = 0;
  4295. if (h < 0)
  4296. h = 0;
  4297. *out_w = w;
  4298. *out_h = h;
  4299. }
  4300. static void preload_accept_image(unsigned int node, int bg, const char *url)
  4301. {
  4302. /* An <img> bitmap only depends on its URL, so the next <img> with the
  4303. * same source reuses it (heise repeats one comment icon 85 times).
  4304. * Backgrounds are scaled to their box and are not shared. */
  4305. images[image_count].url_hash =
  4306. !bg && url ? script_cache_hash(url) | 1u : 0;
  4307. if (bg)
  4308. doc.nodes[node].bg_img_index = (short)image_count;
  4309. else
  4310. doc.nodes[node].img_index = (short)image_count;
  4311. image_count++;
  4312. preload_loaded++;
  4313. /* A background bitmap never changes its box, so keep the (expensive)
  4314. * measured layout and only repaint the pixels. */
  4315. if (bg)
  4316. page_cache_valid = 0;
  4317. else
  4318. layout_valid = 0;
  4319. if (image_preload_visible(node, bg))
  4320. image_repaint();
  4321. }
  4322. /* Install a bitmap decoded by the fetch helper. The helper already applied
  4323. * the display bounds (and the JPEG reduced IDCT), so this is a read + copy
  4324. * on the UI thread instead of a decode. */
  4325. static int preload_store_helper(unsigned int node, int bg,
  4326. unsigned char *px, unsigned int pxlen,
  4327. unsigned int dw, unsigned int dh,
  4328. int alpha, unsigned int nw, unsigned int nh,
  4329. const char *url)
  4330. {
  4331. struct br_image *bi;
  4332. unsigned int npx;
  4333. if (image_count >= BR_MAX_IMAGES || !px || !dw || !dh ||
  4334. dw > 4096 || dh > 4096) {
  4335. free(px);
  4336. return -1;
  4337. }
  4338. npx = dw * dh;
  4339. if (image_pixels + npx > BR_IMG_PIXEL_BUDGET ||
  4340. pxlen < npx * 2u + (alpha ? npx : 0)) {
  4341. free(px);
  4342. return -1;
  4343. }
  4344. bi = &images[image_count];
  4345. bi->img.format = 0;
  4346. bi->img.w = dw;
  4347. bi->img.h = dh;
  4348. bi->img.px = (unsigned short *)px;
  4349. bi->img.alpha = alpha ? px + npx * 2u : 0;
  4350. bi->img.flags = 0;
  4351. bi->native_w = nw ? (int)nw : (int)dw;
  4352. bi->native_h = nh ? (int)nh : (int)dh;
  4353. bi->state = 1;
  4354. image_pixels += npx;
  4355. preload_accept_image(node, bg, url);
  4356. return 0;
  4357. }
  4358. static void preload_decode(unsigned int node, int bg,
  4359. const unsigned char *data, unsigned int len,
  4360. const char *url)
  4361. {
  4362. int fit_w = 0, fit_h = 0;
  4363. if (image_count >= BR_MAX_IMAGES) {
  4364. if (bg)
  4365. doc.nodes[node].bg_img_index = -2;
  4366. else
  4367. doc.nodes[node].img_index = -2;
  4368. return;
  4369. }
  4370. if (!bg)
  4371. image_fit_size(node, &fit_w, &fit_h);
  4372. if (decode_image_data(data, len, &images[image_count],
  4373. bg && node < BR_MAX_NODES &&
  4374. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  4375. bg && node < BR_MAX_NODES &&
  4376. layout_boxes[node].valid ? layout_boxes[node].h : 0,
  4377. fit_w, fit_h) == 0) {
  4378. preload_accept_image(node, bg, url);
  4379. } else {
  4380. if (bg)
  4381. doc.nodes[node].bg_img_index = -2;
  4382. else
  4383. doc.nodes[node].img_index = -2;
  4384. layout_valid = 0;
  4385. }
  4386. if (image_preload_visible(node, bg))
  4387. image_repaint();
  4388. }
  4389. /* A local file image bypasses the helpers: count its decode so a page opened
  4390. * from /share or /data still produces the same timing breakdown. */
  4391. static void img_stat_local(int before, unsigned int bytes, unsigned int io_ms)
  4392. {
  4393. img_stat_n++;
  4394. img_stat_bytes += bytes;
  4395. img_stat_io += io_ms;
  4396. if (image_count > before) {
  4397. struct br_image *bi = &images[image_count - 1];
  4398. img_stat_dec += img_last_dec_ms;
  4399. img_stat_scale += img_last_scale_ms;
  4400. if (img_stat_log_len + 100 < sizeof(img_stat_log)) {
  4401. unsigned int n = img_stat_log_len;
  4402. s_append(img_stat_log, &n, "local ", sizeof(img_stat_log));
  4403. s_append_dec(img_stat_log, &n, bytes,
  4404. sizeof(img_stat_log));
  4405. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4406. s_append_dec(img_stat_log, &n, img_last_dec_ms,
  4407. sizeof(img_stat_log));
  4408. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4409. s_append_dec(img_stat_log, &n, img_last_scale_ms,
  4410. sizeof(img_stat_log));
  4411. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4412. s_append_dec(img_stat_log, &n,
  4413. (unsigned int)bi->native_w,
  4414. sizeof(img_stat_log));
  4415. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4416. s_append_dec(img_stat_log, &n,
  4417. (unsigned int)bi->native_h,
  4418. sizeof(img_stat_log));
  4419. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4420. s_append_dec(img_stat_log, &n, bi->img.w,
  4421. sizeof(img_stat_log));
  4422. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4423. s_append_dec(img_stat_log, &n, bi->img.h,
  4424. sizeof(img_stat_log));
  4425. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4426. s_append_dec(img_stat_log, &n,
  4427. bi->img.alpha ? 1u : 0u,
  4428. sizeof(img_stat_log));
  4429. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4430. img_stat_log_len = n;
  4431. }
  4432. }
  4433. }
  4434. /* Harvest one completed worker. Returns 1 when a job was finished. */
  4435. static int preload_finish_worker(struct fetch_worker *w)
  4436. {
  4437. char err[64];
  4438. int rv, tr = 0;
  4439. unsigned int t0, io_ms;
  4440. int before;
  4441. int used_px = 0;
  4442. rv = fetch_worker_poll(w, err, sizeof(err));
  4443. if (rv < 0) {
  4444. /* A helper from an older pack does not understand the image
  4445. * decode request; retry once without it and decode in-process. */
  4446. if (w->image_job && w->dec_w && !w->dec_retried &&
  4447. fetch_worker_submit_req(w, w->url, BR_IMG_FILE_MAX,
  4448. 0, 0, 0, 0, w->node, w->bg,
  4449. 0, 0, err, sizeof(err)) == 0) {
  4450. w->image_job = 1;
  4451. w->dec_retried = 1;
  4452. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4453. return 0;
  4454. }
  4455. preload_job_error(w);
  4456. if (img_stat_log_len + 64 < sizeof(img_stat_log)) {
  4457. unsigned int n = img_stat_log_len;
  4458. char u[48];
  4459. s_copy(u, w->url, sizeof(u));
  4460. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4461. s_append(img_stat_log, &n, " error\n",
  4462. sizeof(img_stat_log));
  4463. img_stat_log_len = n;
  4464. }
  4465. img_stat_n++;
  4466. fetch_worker_release(w);
  4467. return 1;
  4468. }
  4469. if (rv == 0)
  4470. return 0;
  4471. t0 = u_ticks_ms();
  4472. rv = -1;
  4473. before = image_count;
  4474. if (w->m.px_len && !w->m.dec_err && w->m.dw && w->m.dh &&
  4475. w->m.px_len <= 8u * 1024u * 1024u) {
  4476. unsigned char *px = (unsigned char *)malloc(w->m.px_len);
  4477. int pr = -1;
  4478. if (px)
  4479. pr = u_syscall3(SYS_READ_FILE, (int)w->px, (int)px,
  4480. (int)w->m.px_len);
  4481. if (pr == (int)w->m.px_len) {
  4482. if (preload_store_helper(w->node, w->bg, px,
  4483. w->m.px_len, w->m.dw,
  4484. w->m.dh, (int)w->m.alpha,
  4485. w->m.nw, w->m.nh,
  4486. w->url) == 0) {
  4487. rv = (int)w->m.len;
  4488. img_last_dec_ms = w->m.dec_ms;
  4489. img_last_scale_ms = 0;
  4490. used_px = 1;
  4491. } else {
  4492. px = 0; /* the helper freed it */
  4493. }
  4494. }
  4495. if (px && !(pr == (int)w->m.px_len))
  4496. free(px);
  4497. }
  4498. io_ms = u_ticks_ms() - t0;
  4499. if (rv < 0) {
  4500. t0 = u_ticks_ms();
  4501. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  4502. image_comp_buf, BR_IMG_FILE_MAX,
  4503. &tr, err, sizeof(err));
  4504. io_ms += u_ticks_ms() - t0;
  4505. before = image_count;
  4506. if (rv >= 0)
  4507. preload_decode(w->node, w->bg, image_file_buf,
  4508. (unsigned int)rv, w->url);
  4509. else
  4510. preload_job_error(w);
  4511. }
  4512. img_stat_n++;
  4513. img_stat_net += w->m.total_ms;
  4514. img_stat_open += w->m.open_ms;
  4515. img_stat_first += w->m.first_ms;
  4516. img_stat_io += io_ms;
  4517. img_stat_bytes += rv > 0 ? (unsigned int)rv : 0;
  4518. img_stat_dec += w->m.dec_ms;
  4519. if (rv >= 0 && !used_px) {
  4520. img_stat_dec += img_last_dec_ms;
  4521. img_stat_scale += img_last_scale_ms;
  4522. }
  4523. if (img_stat_log_len + 160 < sizeof(img_stat_log)) {
  4524. unsigned int n = img_stat_log_len;
  4525. char u[48];
  4526. s_copy(u, w->url, sizeof(u));
  4527. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4528. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4529. s_append_dec(img_stat_log, &n,
  4530. rv > 0 ? (unsigned int)rv : 0,
  4531. sizeof(img_stat_log));
  4532. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4533. s_append_dec(img_stat_log, &n, w->m.open_ms,
  4534. sizeof(img_stat_log));
  4535. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4536. s_append_dec(img_stat_log, &n, w->m.first_ms,
  4537. sizeof(img_stat_log));
  4538. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4539. s_append_dec(img_stat_log, &n, w->m.total_ms,
  4540. sizeof(img_stat_log));
  4541. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4542. s_append_dec(img_stat_log, &n, io_ms, sizeof(img_stat_log));
  4543. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4544. s_append_dec(img_stat_log, &n,
  4545. rv >= 0 ? img_last_dec_ms : 0,
  4546. sizeof(img_stat_log));
  4547. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4548. s_append_dec(img_stat_log, &n,
  4549. rv >= 0 ? img_last_scale_ms : 0,
  4550. sizeof(img_stat_log));
  4551. if (image_count > before) {
  4552. struct br_image *bi = &images[image_count - 1];
  4553. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4554. s_append_dec(img_stat_log, &n,
  4555. (unsigned int)bi->native_w,
  4556. sizeof(img_stat_log));
  4557. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4558. s_append_dec(img_stat_log, &n,
  4559. (unsigned int)bi->native_h,
  4560. sizeof(img_stat_log));
  4561. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4562. s_append_dec(img_stat_log, &n, bi->img.w,
  4563. sizeof(img_stat_log));
  4564. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4565. s_append_dec(img_stat_log, &n, bi->img.h,
  4566. sizeof(img_stat_log));
  4567. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4568. s_append_dec(img_stat_log, &n,
  4569. bi->img.alpha ? 1u : 0u,
  4570. sizeof(img_stat_log));
  4571. }
  4572. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4573. img_stat_log_len = n;
  4574. }
  4575. fetch_worker_release(w);
  4576. return 1;
  4577. }
  4578. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  4579. * the number of jobs started. */
  4580. static int preload_fill_jobs(void)
  4581. {
  4582. int started = 0;
  4583. char err[64];
  4584. while (preload_active && preload_node < doc.nnode) {
  4585. unsigned int i = preload_node;
  4586. struct br_node *nd = &doc.nodes[i];
  4587. const char *src;
  4588. char url[BR_URL_MAX];
  4589. struct fetch_worker *w;
  4590. if (preload_active_jobs() >= preload_max_jobs)
  4591. break;
  4592. if (nd->type != BR_NODE_ELEM) {
  4593. preload_node++;
  4594. continue;
  4595. }
  4596. if (nd->tag != BR_TAG_IMG) {
  4597. if (nd->bg_img_index == -1) {
  4598. struct br_style bs;
  4599. style_for_node(i, &bs);
  4600. if (bs.display != BR_DISPLAY_NONE &&
  4601. !bs.vis_hidden && bs.bg_image) {
  4602. const char *bsrc =
  4603. br_bg_image_url(bs.bg_image - 1);
  4604. /* Lazy like <img>: a background box
  4605. * below the viewport (or not laid
  4606. * out yet) waits for the next scan. */
  4607. if (bsrc[0] &&
  4608. (!layout_boxes[i].valid ||
  4609. block_top[i] >
  4610. (unsigned int)(page_scroll.offset +
  4611. page_rect.h + 160))) {
  4612. preload_pending = 1;
  4613. preload_node++;
  4614. continue;
  4615. }
  4616. if (bsrc[0] &&
  4617. !starts_with(bsrc, "data:") &&
  4618. resolve_link(page_url, bsrc, url,
  4619. sizeof(url)) == 0) {
  4620. if (image_count +
  4621. preload_active_jobs() >=
  4622. BR_MAX_IMAGES) {
  4623. preload_node = doc.nnode;
  4624. break;
  4625. }
  4626. if (url[0] == '/') {
  4627. unsigned char *data = 0;
  4628. unsigned int len = 0;
  4629. unsigned int t0;
  4630. int before;
  4631. preload_node = i + 1;
  4632. before = image_count;
  4633. t0 = u_ticks_ms();
  4634. if (fetch_image(url,
  4635. BR_IMG_FILE_MAX,
  4636. &data, &len,
  4637. err,
  4638. sizeof(err)) == 0) {
  4639. preload_decode(i, 1, data, len, 0);
  4640. img_stat_local(before, len,
  4641. u_ticks_ms() - t0);
  4642. } else {
  4643. nd->bg_img_index = -2;
  4644. }
  4645. continue;
  4646. }
  4647. w = fetch_worker_alloc();
  4648. if (!w)
  4649. return started;
  4650. preload_node = i + 1;
  4651. if (fetch_worker_submit(w, url,
  4652. BR_IMG_FILE_MAX,
  4653. 0, 0, i, 1,
  4654. err,
  4655. sizeof(err)) != 0) {
  4656. nd->bg_img_index = -2;
  4657. fetch_worker_release(w);
  4658. continue;
  4659. }
  4660. w->image_job = 1;
  4661. w->deadline = u_ticks_ms() +
  4662. BR_IMG_JOB_TIMEOUT_MS;
  4663. /* in flight: rescans skip it */
  4664. nd->bg_img_index = -3;
  4665. started++;
  4666. continue;
  4667. }
  4668. }
  4669. nd->bg_img_index = -2;
  4670. }
  4671. preload_node++;
  4672. continue;
  4673. }
  4674. if (nd->img_index != -1) {
  4675. preload_node++;
  4676. continue;
  4677. }
  4678. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  4679. preload_node++;
  4680. continue;
  4681. }
  4682. src = br_src(&doc, i);
  4683. if (!src[0] || starts_with(src, "data:")) {
  4684. preload_node++;
  4685. continue;
  4686. }
  4687. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  4688. preload_node++;
  4689. continue;
  4690. }
  4691. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  4692. preload_node = doc.nnode;
  4693. break;
  4694. }
  4695. /* Do not stop at the first below-fold image: DOM order is
  4696. * not visual order, and a footer/ad image early in the DOM
  4697. * used to hide every later article image from the loader. */
  4698. if (img_top[i] >
  4699. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  4700. preload_pending = 1;
  4701. preload_node++;
  4702. continue;
  4703. }
  4704. {
  4705. unsigned int uh = script_cache_hash(url) | 1u;
  4706. int k;
  4707. for (k = 0; k < image_count; k++)
  4708. if (images[k].state == 1 &&
  4709. images[k].url_hash == uh)
  4710. break;
  4711. if (k < image_count) {
  4712. nd->img_index = (short)k;
  4713. layout_valid = 0;
  4714. preload_node = i + 1;
  4715. image_repaint();
  4716. continue;
  4717. }
  4718. }
  4719. if (url[0] == '/') {
  4720. unsigned char *data = 0;
  4721. unsigned int len = 0;
  4722. unsigned int t0;
  4723. int before;
  4724. preload_node = i + 1;
  4725. before = image_count;
  4726. t0 = u_ticks_ms();
  4727. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  4728. err, sizeof(err)) == 0) {
  4729. preload_decode(i, 0, data, len, url);
  4730. img_stat_local(before, len, u_ticks_ms() - t0);
  4731. } else {
  4732. nd->img_index = -2;
  4733. }
  4734. continue;
  4735. }
  4736. w = fetch_worker_alloc();
  4737. if (!w)
  4738. return started;
  4739. preload_node = i + 1;
  4740. {
  4741. char msg[64];
  4742. unsigned int n = 0;
  4743. s_append(msg, &n, "Loading images ", sizeof(msg));
  4744. s_append_dec(msg, &n,
  4745. (unsigned int)preload_loaded + 1,
  4746. sizeof(msg));
  4747. s_append(msg, &n, "...", sizeof(msg));
  4748. set_status_quiet(msg);
  4749. image_repaint();
  4750. }
  4751. {
  4752. int fit_w = 0, fit_h = 0;
  4753. image_fit_size(i, &fit_w, &fit_h);
  4754. if (!fit_w)
  4755. fit_w = BR_IMG_LAYOUT_W;
  4756. if (fetch_worker_submit_image(w, url, BR_IMG_FILE_MAX,
  4757. i, 0,
  4758. (unsigned int)fit_w,
  4759. (unsigned int)fit_h,
  4760. err, sizeof(err)) != 0) {
  4761. nd->img_index = -2;
  4762. fetch_worker_release(w);
  4763. continue;
  4764. }
  4765. }
  4766. w->image_job = 1;
  4767. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4768. nd->img_index = -3; /* in flight: rescans skip it */
  4769. started++;
  4770. }
  4771. return started;
  4772. }
  4773. /* Report where the image batch spent its time: status bar for the headline,
  4774. * /share/IMGSTAT for the per-image breakdown (cat it from a terminal). */
  4775. static void img_stats_report(void)
  4776. {
  4777. char msg[80];
  4778. static char out[BR_IMG_STAT_LOG + 512];
  4779. unsigned int n = 0, o = 0;
  4780. if (!img_stat_n)
  4781. return;
  4782. img_stat_wall = img_stat_start ?
  4783. u_ticks_ms() - img_stat_start : 1;
  4784. if (!img_stat_wall)
  4785. img_stat_wall = 1;
  4786. /* Compact on-screen form; /share/IMGSTAT has the full breakdown. */
  4787. s_append(msg, &n, "img ", sizeof(msg));
  4788. s_append_dec(msg, &n, (unsigned int)img_stat_n, sizeof(msg));
  4789. s_append(msg, &n, " ", sizeof(msg));
  4790. s_append_dec(msg, &n, img_stat_wall, sizeof(msg));
  4791. s_append(msg, &n, "ms net ", sizeof(msg));
  4792. s_append_dec(msg, &n, img_stat_net, sizeof(msg));
  4793. s_append(msg, &n, " dec ", sizeof(msg));
  4794. s_append_dec(msg, &n, img_stat_dec, sizeof(msg));
  4795. s_append(msg, &n, " sc ", sizeof(msg));
  4796. s_append_dec(msg, &n, img_stat_scale, sizeof(msg));
  4797. s_append(msg, &n, " paint ", sizeof(msg));
  4798. s_append_dec(msg, &n, img_stat_paint, sizeof(msg));
  4799. /* Keep the page's phase breakdown and append the image summary when
  4800. * it fits; never hide a JS error or a truncation notice. */
  4801. if (!post_status_error && !contains_ci(post_status_text, "truncated")) {
  4802. unsigned int plen = s_len(post_status_text);
  4803. if (!plen) {
  4804. s_copy(post_status_text, msg, sizeof(post_status_text));
  4805. } else if (plen + s_len(msg) + 4 < sizeof(post_status_text)) {
  4806. unsigned int pn = plen;
  4807. s_append(post_status_text, &pn, " | ",
  4808. sizeof(post_status_text));
  4809. s_append(post_status_text, &pn, msg,
  4810. sizeof(post_status_text));
  4811. } else {
  4812. s_copy(post_status_text, msg, sizeof(post_status_text));
  4813. }
  4814. post_status_ttl = 12000;
  4815. }
  4816. s_append(out, &o, "browser image stats\n", sizeof(out));
  4817. s_append(out, &o, "n=", sizeof(out));
  4818. s_append_dec(out, &o, (unsigned int)img_stat_n, sizeof(out));
  4819. s_append(out, &o, " wall=", sizeof(out));
  4820. s_append_dec(out, &o, img_stat_wall, sizeof(out));
  4821. s_append(out, &o, " net=", sizeof(out));
  4822. s_append_dec(out, &o, img_stat_net, sizeof(out));
  4823. s_append(out, &o, " open=", sizeof(out));
  4824. s_append_dec(out, &o, img_stat_open, sizeof(out));
  4825. s_append(out, &o, " first=", sizeof(out));
  4826. s_append_dec(out, &o, img_stat_first, sizeof(out));
  4827. s_append(out, &o, " io=", sizeof(out));
  4828. s_append_dec(out, &o, img_stat_io, sizeof(out));
  4829. s_append(out, &o, " dec=", sizeof(out));
  4830. s_append_dec(out, &o, img_stat_dec, sizeof(out));
  4831. s_append(out, &o, " scale=", sizeof(out));
  4832. s_append_dec(out, &o, img_stat_scale, sizeof(out));
  4833. s_append(out, &o, " paint=", sizeof(out));
  4834. s_append_dec(out, &o, img_stat_paint, sizeof(out));
  4835. s_append(out, &o, " reflow=", sizeof(out));
  4836. s_append_dec(out, &o, img_stat_reflow, sizeof(out));
  4837. s_append(out, &o, " bytes=", sizeof(out));
  4838. s_append_dec(out, &o, img_stat_bytes, sizeof(out));
  4839. s_append(out, &o, "\nurl bytes open first total io dec scale native bitmap\n",
  4840. sizeof(out));
  4841. s_append(out, &o, img_stat_log, sizeof(out));
  4842. u_syscall3(SYS_WRITE_FILE, (int)"/share/IMGSTAT", (int)out,
  4843. (int)s_len(out));
  4844. }
  4845. static void preload_step(void)
  4846. {
  4847. int i;
  4848. unsigned int t0;
  4849. if (!preload_active)
  4850. return;
  4851. if (cancel_fetch || pending_action) {
  4852. preload_active = 0;
  4853. preload_pending = 0;
  4854. fetch_workers_cancel_busy();
  4855. return;
  4856. }
  4857. preload_fill_jobs();
  4858. /* Decode completed images in a short batch instead of one per pass.
  4859. * A pass used to decode one image and then sleep 10 ms, so a page of
  4860. * small icons trickled in at the decode rate. The budget keeps a
  4861. * single huge JPEG from monopolising the UI while small images
  4862. * finish together. */
  4863. t0 = u_ticks_ms();
  4864. for (i = 0; i < FETCH_WORKERS; i++) {
  4865. if (!fetch_workers[i].busy)
  4866. continue;
  4867. if (preload_finish_worker(&fetch_workers[i]) &&
  4868. u_ticks_ms() - t0 >= BR_IMG_DECODE_BUDGET_MS)
  4869. break;
  4870. }
  4871. if (preload_active && preload_node >= doc.nnode &&
  4872. preload_active_jobs() == 0) {
  4873. preload_active = 0;
  4874. if (preload_pending)
  4875. preload_scroll = page_scroll.offset;
  4876. else
  4877. preload_pending = 0;
  4878. /* Keep the now idle helpers and their connections; a later
  4879. * navigation reuses them. They exit after ten idle seconds,
  4880. * and losing window focus stops them at once. */
  4881. if (img_repaint_pending) {
  4882. img_repaint_pending = 0;
  4883. ngui_invalidate(&ui);
  4884. }
  4885. img_stats_report();
  4886. set_status(post_status_text, post_status_error, post_status_ttl);
  4887. ngui_invalidate(&ui);
  4888. }
  4889. }
  4890. /* Set by navigate() when it turned a typed bare host into https://; the next
  4891. * load_page() consumes it and may retry over http. */
  4892. static int nav_https_upgraded;
  4893. /* Errors that mean "https is not served here" rather than "the site is
  4894. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  4895. static int https_fallback_error(int e)
  4896. {
  4897. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  4898. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  4899. e == UHTTP_ERR_RESET;
  4900. }
  4901. static void history_push(const char *url)
  4902. {
  4903. if (!url || !url[0])
  4904. return;
  4905. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  4906. s_eq(history[hist_pos], url))
  4907. return;
  4908. if (hist_len > 0 && hist_pos + 1 < hist_len)
  4909. hist_len = hist_pos + 1;
  4910. if (hist_len < BR_HISTORY) {
  4911. s_copy(history[hist_len], url, BR_URL_MAX);
  4912. hist_pos = hist_len;
  4913. hist_len++;
  4914. } else {
  4915. int i;
  4916. for (i = 1; i < BR_HISTORY; i++)
  4917. s_copy(history[i - 1], history[i], BR_URL_MAX);
  4918. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  4919. hist_pos = BR_HISTORY - 1;
  4920. }
  4921. }
  4922. static void load_page(const char *url, int local, int push)
  4923. {
  4924. unsigned char *body = 0;
  4925. unsigned int len = 0;
  4926. int truncated = 0;
  4927. struct img_info image_info;
  4928. char ctype[64];
  4929. char final[BR_URL_MAX];
  4930. char err[80];
  4931. const char *detail = 0;
  4932. const char *post = pending_post_is ? pending_post : 0;
  4933. unsigned int post_len = pending_post_len;
  4934. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  4935. /* Phase timings for the status line: where a slow load spends it. */
  4936. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  4937. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  4938. int upgraded = nav_https_upgraded;
  4939. int retried = 0;
  4940. int rv;
  4941. nav_https_upgraded = 0;
  4942. final[0] = '\0';
  4943. pending_post_len = 0;
  4944. pending_post_is = 0;
  4945. cancel_fetch = 0;
  4946. preload_active = 0;
  4947. preload_pending = 0;
  4948. fetch_workers_prepare_nav(url);
  4949. js_browser_stop();
  4950. js_last_status[0] = '\0';
  4951. js_last_error = 0;
  4952. heap_clear();
  4953. image_reset();
  4954. form_reset_state();
  4955. layout_valid = 0;
  4956. page_scroll.offset = 0;
  4957. page_scroll.dragging = 0;
  4958. page_title[0] = '\0';
  4959. page_loading = 1;
  4960. page_is_local = local;
  4961. s_copy(page_url, url, sizeof(page_url));
  4962. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4963. url_in.len = s_len(url_in.text);
  4964. url_in.cursor = url_in.len;
  4965. url_in.scroll = 0;
  4966. ngui_set_focus(&ui, 0);
  4967. if (final[0])
  4968. final[0] = '\0';
  4969. if (push)
  4970. history_push(url);
  4971. set_status("Loading...", 0, 0);
  4972. ngui_invalidate(&ui);
  4973. /* heap_clear() detaches the fonts, so attach them again before the
  4974. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  4975. if (heap_start() != 0) {
  4976. show_error("Out of memory", "Cannot allocate the page buffer");
  4977. return;
  4978. }
  4979. br_parse_plain(&doc, "", 0); /* blank while loading */
  4980. ngui_font_attach(&ui);
  4981. redraw_now();
  4982. browser_rules_alloc();
  4983. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  4984. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  4985. &truncated, post, post_len);
  4986. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  4987. fetch_last_error == UHTTP_ERR_DNS) {
  4988. /* A busy previous page can leave the receiver ring full just
  4989. * long enough to lose a DNS reply. Tear the old helpers down
  4990. * and try once more before giving up. */
  4991. retried = 1;
  4992. fetch_workers_stop_all();
  4993. u_sleep_ms(500);
  4994. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  4995. sizeof(ctype), final, sizeof(final), err,
  4996. sizeof(err), &truncated, post, post_len);
  4997. }
  4998. if (rv == FETCH_ABORT)
  4999. return;
  5000. t_fetch = u_ticks_ms() - t_start;
  5001. /* Capture the page timing before CSS/script/image fetches overwrite the
  5002. * shared fetch_meta block. */
  5003. if (rv == 0 && !local) {
  5004. page_open_ms = fetch_meta.open_ms;
  5005. page_first_ms = fetch_meta.first_ms;
  5006. page_total_ms = fetch_meta.total_ms;
  5007. }
  5008. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  5009. https_fallback_error(fetch_last_error)) {
  5010. char http_url[BR_URL_MAX];
  5011. unsigned int n = 0;
  5012. s_append(http_url, &n, "http://", sizeof(http_url));
  5013. s_append(http_url, &n, url + 8, sizeof(http_url));
  5014. /* Replace the https entry instead of adding a second one. */
  5015. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  5016. s_eq(history[hist_pos], url))
  5017. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  5018. load_page(http_url, 0, 0);
  5019. return;
  5020. }
  5021. if (rv != 0) {
  5022. detail = err;
  5023. show_error("Cannot load this page", detail);
  5024. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5025. url_in.len = s_len(url_in.text);
  5026. url_in.cursor = url_in.len;
  5027. url_in.scroll = 0;
  5028. return;
  5029. }
  5030. if (!local)
  5031. origin_cache_learn(url, final[0] ? final : url);
  5032. page_is_local = local;
  5033. if (final[0]) {
  5034. s_copy(page_url, final, sizeof(page_url));
  5035. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5036. url_in.len = s_len(url_in.text);
  5037. url_in.cursor = url_in.len;
  5038. url_in.scroll = 0;
  5039. }
  5040. if (contains_ci(ctype, "text/plain")) {
  5041. br_parse_plain(&doc, (const char *)body, len);
  5042. } else if (contains_ci(ctype, "image/") ||
  5043. (!contains_ci(ctype, "text/html") &&
  5044. img_sniff(body, len, &image_info) == 0)) {
  5045. unsigned int node = br_parse_image_doc(&doc, page_url);
  5046. if (node)
  5047. decode_direct_image(body, len, node);
  5048. s_copy(page_title, "Image", sizeof(page_title));
  5049. } else {
  5050. br_set_viewport(ui.w);
  5051. t_mark = u_ticks_ms();
  5052. br_parse(&doc, (const char *)body, len);
  5053. t_parse = u_ticks_ms() - t_mark;
  5054. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  5055. sizeof(page_title));
  5056. t_mark = u_ticks_ms();
  5057. if (load_stylesheets() == FETCH_ABORT)
  5058. return;
  5059. t_css = u_ticks_ms() - t_mark;
  5060. if (pending_action)
  5061. return;
  5062. }
  5063. preload_begin();
  5064. page_loading = 0;
  5065. hist_visit(page_url, page_title);
  5066. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5067. url_in.len = s_len(url_in.text);
  5068. url_in.cursor = url_in.len;
  5069. url_in.scroll = 0;
  5070. ngui_set_focus(&ui, 0);
  5071. /* Paint the parsed page before fetching/running scripts. A slow
  5072. * remote <script src> then does not hide the page behind the loading
  5073. * screen; the fetch helper pumps this UI while it waits. */
  5074. set_status("Loading scripts...", 0, 0);
  5075. t_mark = u_ticks_ms();
  5076. redraw_now();
  5077. t_paint = u_ticks_ms() - t_mark;
  5078. /* Start one image download before the scripts. The other workers
  5079. * fetch the external script bodies in parallel, and the remaining
  5080. * images start as soon as the script phase ends. */
  5081. preload_max_jobs = 1;
  5082. preload_fill_jobs();
  5083. preload_wait = 0;
  5084. t_mark = u_ticks_ms();
  5085. run_page_scripts();
  5086. t_js = u_ticks_ms() - t_mark;
  5087. preload_max_jobs = FETCH_WORKERS;
  5088. if (pending_action)
  5089. return;
  5090. post_status_text[0] = '\0';
  5091. post_status_error = 0;
  5092. post_status_ttl = 0;
  5093. if (js_last_status[0]) {
  5094. s_copy(post_status_text, js_last_status,
  5095. sizeof(post_status_text));
  5096. post_status_error = js_last_error;
  5097. post_status_ttl = 8000;
  5098. } else if (truncated) {
  5099. s_copy(post_status_text, "Page truncated at the buffer limit",
  5100. sizeof(post_status_text));
  5101. post_status_ttl = 6000;
  5102. } else if (doc.truncated) {
  5103. s_copy(post_status_text, "Page truncated by the parser",
  5104. sizeof(post_status_text));
  5105. post_status_ttl = 6000;
  5106. } else if (page_total_ms) {
  5107. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  5108. * paint 220, js 1750" -- the phases of this load. */
  5109. unsigned int n = 0;
  5110. static const char *const names[] = {
  5111. ", parse ", ", css ", ", paint ", ", js "
  5112. };
  5113. unsigned int vals[4];
  5114. int k;
  5115. vals[0] = t_parse;
  5116. vals[1] = t_css;
  5117. vals[2] = t_paint;
  5118. vals[3] = t_js;
  5119. (void)page_first_ms;
  5120. if (starts_with(page_url, "https://"))
  5121. s_append(post_status_text, &n,
  5122. "HTTPS (not verified), ",
  5123. sizeof(post_status_text));
  5124. s_append(post_status_text, &n, "Loaded in ",
  5125. sizeof(post_status_text));
  5126. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  5127. sizeof(post_status_text));
  5128. s_append(post_status_text, &n, " ms: page ",
  5129. sizeof(post_status_text));
  5130. s_append_dec(post_status_text, &n, t_fetch,
  5131. sizeof(post_status_text));
  5132. s_append(post_status_text, &n, " (headers ",
  5133. sizeof(post_status_text));
  5134. s_append_dec(post_status_text, &n, page_open_ms,
  5135. sizeof(post_status_text));
  5136. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  5137. for (k = 0; k < 4; k++) {
  5138. s_append(post_status_text, &n, names[k],
  5139. sizeof(post_status_text));
  5140. s_append_dec(post_status_text, &n, vals[k],
  5141. sizeof(post_status_text));
  5142. }
  5143. post_status_ttl = 12000;
  5144. } else if (starts_with(page_url, "https://")) {
  5145. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  5146. sizeof(post_status_text));
  5147. post_status_ttl = 6000;
  5148. }
  5149. set_status(post_status_text, post_status_error, post_status_ttl);
  5150. ngui_invalidate(&ui);
  5151. }
  5152. static void load_home(int push)
  5153. {
  5154. pending_post_len = 0;
  5155. pending_post_is = 0;
  5156. cancel_fetch = 0;
  5157. preload_active = 0;
  5158. preload_pending = 0;
  5159. js_browser_stop();
  5160. js_last_status[0] = '\0';
  5161. js_last_error = 0;
  5162. heap_clear();
  5163. image_reset();
  5164. form_reset_state();
  5165. layout_valid = 0;
  5166. page_scroll.offset = 0;
  5167. page_scroll.dragging = 0;
  5168. page_loading = 1;
  5169. page_is_local = 0;
  5170. s_copy(page_url, "about:home", sizeof(page_url));
  5171. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5172. url_in.len = s_len(url_in.text);
  5173. url_in.cursor = url_in.len;
  5174. url_in.scroll = 0;
  5175. ngui_set_focus(&ui, 0);
  5176. if (push)
  5177. history_push(page_url);
  5178. ngui_invalidate(&ui);
  5179. /* See load_page(): reattach the fonts before the first redraw. */
  5180. if (heap_start() != 0) {
  5181. show_error("Out of memory", "Cannot allocate the browser heap");
  5182. return;
  5183. }
  5184. br_parse_plain(&doc, "", 0);
  5185. ngui_font_attach(&ui);
  5186. redraw_now();
  5187. browser_rules_alloc();
  5188. {
  5189. static const char home[] =
  5190. "<html><head><title>NebOS Browser</title><style>"
  5191. "body { margin: 10px; color: #e4e6f0; }"
  5192. "h1 { color: #7fb0ff; }"
  5193. ".box { background-color: #262b3a; margin: 12px; "
  5194. "padding: 10px; }"
  5195. "a { color: #7fb0ff; }"
  5196. "pre { background-color: #32384a; }"
  5197. "</style></head><body>"
  5198. "<h1>NebOS Browser</h1>"
  5199. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  5200. "shared HTTP client and the image library.</p>"
  5201. "<div class=\"box\"><b>Try:</b>"
  5202. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  5203. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  5204. "<li><a href=\"/floppy1/JS.HTM\">/"
  5205. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  5206. "<li><a href=\"http://10.0.2.2:8000/\">"
  5207. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  5208. "<li><a href=\"https://example.com/\">"
  5209. "https://example.com/</a> (TLS, not verified)</li>"
  5210. "</ul></div>"
  5211. "<p>Type a URL in the bar above. Esc closes the "
  5212. "window, Ctrl+L focuses the address bar.</p>"
  5213. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  5214. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  5215. "</body></html>";
  5216. br_set_viewport(ui.w);
  5217. br_parse(&doc, home, sizeof(home) - 1);
  5218. br_parse_inline_css(&doc);
  5219. br_reset_styles(&doc);
  5220. s_copy(page_title, doc.title, sizeof(page_title));
  5221. }
  5222. post_status_text[0] = '\0';
  5223. post_status_error = 0;
  5224. post_status_ttl = 0;
  5225. page_loading = 0;
  5226. set_status("", 0, 0);
  5227. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5228. url_in.len = s_len(url_in.text);
  5229. url_in.cursor = url_in.len;
  5230. url_in.scroll = 0;
  5231. ngui_set_focus(&ui, 0);
  5232. ngui_invalidate(&ui);
  5233. }
  5234. /* Extensions the browser opens from the local filesystem. A dotted input
  5235. * with one of these still resolves relative to the cwd. */
  5236. static int local_file_ext(const char *s)
  5237. {
  5238. static const char *const exts[] = {
  5239. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  5240. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  5241. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  5242. "cfg", "conf", 0
  5243. };
  5244. unsigned int i = 0, start = 0, len = 0, e;
  5245. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  5246. s[i] != '#') {
  5247. if (s[i] == '.') {
  5248. start = i + 1;
  5249. len = 0;
  5250. } else if (start) {
  5251. len++;
  5252. }
  5253. i++;
  5254. }
  5255. if (!len)
  5256. return 0;
  5257. for (e = 0; exts[e]; e++) {
  5258. const char *x = exts[e];
  5259. unsigned int xn = s_len(x), k;
  5260. if (xn != len)
  5261. continue;
  5262. for (k = 0; k < len; k++) {
  5263. char a = s[start + k];
  5264. if (a >= 'A' && a <= 'Z')
  5265. a = (char)(a - 'A' + 'a');
  5266. if (a != x[k])
  5267. break;
  5268. }
  5269. if (k == len)
  5270. return 1;
  5271. }
  5272. return 0;
  5273. }
  5274. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  5275. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  5276. * Enter to the first network request. */
  5277. static int looks_like_host(const char *s)
  5278. {
  5279. unsigned int i = 0;
  5280. int dot = 0;
  5281. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  5282. s[i] != ':') {
  5283. char c = s[i];
  5284. if (c == '.') {
  5285. dot = 1;
  5286. } else if (!((c >= 'a' && c <= 'z') ||
  5287. (c >= 'A' && c <= 'Z') ||
  5288. (c >= '0' && c <= '9') ||
  5289. c == '-' || c == '_')) {
  5290. return 0;
  5291. }
  5292. i++;
  5293. }
  5294. return dot && i > 0 && !local_file_ext(s);
  5295. }
  5296. static void load_remote(const char *url, int push)
  5297. {
  5298. char canon[BR_URL_MAX];
  5299. s_copy(canon, url, sizeof(canon));
  5300. origin_cache_apply(canon, sizeof(canon));
  5301. load_page(canon, 0, push);
  5302. }
  5303. static void navigate(const char *input, int push)
  5304. {
  5305. char target[BR_URL_MAX];
  5306. char *t;
  5307. if (!input)
  5308. return;
  5309. s_copy(target, input, sizeof(target));
  5310. t = trim(target);
  5311. if (!t[0])
  5312. return;
  5313. if (s_eq(t, "about:home")) {
  5314. load_home(push);
  5315. return;
  5316. }
  5317. if (starts_with(t, "file://")) {
  5318. make_abs_local(t + 7, target, sizeof(target));
  5319. load_page(target, 1, push);
  5320. return;
  5321. }
  5322. if (is_http(t)) {
  5323. load_remote(t, push);
  5324. return;
  5325. }
  5326. if (t[0] == '/') {
  5327. make_abs_local(t, target, sizeof(target));
  5328. load_page(target, 1, push);
  5329. return;
  5330. }
  5331. if (!looks_like_host(t)) {
  5332. struct sys_stat st;
  5333. if (u_stat(t, &st) == 0 && !st.is_dir) {
  5334. make_abs_local(t, target, sizeof(target));
  5335. load_page(target, 1, push);
  5336. return;
  5337. }
  5338. }
  5339. {
  5340. /* A typed bare host tries https first: nearly every site
  5341. * redirects http -> https anyway, and that hop costs a whole
  5342. * extra connection. load_page() falls back to http when the
  5343. * https connection itself fails. */
  5344. char with_scheme[BR_URL_MAX];
  5345. unsigned int n = 0;
  5346. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  5347. s_append(with_scheme, &n, t, sizeof(with_scheme));
  5348. nav_https_upgraded = 1;
  5349. load_remote(with_scheme, push);
  5350. }
  5351. }
  5352. /* ---- layout ---- */
  5353. static struct ufont_face *style_face(const struct br_style *st)
  5354. {
  5355. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  5356. return font_faces[st->font_face - 1];
  5357. return 0;
  5358. }
  5359. static struct ufont_face *run_face(const struct lay_run *r)
  5360. {
  5361. if (r->font_face && r->font_face <= BR_MAX_FACES)
  5362. return font_faces[r->font_face - 1];
  5363. return 0;
  5364. }
  5365. static unsigned int face_text_width(struct ngui *gui,
  5366. const struct br_style *st,
  5367. const char *s, unsigned int n)
  5368. {
  5369. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  5370. st->bold, st->italic, st->mono);
  5371. }
  5372. static int face_line_height(struct ngui *gui, const struct br_style *st)
  5373. {
  5374. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  5375. st->mono);
  5376. }
  5377. static unsigned int run_text_width(struct ngui *gui,
  5378. const struct lay_run *r,
  5379. const char *s, unsigned int n)
  5380. {
  5381. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  5382. r->bold, r->italic, r->mono);
  5383. }
  5384. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  5385. {
  5386. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  5387. r->mono);
  5388. }
  5389. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  5390. {
  5391. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  5392. }
  5393. static struct br_style base_style(void)
  5394. {
  5395. struct br_style s = { 0 };
  5396. s.color = ui.theme.text;
  5397. s.bg = ui.theme.bg;
  5398. s.has_bg = 0;
  5399. for (int i = 0; i < 4; i++) {
  5400. s.border_c[i] = 0;
  5401. s.border_w[i] = 0;
  5402. s.border_s[i] = BR_BORDER_SOLID;
  5403. }
  5404. s.font_px = 16;
  5405. s.bold = 0;
  5406. s.italic = 0;
  5407. s.mono = 0;
  5408. s.underline = 0;
  5409. s.strike = 0;
  5410. s.overline = 0;
  5411. s.align = BR_ALIGN_LEFT;
  5412. s.display = BR_DISPLAY_BLOCK;
  5413. s.no_bullet = 0;
  5414. s.list_style = BR_LIST_AUTO;
  5415. s.uppercase = 0;
  5416. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  5417. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  5418. s.width = s.max_width = s.min_width = 0;
  5419. s.height = s.min_height = s.max_height = 0;
  5420. s.box_sizing = 0;
  5421. s.ml_auto = s.mr_auto = 0;
  5422. s.line_h_pct = 0;
  5423. s.line_h_px = 0;
  5424. s.mt = s.mb = s.ml = s.mr = 0;
  5425. s.pt = s.pb = s.pl = s.pr = 0;
  5426. return s;
  5427. }
  5428. /* Resolve a margin/padding raw value. Percentages use the containing
  5429. * block width for all four sides, as CSS specifies. */
  5430. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  5431. {
  5432. if (unit == 1)
  5433. return base * v / 10000;
  5434. if (unit == 2)
  5435. return st->font_px * v / 100;
  5436. if (unit == 3)
  5437. return (int)br_root_font_px() * v / 100;
  5438. if (unit == 4)
  5439. return 0;
  5440. return v;
  5441. }
  5442. static int mp_px(const struct br_style *st, int side, int base)
  5443. {
  5444. int raw;
  5445. switch (side) {
  5446. case 0: raw = st->mt; break;
  5447. case 1: raw = st->mr; break;
  5448. case 2: raw = st->mb; break;
  5449. case 3: raw = st->ml; break;
  5450. case 4: raw = st->pt; break;
  5451. case 5: raw = st->pr; break;
  5452. case 6: raw = st->pb; break;
  5453. default: raw = st->pl; break;
  5454. }
  5455. if (st->mp_unit[side] == 5)
  5456. return base * raw / 100 + st->mp_calc_px[side];
  5457. return css_mp_px(st, raw, st->mp_unit[side], base);
  5458. }
  5459. static int style_width_px(const struct br_style *st, int base)
  5460. {
  5461. if (st->width_kind == 1)
  5462. return st->width;
  5463. if (st->width_kind == 2)
  5464. return base * (int)st->width / 100;
  5465. if (st->width_kind == 3)
  5466. return base * st->width_calc_pct / 100 + st->width_calc_px;
  5467. return 0;
  5468. }
  5469. static int style_height_px(const struct br_style *st, int base)
  5470. {
  5471. if (st->height_kind == 1)
  5472. return st->height;
  5473. if (st->height_kind == 2)
  5474. return base * (int)st->height / 100;
  5475. if (st->height_kind == 3)
  5476. return base * st->height_calc_pct / 100 + st->height_calc_px;
  5477. return 0;
  5478. }
  5479. static int css_size(unsigned char kind, int val, int base)
  5480. {
  5481. if (kind == 1)
  5482. return val;
  5483. if (kind == 2)
  5484. return base * val / 100;
  5485. return -1;
  5486. }
  5487. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  5488. int thick, int horizontal, unsigned short color,
  5489. unsigned char style)
  5490. {
  5491. int pos;
  5492. if (len <= 0 || thick <= 0)
  5493. return;
  5494. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  5495. if (horizontal)
  5496. ngui_fill_rect(ui, (struct ngui_rect){
  5497. x, y, len, thick}, color);
  5498. else
  5499. ngui_fill_rect(ui, (struct ngui_rect){
  5500. x, y, thick, len}, color);
  5501. return;
  5502. }
  5503. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  5504. int seg = len - pos;
  5505. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  5506. seg = style == BR_BORDER_DASHED ? 4 : 2;
  5507. if (horizontal)
  5508. ngui_fill_rect(ui, (struct ngui_rect){
  5509. x + pos, y, seg, thick}, color);
  5510. else
  5511. ngui_fill_rect(ui, (struct ngui_rect){
  5512. x, y + pos, thick, seg}, color);
  5513. }
  5514. }
  5515. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  5516. const struct br_style *st)
  5517. {
  5518. int top = st->border_w[0], right = st->border_w[1];
  5519. int bottom = st->border_w[2], left = st->border_w[3];
  5520. if (r.w <= 0 || r.h <= 0)
  5521. return;
  5522. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  5523. int i;
  5524. for (i = 0; i < 4; i++)
  5525. if (st->border_w[i] && !st->border_t[i]) {
  5526. ngui_fill_rect(ui, r, st->border_c[i]);
  5527. break;
  5528. }
  5529. return;
  5530. }
  5531. if (top && !st->border_t[0])
  5532. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  5533. st->border_c[0], st->border_s[0]);
  5534. if (bottom && !st->border_t[2])
  5535. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  5536. st->border_c[2], st->border_s[2]);
  5537. if (left && !st->border_t[3])
  5538. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  5539. left, 0, st->border_c[3], st->border_s[3]);
  5540. if (right && !st->border_t[1])
  5541. draw_border_side(ui, r.x + r.w - right, r.y + top,
  5542. r.h - top - bottom, right, 0,
  5543. st->border_c[1], st->border_s[1]);
  5544. }
  5545. static void transform_origin(const struct br_style *st, int w, int h,
  5546. int *ox, int *oy)
  5547. {
  5548. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  5549. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  5550. }
  5551. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  5552. unsigned int a)
  5553. {
  5554. unsigned int dr, dg, db, sr, sg, sb;
  5555. if (a >= 255)
  5556. return s;
  5557. dr = (d >> 11) & 31;
  5558. dg = (d >> 5) & 63;
  5559. db = d & 31;
  5560. sr = (s >> 11) & 31;
  5561. sg = (s >> 5) & 63;
  5562. sb = s & 31;
  5563. dr = (dr * (255 - a) + sr * a) / 255;
  5564. dg = (dg * (255 - a) + sg * a) / 255;
  5565. db = (db * (255 - a) + sb * a) / 255;
  5566. return (unsigned short)((dr << 11) | (dg << 5) | db);
  5567. }
  5568. /* Paint a solid box through scale()/rotate() around transform-origin. This
  5569. * transforms the element's own background box; text and descendants keep
  5570. * their layout (documented approximation). */
  5571. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  5572. unsigned short color,
  5573. const struct br_style *st)
  5574. {
  5575. double sx = st->scale_x / 100.0;
  5576. double sy = st->scale_y / 100.0;
  5577. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  5578. double c = cos(th), sn = sin(th);
  5579. int ox, oy, minx, miny, maxx, maxy, x, y;
  5580. double ax, ay;
  5581. double px[4], py[4];
  5582. int cx1, cy1, cx2, cy2, i;
  5583. if (sx == 0)
  5584. sx = 0.01;
  5585. if (sy == 0)
  5586. sy = 0.01;
  5587. transform_origin(st, box.w, box.h, &ox, &oy);
  5588. ax = box.x + ox;
  5589. ay = box.y + oy;
  5590. px[0] = -ox; py[0] = -oy;
  5591. px[1] = box.w - ox; py[1] = -oy;
  5592. px[2] = box.w - ox; py[2] = box.h - oy;
  5593. px[3] = -ox; py[3] = box.h - oy;
  5594. minx = miny = 1000000;
  5595. maxx = maxy = -1000000;
  5596. for (i = 0; i < 4; i++) {
  5597. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  5598. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  5599. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5600. if (dx < minx) minx = dx;
  5601. if (dx > maxx) maxx = dx;
  5602. if (dy < miny) miny = dy;
  5603. if (dy > maxy) maxy = dy;
  5604. }
  5605. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5606. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5607. cx2 = page_rect.x + page_rect.w - 12;
  5608. cy2 = page_rect.y + page_rect.h;
  5609. if (cx2 > gui->w) cx2 = gui->w;
  5610. if (cy2 > gui->h) cy2 = gui->h;
  5611. if (minx < cx1) minx = cx1;
  5612. if (miny < cy1) miny = cy1;
  5613. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5614. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5615. for (y = miny; y <= maxy; y++) {
  5616. for (x = minx; x <= maxx; x++) {
  5617. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  5618. double rx = dx * c + dy * sn;
  5619. double ry = -dx * sn + dy * c;
  5620. double bx = rx / sx + ox;
  5621. double by = ry / sy + oy;
  5622. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  5623. gui->px[y * gui->w + x] = color;
  5624. }
  5625. }
  5626. }
  5627. static void draw_image_transformed(struct ngui *gui,
  5628. const struct img_image *im,
  5629. int x, int y, int w, int h,
  5630. int sx100, int sy100, int rot100,
  5631. int origin_x, int origin_y,
  5632. int origin_x_kind, int origin_y_kind)
  5633. {
  5634. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  5635. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  5636. double c = cos(th), sn = sin(th);
  5637. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  5638. double ax, ay;
  5639. double bx[4], by[4];
  5640. int cx1, cy1, cx2, cy2;
  5641. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  5642. return;
  5643. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  5644. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  5645. ax = x + ox;
  5646. ay = y + oy;
  5647. bx[0] = -ox; by[0] = -oy;
  5648. bx[1] = w - ox; by[1] = -oy;
  5649. bx[2] = w - ox; by[2] = h - oy;
  5650. bx[3] = -ox; by[3] = h - oy;
  5651. minx = miny = 1000000;
  5652. maxx = maxy = -1000000;
  5653. for (i = 0; i < 4; i++) {
  5654. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  5655. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  5656. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5657. if (dx < minx) minx = dx;
  5658. if (dx > maxx) maxx = dx;
  5659. if (dy < miny) miny = dy;
  5660. if (dy > maxy) maxy = dy;
  5661. }
  5662. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5663. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5664. cx2 = page_rect.x + page_rect.w - 12;
  5665. cy2 = page_rect.y + page_rect.h;
  5666. if (cx2 > gui->w) cx2 = gui->w;
  5667. if (cy2 > gui->h) cy2 = gui->h;
  5668. if (minx < cx1) minx = cx1;
  5669. if (miny < cy1) miny = cy1;
  5670. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5671. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5672. for (py = miny; py <= maxy; py++) {
  5673. for (px = minx; px <= maxx; px++) {
  5674. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  5675. double rx = dx * c + dy * sn;
  5676. double ry = -dx * sn + dy * c;
  5677. double fx = rx / sx + ox;
  5678. double fy = ry / sy + oy;
  5679. int ix, iy;
  5680. unsigned int si, a;
  5681. unsigned short src;
  5682. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  5683. continue;
  5684. ix = (int)(fx * (double)im->w / w);
  5685. iy = (int)(fy * (double)im->h / h);
  5686. if (ix < 0 || ix >= (int)im->w ||
  5687. iy < 0 || iy >= (int)im->h)
  5688. continue;
  5689. si = (unsigned int)iy * im->w + (unsigned int)ix;
  5690. src = im->px[si];
  5691. a = im->alpha ? im->alpha[si] : 255;
  5692. gui->px[py * gui->w + px] =
  5693. a >= 255 ? src :
  5694. blend_rgb565(gui->px[py * gui->w + px],
  5695. src, a);
  5696. }
  5697. }
  5698. }
  5699. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5700. unsigned int node, const struct br_style *st);
  5701. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  5702. * first and every pixel outside a corner's arc is restored afterwards. */
  5703. #define BG_ROUND_MAX 64
  5704. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  5705. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  5706. unsigned int node, const struct br_style *st,
  5707. int rtl, int rtr, int rbr, int rbl)
  5708. {
  5709. struct ngui *ui = l->ui;
  5710. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  5711. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  5712. if (ui->nclip > 0)
  5713. clip = ui->clip[ui->nclip - 1];
  5714. for (c = 0; c < 4; c++) {
  5715. if (r[c] > BG_ROUND_MAX)
  5716. r[c] = BG_ROUND_MAX;
  5717. if (r[c] > box.w / 2)
  5718. r[c] = box.w / 2;
  5719. if (r[c] > box.h / 2)
  5720. r[c] = box.h / 2;
  5721. }
  5722. for (c = 0; c < 4; c++) {
  5723. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5724. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5725. for (dy = 0; dy < r[c]; dy++)
  5726. for (dx = 0; dx < r[c]; dx++) {
  5727. int px = ox + dx, py = oy + dy;
  5728. if (px >= clip.x && py >= clip.y &&
  5729. px < clip.x + clip.w && py < clip.y + clip.h)
  5730. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  5731. ui->px[py * ui->w + px];
  5732. }
  5733. }
  5734. draw_bg_image(l, box, node, st);
  5735. for (c = 0; c < 4; c++) {
  5736. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5737. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5738. /* arc centre, in corner-square coordinates */
  5739. int cx = (c == 1 || c == 2) ? 0 : r[c];
  5740. int cy = (c >= 2) ? 0 : r[c];
  5741. for (dy = 0; dy < r[c]; dy++)
  5742. for (dx = 0; dx < r[c]; dx++) {
  5743. int px = ox + dx, py = oy + dy;
  5744. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  5745. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  5746. continue;
  5747. if (px >= clip.x && py >= clip.y &&
  5748. px < clip.x + clip.w && py < clip.y + clip.h)
  5749. ui->px[py * ui->w + px] =
  5750. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  5751. }
  5752. }
  5753. }
  5754. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5755. unsigned int node, const struct br_style *st)
  5756. {
  5757. struct br_image *bi;
  5758. struct img_blit b;
  5759. int tw, th, x, y, rep_x, rep_y, posx, posy;
  5760. unsigned int scale = 65536;
  5761. int legacy, tiles = 0, rows = 0;
  5762. int cx1, cy1, cx2, cy2;
  5763. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  5764. return;
  5765. if (doc.nodes[node].bg_img_index < 0 ||
  5766. doc.nodes[node].bg_img_index >= image_count)
  5767. return;
  5768. bi = &images[doc.nodes[node].bg_img_index];
  5769. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  5770. return;
  5771. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  5772. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  5773. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  5774. if (legacy) {
  5775. scale = ((unsigned int)box.w << 16) / bi->img.w;
  5776. tw = box.w;
  5777. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  5778. x = box.x;
  5779. y = box.y;
  5780. rep_x = rep_y = 0;
  5781. } else {
  5782. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  5783. unsigned int sx = ((unsigned int)box.w << 16) /
  5784. bi->img.w;
  5785. unsigned int sy = ((unsigned int)box.h << 16) /
  5786. bi->img.h;
  5787. scale = st->bg_size_kind == 3 ?
  5788. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  5789. } else if (st->bg_size_kind == 1 ||
  5790. st->bg_size_kind == 2) {
  5791. int w = st->bg_size_w;
  5792. int h = st->bg_size_h;
  5793. if (st->bg_size_kind == 2) {
  5794. if (w)
  5795. w = box.w * w / 100;
  5796. if (h)
  5797. h = box.h * h / 100;
  5798. }
  5799. if (w)
  5800. scale = ((unsigned int)w << 16) / bi->img.w;
  5801. else if (h)
  5802. scale = ((unsigned int)h << 16) / bi->img.h;
  5803. }
  5804. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  5805. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  5806. if (tw < 1)
  5807. tw = 1;
  5808. if (th < 1)
  5809. th = 1;
  5810. posx = st->bg_pos_x_kind == 1 ?
  5811. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  5812. posy = st->bg_pos_y_kind == 1 ?
  5813. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  5814. x = box.x + posx;
  5815. y = box.y + posy;
  5816. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  5817. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  5818. if (rep_x) {
  5819. int m = (x - box.x) % tw;
  5820. if (m > 0)
  5821. m -= tw;
  5822. x = box.x + m;
  5823. }
  5824. if (rep_y) {
  5825. int m = (y - box.y) % th;
  5826. if (m > 0)
  5827. m -= th;
  5828. y = box.y + m;
  5829. }
  5830. }
  5831. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  5832. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  5833. cx2 = box.x + box.w;
  5834. cy2 = box.y + box.h;
  5835. if (cx2 > page_rect.x + page_rect.w - 12)
  5836. cx2 = page_rect.x + page_rect.w - 12;
  5837. if (cy2 > page_rect.y + page_rect.h)
  5838. cy2 = page_rect.y + page_rect.h;
  5839. if (cx1 >= cx2 || cy1 >= cy2)
  5840. return;
  5841. b.dst = l->ui->px;
  5842. b.dst_w = l->ui->w;
  5843. b.dst_h = l->ui->h;
  5844. b.clip_x = cx1;
  5845. b.clip_y = cy1;
  5846. b.clip_w = cx2 - cx1;
  5847. b.clip_h = cy2 - cy1;
  5848. b.bg = ui.theme.bg;
  5849. b.bg2 = ui.theme.bg;
  5850. b.dst_a = 0;
  5851. {
  5852. struct img_image *src = image_display_get(bi, tw, th);
  5853. int row_x;
  5854. if (!src)
  5855. src = &bi->img;
  5856. b.scale = ((unsigned int)tw << 16) / src->w;
  5857. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  5858. row_x = x;
  5859. for (;;) {
  5860. for (;;) {
  5861. b.x = x;
  5862. b.y = y;
  5863. img_draw(src, &b);
  5864. if (!rep_x || ++tiles > 512)
  5865. break;
  5866. x += tw;
  5867. if (x >= box.x + box.w)
  5868. break;
  5869. }
  5870. if (!rep_y || ++rows > 64)
  5871. break;
  5872. y += th;
  5873. if (y >= box.y + box.h)
  5874. break;
  5875. x = row_x;
  5876. }
  5877. }
  5878. }
  5879. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  5880. int *out_w, int *out_h);
  5881. static void svg_paint_box(struct ngui *ui, unsigned int node,
  5882. const struct br_style *st, int x, int y, int w,
  5883. int h);
  5884. /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
  5885. * RUN_SVG an inline <svg> icon (its node in off). */
  5886. #define RUN_SVG (-3)
  5887. static int run_width(const struct lay_run *r)
  5888. {
  5889. if (r->img >= 0)
  5890. return r->iw;
  5891. if (r->img == -2 || r->img == RUN_SVG)
  5892. return r->iw;
  5893. return (int)r->w;
  5894. }
  5895. static void start_line(struct lay *l, const struct br_style *st)
  5896. {
  5897. (void)st;
  5898. if (l->nruns == 0) {
  5899. l->line_y = l->y;
  5900. l->line_h = 0;
  5901. }
  5902. l->line_left = l->left;
  5903. l->line_right = l->right;
  5904. if (l->float_active && l->line_y < l->float_bottom) {
  5905. if (l->float_left > l->line_left)
  5906. l->line_left = l->float_left;
  5907. if (l->float_right < l->line_right)
  5908. l->line_right = l->float_right;
  5909. }
  5910. if (l->line_right < l->line_left + 8)
  5911. l->line_right = l->line_left + 8;
  5912. l->line_x = l->line_left;
  5913. l->run_x = l->line_left;
  5914. }
  5915. static void flush_line(struct lay *l)
  5916. {
  5917. int total, x, i, vis;
  5918. if (!l->nruns && l->line_x == l->line_left) {
  5919. l->line_h = 0;
  5920. return;
  5921. }
  5922. total = l->line_x - l->line_left;
  5923. x = l->line_left;
  5924. vis = 1;
  5925. if (l->draw) {
  5926. int lh = l->line_h ? l->line_h : 16;
  5927. vis = l->line_y + lh >= page_rect.y &&
  5928. l->line_y <= page_rect.y + page_rect.h;
  5929. }
  5930. if (l->align == BR_ALIGN_CENTER)
  5931. x += (l->line_right - l->line_left - total) / 2;
  5932. else if (l->align == BR_ALIGN_RIGHT)
  5933. x = l->line_right - total;
  5934. if (x < l->line_left)
  5935. x = l->line_left;
  5936. for (i = 0; i < l->nruns; i++) {
  5937. struct lay_run *r = &l->runs[i];
  5938. int w = run_width(r);
  5939. int ry = l->line_y + r->dy;
  5940. x += r->gap;
  5941. if (l->draw && vis) {
  5942. if (r->form) {
  5943. unsigned int node = r->form - 1;
  5944. struct form_state *fs = form_get(node, 1);
  5945. int hh = r->ih ? r->ih : 20;
  5946. int focused = form_focus == node;
  5947. int disabled = r->form_disabled;
  5948. unsigned short bg = l->ui->theme.panel_alt;
  5949. unsigned short fg = disabled ? 0x8410 : r->color;
  5950. struct ngui_rect box = {x, ry, w, hh};
  5951. if (r->form_kind == FORM_CHECKBOX ||
  5952. r->form_kind == FORM_RADIO) {
  5953. ngui_fill_rect(l->ui, box, bg);
  5954. ngui_frame(l->ui, box,
  5955. focused ? l->ui->theme.accent :
  5956. l->ui->theme.border);
  5957. if (fs && fs->checked) {
  5958. struct ngui_rect dot = {
  5959. x + 4, ry + 4,
  5960. w > 8 ? w - 8 : 1,
  5961. hh > 8 ? hh - 8 : 1
  5962. };
  5963. if (r->form_kind == FORM_RADIO)
  5964. ngui_fill_round_rect(
  5965. l->ui, dot, 4,
  5966. 4, 4, 4,
  5967. l->ui->theme.accent);
  5968. else
  5969. ngui_fill_rect(l->ui,
  5970. dot,
  5971. l->ui->theme.accent);
  5972. }
  5973. } else {
  5974. int editable =
  5975. r->form_kind == FORM_TEXT ||
  5976. r->form_kind == FORM_PASSWORD ||
  5977. r->form_kind == FORM_TEXTAREA;
  5978. int scroll = 0;
  5979. /* Editable fields draw the live value
  5980. * (r->lit is a short copy). */
  5981. static char shown[FORM_VALUE_MAX + 1];
  5982. const char *txt = r->lit;
  5983. unsigned int tl = s_len(r->lit);
  5984. if (editable && fs && fs->len) {
  5985. unsigned int k;
  5986. if (r->form_kind == FORM_PASSWORD) {
  5987. for (k = 0; k < fs->len; k++)
  5988. shown[k] = '*';
  5989. shown[k] = '\0';
  5990. txt = shown;
  5991. } else {
  5992. txt = fs->value;
  5993. }
  5994. tl = fs->len;
  5995. }
  5996. struct br_style fst;
  5997. int author, tx = x + 6, pr = 6;
  5998. style_for_node(node, &fst);
  5999. author = form_author_styled(&fst);
  6000. if (author) {
  6001. /* The page styled the control:
  6002. * its background, border, radius
  6003. * and text colour. */
  6004. form_paint_author(l->ui, box, &fst,
  6005. focused);
  6006. tx = x + fst.border_w[3] +
  6007. mp_px(&fst, 7, w);
  6008. pr = fst.border_w[1] +
  6009. mp_px(&fst, 5, w);
  6010. if (tx < x + 2 && !editable)
  6011. tx = x + 2;
  6012. if (!disabled)
  6013. fg = editable && fs &&
  6014. !fs->len ?
  6015. 0x8410 : fst.color;
  6016. if (!editable) {
  6017. int tw0 = (int)
  6018. run_text_width(l->ui,
  6019. r, txt, tl);
  6020. tx = x + (w - tw0) / 2;
  6021. }
  6022. } else {
  6023. /* The box is drawn in theme colours, so
  6024. * the text is too: the page's CSS colour
  6025. * (dark on a light page) would vanish on
  6026. * the dark field. */
  6027. if (!disabled)
  6028. fg = editable && fs && !fs->len ?
  6029. l->ui->theme.text_dim :
  6030. l->ui->theme.text;
  6031. ngui_fill_rect(l->ui, box, bg);
  6032. ngui_frame(l->ui, box,
  6033. focused ? l->ui->theme.accent :
  6034. l->ui->theme.border);
  6035. }
  6036. /* A value wider than the field shows its
  6037. * tail (where typing happens). */
  6038. if (editable && fs && fs->len &&
  6039. w > (tx - x) + pr) {
  6040. int tw = (int)run_text_width(l->ui,
  6041. r, txt, tl);
  6042. int room = w - (tx - x) - pr;
  6043. if (tw > room)
  6044. scroll = tw - room;
  6045. }
  6046. ngui_push_clip(l->ui, (struct ngui_rect){
  6047. x + 1, ry + 1,
  6048. w > 2 ? w - 2 : 1,
  6049. hh > 2 ? hh - 2 : 1 });
  6050. ngui_text_px_face(l->ui, run_face(r),
  6051. tx - scroll,
  6052. ry + (hh - r->font_px) / 2 - 1,
  6053. txt, tl, fg, r->font_px,
  6054. r->bold, r->italic, r->mono);
  6055. if (focused && fs && editable) {
  6056. int cw = 0;
  6057. if (fs->len && fs->caret)
  6058. cw = (int)run_text_width(
  6059. l->ui, r, txt,
  6060. fs->caret < fs->len ?
  6061. fs->caret : fs->len);
  6062. ngui_fill_rect(l->ui,
  6063. (struct ngui_rect){
  6064. tx + cw - scroll,
  6065. ry + 4, 1,
  6066. hh > 8 ? hh - 8 : 1
  6067. },
  6068. l->ui->theme.accent);
  6069. }
  6070. ngui_pop_clip(l->ui);
  6071. if (r->form_kind == FORM_SELECT) {
  6072. ngui_text_px(l->ui, x + w - 12,
  6073. ry + 2, "v", 1, fg,
  6074. r->font_px, 0, 0, 0);
  6075. }
  6076. }
  6077. } else if (r->img == RUN_SVG) {
  6078. struct br_style sst;
  6079. style_for_node(r->off, &sst);
  6080. svg_paint_box(l->ui, r->off, &sst, x, ry, w,
  6081. r->ih);
  6082. } else if (r->img == -2) {
  6083. int hh = r->ih ? r->ih : 20;
  6084. ngui_fill_rect(l->ui,
  6085. (struct ngui_rect){x, ry, w, hh},
  6086. l->ui->theme.panel_alt);
  6087. ngui_frame(l->ui,
  6088. (struct ngui_rect){x, ry, w, hh},
  6089. l->ui->theme.border);
  6090. ngui_text_px_face(l->ui, run_face(r),
  6091. x + 6, ry + 2, r->lit,
  6092. s_len(r->lit), r->color,
  6093. r->font_px, r->bold, r->italic,
  6094. r->mono);
  6095. } else if (r->img >= 0) {
  6096. struct br_image *bi = &images[r->img];
  6097. if (bi->state == 1 && r->transform_scale) {
  6098. draw_image_transformed(l->ui, &bi->img,
  6099. x, ry, r->iw, r->ih,
  6100. r->scale_x, r->scale_y,
  6101. r->rotate_x100, r->origin_x,
  6102. r->origin_y, r->origin_x_kind,
  6103. r->origin_y_kind);
  6104. } else if (bi->state == 1) {
  6105. struct img_image *src =
  6106. image_display_get(bi, r->iw, r->ih);
  6107. struct img_blit b;
  6108. if (!src)
  6109. src = &bi->img;
  6110. b.dst = l->ui->px;
  6111. b.dst_w = l->ui->w;
  6112. b.dst_h = l->ui->h;
  6113. b.clip_x = page_rect.x;
  6114. b.clip_y = page_rect.y;
  6115. b.clip_w = page_rect.w - 12;
  6116. b.clip_h = page_rect.h;
  6117. b.x = x;
  6118. b.y = ry;
  6119. b.scale = ((unsigned int)r->iw << 16) /
  6120. src->w;
  6121. b.bg = ui.theme.bg;
  6122. b.bg2 = ui.theme.bg;
  6123. b.dst_a = 0;
  6124. b.flags = src->alpha ?
  6125. IMG_BLIT_OVER_DST : 0;
  6126. img_draw(src, &b);
  6127. }
  6128. } else {
  6129. const char *s = r->has_lit ? r->lit :
  6130. doc.text + r->off;
  6131. unsigned int n = r->has_lit ? s_len(r->lit) :
  6132. r->len;
  6133. ngui_text_px_face(l->ui, run_face(r), x, ry,
  6134. s, n, r->color, r->font_px,
  6135. r->bold, r->italic, r->mono);
  6136. if (r->underline)
  6137. ngui_fill_rect(l->ui,
  6138. (struct ngui_rect){x,
  6139. ry + run_ascent(l->ui, r) + 2,
  6140. w, 1}, r->color);
  6141. if (r->strike)
  6142. ngui_fill_rect(l->ui,
  6143. (struct ngui_rect){x,
  6144. ry + run_ascent(l->ui, r) -
  6145. (r->font_px > 3 ?
  6146. r->font_px / 3 : 1),
  6147. w, 1}, r->color);
  6148. if (r->overline)
  6149. ngui_fill_rect(l->ui,
  6150. (struct ngui_rect){x, ry,
  6151. w, 1}, r->color);
  6152. }
  6153. if (r->form || r->href) {
  6154. if (nhits < HIT_MAX) {
  6155. struct hit *h = &hits[nhits];
  6156. unsigned int target = r->form ?
  6157. r->form - 1 : r->href;
  6158. int hh = (r->form || r->img >= 0 ||
  6159. r->img == RUN_SVG) ?
  6160. r->ih :
  6161. run_line_height(l->ui, r);
  6162. int merge = nhits > 0 &&
  6163. hits[nhits - 1].node == target &&
  6164. hits[nhits - 1].y == ry &&
  6165. hits[nhits - 1].h == hh &&
  6166. x <= hits[nhits - 1].x +
  6167. hits[nhits - 1].w + 2;
  6168. if (merge) {
  6169. struct hit *p = &hits[nhits - 1];
  6170. int end = x + w;
  6171. if (end > p->x + p->w)
  6172. p->w = end - p->x;
  6173. } else {
  6174. h->x = x;
  6175. h->y = ry;
  6176. h->w = w;
  6177. h->h = hh;
  6178. h->node = (unsigned short)target;
  6179. nhits++;
  6180. }
  6181. }
  6182. }
  6183. }
  6184. x += w;
  6185. }
  6186. l->y += l->line_h + 2;
  6187. if (l->float_active && l->y >= l->float_bottom)
  6188. l->float_active = 0;
  6189. l->nruns = 0;
  6190. l->line_x = l->left;
  6191. l->run_x = l->left;
  6192. l->line_left = l->left;
  6193. l->line_right = l->right;
  6194. l->line_h = 0;
  6195. l->space_pending = 0;
  6196. }
  6197. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  6198. const struct br_style *st, unsigned short href,
  6199. const char *lit)
  6200. {
  6201. unsigned int n = lit ? s_len(lit) : len;
  6202. const char *tp = lit ? lit : doc.text + off;
  6203. int w = (int)face_text_width(l->ui, st, tp, n);
  6204. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6205. flush_line(l);
  6206. if (l->nruns == 0) {
  6207. l->line_y = l->y;
  6208. l->line_h = 0;
  6209. start_line(l, st);
  6210. }
  6211. {
  6212. struct lay_run *r = &l->runs[l->nruns++];
  6213. int gap = l->line_x - l->run_x;
  6214. if (gap < 0)
  6215. gap = 0;
  6216. r->gap = (unsigned short)gap;
  6217. r->off = off;
  6218. r->len = len;
  6219. r->color = st->color;
  6220. r->href = href;
  6221. r->dy = 0;
  6222. r->has_lit = 0;
  6223. r->form = 0;
  6224. r->form_kind = 0;
  6225. r->form_disabled = 0;
  6226. r->lit[0] = '\0';
  6227. if (lit && lit[0]) {
  6228. unsigned int i;
  6229. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  6230. r->lit[i] = lit[i];
  6231. r->lit[i] = '\0';
  6232. r->has_lit = 1;
  6233. }
  6234. r->img = -1;
  6235. r->iw = r->ih = 0;
  6236. r->font_px = st->font_px;
  6237. r->bold = st->bold;
  6238. r->italic = st->italic;
  6239. r->mono = st->mono;
  6240. r->font_face = st->font_face;
  6241. /* A control with its own background is a button, not body copy;
  6242. * an inherited link underline would strike through the fill. */
  6243. r->underline = st->underline && !st->has_bg;
  6244. r->strike = st->strike && !st->has_bg;
  6245. r->overline = st->overline && !st->has_bg;
  6246. r->w = (unsigned short)w;
  6247. if (r->has_lit)
  6248. r->w = (unsigned short)run_text_width(
  6249. l->ui, r, r->lit, s_len(r->lit));
  6250. w = r->w;
  6251. }
  6252. l->line_x += w;
  6253. l->run_x = l->line_x;
  6254. {
  6255. int lh = face_line_height(l->ui, st);
  6256. if (st->line_h_px)
  6257. lh = st->line_h_px;
  6258. else if (st->line_h_pct)
  6259. lh = st->font_px * st->line_h_pct / 100;
  6260. if (lh < face_line_height(l->ui, st))
  6261. lh = face_line_height(l->ui, st);
  6262. if (l->line_h < lh)
  6263. l->line_h = lh;
  6264. }
  6265. }
  6266. static void add_image_run(struct lay *l, unsigned int node,
  6267. const struct br_style *st, unsigned short href)
  6268. {
  6269. struct br_image *bi = 0;
  6270. int idx = doc.nodes[node].img_index;
  6271. int dw, dh, maxw;
  6272. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  6273. bi = &images[idx];
  6274. if (l->nruns == 0)
  6275. start_line(l, st);
  6276. if (l->space_pending &&
  6277. (l->nruns > 0 || l->line_x > l->line_left)) {
  6278. int sp = (int)face_text_width(l->ui, st, " ", 1);
  6279. if (l->line_x + sp <= l->line_right)
  6280. l->line_x += sp;
  6281. }
  6282. l->space_pending = 0;
  6283. if (!bi) {
  6284. const char *alt = br_alt(&doc, node);
  6285. struct br_style gs = *st;
  6286. char tmp[96];
  6287. unsigned int n = 0;
  6288. int w;
  6289. gs.color = BR_GRAY;
  6290. gs.underline = 0;
  6291. s_append(tmp, &n, "[", sizeof(tmp));
  6292. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  6293. s_append(tmp, &n, "]", sizeof(tmp));
  6294. w = (int)face_text_width(l->ui, &gs, tmp, n);
  6295. if (l->line_x + w > l->line_right &&
  6296. (l->nruns > 0 || l->line_x > l->line_left))
  6297. flush_line(l);
  6298. add_run(l, 0, 0, &gs, href, tmp);
  6299. if (!l->draw) {
  6300. int t = l->line_y < 0 ? 0 : l->line_y;
  6301. int hh = face_line_height(l->ui, &gs);
  6302. if (t > 65535)
  6303. t = 65535;
  6304. if (hh > 65535)
  6305. hh = 65535;
  6306. img_top[node] = (unsigned short)t;
  6307. img_h[node] = (unsigned short)hh;
  6308. }
  6309. return;
  6310. }
  6311. maxw = l->line_right - l->line_left;
  6312. if (maxw < 8)
  6313. maxw = 8;
  6314. {
  6315. int iw = bi->native_w, ih = bi->native_h;
  6316. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  6317. if (iw <= 0 || ih <= 0) {
  6318. iw = (int)bi->img.w;
  6319. ih = (int)bi->img.h;
  6320. }
  6321. dw = iw;
  6322. dh = ih;
  6323. if (doc.nodes[node].width_attr) {
  6324. int want = doc.nodes[node].width_attr;
  6325. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  6326. have_w = 1;
  6327. }
  6328. if (doc.nodes[node].height_attr) {
  6329. int want = doc.nodes[node].height_attr;
  6330. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  6331. have_h = 1;
  6332. }
  6333. if (have_w && !have_h)
  6334. dh = ih ? ih * dw / iw : 0;
  6335. if (have_h && !have_w)
  6336. dw = iw ? iw * dh / ih : 0;
  6337. if (st->width_kind) {
  6338. css_w = 1;
  6339. if (st->width_kind == 3)
  6340. dw = maxw * st->width_calc_pct / 100 +
  6341. st->width_calc_px;
  6342. else
  6343. dw = st->width_kind == 2 ?
  6344. maxw * (int)st->width / 100 :
  6345. (int)st->width;
  6346. }
  6347. if (st->height_kind) {
  6348. css_h = 1;
  6349. if (st->height_kind == 3)
  6350. dh = maxw * st->height_calc_pct / 100 +
  6351. st->height_calc_px;
  6352. else
  6353. dh = st->height_kind == 2 ?
  6354. maxw * (int)st->height / 100 :
  6355. (int)st->height;
  6356. }
  6357. if (css_w && !css_h)
  6358. dh = ih ? ih * dw / iw : 0;
  6359. if (css_h && !css_w)
  6360. dw = iw ? iw * dh / ih : 0;
  6361. if (st->max_width_kind) {
  6362. int mw = st->max_width_kind == 3 ?
  6363. maxw * st->max_width_calc_pct / 100 +
  6364. st->max_width_calc_px :
  6365. st->max_width_kind == 2 ?
  6366. maxw * (int)st->max_width / 100 :
  6367. (int)st->max_width;
  6368. if (mw > 0 && dw > mw) {
  6369. dh = iw ? ih * mw / iw : 0;
  6370. dw = mw;
  6371. }
  6372. }
  6373. }
  6374. if (dw < 8)
  6375. dw = 8;
  6376. if (dh < 8)
  6377. dh = 8;
  6378. if (dw > maxw) {
  6379. dh = dw ? dh * maxw / dw : dh;
  6380. dw = maxw;
  6381. }
  6382. if (!l->draw) {
  6383. int t = l->line_y < 0 ? 0 : l->line_y;
  6384. if (t > 65535)
  6385. t = 65535;
  6386. if (dh > 65535)
  6387. dh = 65535;
  6388. img_top[node] = (unsigned short)t;
  6389. img_h[node] = (unsigned short)dh;
  6390. }
  6391. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  6392. l->line_x > l->line_left))
  6393. flush_line(l);
  6394. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6395. flush_line(l);
  6396. if (l->nruns == 0) {
  6397. l->line_y = l->y;
  6398. l->line_h = 0;
  6399. start_line(l, st);
  6400. }
  6401. {
  6402. struct lay_run *r = &l->runs[l->nruns++];
  6403. int gap = l->line_x - l->run_x;
  6404. if (gap < 0)
  6405. gap = 0;
  6406. r->gap = (unsigned short)gap;
  6407. r->off = 0;
  6408. r->len = 0;
  6409. r->color = 0;
  6410. r->href = href;
  6411. r->form = 0;
  6412. r->form_kind = 0;
  6413. r->form_disabled = 0;
  6414. /* Inline replaced elements honour their vertical margins; this
  6415. * is how Bootstrap's negative logo margins centre the wordmark. */
  6416. {
  6417. int idy = mp_px(st, 0, l->right - l->left);
  6418. if (idy < -2048)
  6419. idy = -2048;
  6420. if (idy > 2048)
  6421. idy = 2048;
  6422. r->dy = (signed short)idy;
  6423. }
  6424. r->has_lit = 0;
  6425. r->lit[0] = '\0';
  6426. r->img = (short)idx;
  6427. r->iw = (unsigned short)dw;
  6428. r->ih = (unsigned short)dh;
  6429. r->w = (unsigned short)dw;
  6430. r->font_px = st->font_px;
  6431. r->bold = st->bold;
  6432. r->italic = st->italic;
  6433. r->mono = st->mono;
  6434. r->font_face = st->font_face;
  6435. r->transform_scale = st->transform_scale;
  6436. r->scale_x = st->scale_x;
  6437. r->scale_y = st->scale_y;
  6438. r->rotate_x100 = st->rotate_x100;
  6439. r->origin_x = st->origin_x;
  6440. r->origin_y = st->origin_y;
  6441. r->origin_x_kind = st->origin_x_kind;
  6442. r->origin_y_kind = st->origin_y_kind;
  6443. r->underline = 0;
  6444. }
  6445. if (node < BR_MAX_NODES) {
  6446. layout_boxes[node].x = l->line_x;
  6447. layout_boxes[node].y = l->line_y +
  6448. mp_px(st, 0, l->right - l->left);
  6449. layout_boxes[node].w = dw;
  6450. layout_boxes[node].h = dh;
  6451. layout_boxes[node].valid = 1;
  6452. }
  6453. l->line_x += dw;
  6454. l->run_x = l->line_x;
  6455. if (l->line_h < dh)
  6456. l->line_h = dh;
  6457. }
  6458. /* An inline (or inline-block) <svg> is a replaced element in the text
  6459. * line, like an <img>: comment bubbles and arrows sit next to their label
  6460. * instead of starting a block of their own. */
  6461. static void add_svg_run(struct lay *l, unsigned int node,
  6462. const struct br_style *st, unsigned short href)
  6463. {
  6464. struct lay_run *r;
  6465. int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
  6466. if (lw < 8)
  6467. lw = 8;
  6468. cw = st->width_kind ? style_width_px(st, lw) : lw;
  6469. if (cw < 1)
  6470. cw = 1;
  6471. svg_size(node, st, cw, &dw, &dh);
  6472. if (dw > lw)
  6473. dw = lw;
  6474. ml = mp_px(st, 3, lw);
  6475. mr = mp_px(st, 1, lw);
  6476. if (ml < 0)
  6477. ml = 0;
  6478. if (mr < 0)
  6479. mr = 0;
  6480. if (l->line_x + ml + dw > l->line_right &&
  6481. (l->nruns > 0 || l->line_x > l->line_left))
  6482. flush_line(l);
  6483. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6484. flush_line(l);
  6485. if (l->nruns == 0) {
  6486. l->line_y = l->y;
  6487. l->line_h = 0;
  6488. start_line(l, st);
  6489. }
  6490. l->line_x += ml;
  6491. r = &l->runs[l->nruns++];
  6492. memset(r, 0, sizeof(*r));
  6493. r->gap = (unsigned short)(l->line_x > l->run_x ?
  6494. l->line_x - l->run_x : 0);
  6495. r->off = node;
  6496. r->color = st->color;
  6497. r->href = href;
  6498. r->img = RUN_SVG;
  6499. r->iw = (unsigned short)dw;
  6500. r->ih = (unsigned short)dh;
  6501. r->w = (unsigned short)dw;
  6502. r->font_px = st->font_px;
  6503. if (node < BR_MAX_NODES) {
  6504. layout_boxes[node].x = l->line_x;
  6505. layout_boxes[node].y = l->line_y;
  6506. layout_boxes[node].w = dw;
  6507. layout_boxes[node].h = dh;
  6508. layout_boxes[node].valid = 1;
  6509. }
  6510. l->line_x += dw + mr;
  6511. l->run_x = l->line_x;
  6512. if (l->line_h < dh)
  6513. l->line_h = dh;
  6514. }
  6515. static int text_width(struct lay *l, const char *s, unsigned int n,
  6516. const struct br_style *st)
  6517. {
  6518. return (int)face_text_width(l->ui, st, s, n);
  6519. }
  6520. /* Longest prefix that fits in maxw, at least one byte. */
  6521. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  6522. const struct br_style *st, int maxw)
  6523. {
  6524. unsigned int take = 0;
  6525. while (take < n) {
  6526. if (text_width(l, s, take + 1, st) > maxw)
  6527. break;
  6528. take++;
  6529. }
  6530. return take ? take : 1;
  6531. }
  6532. static void emit_word(struct lay *l, const char *s, unsigned int start,
  6533. unsigned int n, unsigned int base,
  6534. const struct br_style *st, unsigned short href)
  6535. {
  6536. int avail;
  6537. int w = text_width(l, s + start, n, st);
  6538. unsigned int off = start;
  6539. if (l->nruns == 0)
  6540. start_line(l, st);
  6541. avail = l->line_right - l->line_left;
  6542. if (st->nowrap) {
  6543. if (n)
  6544. add_run(l, base + start,
  6545. (unsigned short)n, st, href, 0);
  6546. return;
  6547. }
  6548. /* A padded/bordered one-word button can be a few pixels wider than
  6549. * the content box; keep it on one line instead of splitting it. */
  6550. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  6551. add_run(l, base + start,
  6552. (unsigned short)n, st, href, 0);
  6553. return;
  6554. }
  6555. if (l->line_x + w > l->line_right &&
  6556. (l->nruns > 0 || l->line_x > l->line_left)) {
  6557. flush_line(l);
  6558. start_line(l, st);
  6559. avail = l->line_right - l->line_left;
  6560. }
  6561. if (w <= avail) {
  6562. if (n)
  6563. add_run(l, base + start,
  6564. (unsigned short)n, st, href, 0);
  6565. return;
  6566. }
  6567. while (n > 0) {
  6568. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  6569. add_run(l, base + off,
  6570. (unsigned short)take, st, href, 0);
  6571. off += take;
  6572. n -= take;
  6573. if (n) {
  6574. flush_line(l);
  6575. start_line(l, st);
  6576. avail = l->line_right - l->line_left;
  6577. }
  6578. }
  6579. }
  6580. static void emit_text(struct lay *l, const char *s, unsigned int len,
  6581. const struct br_style *st, unsigned short href, int pre)
  6582. {
  6583. unsigned int i = 0;
  6584. unsigned int base;
  6585. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  6586. if (!s || !len)
  6587. return;
  6588. if (space_w <= 0)
  6589. space_w = 8;
  6590. if (l->nruns == 0)
  6591. start_line(l, st);
  6592. base = (unsigned int)(s - doc.text);
  6593. if (st->uppercase) {
  6594. char *p = (char *)s;
  6595. unsigned int j;
  6596. for (j = 0; j < len; j++)
  6597. if (p[j] >= 'a' && p[j] <= 'z')
  6598. p[j] = (char)(p[j] - 'a' + 'A');
  6599. }
  6600. if (pre) {
  6601. while (i < len) {
  6602. unsigned int start;
  6603. if (s[i] == '\n') {
  6604. flush_line(l);
  6605. start_line(l, st);
  6606. i++;
  6607. continue;
  6608. }
  6609. if (s[i] == ' ') {
  6610. if (l->line_x + space_w > l->line_right &&
  6611. (l->nruns > 0 || l->line_x > l->line_left)) {
  6612. flush_line(l);
  6613. start_line(l, st);
  6614. } else {
  6615. l->line_x += space_w;
  6616. }
  6617. i++;
  6618. continue;
  6619. }
  6620. start = i;
  6621. while (i < len && s[i] != ' ' && s[i] != '\n')
  6622. i++;
  6623. emit_word(l, s, start, i - start, base, st, href);
  6624. }
  6625. return;
  6626. }
  6627. while (i < len) {
  6628. unsigned int start, n;
  6629. if (s[i] == ' ') {
  6630. l->space_pending = 1;
  6631. i++;
  6632. continue;
  6633. }
  6634. start = i;
  6635. while (i < len && s[i] != ' ')
  6636. i++;
  6637. n = i - start;
  6638. if (l->space_pending &&
  6639. (l->nruns > 0 || l->line_x > l->line_left)) {
  6640. if (st->nowrap ||
  6641. l->line_x + space_w <= l->line_right)
  6642. l->line_x += space_w;
  6643. }
  6644. l->space_pending = 0;
  6645. emit_word(l, s, start, n, base, st, href);
  6646. }
  6647. }
  6648. static int list_index(unsigned int parent, unsigned int node)
  6649. {
  6650. unsigned int n = 0, i;
  6651. for (i = doc.nodes[parent].first; i && i != node;
  6652. i = doc.nodes[i].next)
  6653. if (doc.nodes[i].tag == BR_TAG_LI)
  6654. n++;
  6655. return (int)n + 1;
  6656. }
  6657. static void list_roman(char *m, unsigned int *n, int v, int upper,
  6658. unsigned int cap)
  6659. {
  6660. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  6661. 50, 40, 10, 9, 5, 4, 1 };
  6662. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  6663. "l", "xl", "x", "ix", "v", "iv", "i" };
  6664. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  6665. "L", "XL", "X", "IX", "V", "IV", "I" };
  6666. unsigned int i;
  6667. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  6668. while (v >= val[i] && *n + 1 < cap) {
  6669. const char *s = upper ? up[i] : lo[i];
  6670. while (*s && *n + 1 < cap)
  6671. m[(*n)++] = *s++;
  6672. v -= val[i];
  6673. }
  6674. }
  6675. }
  6676. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  6677. {
  6678. unsigned int n = 0;
  6679. if (style == BR_LIST_DISC) {
  6680. m[n++] = '-';
  6681. } else if (style == BR_LIST_CIRCLE) {
  6682. m[n++] = 'o';
  6683. } else if (style == BR_LIST_SQUARE) {
  6684. m[n++] = '+';
  6685. } else if (style == BR_LIST_LOWER_ALPHA ||
  6686. style == BR_LIST_UPPER_ALPHA) {
  6687. if (idx >= 1 && idx <= 26)
  6688. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  6689. 'A' : 'a') + idx - 1);
  6690. else
  6691. m[n++] = '?';
  6692. m[n++] = '.';
  6693. } else if (style == BR_LIST_LOWER_ROMAN ||
  6694. style == BR_LIST_UPPER_ROMAN) {
  6695. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  6696. if (n + 1 < cap)
  6697. m[n++] = '.';
  6698. } else {
  6699. s_append_dec(m, &n, (unsigned int)idx, cap);
  6700. if (n + 1 < cap)
  6701. m[n++] = '.';
  6702. }
  6703. m[n] = '\0';
  6704. }
  6705. /* A control the page styled itself (background, border or radius in author
  6706. * CSS -- `background:transparent;border:none` counts) is painted with that
  6707. * style, sized from its padding/height and keeps the page's text colour.
  6708. * Unstyled controls keep the ngui theme look. */
  6709. static int form_author_styled(const struct br_style *st)
  6710. {
  6711. int i;
  6712. if (st->bg_set)
  6713. return 1;
  6714. for (i = 0; i < 4; i++)
  6715. if (st->border_w[i] || st->radius[i])
  6716. return 1;
  6717. return 0;
  6718. }
  6719. /* Set by the layout when the control is stretched to its line: a flex item
  6720. * (its box width was assigned by the flex row) or a child of a flex column,
  6721. * whose default align-items: stretch makes inputs full width. */
  6722. static int form_fill_line;
  6723. static void add_form_run(struct lay *l, unsigned int node,
  6724. const struct br_style *st, unsigned short href)
  6725. {
  6726. struct form_state *fs = form_get(node, 1);
  6727. char shown[FORM_VALUE_MAX + 1];
  6728. char opt[64];
  6729. const char *text = "";
  6730. struct lay_run *r;
  6731. int kind = form_kind_of(node);
  6732. int disabled = form_disabled(node);
  6733. int author = form_author_styled(st);
  6734. int tw, w = 120, h = 20, i, line_w, pad_x, pad_y;
  6735. int ml = 0, mr = 0, mt = 0, mb = 0;
  6736. if (!fs)
  6737. return;
  6738. if (l->nruns == 0)
  6739. start_line(l, st);
  6740. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  6741. text = "";
  6742. w = 16;
  6743. h = 16;
  6744. } else if (kind == FORM_SELECT) {
  6745. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  6746. s_copy(opt, "Select", sizeof(opt));
  6747. text = opt;
  6748. w = 120;
  6749. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  6750. kind == FORM_RESET) {
  6751. if (fs->len)
  6752. text = fs->value;
  6753. else
  6754. text = kind == FORM_SUBMIT ? "Submit" :
  6755. kind == FORM_RESET ? "Reset" : "Button";
  6756. } else if (kind == FORM_PASSWORD) {
  6757. for (i = 0; i < fs->len; i++)
  6758. shown[i] = '*';
  6759. shown[fs->len] = '\0';
  6760. text = fs->len ? shown : br_placeholder(&doc, node);
  6761. } else {
  6762. if (fs->len)
  6763. text = fs->value;
  6764. else
  6765. text = br_placeholder(&doc, node);
  6766. if (kind == FORM_TEXTAREA) {
  6767. w = 180;
  6768. h = 40;
  6769. }
  6770. }
  6771. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  6772. line_w = l->line_right - l->line_left;
  6773. pad_x = mp_px(st, 7, line_w) + mp_px(st, 5, line_w) +
  6774. st->border_w[1] + st->border_w[3];
  6775. pad_y = mp_px(st, 4, line_w) + mp_px(st, 6, line_w) +
  6776. st->border_w[0] + st->border_w[2];
  6777. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  6778. /* Buttons are border-box in every UA stylesheet: an
  6779. * explicit width/height is the whole box. */
  6780. if (author || pad_x) {
  6781. w = tw + pad_x;
  6782. } else {
  6783. w = tw + 18;
  6784. if (w < 64)
  6785. w = 64;
  6786. }
  6787. if (st->width_kind)
  6788. w = style_width_px(st, line_w);
  6789. if (st->min_width_kind == 1 && w < (int)st->min_width)
  6790. w = st->min_width;
  6791. if (st->height_kind == 1)
  6792. h = st->height;
  6793. else if (author)
  6794. h = st->font_px + 6 + pad_y;
  6795. else
  6796. h = 22;
  6797. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  6798. kind == FORM_TEXTAREA) {
  6799. int fill = form_fill_line || st->display == BR_DISPLAY_BLOCK ||
  6800. st->display == BR_DISPLAY_FLEX;
  6801. int boxed = st->box_sizing ? 0 : pad_x;
  6802. if (st->width_kind)
  6803. w = style_width_px(st, line_w) + boxed;
  6804. else if (fill)
  6805. w = line_w - (l->line_x - l->line_left);
  6806. else
  6807. w = kind == FORM_TEXTAREA ? 180 : 120;
  6808. if (kind == FORM_TEXTAREA) {
  6809. const char *ra = br_find_attr(&doc, node, "rows");
  6810. int rows = 0;
  6811. int lh = st->line_h_px ? st->line_h_px :
  6812. st->font_px * 5 / 4;
  6813. while (ra && *ra >= '0' && *ra <= '9')
  6814. rows = rows * 10 + (*ra++ - '0');
  6815. if (rows < 1 || rows > 40)
  6816. rows = 2;
  6817. h = author ? rows * lh + pad_y : 40;
  6818. } else if (author) {
  6819. h = st->font_px + 8 + pad_y;
  6820. } else if (st->font_px + 8 > h) {
  6821. /* Taller fields for large text (min-height/padding
  6822. * on login pages): keep the box around the glyphs. */
  6823. h = st->font_px + 8;
  6824. }
  6825. if (st->height_kind == 1)
  6826. h = st->height + (st->box_sizing ? 0 : pad_y);
  6827. if (st->min_height_kind == 1 && h < (int)st->min_height)
  6828. h = st->min_height;
  6829. } else if (kind == FORM_SELECT) {
  6830. w = st->width_kind == 1 ? st->width : 120;
  6831. }
  6832. if (author) {
  6833. /* Inline margins (Google's `margin:11px 4px` between its
  6834. * two submit buttons). */
  6835. ml = mp_px(st, 3, line_w);
  6836. mr = mp_px(st, 1, line_w);
  6837. mt = mp_px(st, 0, line_w);
  6838. mb = mp_px(st, 2, line_w);
  6839. if (ml < 0 || ml > 64) ml = 0;
  6840. if (mr < 0 || mr > 64) mr = 0;
  6841. if (mt < 0 || mt > 64) mt = 0;
  6842. if (mb < 0 || mb > 64) mb = 0;
  6843. }
  6844. if (w > line_w - ml - mr)
  6845. w = line_w - ml - mr;
  6846. if (w < 8)
  6847. w = 8;
  6848. if (h > 400)
  6849. h = 400;
  6850. if (l->line_x + ml + w > l->line_right &&
  6851. (l->nruns > 0 || l->line_x > l->line_left))
  6852. flush_line(l);
  6853. if (l->nruns >= 96)
  6854. return;
  6855. if (l->nruns == 0) {
  6856. l->line_y = l->y;
  6857. l->line_h = 0;
  6858. start_line(l, st);
  6859. }
  6860. l->line_x += ml;
  6861. r = &l->runs[l->nruns++];
  6862. r->gap = (unsigned short)(l->line_x - l->run_x);
  6863. r->off = r->len = 0;
  6864. r->color = st->color;
  6865. r->href = href;
  6866. r->dy = (signed short)mt;
  6867. r->has_lit = 1;
  6868. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  6869. r->lit[i] = text[i];
  6870. r->lit[i] = '\0';
  6871. r->img = -2;
  6872. r->iw = (unsigned short)w;
  6873. r->ih = (unsigned short)h;
  6874. r->w = (unsigned short)w;
  6875. r->font_px = st->font_px;
  6876. r->bold = st->bold;
  6877. r->italic = st->italic;
  6878. r->mono = st->mono;
  6879. r->font_face = st->font_face;
  6880. r->underline = 0;
  6881. r->form = node + 1;
  6882. r->form_kind = (unsigned char)kind;
  6883. r->form_disabled = (unsigned char)disabled;
  6884. if (node < BR_MAX_NODES) {
  6885. layout_boxes[node].x = l->line_x;
  6886. layout_boxes[node].y = l->line_y + mt;
  6887. layout_boxes[node].w = w;
  6888. layout_boxes[node].h = h;
  6889. layout_boxes[node].valid = 1;
  6890. }
  6891. l->line_x += w;
  6892. l->run_x = l->line_x;
  6893. l->line_x += mr;
  6894. if (l->line_h < h + mt + mb)
  6895. l->line_h = h + mt + mb;
  6896. }
  6897. /* Background, border and corner radius of an author-styled control, the
  6898. * same decoration rules as a block box. */
  6899. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  6900. const struct br_style *st, int focused)
  6901. {
  6902. int rtl = css_radius(st, 0, box.w, box.h);
  6903. int rtr = css_radius(st, 1, box.w, box.h);
  6904. int rbr = css_radius(st, 2, box.w, box.h);
  6905. int rbl = css_radius(st, 3, box.w, box.h);
  6906. int bw = st->border_t[0] ? 0 : st->border_w[0];
  6907. (void)focused;
  6908. if (box.w <= 0 || box.h <= 0)
  6909. return;
  6910. if (rtl || rtr || rbr || rbl) {
  6911. if (bw > 0 && st->has_bg && st->border_c[0] != st->bg &&
  6912. box.w > bw * 2 && box.h > bw * 2) {
  6913. struct ngui_rect in = { box.x + bw, box.y + bw,
  6914. box.w - bw * 2,
  6915. box.h - bw * 2 };
  6916. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  6917. st->border_c[0]);
  6918. ngui_fill_round_rect(ui, in,
  6919. rtl > bw ? rtl - bw : 0,
  6920. rtr > bw ? rtr - bw : 0,
  6921. rbr > bw ? rbr - bw : 0,
  6922. rbl > bw ? rbl - bw : 0, st->bg);
  6923. } else if (st->has_bg) {
  6924. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  6925. st->bg);
  6926. } else if (bw > 0) {
  6927. ngui_frame_round(ui, box, rtl, rtr, rbr, rbl, bw,
  6928. st->border_c[0]);
  6929. }
  6930. return;
  6931. }
  6932. if (st->has_bg)
  6933. ngui_fill_rect(ui, box, st->bg);
  6934. if (st->border_w[0] || st->border_w[1] || st->border_w[2] ||
  6935. st->border_w[3])
  6936. draw_border_box(ui, box, st);
  6937. }
  6938. /* A poster wrapper is absolutely positioned over the media slot; the
  6939. * measured height of its picture is normally added back to the flow. When a
  6940. * loading-skeleton sibling already reserves that slot, adding both doubles
  6941. * the media height and pushes the article text a full screen down. */
  6942. static int has_skeleton_sibling(unsigned int node)
  6943. {
  6944. unsigned int p = doc.nodes[node].parent, c;
  6945. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  6946. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  6947. continue;
  6948. if (doc.nodes[c].class_off &&
  6949. contains_ci(doc.attrs + doc.nodes[c].class_off,
  6950. "skeleton"))
  6951. return 1;
  6952. }
  6953. return 0;
  6954. }
  6955. static void layout_children(struct lay *l, unsigned int parent,
  6956. const struct br_style *pst, int depth,
  6957. unsigned short link);
  6958. static void layout_flex_children(struct lay *l, unsigned int parent,
  6959. const struct br_style *pst, int depth,
  6960. unsigned short link);
  6961. static void layout_grid_children(struct lay *l, unsigned int parent,
  6962. const struct br_style *pst, int depth,
  6963. unsigned short link);
  6964. static void layout_grid_auto(struct lay *l, unsigned int parent,
  6965. const struct br_style *pst, int depth,
  6966. unsigned short link);
  6967. static int flex_item_width(struct lay *l, unsigned int n,
  6968. const struct br_style *cs, int avail);
  6969. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  6970. const struct br_style *pst, int depth,
  6971. unsigned short link);
  6972. static void layout_table_row(struct lay *l, unsigned int row,
  6973. const struct br_style *pst, int depth,
  6974. unsigned short link);
  6975. static int table_has_rowspan(unsigned int table);
  6976. static void layout_table(struct lay *l, unsigned int table,
  6977. const struct br_style *st, int depth,
  6978. unsigned short link);
  6979. /* A flex container whose items are only inline spans is usually just a
  6980. * heading/icon pair. Our flex row positions such items without emitting
  6981. * their inline text in some deep page contexts; normal inline flow renders
  6982. * the same content correctly. */
  6983. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  6984. {
  6985. unsigned int c;
  6986. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  6987. struct br_node *nd = &doc.nodes[c];
  6988. struct br_style cs;
  6989. if (nd->type == BR_NODE_TEXT)
  6990. continue;
  6991. br_style_for(&doc, c, pst, &cs);
  6992. if (cs.display == BR_DISPLAY_NONE)
  6993. continue;
  6994. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  6995. cs.width_kind || cs.has_bg ||
  6996. cs.border_w[0] || cs.border_w[1] ||
  6997. cs.border_w[2] || cs.border_w[3] ||
  6998. nd->tag == BR_TAG_IMG)
  6999. return 1;
  7000. }
  7001. return 0;
  7002. }
  7003. static int css_radius(const struct br_style *st, int corner,
  7004. int w, int h)
  7005. {
  7006. int r = st->radius[corner];
  7007. if (r <= 0)
  7008. return 0;
  7009. if (r > w / 2)
  7010. r = w / 2;
  7011. if (r > h / 2)
  7012. r = h / 2;
  7013. return r;
  7014. }
  7015. /* ---- inline SVG ----
  7016. *
  7017. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  7018. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  7019. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  7020. * opacity and solid paint; a gradient paints the average of its stops) and
  7021. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  7022. #define SVG_CACHE_MAX 48
  7023. #define SVG_CACHE_PIXELS (640 * 1024)
  7024. #define SVG_MAX_POINTS 24576
  7025. struct svg_cache_ent {
  7026. unsigned int node;
  7027. int w, h;
  7028. unsigned short *px;
  7029. unsigned char *a;
  7030. unsigned int stamp;
  7031. };
  7032. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  7033. static unsigned int svg_cache_pixels, svg_cache_clock;
  7034. static struct svgr svg_geom;
  7035. static void *svg_geom_buf;
  7036. /* Current viewport in user units: percentage lengths resolve against it
  7037. * (the viewBox size, not the device pixels). */
  7038. static double svg_vp_w = 300, svg_vp_h = 150;
  7039. /* The layers live in the page heap: forget them before heap_reset(). */
  7040. static void svg_cache_clear(void)
  7041. {
  7042. memset(svg_cache, 0, sizeof(svg_cache));
  7043. svg_cache_pixels = 0;
  7044. svg_geom_buf = 0;
  7045. }
  7046. static int svg_name_is(const char *a, const char *b)
  7047. {
  7048. while (*a && *b) {
  7049. char x = *a, y = *b;
  7050. if (x >= 'A' && x <= 'Z')
  7051. x = (char)(x - 'A' + 'a');
  7052. if (x != y)
  7053. return 0;
  7054. a++;
  7055. b++;
  7056. }
  7057. return *a == *b;
  7058. }
  7059. static const char *svg_elem_name(unsigned int node)
  7060. {
  7061. const struct br_node *nd = &doc.nodes[node];
  7062. if (nd->name_off)
  7063. return doc.attrs + nd->name_off;
  7064. return br_tag_name(nd->tag);
  7065. }
  7066. /* A numeric attribute; a percentage resolves against `base`. */
  7067. static double svg_attr_num(unsigned int node, const char *name, double def,
  7068. double base)
  7069. {
  7070. const char *v = br_find_attr(&doc, node, name);
  7071. const char *p = v;
  7072. int ok = 0;
  7073. double x;
  7074. if (!v)
  7075. return def;
  7076. x = svgr_num(&p, &ok);
  7077. if (!ok)
  7078. return def;
  7079. if (*p == '%')
  7080. x = x * base / 100.0;
  7081. return x;
  7082. }
  7083. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  7084. static int svg_viewbox4(unsigned int node, double vb[4])
  7085. {
  7086. const char *v = br_find_attr(&doc, node, "viewbox");
  7087. const char *p = v;
  7088. int i, ok = 1;
  7089. if (!v)
  7090. return 0;
  7091. for (i = 0; i < 4 && ok; i++)
  7092. vb[i] = svgr_num(&p, &ok);
  7093. return ok && vb[2] > 0 && vb[3] > 0;
  7094. }
  7095. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  7096. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  7097. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  7098. double w, double h, double m[6])
  7099. {
  7100. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  7101. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  7102. int ax = 1, ay = 1;
  7103. if (par && contains_ci(par, "none")) {
  7104. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  7105. m[4] = -vb[0] * sx;
  7106. m[5] = -vb[1] * sy;
  7107. return;
  7108. }
  7109. if (par) {
  7110. if (contains_ci(par, "xmin"))
  7111. ax = 0;
  7112. else if (contains_ci(par, "xmax"))
  7113. ax = 2;
  7114. if (contains_ci(par, "ymin"))
  7115. ay = 0;
  7116. else if (contains_ci(par, "ymax"))
  7117. ay = 2;
  7118. }
  7119. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  7120. (sx < sy ? sx : sy);
  7121. tx = (w - vb[2] * s) * ax / 2.0;
  7122. ty = (h - vb[3] * s) * ay / 2.0;
  7123. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  7124. m[4] = tx - vb[0] * s;
  7125. m[5] = ty - vb[1] * s;
  7126. }
  7127. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  7128. * the paint attribute, then average the gradient's stops. */
  7129. static int svg_url_paint(unsigned int node, const char *attr,
  7130. unsigned short *color, unsigned int *alpha)
  7131. {
  7132. const char *v = 0, *h;
  7133. char id[64];
  7134. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  7135. for (k = 0; node && k < 32 && !v; k++) {
  7136. v = br_find_attr(&doc, node, attr);
  7137. if (!v) {
  7138. const char *style = br_find_attr(&doc, node, "style");
  7139. if (style && contains_ci(style, "url(#"))
  7140. v = strstr(style, "url(#");
  7141. }
  7142. if (v && !contains_ci(v, "url("))
  7143. v = 0;
  7144. node = doc.nodes[node].parent;
  7145. }
  7146. if (!v || !(h = strstr(v, "#")))
  7147. return 0;
  7148. h++;
  7149. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  7150. id[n++] = *h++;
  7151. id[n] = '\0';
  7152. g = br_find_id(&doc, id);
  7153. /* Follow href chains (a gradient that only references another one's
  7154. * stops), at most a few hops. */
  7155. for (k = 0; g && k < 4; k++) {
  7156. unsigned int gi = g - 1;
  7157. const char *ref;
  7158. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  7159. const char *nm, *sc, *so;
  7160. unsigned short col = 0;
  7161. double op = 1;
  7162. if (doc.nodes[c].type != BR_NODE_ELEM)
  7163. continue;
  7164. nm = svg_elem_name(c);
  7165. if (!svg_name_is(nm, "stop"))
  7166. continue;
  7167. sc = br_find_attr(&doc, c, "stop-color");
  7168. so = br_find_attr(&doc, c, "stop-opacity");
  7169. {
  7170. const char *st = br_find_attr(&doc, c, "style");
  7171. const char *q;
  7172. if (st && (q = strstr(st, "stop-color:")) != 0)
  7173. sc = q + 11;
  7174. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  7175. so = q + 13;
  7176. }
  7177. if (sc) {
  7178. unsigned int L = 0;
  7179. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  7180. L++;
  7181. if (!br_parse_color(sc, L, &col))
  7182. col = 0;
  7183. }
  7184. if (so) {
  7185. const char *p = so;
  7186. int ok = 0;
  7187. double x = svgr_num(&p, &ok);
  7188. if (ok)
  7189. op = x < 0 ? 0 : x > 1 ? 1 : x;
  7190. }
  7191. sr += (col >> 11) & 31;
  7192. sg += (col >> 5) & 63;
  7193. sb += col & 31;
  7194. sa += (unsigned int)(op * 255);
  7195. cnt++;
  7196. }
  7197. if (cnt)
  7198. break;
  7199. ref = br_find_attr(&doc, gi, "href");
  7200. if (!ref)
  7201. ref = br_find_attr(&doc, gi, "xlink:href");
  7202. if (!ref || ref[0] != '#')
  7203. break;
  7204. g = br_find_id(&doc, ref + 1);
  7205. }
  7206. if (!cnt)
  7207. return 0;
  7208. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  7209. (sb / cnt));
  7210. *alpha = sa / cnt;
  7211. return 1;
  7212. }
  7213. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  7214. unsigned short *color, unsigned int *alpha)
  7215. {
  7216. int mode = fill ? st->fill_mode : st->stroke_mode;
  7217. const char *op = br_find_attr(&doc, node,
  7218. fill ? "fill-opacity" : "stroke-opacity");
  7219. *alpha = 255;
  7220. switch (mode) {
  7221. case BR_PAINT_UNSET:
  7222. if (!fill)
  7223. return 0;
  7224. *color = 0;
  7225. break;
  7226. case BR_PAINT_COLOR:
  7227. *color = fill ? st->fill : st->stroke;
  7228. break;
  7229. case BR_PAINT_CURRENT:
  7230. *color = st->color;
  7231. break;
  7232. case BR_PAINT_URL:
  7233. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  7234. alpha))
  7235. return 0;
  7236. break;
  7237. default:
  7238. return 0;
  7239. }
  7240. if (op) {
  7241. const char *p = op;
  7242. int ok = 0;
  7243. double x = svgr_num(&p, &ok);
  7244. if (ok)
  7245. *alpha = (unsigned int)(*alpha *
  7246. (x < 0 ? 0 : x > 1 ? 1 : x));
  7247. }
  7248. return *alpha > 0;
  7249. }
  7250. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7251. const double m[6], const struct br_style *pst,
  7252. unsigned int alpha, int depth);
  7253. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  7254. const double m[6], const struct br_style *st,
  7255. unsigned int alpha, int depth)
  7256. {
  7257. unsigned int c;
  7258. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  7259. if (doc.nodes[c].type == BR_NODE_ELEM)
  7260. svg_draw_node(L, c, m, st, alpha, depth + 1);
  7261. }
  7262. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7263. const double pm[6], const struct br_style *pst,
  7264. unsigned int alpha, int depth)
  7265. {
  7266. struct br_style st;
  7267. const char *nm = svg_elem_name(node);
  7268. const char *tf;
  7269. double m[6];
  7270. unsigned short color;
  7271. unsigned int pa;
  7272. int shape = 0, fillable = 1;
  7273. if (depth > 24 || !nm)
  7274. return;
  7275. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  7276. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  7277. svg_name_is(nm, "lineargradient") ||
  7278. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  7279. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  7280. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  7281. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  7282. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  7283. svg_name_is(nm, "foreignobject"))
  7284. return;
  7285. br_style_for(&doc, node, pst, &st);
  7286. if (st.display == BR_DISPLAY_NONE)
  7287. return;
  7288. memcpy(m, pm, sizeof(m));
  7289. tf = br_find_attr(&doc, node, "transform");
  7290. if (tf)
  7291. svgr_transform(m, tf);
  7292. {
  7293. const char *op = br_find_attr(&doc, node, "opacity");
  7294. if (op) {
  7295. const char *p = op;
  7296. int ok = 0;
  7297. double x = svgr_num(&p, &ok);
  7298. if (ok)
  7299. alpha = (unsigned int)(alpha *
  7300. (x < 0 ? 0 :
  7301. x > 1 ? 1 : x));
  7302. }
  7303. }
  7304. if (!alpha)
  7305. return;
  7306. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  7307. svg_name_is(nm, "switch")) {
  7308. svg_draw_children(L, node, m, &st, alpha, depth);
  7309. return;
  7310. }
  7311. if (svg_name_is(nm, "svg")) {
  7312. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  7313. y = svg_attr_num(node, "y", 0, 0);
  7314. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7315. t[4] = x;
  7316. t[5] = y;
  7317. svgr_mat_mul(m, m, t);
  7318. double ow = svg_vp_w, oh = svg_vp_h;
  7319. if (svg_viewbox4(node, vb)) {
  7320. double w = svg_attr_num(node, "width", vb[2], ow);
  7321. double h = svg_attr_num(node, "height", vb[3], oh);
  7322. double vm[6];
  7323. svg_viewport_matrix(node, vb, w, h, vm);
  7324. svgr_mat_mul(m, m, vm);
  7325. svg_vp_w = vb[2];
  7326. svg_vp_h = vb[3];
  7327. }
  7328. svg_draw_children(L, node, m, &st, alpha, depth);
  7329. svg_vp_w = ow;
  7330. svg_vp_h = oh;
  7331. return;
  7332. }
  7333. if (svg_name_is(nm, "use")) {
  7334. const char *ref = br_find_attr(&doc, node, "href");
  7335. unsigned int tgt;
  7336. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7337. if (!ref)
  7338. ref = br_find_attr(&doc, node, "xlink:href");
  7339. if (!ref || ref[0] != '#')
  7340. return;
  7341. tgt = br_find_id(&doc, ref + 1);
  7342. if (!tgt || tgt - 1 == node)
  7343. return;
  7344. tgt--;
  7345. t[4] = svg_attr_num(node, "x", 0, 0);
  7346. t[5] = svg_attr_num(node, "y", 0, 0);
  7347. svgr_mat_mul(m, m, t);
  7348. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  7349. double vb[4];
  7350. double ow = svg_vp_w, oh = svg_vp_h;
  7351. if (svg_viewbox4(tgt, vb)) {
  7352. double w = svg_attr_num(node, "width", vb[2],
  7353. ow);
  7354. double h = svg_attr_num(node, "height", vb[3],
  7355. oh);
  7356. double vm[6];
  7357. svg_viewport_matrix(tgt, vb, w, h, vm);
  7358. svgr_mat_mul(m, m, vm);
  7359. svg_vp_w = vb[2];
  7360. svg_vp_h = vb[3];
  7361. }
  7362. svg_draw_children(L, tgt, m, &st, alpha, depth);
  7363. svg_vp_w = ow;
  7364. svg_vp_h = oh;
  7365. } else {
  7366. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  7367. }
  7368. return;
  7369. }
  7370. svgr_reset(&svg_geom, m);
  7371. if (svg_name_is(nm, "path")) {
  7372. const char *d = br_find_attr(&doc, node, "d");
  7373. if (d) {
  7374. svgr_path(&svg_geom, d);
  7375. shape = 1;
  7376. }
  7377. } else if (svg_name_is(nm, "rect")) {
  7378. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  7379. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  7380. double rx = svg_attr_num(node, "rx", -1, w);
  7381. double ry = svg_attr_num(node, "ry", -1, h);
  7382. if (rx < 0)
  7383. rx = ry < 0 ? 0 : ry;
  7384. if (ry < 0)
  7385. ry = rx;
  7386. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  7387. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  7388. shape = 1;
  7389. } else if (svg_name_is(nm, "circle")) {
  7390. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  7391. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7392. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  7393. shape = 1;
  7394. } else if (svg_name_is(nm, "ellipse")) {
  7395. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7396. svg_attr_num(node, "cy", 0, svg_vp_h),
  7397. svg_attr_num(node, "rx", 0, svg_vp_w),
  7398. svg_attr_num(node, "ry", 0, svg_vp_h));
  7399. shape = 1;
  7400. } else if (svg_name_is(nm, "line")) {
  7401. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  7402. svg_attr_num(node, "y1", 0, svg_vp_h));
  7403. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  7404. svg_attr_num(node, "y2", 0, svg_vp_h));
  7405. shape = 1;
  7406. fillable = 0;
  7407. } else if (svg_name_is(nm, "polyline") ||
  7408. svg_name_is(nm, "polygon")) {
  7409. const char *pts = br_find_attr(&doc, node, "points");
  7410. if (pts) {
  7411. svgr_points(&svg_geom, pts,
  7412. svg_name_is(nm, "polygon"));
  7413. shape = 1;
  7414. }
  7415. }
  7416. if (!shape)
  7417. return;
  7418. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  7419. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  7420. st.fill_evenodd);
  7421. if (svg_paint(node, &st, 0, &color, &pa)) {
  7422. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  7423. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7424. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  7425. }
  7426. }
  7427. /* <text> elements: drawn straight onto the page every frame (the glyph
  7428. * renderer targets the ngui canvas, not a layer). x/y map through the
  7429. * accumulated transform; the font size scales with it. */
  7430. static void svg_draw_text(struct ngui *ui, unsigned int node,
  7431. const double pm[6], const struct br_style *pst,
  7432. int ox, int oy, int depth)
  7433. {
  7434. unsigned int c;
  7435. if (depth > 24)
  7436. return;
  7437. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7438. struct br_style st;
  7439. const char *nm, *tf;
  7440. double m[6];
  7441. if (doc.nodes[c].type != BR_NODE_ELEM)
  7442. continue;
  7443. nm = svg_elem_name(c);
  7444. if (!nm || svg_name_is(nm, "defs") ||
  7445. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  7446. svg_name_is(nm, "clippath"))
  7447. continue;
  7448. br_style_for(&doc, c, pst, &st);
  7449. if (st.display == BR_DISPLAY_NONE)
  7450. continue;
  7451. memcpy(m, pm, sizeof(m));
  7452. tf = br_find_attr(&doc, c, "transform");
  7453. if (tf)
  7454. svgr_transform(m, tf);
  7455. if (svg_name_is(nm, "text")) {
  7456. unsigned int t = doc.nodes[c].first;
  7457. const char *s;
  7458. unsigned int n, tw;
  7459. double x = svg_attr_num(c, "x", 0, 0),
  7460. y = svg_attr_num(c, "y", 0, 0);
  7461. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7462. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  7463. int tx, ty, anchor;
  7464. unsigned short col;
  7465. unsigned int pa;
  7466. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  7467. continue;
  7468. if (px < 6)
  7469. px = 6;
  7470. if (px > 72)
  7471. px = 72;
  7472. if (!svg_paint(c, &st, 1, &col, &pa))
  7473. continue;
  7474. s = doc.text + doc.nodes[t].text_off;
  7475. n = doc.nodes[t].text_len;
  7476. st.font_px = (unsigned char)px;
  7477. tw = face_text_width(ui, &st, s, n);
  7478. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  7479. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  7480. ngui_text_ascent_face(ui, style_face(&st), px,
  7481. st.mono);
  7482. anchor = st.align;
  7483. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  7484. anchor = BR_ALIGN_CENTER;
  7485. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  7486. anchor = BR_ALIGN_RIGHT;
  7487. if (anchor == BR_ALIGN_CENTER)
  7488. tx -= (int)tw / 2;
  7489. else if (anchor == BR_ALIGN_RIGHT)
  7490. tx -= (int)tw;
  7491. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  7492. col, px, st.bold, st.italic,
  7493. st.mono);
  7494. } else {
  7495. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  7496. }
  7497. }
  7498. }
  7499. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  7500. {
  7501. double vb[4];
  7502. if (svg_viewbox4(node, vb)) {
  7503. svg_viewport_matrix(node, vb, w, h, m);
  7504. } else {
  7505. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  7506. }
  7507. }
  7508. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  7509. const struct br_style *st)
  7510. {
  7511. struct svg_cache_ent *e = 0;
  7512. struct svgr_layer L;
  7513. double m[6];
  7514. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  7515. svg_cache_clock++;
  7516. for (i = 0; i < SVG_CACHE_MAX; i++)
  7517. if (svg_cache[i].px && svg_cache[i].node == node &&
  7518. svg_cache[i].w == w && svg_cache[i].h == h) {
  7519. svg_cache[i].stamp = svg_cache_clock;
  7520. return &svg_cache[i];
  7521. }
  7522. if (need > SVG_CACHE_PIXELS)
  7523. return 0;
  7524. /* Evict least recently used layers until this one fits. */
  7525. for (;;) {
  7526. struct svg_cache_ent *lru = 0, *free_slot = 0;
  7527. for (i = 0; i < SVG_CACHE_MAX; i++) {
  7528. if (!svg_cache[i].px) {
  7529. if (!free_slot)
  7530. free_slot = &svg_cache[i];
  7531. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  7532. lru = &svg_cache[i];
  7533. }
  7534. }
  7535. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  7536. e = free_slot;
  7537. break;
  7538. }
  7539. if (!lru)
  7540. return 0;
  7541. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  7542. free(lru->px);
  7543. free(lru->a);
  7544. memset(lru, 0, sizeof(*lru));
  7545. }
  7546. if (!svg_geom_buf) {
  7547. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7548. if (!svg_geom_buf)
  7549. return 0;
  7550. }
  7551. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  7552. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  7553. e->a = (unsigned char *)calloc(need, 1);
  7554. if (!e->px || !e->a) {
  7555. free(e->px);
  7556. free(e->a);
  7557. memset(e, 0, sizeof(*e));
  7558. return 0;
  7559. }
  7560. e->node = node;
  7561. e->w = w;
  7562. e->h = h;
  7563. e->stamp = svg_cache_clock;
  7564. svg_cache_pixels += need;
  7565. L.px = e->px;
  7566. L.a = e->a;
  7567. L.w = w;
  7568. L.h = h;
  7569. svg_root_matrix(node, w, h, m);
  7570. {
  7571. double vb[4];
  7572. if (svg_viewbox4(node, vb)) {
  7573. svg_vp_w = vb[2];
  7574. svg_vp_h = vb[3];
  7575. } else {
  7576. svg_vp_w = w;
  7577. svg_vp_h = h;
  7578. }
  7579. }
  7580. svg_draw_children(&L, node, m, st, 255, 0);
  7581. return e;
  7582. }
  7583. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  7584. *
  7585. * The markup is parsed into a detached subtree of the page document and
  7586. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  7587. * bitmap, which then behaves like any decoded image. currentColor is
  7588. * black (an image has no inherited text colour); <text> is not drawn. */
  7589. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  7590. {
  7591. unsigned int i = 0;
  7592. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  7593. i = 3;
  7594. while (i < len) {
  7595. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  7596. d[i] == '\r' || d[i] == '\n'))
  7597. i++;
  7598. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  7599. return 1;
  7600. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  7601. i += 4;
  7602. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  7603. i++;
  7604. i += 3;
  7605. continue;
  7606. }
  7607. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  7608. while (i < len && d[i] != '>')
  7609. i++;
  7610. i++;
  7611. continue;
  7612. }
  7613. return 0;
  7614. }
  7615. return 0;
  7616. }
  7617. static int svg_len_attr(unsigned int node, const char *name)
  7618. {
  7619. const char *v = br_find_attr(&doc, node, name);
  7620. int n = 0, any = 0;
  7621. if (!v)
  7622. return 0;
  7623. while (*v == ' ')
  7624. v++;
  7625. while (*v >= '0' && *v <= '9') {
  7626. n = n * 10 + (*v++ - '0');
  7627. any = 1;
  7628. }
  7629. if (*v == '.')
  7630. while (*++v >= '0' && *v <= '9')
  7631. ;
  7632. if (!any || *v == '%')
  7633. return 0;
  7634. return n;
  7635. }
  7636. static int svg_decode_image(const unsigned char *data, unsigned int len,
  7637. struct br_image *bi, int box_w, int box_h)
  7638. {
  7639. unsigned int holder, svg = 0, c, need, i;
  7640. struct br_style base = base_style(), st;
  7641. struct svgr_layer L;
  7642. double vb[4], m[6];
  7643. int w, h, have_vb, nat_w, nat_h;
  7644. holder = br_create_element(&doc, "div", 3);
  7645. if (!holder) {
  7646. s_copy(bi->err, "page is full", sizeof(bi->err));
  7647. return -1;
  7648. }
  7649. holder--;
  7650. br_set_inner_html(&doc, holder, (const char *)data, len);
  7651. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  7652. if (doc.nodes[c].type == BR_NODE_ELEM &&
  7653. doc.nodes[c].tag == BR_TAG_SVG) {
  7654. svg = c;
  7655. break;
  7656. }
  7657. if (!svg) {
  7658. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  7659. return -1;
  7660. }
  7661. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  7662. w = svg_len_attr(svg, "width");
  7663. h = svg_len_attr(svg, "height");
  7664. if (box_w > 0 && box_h > 0) {
  7665. w = box_w;
  7666. h = box_h;
  7667. } else if (!w && !h) {
  7668. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  7669. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  7670. } else if (!w) {
  7671. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  7672. } else if (!h) {
  7673. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  7674. }
  7675. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  7676. * so CSS scaling stays crisp. */
  7677. nat_w = w;
  7678. nat_h = h;
  7679. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  7680. w *= 2;
  7681. h *= 2;
  7682. }
  7683. if (w > BR_IMG_LAYOUT_W) {
  7684. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  7685. w = BR_IMG_LAYOUT_W;
  7686. }
  7687. if (h > 2048)
  7688. h = 2048;
  7689. if (w < 1)
  7690. w = 1;
  7691. if (h < 1)
  7692. h = 1;
  7693. need = (unsigned int)w * (unsigned int)h;
  7694. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  7695. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  7696. return -1;
  7697. }
  7698. if (!svg_geom_buf) {
  7699. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7700. if (!svg_geom_buf) {
  7701. s_copy(bi->err, "out of memory", sizeof(bi->err));
  7702. return -1;
  7703. }
  7704. }
  7705. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  7706. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  7707. L.a = (unsigned char *)calloc(need, 1);
  7708. if (!L.px || !L.a) {
  7709. free(L.px);
  7710. free(L.a);
  7711. s_copy(bi->err, "out of memory", sizeof(bi->err));
  7712. return -1;
  7713. }
  7714. for (i = 0; i < need; i++)
  7715. L.px[i] = 0xFFFF;
  7716. L.w = w;
  7717. L.h = h;
  7718. base.color = 0x0000;
  7719. br_style_for(&doc, svg, &base, &st);
  7720. svg_root_matrix(svg, w, h, m);
  7721. svg_vp_w = have_vb ? vb[2] : w;
  7722. svg_vp_h = have_vb ? vb[3] : h;
  7723. svg_draw_children(&L, svg, m, &st, 255, 0);
  7724. bi->native_w = nat_w;
  7725. bi->native_h = nat_h;
  7726. bi->img.format = 0;
  7727. bi->img.w = (unsigned int)w;
  7728. bi->img.h = (unsigned int)h;
  7729. bi->img.px = L.px;
  7730. bi->img.alpha = L.a;
  7731. bi->img.flags = 0;
  7732. bi->state = 1;
  7733. image_pixels += need;
  7734. return 0;
  7735. }
  7736. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  7737. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  7738. int *out_w, int *out_h)
  7739. {
  7740. double vb[4];
  7741. int has_vb = svg_viewbox4(node, vb);
  7742. double aw = svg_attr_num(node, "width", -1, cw);
  7743. double ah = svg_attr_num(node, "height", -1, 0);
  7744. int w, h;
  7745. if (st->width_kind)
  7746. w = cw;
  7747. else if (aw > 0)
  7748. w = (int)(aw + 0.5);
  7749. else if (st->height_kind == 1 && has_vb)
  7750. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  7751. else if (ah > 0 && has_vb)
  7752. w = (int)(ah * vb[2] / vb[3] + 0.5);
  7753. else if (has_vb)
  7754. w = cw;
  7755. else
  7756. w = 300;
  7757. if (st->max_width_kind == 1 && w > st->max_width)
  7758. w = st->max_width;
  7759. if (w > cw && cw > 0 && !(aw > 0))
  7760. w = cw;
  7761. if (w < 1)
  7762. w = 1;
  7763. if (w > 2000)
  7764. w = 2000;
  7765. if (st->height_kind == 1)
  7766. h = st->height;
  7767. else if (ah > 0)
  7768. h = (int)(ah + 0.5);
  7769. else if (has_vb)
  7770. h = (int)(w * vb[3] / vb[2] + 0.5);
  7771. else
  7772. h = 150;
  7773. if (h < 1)
  7774. h = 1;
  7775. if (h > 1400)
  7776. h = 1400;
  7777. *out_w = w;
  7778. *out_h = h;
  7779. }
  7780. static void svg_paint_box(struct ngui *ui, unsigned int node,
  7781. const struct br_style *st, int x, int y, int w, int h)
  7782. {
  7783. struct svg_cache_ent *e;
  7784. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  7785. int cx0, cy0, cx1, cy1, px, py;
  7786. double m[6];
  7787. if (ui->nclip > 0)
  7788. clip = ui->clip[ui->nclip - 1];
  7789. cx0 = r.x > clip.x ? r.x : clip.x;
  7790. cy0 = r.y > clip.y ? r.y : clip.y;
  7791. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  7792. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  7793. if (cx0 >= cx1 || cy0 >= cy1)
  7794. return;
  7795. e = svg_layer(node, w, h, st);
  7796. if (e) {
  7797. for (py = cy0; py < cy1; py++) {
  7798. unsigned int srow = (unsigned int)(py - y) *
  7799. (unsigned int)w;
  7800. unsigned short *dst = ui->px + py * ui->w;
  7801. for (px = cx0; px < cx1; px++) {
  7802. unsigned int si = srow + (unsigned int)(px - x);
  7803. unsigned int a = e->a[si];
  7804. if (!a)
  7805. continue;
  7806. dst[px] = a >= 255 ? e->px[si] :
  7807. blend_rgb565(dst[px], e->px[si], a);
  7808. }
  7809. }
  7810. }
  7811. svg_root_matrix(node, w, h, m);
  7812. ngui_push_clip(ui, r);
  7813. svg_draw_text(ui, node, m, st, x, y, 0);
  7814. ngui_pop_clip(ui);
  7815. }
  7816. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  7817. * keep using add_image_run(); this covers the CSS `position:absolute;
  7818. * width:100%` poster pattern used by news sites. */
  7819. static void image_block_size(unsigned int node, const struct br_style *st,
  7820. int cbw, int *out_w, int *out_h)
  7821. {
  7822. struct br_node *nd = &doc.nodes[node];
  7823. int idx = nd->img_index;
  7824. int iw = 0, ih = 0, w, h, aw, ah;
  7825. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  7826. iw = (int)images[idx].img.w;
  7827. ih = (int)images[idx].img.h;
  7828. if (iw <= 0 || ih <= 0) {
  7829. iw = (int)images[idx].native_w;
  7830. ih = (int)images[idx].native_h;
  7831. }
  7832. }
  7833. if (st->width_kind)
  7834. w = style_width_px(st, cbw);
  7835. else if (nd->width_attr)
  7836. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  7837. (int)nd->width_attr;
  7838. else if (nd->height_attr && !nd->height_pct && iw && ih)
  7839. w = iw * (int)nd->height_attr / ih;
  7840. else if (iw)
  7841. w = iw;
  7842. else
  7843. w = 64;
  7844. /* max-width/min-width against the containing block: Tailwind's
  7845. * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
  7846. * 300x300 thumbnail to its 75 px avatar box. */
  7847. if (st->max_width_kind) {
  7848. int mw = st->max_width_kind == 3 ?
  7849. cbw * st->max_width_calc_pct / 100 +
  7850. st->max_width_calc_px :
  7851. st->max_width_kind == 2 ?
  7852. cbw * (int)st->max_width / 100 : (int)st->max_width;
  7853. if (mw > 0 && w > mw)
  7854. w = mw;
  7855. }
  7856. if (st->min_width_kind) {
  7857. int mn = st->min_width_kind == 3 ?
  7858. cbw * st->min_width_calc_pct / 100 +
  7859. st->min_width_calc_px :
  7860. st->min_width_kind == 2 ?
  7861. cbw * (int)st->min_width / 100 : (int)st->min_width;
  7862. if (mn > w)
  7863. w = mn;
  7864. }
  7865. if (w < 8)
  7866. w = 8;
  7867. if (cbw > 0 && w > cbw)
  7868. w = cbw;
  7869. /* Without a CSS height the attributes (or the bitmap) only give the
  7870. * aspect ratio: a width clamped by max-width scales the height too,
  7871. * instead of letterboxing the image into its attribute height. */
  7872. aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
  7873. ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
  7874. if (st->height_kind)
  7875. h = style_height_px(st, cbw);
  7876. else if (aw > 0 && ah > 0)
  7877. h = w * ah / aw;
  7878. else if (nd->height_attr)
  7879. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  7880. (int)nd->height_attr;
  7881. else
  7882. h = 64;
  7883. if (h < 8)
  7884. h = 8;
  7885. *out_w = w;
  7886. *out_h = h;
  7887. }
  7888. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  7889. int dw, int dh)
  7890. {
  7891. int idx = doc.nodes[node].img_index;
  7892. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  7893. struct img_image *src = image_display_get(&images[idx], dw, dh);
  7894. struct img_blit b;
  7895. if (!src)
  7896. src = &images[idx].img;
  7897. b.dst = l->ui->px;
  7898. b.dst_w = l->ui->w;
  7899. b.dst_h = l->ui->h;
  7900. b.clip_x = page_rect.x;
  7901. b.clip_y = page_rect.y;
  7902. b.clip_w = page_rect.w - 12;
  7903. b.clip_h = page_rect.h;
  7904. b.x = x;
  7905. b.y = y;
  7906. b.scale = ((unsigned int)dw << 16) / src->w;
  7907. b.bg = ui.theme.bg;
  7908. b.bg2 = ui.theme.bg;
  7909. b.dst_a = 0;
  7910. /* OVER_DST is only needed for an alpha source; an opaque one can
  7911. * take img_draw's 1:1 copy path. */
  7912. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  7913. img_draw(src, &b);
  7914. } else if (l->draw) {
  7915. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  7916. 0xD69A);
  7917. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  7918. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  7919. }
  7920. }
  7921. static void layout_block(struct lay *l, unsigned int node,
  7922. const struct br_style *st, int depth,
  7923. unsigned short link)
  7924. {
  7925. int old_left = l->left, old_right = l->right, old_align = l->align;
  7926. int parent_cb_h = l->cb_h;
  7927. int saved_parent_top = l->parent_top;
  7928. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  7929. int saved_cb_top = l->cb_top;
  7930. int top, l0, r0;
  7931. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  7932. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  7933. int deco_w, deco_h, content_w, content_h, box_h;
  7934. int img_dh = 0;
  7935. int definite_w = 0;
  7936. int normal_top = 0;
  7937. int rel_dx = 0, rel_dy = 0;
  7938. int clip_pushed = 0;
  7939. struct ngui_rect clip_rect;
  7940. /* A DOM level costs about two depth units (layout_block ->
  7941. * layout_children), so 48 covers a ~24-level page. Real news pages
  7942. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  7943. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  7944. return;
  7945. flow_y = l->y;
  7946. flow_left = l->left;
  7947. flow_right = l->right;
  7948. positioned = st->pos == 1 || st->pos == 2;
  7949. relative = st->pos == 3;
  7950. sticky = st->pos == 4;
  7951. shifted = relative || sticky || st->transform_set;
  7952. if (positioned) {
  7953. int def_w = st->width_kind == 1 ? st->width : -1;
  7954. if (st->pos == 2) {
  7955. int avail_w = page_rect.w - 12;
  7956. if (st->right_set && def_w >= 0)
  7957. l->left = page_rect.x + avail_w - st->right -
  7958. def_w;
  7959. else
  7960. l->left = page_rect.x +
  7961. (st->left_set ? st->left : 0);
  7962. l->right = def_w >= 0 ? l->left + def_w :
  7963. page_rect.x + avail_w;
  7964. if (st->bottom_set && st->height_kind)
  7965. l->y = page_rect.y + page_rect.h -
  7966. st->bottom -
  7967. style_height_px(st, page_rect.w);
  7968. else
  7969. l->y = page_rect.y +
  7970. (st->top_set ? st->top : 0);
  7971. } else {
  7972. int left = flow_left + (st->left_set ? st->left : 0);
  7973. unsigned int parent = doc.nodes[node].parent;
  7974. if (st->right_set && def_w >= 0)
  7975. left = flow_right - st->right - def_w;
  7976. l->left = left;
  7977. l->right = def_w >= 0 ? left + def_w :
  7978. flow_right +
  7979. (st->left_set ? st->left : 0);
  7980. l->y = flow_y + (st->top_set ? st->top : 0);
  7981. if (st->bottom_set && st->height_kind &&
  7982. parent < BR_MAX_NODES && block_h[parent] > 0)
  7983. l->y = flow_y + block_h[parent] - st->bottom -
  7984. style_height_px(st, old_right - old_left);
  7985. }
  7986. old_left = l->left;
  7987. old_right = l->right;
  7988. } else if (relative) {
  7989. rel_dx = st->left_set ? st->left :
  7990. (st->right_set ? -st->right : 0);
  7991. rel_dy = st->top_set ? st->top :
  7992. (st->bottom_set ? -st->bottom : 0);
  7993. }
  7994. if (st->transform_set) {
  7995. rel_dx += st->tx;
  7996. rel_dy += st->ty;
  7997. }
  7998. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  7999. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  8000. doc.nodes[node].tag == BR_TAG_SELECT ||
  8001. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  8002. !button_has_elements(node)) {
  8003. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  8004. s_eq(br_type(&doc, node), "hidden"))
  8005. return;
  8006. /* Reached as a block-level box (a flex item): the control
  8007. * fills the box the caller assigned, and its line is flushed
  8008. * here; flex layout resets the run list for the next item, so
  8009. * a queued run would never be drawn. */
  8010. form_fill_line = 1;
  8011. add_form_run(l, node, st, link);
  8012. form_fill_line = 0;
  8013. flush_line(l);
  8014. return;
  8015. }
  8016. flush_line(l);
  8017. cbw = old_right - old_left;
  8018. if (cbw < 8)
  8019. cbw = 8;
  8020. l->y += mp_px(st, 0, cbw);
  8021. top = l->y;
  8022. ml = mp_px(st, 3, cbw);
  8023. mr = mp_px(st, 1, cbw);
  8024. bl = st->border_w[3];
  8025. br = st->border_w[1];
  8026. pl = mp_px(st, 7, cbw);
  8027. pr = mp_px(st, 5, cbw);
  8028. bt = st->border_w[0];
  8029. bb = st->border_w[2];
  8030. pt = mp_px(st, 4, cbw);
  8031. pb = mp_px(st, 6, cbw);
  8032. deco_w = bl + br + pl + pr;
  8033. deco_h = bt + bb + pt + pb;
  8034. if (st->width_kind) {
  8035. int w;
  8036. if (st->width_kind == 3)
  8037. w = cbw * st->width_calc_pct / 100 +
  8038. st->width_calc_px;
  8039. else
  8040. w = css_size(st->width_kind, st->width, cbw);
  8041. if (w < 0)
  8042. w = 0;
  8043. content_w = st->box_sizing ? w - deco_w : w;
  8044. definite_w = 1;
  8045. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  8046. doc.nodes[node].tag == BR_TAG_TD ||
  8047. doc.nodes[node].tag == BR_TAG_TH) &&
  8048. doc.nodes[node].width_attr) {
  8049. /* Legacy table/cell width attributes: percentages resolve
  8050. * against the containing block, bare numbers are pixels. */
  8051. int w = doc.nodes[node].width_pct ?
  8052. cbw * doc.nodes[node].width_attr / 100 :
  8053. doc.nodes[node].width_attr;
  8054. if (w < 0)
  8055. w = 0;
  8056. content_w = st->box_sizing ? w - deco_w : w;
  8057. definite_w = 1;
  8058. } else {
  8059. content_w = cbw - ml - mr - deco_w;
  8060. }
  8061. if (content_w < 0)
  8062. content_w = 0;
  8063. if (st->max_width_kind) {
  8064. int mw = st->max_width_kind == 3 ?
  8065. cbw * st->max_width_calc_pct / 100 +
  8066. st->max_width_calc_px :
  8067. css_size(st->max_width_kind, st->max_width, cbw);
  8068. int max_box = st->box_sizing ? mw : mw + deco_w;
  8069. /* A clamped auto width is used as the width, so auto
  8070. * margins share the rest (Google's 688 px search box). */
  8071. if (content_w + deco_w > max_box) {
  8072. content_w = max_box - deco_w;
  8073. definite_w = 1;
  8074. }
  8075. }
  8076. if (st->min_width_kind) {
  8077. int mw = st->min_width_kind == 3 ?
  8078. cbw * st->min_width_calc_pct / 100 +
  8079. st->min_width_calc_px :
  8080. css_size(st->min_width_kind, st->min_width, cbw);
  8081. int min_box = st->box_sizing ? mw : mw + deco_w;
  8082. if (content_w + deco_w < min_box) {
  8083. content_w = min_box - deco_w;
  8084. definite_w = 1;
  8085. }
  8086. }
  8087. if (content_w < 8)
  8088. content_w = 8;
  8089. if (definite_w) {
  8090. int free_w = cbw - ml - mr - deco_w - content_w;
  8091. if (free_w < 0)
  8092. free_w = 0;
  8093. if (st->ml_auto && st->mr_auto) {
  8094. ml = free_w / 2;
  8095. mr = free_w - ml;
  8096. } else if (st->ml_auto) {
  8097. ml = free_w;
  8098. } else if (st->mr_auto) {
  8099. mr = free_w;
  8100. }
  8101. }
  8102. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8103. int iw, ih;
  8104. image_block_size(node, st, cbw, &iw, &ih);
  8105. content_w = iw;
  8106. img_dh = ih;
  8107. }
  8108. l0 = old_left + ml;
  8109. r0 = l0 + deco_w + content_w;
  8110. if (r0 < l0 + 8)
  8111. r0 = l0 + 8;
  8112. normal_top = top;
  8113. if (sticky) {
  8114. if (st->top_set) {
  8115. int stick = page_rect.y + 4 + st->top;
  8116. if (normal_top < stick)
  8117. rel_dy += stick - normal_top;
  8118. } else if (st->bottom_set && block_h[node]) {
  8119. int stick = page_rect.y + page_rect.h - st->bottom -
  8120. block_h[node];
  8121. if (normal_top > stick)
  8122. rel_dy += stick - normal_top;
  8123. }
  8124. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  8125. block_h[doc.nodes[node].parent]) {
  8126. unsigned int p = doc.nodes[node].parent;
  8127. int ptop = l->parent_top;
  8128. int pbottom = ptop + block_h[p];
  8129. int eh = block_h[node];
  8130. int moved_top = normal_top + rel_dy;
  8131. int moved_bottom = moved_top + eh;
  8132. if (moved_bottom > pbottom)
  8133. rel_dy -= moved_bottom - pbottom;
  8134. moved_top = normal_top + rel_dy;
  8135. if (moved_top < ptop)
  8136. rel_dy += ptop - moved_top;
  8137. }
  8138. }
  8139. if (shifted && l->draw) {
  8140. top += rel_dy;
  8141. l0 += rel_dx;
  8142. r0 += rel_dx;
  8143. }
  8144. l->parent_top = top;
  8145. if (st->pos != 0) {
  8146. /* Positioned boxes establish the containing block for their
  8147. * absolutely positioned descendants. */
  8148. l->cb_left = l0;
  8149. l->cb_right = r0;
  8150. l->cb_top = top;
  8151. }
  8152. if (l->draw && block_h[node] &&
  8153. top < page_rect.y + page_rect.h &&
  8154. top + block_h[node] > page_rect.y) {
  8155. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  8156. int rtl = css_radius(st, 0, box.w, box.h);
  8157. int rtr = css_radius(st, 1, box.w, box.h);
  8158. int rbr = css_radius(st, 2, box.w, box.h);
  8159. int rbl = css_radius(st, 3, box.w, box.h);
  8160. if (st->transform_scale) {
  8161. if (st->has_bg)
  8162. fill_transformed_rect(l->ui, box, st->bg, st);
  8163. } else if (rtl || rtr || rbr || rbl) {
  8164. if (st->has_bg) {
  8165. int bw = st->border_w[0];
  8166. if (bw > 0 && !st->border_t[0] &&
  8167. st->border_c[0] != st->bg &&
  8168. box.w > bw * 2 && box.h > bw * 2) {
  8169. struct ngui_rect inner = {
  8170. box.x + bw, box.y + bw,
  8171. box.w - bw * 2, box.h - bw * 2
  8172. };
  8173. int itl = rtl > bw ? rtl - bw : 0;
  8174. int itr = rtr > bw ? rtr - bw : 0;
  8175. int ibr = rbr > bw ? rbr - bw : 0;
  8176. int ibl = rbl > bw ? rbl - bw : 0;
  8177. ngui_fill_round_rect(l->ui, box, rtl,
  8178. rtr, rbr, rbl,
  8179. st->border_c[0]);
  8180. ngui_fill_round_rect(l->ui, inner,
  8181. itl, itr, ibr,
  8182. ibl, st->bg);
  8183. } else {
  8184. ngui_fill_round_rect(l->ui, box, rtl,
  8185. rtr, rbr, rbl,
  8186. st->bg);
  8187. }
  8188. } else if (st->border_w[0] && !st->border_t[0]) {
  8189. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  8190. rbl, st->border_w[0],
  8191. st->border_c[0]);
  8192. }
  8193. /* Rounded boxes paint their background image too
  8194. * (app icons are rounded squares), kept inside the
  8195. * corner arcs. */
  8196. if (st->bg_image)
  8197. draw_bg_image_round(l, box, node, st, rtl, rtr,
  8198. rbr, rbl);
  8199. } else {
  8200. if (st->has_bg)
  8201. ngui_fill_rect(l->ui, box, st->bg);
  8202. if (st->bg_image)
  8203. draw_bg_image(l, box, node, st);
  8204. if (st->border_w[0] || st->border_w[1] ||
  8205. st->border_w[2] || st->border_w[3])
  8206. draw_border_box(l->ui, box, st);
  8207. }
  8208. }
  8209. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  8210. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  8211. content_w, img_dh);
  8212. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  8213. l->ui && l->ui->nclip < 4) {
  8214. clip_rect.x = l0 + bl;
  8215. clip_rect.y = top + bt;
  8216. clip_rect.w = (r0 - l0) - bl - br;
  8217. clip_rect.h = (int)block_h[node] - bt - bb;
  8218. if (clip_rect.w > 0 && clip_rect.h > 0) {
  8219. ngui_push_clip(l->ui, clip_rect);
  8220. clip_pushed = 1;
  8221. }
  8222. }
  8223. l->left = l0 + bl + pl;
  8224. l->right = l->left + content_w;
  8225. if (l->right < l->left + 8)
  8226. l->right = l->left + 8;
  8227. l->align = st->align;
  8228. l->line_left = l->left;
  8229. l->line_right = l->right;
  8230. l->y = top + bt + pt;
  8231. if (doc.nodes[node].tag == BR_TAG_HR) {
  8232. if (l->draw)
  8233. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  8234. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  8235. l->y += 8;
  8236. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  8237. int vw = l->right - l->left;
  8238. int vh;
  8239. if (doc.nodes[node].width_pct)
  8240. vw = vw * doc.nodes[node].width_attr / 100;
  8241. else if (doc.nodes[node].width_attr)
  8242. vw = doc.nodes[node].width_attr;
  8243. if (vw > l->right - l->left)
  8244. vw = l->right - l->left;
  8245. if (vw < 8)
  8246. vw = 8;
  8247. vh = vw * 9 / 16;
  8248. if (vh > 240)
  8249. vh = 240;
  8250. if (vh < 80)
  8251. vh = 80;
  8252. if (l->draw) {
  8253. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  8254. vw, vh}, 0xD69A);
  8255. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  8256. vw, vh}, 0x8410);
  8257. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  8258. 0x4208);
  8259. }
  8260. l->y += vh + 4;
  8261. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  8262. int dw, dh, cw = l->right - l->left;
  8263. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  8264. if (l->draw && l->y < page_rect.y + page_rect.h &&
  8265. l->y + dh > page_rect.y)
  8266. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  8267. l->y += dh;
  8268. } else {
  8269. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  8270. !st->no_bullet) {
  8271. char *m = li_marker[node];
  8272. if (!m[0]) {
  8273. unsigned int parent = doc.nodes[node].parent;
  8274. int style = st->list_style;
  8275. int idx = parent ? list_index(parent, node) : 1;
  8276. if (style == BR_LIST_AUTO)
  8277. style = (parent &&
  8278. doc.nodes[parent].tag ==
  8279. BR_TAG_OL) ?
  8280. BR_LIST_DECIMAL : BR_LIST_DISC;
  8281. list_marker_text(m, sizeof(li_marker[node]),
  8282. style, idx);
  8283. }
  8284. if (l->draw && m[0]) {
  8285. int mw = (int)ngui_text_width_ui(l->ui, m);
  8286. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  8287. st->color);
  8288. }
  8289. }
  8290. /* This box's definite content height, for its children's
  8291. * percentage heights. */
  8292. if (doc.nodes[node].tag == BR_TAG_HTML ||
  8293. doc.nodes[node].tag == BR_TAG_BODY)
  8294. l->cb_h = layout_view_h;
  8295. else if (st->height_kind == 1)
  8296. l->cb_h = (int)st->height -
  8297. (st->box_sizing ? deco_h : 0);
  8298. else if (st->height_kind == 2 && parent_cb_h > 0)
  8299. l->cb_h = parent_cb_h * (int)st->height / 100 -
  8300. (st->box_sizing ? deco_h : 0);
  8301. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  8302. l->cb_h = content_w * (int)st->aspect_h /
  8303. (int)st->aspect_w;
  8304. else
  8305. l->cb_h = 0;
  8306. if (l->cb_h < 0)
  8307. l->cb_h = 0;
  8308. if (doc.nodes[node].tag == BR_TAG_TR)
  8309. layout_table_row(l, node, st, depth + 1, link);
  8310. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  8311. table_has_rowspan(node))
  8312. layout_table(l, node, st, depth + 1, link);
  8313. else if (st->grid_auto)
  8314. layout_grid_auto(l, node, st, depth + 1, link);
  8315. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  8316. st->grid_gap > 0)
  8317. layout_grid_children(l, node, st, depth + 1, link);
  8318. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  8319. flex_wants_row(node, st))
  8320. layout_flex_children(l, node, st, depth + 1, link);
  8321. else if (st->display == BR_DISPLAY_FLEX && st->flex_col &&
  8322. st->align_items == 1) {
  8323. /* align-items: center in a column: the items' lines
  8324. * (an app card's icon and label) are centred; a child
  8325. * with its own text-align keeps it. */
  8326. struct br_style cst = *st;
  8327. cst.align = BR_ALIGN_CENTER;
  8328. l->align = BR_ALIGN_CENTER;
  8329. layout_children(l, node, &cst, depth + 1, link);
  8330. } else
  8331. layout_children(l, node, st, depth + 1, link);
  8332. l->cb_h = parent_cb_h;
  8333. }
  8334. flush_line(l);
  8335. if (clip_pushed)
  8336. ngui_pop_clip(l->ui);
  8337. if (l->float_active) {
  8338. if (l->y < l->float_bottom)
  8339. l->y = l->float_bottom;
  8340. l->float_active = 0;
  8341. }
  8342. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8343. content_h = img_dh;
  8344. } else if (st->height_kind == 2 &&
  8345. doc.nodes[node].tag != BR_TAG_HTML &&
  8346. doc.nodes[node].tag != BR_TAG_BODY) {
  8347. /* A percentage of the containing block's definite height, or
  8348. * auto when it has none (it used to resolve against the
  8349. * width). The result is a minimum: without scrollable inner
  8350. * boxes, an app shell's height:100%; overflow:hidden column
  8351. * would otherwise clip everything past the first screen. */
  8352. int auto_h = l->y - (top + bt + pt);
  8353. content_h = parent_cb_h > 0 ?
  8354. parent_cb_h * (int)st->height / 100 -
  8355. (st->box_sizing ? deco_h : 0) : 0;
  8356. if (content_h < auto_h)
  8357. content_h = auto_h;
  8358. } else if (st->height_kind &&
  8359. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8360. doc.nodes[node].tag == BR_TAG_BODY) &&
  8361. st->height_kind == 2)) {
  8362. content_h = style_height_px(st, cbw);
  8363. if (st->box_sizing)
  8364. content_h -= deco_h;
  8365. } else {
  8366. /* Percentage heights on html/body resolve against the
  8367. * viewport, but their content still defines the document
  8368. * scroll height. Treating them as auto avoids collapsing
  8369. * the measured page to the containing block width. */
  8370. content_h = l->y - (top + bt + pt);
  8371. /* aspect-ratio: the preferred height of an auto-height box
  8372. * (Tailwind aspect-video image frames); content can still
  8373. * make it taller, as with min-height: auto. */
  8374. if (st->aspect_w && st->aspect_h && content_w > 0) {
  8375. int ah = content_w * (int)st->aspect_h /
  8376. (int)st->aspect_w;
  8377. if (content_h < ah)
  8378. content_h = ah;
  8379. }
  8380. }
  8381. if (content_h < 0)
  8382. content_h = 0;
  8383. if (st->max_height_kind) {
  8384. int mh = st->max_height_kind == 3 ?
  8385. cbw * st->max_height_calc_pct / 100 +
  8386. st->max_height_calc_px :
  8387. css_size(st->max_height_kind, st->max_height, cbw);
  8388. int max_box = st->box_sizing ? mh : mh + deco_h;
  8389. if (content_h + deco_h > max_box)
  8390. content_h = max_box - deco_h;
  8391. }
  8392. if (st->min_height_kind &&
  8393. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8394. doc.nodes[node].tag == BR_TAG_BODY) &&
  8395. st->min_height_kind == 2)) {
  8396. int mh = st->min_height_kind == 3 ?
  8397. cbw * st->min_height_calc_pct / 100 +
  8398. st->min_height_calc_px :
  8399. css_size(st->min_height_kind, st->min_height, cbw);
  8400. int min_box = st->box_sizing ? mh : mh + deco_h;
  8401. if (content_h + deco_h < min_box)
  8402. content_h = min_box - deco_h;
  8403. }
  8404. if (content_h < 0)
  8405. content_h = 0;
  8406. box_h = deco_h + content_h;
  8407. if (box_h < 0)
  8408. box_h = 0;
  8409. l->y = (shifted ? normal_top : top) + box_h;
  8410. if (node < BR_MAX_NODES) {
  8411. layout_boxes[node].x = l0;
  8412. layout_boxes[node].y = top;
  8413. layout_boxes[node].w = r0 - l0;
  8414. layout_boxes[node].h = box_h;
  8415. layout_boxes[node].valid = r0 > l0;
  8416. }
  8417. l->left = old_left;
  8418. l->right = old_right;
  8419. l->align = old_align;
  8420. l->y += mp_px(st, 2, cbw);
  8421. if (!l->draw) {
  8422. if (box_h > 65535)
  8423. box_h = 65535;
  8424. block_h[node] = (unsigned short)box_h;
  8425. block_top[node] = (unsigned short)(top < 0 ? 0 :
  8426. top > 65535 ? 65535 : top);
  8427. }
  8428. if (positioned) {
  8429. l->y = flow_y;
  8430. l->left = flow_left;
  8431. l->right = flow_right;
  8432. }
  8433. l->parent_top = saved_parent_top;
  8434. l->cb_left = saved_cb_left;
  8435. l->cb_right = saved_cb_right;
  8436. l->cb_top = saved_cb_top;
  8437. }
  8438. static int text_node_blank(const struct br_node *nd)
  8439. {
  8440. const char *t = doc.text + nd->text_off;
  8441. unsigned int i;
  8442. for (i = 0; i < nd->text_len; i++)
  8443. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  8444. t[i] != '\r')
  8445. return 0;
  8446. return 1;
  8447. }
  8448. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  8449. * text/image widths in the subtree, plus padding and margins. This keeps
  8450. * Bootstrap's floated nav items on one line instead of giving each the whole
  8451. * row. */
  8452. static int text_space(char c)
  8453. {
  8454. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  8455. }
  8456. static int intrinsic_width(struct ngui *ui, unsigned int node,
  8457. const struct br_style *pst, int depth, int base)
  8458. {
  8459. unsigned int c;
  8460. int line_w = 0, max_w = 0;
  8461. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  8462. if (depth > 32)
  8463. return 0;
  8464. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8465. struct br_node *nd = &doc.nodes[c];
  8466. struct br_style cs;
  8467. if (nd->type == BR_NODE_TEXT) {
  8468. const char *t = doc.text + nd->text_off;
  8469. unsigned int tn = nd->text_len;
  8470. if (doc.nodes[node].tag == BR_TAG_PRE) {
  8471. line_w += (int)face_text_width(ui, pst, t, tn);
  8472. } else {
  8473. unsigned int ti = 0;
  8474. int first = 1;
  8475. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  8476. int sp = (int)face_text_width(ui, pst, " ", 1);
  8477. while (ti < tn) {
  8478. unsigned int ts;
  8479. while (ti < tn && text_space(t[ti]))
  8480. ti++;
  8481. ts = ti;
  8482. while (ti < tn && !text_space(t[ti]))
  8483. ti++;
  8484. if (ti == ts)
  8485. break;
  8486. if (!first || lead)
  8487. line_w += sp;
  8488. lead = 0;
  8489. line_w += (int)face_text_width(ui, pst,
  8490. t + ts, ti - ts);
  8491. first = 0;
  8492. }
  8493. }
  8494. continue;
  8495. }
  8496. br_style_for(&doc, c, pst, &cs);
  8497. if (cs.display == BR_DISPLAY_NONE)
  8498. continue;
  8499. if (nd->tag == BR_TAG_BR) {
  8500. if (line_w > max_w)
  8501. max_w = line_w;
  8502. line_w = 0;
  8503. continue;
  8504. }
  8505. if (nd->tag == BR_TAG_IMG) {
  8506. /* Measure the image as layout will draw it: a CSS or
  8507. * attribute height keeps the intrinsic aspect ratio, and
  8508. * a CSS width overrides the native pixel width. Bootstrap
  8509. * sizes the Cloudron logo with height:40px only. */
  8510. int idx = nd->img_index;
  8511. int iw = 0, ih = 0;
  8512. if (idx >= 0 && idx < image_count &&
  8513. images[idx].state == 1) {
  8514. iw = (int)images[idx].native_w;
  8515. ih = (int)images[idx].native_h;
  8516. if (iw <= 0 || ih <= 0) {
  8517. iw = (int)images[idx].img.w;
  8518. ih = (int)images[idx].img.h;
  8519. }
  8520. }
  8521. if (cs.width_kind) {
  8522. int ww = style_width_px(&cs, base);
  8523. line_w += ww > 0 ? ww : 64;
  8524. } else if (nd->width_attr) {
  8525. line_w += nd->width_attr;
  8526. } else if (nd->height_attr && iw && ih) {
  8527. line_w += iw * (int)nd->height_attr / ih;
  8528. } else if (cs.height_kind && iw && ih) {
  8529. int hh = style_height_px(&cs, base);
  8530. line_w += hh > 0 ? iw * hh / ih : iw;
  8531. } else if (iw) {
  8532. line_w += iw;
  8533. } else {
  8534. line_w += 64;
  8535. }
  8536. continue;
  8537. }
  8538. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  8539. nd->tag == BR_TAG_TEXTAREA) &&
  8540. !s_eq(br_type(&doc, c), "hidden")) {
  8541. /* Form controls are replaced: CSS width applies even
  8542. * when they are inline (add_form_run's sizes). */
  8543. int fw = cs.width_kind ? style_width_px(&cs, base) :
  8544. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  8545. if (s_eq(br_type(&doc, c), "checkbox") ||
  8546. s_eq(br_type(&doc, c), "radio"))
  8547. fw = 16;
  8548. line_w += (fw > 0 ? fw : 120) +
  8549. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  8550. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  8551. continue;
  8552. }
  8553. if (nd->tag == BR_TAG_SVG) {
  8554. /* A replaced element: its own size, like add_svg_run()
  8555. * (its path children have no width). */
  8556. int sw, sh, sb = cs.width_kind ?
  8557. style_width_px(&cs, base) : base;
  8558. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  8559. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  8560. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  8561. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8562. line_w += sw;
  8563. } else {
  8564. if (line_w > max_w)
  8565. max_w = line_w;
  8566. line_w = 0;
  8567. if (sw > max_w)
  8568. max_w = sw;
  8569. }
  8570. continue;
  8571. }
  8572. {
  8573. int cw = mp_px(&cs, 7, base) +
  8574. mp_px(&cs, 5, base) +
  8575. mp_px(&cs, 3, base) +
  8576. mp_px(&cs, 1, base) +
  8577. cs.border_w[1] + cs.border_w[3];
  8578. /* width/height do not apply to non-replaced inline
  8579. * boxes. The tagesschau home label is an inline span
  8580. * with width:1px for the mobile icon-only header; using
  8581. * that width made the whole subnav collapse to a
  8582. * one-character column. */
  8583. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  8584. cw += cs.width_kind == 1 ? cs.width :
  8585. style_width_px(&cs, base);
  8586. else
  8587. cw += intrinsic_width(ui, c, &cs, depth + 1,
  8588. base);
  8589. if (flex_row || cs.float_left ||
  8590. cs.display == BR_DISPLAY_INLINE ||
  8591. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8592. line_w += cw;
  8593. } else {
  8594. if (line_w > max_w)
  8595. max_w = line_w;
  8596. line_w = 0;
  8597. if (cw > max_w)
  8598. max_w = cw;
  8599. }
  8600. }
  8601. if (line_w > 4096 || max_w > 4096)
  8602. break;
  8603. }
  8604. return line_w > max_w ? line_w : max_w;
  8605. }
  8606. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  8607. * the main user: .row > .col-md-* with float:left and a percentage width.
  8608. * Each column is laid out with its own left/right edge and the row advances
  8609. * to the tallest column. Returns the first child not consumed. */
  8610. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  8611. const struct br_style *pst, int depth,
  8612. unsigned short link)
  8613. {
  8614. unsigned int n = first;
  8615. int row_left = l->left, row_right = l->right;
  8616. int row_top, row_bottom, xl, xr, any = 0;
  8617. int fl_left = row_left, fl_right = row_right, fl_bottom;
  8618. flush_line(l);
  8619. row_top = l->y;
  8620. row_bottom = l->y;
  8621. fl_bottom = row_top;
  8622. xl = row_left;
  8623. xr = row_right;
  8624. while (n) {
  8625. struct br_node *nd = &doc.nodes[n];
  8626. struct br_style cs;
  8627. unsigned short lk = link;
  8628. int colw, right;
  8629. if (nd->type == BR_NODE_TEXT) {
  8630. if (text_node_blank(nd)) {
  8631. n = nd->next;
  8632. continue;
  8633. }
  8634. break;
  8635. }
  8636. br_style_for(&doc, n, pst, &cs);
  8637. if (cs.display == BR_DISPLAY_NONE) {
  8638. n = nd->next;
  8639. continue;
  8640. }
  8641. /* A float blockifies its box: Bootstrap floats inline
  8642. * anchors too (the navbar brand and its text links), and
  8643. * their padding must be honoured. */
  8644. if (!cs.float_left)
  8645. break;
  8646. if (nd->tag == BR_TAG_A && nd->href_off)
  8647. lk = (unsigned short)n;
  8648. right = cs.float_left == 2;
  8649. if (cs.width_kind == 2 || cs.width_kind == 3) {
  8650. colw = style_width_px(&cs, row_right - row_left);
  8651. } else if (cs.width_kind == 1) {
  8652. colw = (int)cs.width;
  8653. } else {
  8654. int base = row_right - row_left;
  8655. /* Shrink-to-fit outer width: borders too (Google's
  8656. * 1px-bordered "Anmelden" pill wrapped otherwise). */
  8657. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  8658. mp_px(&cs, 7, base) +
  8659. mp_px(&cs, 5, base) +
  8660. mp_px(&cs, 3, base) +
  8661. mp_px(&cs, 1, base) +
  8662. cs.border_w[1] + cs.border_w[3];
  8663. if (colw < 8)
  8664. colw = 8;
  8665. }
  8666. if (colw < 8)
  8667. colw = 8;
  8668. if (colw > row_right - row_left)
  8669. colw = row_right - row_left;
  8670. /* The float column width is already resolved. */
  8671. cs.width_kind = 0;
  8672. cs.max_width_kind = 0;
  8673. if (right) {
  8674. if (any && xr - colw < xl) {
  8675. row_top = row_bottom;
  8676. row_bottom = row_top;
  8677. xl = row_left;
  8678. xr = row_right;
  8679. }
  8680. if (xr - colw < xl)
  8681. colw = xr - xl;
  8682. if (colw < 8)
  8683. colw = 8;
  8684. l->left = xr - colw;
  8685. if (l->left < row_left)
  8686. l->left = row_left;
  8687. l->right = xr;
  8688. xr = l->left;
  8689. if (xr < fl_right)
  8690. fl_right = xr;
  8691. } else {
  8692. if (any && xl + colw > xr) {
  8693. row_top = row_bottom;
  8694. row_bottom = row_top;
  8695. xl = row_left;
  8696. xr = row_right;
  8697. }
  8698. l->left = xl;
  8699. l->right = xl + colw;
  8700. xl += colw;
  8701. if (xl > fl_left)
  8702. fl_left = xl;
  8703. }
  8704. if (l->right < l->left + 8)
  8705. l->right = l->left + 8;
  8706. l->y = row_top;
  8707. l->line_x = l->left;
  8708. l->run_x = l->left;
  8709. l->line_y = l->y;
  8710. l->line_h = 0;
  8711. l->nruns = 0;
  8712. l->space_pending = 0;
  8713. l->align = cs.align;
  8714. layout_block(l, n, &cs, depth + 1, lk);
  8715. if (l->y > row_bottom)
  8716. row_bottom = l->y;
  8717. if (l->y > fl_bottom)
  8718. fl_bottom = l->y;
  8719. any = 1;
  8720. n = nd->next;
  8721. }
  8722. l->left = row_left;
  8723. l->right = row_right;
  8724. if (n && any) {
  8725. struct br_node *nd = &doc.nodes[n];
  8726. int inline_next = 0;
  8727. if (nd->type == BR_NODE_TEXT) {
  8728. inline_next = 1;
  8729. } else if (nd->type == BR_NODE_ELEM) {
  8730. struct br_style cs;
  8731. br_style_for(&doc, n, pst, &cs);
  8732. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  8733. cs.display != BR_DISPLAY_NONE &&
  8734. !br_tag_is_block(nd->tag);
  8735. }
  8736. if (inline_next) {
  8737. if (l->float_active) {
  8738. if (l->float_left > fl_left)
  8739. fl_left = l->float_left;
  8740. if (l->float_right < fl_right)
  8741. fl_right = l->float_right;
  8742. if (l->float_bottom > fl_bottom)
  8743. fl_bottom = l->float_bottom;
  8744. }
  8745. l->float_active = 1;
  8746. l->float_left = fl_left;
  8747. l->float_right = fl_right;
  8748. l->float_bottom = fl_bottom;
  8749. l->y = row_top;
  8750. } else {
  8751. l->float_active = 0;
  8752. l->y = row_bottom;
  8753. }
  8754. } else {
  8755. l->float_active = 0;
  8756. l->y = row_bottom;
  8757. }
  8758. l->line_x = l->left;
  8759. l->run_x = l->left;
  8760. l->line_left = l->left;
  8761. l->line_right = l->right;
  8762. l->line_y = l->y;
  8763. l->line_h = 0;
  8764. l->nruns = 0;
  8765. l->space_pending = 0;
  8766. return n;
  8767. }
  8768. static int flex_item_width(struct lay *l, unsigned int n,
  8769. const struct br_style *cs, int avail)
  8770. {
  8771. struct br_node *nd = &doc.nodes[n];
  8772. (void)l;
  8773. int w;
  8774. if (cs->width_kind == 2 || cs->width_kind == 3)
  8775. w = style_width_px(cs, avail);
  8776. else if (cs->width_kind == 1)
  8777. w = (int)cs->width;
  8778. else if (nd->tag == BR_TAG_IMG) {
  8779. int idx = nd->img_index;
  8780. if (idx >= 0 && idx < image_count &&
  8781. images[idx].state == 1)
  8782. w = (int)images[idx].img.w;
  8783. else if (nd->width_attr)
  8784. w = (int)nd->width_attr;
  8785. else
  8786. w = 64;
  8787. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  8788. nd->tag == BR_TAG_TEXTAREA) {
  8789. /* A control has no content to measure: its default size
  8790. * (a search field in a filter bar). */
  8791. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  8792. } else {
  8793. w = intrinsic_width(l->ui, n, cs, 0, avail);
  8794. }
  8795. /* Explicit widths are content-box sizes; the flex item's outer width
  8796. * must include padding, borders and margins. */
  8797. w += mp_px(cs, 7, avail);
  8798. w += mp_px(cs, 5, avail);
  8799. w += mp_px(cs, 3, avail);
  8800. w += mp_px(cs, 1, avail);
  8801. w += cs->border_w[1] + cs->border_w[3];
  8802. if (w < 24)
  8803. w = 24;
  8804. if (w > avail)
  8805. w = avail;
  8806. return w;
  8807. }
  8808. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  8809. int depth);
  8810. /* An inline child of a text-only inline-block: the same test minus the
  8811. * display check (an inline <span> may have padding/background in CSS, but
  8812. * the inline path paints those for spans anyway). */
  8813. static int inline_block_flows_inline(unsigned int node,
  8814. const struct br_style *cs, int depth)
  8815. {
  8816. unsigned int c;
  8817. if (depth > 3 || cs->pos)
  8818. return 0;
  8819. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8820. const struct br_node *nd = &doc.nodes[c];
  8821. struct br_style ch;
  8822. if (nd->type != BR_NODE_ELEM)
  8823. continue;
  8824. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  8825. br_tag_is_block(nd->tag))
  8826. return 0;
  8827. br_style_for(&doc, c, cs, &ch);
  8828. if (ch.display == BR_DISPLAY_NONE)
  8829. continue;
  8830. if (ch.display != BR_DISPLAY_INLINE ||
  8831. !inline_block_flows_inline(c, &ch, depth + 1))
  8832. return 0;
  8833. }
  8834. return 1;
  8835. }
  8836. /* An inline-block that is only text in a line (a <time> in a byline, a
  8837. * label) with no box of its own -- no size, background, border or padding
  8838. * -- lays out exactly like an inline element, so it stays in the text line
  8839. * instead of ending it. Boxes with any of those keep the row path. */
  8840. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  8841. int depth)
  8842. {
  8843. unsigned int c;
  8844. int i;
  8845. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  8846. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  8847. cs->pos || depth > 3)
  8848. return 0;
  8849. for (i = 0; i < 4; i++)
  8850. if (cs->border_w[i])
  8851. return 0;
  8852. for (i = 4; i < 8; i++)
  8853. if (mp_px(cs, i, 0) > 0)
  8854. return 0;
  8855. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8856. const struct br_node *nd = &doc.nodes[c];
  8857. struct br_style ch;
  8858. if (nd->type != BR_NODE_ELEM)
  8859. continue;
  8860. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  8861. br_tag_is_block(nd->tag))
  8862. return 0;
  8863. br_style_for(&doc, c, cs, &ch);
  8864. if (ch.display == BR_DISPLAY_NONE)
  8865. continue;
  8866. if (ch.display != BR_DISPLAY_INLINE ||
  8867. !inline_block_flows_inline(c, &ch, depth + 1))
  8868. return 0;
  8869. }
  8870. return 1;
  8871. }
  8872. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  8873. * on one line, not one full-width block each. Place intrinsic widths from
  8874. * left to right and wrap when the row is full. */
  8875. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  8876. const struct br_style *pst, int depth,
  8877. unsigned short link)
  8878. {
  8879. unsigned int n = first;
  8880. int row_left = l->left, row_right = l->right;
  8881. int avail = row_right - row_left;
  8882. int x = row_left, y = l->y, row_h = 0, any = 0;
  8883. /* Each box sets l->align from its own style; the text after the row
  8884. * must keep the container's (a centred .fa-fw icon centred the menu
  8885. * label that followed it). */
  8886. unsigned char row_align = l->align;
  8887. flush_line(l);
  8888. y = l->y;
  8889. while (n) {
  8890. struct br_node *nd = &doc.nodes[n];
  8891. struct br_style cs;
  8892. unsigned short lk = link;
  8893. int colw, h;
  8894. if (nd->type == BR_NODE_TEXT) {
  8895. if (!text_node_blank(nd))
  8896. break;
  8897. if (any)
  8898. x += 4;
  8899. n = nd->next;
  8900. continue;
  8901. }
  8902. br_style_for(&doc, n, pst, &cs);
  8903. if (cs.display == BR_DISPLAY_NONE) {
  8904. n = nd->next;
  8905. continue;
  8906. }
  8907. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  8908. break;
  8909. if (nd->tag == BR_TAG_A && nd->href_off)
  8910. lk = (unsigned short)n;
  8911. colw = flex_item_width(l, n, &cs, avail);
  8912. /* A few pixels of slack keep a single long token (boot.S)
  8913. * from wrapping at the exact content width. */
  8914. colw += 8;
  8915. if (colw > avail)
  8916. colw = avail;
  8917. cs.width_kind = 0;
  8918. cs.max_width_kind = 0;
  8919. if (any && x + colw > row_right) {
  8920. y += row_h + 2;
  8921. x = row_left;
  8922. row_h = 0;
  8923. any = 0;
  8924. }
  8925. if (any && x > row_left)
  8926. x += 4;
  8927. l->left = x;
  8928. l->right = x + colw;
  8929. if (l->right < l->left + 8)
  8930. l->right = l->left + 8;
  8931. l->y = y;
  8932. l->line_x = l->left;
  8933. l->run_x = l->left;
  8934. l->line_y = l->y;
  8935. l->line_h = 0;
  8936. l->nruns = 0;
  8937. l->space_pending = 0;
  8938. l->align = cs.align;
  8939. layout_block(l, n, &cs, depth + 1, lk);
  8940. h = l->y - y;
  8941. if (h > row_h)
  8942. row_h = h;
  8943. x += colw;
  8944. any = 1;
  8945. n = nd->next;
  8946. }
  8947. if (any)
  8948. y += row_h;
  8949. l->left = row_left;
  8950. l->right = row_right;
  8951. l->align = row_align;
  8952. l->y = y;
  8953. l->line_x = l->left;
  8954. l->run_x = l->left;
  8955. l->line_y = l->y;
  8956. l->line_h = 0;
  8957. l->nruns = 0;
  8958. l->space_pending = 0;
  8959. return n;
  8960. }
  8961. struct flex_item {
  8962. unsigned int node;
  8963. unsigned short link;
  8964. int w;
  8965. };
  8966. static void layout_flex_children(struct lay *l, unsigned int parent,
  8967. const struct br_style *pst, int depth,
  8968. unsigned short link)
  8969. {
  8970. struct flex_item it[32];
  8971. unsigned int c;
  8972. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  8973. int row_left = l->left, row_right = l->right;
  8974. int avail = row_right - row_left;
  8975. int idx, row_top;
  8976. unsigned char row_align = l->align;
  8977. if (avail < 8 || depth > 48) {
  8978. layout_children(l, parent, pst, depth, link);
  8979. return;
  8980. }
  8981. /* If direct text is not just whitespace, normal block flow handles it
  8982. * better than pretending it is a flex item. */
  8983. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  8984. struct br_node *nd = &doc.nodes[c];
  8985. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  8986. layout_children(l, parent, pst, depth, link);
  8987. return;
  8988. }
  8989. }
  8990. for (c = doc.nodes[parent].first;
  8991. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  8992. c = doc.nodes[c].next) {
  8993. struct br_node *nd = &doc.nodes[c];
  8994. struct br_style cs;
  8995. if (nd->type == BR_NODE_TEXT)
  8996. continue;
  8997. br_style_for(&doc, c, pst, &cs);
  8998. if (cs.display == BR_DISPLAY_NONE)
  8999. continue;
  9000. it[nitem].node = c;
  9001. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  9002. (unsigned short)c : link;
  9003. it[nitem].w = 0;
  9004. if (cs.flex_grow && !cs.width_kind)
  9005. grow_count++;
  9006. else
  9007. fixed += flex_item_width(l, c, &cs, avail);
  9008. nitem++;
  9009. }
  9010. /* A narrow container (an icon row sized to its content, Google's
  9011. * mic + lens buttons) is still a row when its items fit; only a
  9012. * narrow one that would overflow or squeeze growing items falls
  9013. * back to block flow. */
  9014. if (avail < 160 && (grow_count || fixed > avail)) {
  9015. layout_children(l, parent, pst, depth, link);
  9016. return;
  9017. }
  9018. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  9019. if (grow_w < 96)
  9020. grow_w = 96;
  9021. for (idx = 0; idx < nitem; idx++) {
  9022. struct br_style cs;
  9023. br_style_for(&doc, it[idx].node, pst, &cs);
  9024. if (cs.flex_grow && !cs.width_kind)
  9025. it[idx].w = grow_w;
  9026. else
  9027. it[idx].w = flex_item_width(l, it[idx].node, &cs, avail);
  9028. if (it[idx].w > avail)
  9029. it[idx].w = avail;
  9030. if (it[idx].w < 8)
  9031. it[idx].w = 8;
  9032. }
  9033. row_top = l->y;
  9034. idx = 0;
  9035. while (idx < nitem) {
  9036. int start = idx, count = 0, row_w = 0;
  9037. int free_w, x, extra = 0, row_h = 0, k;
  9038. while (idx < nitem) {
  9039. int add = it[idx].w + (count ? gap : 0);
  9040. /* CSS default is nowrap; only flex-wrap: wrap (1)
  9041. * starts a new row. */
  9042. if (count && pst->flex_wrap == 1 &&
  9043. row_w + add > avail)
  9044. break;
  9045. row_w += add;
  9046. count++;
  9047. idx++;
  9048. }
  9049. if (!count) {
  9050. count = 1;
  9051. row_w = it[start].w;
  9052. idx = start + 1;
  9053. }
  9054. free_w = avail - row_w;
  9055. if (free_w < 0)
  9056. free_w = 0;
  9057. x = row_left;
  9058. if (pst->justify == 1) {
  9059. x += free_w / 2;
  9060. } else if (pst->justify == 2) {
  9061. x += free_w;
  9062. } else if (pst->justify == 3) {
  9063. extra = count > 1 ? free_w / (count - 1) : 0;
  9064. } else if (pst->justify == 4) {
  9065. extra = count ? free_w / count : 0;
  9066. x += extra / 2;
  9067. } else if (pst->justify == 5) {
  9068. extra = count ? free_w / (count + 1) : 0;
  9069. x += extra;
  9070. }
  9071. for (k = 0; k < count; k++) {
  9072. int node = (int)it[start + k].node;
  9073. int h = block_h[node];
  9074. if (h > row_h)
  9075. row_h = h;
  9076. }
  9077. if (pst->height_kind) {
  9078. int hh = style_height_px(pst, avail);
  9079. if (hh > row_h)
  9080. row_h = hh;
  9081. }
  9082. for (k = 0; k < count; k++) {
  9083. struct br_style cs;
  9084. int node = (int)it[start + k].node;
  9085. int yoff = 0;
  9086. br_style_for(&doc, node, pst, &cs);
  9087. cs.width_kind = 0;
  9088. cs.max_width_kind = 0;
  9089. {
  9090. int ai = cs.align_self ? cs.align_self - 1 :
  9091. pst->align_items;
  9092. if (l->draw && ai && row_h > block_h[node]) {
  9093. if (ai == 1)
  9094. yoff = (row_h -
  9095. block_h[node]) / 2;
  9096. else if (ai == 2)
  9097. yoff = row_h - block_h[node];
  9098. }
  9099. }
  9100. l->left = x;
  9101. l->right = x + it[start + k].w;
  9102. if (l->right < l->left + 8)
  9103. l->right = l->left + 8;
  9104. l->y = row_top + yoff;
  9105. l->line_x = l->left;
  9106. l->run_x = l->left;
  9107. l->line_y = l->y;
  9108. l->line_h = 0;
  9109. l->nruns = 0;
  9110. l->space_pending = 0;
  9111. l->align = cs.align;
  9112. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  9113. if (!l->draw) {
  9114. int h = l->y - row_top;
  9115. if (h > row_h)
  9116. row_h = h;
  9117. }
  9118. x += it[start + k].w;
  9119. if (k + 1 < count)
  9120. x += gap + extra;
  9121. }
  9122. row_top += row_h;
  9123. }
  9124. l->left = row_left;
  9125. l->right = row_right;
  9126. l->align = row_align;
  9127. l->y = row_top;
  9128. l->line_x = l->left;
  9129. l->run_x = l->left;
  9130. l->line_y = l->y;
  9131. l->line_h = 0;
  9132. l->nruns = 0;
  9133. l->space_pending = 0;
  9134. }
  9135. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  9136. * plus the grid-area hints used by site shells (site notice/footer full
  9137. * width, column-start left, page-content right). Anything more elaborate
  9138. * falls back to normal block flow. */
  9139. static int grid_track_width(unsigned char kind, unsigned short val,
  9140. int avail, int other)
  9141. {
  9142. if (kind == 2)
  9143. return avail * (int)val / 100;
  9144. if (kind == 1)
  9145. return val;
  9146. return other;
  9147. }
  9148. static void layout_grid_children(struct lay *l, unsigned int parent,
  9149. const struct br_style *pst, int depth,
  9150. unsigned short link)
  9151. {
  9152. unsigned int n;
  9153. int row_left = l->left, row_right = l->right;
  9154. int avail = row_right - row_left;
  9155. int gap = pst->grid_gap;
  9156. int track_total = avail - gap;
  9157. int col0, col1, x0, x1;
  9158. int row_y, row_bottom, have_left = 0, have_right = 0;
  9159. unsigned int c;
  9160. if (avail < 32 || depth > 48)
  9161. return;
  9162. if (track_total < 16)
  9163. track_total = 16;
  9164. col0 = grid_track_width((unsigned char)(pst->width_kind),
  9165. pst->width, track_total, 0);
  9166. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  9167. pst->max_width, track_total, 0);
  9168. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  9169. int w0 = pst->width ? pst->width : 1;
  9170. int w1 = pst->max_width ? pst->max_width : 1;
  9171. col0 = track_total * w0 / (w0 + w1);
  9172. col1 = track_total - col0;
  9173. } else if (pst->width_kind == 3) {
  9174. col0 = track_total - col1;
  9175. if (col0 < 24)
  9176. col0 = 24;
  9177. } else if (pst->max_width_kind == 3) {
  9178. col1 = track_total - col0;
  9179. if (col1 < 24)
  9180. col1 = 24;
  9181. }
  9182. if (col0 < 24)
  9183. col0 = 24;
  9184. if (col1 < 24)
  9185. col1 = 24;
  9186. if (col0 + col1 > track_total) {
  9187. col1 = track_total - col0;
  9188. if (col1 < 24)
  9189. col1 = 24;
  9190. }
  9191. x0 = row_left;
  9192. x1 = row_left + col0 + gap;
  9193. /* Direct text makes a grid ambiguous; use block flow instead. */
  9194. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9195. struct br_node *nd = &doc.nodes[c];
  9196. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9197. layout_children(l, parent, pst, depth, link);
  9198. return;
  9199. }
  9200. }
  9201. row_y = row_bottom = l->y;
  9202. n = doc.nodes[parent].first;
  9203. while (n) {
  9204. struct br_node *nd = &doc.nodes[n];
  9205. struct br_style cs;
  9206. unsigned short lk = link;
  9207. int slot, x, w;
  9208. if (nd->type == BR_NODE_TEXT) {
  9209. n = nd->next;
  9210. continue;
  9211. }
  9212. br_style_for(&doc, n, pst, &cs);
  9213. if (cs.display == BR_DISPLAY_NONE) {
  9214. n = nd->next;
  9215. continue;
  9216. }
  9217. if (nd->tag == BR_TAG_A && nd->href_off)
  9218. lk = (unsigned short)n;
  9219. slot = cs.grid_slot;
  9220. if (!slot) {
  9221. if (!have_left)
  9222. slot = 2;
  9223. else if (!have_right)
  9224. slot = 3;
  9225. else
  9226. slot = 2;
  9227. }
  9228. if (slot == 1) {
  9229. if (have_left || have_right) {
  9230. row_y = row_bottom;
  9231. have_left = have_right = 0;
  9232. }
  9233. x = row_left;
  9234. w = avail;
  9235. } else if (slot == 2) {
  9236. if (have_left) {
  9237. row_y = row_bottom;
  9238. have_left = have_right = 0;
  9239. }
  9240. x = x0;
  9241. w = col0;
  9242. have_left = 1;
  9243. } else {
  9244. if (have_right) {
  9245. row_y = row_bottom;
  9246. have_left = have_right = 0;
  9247. }
  9248. x = x1;
  9249. w = col1;
  9250. have_right = 1;
  9251. }
  9252. cs.width_kind = 0;
  9253. cs.max_width_kind = 0;
  9254. l->left = x;
  9255. l->right = x + w;
  9256. if (l->right < l->left + 8)
  9257. l->right = l->left + 8;
  9258. l->y = row_y;
  9259. l->line_x = l->left;
  9260. l->run_x = l->left;
  9261. l->line_y = l->y;
  9262. l->line_h = 0;
  9263. l->nruns = 0;
  9264. l->space_pending = 0;
  9265. l->align = cs.align;
  9266. layout_block(l, n, &cs, depth + 1, lk);
  9267. if (l->y > row_bottom)
  9268. row_bottom = l->y;
  9269. n = nd->next;
  9270. }
  9271. l->left = row_left;
  9272. l->right = row_right;
  9273. l->y = row_bottom;
  9274. l->line_x = l->left;
  9275. l->run_x = l->left;
  9276. l->line_y = l->y;
  9277. l->line_h = 0;
  9278. l->nruns = 0;
  9279. l->space_pending = 0;
  9280. }
  9281. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  9282. * capped at four. Used by the project docs' card grids. A fixed
  9283. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  9284. static void layout_grid_auto(struct lay *l, unsigned int parent,
  9285. const struct br_style *pst, int depth,
  9286. unsigned short link)
  9287. {
  9288. unsigned int n, c;
  9289. int row_left = l->left, row_right = l->right;
  9290. int avail = row_right - row_left;
  9291. int gap = pst->grid_gap;
  9292. int minw = pst->width_kind == 1 ? pst->width : 200;
  9293. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  9294. if (avail < 32 || depth > 48) {
  9295. layout_children(l, parent, pst, depth, link);
  9296. return;
  9297. }
  9298. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9299. struct br_node *nd = &doc.nodes[c];
  9300. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9301. layout_children(l, parent, pst, depth, link);
  9302. return;
  9303. }
  9304. }
  9305. if (minw < 80)
  9306. minw = 80;
  9307. ncols = (avail + gap) / (minw + gap);
  9308. if (ncols < 1)
  9309. ncols = 1;
  9310. if (ncols > 4)
  9311. ncols = 4;
  9312. if (pst->grid_auto > BR_GRID_FIXED) {
  9313. /* grid-template-columns: repeat(N, 1fr) */
  9314. ncols = pst->grid_auto - BR_GRID_FIXED;
  9315. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  9316. ncols--;
  9317. }
  9318. colw = (avail - gap * (ncols - 1)) / ncols;
  9319. if (colw < 24)
  9320. colw = 24;
  9321. x = row_left;
  9322. n = doc.nodes[parent].first;
  9323. while (n) {
  9324. struct br_node *nd = &doc.nodes[n];
  9325. struct br_style cs;
  9326. unsigned short lk = link;
  9327. int h;
  9328. if (nd->type == BR_NODE_TEXT) {
  9329. n = nd->next;
  9330. continue;
  9331. }
  9332. br_style_for(&doc, n, pst, &cs);
  9333. if (cs.display == BR_DISPLAY_NONE) {
  9334. n = nd->next;
  9335. continue;
  9336. }
  9337. if (nd->tag == BR_TAG_A && nd->href_off)
  9338. lk = (unsigned short)n;
  9339. cs.width_kind = 0;
  9340. cs.max_width_kind = 0;
  9341. l->left = x;
  9342. l->right = x + colw;
  9343. if (l->right < l->left + 8)
  9344. l->right = l->left + 8;
  9345. l->y = y;
  9346. l->line_x = l->left;
  9347. l->run_x = l->left;
  9348. l->line_y = l->y;
  9349. l->line_h = 0;
  9350. l->nruns = 0;
  9351. l->space_pending = 0;
  9352. l->align = cs.align;
  9353. layout_block(l, n, &cs, depth + 1, lk);
  9354. h = l->y - y;
  9355. if (h > row_h)
  9356. row_h = h;
  9357. col++;
  9358. n = nd->next;
  9359. if (col == ncols) {
  9360. y += row_h + gap;
  9361. x = row_left;
  9362. row_h = 0;
  9363. col = 0;
  9364. } else {
  9365. x += colw + gap;
  9366. }
  9367. }
  9368. if (col)
  9369. y += row_h;
  9370. else if (y > start_y)
  9371. y -= gap;
  9372. l->left = row_left;
  9373. l->right = row_right;
  9374. l->y = y;
  9375. l->line_x = l->left;
  9376. l->run_x = l->left;
  9377. l->line_y = l->y;
  9378. l->line_h = 0;
  9379. l->nruns = 0;
  9380. l->space_pending = 0;
  9381. }
  9382. /* Column widths are the widest cell in each column across every row, so all
  9383. * rows line up. The table model is still deliberately basic: no colspan,
  9384. * border-collapse or percentage columns. */
  9385. static void table_columns(struct lay *l, unsigned int table,
  9386. const struct br_style *pst, int avail,
  9387. int *raw, int maxcols, int *out_cols,
  9388. int *out_total)
  9389. {
  9390. unsigned int r, c;
  9391. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  9392. int fixed[12];
  9393. for (c = 0; c < (unsigned int)maxcols; c++) {
  9394. raw[c] = 0;
  9395. fixed[c] = 0;
  9396. }
  9397. /* Intrinsic widths of single-column cells. */
  9398. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9399. struct br_node *rn = &doc.nodes[r];
  9400. int col = 0;
  9401. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9402. continue;
  9403. for (c = rn->first; c; c = doc.nodes[c].next) {
  9404. struct br_node *cn = &doc.nodes[c];
  9405. struct br_style cs;
  9406. int w, span;
  9407. if (cn->type != BR_NODE_ELEM ||
  9408. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9409. continue;
  9410. span = cn->colspan ? cn->colspan : 1;
  9411. br_style_for(&doc, c, pst, &cs);
  9412. if (cs.display == BR_DISPLAY_NONE)
  9413. continue;
  9414. if (col + span > maxcols)
  9415. span = maxcols - col;
  9416. if (span < 1)
  9417. break;
  9418. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  9419. mp_px(&cs, 7, avail) +
  9420. mp_px(&cs, 5, avail) +
  9421. mp_px(&cs, 3, avail) +
  9422. mp_px(&cs, 1, avail) +
  9423. cs.border_w[0] + cs.border_w[1] +
  9424. cs.border_w[2] + cs.border_w[3];
  9425. if (w < 24)
  9426. w = 24;
  9427. if (span == 1) {
  9428. if (w > raw[col])
  9429. raw[col] = w;
  9430. }
  9431. if (col + span > cols)
  9432. cols = col + span;
  9433. col += span;
  9434. }
  9435. }
  9436. /* A colspan cell only has to be as wide as the sum of its columns. */
  9437. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9438. struct br_node *rn = &doc.nodes[r];
  9439. int col = 0;
  9440. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9441. continue;
  9442. for (c = rn->first; c; c = doc.nodes[c].next) {
  9443. struct br_node *cn = &doc.nodes[c];
  9444. struct br_style cs;
  9445. int span, w, sum, i;
  9446. if (cn->type != BR_NODE_ELEM ||
  9447. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9448. continue;
  9449. span = cn->colspan ? cn->colspan : 1;
  9450. if (col + span > maxcols)
  9451. span = maxcols - col;
  9452. if (span < 1)
  9453. break;
  9454. if (span > 1) {
  9455. br_style_for(&doc, c, pst, &cs);
  9456. if (cs.display != BR_DISPLAY_NONE) {
  9457. w = intrinsic_width(l->ui, c, &cs,
  9458. 0, avail) +
  9459. mp_px(&cs, 7, avail) +
  9460. mp_px(&cs, 5, avail) +
  9461. mp_px(&cs, 3, avail) +
  9462. mp_px(&cs, 1, avail) +
  9463. cs.border_w[0] + cs.border_w[1] +
  9464. cs.border_w[2] + cs.border_w[3];
  9465. sum = 0;
  9466. for (i = 0; i < span; i++)
  9467. sum += raw[col + i];
  9468. if (w > sum)
  9469. raw[col + span - 1] += w - sum;
  9470. }
  9471. }
  9472. col += span;
  9473. }
  9474. }
  9475. /* Explicit and percentage widths override intrinsic widths. */
  9476. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9477. struct br_node *rn = &doc.nodes[r];
  9478. int col = 0;
  9479. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9480. continue;
  9481. for (c = rn->first; c; c = doc.nodes[c].next) {
  9482. struct br_node *cn = &doc.nodes[c];
  9483. struct br_style cs;
  9484. int span;
  9485. if (cn->type != BR_NODE_ELEM ||
  9486. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9487. continue;
  9488. span = cn->colspan ? cn->colspan : 1;
  9489. if (col + span > maxcols)
  9490. span = maxcols - col;
  9491. if (span < 1)
  9492. break;
  9493. if (span == 1) {
  9494. br_style_for(&doc, c, pst, &cs);
  9495. if (cs.display != BR_DISPLAY_NONE) {
  9496. if (cs.width_kind == 1) {
  9497. raw[col] = cs.width;
  9498. fixed[col] = 1;
  9499. } else if (cs.width_kind == 2 ||
  9500. cs.width_kind == 3) {
  9501. raw[col] = style_width_px(&cs,
  9502. avail);
  9503. fixed[col] = 1;
  9504. }
  9505. }
  9506. }
  9507. col += span;
  9508. }
  9509. }
  9510. for (c = 0; c < (unsigned int)cols; c++) {
  9511. if (raw[c] < 8)
  9512. raw[c] = 8;
  9513. total += raw[c];
  9514. if (fixed[c])
  9515. fixed_sum += raw[c];
  9516. else {
  9517. free_raw += raw[c];
  9518. free_cols++;
  9519. }
  9520. }
  9521. if (fixed_sum > 0 && fixed_sum < avail) {
  9522. int free_avail = avail - fixed_sum;
  9523. int i;
  9524. if (free_raw > 0) {
  9525. for (i = 0; i < cols; i++)
  9526. if (!fixed[i])
  9527. raw[i] = free_avail * raw[i] /
  9528. free_raw;
  9529. } else if (free_cols > 0) {
  9530. for (i = 0; i < cols; i++)
  9531. if (!fixed[i])
  9532. raw[i] = free_avail / free_cols;
  9533. }
  9534. total = 0;
  9535. for (i = 0; i < cols; i++)
  9536. total += raw[i];
  9537. } else if (total < avail && total > 0) {
  9538. int i;
  9539. for (i = 0; i < cols; i++)
  9540. raw[i] = raw[i] * avail / total;
  9541. total = 0;
  9542. for (i = 0; i < cols; i++)
  9543. total += raw[i];
  9544. }
  9545. *out_cols = cols;
  9546. *out_total = total;
  9547. }
  9548. static void layout_table_row(struct lay *l, unsigned int row,
  9549. const struct br_style *pst, int depth,
  9550. unsigned short link)
  9551. {
  9552. unsigned int n, cell[12];
  9553. int raw[12], colstart[12], colspan[12];
  9554. int prefix[13];
  9555. int ncell = 0, total = 0, cols = 0, col = 0;
  9556. int row_left = l->left, row_right = l->right;
  9557. int avail = row_right - row_left;
  9558. int y = l->y, bottom = l->y;
  9559. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  9560. struct br_node *nd = &doc.nodes[n];
  9561. struct br_style cs;
  9562. int span;
  9563. if (nd->type == BR_NODE_TEXT) {
  9564. if (text_node_blank(nd))
  9565. continue;
  9566. layout_children(l, row, pst, depth, link);
  9567. return;
  9568. }
  9569. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  9570. layout_children(l, row, pst, depth, link);
  9571. return;
  9572. }
  9573. br_style_for(&doc, n, pst, &cs);
  9574. if (cs.display == BR_DISPLAY_NONE)
  9575. continue;
  9576. if (ncell >= 12) {
  9577. layout_children(l, row, pst, depth, link);
  9578. return;
  9579. }
  9580. span = nd->colspan ? nd->colspan : 1;
  9581. if (span > 12 - col)
  9582. span = 12 - col;
  9583. if (span < 1)
  9584. continue;
  9585. cell[ncell] = n;
  9586. colstart[ncell] = col;
  9587. colspan[ncell] = span;
  9588. col += span;
  9589. ncell++;
  9590. }
  9591. if (ncell < 1 || avail < 32) {
  9592. layout_children(l, row, pst, depth, link);
  9593. return;
  9594. }
  9595. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  9596. &total);
  9597. if (cols < 2 || total <= 0) {
  9598. int c;
  9599. total = 0;
  9600. for (c = 0; c < ncell; c++) {
  9601. struct br_style cs;
  9602. br_style_for(&doc, cell[c], pst, &cs);
  9603. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  9604. avail) +
  9605. mp_px(&cs, 7, avail) +
  9606. mp_px(&cs, 5, avail) +
  9607. mp_px(&cs, 3, avail) +
  9608. mp_px(&cs, 1, avail);
  9609. if (raw[c] < 24)
  9610. raw[c] = 24;
  9611. total += raw[c];
  9612. }
  9613. /* A one-column table still has to fill its own width; the
  9614. * intrinsic fallback above otherwise leaves the cell at its
  9615. * text width (HN's outer table and nested story table). */
  9616. if (total > 0 && total < avail) {
  9617. int c;
  9618. for (c = 0; c < ncell; c++)
  9619. raw[c] = raw[c] * avail / total;
  9620. total = avail;
  9621. }
  9622. }
  9623. prefix[0] = row_left;
  9624. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  9625. prefix[n + 1] = prefix[n] + raw[n];
  9626. for (n = 0; n < (unsigned int)ncell; n++) {
  9627. struct br_style cs;
  9628. int start = colstart[n];
  9629. int end = start + colspan[n];
  9630. int w;
  9631. if (end > cols)
  9632. end = cols;
  9633. if (start >= cols)
  9634. continue;
  9635. w = prefix[end] - prefix[start];
  9636. br_style_for(&doc, cell[n], pst, &cs);
  9637. /* The column width already reflects the cell's width property. */
  9638. cs.width_kind = 0;
  9639. cs.max_width_kind = 0;
  9640. if (w < 24)
  9641. w = 24;
  9642. if (w < 8)
  9643. w = 8;
  9644. l->left = prefix[start];
  9645. l->right = l->left + w;
  9646. l->y = y;
  9647. l->line_x = l->left;
  9648. l->run_x = l->left;
  9649. l->line_y = l->y;
  9650. l->line_h = 0;
  9651. l->nruns = 0;
  9652. l->space_pending = 0;
  9653. l->align = cs.align;
  9654. layout_block(l, cell[n], &cs, depth + 1, link);
  9655. if (l->y > bottom)
  9656. bottom = l->y;
  9657. }
  9658. l->left = row_left;
  9659. l->right = row_right;
  9660. l->y = bottom;
  9661. l->line_x = l->left;
  9662. l->run_x = l->left;
  9663. l->line_y = l->y;
  9664. l->line_h = 0;
  9665. l->nruns = 0;
  9666. l->space_pending = 0;
  9667. }
  9668. #define TBL_MAX_ROWS 32
  9669. #define TBL_MAX_COLS 12
  9670. #define TBL_MAX_CELLS 128
  9671. struct tbl_cell {
  9672. unsigned int node;
  9673. unsigned char row, col, rowspan, colspan;
  9674. int height;
  9675. };
  9676. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  9677. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  9678. static int table_active;
  9679. static int table_has_rowspan(unsigned int table)
  9680. {
  9681. unsigned int r, c;
  9682. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9683. struct br_node *rn = &doc.nodes[r];
  9684. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9685. continue;
  9686. for (c = rn->first; c; c = doc.nodes[c].next) {
  9687. struct br_node *cn = &doc.nodes[c];
  9688. if (cn->type == BR_NODE_ELEM &&
  9689. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  9690. cn->rowspan > 1)
  9691. return 1;
  9692. }
  9693. }
  9694. return 0;
  9695. }
  9696. static void table_cell_style(unsigned int row, unsigned int cell,
  9697. const struct br_style *st, struct br_style *out)
  9698. {
  9699. struct br_style trs;
  9700. br_style_for(&doc, row, st, &trs);
  9701. br_style_for(&doc, cell, &trs, out);
  9702. }
  9703. /* Tables that use rowspan need row heights before anything is painted. This
  9704. * path builds a small occupancy grid, measures the natural cell heights, then
  9705. * lays every cell out at its row/column position. Tables without rowspan
  9706. * keep the lighter per-row path in layout_table_row(). */
  9707. static void layout_table(struct lay *l, unsigned int table,
  9708. const struct br_style *st, int depth,
  9709. unsigned short link)
  9710. {
  9711. unsigned int rows[TBL_MAX_ROWS];
  9712. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  9713. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  9714. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  9715. int free_raw = 0, free_cols = 0;
  9716. int table_left = l->left, table_right = l->right;
  9717. int top = l->y, avail = table_right - table_left;
  9718. unsigned int r, c;
  9719. int i, rr, cc;
  9720. if (depth > 48 || table_active) {
  9721. layout_children(l, table, st, depth, link);
  9722. return;
  9723. }
  9724. table_active = 1;
  9725. for (r = doc.nodes[table].first;
  9726. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  9727. struct br_node *rn = &doc.nodes[r];
  9728. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  9729. rows[nrows++] = r;
  9730. }
  9731. if (!nrows) {
  9732. table_active = 0;
  9733. layout_children(l, table, st, depth, link);
  9734. return;
  9735. }
  9736. for (rr = 0; rr < nrows; rr++)
  9737. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  9738. tbl_at[rr][cc] = 0;
  9739. for (rr = 0; rr < nrows; rr++) {
  9740. int col = 0;
  9741. for (c = doc.nodes[rows[rr]].first; c;
  9742. c = doc.nodes[c].next) {
  9743. struct br_node *cn = &doc.nodes[c];
  9744. struct br_style cs;
  9745. int rs, csn;
  9746. if (cn->type != BR_NODE_ELEM ||
  9747. (cn->tag != BR_TAG_TD &&
  9748. cn->tag != BR_TAG_TH))
  9749. continue;
  9750. table_cell_style(rows[rr], c, st, &cs);
  9751. if (cs.display == BR_DISPLAY_NONE)
  9752. continue;
  9753. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  9754. col++;
  9755. if (col >= TBL_MAX_COLS)
  9756. break;
  9757. rs = cn->rowspan ? cn->rowspan : 1;
  9758. csn = cn->colspan ? cn->colspan : 1;
  9759. if (rr + rs > nrows)
  9760. rs = nrows - rr;
  9761. if (col + csn > TBL_MAX_COLS)
  9762. csn = TBL_MAX_COLS - col;
  9763. if (rs < 1 || csn < 1)
  9764. continue;
  9765. if (ncells >= TBL_MAX_CELLS)
  9766. break;
  9767. tbl_cells[ncells].node = c;
  9768. tbl_cells[ncells].row = (unsigned char)rr;
  9769. tbl_cells[ncells].col = (unsigned char)col;
  9770. tbl_cells[ncells].rowspan = (unsigned char)rs;
  9771. tbl_cells[ncells].colspan = (unsigned char)csn;
  9772. tbl_cells[ncells].height = 0;
  9773. for (i = rr; i < rr + rs; i++)
  9774. for (int j = col; j < col + csn; j++)
  9775. tbl_at[i][j] =
  9776. (unsigned short)(ncells + 1);
  9777. ncells++;
  9778. col += csn;
  9779. if (col > cols)
  9780. cols = col;
  9781. }
  9782. }
  9783. if (!ncells || cols < 1) {
  9784. table_active = 0;
  9785. layout_children(l, table, st, depth, link);
  9786. return;
  9787. }
  9788. for (i = 0; i < cols; i++) {
  9789. raw[i] = 0;
  9790. fixed[i] = 0;
  9791. }
  9792. /* Intrinsic widths of single-column cells. */
  9793. for (i = 0; i < ncells; i++) {
  9794. struct br_style cs;
  9795. int w;
  9796. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  9797. st, &cs);
  9798. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  9799. mp_px(&cs, 7, avail) +
  9800. mp_px(&cs, 5, avail) +
  9801. mp_px(&cs, 3, avail) +
  9802. mp_px(&cs, 1, avail) +
  9803. cs.border_w[0] + cs.border_w[1] +
  9804. cs.border_w[2] + cs.border_w[3];
  9805. if (w < 24)
  9806. w = 24;
  9807. if (tbl_cells[i].colspan == 1) {
  9808. int col = tbl_cells[i].col;
  9809. if (w > raw[col])
  9810. raw[col] = w;
  9811. }
  9812. }
  9813. /* A spanning cell only needs the sum of its columns to be large
  9814. * enough; put the deficit in the last column. */
  9815. for (i = 0; i < ncells; i++) {
  9816. struct br_style cs;
  9817. int w, sum, col, span;
  9818. if (tbl_cells[i].colspan < 2)
  9819. continue;
  9820. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  9821. st, &cs);
  9822. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  9823. mp_px(&cs, 7, avail) +
  9824. mp_px(&cs, 5, avail) +
  9825. mp_px(&cs, 3, avail) +
  9826. mp_px(&cs, 1, avail) +
  9827. cs.border_w[0] + cs.border_w[1] +
  9828. cs.border_w[2] + cs.border_w[3];
  9829. col = tbl_cells[i].col;
  9830. span = tbl_cells[i].colspan;
  9831. sum = 0;
  9832. for (int j = 0; j < span; j++)
  9833. sum += raw[col + j];
  9834. if (w > sum)
  9835. raw[col + span - 1] += w - sum;
  9836. }
  9837. /* Explicit/percentage widths, as in table_columns(). */
  9838. for (i = 0; i < ncells; i++) {
  9839. struct br_style cs;
  9840. int col;
  9841. if (tbl_cells[i].colspan != 1)
  9842. continue;
  9843. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  9844. st, &cs);
  9845. col = tbl_cells[i].col;
  9846. if (cs.width_kind == 1) {
  9847. raw[col] = cs.width;
  9848. fixed[col] = 1;
  9849. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  9850. raw[col] = style_width_px(&cs, avail);
  9851. fixed[col] = 1;
  9852. }
  9853. }
  9854. for (i = 0; i < cols; i++) {
  9855. if (raw[i] < 8)
  9856. raw[i] = 8;
  9857. total += raw[i];
  9858. if (fixed[i])
  9859. fixed_sum += raw[i];
  9860. else {
  9861. free_raw += raw[i];
  9862. free_cols++;
  9863. }
  9864. }
  9865. if (fixed_sum > 0 && fixed_sum < avail) {
  9866. int free_avail = avail - fixed_sum;
  9867. if (free_raw > 0) {
  9868. for (i = 0; i < cols; i++)
  9869. if (!fixed[i])
  9870. raw[i] = free_avail * raw[i] /
  9871. free_raw;
  9872. } else if (free_cols > 0) {
  9873. for (i = 0; i < cols; i++)
  9874. if (!fixed[i])
  9875. raw[i] = free_avail / free_cols;
  9876. }
  9877. } else if (total < avail && total > 0) {
  9878. for (i = 0; i < cols; i++)
  9879. raw[i] = raw[i] * avail / total;
  9880. }
  9881. prefix[0] = table_left;
  9882. for (i = 0; i < cols; i++)
  9883. prefix[i + 1] = prefix[i] + raw[i];
  9884. /* Measure natural cell heights with the column widths. */
  9885. for (i = 0; i < ncells; i++) {
  9886. struct br_style cs;
  9887. int col = tbl_cells[i].col;
  9888. int span = tbl_cells[i].colspan;
  9889. int w = prefix[col + span] - prefix[col];
  9890. int sl = l->left, sr = l->right, sy = l->y;
  9891. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  9892. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  9893. int sal = l->align, sdraw = l->draw;
  9894. struct ngui *sui = l->ui;
  9895. if (w < 8)
  9896. w = 8;
  9897. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  9898. st, &cs);
  9899. cs.width_kind = 0;
  9900. cs.max_width_kind = 0;
  9901. l->draw = 0;
  9902. l->ui = 0;
  9903. l->left = prefix[col];
  9904. l->right = l->left + w;
  9905. l->y = 0;
  9906. l->line_x = l->left;
  9907. l->run_x = l->left;
  9908. l->line_y = 0;
  9909. l->line_h = 0;
  9910. l->nruns = 0;
  9911. l->space_pending = 0;
  9912. l->align = cs.align;
  9913. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  9914. tbl_cells[i].height = block_h[tbl_cells[i].node];
  9915. l->left = sl;
  9916. l->right = sr;
  9917. l->y = sy;
  9918. l->line_x = slx;
  9919. l->run_x = srx;
  9920. l->line_y = sly;
  9921. l->line_h = slh;
  9922. l->nruns = snr;
  9923. l->space_pending = ssp;
  9924. l->align = sal;
  9925. l->draw = sdraw;
  9926. l->ui = sui;
  9927. }
  9928. for (i = 0; i < nrows; i++)
  9929. rowh[i] = 0;
  9930. for (i = 0; i < ncells; i++) {
  9931. int row = tbl_cells[i].row;
  9932. if (tbl_cells[i].rowspan == 1) {
  9933. if (tbl_cells[i].height > rowh[row])
  9934. rowh[row] = tbl_cells[i].height;
  9935. }
  9936. }
  9937. for (i = 0; i < ncells; i++) {
  9938. int row = tbl_cells[i].row;
  9939. int span = tbl_cells[i].rowspan;
  9940. int sum = 0;
  9941. if (span < 2)
  9942. continue;
  9943. for (int j = 0; j < span; j++)
  9944. sum += rowh[row + j];
  9945. if (sum < tbl_cells[i].height)
  9946. rowh[row + span - 1] +=
  9947. tbl_cells[i].height - sum;
  9948. }
  9949. for (i = 0; i < nrows; i++)
  9950. if (rowh[i] < 8)
  9951. rowh[i] = 8;
  9952. rowy[0] = top;
  9953. for (i = 1; i < nrows; i++)
  9954. rowy[i] = rowy[i - 1] + rowh[i - 1];
  9955. if (!l->draw) {
  9956. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  9957. table_active = 0;
  9958. return;
  9959. }
  9960. for (i = 0; i < ncells; i++) {
  9961. struct br_style cs;
  9962. int col = tbl_cells[i].col;
  9963. int span = tbl_cells[i].colspan;
  9964. int row = tbl_cells[i].row;
  9965. int rspan = tbl_cells[i].rowspan;
  9966. int w = prefix[col + span] - prefix[col];
  9967. int h = 0;
  9968. int sl = l->left, sr = l->right, sy = l->y;
  9969. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  9970. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  9971. int sal = l->align;
  9972. int deco;
  9973. for (int j = 0; j < rspan; j++)
  9974. h += rowh[row + j];
  9975. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  9976. cs.width_kind = 0;
  9977. cs.max_width_kind = 0;
  9978. cs.box_sizing = 0;
  9979. deco = mp_px(&cs, 4, avail) +
  9980. mp_px(&cs, 6, avail) +
  9981. cs.border_w[0] + cs.border_w[2];
  9982. cs.height_kind = 1;
  9983. cs.height = h > deco ? h - deco : 0;
  9984. /* The block painter reads block_h[] from the measure pass; make
  9985. * the table cell fill its row/rowspan, not just its content. */
  9986. if (h > 0 && h < 65536)
  9987. block_h[tbl_cells[i].node] = (unsigned short)h;
  9988. l->left = prefix[col];
  9989. l->right = l->left + w;
  9990. l->y = rowy[row];
  9991. l->line_x = l->left;
  9992. l->run_x = l->left;
  9993. l->line_y = l->y;
  9994. l->line_h = 0;
  9995. l->nruns = 0;
  9996. l->space_pending = 0;
  9997. l->align = cs.align;
  9998. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  9999. l->left = sl;
  10000. l->right = sr;
  10001. l->y = sy;
  10002. l->line_x = slx;
  10003. l->run_x = srx;
  10004. l->line_y = sly;
  10005. l->line_h = slh;
  10006. l->nruns = snr;
  10007. l->space_pending = ssp;
  10008. l->align = sal;
  10009. }
  10010. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10011. table_active = 0;
  10012. }
  10013. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  10014. * flow so they sit above it, like CSS painting order. Their flow origin is
  10015. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  10016. struct br_deferred {
  10017. unsigned int node;
  10018. int flow_y, flow_left, flow_right;
  10019. int parent_top; /* the parent box top, for sticky clamping */
  10020. unsigned short link;
  10021. signed short z_index;
  10022. unsigned char z_set;
  10023. unsigned int order;
  10024. };
  10025. /* Positioned boxes painted after the flow. News front pages have one or two
  10026. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  10027. * old 16 entries the rest fell back into the flow, so a hero image landed
  10028. * below its padding-top aspect box instead of on top of it. */
  10029. #define BR_MAX_DEFERRED 256
  10030. static struct br_deferred deferred[BR_MAX_DEFERRED];
  10031. static int ndeferred;
  10032. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  10033. * element's line. A block-level pseudo-element gets its own line; its box
  10034. * (margins, padding, background) is not drawn. */
  10035. static void emit_pseudo(struct lay *l, unsigned int node,
  10036. const struct br_style *st, int pe, unsigned short link)
  10037. {
  10038. char buf[160];
  10039. struct br_style ps;
  10040. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  10041. unsigned int i = 0;
  10042. int block, space_w;
  10043. if (!n)
  10044. return;
  10045. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  10046. if (block)
  10047. flush_line(l);
  10048. if (ps.uppercase)
  10049. for (i = 0; i < n; i++)
  10050. if (buf[i] >= 'a' && buf[i] <= 'z')
  10051. buf[i] = (char)(buf[i] - 'a' + 'A');
  10052. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  10053. if (space_w <= 0)
  10054. space_w = 8;
  10055. i = 0;
  10056. while (i < n) {
  10057. char word[28];
  10058. unsigned int k = 0;
  10059. int w;
  10060. if (buf[i] == ' ') {
  10061. l->space_pending = 1;
  10062. i++;
  10063. continue;
  10064. }
  10065. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  10066. word[k++] = buf[i++];
  10067. word[k] = '\0';
  10068. if (l->space_pending &&
  10069. (l->nruns > 0 || l->line_x > l->line_left) &&
  10070. l->line_x + space_w <= l->line_right)
  10071. l->line_x += space_w;
  10072. l->space_pending = 0;
  10073. w = (int)face_text_width(l->ui, &ps, word, k);
  10074. if (l->line_x + w > l->line_right &&
  10075. (l->nruns > 0 || l->line_x > l->line_left))
  10076. flush_line(l);
  10077. add_run(l, 0, 0, &ps, link, word);
  10078. }
  10079. if (block)
  10080. flush_line(l);
  10081. }
  10082. static void layout_children(struct lay *l, unsigned int parent,
  10083. const struct br_style *pst, int depth,
  10084. unsigned short link)
  10085. {
  10086. unsigned int n;
  10087. if (depth > 48)
  10088. return;
  10089. emit_pseudo(l, parent, pst, 1, link);
  10090. n = doc.nodes[parent].first;
  10091. while (n) {
  10092. struct br_node *nd = &doc.nodes[n];
  10093. struct br_style cs;
  10094. unsigned short lk = link;
  10095. if (nd->type == BR_NODE_TEXT) {
  10096. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  10097. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  10098. n = nd->next;
  10099. continue;
  10100. }
  10101. br_style_for(&doc, n, pst, &cs);
  10102. if (cs.display == BR_DISPLAY_NONE) {
  10103. n = nd->next;
  10104. continue;
  10105. }
  10106. if (cs.clear && l->float_active) {
  10107. flush_line(l);
  10108. if (l->y < l->float_bottom)
  10109. l->y = l->float_bottom;
  10110. l->float_active = 0;
  10111. l->line_x = l->left;
  10112. l->run_x = l->left;
  10113. l->line_left = l->left;
  10114. l->line_right = l->right;
  10115. l->line_y = l->y;
  10116. l->line_h = 0;
  10117. l->nruns = 0;
  10118. l->space_pending = 0;
  10119. }
  10120. if (nd->tag == BR_TAG_A && nd->href_off)
  10121. lk = (unsigned short)n;
  10122. if (cs.pos == 1 || cs.pos == 2 ||
  10123. ((cs.pos == 3 || cs.pos == 4) && cs.z_set)) {
  10124. if ((cs.pos == 3 || cs.pos == 4) && l->draw &&
  10125. ndeferred < BR_MAX_DEFERRED) {
  10126. /* Relative or sticky z-index (a sticky site
  10127. * header): measure and advance the flow without
  10128. * painting, then paint it in the deferred
  10129. * (stacked) pass, above the content after it. */
  10130. int fy = l->y, fl = l->left, fr = l->right;
  10131. int save_draw = l->draw;
  10132. l->draw = 0;
  10133. layout_block(l, n, &cs, depth + 1, lk);
  10134. l->draw = save_draw;
  10135. deferred[ndeferred].node = n;
  10136. deferred[ndeferred].parent_top = l->parent_top;
  10137. deferred[ndeferred].flow_y = fy;
  10138. deferred[ndeferred].flow_left = fl;
  10139. deferred[ndeferred].flow_right = fr;
  10140. deferred[ndeferred].link = lk;
  10141. deferred[ndeferred].z_index = cs.z_index;
  10142. deferred[ndeferred].z_set = cs.z_set;
  10143. deferred[ndeferred].order = (unsigned int)ndeferred;
  10144. ndeferred++;
  10145. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  10146. deferred[ndeferred].node = n;
  10147. deferred[ndeferred].parent_top = l->parent_top;
  10148. deferred[ndeferred].flow_y =
  10149. cs.pos == 1 ? l->cb_top : l->y;
  10150. deferred[ndeferred].flow_left =
  10151. cs.pos == 1 ? l->cb_left : l->left;
  10152. deferred[ndeferred].flow_right =
  10153. cs.pos == 1 ? l->cb_right : l->right;
  10154. deferred[ndeferred].link = lk;
  10155. deferred[ndeferred].z_index = cs.z_index;
  10156. deferred[ndeferred].z_set = cs.z_set;
  10157. deferred[ndeferred].order = (unsigned int)ndeferred;
  10158. ndeferred++;
  10159. } else if (l->draw && cs.pos == 1) {
  10160. /* Deferred list full: paint in place, but still
  10161. * against the containing block, not the flow. */
  10162. int fy = l->y, fl = l->left, fr = l->right;
  10163. l->y = l->cb_top;
  10164. l->left = l->cb_left;
  10165. l->right = l->cb_right;
  10166. layout_block(l, n, &cs, depth + 1, lk);
  10167. l->y = fy;
  10168. l->left = fl;
  10169. l->right = fr;
  10170. } else {
  10171. layout_block(l, n, &cs, depth + 1, lk);
  10172. }
  10173. if (cs.pos == 1 && block_h[n] &&
  10174. doc.nodes[n].class_off) {
  10175. const char *cl = doc.attrs +
  10176. doc.nodes[n].class_off;
  10177. if ((contains_ci(cl, "poster-wrapper") ||
  10178. contains_ci(cl, "ts-picture")) &&
  10179. !has_skeleton_sibling(n))
  10180. l->y += block_h[n];
  10181. }
  10182. n = nd->next;
  10183. continue;
  10184. }
  10185. if (nd->tag == BR_TAG_BR) {
  10186. flush_line(l);
  10187. n = nd->next;
  10188. continue;
  10189. }
  10190. if (nd->tag == BR_TAG_HR) {
  10191. flush_line(l);
  10192. if (l->draw)
  10193. ngui_fill_rect(l->ui,
  10194. (struct ngui_rect){l->left, l->y + 2,
  10195. l->right - l->left, 1}, BR_GRAY);
  10196. l->y += 8;
  10197. n = nd->next;
  10198. continue;
  10199. }
  10200. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  10201. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  10202. !button_has_elements(n)) {
  10203. if (!(nd->tag == BR_TAG_INPUT &&
  10204. s_eq(br_type(&doc, n), "hidden"))) {
  10205. form_fill_line = pst->display ==
  10206. BR_DISPLAY_FLEX &&
  10207. pst->flex_col;
  10208. add_form_run(l, n, &cs, lk);
  10209. form_fill_line = 0;
  10210. }
  10211. n = nd->next;
  10212. continue;
  10213. }
  10214. if (nd->tag == BR_TAG_IMG) {
  10215. add_image_run(l, n, &cs, lk);
  10216. n = nd->next;
  10217. continue;
  10218. }
  10219. if (nd->tag == BR_TAG_SVG &&
  10220. (cs.display == BR_DISPLAY_INLINE ||
  10221. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  10222. !cs.float_left) {
  10223. add_svg_run(l, n, &cs, lk);
  10224. n = nd->next;
  10225. continue;
  10226. }
  10227. if (nd->tag == BR_TAG_VIDEO) {
  10228. layout_block(l, n, &cs, depth + 1, lk);
  10229. n = nd->next;
  10230. continue;
  10231. }
  10232. if (cs.float_left) {
  10233. n = layout_float_group(l, n, pst, depth, lk);
  10234. continue;
  10235. }
  10236. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  10237. inline_block_flows(n, &cs, 0)) {
  10238. layout_children(l, n, &cs, depth + 1, lk);
  10239. n = nd->next;
  10240. continue;
  10241. }
  10242. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  10243. n = layout_inline_blocks(l, n, pst, depth, link);
  10244. continue;
  10245. }
  10246. /* A flex container is block-level like any block box even when
  10247. * the element is an inline tag such as <a> (a link card with
  10248. * display:flex is common on news sites). Without the block box
  10249. * its children were laid out in the parent flow with a 0x0 box
  10250. * of their own. */
  10251. /* inline-flex around inline content only ("| mehr" link
  10252. * tails, icon+label pills) stays in the text line. */
  10253. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  10254. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  10255. !flex_wants_row(n, &cs)) {
  10256. layout_children(l, n, &cs, depth + 1, lk);
  10257. } else if (cs.display == BR_DISPLAY_BLOCK ||
  10258. cs.display == BR_DISPLAY_FLEX ||
  10259. br_tag_is_block(nd->tag))
  10260. layout_block(l, n, &cs, depth + 1, lk);
  10261. else {
  10262. layout_children(l, n, &cs, depth + 1, lk);
  10263. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  10264. l->space_pending = 1;
  10265. }
  10266. n = nd->next;
  10267. }
  10268. emit_pseudo(l, parent, pst, 2, link);
  10269. }
  10270. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  10271. * runs and a recursive page can otherwise overflow the stack. */
  10272. static struct lay layout_state;
  10273. static int measure_page(int left, int right)
  10274. {
  10275. struct lay *l = &layout_state;
  10276. struct br_style base = base_style();
  10277. unsigned int i;
  10278. for (i = 0; i < BR_MAX_NODES; i++) {
  10279. block_h[i] = 0;
  10280. img_top[i] = 0;
  10281. block_top[i] = 0;
  10282. img_h[i] = 0;
  10283. layout_boxes[i].valid = 0;
  10284. }
  10285. memset(li_marker, 0, sizeof(li_marker));
  10286. l->draw = 0;
  10287. l->ui = &ui;
  10288. l->left = left;
  10289. l->right = right;
  10290. l->y = 0;
  10291. l->line_x = left;
  10292. l->run_x = left;
  10293. l->line_left = left;
  10294. l->line_right = right;
  10295. l->line_y = 0;
  10296. l->line_h = 0;
  10297. l->align = BR_ALIGN_LEFT;
  10298. l->cb_h = layout_view_h;
  10299. l->float_active = 0;
  10300. l->parent_top = 0;
  10301. l->cb_left = left;
  10302. l->cb_right = right;
  10303. l->cb_top = 0;
  10304. l->depth = 0;
  10305. l->nruns = 0;
  10306. l->space_pending = 0;
  10307. layout_children(l, doc.root, &base, 0, 0);
  10308. return l->y + 8;
  10309. }
  10310. static int deferred_cmp(const struct br_deferred *a,
  10311. const struct br_deferred *b)
  10312. {
  10313. int az = a->z_set ? a->z_index : 0;
  10314. int bz = b->z_set ? b->z_index : 0;
  10315. if (az != bz)
  10316. return az < bz ? -1 : 1;
  10317. if (a->order != b->order)
  10318. return a->order < b->order ? -1 : 1;
  10319. return 0;
  10320. }
  10321. static void sort_deferred(void)
  10322. {
  10323. int i;
  10324. for (i = 1; i < ndeferred; i++) {
  10325. struct br_deferred key = deferred[i];
  10326. int j = i;
  10327. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  10328. deferred[j] = deferred[j - 1];
  10329. j--;
  10330. }
  10331. deferred[j] = key;
  10332. }
  10333. }
  10334. static void render_page(int left, int right, int y0)
  10335. {
  10336. struct lay *l = &layout_state;
  10337. struct br_style base = base_style();
  10338. l->draw = 1;
  10339. l->ui = &ui;
  10340. l->left = left;
  10341. l->right = right;
  10342. l->y = y0;
  10343. l->line_x = left;
  10344. l->run_x = left;
  10345. l->line_left = left;
  10346. l->line_right = right;
  10347. l->line_y = y0;
  10348. l->line_h = 0;
  10349. l->align = BR_ALIGN_LEFT;
  10350. l->cb_h = layout_view_h;
  10351. l->float_active = 0;
  10352. l->parent_top = 0;
  10353. l->cb_left = left;
  10354. l->cb_right = right;
  10355. l->cb_top = y0;
  10356. l->depth = 0;
  10357. l->nruns = 0;
  10358. l->space_pending = 0;
  10359. nhits = 0;
  10360. ndeferred = 0;
  10361. layout_children(l, doc.root, &base, 0, 0);
  10362. sort_deferred();
  10363. {
  10364. int i;
  10365. for (i = 0; i < ndeferred; i++) {
  10366. struct br_style st;
  10367. br_style_for(&doc, deferred[i].node, &base, &st);
  10368. if (st.display == BR_DISPLAY_NONE)
  10369. continue;
  10370. l->draw = 1;
  10371. l->left = deferred[i].flow_left;
  10372. l->right = deferred[i].flow_right;
  10373. l->y = deferred[i].flow_y;
  10374. l->parent_top = deferred[i].parent_top;
  10375. l->line_x = l->left;
  10376. l->run_x = l->left;
  10377. l->line_y = l->y;
  10378. l->line_h = 0;
  10379. l->nruns = 0;
  10380. l->space_pending = 0;
  10381. l->align = st.align;
  10382. if (st.pos == 2 && block_h[deferred[i].node]) {
  10383. struct ngui_rect clip;
  10384. int ch = block_h[deferred[i].node] + 24;
  10385. clip.x = page_rect.x;
  10386. clip.y = page_rect.y;
  10387. clip.w = page_rect.w - 12;
  10388. if (ch > page_rect.h)
  10389. ch = page_rect.h;
  10390. clip.h = ch;
  10391. ngui_push_clip(&ui, clip);
  10392. if (st.has_bg)
  10393. ngui_fill_rect(&ui, clip, st.bg);
  10394. layout_block(l, deferred[i].node, &st, 0,
  10395. deferred[i].link);
  10396. ngui_pop_clip(&ui);
  10397. } else {
  10398. layout_block(l, deferred[i].node, &st, 0,
  10399. deferred[i].link);
  10400. }
  10401. }
  10402. }
  10403. }
  10404. /* ---- UI ---- */
  10405. static int find_hit(int x, int y)
  10406. {
  10407. int i;
  10408. for (i = nhits - 1; i >= 0; i--) {
  10409. struct hit *h = &hits[i];
  10410. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  10411. y < h->y + h->h)
  10412. return (int)h->node;
  10413. }
  10414. return 0;
  10415. }
  10416. /* ---- URL-bar autocomplete ----
  10417. *
  10418. * While the address bar has the focus a dropdown lists up to SUG_MAX
  10419. * history entries. An empty bar (a fresh focus, Ctrl+L) shows the most
  10420. * visited/recent sites; typing ranks prefix matches of the URL (with or
  10421. * without the scheme and "www.") above substring matches of the URL, then
  10422. * of the title, and adds visit count and recency. Typing at the end of the
  10423. * text also completes inline to the next '/' of the best prefix match
  10424. * ("clo" -> "cloudron.io/"), with the added part selected so the next
  10425. * keystroke replaces it; Enter on that text opens the history URL it came
  10426. * from (scheme included). Up/Down preview a row in the bar, Delete on a
  10427. * highlighted row forgets it, Esc closes the list (a second Esc leaves the
  10428. * bar), and a click on a row opens it. */
  10429. #define SUG_MAX 6
  10430. #define SUG_ROW_H 36
  10431. static int sug_idx[SUG_MAX];
  10432. static int sug_n, sug_sel = -1, sug_open;
  10433. static char sug_typed[NGUI_INPUT_MAX]; /* what the user typed */
  10434. static char sug_restore[NGUI_INPUT_MAX]; /* bar text before a preview */
  10435. static char ac_text[NGUI_INPUT_MAX]; /* bar text of the inline completion */
  10436. static char ac_url[HIST_URL_MAX]; /* the history URL it stands for */
  10437. static struct ngui_rect url_rect, sug_rect;
  10438. static int url_had_focus;
  10439. static char lc(char c)
  10440. {
  10441. return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
  10442. }
  10443. static int prefix_ci(const char *s, const char *p) /* p is lower case */
  10444. {
  10445. for (; *p; s++, p++)
  10446. if (lc(*s) != *p)
  10447. return 0;
  10448. return 1;
  10449. }
  10450. static unsigned int url_scheme_len(const char *url)
  10451. {
  10452. if (starts_with(url, "https://"))
  10453. return 8;
  10454. if (starts_with(url, "http://"))
  10455. return 7;
  10456. return 0;
  10457. }
  10458. /* Offset in `url` where the lower-case text `t` matches as a prefix: the
  10459. * whole URL, the URL without its scheme, or without scheme and "www.". */
  10460. static int hist_prefix_at(const char *url, const char *t)
  10461. {
  10462. unsigned int s = url_scheme_len(url);
  10463. if (prefix_ci(url, t))
  10464. return 0;
  10465. if (s && prefix_ci(url + s, t))
  10466. return (int)s;
  10467. if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
  10468. return (int)s + 4;
  10469. return -1;
  10470. }
  10471. static int hist_score(const struct hist_ent *e, const char *t,
  10472. unsigned int next)
  10473. {
  10474. unsigned int age = next - e->stamp;
  10475. int sc, at;
  10476. if (!t[0]) {
  10477. sc = 0;
  10478. } else if ((at = hist_prefix_at(e->url, t)) >= 0) {
  10479. /* Shorter rests first: "cloudron.io/" before its subpages. */
  10480. int rest = (int)s_len(e->url + at);
  10481. sc = 4000 - (rest > 400 ? 400 : rest);
  10482. } else if (contains_ci(e->url, t)) {
  10483. sc = 1000;
  10484. } else if (contains_ci(e->title, t)) {
  10485. sc = 600;
  10486. } else {
  10487. return -1;
  10488. }
  10489. sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
  10490. sc += age >= 500 ? 0 : (int)(500 - age);
  10491. return sc;
  10492. }
  10493. static void sug_lower(char *t, unsigned int cap)
  10494. {
  10495. unsigned int k;
  10496. for (k = 0; sug_typed[k] && k + 1 < cap; k++)
  10497. t[k] = lc(sug_typed[k]);
  10498. t[k] = '\0';
  10499. }
  10500. static void sug_refresh(void)
  10501. {
  10502. char t[NGUI_INPUT_MAX];
  10503. int sc[SUG_MAX], i, j;
  10504. unsigned int next = hist_next_stamp();
  10505. sug_lower(t, sizeof(t));
  10506. sug_n = 0;
  10507. for (i = 0; i < hist_n; i++) {
  10508. int s = hist_score(&hist_tab[i], t, next);
  10509. if (s < 0)
  10510. continue;
  10511. j = sug_n;
  10512. if (j == SUG_MAX) {
  10513. if (sc[SUG_MAX - 1] >= s)
  10514. continue;
  10515. j = SUG_MAX - 1;
  10516. }
  10517. while (j > 0 && sc[j - 1] < s) {
  10518. sc[j] = sc[j - 1];
  10519. sug_idx[j] = sug_idx[j - 1];
  10520. j--;
  10521. }
  10522. sc[j] = s;
  10523. sug_idx[j] = i;
  10524. if (sug_n < SUG_MAX)
  10525. sug_n++;
  10526. }
  10527. if (sug_sel >= sug_n)
  10528. sug_sel = -1;
  10529. }
  10530. /* Complete the typed text inline to the next '/' of the best prefix match. */
  10531. static void sug_inline(void)
  10532. {
  10533. char t[NGUI_INPUT_MAX];
  10534. const char *url, *rest;
  10535. unsigned int L, start, end, hs, tn, n = 0;
  10536. unsigned int next = hist_next_stamp();
  10537. int i, best = -1, best_sc = -1, at = 0;
  10538. sug_lower(t, sizeof(t));
  10539. L = s_len(t);
  10540. if (!L)
  10541. return;
  10542. for (i = 0; i < hist_n; i++) {
  10543. int a = hist_prefix_at(hist_tab[i].url, t), s;
  10544. if (a < 0)
  10545. continue;
  10546. s = hist_score(&hist_tab[i], t, next);
  10547. if (s > best_sc) {
  10548. best_sc = s;
  10549. best = i;
  10550. at = a;
  10551. }
  10552. }
  10553. if (best < 0)
  10554. return;
  10555. url = hist_tab[best].url;
  10556. rest = url + at;
  10557. /* Typing the scheme ("htt") completes past "https://", not to it. */
  10558. hs = at == 0 ? url_scheme_len(url) : 0;
  10559. start = L > hs ? L : hs;
  10560. end = start;
  10561. while (rest[end] && rest[end] != '/')
  10562. end++;
  10563. if (rest[end] == '/')
  10564. end++;
  10565. tn = s_len(sug_typed);
  10566. if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
  10567. return;
  10568. s_append(ac_text, &n, sug_typed, sizeof(ac_text));
  10569. for (; L < end && n + 1 < sizeof(ac_text); L++)
  10570. ac_text[n++] = rest[L];
  10571. ac_text[n] = '\0';
  10572. s_copy(ac_url, url, (unsigned int)at + end + 1);
  10573. ngui_input_set(&url_in, ac_text);
  10574. url_in.anchor = tn; /* select the completed part */
  10575. }
  10576. static void sug_close(void)
  10577. {
  10578. sug_open = 0;
  10579. sug_sel = -1;
  10580. ac_text[0] = '\0';
  10581. }
  10582. static int sug_visible(void)
  10583. {
  10584. return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
  10585. }
  10586. /* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
  10587. * start page) lists the top sites until something is typed. */
  10588. static int sug_focus_check(void)
  10589. {
  10590. int focused = ngui_focus(&ui) == ID_URL;
  10591. if (focused && !url_had_focus) {
  10592. sug_typed[0] = '\0';
  10593. sug_close();
  10594. sug_open = 1;
  10595. sug_refresh();
  10596. }
  10597. url_had_focus = focused;
  10598. return focused;
  10599. }
  10600. static void url_submit(unsigned int *action)
  10601. {
  10602. if (ac_text[0] && s_eq(url_in.text, ac_text))
  10603. s_copy(click_url, ac_url, sizeof(click_url));
  10604. *action |= ACT_NAV;
  10605. sug_close();
  10606. }
  10607. /* The bar text changed through typing or editing. */
  10608. static void sug_changed(void)
  10609. {
  10610. unsigned int pl = s_len(sug_typed);
  10611. int grew = url_in.len > pl && url_in.cursor == url_in.len &&
  10612. !memcmp(url_in.text, sug_typed, pl);
  10613. s_copy(sug_typed, url_in.text, sizeof(sug_typed));
  10614. ac_text[0] = '\0';
  10615. sug_sel = -1;
  10616. sug_open = 1;
  10617. sug_refresh();
  10618. if (grew)
  10619. sug_inline();
  10620. }
  10621. /* Keys for the list, taken off the queue before the text field sees them.
  10622. * Only a leading run is handled; the rest goes to the field. */
  10623. static void sug_keys(void)
  10624. {
  10625. int k;
  10626. while ((k = ngui_key_peek(&ui)) != 0) {
  10627. if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
  10628. ngui_key(&ui);
  10629. if (!sug_open) {
  10630. sug_open = 1;
  10631. continue;
  10632. }
  10633. if (sug_sel < 0)
  10634. s_copy(sug_restore, url_in.text,
  10635. sizeof(sug_restore));
  10636. if (k == NGUI_KEY_DOWN)
  10637. sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
  10638. else
  10639. sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
  10640. ngui_input_set(&url_in, sug_sel >= 0 ?
  10641. hist_tab[sug_idx[sug_sel]].url :
  10642. sug_restore);
  10643. } else if (k == NGUI_KEY_ESC && sug_visible()) {
  10644. ngui_key(&ui);
  10645. if (sug_sel >= 0)
  10646. ngui_input_set(&url_in, sug_restore);
  10647. else if (ac_text[0] && s_eq(url_in.text, ac_text))
  10648. ngui_input_set(&url_in, sug_typed);
  10649. sug_close();
  10650. } else if (k == NGUI_KEY_DELETE && sug_visible() &&
  10651. sug_sel >= 0) {
  10652. ngui_key(&ui);
  10653. hist_forget(sug_idx[sug_sel]);
  10654. ngui_input_set(&url_in, sug_restore);
  10655. sug_sel = -1;
  10656. sug_refresh();
  10657. } else {
  10658. break;
  10659. }
  10660. }
  10661. }
  10662. /* A press on a row of last frame's list opens it; any press on the list is
  10663. * swallowed so the page underneath does not see it. */
  10664. static void sug_click(unsigned int *action)
  10665. {
  10666. int row;
  10667. if (!(ui.pressed & 1) || !sug_rect.w ||
  10668. !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
  10669. return;
  10670. row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
  10671. if (row >= 0 && row < sug_n) {
  10672. s_copy(click_url, hist_tab[sug_idx[row]].url,
  10673. sizeof(click_url));
  10674. *action |= ACT_NAV;
  10675. sug_close();
  10676. }
  10677. ui.pressed = 0;
  10678. }
  10679. static void draw_suggest(struct ngui_rect page)
  10680. {
  10681. struct ngui_rect r;
  10682. int i, rows = sug_n, hover = -1;
  10683. r.x = url_rect.x;
  10684. r.y = url_rect.y + url_rect.h + 1;
  10685. r.w = url_rect.w < 320 ? 320 : url_rect.w;
  10686. if (r.x + r.w > ui.w - 2)
  10687. r.w = ui.w - 2 - r.x;
  10688. while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
  10689. rows--;
  10690. if (rows <= 0 || r.w < 60) {
  10691. sug_rect.w = 0;
  10692. return;
  10693. }
  10694. r.h = rows * SUG_ROW_H + 2;
  10695. sug_rect = r;
  10696. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  10697. hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
  10698. }
  10699. ngui_fill_rect(&ui, r, ui.theme.border);
  10700. for (i = 0; i < rows; i++) {
  10701. const struct hist_ent *e = &hist_tab[sug_idx[i]];
  10702. struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
  10703. r.w - 2, SUG_ROW_H};
  10704. struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
  10705. unsigned short bg = i == sug_sel ? ui.theme.selection :
  10706. i == hover ? ui.theme.panel_alt :
  10707. ui.theme.panel;
  10708. ngui_fill_rect(&ui, rr, bg);
  10709. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
  10710. e->title[0] ? e->title : e->url,
  10711. ui.theme.text);
  10712. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
  10713. i == sug_sel ? ui.theme.text :
  10714. ui.theme.text_dim);
  10715. }
  10716. }
  10717. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  10718. {
  10719. int x = r.x + 4, y = r.y + 4, h = 22;
  10720. int compact = r.w < 560;
  10721. int go_w = r.w < 420 ? 32 : 42;
  10722. int in_x, in_w, res;
  10723. ngui_fill_rect(&ui, r, ui.theme.panel);
  10724. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  10725. ui.theme.border);
  10726. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  10727. NGUI_ICON_CHEVRON_LEFT))
  10728. *action |= ACT_BACK;
  10729. x += 32;
  10730. if (!compact) {
  10731. if (ngui_icon_button(&ui, ID_FORWARD,
  10732. (struct ngui_rect){x, y, 28, h},
  10733. NGUI_ICON_CHEVRON_RIGHT))
  10734. *action |= ACT_FORWARD;
  10735. x += 32;
  10736. }
  10737. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  10738. NGUI_ICON_REFRESH))
  10739. *action |= ACT_RELOAD;
  10740. x += 32;
  10741. if (!compact) {
  10742. if (ngui_icon_button(&ui, ID_HOME,
  10743. (struct ngui_rect){x, y, 28, h},
  10744. NGUI_ICON_HOME))
  10745. *action |= ACT_HOME;
  10746. x += 32;
  10747. }
  10748. in_x = x + 2;
  10749. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  10750. if (in_w < 60)
  10751. in_w = 60;
  10752. url_rect = (struct ngui_rect){in_x, y, in_w, h};
  10753. if (sug_focus_check())
  10754. sug_keys();
  10755. res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
  10756. sug_focus_check(); /* a click into the bar focuses it here */
  10757. if (res & NGUI_INPUT_CHANGED)
  10758. sug_changed();
  10759. if (res & NGUI_INPUT_SUBMIT)
  10760. url_submit(action);
  10761. if (res & NGUI_INPUT_CANCEL)
  10762. ngui_set_focus(&ui, 0);
  10763. if (ngui_button(&ui, ID_GO,
  10764. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  10765. "Go"))
  10766. url_submit(action);
  10767. if (!sug_focus_check())
  10768. sug_close();
  10769. }
  10770. static int page_hover_node(void)
  10771. {
  10772. if (!ui.inside)
  10773. return 0;
  10774. if (ui.mouse_x < page_rect.x ||
  10775. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  10776. ui.mouse_y < page_rect.y ||
  10777. ui.mouse_y >= page_rect.y + page_rect.h)
  10778. return 0;
  10779. return find_hit(ui.mouse_x, ui.mouse_y);
  10780. }
  10781. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  10782. {
  10783. int x, y, w = page.w, h = page.h;
  10784. if (!src || w <= 0 || h <= 0)
  10785. return;
  10786. for (y = 0; y < h; y++) {
  10787. unsigned short *s = src + (page.y + y) * sw + page.x;
  10788. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  10789. for (x = 0; x + 1 < w; x += 2) {
  10790. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  10791. }
  10792. if (x < w)
  10793. d[x] = s[x];
  10794. }
  10795. }
  10796. static void draw_page(struct ngui_rect page)
  10797. {
  10798. int left, right, ch;
  10799. int old_panel, old_dim;
  10800. unsigned short *saved_px;
  10801. unsigned short page_bg = ui.theme.bg;
  10802. int saved_w, saved_h, use_buf;
  10803. unsigned int t0 = u_ticks_ms();
  10804. page_rect = page;
  10805. {
  10806. unsigned int root = doc.nnode > 1 ?
  10807. br_find_tag(&doc, BR_TAG_HTML) : 0;
  10808. unsigned int body = doc.nnode > 1 ?
  10809. br_find_tag(&doc, BR_TAG_BODY) : 0;
  10810. struct br_style bs;
  10811. if (root) {
  10812. style_for_node(root - 1, &bs);
  10813. if (bs.has_bg)
  10814. page_bg = bs.bg;
  10815. }
  10816. if (body) {
  10817. style_for_node(body - 1, &bs);
  10818. if (bs.has_bg)
  10819. page_bg = bs.bg;
  10820. }
  10821. }
  10822. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  10823. page_cache_valid && layout_valid &&
  10824. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  10825. !(ui.scroll_y &&
  10826. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  10827. page_scroll.offset == page_cache_scroll &&
  10828. page_cache_nnode == doc.nnode &&
  10829. page_cache_x == page.x && page_cache_y == page.y &&
  10830. page_cache_w == page.w && page_cache_h == page.h) {
  10831. blit_page(page, page_backbuf, pagebuf_w);
  10832. if (img_stat_n)
  10833. img_stat_paint += u_ticks_ms() - t0;
  10834. return;
  10835. }
  10836. ngui_fill_rect(&ui, page, page_bg);
  10837. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  10838. const char *s = page_loading ? "Loading..." : "No page";
  10839. int w = (int)ngui_text_width_ui(&ui, s);
  10840. ngui_text(&ui, page.x + (page.w - w) / 2,
  10841. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  10842. page_scroll.content_h = 0;
  10843. page_scroll.view_h = page.h;
  10844. page_cache_valid = 0;
  10845. return;
  10846. }
  10847. if (page.w < 40 || page.h < 40) {
  10848. page_cache_valid = 0;
  10849. return;
  10850. }
  10851. saved_px = ui.px;
  10852. saved_w = ui.w;
  10853. saved_h = ui.h;
  10854. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  10855. if (use_buf) {
  10856. ui.px = page_backbuf;
  10857. ui.w = pagebuf_w;
  10858. ui.h = pagebuf_h;
  10859. ngui_fill_rect(&ui, page, page_bg);
  10860. }
  10861. left = page.x + 8;
  10862. right = page.x + page.w - 16;
  10863. if (!layout_valid || left != layout_left || right != layout_right ||
  10864. layout_nnode != doc.nnode) {
  10865. unsigned int tm = u_ticks_ms();
  10866. layout_view_h = page.h - 8;
  10867. layout_content_h = measure_page(left, right);
  10868. if (img_stat_n)
  10869. img_stat_reflow += u_ticks_ms() - tm;
  10870. layout_valid = 1;
  10871. layout_left = left;
  10872. layout_right = right;
  10873. layout_nnode = doc.nnode;
  10874. /* Scripts that measured before any layout (offsetWidth on
  10875. * mount) get a resize event once real boxes exist, and again
  10876. * whenever the page width changes. */
  10877. if (js_browser_active() && right - left != resize_sent_w)
  10878. resize_pending = 1;
  10879. }
  10880. ch = layout_content_h;
  10881. page_scroll.content_h = ch;
  10882. page_scroll.view_h = page.h;
  10883. t0 = u_ticks_ms();
  10884. ngui_scroll_begin(&ui, page, &page_scroll);
  10885. ngui_scroll_wheel(&ui, page, &page_scroll);
  10886. render_page(left, right, page.y + 4 - page_scroll.offset);
  10887. old_panel = ui.theme.panel_alt;
  10888. old_dim = ui.theme.text_dim;
  10889. ui.theme.panel_alt = 0xC618;
  10890. ui.theme.text_dim = 0x8410;
  10891. ngui_scroll_end(&ui, page, &page_scroll);
  10892. ui.theme.panel_alt = old_panel;
  10893. ui.theme.text_dim = old_dim;
  10894. if (use_buf) {
  10895. ui.px = saved_px;
  10896. ui.w = saved_w;
  10897. ui.h = saved_h;
  10898. blit_page(page, page_backbuf, pagebuf_w);
  10899. page_cache_valid = 1;
  10900. page_cache_scroll = page_scroll.offset;
  10901. page_cache_nnode = doc.nnode;
  10902. page_cache_x = page.x;
  10903. page_cache_y = page.y;
  10904. page_cache_w = page.w;
  10905. page_cache_h = page.h;
  10906. } else {
  10907. page_cache_valid = 0;
  10908. }
  10909. if (img_stat_n)
  10910. img_stat_paint += u_ticks_ms() - t0;
  10911. }
  10912. static void draw_status(struct ngui_rect r)
  10913. {
  10914. static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
  10915. unsigned int n = 0;
  10916. int hover = page_hover_node();
  10917. unsigned short color;
  10918. const char *kind;
  10919. ngui_fill_rect(&ui, r, ui.theme.panel);
  10920. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  10921. ui.theme.border);
  10922. if (hover) {
  10923. const char *href = br_href(&doc, (unsigned int)hover);
  10924. char url[BR_URL_MAX];
  10925. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  10926. s_append(msg, &n, "Link: ", sizeof(msg));
  10927. s_append(msg, &n, url, sizeof(msg));
  10928. } else {
  10929. s_copy(msg, "Link", sizeof(msg));
  10930. }
  10931. color = ui.theme.accent;
  10932. } else if (status_text[0]) {
  10933. s_copy(msg, status_text, sizeof(msg));
  10934. color = status_error ? ui.theme.error : ui.theme.text;
  10935. } else if (page_title[0]) {
  10936. s_copy(msg, page_title, sizeof(msg));
  10937. color = ui.theme.text;
  10938. } else {
  10939. s_copy(msg, "Ready", sizeof(msg));
  10940. color = ui.theme.text_dim;
  10941. }
  10942. kind = s_eq(page_url, "about:home") ? "HOME" :
  10943. page_is_local ? "FILE" :
  10944. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  10945. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  10946. {
  10947. int kw = (int)ngui_text_width_ui(&ui, kind);
  10948. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  10949. ui.theme.text_dim);
  10950. }
  10951. }
  10952. /* Mouse cursor over the page: the hovered node's CSS `cursor` (inherited);
  10953. * for `auto`, a hand over links, the I-beam over text fields, and the
  10954. * progress arrow anywhere on the page while it is still loading. The
  10955. * toolbar's URL field sets its own I-beam through ngui. */
  10956. static void page_cursor(void)
  10957. {
  10958. int hover = page_hover_node();
  10959. struct br_style st;
  10960. if (!hover) {
  10961. if (page_loading && ui.inside &&
  10962. ngui_rect_contains(&page_rect, ui.mouse_x, ui.mouse_y))
  10963. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  10964. return;
  10965. }
  10966. style_for_node((unsigned int)hover, &st);
  10967. if (st.cursor != BR_CURSOR_AUTO) {
  10968. ngui_set_cursor(&ui, (int)st.cursor - 1);
  10969. return;
  10970. }
  10971. if (br_href(&doc, (unsigned int)hover)) {
  10972. ngui_set_cursor(&ui, CURSOR_POINTER);
  10973. return;
  10974. }
  10975. if (form_is_control((unsigned int)hover)) {
  10976. int k = form_kind_of((unsigned int)hover);
  10977. if (form_disabled((unsigned int)hover))
  10978. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  10979. else if (k == FORM_TEXT || k == FORM_PASSWORD ||
  10980. k == FORM_TEXTAREA)
  10981. ngui_set_cursor(&ui, CURSOR_TEXT);
  10982. return;
  10983. }
  10984. if (page_loading)
  10985. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  10986. }
  10987. static void draw(unsigned int *action)
  10988. {
  10989. struct ngui_rect r = {0, 0, ui.w, ui.h};
  10990. struct ngui_rect toolbar, status, page;
  10991. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  10992. status = ngui_cut_bottom(&r, BR_STATUS_H);
  10993. page = r;
  10994. if (sug_visible())
  10995. sug_click(action);
  10996. draw_toolbar(toolbar, action);
  10997. draw_page(page);
  10998. draw_status(status);
  10999. page_cursor();
  11000. if (sug_visible())
  11001. draw_suggest(page);
  11002. else
  11003. sug_rect.w = 0;
  11004. }
  11005. static void redraw_now(void)
  11006. {
  11007. unsigned int action = 0;
  11008. ngui_begin(&ui);
  11009. draw(&action);
  11010. ngui_end(&ui);
  11011. }
  11012. static void handle_keys(unsigned int *action)
  11013. {
  11014. int k, scrolled = 0;
  11015. if (form_focus >= doc.nnode)
  11016. form_focus = 0;
  11017. if (form_focus && !ngui_focus(&ui)) {
  11018. while ((k = ngui_key(&ui)) != 0)
  11019. form_key(k);
  11020. return;
  11021. }
  11022. /* Batch queued page keys: a slow full-page render must not make a
  11023. * held Page Down advance only once every few frames. */
  11024. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  11025. scrolled++;
  11026. if (scrolled)
  11027. ngui_invalidate(&ui);
  11028. if (ngui_focus(&ui))
  11029. return;
  11030. while ((k = ngui_key(&ui)) != 0) {
  11031. switch (k) {
  11032. case NGUI_KEY_ESC:
  11033. *action |= ACT_CLOSE;
  11034. break;
  11035. case NGUI_KEY_TAB:
  11036. case 0x0C: /* Ctrl+L */
  11037. ngui_set_focus(&ui, ID_URL);
  11038. break;
  11039. case 0x12: /* Ctrl+R */
  11040. *action |= ACT_RELOAD;
  11041. break;
  11042. case NGUI_KEY_BACKSPACE:
  11043. *action |= ACT_BACK;
  11044. break;
  11045. case NGUI_KEY_UP:
  11046. ngui_scroll_to(&page_scroll,
  11047. page_scroll.offset - 24);
  11048. ngui_invalidate(&ui);
  11049. break;
  11050. case NGUI_KEY_DOWN:
  11051. ngui_scroll_to(&page_scroll,
  11052. page_scroll.offset + 24);
  11053. ngui_invalidate(&ui);
  11054. break;
  11055. case NGUI_KEY_HOME:
  11056. ngui_scroll_to(&page_scroll, 0);
  11057. ngui_invalidate(&ui);
  11058. break;
  11059. case NGUI_KEY_END:
  11060. ngui_scroll_to(&page_scroll,
  11061. page_scroll.content_h -
  11062. page_scroll.view_h);
  11063. ngui_invalidate(&ui);
  11064. break;
  11065. default:
  11066. break;
  11067. }
  11068. }
  11069. }
  11070. static unsigned int form_ancestor(unsigned int node)
  11071. {
  11072. unsigned int p = node;
  11073. while (p && p < doc.nnode) {
  11074. if (doc.nodes[p].tag == BR_TAG_FORM &&
  11075. doc.nodes[p].type == BR_NODE_ELEM)
  11076. return p;
  11077. p = doc.nodes[p].parent;
  11078. }
  11079. return 0;
  11080. }
  11081. static int form_descendant(unsigned int node, unsigned int form)
  11082. {
  11083. unsigned int p = node;
  11084. while (p && p < doc.nnode) {
  11085. if (p == form)
  11086. return 1;
  11087. p = doc.nodes[p].parent;
  11088. }
  11089. return 0;
  11090. }
  11091. static void form_reset_form(unsigned int form)
  11092. {
  11093. unsigned int i;
  11094. for (i = 0; i < FORM_MAX; i++)
  11095. if (form_states[i].used &&
  11096. form_descendant(form_states[i].node, form))
  11097. form_states[i].used = 0;
  11098. form_focus = 0;
  11099. }
  11100. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  11101. const char *s)
  11102. {
  11103. static const char hex[] = "0123456789ABCDEF";
  11104. while (s && *s && *n + 1 < cap) {
  11105. unsigned char c = (unsigned char)*s++;
  11106. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  11107. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  11108. c == '.' || c == '~') {
  11109. dst[(*n)++] = (char)c;
  11110. } else if (c == ' ') {
  11111. dst[(*n)++] = '+';
  11112. } else if (*n + 3 < cap) {
  11113. dst[(*n)++] = '%';
  11114. dst[(*n)++] = hex[c >> 4];
  11115. dst[(*n)++] = hex[c & 15];
  11116. }
  11117. }
  11118. dst[*n] = '\0';
  11119. }
  11120. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  11121. const char *name, const char *value, int *first)
  11122. {
  11123. if (!name || !name[0])
  11124. return;
  11125. if (!*first && *n + 1 < cap)
  11126. dst[(*n)++] = '&';
  11127. *first = 0;
  11128. form_url_append(dst, n, cap, name);
  11129. if (*n + 1 < cap)
  11130. dst[(*n)++] = '=';
  11131. form_url_append(dst, n, cap, value ? value : "");
  11132. dst[*n] = '\0';
  11133. }
  11134. static int form_submit_form(unsigned int node, int fire_event)
  11135. {
  11136. unsigned int form = form_ancestor(node);
  11137. char action[BR_URL_MAX], query[2048];
  11138. unsigned int qn = 0, i;
  11139. int first = 1, is_post = 0;
  11140. const char *a, *method;
  11141. if (!form)
  11142. return 0;
  11143. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  11144. return 0;
  11145. method = br_find_attr(&doc, form, "method");
  11146. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  11147. is_post = 1;
  11148. a = br_find_attr(&doc, form, "action");
  11149. if (a && a[0]) {
  11150. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  11151. return 0;
  11152. } else {
  11153. s_copy(action, page_url, sizeof(action));
  11154. }
  11155. query[0] = '\0';
  11156. for (i = 0; i < doc.nnode; i++) {
  11157. struct br_node *nd = &doc.nodes[i];
  11158. struct form_state *fs;
  11159. const char *name;
  11160. const char *value = "";
  11161. if (nd->type != BR_NODE_ELEM || i == form ||
  11162. !form_descendant(i, form))
  11163. continue;
  11164. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  11165. nd->tag != BR_TAG_SELECT)
  11166. continue;
  11167. if (form_disabled(i))
  11168. continue;
  11169. name = br_find_attr(&doc, i, "name");
  11170. if (!name || !name[0])
  11171. continue;
  11172. fs = form_get(i, 1);
  11173. if (!fs)
  11174. continue;
  11175. if (nd->tag == BR_TAG_SELECT) {
  11176. char opt[64];
  11177. if (!form_option_text(i, fs->selected, opt,
  11178. sizeof(opt)))
  11179. s_copy(opt, "", sizeof(opt));
  11180. value = opt;
  11181. {
  11182. unsigned int c, oi = 0;
  11183. for (c = nd->first; c;
  11184. c = doc.nodes[c].next) {
  11185. if (doc.nodes[c].type != BR_NODE_ELEM ||
  11186. doc.nodes[c].tag != BR_TAG_OPTION)
  11187. continue;
  11188. if (oi == fs->selected) {
  11189. const char *v =
  11190. br_value(&doc, c);
  11191. if (v && v[0])
  11192. value = v;
  11193. break;
  11194. }
  11195. oi++;
  11196. }
  11197. }
  11198. } else if (nd->tag == BR_TAG_INPUT) {
  11199. int kind = form_kind_of(i);
  11200. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  11201. if (!fs->checked)
  11202. continue;
  11203. value = br_value(&doc, i);
  11204. if (!value || !value[0])
  11205. value = "on";
  11206. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  11207. kind == FORM_BUTTON) {
  11208. if (i != node)
  11209. continue;
  11210. value = fs->value;
  11211. } else {
  11212. value = fs->value;
  11213. }
  11214. } else {
  11215. value = fs->value;
  11216. }
  11217. form_add_param(query, &qn, sizeof(query), name, value, &first);
  11218. }
  11219. if (is_post) {
  11220. if (action[0] == '/') {
  11221. set_status("POST forms need an HTTP action URL", 1, 4000);
  11222. ngui_invalidate(&ui);
  11223. return 0;
  11224. }
  11225. if (qn >= sizeof(pending_post))
  11226. qn = sizeof(pending_post) - 1;
  11227. if (qn)
  11228. memcpy(pending_post, query, qn);
  11229. pending_post[qn] = '\0';
  11230. pending_post_len = qn;
  11231. pending_post_is = 1;
  11232. } else {
  11233. pending_post_len = 0;
  11234. pending_post_is = 0;
  11235. if (qn) {
  11236. unsigned int an = s_len(action);
  11237. if (an + qn + 2 < sizeof(action)) {
  11238. action[an++] = strchr(action, '?') ? '&' : '?';
  11239. action[an] = '\0';
  11240. s_copy(action + an, query,
  11241. sizeof(action) - an);
  11242. }
  11243. }
  11244. }
  11245. s_copy(pending_url, action, sizeof(pending_url));
  11246. pending_action |= ACT_NAV;
  11247. cancel_fetch = 1;
  11248. ngui_invalidate(&ui);
  11249. return 1;
  11250. }
  11251. static void form_reset_event(unsigned int form)
  11252. {
  11253. if (form && !js_browser_event(form, "reset", 1, 1))
  11254. return;
  11255. if (form)
  11256. form_reset_form(form);
  11257. else
  11258. form_reset_state();
  11259. form_dirty = 0;
  11260. layout_valid = 0;
  11261. ngui_invalidate(&ui);
  11262. }
  11263. static void form_blur(void)
  11264. {
  11265. unsigned int node = form_focus;
  11266. form_focus = 0;
  11267. if (node && form_dirty) {
  11268. form_dirty = 0;
  11269. js_browser_event(node, "change", 1, 0);
  11270. }
  11271. }
  11272. static void form_click(unsigned int node)
  11273. {
  11274. struct form_state *fs;
  11275. int kind, changed = 0;
  11276. if (!form_is_control(node) || form_disabled(node))
  11277. return;
  11278. if (form_focus != node)
  11279. form_blur();
  11280. if (!js_browser_event(node, "click", 1, 1))
  11281. return;
  11282. fs = form_get(node, 1);
  11283. if (!fs)
  11284. return;
  11285. kind = form_kind_of(node);
  11286. form_focus = node;
  11287. form_dirty = 0;
  11288. if (kind == FORM_CHECKBOX) {
  11289. fs->checked = !fs->checked;
  11290. changed = 1;
  11291. } else if (kind == FORM_RADIO) {
  11292. const char *name = br_find_attr(&doc, node, "name");
  11293. unsigned int i;
  11294. fs->checked = 1;
  11295. changed = 1;
  11296. if (name) {
  11297. for (i = 0; i < FORM_MAX; i++) {
  11298. struct form_state *o = &form_states[i];
  11299. if (!o->used || o->node == node)
  11300. continue;
  11301. if (form_kind_of(o->node) == FORM_RADIO) {
  11302. const char *on = br_find_attr(&doc,
  11303. o->node,
  11304. "name");
  11305. if (on && s_eq(on, name))
  11306. o->checked = 0;
  11307. }
  11308. }
  11309. }
  11310. } else if (kind == FORM_SELECT) {
  11311. unsigned int n = form_option_count(node);
  11312. if (n) {
  11313. fs->selected = (unsigned char)
  11314. ((fs->selected + 1) % n);
  11315. changed = 1;
  11316. }
  11317. } else if (kind == FORM_SUBMIT) {
  11318. form_submit_form(node, 1);
  11319. return;
  11320. } else if (kind == FORM_RESET) {
  11321. form_reset_event(form_ancestor(node));
  11322. return;
  11323. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  11324. kind == FORM_TEXTAREA) {
  11325. fs->caret = fs->len;
  11326. }
  11327. if (changed) {
  11328. js_browser_event(node, "input", 1, 0);
  11329. js_browser_event(node, "change", 1, 0);
  11330. }
  11331. layout_valid = 0;
  11332. ngui_invalidate(&ui);
  11333. }
  11334. static void form_focus_next(void)
  11335. {
  11336. unsigned int start = form_focus ? form_focus + 1 : 0;
  11337. unsigned int i;
  11338. form_blur();
  11339. for (i = start; i < doc.nnode; i++) {
  11340. if (form_is_control(i) && !form_disabled(i) &&
  11341. !s_eq(br_type(&doc, i), "hidden")) {
  11342. form_focus = i;
  11343. layout_valid = 0;
  11344. ngui_invalidate(&ui);
  11345. return;
  11346. }
  11347. }
  11348. form_focus = 0;
  11349. layout_valid = 0;
  11350. ngui_invalidate(&ui);
  11351. }
  11352. static void form_key(int k)
  11353. {
  11354. struct form_state *fs;
  11355. int kind;
  11356. if (!form_focus || form_focus >= doc.nnode) {
  11357. form_focus = 0;
  11358. return;
  11359. }
  11360. fs = form_get(form_focus, 1);
  11361. if (!fs || form_disabled(form_focus))
  11362. return;
  11363. kind = form_kind_of(form_focus);
  11364. if (kind == FORM_SELECT) {
  11365. unsigned int n = form_option_count(form_focus);
  11366. int changed = 0;
  11367. if (k == NGUI_KEY_UP && n) {
  11368. fs->selected = (unsigned char)
  11369. ((fs->selected + n - 1) % n);
  11370. changed = 1;
  11371. } else if (k == NGUI_KEY_DOWN && n) {
  11372. fs->selected = (unsigned char)
  11373. ((fs->selected + 1) % n);
  11374. changed = 1;
  11375. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  11376. form_blur();
  11377. layout_valid = 0;
  11378. ngui_invalidate(&ui);
  11379. return;
  11380. } else {
  11381. return;
  11382. }
  11383. if (changed) {
  11384. js_browser_event(form_focus, "input", 1, 0);
  11385. js_browser_event(form_focus, "change", 1, 0);
  11386. }
  11387. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  11388. if (k == ' ') {
  11389. form_click(form_focus);
  11390. return;
  11391. }
  11392. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  11393. form_blur();
  11394. layout_valid = 0;
  11395. ngui_invalidate(&ui);
  11396. }
  11397. return;
  11398. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  11399. kind == FORM_RESET) {
  11400. if (k == NGUI_KEY_ESC) {
  11401. form_blur();
  11402. layout_valid = 0;
  11403. ngui_invalidate(&ui);
  11404. } else if (k == '\r' || k == '\n' || k == ' ') {
  11405. form_click(form_focus);
  11406. }
  11407. return;
  11408. } else if (k == NGUI_KEY_TAB) {
  11409. form_focus_next();
  11410. return;
  11411. } else if (k == NGUI_KEY_ESC) {
  11412. form_blur();
  11413. layout_valid = 0;
  11414. ngui_invalidate(&ui);
  11415. return;
  11416. } else if (k == '\r' || k == '\n') {
  11417. unsigned int node = form_focus;
  11418. form_blur();
  11419. if (form_ancestor(node))
  11420. form_submit_form(node, 1);
  11421. layout_valid = 0;
  11422. ngui_invalidate(&ui);
  11423. return;
  11424. } else if (k == NGUI_KEY_BACKSPACE) {
  11425. if (fs->caret) {
  11426. unsigned int i = --fs->caret;
  11427. for (; i < fs->len; i++)
  11428. fs->value[i] = fs->value[i + 1];
  11429. if (fs->len)
  11430. fs->len--;
  11431. form_dirty = 1;
  11432. js_browser_event(form_focus, "input", 1, 0);
  11433. }
  11434. } else if (k == NGUI_KEY_DELETE) {
  11435. if (fs->caret < fs->len) {
  11436. unsigned int i;
  11437. for (i = fs->caret; i < fs->len; i++)
  11438. fs->value[i] = fs->value[i + 1];
  11439. fs->len--;
  11440. form_dirty = 1;
  11441. js_browser_event(form_focus, "input", 1, 0);
  11442. }
  11443. } else if (k == NGUI_KEY_LEFT) {
  11444. if (fs->caret)
  11445. fs->caret--;
  11446. } else if (k == NGUI_KEY_RIGHT) {
  11447. if (fs->caret < fs->len)
  11448. fs->caret++;
  11449. } else if (k == NGUI_KEY_HOME) {
  11450. fs->caret = 0;
  11451. } else if (k == NGUI_KEY_END) {
  11452. fs->caret = fs->len;
  11453. } else if (k >= 32 && k < 127) {
  11454. if (fs->len < FORM_VALUE_MAX) {
  11455. unsigned int i;
  11456. for (i = fs->len; i > fs->caret; i--)
  11457. fs->value[i] = fs->value[i - 1];
  11458. fs->value[fs->caret++] = (char)k;
  11459. fs->len++;
  11460. form_dirty = 1;
  11461. js_browser_event(form_focus, "input", 1, 0);
  11462. }
  11463. } else {
  11464. return;
  11465. }
  11466. fs->value[fs->len] = '\0';
  11467. layout_valid = 0;
  11468. ngui_invalidate(&ui);
  11469. }
  11470. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  11471. * a same-document navigation: update the URL and fire hashchange. Returns
  11472. * 1 when handled. */
  11473. static int link_fragment_nav(unsigned int node)
  11474. {
  11475. const char *href = br_href(&doc, node);
  11476. char url[BR_URL_MAX];
  11477. unsigned int n = 0;
  11478. if (!href || !href[0] || !js_browser_active())
  11479. return 0;
  11480. if (href[0] == '#') {
  11481. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  11482. url[n] = page_url[n];
  11483. n++;
  11484. }
  11485. url[n] = '\0';
  11486. s_append(url, &n, href, sizeof(url));
  11487. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  11488. return 0;
  11489. }
  11490. if (!same_doc_fragment(url))
  11491. return href[0] == '#';
  11492. page_set_fragment(url, 1);
  11493. js_browser_hashchange();
  11494. return 1;
  11495. }
  11496. /* The innermost laid-out box under a screen point: the smallest valid box
  11497. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  11498. * Used to deliver clicks to elements that are neither links nor controls
  11499. * (a Vue <div role="button">, a card with a click listener). */
  11500. static unsigned int find_box_hit(int x, int y)
  11501. {
  11502. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  11503. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  11504. const struct br_layout_box *b = &layout_boxes[i];
  11505. unsigned int area;
  11506. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  11507. x < b->x || y < b->y || x >= b->x + b->w ||
  11508. y >= b->y + b->h)
  11509. continue;
  11510. area = (unsigned int)b->w * (unsigned int)b->h;
  11511. if (area <= best_area) {
  11512. best = i;
  11513. best_area = area;
  11514. }
  11515. }
  11516. return best;
  11517. }
  11518. static void handle_page_click(unsigned int *action)
  11519. {
  11520. int node;
  11521. char url[BR_URL_MAX];
  11522. if (!ui.pressed)
  11523. return;
  11524. if (ui.press_x < page_rect.x ||
  11525. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  11526. ui.press_y < page_rect.y ||
  11527. ui.press_y >= page_rect.y + page_rect.h)
  11528. return;
  11529. node = find_hit(ui.press_x, ui.press_y);
  11530. if (!node) {
  11531. unsigned int box;
  11532. if (!js_browser_active())
  11533. return;
  11534. box = find_box_hit(ui.press_x, ui.press_y);
  11535. if (box) {
  11536. form_blur();
  11537. js_browser_event(box, "click", 1, 1);
  11538. }
  11539. return;
  11540. }
  11541. if (form_is_control((unsigned int)node)) {
  11542. form_click((unsigned int)node);
  11543. return;
  11544. }
  11545. form_blur();
  11546. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  11547. return;
  11548. if (link_fragment_nav((unsigned int)node))
  11549. return;
  11550. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  11551. sizeof(url)) != 0)
  11552. return;
  11553. s_copy(click_url, url, sizeof(click_url));
  11554. *action |= ACT_NAV;
  11555. }
  11556. void _start(const char *arg)
  11557. {
  11558. struct win_info wi;
  11559. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  11560. u_win_create(960, 640, "Browser", &wi) != 0 &&
  11561. u_win_create(780, 540, "Browser", &wi) != 0) {
  11562. u_puts("browser: no graphics window\n");
  11563. u_exit(1);
  11564. }
  11565. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  11566. url_in.placeholder = "http://...";
  11567. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  11568. ui.theme.accent);
  11569. br_set_viewport(wi.width);
  11570. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  11571. s_copy(cwd, "/", sizeof(cwd));
  11572. heap_clear();
  11573. origin_cache_load();
  11574. css_cache_init();
  11575. script_cache_init();
  11576. persist_restore();
  11577. hist_load();
  11578. page_scroll.offset = 0;
  11579. page_scroll.content_h = 0;
  11580. if (arg && arg[0]) {
  11581. navigate(arg, 1);
  11582. } else {
  11583. load_home(1);
  11584. /* Start ready to type: keep the home page, but leave the address
  11585. * bar empty instead of showing "about:home". */
  11586. ngui_input_set(&url_in, "");
  11587. ngui_set_focus(&ui, ID_URL);
  11588. }
  11589. for (;;) {
  11590. unsigned int action = 0;
  11591. unsigned int now;
  11592. click_url[0] = '\0';
  11593. if (pending_action) {
  11594. action |= pending_action & ACT_WAIT_NAV;
  11595. if (pending_url[0])
  11596. s_copy(click_url, pending_url, sizeof(click_url));
  11597. pending_action = 0;
  11598. pending_url[0] = '\0';
  11599. cancel_fetch = 0;
  11600. } else if (preload_active) {
  11601. if (preload_wait)
  11602. preload_wait = 0;
  11603. else
  11604. preload_step();
  11605. } else if ((preload_pending &&
  11606. page_scroll.offset != preload_scroll) ||
  11607. (preload_rescan && layout_valid)) {
  11608. preload_scroll = page_scroll.offset;
  11609. preload_rescan = 0;
  11610. preload_pending = 0;
  11611. preload_node = 0;
  11612. preload_active = 1;
  11613. }
  11614. js_browser_tick();
  11615. if (resize_pending && !pending_action) {
  11616. resize_pending = 0;
  11617. resize_sent_w = layout_right - layout_left;
  11618. js_browser_window_event("resize");
  11619. }
  11620. persist_tick();
  11621. if (pending_action)
  11622. continue;
  11623. now = u_ticks_ms();
  11624. if (status_until && (int)(now - status_until) >= 0) {
  11625. status_text[0] = '\0';
  11626. status_until = 0;
  11627. status_error = 0;
  11628. ngui_invalidate(&ui);
  11629. }
  11630. if (!ngui_begin(&ui)) {
  11631. /* A queued navigation (e.g. Enter in the URL bar during
  11632. * a slow fetch) must be handled even when this frame
  11633. * needs no redraw. */
  11634. if (!action) {
  11635. fetch_workers_stop_if_unfocused();
  11636. u_sleep_ms(10);
  11637. continue;
  11638. }
  11639. } else {
  11640. draw(&action);
  11641. handle_keys(&action);
  11642. handle_page_click(&action);
  11643. ngui_end(&ui);
  11644. }
  11645. if (action & ACT_NAV) {
  11646. if (click_url[0]) {
  11647. navigate(click_url, 1);
  11648. click_url[0] = '\0';
  11649. } else {
  11650. navigate(url_in.text, 1);
  11651. }
  11652. }
  11653. if (action & ACT_BACK) {
  11654. if (hist_pos > 0) {
  11655. hist_pos--;
  11656. if (same_doc_fragment(history[hist_pos])) {
  11657. page_set_fragment(history[hist_pos], 0);
  11658. js_browser_hashchange();
  11659. } else {
  11660. navigate(history[hist_pos], 0);
  11661. }
  11662. }
  11663. }
  11664. if (action & ACT_FORWARD) {
  11665. if (hist_pos + 1 < hist_len) {
  11666. hist_pos++;
  11667. if (same_doc_fragment(history[hist_pos])) {
  11668. page_set_fragment(history[hist_pos], 0);
  11669. js_browser_hashchange();
  11670. } else {
  11671. navigate(history[hist_pos], 0);
  11672. }
  11673. }
  11674. }
  11675. if (action & ACT_RELOAD) {
  11676. if (s_eq(page_url, "about:home"))
  11677. load_home(0);
  11678. else
  11679. navigate(page_url, 0);
  11680. }
  11681. if (action & ACT_HOME)
  11682. load_home(1);
  11683. if (action & ACT_CLOSE)
  11684. quit = 1;
  11685. if (quit)
  11686. break;
  11687. if (pending_action)
  11688. continue;
  11689. fetch_workers_stop_if_unfocused();
  11690. u_sleep_ms(10);
  11691. }
  11692. fetch_workers_stop_all();
  11693. u_win_close();
  11694. u_exit(0);
  11695. }