browser.c 278 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810
  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 (512u * 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_ARENA_MAX (24u * 1024u * 1024u)
  43. #define BR_IMG_LAYOUT_W 1000
  44. /* An image job may hold a fetch helper this long. The page/script
  45. * deadline (UHTTP_TOTAL_TIMEOUT_MS) is minutes; one unreachable image host
  46. * must not starve the other images of all four helpers that long. */
  47. #define BR_IMG_JOB_TIMEOUT_MS 30000u
  48. #define BR_CSS_MAX (832u * 1024u)
  49. #define BR_CSS_COMP_MAX (192u * 1024u)
  50. /* Scripts and ES modules: Vite bundles reach ~1.7 MB (the Cloudron
  51. * dashboard's main chunk); the helper's FETCH_MAX is the same 2 MB. */
  52. #define BR_SCRIPT_MAX (2u * 1024u * 1024u)
  53. #define FETCH_ABORT (-2)
  54. /* Session cache for remote stylesheets (per launch; cleared at startup). */
  55. #define CSS_CACHE_MAX 16
  56. #define CSS_CACHE_FILE_MAX (256u * 1024u)
  57. #define CSS_CACHE_PREFIX "bcss-"
  58. #define SCRIPT_CACHE_MAX 24
  59. #define SCRIPT_CACHE_FILE_MAX BR_SCRIPT_MAX
  60. #define SCRIPT_CACHE_PREFIX "bjs-"
  61. #define BR_MAX_SHEETS 6
  62. #define BR_HISTORY 16
  63. #define BR_URL_MAX 512
  64. #define BR_STATUS_MAX 200
  65. #define BR_IMG_RGB565(r, g, b) \
  66. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  67. #define BR_GRAY 0x8410
  68. enum {
  69. ID_URL = 1,
  70. ID_GO,
  71. ID_BACK,
  72. ID_FORWARD,
  73. ID_RELOAD,
  74. ID_HOME
  75. };
  76. #define ACT_NAV (1u << 0)
  77. #define ACT_BACK (1u << 1)
  78. #define ACT_FORWARD (1u << 2)
  79. #define ACT_RELOAD (1u << 3)
  80. #define ACT_HOME (1u << 4)
  81. #define ACT_CLOSE (1u << 5)
  82. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  83. ACT_HOME | ACT_CLOSE)
  84. struct br_image {
  85. int state; /* 0 empty, 1 ready */
  86. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  87. int native_w, native_h;
  88. unsigned int url_hash; /* <img> source, 0 = not shareable */
  89. char err[32];
  90. };
  91. static struct ngui ui;
  92. static struct ngui_input url_in;
  93. static struct ngui_scroll page_scroll;
  94. static struct br_doc doc;
  95. static struct br_image images[BR_MAX_IMAGES];
  96. static int image_count;
  97. static unsigned int image_pixels;
  98. /* Painted border boxes, in page/screen coordinates (layout starts at
  99. * page_rect.y + 4 - scroll). getBoundingClientRect() subtracts page_rect. */
  100. struct br_layout_box {
  101. int x, y;
  102. int w, h;
  103. unsigned char valid;
  104. };
  105. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  106. /* Images are loaded one per main-loop iteration so the parsed page stays
  107. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  108. static int preload_active;
  109. static int preload_max_jobs;
  110. static int preload_pending;
  111. static int preload_wait;
  112. static unsigned int preload_node;
  113. static int preload_loaded;
  114. static int preload_scroll;
  115. static int preload_rescan;
  116. static char post_status_text[BR_STATUS_MAX];
  117. static int post_status_error;
  118. static unsigned int post_status_ttl;
  119. /* Content-relative position/height of each <img>, recorded by the measure
  120. * pass so image loading can be deferred until it is near the viewport. */
  121. static unsigned short img_top[BR_MAX_NODES];
  122. static unsigned short img_h[BR_MAX_NODES];
  123. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  124. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  125. * body. Decode arenas are allocated per image instead of living here. */
  126. static unsigned char *image_io_buf;
  127. static struct ufont_face *font_faces[BR_MAX_FACES];
  128. #define image_file_buf (image_io_buf)
  129. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  130. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  131. static struct inflate image_inflate_ws;
  132. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  133. #error "CSS scratch must fit in image_io_buf"
  134. #endif
  135. static char page_url[BR_URL_MAX];
  136. static char page_title[BR_TITLE_MAX];
  137. static char cwd[64];
  138. static int page_is_local;
  139. static int page_loading;
  140. static char status_text[BR_STATUS_MAX];
  141. static unsigned int status_until;
  142. static int status_error;
  143. static char history[BR_HISTORY][BR_URL_MAX];
  144. static int hist_len, hist_pos;
  145. static char click_url[BR_URL_MAX];
  146. static char pending_url[BR_URL_MAX];
  147. #define BR_POST_MAX 4096
  148. static char pending_post[BR_POST_MAX];
  149. static unsigned int pending_post_len;
  150. /* The pending navigation is a POST even when its body is empty (a form
  151. * without fields, e.g. the OIDC consent auto-submit). */
  152. static int pending_post_is;
  153. /* window "resize" bookkeeping: the page width the last event was for. */
  154. static int resize_sent_w = -1;
  155. static int resize_pending;
  156. static unsigned int pending_action;
  157. static int cancel_fetch;
  158. static int quit;
  159. static struct ngui_rect page_rect;
  160. static unsigned short *page_backbuf;
  161. static int pagebuf_w, pagebuf_h;
  162. static int page_cache_valid;
  163. static int page_cache_scroll;
  164. static unsigned int page_cache_nnode;
  165. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  166. static int layout_valid, layout_left, layout_right;
  167. /* Height of the page viewport: what html/body height:100% resolves to. */
  168. static int layout_view_h;
  169. static unsigned int layout_nnode;
  170. static int layout_content_h;
  171. /* layout output */
  172. struct lay_run {
  173. unsigned int off;
  174. unsigned short len;
  175. unsigned short gap;
  176. unsigned short color;
  177. unsigned short href;
  178. char lit[28];
  179. short img;
  180. signed short dy; /* inline image vertical offset */
  181. unsigned short iw, ih;
  182. unsigned short w;
  183. unsigned char font_px, bold, italic, mono, underline, strike;
  184. unsigned char overline, font_face;
  185. unsigned char transform_scale;
  186. unsigned char origin_x_kind, origin_y_kind;
  187. signed short scale_x, scale_y, rotate_x100;
  188. signed short origin_x, origin_y;
  189. unsigned char has_lit;
  190. unsigned int form; /* node + 1, 0 = not a control */
  191. unsigned char form_kind;
  192. unsigned char form_disabled;
  193. };
  194. struct lay {
  195. int draw;
  196. struct ngui *ui;
  197. int left, right;
  198. int y;
  199. int line_x, line_y, line_h;
  200. int line_left, line_right;
  201. int parent_top;
  202. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  203. int cb_h; /* definite content height of the containing block for
  204. * percentage heights; 0 = indefinite (auto) */
  205. int run_x;
  206. int align;
  207. int depth;
  208. int space_pending;
  209. unsigned char float_active;
  210. int float_left, float_right, float_bottom;
  211. struct lay_run runs[96];
  212. int nruns;
  213. };
  214. struct hit {
  215. int x, y, w, h;
  216. unsigned short node;
  217. };
  218. /* Live form state; the DOM attributes stay the initial/default value. */
  219. #define FORM_MAX 64
  220. #define FORM_VALUE_MAX 63
  221. enum {
  222. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  223. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  224. };
  225. struct form_state {
  226. unsigned int node;
  227. char value[FORM_VALUE_MAX + 1];
  228. unsigned char len, caret, checked, selected, used;
  229. };
  230. static struct form_state form_states[FORM_MAX];
  231. static unsigned int form_focus;
  232. static unsigned int form_dirty;
  233. static int form_descendant(unsigned int node, unsigned int form);
  234. static int form_submit_form(unsigned int node, int fire_event);
  235. static int link_fragment_nav(unsigned int node);
  236. static void history_push(const char *url);
  237. static void form_reset_event(unsigned int form);
  238. static unsigned int s_len(const char *s);
  239. static int s_eq(const char *a, const char *b);
  240. static void form_key(int k);
  241. static void form_click(unsigned int node);
  242. static void style_for_node(unsigned int node, struct br_style *out);
  243. static int form_disabled(unsigned int node)
  244. {
  245. struct br_node *n = &doc.nodes[node];
  246. if (n->attr_flags & BR_ATTR_DISABLED)
  247. return 1;
  248. return br_find_attr(&doc, node, "disabled") != 0;
  249. }
  250. static int form_kind_of(unsigned int node)
  251. {
  252. const char *type = br_type(&doc, node);
  253. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  254. return FORM_TEXTAREA;
  255. if (doc.nodes[node].tag == BR_TAG_SELECT)
  256. return FORM_SELECT;
  257. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  258. if (s_eq(type, "reset"))
  259. return FORM_RESET;
  260. if (s_eq(type, "button"))
  261. return FORM_BUTTON;
  262. return FORM_SUBMIT;
  263. }
  264. if (s_eq(type, "password"))
  265. return FORM_PASSWORD;
  266. if (s_eq(type, "checkbox"))
  267. return FORM_CHECKBOX;
  268. if (s_eq(type, "radio"))
  269. return FORM_RADIO;
  270. if (s_eq(type, "submit"))
  271. return FORM_SUBMIT;
  272. if (s_eq(type, "reset"))
  273. return FORM_RESET;
  274. if (s_eq(type, "button"))
  275. return FORM_BUTTON;
  276. return FORM_TEXT;
  277. }
  278. static unsigned int form_option_count(unsigned int node)
  279. {
  280. unsigned int c, n = 0;
  281. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  282. if (doc.nodes[c].type == BR_NODE_ELEM &&
  283. doc.nodes[c].tag == BR_TAG_OPTION)
  284. n++;
  285. return n;
  286. }
  287. static unsigned int form_option_selected(unsigned int node)
  288. {
  289. unsigned int c, i = 0;
  290. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  291. if (doc.nodes[c].type != BR_NODE_ELEM ||
  292. doc.nodes[c].tag != BR_TAG_OPTION)
  293. continue;
  294. if (br_find_attr(&doc, c, "selected"))
  295. return i;
  296. i++;
  297. }
  298. return 0;
  299. }
  300. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  301. char *out, unsigned int cap)
  302. {
  303. unsigned int c, i = 0;
  304. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  305. if (doc.nodes[c].type != BR_NODE_ELEM ||
  306. doc.nodes[c].tag != BR_TAG_OPTION)
  307. continue;
  308. if (i == idx)
  309. return br_text_content(&doc, c, out, cap);
  310. i++;
  311. }
  312. return 0;
  313. }
  314. static struct form_state *form_get(unsigned int node, int create)
  315. {
  316. struct form_state *slot = 0;
  317. unsigned int i;
  318. for (i = 0; i < FORM_MAX; i++) {
  319. if (form_states[i].used) {
  320. if (form_states[i].node == node)
  321. return &form_states[i];
  322. } else if (!slot) {
  323. slot = &form_states[i];
  324. }
  325. }
  326. if (!create || !slot)
  327. return 0;
  328. slot->node = node;
  329. slot->len = 0;
  330. slot->caret = 0;
  331. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  332. slot->selected = form_option_selected(node);
  333. slot->used = 1;
  334. {
  335. unsigned int n = 0;
  336. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  337. n = br_text_content(&doc, node, slot->value,
  338. FORM_VALUE_MAX + 1);
  339. } else {
  340. const char *v = br_value(&doc, node);
  341. if (v) {
  342. n = s_len(v);
  343. if (n > FORM_VALUE_MAX)
  344. n = FORM_VALUE_MAX;
  345. for (unsigned int j = 0; j < n; j++)
  346. slot->value[j] = v[j];
  347. }
  348. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  349. n = br_text_content(&doc, node, slot->value,
  350. FORM_VALUE_MAX + 1);
  351. }
  352. if (n > FORM_VALUE_MAX)
  353. n = FORM_VALUE_MAX;
  354. slot->value[n] = '\0';
  355. slot->len = (unsigned char)n;
  356. slot->caret = (unsigned char)n;
  357. }
  358. return slot;
  359. }
  360. static void form_reset_state(void)
  361. {
  362. unsigned int i;
  363. for (i = 0; i < FORM_MAX; i++)
  364. form_states[i].used = 0;
  365. form_focus = 0;
  366. }
  367. /* A <button> with element content (an icon <svg>/<img>, a <span> label)
  368. * is laid out like a normal element so that content shows; only a text or
  369. * empty button is drawn as a native control. Clicks still reach it
  370. * through the box hit test. */
  371. static int button_has_elements(unsigned int node)
  372. {
  373. unsigned int c;
  374. if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
  375. return 0;
  376. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  377. if (doc.nodes[c].type == BR_NODE_ELEM)
  378. return 1;
  379. return 0;
  380. }
  381. static int form_is_control(unsigned int node)
  382. {
  383. unsigned int tag;
  384. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  385. return 0;
  386. tag = doc.nodes[node].tag;
  387. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  388. tag == BR_TAG_SELECT ||
  389. (tag == BR_TAG_BUTTON && !button_has_elements(node));
  390. }
  391. #define HIT_MAX 96
  392. static struct hit hits[HIT_MAX];
  393. static int nhits;
  394. static unsigned short block_h[BR_MAX_NODES];
  395. /* Measure-pass top of each block, in the same document coordinates as
  396. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  397. * paint, so it cannot drive the lazy background loader). */
  398. static unsigned short block_top[BR_MAX_NODES];
  399. static char li_marker[BR_MAX_NODES][12];
  400. /* one connection object; the browser fetches one resource at a time */
  401. /* ---- tiny strings ---- */
  402. static unsigned int s_len(const char *s)
  403. {
  404. unsigned int n = 0;
  405. while (s && s[n])
  406. n++;
  407. return n;
  408. }
  409. static void s_copy(char *d, const char *s, unsigned int cap)
  410. {
  411. unsigned int i = 0;
  412. if (!cap)
  413. return;
  414. while (s && s[i] && i + 1 < cap) {
  415. d[i] = s[i];
  416. i++;
  417. }
  418. d[i] = '\0';
  419. }
  420. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  421. {
  422. while (s && *s && *n + 1 < cap)
  423. d[(*n)++] = *s++;
  424. d[*n] = '\0';
  425. }
  426. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  427. unsigned int cap)
  428. {
  429. char tmp[12];
  430. unsigned int i = 0, j;
  431. do {
  432. tmp[i++] = (char)('0' + v % 10);
  433. v /= 10;
  434. } while (v && i < sizeof(tmp));
  435. for (j = 0; j < i && *n + 1 < cap; j++)
  436. d[(*n)++] = tmp[i - 1 - j];
  437. d[*n] = '\0';
  438. }
  439. static int s_eq(const char *a, const char *b)
  440. {
  441. while (*a && *b) {
  442. if (*a != *b)
  443. return 0;
  444. a++;
  445. b++;
  446. }
  447. return *a == *b;
  448. }
  449. static int starts_with(const char *s, const char *p)
  450. {
  451. unsigned int i = 0;
  452. while (p[i]) {
  453. if (s[i] != p[i])
  454. return 0;
  455. i++;
  456. }
  457. return 1;
  458. }
  459. static int contains_ci(const char *s, const char *p)
  460. {
  461. unsigned int i, j;
  462. for (i = 0; s[i]; i++) {
  463. for (j = 0; p[j]; j++) {
  464. char a = s[i + j];
  465. if (a >= 'A' && a <= 'Z')
  466. a = (char)(a - 'A' + 'a');
  467. if (a != p[j])
  468. break;
  469. }
  470. if (!p[j])
  471. return 1;
  472. }
  473. return 0;
  474. }
  475. static char *trim(char *s)
  476. {
  477. unsigned int n;
  478. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  479. s++;
  480. n = s_len(s);
  481. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  482. s[n - 1] == '\r' || s[n - 1] == '\n'))
  483. s[--n] = '\0';
  484. return s;
  485. }
  486. /* ---- per-process heap ---- */
  487. static int heap_start(void)
  488. {
  489. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  490. if (!image_io_buf)
  491. return -1;
  492. page_backbuf = (unsigned short *)malloc(
  493. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  494. pagebuf_w = page_backbuf ? ui.w : 0;
  495. pagebuf_h = page_backbuf ? ui.h : 0;
  496. page_cache_valid = 0;
  497. return 0;
  498. }
  499. static void heap_clear(void)
  500. {
  501. memset(font_faces, 0, sizeof(font_faces));
  502. ngui_font_detach(&ui);
  503. svg_cache_clear();
  504. decode_arena = 0; /* lives in the page heap too */
  505. decode_arena_size = 0;
  506. heap_reset();
  507. /* The document arenas live in that heap; drop the stale pointers so
  508. * the next br_parse_plain() allocates fresh ones. */
  509. doc.nodes = 0;
  510. doc.text = 0;
  511. doc.attrs = 0;
  512. image_io_buf = 0;
  513. page_backbuf = 0;
  514. pagebuf_w = pagebuf_h = 0;
  515. page_cache_valid = 0;
  516. }
  517. static void browser_rules_alloc(void)
  518. {
  519. struct br_rule *rules;
  520. rules = (struct br_rule *)malloc(
  521. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  522. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  523. }
  524. /* ---- status ---- */
  525. static void set_status(const char *s, int err, unsigned int ttl_ms)
  526. {
  527. s_copy(status_text, s, sizeof(status_text));
  528. status_error = err;
  529. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  530. ngui_invalidate(&ui);
  531. }
  532. /* ---- JavaScript ---- */
  533. static int resolve_link(const char *base, const char *href, char *out,
  534. unsigned int cap);
  535. static char js_last_status[BR_STATUS_MAX];
  536. static int js_last_error;
  537. static void js_host_status(const char *msg, int error)
  538. {
  539. s_copy(js_last_status, msg, sizeof(js_last_status));
  540. js_last_error = error;
  541. set_status(msg, error, 6000);
  542. }
  543. static void js_host_report(const char *msg)
  544. {
  545. u_puts("[js] ");
  546. u_puts(msg);
  547. u_putc('\n');
  548. s_copy(js_last_status, msg, sizeof(js_last_status));
  549. js_last_error = 1;
  550. set_status(msg, 1, 8000);
  551. }
  552. static void js_host_navigate(const char *url)
  553. {
  554. char resolved[BR_URL_MAX];
  555. if (!url || !url[0])
  556. return;
  557. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  558. return;
  559. s_copy(pending_url, resolved, sizeof(pending_url));
  560. pending_action |= ACT_NAV;
  561. cancel_fetch = 1;
  562. }
  563. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  564. * back/forward between fragments): the page URL, address bar and history
  565. * follow, nothing is reloaded. `push` adds a history entry. */
  566. static int page_set_fragment(const char *url, int push)
  567. {
  568. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  569. return -1;
  570. s_copy(page_url, url, sizeof(page_url));
  571. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  572. url_in.len = s_len(url_in.text);
  573. url_in.cursor = url_in.len;
  574. url_in.scroll = 0;
  575. if (push)
  576. history_push(page_url);
  577. ngui_invalidate(&ui);
  578. return 0;
  579. }
  580. static int js_host_set_hash(const char *url)
  581. {
  582. return page_set_fragment(url, 1);
  583. }
  584. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  585. * the page, so a hash router can react). */
  586. static int same_doc_fragment(const char *url)
  587. {
  588. unsigned int a = 0, b = 0;
  589. if (!js_browser_active() || !url)
  590. return 0;
  591. while (url[a] && url[a] != '#')
  592. a++;
  593. while (page_url[b] && page_url[b] != '#')
  594. b++;
  595. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  596. !s_eq(url, page_url);
  597. }
  598. static void js_host_changed(void)
  599. {
  600. /* Class/style/attribute mutations change computed styles, not just the
  601. * text: drop the per-node style cache before the next layout. */
  602. br_reset_styles(&doc);
  603. layout_valid = 0;
  604. /* Script-built content (Angular's ng-repeat cards) brings new images
  605. * and inline background styles: rescan once the main loop is idle. */
  606. preload_rescan = 1;
  607. ngui_invalidate(&ui);
  608. }
  609. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  610. {
  611. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  612. return 0;
  613. *x = layout_boxes[node].x - page_rect.x;
  614. *y = layout_boxes[node].y - page_rect.y;
  615. *w = layout_boxes[node].w;
  616. *h = layout_boxes[node].h;
  617. return 1;
  618. }
  619. static void form_copy_out(const char *s, char *buf, int cap)
  620. {
  621. int i = 0;
  622. if (!buf || cap <= 0)
  623. return;
  624. while (s && s[i] && i + 1 < cap) {
  625. buf[i] = s[i];
  626. i++;
  627. }
  628. buf[i] = '\0';
  629. }
  630. static int js_host_form_value(unsigned int node, char *buf, int cap)
  631. {
  632. struct form_state *fs;
  633. int kind;
  634. if (!form_is_control(node))
  635. return 0;
  636. kind = form_kind_of(node);
  637. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  638. return 0;
  639. if (kind == FORM_SELECT) {
  640. char opt[64] = "";
  641. unsigned int c, i = 0;
  642. fs = form_get(node, 1);
  643. if (!fs)
  644. return 0;
  645. form_option_text(node, fs->selected, opt, sizeof(opt));
  646. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  647. if (doc.nodes[c].type != BR_NODE_ELEM ||
  648. doc.nodes[c].tag != BR_TAG_OPTION)
  649. continue;
  650. if (i == fs->selected) {
  651. const char *v = br_value(&doc, c);
  652. if (v && v[0])
  653. form_copy_out(v, buf, cap);
  654. else
  655. form_copy_out(opt, buf, cap);
  656. return 1;
  657. }
  658. i++;
  659. }
  660. form_copy_out(opt, buf, cap);
  661. return 1;
  662. }
  663. fs = form_get(node, 1);
  664. if (!fs)
  665. return 0;
  666. form_copy_out(fs->value, buf, cap);
  667. return 1;
  668. }
  669. static int js_host_form_checked(unsigned int node)
  670. {
  671. struct form_state *fs;
  672. int kind;
  673. if (!form_is_control(node))
  674. return -1;
  675. kind = form_kind_of(node);
  676. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  677. return -1;
  678. fs = form_get(node, 1);
  679. return fs ? fs->checked : 0;
  680. }
  681. static int js_host_form_selected(unsigned int node)
  682. {
  683. struct form_state *fs;
  684. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  685. return -1;
  686. fs = form_get(node, 1);
  687. return fs ? fs->selected : 0;
  688. }
  689. static int js_host_form_set_value(unsigned int node, const char *value)
  690. {
  691. struct form_state *fs;
  692. unsigned int n;
  693. if (!form_is_control(node))
  694. return 0;
  695. fs = form_get(node, 1);
  696. if (!fs)
  697. return 0;
  698. n = s_len(value ? value : "");
  699. if (n > FORM_VALUE_MAX)
  700. n = FORM_VALUE_MAX;
  701. for (unsigned int i = 0; i < n; i++)
  702. fs->value[i] = value[i];
  703. fs->value[n] = '\0';
  704. fs->len = (unsigned char)n;
  705. fs->caret = (unsigned char)n;
  706. layout_valid = 0;
  707. ngui_invalidate(&ui);
  708. return 1;
  709. }
  710. static int js_host_form_set_checked(unsigned int node, int checked)
  711. {
  712. struct form_state *fs;
  713. int kind;
  714. if (!form_is_control(node))
  715. return 0;
  716. kind = form_kind_of(node);
  717. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  718. return 0;
  719. fs = form_get(node, 1);
  720. if (!fs)
  721. return 0;
  722. fs->checked = (unsigned char)(checked != 0);
  723. layout_valid = 0;
  724. ngui_invalidate(&ui);
  725. return 1;
  726. }
  727. static int js_host_form_set_selected(unsigned int node, int index)
  728. {
  729. struct form_state *fs;
  730. unsigned int n;
  731. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  732. return 0;
  733. fs = form_get(node, 1);
  734. if (!fs)
  735. return 0;
  736. n = form_option_count(node);
  737. if (index < 0)
  738. index = 0;
  739. if (n && (unsigned int)index >= n)
  740. index = (int)n - 1;
  741. fs->selected = (unsigned char)index;
  742. layout_valid = 0;
  743. ngui_invalidate(&ui);
  744. return 1;
  745. }
  746. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  747. {
  748. unsigned int i;
  749. int n = 0;
  750. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  751. doc.nodes[form].tag != BR_TAG_FORM)
  752. return 0;
  753. for (i = 0; i < doc.nnode && n < cap; i++) {
  754. struct br_node *nd = &doc.nodes[i];
  755. if (i == form || nd->type != BR_NODE_ELEM)
  756. continue;
  757. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  758. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  759. continue;
  760. if (!form_descendant(i, form))
  761. continue;
  762. out[n++] = i;
  763. }
  764. return n;
  765. }
  766. static int js_host_form_submit(unsigned int form)
  767. {
  768. form_submit_form(form, 0);
  769. return 1;
  770. }
  771. static int js_host_form_reset(unsigned int form)
  772. {
  773. form_reset_event(form);
  774. return 1;
  775. }
  776. static void css_computed_name(const char *p, char *out, int cap)
  777. {
  778. int n = 0;
  779. for (; p && *p && n + 2 < cap; p++) {
  780. char c = *p;
  781. if (c >= 'A' && c <= 'Z') {
  782. out[n++] = '-';
  783. c = (char)(c - 'A' + 'a');
  784. } else if (c == '_') {
  785. c = '-';
  786. } else if (c >= 'a' && c <= 'z') {
  787. /* keep */
  788. }
  789. out[n++] = c;
  790. }
  791. out[n] = '\0';
  792. if (!strcmp(out, "css-float"))
  793. strcpy(out, "float");
  794. }
  795. static void css_rgb(unsigned short c, char *buf, int cap)
  796. {
  797. int r = ((c >> 11) & 31) * 255 / 31;
  798. int g = ((c >> 5) & 63) * 255 / 63;
  799. int b = (c & 31) * 255 / 31;
  800. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  801. }
  802. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  803. int font_px)
  804. {
  805. if (unit == 4) {
  806. snprintf(buf, cap, "auto");
  807. } else if (unit == 0) {
  808. snprintf(buf, cap, "%dpx", raw);
  809. } else if (unit == 1) {
  810. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  811. } else if (unit == 2) {
  812. /* Chrome's getComputedStyle() reports used pixel values. */
  813. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  814. } else if (unit == 3) {
  815. snprintf(buf, cap, "%dpx",
  816. (int)br_root_font_px() * raw / 100);
  817. } else {
  818. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  819. raw / 100, raw % 100, px);
  820. }
  821. }
  822. static int js_host_computed(unsigned int node, const char *property,
  823. char *buf, int cap)
  824. {
  825. struct br_style st;
  826. char name[40];
  827. if (!buf || cap <= 0 || node >= doc.nnode || node == 0)
  828. return 0;
  829. buf[0] = '\0';
  830. css_computed_name(property, name, sizeof(name));
  831. style_for_node(node, &st);
  832. if (!strcmp(name, "display")) {
  833. const char *v = "inline";
  834. if (st.display == BR_DISPLAY_BLOCK)
  835. v = "block";
  836. else if (st.display == BR_DISPLAY_NONE)
  837. v = "none";
  838. else if (st.display == BR_DISPLAY_FLEX)
  839. v = "flex";
  840. else if (st.display == BR_DISPLAY_GRID)
  841. v = "grid";
  842. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  843. v = "inline-block";
  844. snprintf(buf, cap, "%s", v);
  845. } else if (!strcmp(name, "position")) {
  846. static const char *pos[] = {
  847. "static", "absolute", "fixed", "relative", "sticky"
  848. };
  849. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  850. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  851. int is_w = name[0] == 'w';
  852. int kind = is_w ? st.width_kind : st.height_kind;
  853. int val = is_w ? st.width : st.height;
  854. if (kind == 3) {
  855. if (is_w)
  856. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  857. st.width_calc_pct / 100,
  858. st.width_calc_pct % 100,
  859. st.width_calc_px);
  860. else
  861. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  862. st.height_calc_pct / 100,
  863. st.height_calc_pct % 100,
  864. st.height_calc_px);
  865. } else if (kind == 1) {
  866. snprintf(buf, cap, "%dpx", val);
  867. } else if (kind == 2) {
  868. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  869. } else {
  870. snprintf(buf, cap, "auto");
  871. }
  872. } else if (!strcmp(name, "color") ||
  873. !strcmp(name, "background-color")) {
  874. if (!strcmp(name, "background-color") && !st.has_bg)
  875. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  876. else
  877. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  878. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  879. int is_fill = name[0] == 'f';
  880. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  881. if (mode == BR_PAINT_COLOR)
  882. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  883. else if (mode == BR_PAINT_CURRENT)
  884. css_rgb(st.color, buf, cap);
  885. else if (mode == BR_PAINT_UNSET && is_fill)
  886. snprintf(buf, cap, "rgb(0, 0, 0)");
  887. else if (mode == BR_PAINT_URL)
  888. snprintf(buf, cap, "url()");
  889. else
  890. snprintf(buf, cap, "none");
  891. } else if (!strcmp(name, "font-size")) {
  892. snprintf(buf, cap, "%dpx", st.font_px);
  893. } else if (!strcmp(name, "font-weight")) {
  894. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  895. } else if (!strcmp(name, "font-style")) {
  896. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  897. } else if (!strcmp(name, "font-family")) {
  898. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  899. br_font_face_family(st.font_face)[0])
  900. snprintf(buf, cap, "%s",
  901. br_font_face_family(st.font_face));
  902. else
  903. snprintf(buf, cap, "%s",
  904. st.mono ? "monospace" : "sans-serif");
  905. } else if (!strcmp(name, "text-align")) {
  906. static const char *al[] = { "left", "center", "right", "justify" };
  907. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  908. } else if (!strcmp(name, "float")) {
  909. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  910. st.float_left == 2 ? "right" : "none");
  911. } else if (!strcmp(name, "clear")) {
  912. static const char *cl[] = { "none", "left", "right", "both" };
  913. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  914. } else if (!strcmp(name, "opacity")) {
  915. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  916. } else if (!strcmp(name, "visibility")) {
  917. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  918. } else if (!strcmp(name, "overflow")) {
  919. snprintf(buf, cap, "%s",
  920. st.overflow_hidden ? "hidden" : "visible");
  921. } else if (!strcmp(name, "white-space")) {
  922. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  923. } else if (!strcmp(name, "text-transform")) {
  924. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  925. } else if (!strcmp(name, "box-sizing")) {
  926. snprintf(buf, cap, "%s",
  927. st.box_sizing ? "border-box" : "content-box");
  928. } else if (!strcmp(name, "line-height")) {
  929. if (st.line_h_px)
  930. snprintf(buf, cap, "%dpx", st.line_h_px);
  931. else if (st.line_h_pct)
  932. snprintf(buf, cap, "%d%%", st.line_h_pct);
  933. else
  934. snprintf(buf, cap, "normal");
  935. } else if (!strcmp(name, "z-index")) {
  936. if (st.z_set)
  937. snprintf(buf, cap, "%d", st.z_index);
  938. else
  939. snprintf(buf, cap, "auto");
  940. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  941. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  942. int set = name[0] == 't' ? st.top_set :
  943. name[0] == 'l' ? st.left_set :
  944. name[0] == 'r' ? st.right_set : st.bottom_set;
  945. int v = name[0] == 't' ? st.top :
  946. name[0] == 'l' ? st.left :
  947. name[0] == 'r' ? st.right : st.bottom;
  948. if (set)
  949. snprintf(buf, cap, "%dpx", v);
  950. else
  951. snprintf(buf, cap, "auto");
  952. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  953. !strcmp(name, "margin-bottom") ||
  954. !strcmp(name, "margin-left") ||
  955. !strcmp(name, "padding-top") ||
  956. !strcmp(name, "padding-right") ||
  957. !strcmp(name, "padding-bottom") ||
  958. !strcmp(name, "padding-left")) {
  959. int is_pad = name[0] == 'p';
  960. int side = name[strlen(name) - 1] == 'p' ? 0 :
  961. name[strlen(name) - 1] == 't' ? 1 :
  962. name[strlen(name) - 1] == 'm' ? 2 : 3;
  963. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  964. if (!strcmp(name, "margin-right") ||
  965. !strcmp(name, "padding-right"))
  966. side = 1;
  967. else if (!strcmp(name, "margin-bottom") ||
  968. !strcmp(name, "padding-bottom"))
  969. side = 2;
  970. else if (!strcmp(name, "margin-left") ||
  971. !strcmp(name, "padding-left"))
  972. side = 3;
  973. else
  974. side = 0;
  975. side += is_pad ? 4 : 0;
  976. css_mp_value(buf, cap,
  977. side == 0 ? st.mt : side == 1 ? st.mr :
  978. side == 2 ? st.mb : side == 3 ? st.ml :
  979. side == 4 ? st.pt : side == 5 ? st.pr :
  980. side == 6 ? st.pb : st.pl,
  981. st.mp_unit[side], st.mp_calc_px[side],
  982. st.font_px);
  983. } else if (!strcmp(name, "border-top-width") ||
  984. !strcmp(name, "border-right-width") ||
  985. !strcmp(name, "border-bottom-width") ||
  986. !strcmp(name, "border-left-width")) {
  987. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  988. name[7] == 'b' ? 2 : 3;
  989. snprintf(buf, cap, "%dpx", st.border_w[side]);
  990. } else if (!strcmp(name, "border-top-color") ||
  991. !strcmp(name, "border-right-color") ||
  992. !strcmp(name, "border-bottom-color") ||
  993. !strcmp(name, "border-left-color")) {
  994. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  995. name[7] == 'b' ? 2 : 3;
  996. if (st.border_w[side] && !st.border_t[side])
  997. css_rgb(st.border_c[side], buf, cap);
  998. else
  999. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1000. } else if (!strcmp(name, "background-image")) {
  1001. if (st.bg_image)
  1002. snprintf(buf, cap, "url(\"%s\")",
  1003. br_bg_image_url(st.bg_image - 1));
  1004. else
  1005. snprintf(buf, cap, "none");
  1006. } else if (!strcmp(name, "background-repeat")) {
  1007. static const char *rp[] = {
  1008. "repeat", "no-repeat", "repeat-x", "repeat-y"
  1009. };
  1010. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  1011. st.bg_repeat : 0]);
  1012. } else if (!strcmp(name, "background-position")) {
  1013. if (st.bg_pos_x_kind == 1)
  1014. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  1015. st.bg_pos_y);
  1016. else
  1017. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1018. st.bg_pos_y);
  1019. } else if (!strcmp(name, "background-size")) {
  1020. if (st.bg_size_kind == 3)
  1021. snprintf(buf, cap, "cover");
  1022. else if (st.bg_size_kind == 4)
  1023. snprintf(buf, cap, "contain");
  1024. else if (st.bg_size_kind == 1)
  1025. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1026. st.bg_size_h);
  1027. else if (st.bg_size_kind == 2)
  1028. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1029. st.bg_size_h);
  1030. else
  1031. snprintf(buf, cap, "auto");
  1032. } else if (!strcmp(name, "transform")) {
  1033. char tmp[128];
  1034. unsigned int n = 0;
  1035. if (!st.transform_set) {
  1036. snprintf(buf, cap, "none");
  1037. } else {
  1038. tmp[0] = '\0';
  1039. if (st.tx || st.ty) {
  1040. snprintf(tmp + n, sizeof(tmp) - n,
  1041. "translate(%dpx, %dpx)", st.tx, st.ty);
  1042. n = (unsigned int)strlen(tmp);
  1043. }
  1044. if (st.transform_scale) {
  1045. snprintf(tmp + n, sizeof(tmp) - n,
  1046. "%sscale(%d.%02d, %d.%02d)",
  1047. n ? " " : "", st.scale_x / 100,
  1048. st.scale_x % 100, st.scale_y / 100,
  1049. st.scale_y % 100);
  1050. n = (unsigned int)strlen(tmp);
  1051. if (st.rotate_x100) {
  1052. snprintf(tmp + n, sizeof(tmp) - n,
  1053. " rotate(%d.%02ddeg)",
  1054. st.rotate_x100 / 100,
  1055. st.rotate_x100 % 100);
  1056. }
  1057. } else if (st.rotate_x100) {
  1058. snprintf(tmp + n, sizeof(tmp) - n,
  1059. "%srotate(%d.%02ddeg)",
  1060. n ? " " : "", st.rotate_x100 / 100,
  1061. st.rotate_x100 % 100);
  1062. }
  1063. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1064. }
  1065. } else {
  1066. return 0;
  1067. }
  1068. return buf[0] != '\0';
  1069. }
  1070. static int js_host_click(unsigned int node)
  1071. {
  1072. char url[BR_URL_MAX];
  1073. const char *href;
  1074. if (node >= doc.nnode)
  1075. return 0;
  1076. if (form_is_control(node)) {
  1077. form_click(node); /* dispatches its own click event */
  1078. return 1;
  1079. }
  1080. /* element.click() fires a bubbling, cancelable click before the
  1081. * default action, like a real click (delegated list handlers). */
  1082. if (!js_browser_event(node, "click", 1, 1))
  1083. return 1;
  1084. if (link_fragment_nav(node))
  1085. return 1;
  1086. href = br_href(&doc, node);
  1087. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1088. return 0;
  1089. s_copy(pending_url, url, sizeof(pending_url));
  1090. pending_action |= ACT_NAV;
  1091. cancel_fetch = 1;
  1092. ngui_invalidate(&ui);
  1093. return 1;
  1094. }
  1095. static int fetch_script_text(const char *url, unsigned char **out,
  1096. unsigned int *outlen, char *err,
  1097. unsigned int errcap);
  1098. struct fetch_worker;
  1099. static struct fetch_worker *fetch_worker_alloc(void);
  1100. static void fetch_worker_release(struct fetch_worker *w);
  1101. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1102. unsigned int cap, const char *post,
  1103. unsigned int post_len, unsigned int node,
  1104. int bg, char *err, unsigned int errcap);
  1105. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1106. unsigned int errcap);
  1107. static int fetch_worker_read_body(struct fetch_worker *w,
  1108. unsigned char *plain,
  1109. unsigned int plaincap,
  1110. unsigned char *comp,
  1111. unsigned int compcap,
  1112. int *truncated, char *err,
  1113. unsigned int errcap);
  1114. static void fetch_workers_stop_all(void);
  1115. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1116. unsigned int cap, const char *method,
  1117. const char *ctype, const char *post,
  1118. unsigned int post_len, unsigned int node,
  1119. int bg, char *err, unsigned int errcap);
  1120. static int script_cache_has(const char *url);
  1121. static void script_cache_put(const char *url, const unsigned char *data,
  1122. unsigned int len);
  1123. static unsigned int script_cache_hash(const char *s);
  1124. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1125. unsigned int errcap);
  1126. static void fetch_workers_cancel_busy(void);
  1127. static void worker_wait_ui(void);
  1128. static int fetch_worker_status(const struct fetch_worker *w);
  1129. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1130. * module load: the wait must not pump input, or a click would dispatch DOM
  1131. * events into the middle of the running script. */
  1132. static int fetch_wait_passive;
  1133. static void script_error(const char *what, const char *url, const char *why)
  1134. {
  1135. char msg[192];
  1136. unsigned int n = 0;
  1137. s_append(msg, &n, what, sizeof(msg));
  1138. if (url && url[0]) {
  1139. s_append(msg, &n, " ", sizeof(msg));
  1140. s_append(msg, &n, url, sizeof(msg));
  1141. }
  1142. if (why && why[0]) {
  1143. s_append(msg, &n, ": ", sizeof(msg));
  1144. s_append(msg, &n, why, sizeof(msg));
  1145. }
  1146. js_host_report(msg);
  1147. }
  1148. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1149. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1150. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1151. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1152. #define JS_HTTP_POST_MAX (16u * 1024u)
  1153. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1154. static int js_worker_http(const char *method, const char *url,
  1155. const char *ctype, const char *body,
  1156. unsigned int body_len, struct js_http_resp *r,
  1157. char *err, int errcap);
  1158. static int js_host_http(const char *method, const char *url,
  1159. const char *ctype, const char *body,
  1160. unsigned int body_len, struct js_http_resp *r,
  1161. char *err, int errcap)
  1162. {
  1163. if (pending_action) {
  1164. s_copy(err, "page is navigating", (unsigned int)errcap);
  1165. return -1;
  1166. }
  1167. if (url[0] == '/') {
  1168. /* Local file: GET only. */
  1169. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1170. int rv;
  1171. if (!buf) {
  1172. s_copy(err, "out of memory", (unsigned int)errcap);
  1173. return -1;
  1174. }
  1175. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1176. (int)JS_HTTP_MAX);
  1177. r->status = rv < 0 ? 404 : 200;
  1178. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1179. buf[r->len] = '\0';
  1180. r->body = (char *)buf;
  1181. s_copy(r->url, url, sizeof(r->url));
  1182. if (contains_ci(url, ".json"))
  1183. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1184. return 0;
  1185. }
  1186. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1187. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1188. return -1;
  1189. }
  1190. if (body_len > JS_HTTP_POST_MAX) {
  1191. s_copy(err, "request body too large", (unsigned int)errcap);
  1192. return -1;
  1193. }
  1194. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1195. errcap);
  1196. }
  1197. /* Module source for the engine's loader: the boot script cache first, then
  1198. * one blocking fetch with input pumping disabled (the loader runs inside
  1199. * JavaScript). */
  1200. static char *js_host_load_script(const char *url, unsigned int *len)
  1201. {
  1202. unsigned char *data = 0;
  1203. char err[64];
  1204. int rv;
  1205. fetch_wait_passive++;
  1206. set_status("Loading module...", 0, 0);
  1207. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1208. fetch_wait_passive--;
  1209. if (rv != 0) {
  1210. script_error("Cannot load module", url,
  1211. rv == FETCH_ABORT ? "navigation" : err);
  1212. return 0;
  1213. }
  1214. return (char *)data;
  1215. }
  1216. /* Web Storage lives in /share, outside the page heap that every navigation
  1217. * resets: localStorage per origin for the boot, sessionStorage per origin
  1218. * and browser window. */
  1219. #define JS_ORIGIN_MAX 160
  1220. /* scheme://host[:port] of the page (a local page's whole path). */
  1221. static void js_page_origin(char *origin, unsigned int cap)
  1222. {
  1223. unsigned int i = 0, slashes = 0;
  1224. while (page_url[i] && i + 1 < cap) {
  1225. if (page_url[i] == '/' && ++slashes == 3)
  1226. break;
  1227. origin[i] = page_url[i];
  1228. i++;
  1229. }
  1230. origin[i] = '\0';
  1231. }
  1232. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1233. {
  1234. unsigned int n = 0;
  1235. s_append(out, &n, "/share/bls", cap);
  1236. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1237. }
  1238. static void js_storage_path(int kind, char *out, unsigned int cap)
  1239. {
  1240. char origin[JS_ORIGIN_MAX];
  1241. unsigned int n = 0;
  1242. js_page_origin(origin, sizeof(origin));
  1243. if (!kind) {
  1244. js_origin_path(origin, out, cap);
  1245. return;
  1246. }
  1247. s_append(out, &n, "/share/bss", cap);
  1248. if (kind) {
  1249. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1250. s_append(out, &n, "-", cap);
  1251. }
  1252. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1253. }
  1254. static void persist_mark_origin(const char *origin);
  1255. static int persist_store_lookup(const char *origin, char *out, int cap);
  1256. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1257. {
  1258. char path[48], origin[JS_ORIGIN_MAX];
  1259. int rv;
  1260. js_storage_path(kind, path, sizeof(path));
  1261. if (set) {
  1262. if (kind) {
  1263. if (!set[0] || !strcmp(set, "{}")) {
  1264. u_syscall1(SYS_UNLINK, (int)path);
  1265. return 0;
  1266. }
  1267. } else {
  1268. /* localStorage keeps an explicit "{}" rather than no
  1269. * file: a missing /share file means "not loaded from
  1270. * /data yet", and a cleared store must not come back
  1271. * from the disk copy before it is flushed. */
  1272. if (!set[0])
  1273. set = "{}";
  1274. js_page_origin(origin, sizeof(origin));
  1275. persist_mark_origin(origin);
  1276. }
  1277. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1278. (int)strlen(set)) < 0 ? -1 : 0;
  1279. }
  1280. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1281. if (rv < 0 && !kind) {
  1282. /* First use this boot: the persistent copy on /data. */
  1283. js_page_origin(origin, sizeof(origin));
  1284. rv = persist_store_lookup(origin, out, cap);
  1285. if (rv >= 0)
  1286. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1287. }
  1288. if (rv < 0)
  1289. return -1;
  1290. out[rv] = '\0';
  1291. return rv;
  1292. }
  1293. /* ---- persistence on /data ----
  1294. *
  1295. * /share is the working copy (RAM, shared by every helper and window); the
  1296. * installed disk's /data volume keeps the cookie jar and localStorage
  1297. * across reboots when it is mounted. The browser owns the disk copies: at
  1298. * start it restores the jar into /share, and its main loop writes back
  1299. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1300. * setItem updates costs one FAT write. The helpers only touch /share (they
  1301. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1302. * /data mount every disk access simply fails. Both files are plaintext
  1303. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1304. #define PERSIST_MS 3000u
  1305. #define SHARE_COOKIES "/share/bcookies"
  1306. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1307. #define DATA_STORE "/data/BSTORE.DAT"
  1308. #define DATA_STORE_MAGIC "NBLS1\n"
  1309. #define DATA_STORE_MAX (192u * 1024u)
  1310. #define PERSIST_DIRTY_MAX 8
  1311. static unsigned int persist_due;
  1312. static unsigned int cookie_sum_saved;
  1313. static int cookie_sum_valid;
  1314. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1315. static int persist_ndirty;
  1316. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1317. {
  1318. unsigned int h = 2166136261u, i;
  1319. for (i = 0; i < n; i++)
  1320. h = (h ^ p[i]) * 16777619u;
  1321. return h;
  1322. }
  1323. /* Called once at startup, before any helper runs. */
  1324. static void persist_restore(void)
  1325. {
  1326. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1327. int n;
  1328. if (!jar)
  1329. return;
  1330. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1331. (int)sizeof(struct uhttp_jar));
  1332. if (n != (int)sizeof(struct uhttp_jar)) {
  1333. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1334. (int)sizeof(struct uhttp_jar));
  1335. if (n == (int)sizeof(struct uhttp_jar)) {
  1336. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1337. (int)jar, n);
  1338. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1339. cookie_sum_valid = 1;
  1340. }
  1341. }
  1342. free(jar);
  1343. persist_due = u_ticks_ms() + PERSIST_MS;
  1344. }
  1345. static void persist_mark_origin(const char *origin)
  1346. {
  1347. int i;
  1348. for (i = 0; i < persist_ndirty; i++)
  1349. if (s_eq(persist_dirty[i], origin))
  1350. return;
  1351. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1352. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1353. }
  1354. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1355. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1356. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1357. unsigned int *o_off, unsigned int *o_len,
  1358. unsigned int *d_off, unsigned int *d_len,
  1359. unsigned int *rec_end)
  1360. {
  1361. unsigned int p = *pos, v = 0;
  1362. if (p >= len)
  1363. return 0;
  1364. *o_off = p;
  1365. while (p < len && buf[p] != '\n')
  1366. p++;
  1367. if (p >= len)
  1368. return 0;
  1369. *o_len = p - *o_off;
  1370. p++;
  1371. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1372. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1373. if (p >= len || buf[p] != '\n')
  1374. return 0;
  1375. p++;
  1376. if (v > len - p)
  1377. return 0;
  1378. *d_off = p;
  1379. *d_len = v;
  1380. p += v;
  1381. if (p < len && buf[p] == '\n')
  1382. p++;
  1383. *rec_end = p;
  1384. *pos = p;
  1385. return 1;
  1386. }
  1387. static int store_load(char **out)
  1388. {
  1389. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1390. int n;
  1391. *out = buf;
  1392. if (!buf)
  1393. return -1;
  1394. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1395. (int)DATA_STORE_MAX);
  1396. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1397. !starts_with(buf, DATA_STORE_MAGIC))
  1398. return 0;
  1399. return n;
  1400. }
  1401. static int persist_store_lookup(const char *origin, char *out, int cap)
  1402. {
  1403. char *buf;
  1404. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1405. unsigned int olen = s_len(origin);
  1406. int n = store_load(&buf), rv = -1;
  1407. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1408. &dl, &e)) {
  1409. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1410. if ((int)dl < cap) {
  1411. memcpy(out, buf + d, dl);
  1412. out[dl] = '\0';
  1413. rv = (int)dl;
  1414. }
  1415. break;
  1416. }
  1417. }
  1418. free(buf);
  1419. return rv;
  1420. }
  1421. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1422. static void persist_store_flush(void)
  1423. {
  1424. char *old, *nb, path[48];
  1425. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1426. int n = store_load(&old), i, w;
  1427. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1428. if (n < 0 || !nb) {
  1429. free(old);
  1430. free(nb);
  1431. return;
  1432. }
  1433. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1434. /* Untouched origins first, in their old order. */
  1435. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1436. &dl, &e)) {
  1437. int dirty = 0;
  1438. for (i = 0; i < persist_ndirty; i++)
  1439. if (s_len(persist_dirty[i]) == ol &&
  1440. !memcmp(persist_dirty[i], old + oo, ol))
  1441. dirty = 1;
  1442. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1443. continue;
  1444. memcpy(nb + nn, old + oo, e - oo);
  1445. nn += e - oo;
  1446. }
  1447. /* Then the changed ones (an emptied store is dropped). */
  1448. for (i = 0; i < persist_ndirty; i++) {
  1449. char num[12];
  1450. unsigned int k = 0;
  1451. js_origin_path(persist_dirty[i], path, sizeof(path));
  1452. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1453. (int)DATA_STORE_MAX);
  1454. if (w <= 2) /* missing or "{}" */
  1455. continue;
  1456. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1457. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1458. DATA_STORE_MAX) {
  1459. set_status("Saved site data is full; a site's "
  1460. "localStorage was not saved", 1, 6000);
  1461. continue;
  1462. }
  1463. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1464. nb[nn++] = '\n';
  1465. s_append(nb, &nn, num, DATA_STORE_MAX);
  1466. nb[nn++] = '\n';
  1467. memcpy(nb + nn, old, (unsigned int)w);
  1468. nn += (unsigned int)w;
  1469. nb[nn++] = '\n';
  1470. }
  1471. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1472. persist_ndirty = 0;
  1473. free(old);
  1474. free(nb);
  1475. }
  1476. static void persist_cookies_flush(void)
  1477. {
  1478. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1479. unsigned int sum;
  1480. int n;
  1481. if (!jar)
  1482. return;
  1483. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1484. (int)sizeof(struct uhttp_jar));
  1485. if (n == (int)sizeof(struct uhttp_jar)) {
  1486. sum = persist_sum(jar, (unsigned int)n);
  1487. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1488. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1489. (int)jar, n) >= 0) {
  1490. cookie_sum_saved = sum;
  1491. cookie_sum_valid = 1;
  1492. }
  1493. }
  1494. }
  1495. free(jar);
  1496. }
  1497. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1498. static void persist_tick(void)
  1499. {
  1500. unsigned int now = u_ticks_ms();
  1501. if ((int)(now - persist_due) < 0)
  1502. return;
  1503. persist_due = now + PERSIST_MS;
  1504. persist_cookies_flush();
  1505. if (persist_ndirty)
  1506. persist_store_flush();
  1507. }
  1508. /* <link rel="modulepreload">: download the page's module graph on all
  1509. * helpers at once into the boot script cache, before any script runs. The
  1510. * engine's module loader is sequential (one blocking fetch per import), so
  1511. * without this a Vite app with a dozen chunks pays every round trip in a
  1512. * row. Failures are ignored; the loader fetches what is missing. */
  1513. #define MODULE_PRELOAD_MAX 24
  1514. static void prefetch_module_preloads(void)
  1515. {
  1516. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1517. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1518. unsigned int count = 0, next = 0, done = 0, i;
  1519. char err[64];
  1520. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1521. struct br_node *nd = &doc.nodes[i];
  1522. const char *rel, *href;
  1523. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1524. continue;
  1525. rel = br_rel(&doc, i);
  1526. href = br_href(&doc, i);
  1527. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1528. continue;
  1529. if (resolve_link(page_url, href, urls[count],
  1530. sizeof(urls[count])) != 0 ||
  1531. urls[count][0] == '/' || script_cache_has(urls[count]))
  1532. continue;
  1533. slot[count++] = 0;
  1534. }
  1535. if (!count)
  1536. return;
  1537. set_status("Loading modules...", 0, 0);
  1538. while (done < count) {
  1539. struct fetch_worker *w;
  1540. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1541. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1542. 0, 0, 0, err,
  1543. sizeof(err)) != 0) {
  1544. fetch_worker_release(w);
  1545. done++;
  1546. } else {
  1547. slot[next] = w;
  1548. }
  1549. next++;
  1550. }
  1551. worker_wait_ui();
  1552. if (cancel_fetch || pending_action) {
  1553. fetch_workers_cancel_busy();
  1554. return;
  1555. }
  1556. for (i = 0; i < next; i++) {
  1557. unsigned char *body;
  1558. int rv, tr = 0;
  1559. if (!slot[i])
  1560. continue;
  1561. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1562. if (rv == 0)
  1563. continue;
  1564. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1565. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1566. if (body) {
  1567. rv = fetch_worker_read_body(slot[i], body,
  1568. BR_SCRIPT_MAX, image_io_buf,
  1569. BR_PAGE_COMP_MAX, &tr, err,
  1570. sizeof(err));
  1571. if (rv > 0 && !tr)
  1572. script_cache_put(urls[i], body,
  1573. (unsigned int)rv);
  1574. free(body);
  1575. }
  1576. fetch_worker_release(slot[i]);
  1577. slot[i] = 0;
  1578. done++;
  1579. }
  1580. u_sleep_ms(10);
  1581. }
  1582. }
  1583. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1584. * submitted to helper workers ahead of time, but scripts still execute in
  1585. * document order. */
  1586. #define SCRIPT_INLINE 0
  1587. #define SCRIPT_LOCAL 1
  1588. #define SCRIPT_REMOTE 2
  1589. #define SCRIPT_ERROR 3
  1590. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1591. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1592. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1593. static void script_submit_window(unsigned int *next, char *err,
  1594. unsigned int errcap)
  1595. {
  1596. while (*next < doc.nscripts) {
  1597. struct fetch_worker *w;
  1598. if (script_kind[*next] != SCRIPT_REMOTE) {
  1599. (*next)++;
  1600. continue;
  1601. }
  1602. w = fetch_worker_alloc();
  1603. if (!w)
  1604. return;
  1605. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1606. 0, 0, 0, 0, err, errcap) != 0) {
  1607. fetch_worker_release(w);
  1608. script_kind[*next] = SCRIPT_ERROR;
  1609. (*next)++;
  1610. continue;
  1611. }
  1612. script_slot[*next] = w;
  1613. (*next)++;
  1614. }
  1615. }
  1616. /* Run the page's scripts in document order. External bodies are prefetched
  1617. * in parallel so downloading script N+1 overlaps executing script N; inline
  1618. * bodies are copied because the engine needs NUL-terminated text. */
  1619. static void run_page_scripts(void)
  1620. {
  1621. struct js_browser_host host;
  1622. unsigned int i, next = 0;
  1623. char err[64], ferr[64];
  1624. if (!doc.nscripts)
  1625. return;
  1626. host.status = js_host_status;
  1627. host.report = js_host_report;
  1628. host.navigate = js_host_navigate;
  1629. host.changed = js_host_changed;
  1630. host.rect = js_host_rect;
  1631. host.form_value = js_host_form_value;
  1632. host.form_checked = js_host_form_checked;
  1633. host.form_selected = js_host_form_selected;
  1634. host.form_set_value = js_host_form_set_value;
  1635. host.form_set_checked = js_host_form_set_checked;
  1636. host.form_set_selected = js_host_form_set_selected;
  1637. host.form_elements = js_host_form_elements;
  1638. host.form_submit = js_host_form_submit;
  1639. host.form_reset = js_host_form_reset;
  1640. host.click = js_host_click;
  1641. host.computed = js_host_computed;
  1642. host.http = js_host_http;
  1643. host.load_script = js_host_load_script;
  1644. host.storage = js_host_storage;
  1645. host.set_hash = js_host_set_hash;
  1646. host.page_url = page_url;
  1647. host.width = ui.w;
  1648. host.height = ui.h;
  1649. if (js_browser_start(&doc, &host) != 0) {
  1650. js_host_status("JavaScript: out of memory", 1);
  1651. return;
  1652. }
  1653. resize_sent_w = -1;
  1654. resize_pending = 0;
  1655. prefetch_module_preloads();
  1656. for (i = 0; i < doc.nscripts; i++) {
  1657. struct br_script *script = &doc.scripts[i];
  1658. const char *src_attr = script->src_off ?
  1659. doc.attrs + script->src_off : "";
  1660. script_slot[i] = 0;
  1661. if (!script->src_off) {
  1662. script_kind[i] = SCRIPT_INLINE;
  1663. continue;
  1664. }
  1665. if (!src_attr[0] ||
  1666. resolve_link(page_url, src_attr, script_urls[i],
  1667. sizeof(script_urls[i])) != 0) {
  1668. script_urls[i][0] = '\0';
  1669. script_kind[i] = SCRIPT_ERROR;
  1670. continue;
  1671. }
  1672. if (script_urls[i][0] == '/' ||
  1673. script_cache_has(script_urls[i]))
  1674. script_kind[i] = SCRIPT_LOCAL;
  1675. else
  1676. script_kind[i] = SCRIPT_REMOTE;
  1677. }
  1678. script_submit_window(&next, ferr, sizeof(ferr));
  1679. for (i = 0; i < doc.nscripts; i++) {
  1680. struct br_script *script = &doc.scripts[i];
  1681. if (script_kind[i] == SCRIPT_INLINE) {
  1682. unsigned int off = script->off;
  1683. unsigned int len = script->len;
  1684. unsigned int k;
  1685. char *src = (char *)malloc(len + 1);
  1686. if (!src) {
  1687. js_host_status("JavaScript: out of memory", 1);
  1688. break;
  1689. }
  1690. for (k = 0; k < len; k++)
  1691. src[k] = doc.script_src[off + k];
  1692. src[len] = '\0';
  1693. if (script->module) {
  1694. /* A distinct module name per inline module
  1695. * (QuickJS registers modules by name); the
  1696. * fragment keeps relative imports resolving
  1697. * against the page. */
  1698. char mname[BR_URL_MAX + 16];
  1699. unsigned int mn = 0;
  1700. s_append(mname, &mn, page_url, sizeof(mname));
  1701. s_append(mname, &mn, "#module", sizeof(mname));
  1702. s_append_dec(mname, &mn, i, sizeof(mname));
  1703. js_browser_run_module(src, mname);
  1704. } else {
  1705. js_browser_run(src, page_url);
  1706. }
  1707. free(src);
  1708. } else if (script->src_off) {
  1709. const char *src_attr = doc.attrs + script->src_off;
  1710. if (script_kind[i] == SCRIPT_ERROR) {
  1711. script_error("Cannot load script", src_attr,
  1712. script_urls[i][0] ?
  1713. "network busy" :
  1714. "unsupported URL");
  1715. continue;
  1716. }
  1717. if (script_kind[i] == SCRIPT_LOCAL) {
  1718. unsigned char *data = 0;
  1719. unsigned int len = 0;
  1720. int rv;
  1721. set_status("Loading script...", 0, 0);
  1722. rv = fetch_script_text(script_urls[i], &data,
  1723. &len, err, sizeof(err));
  1724. if (rv == FETCH_ABORT)
  1725. break;
  1726. if (rv != 0) {
  1727. script_error("Cannot load script",
  1728. script_urls[i], err);
  1729. continue;
  1730. }
  1731. if (script->module)
  1732. js_browser_run_module(
  1733. (const char *)data,
  1734. script_urls[i]);
  1735. else
  1736. js_browser_run((const char *)data,
  1737. script_urls[i]);
  1738. free(data);
  1739. } else {
  1740. struct fetch_worker *w = script_slot[i];
  1741. unsigned char *body = 0;
  1742. int tr = 0, rv;
  1743. if (!w) {
  1744. w = fetch_worker_alloc();
  1745. if (!w)
  1746. continue;
  1747. if (fetch_worker_submit(w,
  1748. script_urls[i],
  1749. BR_SCRIPT_MAX,
  1750. 0, 0, 0, 0, err,
  1751. sizeof(err)) != 0) {
  1752. fetch_worker_release(w);
  1753. script_kind[i] = SCRIPT_ERROR;
  1754. if (i == next)
  1755. next++;
  1756. continue;
  1757. }
  1758. script_slot[i] = w;
  1759. if (i == next)
  1760. next++;
  1761. }
  1762. set_status("Loading script...", 0, 0);
  1763. rv = fetch_worker_wait(w, err, sizeof(err));
  1764. if (rv == FETCH_ABORT) {
  1765. fetch_workers_stop_all();
  1766. break;
  1767. }
  1768. /* The body gets its own buffer (scripts are up
  1769. * to 2 MB); image_io_buf takes the gzip
  1770. * stream. */
  1771. body = rv == 0 ? (unsigned char *)malloc(
  1772. BR_SCRIPT_MAX + 1) : 0;
  1773. if (body)
  1774. rv = fetch_worker_read_body(w, body,
  1775. BR_SCRIPT_MAX, image_io_buf,
  1776. BR_PAGE_COMP_MAX, &tr, err,
  1777. sizeof(err));
  1778. else {
  1779. if (rv == 0)
  1780. s_copy(err, "out of memory",
  1781. sizeof(err));
  1782. rv = -1;
  1783. }
  1784. fetch_worker_release(w);
  1785. script_slot[i] = 0;
  1786. script_submit_window(&next, ferr, sizeof(ferr));
  1787. if (rv <= 0)
  1788. script_error("Cannot load script",
  1789. script_urls[i], err);
  1790. else if (tr || (unsigned int)rv >=
  1791. BR_SCRIPT_MAX)
  1792. script_error("Cannot load script",
  1793. script_urls[i],
  1794. "script is too large");
  1795. else {
  1796. body[rv] = '\0';
  1797. script_cache_put(script_urls[i], body,
  1798. (unsigned int)rv);
  1799. if (script->module)
  1800. js_browser_run_module(
  1801. (const char *)body,
  1802. script_urls[i]);
  1803. else
  1804. js_browser_run(
  1805. (const char *)body,
  1806. script_urls[i]);
  1807. }
  1808. free(body);
  1809. }
  1810. }
  1811. if (pending_action)
  1812. break;
  1813. }
  1814. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  1815. * load_home() stop it before the next navigation. */
  1816. if (doc.scripts_truncated && !js_last_error)
  1817. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  1818. 1);
  1819. }
  1820. /* ---- images ---- */
  1821. static void image_reset(void)
  1822. {
  1823. int i;
  1824. for (i = 0; i < BR_MAX_IMAGES; i++) {
  1825. images[i].state = 0;
  1826. images[i].native_w = images[i].native_h = 0;
  1827. images[i].err[0] = '\0';
  1828. }
  1829. image_count = 0;
  1830. image_pixels = 0;
  1831. preload_active = 0;
  1832. preload_pending = 0;
  1833. preload_wait = 0;
  1834. preload_node = 0;
  1835. preload_loaded = 0;
  1836. }
  1837. /* Decode into the shared arena, then copy/scale the result into a display
  1838. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  1839. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  1840. * pixels. Transparent edges are composited over white. */
  1841. /* One decode scratch arena per page, reused across images. Allocating and
  1842. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  1843. * each small display bitmap landed in the hole the previous arena left, so
  1844. * the next arena no longer fit and the heap ratcheted up until an app
  1845. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  1846. * still released right after their one image. */
  1847. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  1848. static unsigned char *decode_arena_get(unsigned int bytes)
  1849. {
  1850. if (decode_arena && decode_arena_size >= bytes)
  1851. return decode_arena;
  1852. free(decode_arena);
  1853. decode_arena = (unsigned char *)malloc(bytes);
  1854. decode_arena_size = decode_arena ? bytes : 0;
  1855. return decode_arena;
  1856. }
  1857. static void decode_arena_put(void)
  1858. {
  1859. if (decode_arena_size > DECODE_ARENA_KEEP) {
  1860. free(decode_arena);
  1861. decode_arena = 0;
  1862. decode_arena_size = 0;
  1863. }
  1864. }
  1865. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  1866. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  1867. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  1868. static int svg_text_sniff(const unsigned char *d, unsigned int len);
  1869. static int svg_decode_image(const unsigned char *data, unsigned int len,
  1870. struct br_image *bi, int box_w, int box_h);
  1871. static int decode_image_data(const unsigned char *data, unsigned int len,
  1872. struct br_image *bi, int box_w, int box_h)
  1873. {
  1874. struct img_info info;
  1875. struct img_options opt;
  1876. struct img_mem mem;
  1877. struct img_image decoded;
  1878. unsigned char *arena;
  1879. unsigned int est, bytes, i;
  1880. unsigned short *px;
  1881. unsigned char *alpha = 0;
  1882. int dw, dh, r;
  1883. bi->url_hash = 0;
  1884. if (img_sniff(data, len, &info) != 0) {
  1885. if (svg_text_sniff(data, len))
  1886. return svg_decode_image(data, len, bi, box_w, box_h);
  1887. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  1888. return -1;
  1889. }
  1890. est = img_estimate(&info);
  1891. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  1892. s_copy(bi->err, "image too large", sizeof(bi->err));
  1893. return -1;
  1894. }
  1895. arena = decode_arena_get(est);
  1896. if (!arena) {
  1897. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1898. return -1;
  1899. }
  1900. img_mem_init(&mem, arena, est);
  1901. opt.max_pixels = BR_IMG_PIX_MAX;
  1902. r = img_decode(data, len, &opt, &mem, &decoded);
  1903. if (r != 0) {
  1904. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  1905. goto fail;
  1906. }
  1907. if (decoded.w == 0 || decoded.h == 0) {
  1908. s_copy(bi->err, "empty image", sizeof(bi->err));
  1909. goto fail;
  1910. }
  1911. bi->native_w = (int)decoded.w;
  1912. bi->native_h = (int)decoded.h;
  1913. dw = (int)decoded.w;
  1914. dh = (int)decoded.h;
  1915. if (box_w > 0 && box_h > 0) {
  1916. /* cover: scale so both box sides are filled, never up */
  1917. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  1918. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  1919. unsigned int sc = sw > sh ? sw : sh;
  1920. if (sc < 0x10000u) {
  1921. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  1922. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  1923. }
  1924. }
  1925. if (dw > BR_IMG_LAYOUT_W) {
  1926. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  1927. dw = BR_IMG_LAYOUT_W;
  1928. }
  1929. if (dh < 1)
  1930. dh = 1;
  1931. if (dw < 1)
  1932. dw = 1;
  1933. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  1934. BR_IMG_PIXEL_BUDGET) {
  1935. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  1936. goto fail;
  1937. }
  1938. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  1939. px = (unsigned short *)malloc(bytes);
  1940. if (!px) {
  1941. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1942. goto fail;
  1943. }
  1944. /* Keep the alpha plane for the scaled image so transparent logos and
  1945. * icons composite over the page instead of the browser's dark theme
  1946. * background. Very large alpha images stay flattened to bound the
  1947. * heap use. */
  1948. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  1949. alpha = (unsigned char *)malloc((unsigned int)dw *
  1950. (unsigned int)dh);
  1951. if (alpha) {
  1952. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1953. alpha[i] = 255;
  1954. }
  1955. }
  1956. /* With an alpha plane the colour under transparent pixels only shows
  1957. * through partially covered edge pixels of the downscale: use white,
  1958. * as documented above, not the dark browser theme (which left a dark
  1959. * fringe around scaled app icons). */
  1960. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1961. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  1962. {
  1963. struct img_blit b;
  1964. b.dst = px;
  1965. b.dst_w = dw;
  1966. b.dst_h = dh;
  1967. b.clip_x = 0;
  1968. b.clip_y = 0;
  1969. b.clip_w = dw;
  1970. b.clip_h = dh;
  1971. b.x = 0;
  1972. b.y = 0;
  1973. b.scale = ((unsigned int)dw << 16) / decoded.w;
  1974. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  1975. b.bg2 = b.bg;
  1976. b.dst_a = alpha;
  1977. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  1978. img_draw(&decoded, &b);
  1979. }
  1980. bi->img.format = decoded.format;
  1981. bi->img.w = (unsigned int)dw;
  1982. bi->img.h = (unsigned int)dh;
  1983. bi->img.px = px;
  1984. bi->img.alpha = alpha;
  1985. bi->img.flags = 0;
  1986. bi->state = 1;
  1987. image_pixels += (unsigned int)dw * (unsigned int)dh;
  1988. decode_arena_put();
  1989. return 0;
  1990. fail:
  1991. decode_arena_put();
  1992. return -1;
  1993. }
  1994. /* ---- URL / local path handling ---- */
  1995. static int is_http(const char *s)
  1996. {
  1997. return starts_with(s, "http://") || starts_with(s, "https://");
  1998. }
  1999. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  2000. static int normalize_abs(const char *in, char *out, unsigned int cap)
  2001. {
  2002. char seg[64];
  2003. unsigned int i = 0, o = 1;
  2004. int depth = 0;
  2005. int trailing;
  2006. if (!in || in[0] != '/' || cap < 2)
  2007. return -1;
  2008. trailing = 0;
  2009. {
  2010. unsigned int n = s_len(in);
  2011. if (n > 1 && in[n - 1] == '/')
  2012. trailing = 1;
  2013. }
  2014. out[0] = '/';
  2015. while (in[i]) {
  2016. unsigned int n = 0;
  2017. while (in[i] == '/')
  2018. i++;
  2019. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  2020. if (n + 1 < sizeof(seg))
  2021. seg[n++] = in[i];
  2022. i++;
  2023. }
  2024. seg[n] = '\0';
  2025. if (n == 0)
  2026. break;
  2027. if (s_eq(seg, "."))
  2028. continue;
  2029. if (s_eq(seg, "..")) {
  2030. if (depth > 0) {
  2031. while (o > 1 && out[o - 1] != '/')
  2032. o--;
  2033. if (o > 1)
  2034. o--;
  2035. depth--;
  2036. }
  2037. continue;
  2038. }
  2039. if (o > 1) {
  2040. if (o + 1 >= cap)
  2041. return -1;
  2042. out[o++] = '/';
  2043. }
  2044. if (o + n + 1 >= cap)
  2045. return -1;
  2046. {
  2047. unsigned int j;
  2048. for (j = 0; j < n; j++)
  2049. out[o++] = seg[j];
  2050. }
  2051. depth++;
  2052. }
  2053. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2054. if (o + 1 >= cap)
  2055. return -1;
  2056. out[o++] = '/';
  2057. }
  2058. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2059. if (in[i] == '?' || in[i] == '#') {
  2060. while (in[i]) {
  2061. if (o + 1 >= cap)
  2062. return -1;
  2063. out[o++] = in[i++];
  2064. }
  2065. }
  2066. out[o] = '\0';
  2067. return 0;
  2068. }
  2069. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2070. {
  2071. char joined[BR_URL_MAX];
  2072. if (!in || !in[0]) {
  2073. s_copy(out, cwd[0] ? cwd : "/", cap);
  2074. return;
  2075. }
  2076. if (in[0] == '/') {
  2077. if (normalize_abs(in, out, cap) != 0)
  2078. s_copy(out, in, cap);
  2079. return;
  2080. }
  2081. {
  2082. unsigned int n = 0;
  2083. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2084. s_append(joined, &n, "/", sizeof(joined));
  2085. s_append(joined, &n, in, sizeof(joined));
  2086. }
  2087. if (normalize_abs(joined, out, cap) != 0)
  2088. s_copy(out, joined, cap);
  2089. }
  2090. /* ---- canonical origin cache ---- *
  2091. *
  2092. * Sites commonly redirect http://host to https://host and then to
  2093. * https://www.host. Remember the final scheme/host of the last navigation so
  2094. * a bare domain typed again goes straight there instead of paying for two
  2095. * more connections and TLS handshakes. Only default-port requests are
  2096. * rewritten; explicit ports are left alone. */
  2097. #define ORIGIN_CACHE_MAX 8
  2098. #define ORIGIN_FILE "/share/borigins"
  2099. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2100. UHTTP_HOST_MAX + 2))
  2101. struct origin_cache_entry {
  2102. char host[UHTTP_HOST_MAX];
  2103. char origin[UHTTP_HOST_MAX + 16];
  2104. };
  2105. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2106. static int origin_count;
  2107. static char origin_buf[ORIGIN_BUF_SIZE];
  2108. static int default_port(const struct uhttp_url *u)
  2109. {
  2110. return u->secure ? u->port == 443 : u->port == 80;
  2111. }
  2112. static void url_origin(const struct uhttp_url *u, char *out,
  2113. unsigned int cap)
  2114. {
  2115. unsigned int n = 0;
  2116. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2117. s_append(out, &n, u->host, cap);
  2118. if (!default_port(u)) {
  2119. s_append(out, &n, ":", cap);
  2120. s_append_dec(out, &n, u->port, cap);
  2121. }
  2122. }
  2123. static void origin_cache_apply(char *url, unsigned int cap)
  2124. {
  2125. struct uhttp_url u;
  2126. char out[BR_URL_MAX];
  2127. unsigned int n = 0;
  2128. int i;
  2129. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2130. return;
  2131. for (i = 0; i < origin_count; i++) {
  2132. if (!s_eq(u.host, origins[i].host))
  2133. continue;
  2134. s_append(out, &n, origins[i].origin, sizeof(out));
  2135. s_append(out, &n, u.path, sizeof(out));
  2136. s_copy(url, out, cap);
  2137. return;
  2138. }
  2139. }
  2140. static void origin_cache_save(void)
  2141. {
  2142. unsigned int n = 0;
  2143. int i;
  2144. for (i = 0; i < origin_count; i++) {
  2145. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2146. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2147. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2148. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2149. }
  2150. if (n)
  2151. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2152. (int)origin_buf, (int)n);
  2153. }
  2154. static void origin_cache_load(void)
  2155. {
  2156. char *p;
  2157. int rn;
  2158. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2159. (int)(sizeof(origin_buf) - 1));
  2160. if (rn <= 0)
  2161. return;
  2162. origin_buf[rn] = '\0';
  2163. p = origin_buf;
  2164. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2165. char *line = p, *origin;
  2166. while (*p && *p != '\n')
  2167. p++;
  2168. if (*p)
  2169. *p++ = '\0';
  2170. if (!line[0])
  2171. continue;
  2172. origin = line;
  2173. while (*origin && *origin != ' ')
  2174. origin++;
  2175. if (!*origin)
  2176. continue;
  2177. *origin++ = '\0';
  2178. if (!line[0] || !is_http(origin))
  2179. continue;
  2180. {
  2181. struct uhttp_url uo;
  2182. if (uhttp_parse_url(origin, &uo) != 0 ||
  2183. !s_eq(uo.path, "/"))
  2184. continue;
  2185. }
  2186. s_copy(origins[origin_count].host, line,
  2187. sizeof(origins[origin_count].host));
  2188. s_copy(origins[origin_count].origin, origin,
  2189. sizeof(origins[origin_count].origin));
  2190. origin_count++;
  2191. }
  2192. }
  2193. static int host_is_www_of(const char *host, const char *base)
  2194. {
  2195. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2196. host[3] == '.' && s_eq(host + 4, base);
  2197. }
  2198. static void origin_cache_learn(const char *requested, const char *final)
  2199. {
  2200. struct uhttp_url from, to;
  2201. char origin[UHTTP_HOST_MAX + 16];
  2202. int i;
  2203. if (!is_http(requested) || !is_http(final))
  2204. return;
  2205. if (uhttp_parse_url(requested, &from) != 0 ||
  2206. uhttp_parse_url(final, &to) != 0)
  2207. return;
  2208. if (!default_port(&from))
  2209. return;
  2210. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2211. from.port == to.port)
  2212. return;
  2213. /* Only remember origin-level canonicalisation: the same path, and
  2214. * either the same host or its www./apex sibling. A path- or
  2215. * host-specific redirect (a shortener, a login page) must not poison
  2216. * every request to the typed host. */
  2217. if (!s_eq(from.path, to.path))
  2218. return;
  2219. if (!s_eq(from.host, to.host) &&
  2220. !host_is_www_of(to.host, from.host) &&
  2221. !host_is_www_of(from.host, to.host))
  2222. return;
  2223. url_origin(&to, origin, sizeof(origin));
  2224. for (i = 0; i < origin_count; i++) {
  2225. if (s_eq(origins[i].host, from.host)) {
  2226. if (!s_eq(origins[i].origin, origin)) {
  2227. s_copy(origins[i].origin, origin,
  2228. sizeof(origins[i].origin));
  2229. origin_cache_save();
  2230. }
  2231. return;
  2232. }
  2233. }
  2234. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2235. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2236. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2237. origin_cache_save();
  2238. }
  2239. static int path_dir(const char *path, char *out, unsigned int cap)
  2240. {
  2241. unsigned int i, last = 0;
  2242. for (i = 0; path[i]; i++)
  2243. if (path[i] == '/')
  2244. last = i;
  2245. if (last == 0) {
  2246. if (cap < 2)
  2247. return -1;
  2248. out[0] = '/';
  2249. out[1] = '\0';
  2250. return 0;
  2251. }
  2252. if (last + 1 >= cap)
  2253. return -1;
  2254. {
  2255. unsigned int j;
  2256. for (j = 0; j < last; j++)
  2257. out[j] = path[j];
  2258. out[last] = '\0';
  2259. }
  2260. return 0;
  2261. }
  2262. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2263. static int resolve_link(const char *base, const char *href, char *out,
  2264. unsigned int cap)
  2265. {
  2266. char joined[BR_URL_MAX];
  2267. if (!href || !href[0] || href[0] == '#')
  2268. return -1;
  2269. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2270. starts_with(href, "data:") || starts_with(href, "tel:"))
  2271. return -1;
  2272. if (starts_with(href, "about:")) {
  2273. s_copy(out, href, cap);
  2274. return 0;
  2275. }
  2276. if (is_http(href)) {
  2277. s_copy(out, href, cap);
  2278. return 0;
  2279. }
  2280. if (starts_with(href, "//")) {
  2281. if (is_http(base)) {
  2282. unsigned int n = 0;
  2283. s_append(out, &n, starts_with(base, "https:") ?
  2284. "https:" : "http:", cap);
  2285. s_append(out, &n, href, cap);
  2286. return 0;
  2287. }
  2288. return -1;
  2289. }
  2290. if (is_http(base)) {
  2291. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2292. }
  2293. /* local page */
  2294. if (href[0] == '/') {
  2295. if (normalize_abs(href, out, cap) != 0)
  2296. return -1;
  2297. return 0;
  2298. }
  2299. {
  2300. char dir[BR_URL_MAX];
  2301. unsigned int n = 0;
  2302. if (s_eq(base, "about:home"))
  2303. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2304. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2305. s_copy(dir, "/", sizeof(dir));
  2306. s_append(joined, &n, dir, sizeof(joined));
  2307. if (n == 0 || joined[n - 1] != '/')
  2308. s_append(joined, &n, "/", sizeof(joined));
  2309. s_append(joined, &n, href, sizeof(joined));
  2310. }
  2311. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2312. }
  2313. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2314. * rest instead of failing when a page or stylesheet is larger than the
  2315. * buffer. The stream is still walked to the end, so a normal page is
  2316. * verified; a truncated compressed input still returns whatever was decoded
  2317. * so far. */
  2318. struct trunc_buf {
  2319. unsigned char *dst;
  2320. unsigned int cap, pos;
  2321. int full;
  2322. };
  2323. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2324. {
  2325. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2326. if (len > m->cap - m->pos) {
  2327. unsigned int room = m->cap - m->pos;
  2328. if (room) {
  2329. unsigned int i;
  2330. for (i = 0; i < room; i++)
  2331. m->dst[m->pos + i] = data[i];
  2332. m->pos += room;
  2333. }
  2334. m->full = 1;
  2335. return 0;
  2336. }
  2337. {
  2338. unsigned int i;
  2339. for (i = 0; i < len; i++)
  2340. m->dst[m->pos + i] = data[i];
  2341. }
  2342. m->pos += len;
  2343. return 0;
  2344. }
  2345. static void worker_wait_ui(void);
  2346. static void inflate_ui_pump(void *ctx)
  2347. {
  2348. static unsigned int last;
  2349. unsigned int now = u_ticks_ms();
  2350. (void)ctx;
  2351. if ((int)(now - last) >= 50) {
  2352. last = now;
  2353. worker_wait_ui();
  2354. }
  2355. }
  2356. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2357. unsigned char *dst, unsigned int cap,
  2358. unsigned int *outlen, int gzip, int *truncated)
  2359. {
  2360. struct inflate_src in;
  2361. struct inflate_sink sink;
  2362. struct trunc_buf m;
  2363. unsigned int got = 0;
  2364. int r;
  2365. in.p = src;
  2366. in.len = len;
  2367. in.more = 0;
  2368. in.ctx = 0;
  2369. m.dst = dst;
  2370. m.cap = cap;
  2371. m.pos = 0;
  2372. m.full = 0;
  2373. sink.write = trunc_write;
  2374. sink.ctx = &m;
  2375. inflate_init(&image_inflate_ws, &in, &sink);
  2376. image_inflate_ws.progress = inflate_ui_pump;
  2377. image_inflate_ws.progress_ctx = 0;
  2378. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2379. inflate_zlib(&image_inflate_ws, &got);
  2380. *outlen = m.pos;
  2381. *truncated = m.full || r != 0;
  2382. if (r != 0 && m.pos == 0)
  2383. return -1;
  2384. return 0;
  2385. }
  2386. /* ---- headless fetch workers ------------------------------------------ *
  2387. *
  2388. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2389. * writes the raw response, a small metadata file and a done marker under
  2390. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2391. * or a multi-megabyte body never freezes the UI and images download in
  2392. * parallel.
  2393. */
  2394. struct fetch_meta {
  2395. int status;
  2396. int error;
  2397. int trunc;
  2398. unsigned int len;
  2399. unsigned int open_ms;
  2400. unsigned int first_ms;
  2401. unsigned int total_ms;
  2402. char encoding[16];
  2403. char ctype[64];
  2404. char final[BR_URL_MAX];
  2405. };
  2406. static void draw(unsigned int *action);
  2407. static void handle_keys(unsigned int *action);
  2408. static void handle_page_click(unsigned int *action);
  2409. #define FETCH_WORKERS 4
  2410. #define FETCH_PATH_MAX 32
  2411. /* One long-lived curl __serve helper per worker. Each worker has its own
  2412. * request/body/meta/done files under /share so several downloads can be in
  2413. * flight at once; the keep-alive connection stays in the helper process, so
  2414. * tls.c's per-process state remains valid. */
  2415. struct fetch_worker {
  2416. int pid;
  2417. int slot;
  2418. int busy;
  2419. int ready;
  2420. int image_job;
  2421. unsigned int seq;
  2422. unsigned int deadline;
  2423. int retried;
  2424. char req[FETCH_PATH_MAX];
  2425. char body[FETCH_PATH_MAX];
  2426. char meta[FETCH_PATH_MAX];
  2427. char done[FETCH_PATH_MAX];
  2428. char post[FETCH_PATH_MAX];
  2429. /* Optional preload job attached to this worker. */
  2430. unsigned int node;
  2431. int bg;
  2432. char url[BR_URL_MAX];
  2433. struct fetch_meta m;
  2434. };
  2435. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2436. static int fetch_tty = -2;
  2437. static void fetch_tty_drain(void);
  2438. static unsigned int fetch_session;
  2439. static unsigned int fetch_seq;
  2440. static struct fetch_meta fetch_meta;
  2441. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2442. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2443. static int fetch_last_error;
  2444. static unsigned int meta_uint(char **pp)
  2445. {
  2446. char *p = *pp;
  2447. unsigned int v = 0;
  2448. while (*p >= '0' && *p <= '9') {
  2449. v = v * 10 + (unsigned int)(*p - '0');
  2450. p++;
  2451. }
  2452. while (*p && *p != '\n')
  2453. p++;
  2454. if (*p == '\n')
  2455. p++;
  2456. *pp = p;
  2457. return v;
  2458. }
  2459. static void meta_str(char **pp, char *out, unsigned int cap)
  2460. {
  2461. char *p = *pp;
  2462. unsigned int n = 0;
  2463. while (*p && *p != '\n' && n + 1 < cap)
  2464. out[n++] = *p++;
  2465. out[n] = '\0';
  2466. while (*p && *p != '\n')
  2467. p++;
  2468. if (*p == '\n')
  2469. p++;
  2470. *pp = p;
  2471. }
  2472. static void worker_wait_ui(void)
  2473. {
  2474. unsigned int action = 0;
  2475. if (!ngui_begin(&ui))
  2476. return;
  2477. draw(&action);
  2478. handle_keys(&action);
  2479. handle_page_click(&action);
  2480. if (action & ACT_WAIT_NAV) {
  2481. pending_action |= action & ACT_WAIT_NAV;
  2482. if ((action & ACT_NAV) && click_url[0])
  2483. s_copy(pending_url, click_url, sizeof(pending_url));
  2484. click_url[0] = '\0';
  2485. cancel_fetch = 1;
  2486. }
  2487. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  2488. ngui_invalidate(&ui);
  2489. ngui_end(&ui);
  2490. }
  2491. static void fetch_path(char *out, unsigned int cap, const char *kind,
  2492. unsigned int session, int slot)
  2493. {
  2494. unsigned int n = 0;
  2495. s_append(out, &n, "/share/bf", cap);
  2496. s_append_dec(out, &n, session, cap);
  2497. s_append(out, &n, "_", cap);
  2498. s_append_dec(out, &n, (unsigned int)slot, cap);
  2499. s_append(out, &n, kind, cap);
  2500. }
  2501. static void fetch_pool_init(void)
  2502. {
  2503. static int ready;
  2504. int i;
  2505. if (ready)
  2506. return;
  2507. ready = 1;
  2508. fetch_session = ((unsigned int)u_getpid() << 16) ^
  2509. (u_ticks_ms() & 0xFFFFu);
  2510. if (!fetch_session)
  2511. fetch_session = 1;
  2512. for (i = 0; i < FETCH_WORKERS; i++) {
  2513. struct fetch_worker *w = &fetch_workers[i];
  2514. w->pid = -1;
  2515. w->slot = i;
  2516. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  2517. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  2518. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  2519. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  2520. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  2521. }
  2522. }
  2523. static void fetch_worker_stop(struct fetch_worker *w)
  2524. {
  2525. int i;
  2526. /* An abandoned image job leaves its node loadable again. */
  2527. if (w->busy && w->image_job && w->node < doc.nnode) {
  2528. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  2529. doc.nodes[w->node].bg_img_index = -1;
  2530. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  2531. doc.nodes[w->node].img_index = -1;
  2532. }
  2533. if (w->pid > 0) {
  2534. u_kill((unsigned int)w->pid);
  2535. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  2536. u_sleep_ms(5);
  2537. /* Let the reaper close the socket before we reuse the slot. */
  2538. u_sleep_ms(10);
  2539. }
  2540. w->pid = -1;
  2541. w->busy = 0;
  2542. w->ready = 0;
  2543. w->image_job = 0;
  2544. if (w->req[0]) {
  2545. u_syscall1(SYS_UNLINK, (int)w->done);
  2546. u_syscall1(SYS_UNLINK, (int)w->meta);
  2547. u_syscall1(SYS_UNLINK, (int)w->body);
  2548. u_syscall1(SYS_UNLINK, (int)w->post);
  2549. u_syscall1(SYS_UNLINK, (int)w->req);
  2550. }
  2551. }
  2552. static void fetch_workers_stop_all(void)
  2553. {
  2554. int i;
  2555. for (i = 0; i < FETCH_WORKERS; i++)
  2556. fetch_worker_stop(&fetch_workers[i]);
  2557. }
  2558. /* Abandon the transfers of the current page but keep idle helpers and their
  2559. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  2560. * because its response would otherwise land in a reused /share slot. */
  2561. static void fetch_workers_cancel_busy(void)
  2562. {
  2563. int i;
  2564. for (i = 0; i < FETCH_WORKERS; i++)
  2565. if (fetch_workers[i].busy)
  2566. fetch_worker_stop(&fetch_workers[i]);
  2567. }
  2568. static void fetch_workers_prepare_nav(const char *url)
  2569. {
  2570. int i;
  2571. (void)url;
  2572. for (i = 0; i < FETCH_WORKERS; i++) {
  2573. struct fetch_worker *w = &fetch_workers[i];
  2574. if (w->pid <= 0)
  2575. continue;
  2576. /* Only an in-flight transfer must be aborted. Idle helpers
  2577. * stay warm across origins: there are just FETCH_WORKERS of
  2578. * them, and uhttp_open drops the old connection when the
  2579. * next job is for another host. Killing and respawning all
  2580. * four on every navigation churned processes and sockets
  2581. * while images were still loading. */
  2582. if (w->busy)
  2583. fetch_worker_stop(w);
  2584. }
  2585. }
  2586. /* The browser is no longer the active window and no fetch is running: give
  2587. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  2588. static void fetch_workers_stop_if_unfocused(void)
  2589. {
  2590. int i;
  2591. fetch_tty_drain();
  2592. if (ui.focused || page_loading || preload_active)
  2593. return;
  2594. for (i = 0; i < FETCH_WORKERS; i++)
  2595. if (fetch_workers[i].pid > 0) {
  2596. fetch_workers_stop_all();
  2597. return;
  2598. }
  2599. }
  2600. /* The helpers (and this process, since u_tty_create() rebinds our own
  2601. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  2602. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  2603. * a dozen TLS connections every helper hung in its next log line, so the
  2604. * following cross-origin navigation sat at "Loading..." until it timed out.
  2605. * Drain and discard it from every wait/poll loop. */
  2606. static void fetch_tty_drain(void)
  2607. {
  2608. char sink[512];
  2609. int i;
  2610. if (fetch_tty <= 0)
  2611. return;
  2612. for (i = 0; i < 16; i++)
  2613. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  2614. break;
  2615. }
  2616. static int fetch_worker_start(struct fetch_worker *w, char *err,
  2617. unsigned int errcap)
  2618. {
  2619. char arg[40];
  2620. unsigned int n = 0;
  2621. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  2622. return 0;
  2623. w->pid = -1;
  2624. fetch_pool_init();
  2625. if (fetch_tty == -2) {
  2626. int t = u_tty_create();
  2627. fetch_tty = t > 0 ? t : 0;
  2628. }
  2629. s_append(arg, &n, "__serve ", sizeof(arg));
  2630. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  2631. s_append(arg, &n, " ", sizeof(arg));
  2632. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  2633. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  2634. if (w->pid <= 0) {
  2635. w->pid = -1;
  2636. s_copy(err, "cannot start network helper", errcap);
  2637. return -1;
  2638. }
  2639. return 0;
  2640. }
  2641. static struct fetch_worker *fetch_worker_alloc(void)
  2642. {
  2643. int i;
  2644. fetch_pool_init();
  2645. for (i = 0; i < FETCH_WORKERS; i++)
  2646. if (!fetch_workers[i].busy)
  2647. return &fetch_workers[i];
  2648. return 0;
  2649. }
  2650. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  2651. unsigned int cap, const char *method,
  2652. const char *ctype, const char *post,
  2653. unsigned int post_len, unsigned int node,
  2654. int bg, char *err, unsigned int errcap);
  2655. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  2656. unsigned int cap, const char *post,
  2657. unsigned int post_len, unsigned int node,
  2658. int bg, char *err, unsigned int errcap)
  2659. {
  2660. /* A body pointer with no bytes is still a POST: the classic request
  2661. * line would turn it into a GET. */
  2662. if (post && !post_len)
  2663. return fetch_worker_submit_req(w, url, cap, "POST",
  2664. "application/x-www-form-urlencoded", post, 0, node,
  2665. bg, err, errcap);
  2666. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  2667. node, bg, err, errcap);
  2668. }
  2669. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  2670. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  2671. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  2672. unsigned int cap, const char *method,
  2673. const char *ctype, const char *post,
  2674. unsigned int post_len, unsigned int node,
  2675. int bg, char *err, unsigned int errcap)
  2676. {
  2677. static char req[1024];
  2678. unsigned int n = 0;
  2679. fetch_seq++;
  2680. if (!fetch_seq)
  2681. fetch_seq = 1;
  2682. w->seq = fetch_seq;
  2683. w->ready = 0;
  2684. w->image_job = 0;
  2685. w->retried = 0;
  2686. w->m.error = 0;
  2687. w->node = node;
  2688. w->bg = bg;
  2689. s_copy(w->url, url, sizeof(w->url));
  2690. s_append_dec(req, &n, w->seq, sizeof(req));
  2691. s_append(req, &n, " ", sizeof(req));
  2692. s_append_dec(req, &n, cap, sizeof(req));
  2693. s_append(req, &n, " ", sizeof(req));
  2694. if (method) {
  2695. unsigned int k;
  2696. s_append(req, &n, "X ", sizeof(req));
  2697. s_append(req, &n, method, sizeof(req));
  2698. s_append(req, &n, " ", sizeof(req));
  2699. s_append_dec(req, &n, post_len, sizeof(req));
  2700. s_append(req, &n, " ", sizeof(req));
  2701. if (!ctype || !ctype[0])
  2702. s_append(req, &n, "-", sizeof(req));
  2703. /* One token on the request line: drop the spaces
  2704. * ("application/json; charset=utf-8" stays valid). */
  2705. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  2706. if (ctype[k] != ' ')
  2707. req[n++] = ctype[k];
  2708. req[n] = '\0';
  2709. s_append(req, &n, " ", sizeof(req));
  2710. } else if (post_len) {
  2711. s_append(req, &n, "POST ", sizeof(req));
  2712. s_append_dec(req, &n, post_len, sizeof(req));
  2713. s_append(req, &n, " ", sizeof(req));
  2714. }
  2715. s_append(req, &n, url, sizeof(req));
  2716. s_append(req, &n, "\n", sizeof(req));
  2717. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  2718. (int)post, (int)post_len) < 0) {
  2719. s_copy(err, "cannot queue form body", errcap);
  2720. return -1;
  2721. }
  2722. u_syscall1(SYS_UNLINK, (int)w->done);
  2723. u_syscall1(SYS_UNLINK, (int)w->meta);
  2724. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  2725. s_copy(err, "cannot queue network request", errcap);
  2726. return -1;
  2727. }
  2728. if (fetch_worker_start(w, err, errcap) != 0)
  2729. return -1;
  2730. w->busy = 1;
  2731. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  2732. return 0;
  2733. }
  2734. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  2735. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  2736. unsigned int errcap)
  2737. {
  2738. static char meta[1024];
  2739. char *p;
  2740. int rn, mseq;
  2741. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  2742. (int)(sizeof(meta) - 1));
  2743. if (rn <= 0) {
  2744. s_copy(err, "network helper failed", errcap);
  2745. return -1;
  2746. }
  2747. meta[rn] = '\0';
  2748. p = meta;
  2749. mseq = (int)meta_uint(&p);
  2750. if (mseq != (int)w->seq) {
  2751. s_copy(err, "stale network response", errcap);
  2752. return -1;
  2753. }
  2754. w->m.status = (int)meta_uint(&p);
  2755. w->m.error = (int)meta_uint(&p);
  2756. w->m.trunc = (int)meta_uint(&p);
  2757. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  2758. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  2759. meta_str(&p, w->m.final, sizeof(w->m.final));
  2760. w->m.len = meta_uint(&p);
  2761. w->m.open_ms = 0;
  2762. w->m.first_ms = 0;
  2763. w->m.total_ms = 0;
  2764. if (*p) {
  2765. w->m.open_ms = meta_uint(&p);
  2766. w->m.first_ms = meta_uint(&p);
  2767. w->m.total_ms = meta_uint(&p);
  2768. }
  2769. if (w->m.error) {
  2770. s_copy(err, uhttp_error_string(w->m.error), errcap);
  2771. return -1;
  2772. }
  2773. w->ready = 1;
  2774. return 0;
  2775. }
  2776. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  2777. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  2778. unsigned int errcap)
  2779. {
  2780. static char done[24];
  2781. char *p;
  2782. int rn, mseq;
  2783. fetch_tty_drain();
  2784. if (!w->busy)
  2785. return -1;
  2786. if (w->ready)
  2787. return 1;
  2788. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  2789. (int)(sizeof(done) - 1));
  2790. if (rn > 0) {
  2791. done[rn] = '\0';
  2792. p = done;
  2793. mseq = (int)meta_uint(&p);
  2794. if (mseq == (int)w->seq) {
  2795. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  2796. fetch_worker_stop(w);
  2797. return -1;
  2798. }
  2799. return 1;
  2800. }
  2801. }
  2802. if (!u_alive((unsigned int)w->pid)) {
  2803. w->pid = -1;
  2804. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  2805. w->retried = 1;
  2806. return 0;
  2807. }
  2808. s_copy(err, "network helper stopped", errcap);
  2809. fetch_worker_stop(w);
  2810. return -1;
  2811. }
  2812. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  2813. s_copy(err, "network request timed out", errcap);
  2814. fetch_worker_stop(w);
  2815. return -1;
  2816. }
  2817. return 0;
  2818. }
  2819. /* Copy the completed body, inflating it if the server ignored our identity
  2820. * request. Mirrors the old fetch_remote body path. */
  2821. static int fetch_worker_read_body(struct fetch_worker *w,
  2822. unsigned char *plain,
  2823. unsigned int plaincap,
  2824. unsigned char *comp,
  2825. unsigned int compcap,
  2826. int *truncated, char *err,
  2827. unsigned int errcap)
  2828. {
  2829. int rv, zr, was_trunc;
  2830. if (contains_ci(w->m.encoding, "gzip") ||
  2831. contains_ci(w->m.encoding, "deflate")) {
  2832. unsigned int comp_len = 0, plen = 0;
  2833. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  2834. (int)compcap);
  2835. if (rv < 0) {
  2836. s_copy(err, "empty response", errcap);
  2837. return -1;
  2838. }
  2839. comp_len = (unsigned int)rv;
  2840. if (comp_len < w->m.len) {
  2841. s_copy(err, "compressed response is too large", errcap);
  2842. return -1;
  2843. }
  2844. if (contains_ci(w->m.encoding, "deflate"))
  2845. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2846. &plen, 0, &was_trunc);
  2847. else
  2848. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2849. &plen, 1, &was_trunc);
  2850. if (zr != 0) {
  2851. s_copy(err, "compressed response is corrupt", errcap);
  2852. return -1;
  2853. }
  2854. *truncated = w->m.trunc || was_trunc;
  2855. return (int)plen;
  2856. }
  2857. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  2858. if (rv < 0) {
  2859. s_copy(err, "empty response", errcap);
  2860. return -1;
  2861. }
  2862. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  2863. return rv;
  2864. }
  2865. static void fetch_worker_release(struct fetch_worker *w)
  2866. {
  2867. u_syscall1(SYS_UNLINK, (int)w->done);
  2868. u_syscall1(SYS_UNLINK, (int)w->meta);
  2869. u_syscall1(SYS_UNLINK, (int)w->body);
  2870. u_syscall1(SYS_UNLINK, (int)w->post);
  2871. u_syscall1(SYS_UNLINK, (int)w->req);
  2872. w->busy = 0;
  2873. w->ready = 0;
  2874. w->image_job = 0;
  2875. }
  2876. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  2877. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  2878. unsigned int errcap)
  2879. {
  2880. for (;;) {
  2881. int rv;
  2882. if (!fetch_wait_passive)
  2883. worker_wait_ui();
  2884. if (cancel_fetch || pending_action) {
  2885. fetch_workers_cancel_busy();
  2886. return FETCH_ABORT;
  2887. }
  2888. rv = fetch_worker_poll(w, err, errcap);
  2889. if (rv != 0)
  2890. return rv == 1 ? 0 : -1;
  2891. u_sleep_ms(10);
  2892. }
  2893. }
  2894. static int fetch_remote(const char *url, unsigned int cap,
  2895. const char *post, unsigned int post_len,
  2896. unsigned char *plain, unsigned int plaincap,
  2897. unsigned char *comp, unsigned int compcap,
  2898. struct fetch_meta *m, int *truncated,
  2899. char *err, unsigned int errcap)
  2900. {
  2901. struct fetch_worker *w = fetch_worker_alloc();
  2902. int rv;
  2903. fetch_last_error = 0;
  2904. if (!w) {
  2905. s_copy(err, "network busy", errcap);
  2906. return -1;
  2907. }
  2908. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  2909. err, errcap) != 0) {
  2910. fetch_worker_release(w);
  2911. return -1;
  2912. }
  2913. rv = fetch_worker_wait(w, err, errcap);
  2914. if (rv == FETCH_ABORT) {
  2915. fetch_worker_release(w);
  2916. return FETCH_ABORT;
  2917. }
  2918. if (rv != 0) {
  2919. fetch_last_error = w->m.error;
  2920. fetch_worker_release(w);
  2921. return -1;
  2922. }
  2923. *m = w->m;
  2924. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  2925. truncated, err, errcap);
  2926. fetch_worker_release(w);
  2927. if (rv >= 0 && (cancel_fetch || pending_action))
  2928. return FETCH_ABORT;
  2929. return rv;
  2930. }
  2931. static int fetch_worker_status(const struct fetch_worker *w)
  2932. {
  2933. return w->m.status;
  2934. }
  2935. /* fetch()/XHR through a helper: one request, the status and body come back
  2936. * whatever the HTTP status (a 401 is an answer, not a network error). */
  2937. static int js_worker_http(const char *method, const char *url,
  2938. const char *ctype, const char *body,
  2939. unsigned int body_len, struct js_http_resp *r,
  2940. char *err, int errcap)
  2941. {
  2942. struct fetch_worker *w = fetch_worker_alloc();
  2943. unsigned char *plain;
  2944. int rv, tr = 0;
  2945. if (!w) {
  2946. s_copy(err, "network busy", (unsigned int)errcap);
  2947. return -1;
  2948. }
  2949. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  2950. body_len, 0, 0, err,
  2951. (unsigned int)errcap) != 0) {
  2952. fetch_worker_release(w);
  2953. return -1;
  2954. }
  2955. fetch_wait_passive++;
  2956. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  2957. fetch_wait_passive--;
  2958. if (rv != 0) {
  2959. if (rv == FETCH_ABORT)
  2960. s_copy(err, "page is navigating", (unsigned int)errcap);
  2961. fetch_worker_release(w);
  2962. return -1;
  2963. }
  2964. r->status = w->m.status;
  2965. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  2966. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  2967. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  2968. if (!plain) {
  2969. fetch_worker_release(w);
  2970. s_copy(err, "out of memory", (unsigned int)errcap);
  2971. return -1;
  2972. }
  2973. if (w->m.len == 0) {
  2974. rv = 0; /* 204, an empty 200: no body file */
  2975. } else {
  2976. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  2977. image_io_buf, BR_PAGE_COMP_MAX,
  2978. &tr, err, (unsigned int)errcap);
  2979. }
  2980. fetch_worker_release(w);
  2981. if (rv < 0) {
  2982. free(plain);
  2983. return -1;
  2984. }
  2985. plain[rv] = '\0';
  2986. r->body = (char *)plain;
  2987. r->len = (unsigned int)rv;
  2988. return 0;
  2989. }
  2990. /* ---- HTTP / file fetch ---- */
  2991. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  2992. unsigned int *outlen, int *is_local, char *ctype,
  2993. unsigned int ctcap, char *final, unsigned int finalcap,
  2994. char *err, unsigned int errcap, int *truncated,
  2995. const char *post, unsigned int post_len)
  2996. {
  2997. unsigned char *buf;
  2998. unsigned int len;
  2999. int tr = 0;
  3000. int rv;
  3001. *out = 0;
  3002. *outlen = 0;
  3003. *truncated = 0;
  3004. if (final && finalcap)
  3005. final[0] = '\0';
  3006. if (ctype && ctcap)
  3007. ctype[0] = '\0';
  3008. if (url[0] == '/') {
  3009. char pathbuf[BR_URL_MAX];
  3010. const char *open_url = url;
  3011. unsigned int i = 0;
  3012. /* A local form GET keeps ?query in the address bar but the
  3013. * file lookup uses the path alone, like a real browser. */
  3014. while (url[i] && url[i] != '?' && url[i] != '#')
  3015. i++;
  3016. if (url[i]) {
  3017. s_copy(pathbuf, url, i + 1);
  3018. open_url = pathbuf;
  3019. }
  3020. buf = (unsigned char *)malloc(cap);
  3021. if (!buf) {
  3022. s_copy(err, "out of memory", errcap);
  3023. return -1;
  3024. }
  3025. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  3026. if (rv < 0) {
  3027. free(buf);
  3028. s_copy(err, "file not found", errcap);
  3029. return -1;
  3030. }
  3031. *out = buf;
  3032. *outlen = (unsigned int)rv;
  3033. *is_local = 1;
  3034. if (ctype)
  3035. s_copy(ctype, "text/html", ctcap);
  3036. if (final)
  3037. s_copy(final, url, finalcap);
  3038. if ((unsigned int)rv == cap)
  3039. *truncated = 1;
  3040. return 0;
  3041. }
  3042. buf = (unsigned char *)malloc(cap);
  3043. if (!buf) {
  3044. s_copy(err, "out of memory", errcap);
  3045. return -1;
  3046. }
  3047. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3048. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3049. if (rv == FETCH_ABORT) {
  3050. free(buf);
  3051. return FETCH_ABORT;
  3052. }
  3053. if (rv < 0) {
  3054. free(buf);
  3055. return -1;
  3056. }
  3057. len = (unsigned int)rv;
  3058. if (len == 0) {
  3059. free(buf);
  3060. s_copy(err, "empty response", errcap);
  3061. return -1;
  3062. }
  3063. if (ctype)
  3064. s_copy(ctype, fetch_meta.ctype, ctcap);
  3065. if (final && fetch_meta.final[0])
  3066. s_copy(final, fetch_meta.final, finalcap);
  3067. *is_local = 0;
  3068. *out = buf;
  3069. *outlen = len;
  3070. *truncated = tr;
  3071. return 0;
  3072. }
  3073. /* Load every @font-face the parser registered. Local files go through
  3074. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  3075. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  3076. * to the built-in regular/bold/italic/mono set. */
  3077. static void load_font_faces(void)
  3078. {
  3079. unsigned int i;
  3080. memset(font_faces, 0, sizeof(font_faces));
  3081. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  3082. i <= BR_MAX_FACES; i++) {
  3083. const char *url = br_font_face_url((int)i);
  3084. const char *base = br_font_face_base((int)i);
  3085. char abs[BR_URL_MAX];
  3086. if (!url || !url[0])
  3087. continue;
  3088. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  3089. sizeof(abs)) != 0)
  3090. continue;
  3091. if (abs[0] == '/') {
  3092. font_faces[i - 1] = ufont_face_open_path(abs);
  3093. } else if (is_http(abs)) {
  3094. unsigned char *buf;
  3095. char err[64];
  3096. int rv, tr = 0;
  3097. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  3098. if (!buf)
  3099. continue;
  3100. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3101. UFONT_MAX_FILE, image_io_buf,
  3102. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  3103. err, sizeof(err));
  3104. if (rv > 0)
  3105. font_faces[i - 1] = ufont_face_open_mem(buf,
  3106. rv);
  3107. free(buf);
  3108. }
  3109. }
  3110. }
  3111. /* Remote scripts are cached under /share for the current boot, like the
  3112. * stylesheet cache, so reloads and later visits skip the network. */
  3113. static int script_cache_count;
  3114. static unsigned int script_cache_hash(const char *s)
  3115. {
  3116. unsigned int h = 2166136261u;
  3117. while (*s) {
  3118. h ^= (unsigned char)*s++;
  3119. h *= 16777619u;
  3120. }
  3121. return h;
  3122. }
  3123. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3124. {
  3125. unsigned int n = 0;
  3126. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3127. s_append_dec(out, &n, script_cache_hash(url), cap);
  3128. }
  3129. static void script_cache_clear(void)
  3130. {
  3131. struct sys_dirent d;
  3132. char path[96];
  3133. for (;;) {
  3134. int i, found = 0;
  3135. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3136. (int)&d) == 1; i++) {
  3137. unsigned int n = 0;
  3138. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3139. continue;
  3140. s_append(path, &n, "/share/", sizeof(path));
  3141. s_append(path, &n, d.name, sizeof(path));
  3142. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3143. return;
  3144. found = 1;
  3145. break;
  3146. }
  3147. if (!found)
  3148. break;
  3149. }
  3150. script_cache_count = 0;
  3151. }
  3152. static void script_cache_init(void)
  3153. {
  3154. struct sys_dirent d;
  3155. int i, count = 0;
  3156. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3157. (int)&d) == 1; i++)
  3158. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3159. count++;
  3160. if (count >= SCRIPT_CACHE_MAX) {
  3161. script_cache_clear();
  3162. return;
  3163. }
  3164. script_cache_count = count;
  3165. }
  3166. static int script_cache_get(const char *url, unsigned char **out,
  3167. unsigned int *outlen)
  3168. {
  3169. char path[96];
  3170. struct sys_stat st;
  3171. unsigned char *buf;
  3172. int rn;
  3173. script_cache_path(url, path, sizeof(path));
  3174. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3175. st.size >= SCRIPT_CACHE_FILE_MAX)
  3176. return 0;
  3177. buf = (unsigned char *)malloc(st.size + 1);
  3178. if (!buf)
  3179. return 0;
  3180. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3181. if (rn != (int)st.size) {
  3182. free(buf);
  3183. return 0;
  3184. }
  3185. buf[st.size] = '\0';
  3186. *out = buf;
  3187. *outlen = st.size;
  3188. return 1;
  3189. }
  3190. static void script_cache_put(const char *url, const unsigned char *data,
  3191. unsigned int len)
  3192. {
  3193. char path[96];
  3194. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3195. len >= SCRIPT_CACHE_FILE_MAX)
  3196. return;
  3197. script_cache_path(url, path, sizeof(path));
  3198. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3199. (int)len) >= 0)
  3200. script_cache_count++;
  3201. }
  3202. static int script_cache_has(const char *url)
  3203. {
  3204. char path[96];
  3205. struct sys_stat st;
  3206. script_cache_path(url, path, sizeof(path));
  3207. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3208. st.size < SCRIPT_CACHE_FILE_MAX;
  3209. }
  3210. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3211. static int fetch_script_text(const char *url, unsigned char **out,
  3212. unsigned int *outlen, char *err,
  3213. unsigned int errcap)
  3214. {
  3215. unsigned char *buf;
  3216. unsigned int len;
  3217. int local, truncated = 0;
  3218. char ctype[64], final[BR_URL_MAX];
  3219. int rv;
  3220. *out = 0;
  3221. *outlen = 0;
  3222. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3223. return 0;
  3224. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3225. sizeof(ctype), final, sizeof(final), err, errcap,
  3226. &truncated, 0, 0);
  3227. if (rv != 0)
  3228. return rv;
  3229. if (truncated || len >= BR_SCRIPT_MAX) {
  3230. free(buf);
  3231. s_copy(err, "script is too large", errcap);
  3232. return -1;
  3233. }
  3234. buf[len] = '\0';
  3235. if (!local)
  3236. script_cache_put(url, buf, len);
  3237. *out = buf;
  3238. *outlen = len;
  3239. return 0;
  3240. }
  3241. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  3242. * the heap, so images must not allocate their file body from it as well. */
  3243. static int fetch_image(const char *url, unsigned int cap,
  3244. unsigned char **out, unsigned int *outlen,
  3245. char *err, unsigned int errcap)
  3246. {
  3247. unsigned int len;
  3248. int tr = 0;
  3249. int rv;
  3250. *out = 0;
  3251. *outlen = 0;
  3252. if (cap > BR_IMG_FILE_MAX)
  3253. cap = BR_IMG_FILE_MAX;
  3254. if (url[0] == '/') {
  3255. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  3256. (int)cap);
  3257. if (rv < 0) {
  3258. s_copy(err, "file not found", errcap);
  3259. return -1;
  3260. }
  3261. *out = image_file_buf;
  3262. *outlen = (unsigned int)rv;
  3263. return 0;
  3264. }
  3265. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  3266. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  3267. if (rv == FETCH_ABORT)
  3268. return FETCH_ABORT;
  3269. if (rv < 0)
  3270. return -1;
  3271. len = (unsigned int)rv;
  3272. if (len == 0) {
  3273. s_copy(err, "empty image", errcap);
  3274. return -1;
  3275. }
  3276. *out = image_file_buf;
  3277. *outlen = len;
  3278. return 0;
  3279. }
  3280. /* Remote stylesheets are immutable enough for the current boot: keep
  3281. * successful responses under /share so a reload, a second visit or a fresh
  3282. * browser launch does not fetch the same five sheets over the network again.
  3283. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  3284. static int css_cache_count;
  3285. static unsigned int css_cache_hash(const char *s)
  3286. {
  3287. unsigned int h = 2166136261u;
  3288. while (*s) {
  3289. h ^= (unsigned char)*s++;
  3290. h *= 16777619u;
  3291. }
  3292. return h;
  3293. }
  3294. static void css_cache_path(const char *url, char *out, unsigned int cap)
  3295. {
  3296. unsigned int n = 0;
  3297. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  3298. s_append_dec(out, &n, css_cache_hash(url), cap);
  3299. }
  3300. static void css_cache_clear(void)
  3301. {
  3302. struct sys_dirent d;
  3303. char path[96];
  3304. for (;;) {
  3305. int i, found = 0;
  3306. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3307. (int)&d) == 1; i++) {
  3308. unsigned int n = 0;
  3309. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  3310. continue;
  3311. s_append(path, &n, "/share/", sizeof(path));
  3312. s_append(path, &n, d.name, sizeof(path));
  3313. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3314. return;
  3315. found = 1;
  3316. break;
  3317. }
  3318. if (!found)
  3319. break;
  3320. }
  3321. css_cache_count = 0;
  3322. }
  3323. static void css_cache_init(void)
  3324. {
  3325. struct sys_dirent d;
  3326. int i, count = 0;
  3327. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3328. (int)&d) == 1; i++)
  3329. if (starts_with(d.name, CSS_CACHE_PREFIX))
  3330. count++;
  3331. if (count >= CSS_CACHE_MAX) {
  3332. css_cache_clear();
  3333. return;
  3334. }
  3335. css_cache_count = count;
  3336. }
  3337. static int css_cache_get(const char *url, unsigned char **out,
  3338. unsigned int *outlen)
  3339. {
  3340. char path[96];
  3341. int rn;
  3342. css_cache_path(url, path, sizeof(path));
  3343. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  3344. (int)CSS_CACHE_FILE_MAX);
  3345. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  3346. return 0;
  3347. *out = image_io_buf;
  3348. *outlen = (unsigned int)rn;
  3349. return 1;
  3350. }
  3351. static void css_cache_put(const char *url, const unsigned char *data,
  3352. unsigned int len)
  3353. {
  3354. char path[96];
  3355. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  3356. len >= CSS_CACHE_FILE_MAX)
  3357. return;
  3358. css_cache_path(url, path, sizeof(path));
  3359. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3360. (int)len) >= 0)
  3361. css_cache_count++;
  3362. }
  3363. static int css_cache_has(const char *url)
  3364. {
  3365. char path[96];
  3366. struct sys_stat st;
  3367. css_cache_path(url, path, sizeof(path));
  3368. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3369. st.size < CSS_CACHE_FILE_MAX;
  3370. }
  3371. /* Read one stylesheet into the shared static buffer. CSS is parsed
  3372. * immediately, so it does not need the page heap; this leaves the heap for
  3373. * the 2 MB page body, the rules and the scaled image bitmaps. */
  3374. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  3375. char *err, unsigned int errcap)
  3376. {
  3377. unsigned int len;
  3378. int tr = 0;
  3379. int rv;
  3380. *out = 0;
  3381. *outlen = 0;
  3382. if (url[0] == '/') {
  3383. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  3384. (int)BR_CSS_MAX);
  3385. if (rv < 0) {
  3386. s_copy(err, "stylesheet not found", errcap);
  3387. return -1;
  3388. }
  3389. *out = image_io_buf;
  3390. *outlen = (unsigned int)rv;
  3391. return 0;
  3392. }
  3393. if (css_cache_get(url, out, outlen))
  3394. return 0;
  3395. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  3396. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  3397. &fetch_meta, &tr, err, errcap);
  3398. if (rv == FETCH_ABORT)
  3399. return FETCH_ABORT;
  3400. if (rv < 0)
  3401. return -1;
  3402. len = (unsigned int)rv;
  3403. if (len == 0) {
  3404. s_copy(err, "empty stylesheet", errcap);
  3405. return -1;
  3406. }
  3407. *out = image_io_buf;
  3408. *outlen = len;
  3409. css_cache_put(url, image_io_buf, len);
  3410. return 0;
  3411. }
  3412. static void redraw_now(void);
  3413. static char error_page[1024];
  3414. static void show_error(const char *title, const char *detail)
  3415. {
  3416. char *page = error_page;
  3417. unsigned int n = 0;
  3418. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  3419. s_append(page, &n, title, sizeof(error_page));
  3420. s_append(page, &n, "</h2><p>", sizeof(error_page));
  3421. {
  3422. const char *p = detail;
  3423. while (*p && n + 1 < sizeof(error_page)) {
  3424. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  3425. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  3426. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  3427. else page[n++] = *p;
  3428. p++;
  3429. }
  3430. }
  3431. page[n] = '\0';
  3432. s_append(page, &n, "</p><p>", sizeof(error_page));
  3433. s_append(page, &n, page_url, sizeof(error_page));
  3434. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  3435. sizeof(error_page));
  3436. br_parse(&doc, page, n);
  3437. layout_valid = 0;
  3438. preload_active = 0;
  3439. preload_pending = 0;
  3440. preload_wait = 0;
  3441. fetch_workers_cancel_busy();
  3442. s_copy(page_title, title, sizeof(page_title));
  3443. page_loading = 0;
  3444. set_status(title, 1, 0);
  3445. ngui_invalidate(&ui);
  3446. }
  3447. static int decode_direct_image(const unsigned char *data, unsigned int len,
  3448. unsigned int node)
  3449. {
  3450. if (image_count >= BR_MAX_IMAGES)
  3451. return -1;
  3452. if (decode_image_data(data, len, &images[0], 0, 0) != 0)
  3453. return -1;
  3454. doc.nodes[node].img_index = 0;
  3455. image_count = 1;
  3456. return 0;
  3457. }
  3458. static int ancestor_is(unsigned int node, unsigned int tag)
  3459. {
  3460. unsigned int p = doc.nodes[node].parent;
  3461. while (p) {
  3462. if (doc.nodes[p].tag == tag)
  3463. return 1;
  3464. p = doc.nodes[p].parent;
  3465. }
  3466. return 0;
  3467. }
  3468. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  3469. * parallel but parsed in document order, so the cascade is unchanged. */
  3470. static int load_stylesheets(void)
  3471. {
  3472. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  3473. static unsigned char remote[BR_MAX_SHEETS];
  3474. struct fetch_worker *slot[BR_MAX_SHEETS];
  3475. unsigned int i, n = 0, next = 0, k;
  3476. char err[64];
  3477. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  3478. struct br_node *nd = &doc.nodes[i];
  3479. const char *rel, *href;
  3480. char url[BR_URL_MAX];
  3481. int dup = 0;
  3482. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  3483. continue;
  3484. rel = br_rel(&doc, i);
  3485. if (!contains_ci(rel, "stylesheet"))
  3486. continue;
  3487. href = br_href(&doc, i);
  3488. if (!href[0])
  3489. continue;
  3490. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  3491. continue;
  3492. for (k = 0; k < n; k++)
  3493. if (s_eq(urls[k], url)) {
  3494. dup = 1;
  3495. break;
  3496. }
  3497. if (dup)
  3498. continue;
  3499. s_copy(urls[n], url, BR_URL_MAX);
  3500. remote[n] = url[0] != '/' && !css_cache_has(url);
  3501. n++;
  3502. }
  3503. for (i = 0; i < BR_MAX_SHEETS; i++)
  3504. slot[i] = 0;
  3505. /* Start as many remote sheets as there are free workers. */
  3506. for (; next < n; next++) {
  3507. struct fetch_worker *w;
  3508. if (!remote[next])
  3509. continue;
  3510. w = fetch_worker_alloc();
  3511. if (!w)
  3512. break;
  3513. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  3514. err, sizeof(err)) != 0) {
  3515. fetch_worker_release(w);
  3516. remote[next] = 0;
  3517. continue;
  3518. }
  3519. slot[next] = w;
  3520. }
  3521. for (i = 0; i < n; i++) {
  3522. unsigned char *data = 0;
  3523. unsigned int len = 0;
  3524. int rv;
  3525. if (!remote[i]) {
  3526. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  3527. if (rv == FETCH_ABORT) {
  3528. fetch_workers_stop_all();
  3529. return FETCH_ABORT;
  3530. }
  3531. if (rv != 0 || !len)
  3532. continue;
  3533. } else {
  3534. struct fetch_worker *w = slot[i];
  3535. int tr = 0;
  3536. if (!w) {
  3537. w = fetch_worker_alloc();
  3538. if (!w)
  3539. continue;
  3540. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  3541. 0, 0, 0, 0, err,
  3542. sizeof(err)) != 0) {
  3543. fetch_worker_release(w);
  3544. remote[i] = 0;
  3545. if (i == next)
  3546. next++;
  3547. continue;
  3548. }
  3549. slot[i] = w;
  3550. if (i == next)
  3551. next++;
  3552. }
  3553. rv = fetch_worker_wait(w, err, sizeof(err));
  3554. if (rv == FETCH_ABORT) {
  3555. fetch_workers_stop_all();
  3556. return FETCH_ABORT;
  3557. }
  3558. if (rv == 0)
  3559. rv = fetch_worker_read_body(w, image_io_buf,
  3560. BR_CSS_MAX,
  3561. image_io_buf + BR_CSS_MAX,
  3562. BR_CSS_COMP_MAX, &tr,
  3563. err, sizeof(err));
  3564. else
  3565. rv = -1;
  3566. fetch_worker_release(w);
  3567. slot[i] = 0;
  3568. /* Refill the worker window before parsing this sheet. */
  3569. for (; next < n; next++) {
  3570. struct fetch_worker *nw;
  3571. if (!remote[next])
  3572. continue;
  3573. nw = fetch_worker_alloc();
  3574. if (!nw)
  3575. break;
  3576. if (fetch_worker_submit(nw, urls[next],
  3577. BR_CSS_MAX, 0, 0, 0, 0,
  3578. err, sizeof(err)) != 0) {
  3579. fetch_worker_release(nw);
  3580. remote[next] = 0;
  3581. continue;
  3582. }
  3583. slot[next] = nw;
  3584. }
  3585. if (rv <= 0)
  3586. continue;
  3587. len = (unsigned int)rv;
  3588. data = image_io_buf;
  3589. css_cache_put(urls[i], data, len);
  3590. }
  3591. if (len) {
  3592. br_set_font_base(urls[i]);
  3593. br_parse_css_text(&doc, (const char *)data, len);
  3594. }
  3595. }
  3596. br_set_font_base(page_url);
  3597. br_parse_inline_css(&doc);
  3598. load_font_faces();
  3599. br_reset_styles(&doc);
  3600. layout_valid = 0;
  3601. return 0;
  3602. }
  3603. static void preload_begin(void)
  3604. {
  3605. preload_active = 1;
  3606. preload_pending = 0;
  3607. preload_wait = 1;
  3608. preload_max_jobs = FETCH_WORKERS;
  3609. preload_node = 0;
  3610. preload_loaded = 0;
  3611. preload_scroll = 0;
  3612. }
  3613. /* Styles are computed top-down during layout, but images inside a hidden
  3614. * menu/carousel are never visited and keep img_top == 0. Without this check
  3615. * the preloader walks the DOM in node order and spends the whole image
  3616. * budget on logos and off-canvas thumbnails the reader cannot see. */
  3617. static int node_hidden(unsigned int node)
  3618. {
  3619. unsigned int path[32], n = 0, p = node, i;
  3620. struct br_style st, parent;
  3621. while (p && n < sizeof(path) / sizeof(path[0])) {
  3622. path[n++] = p;
  3623. p = doc.nodes[p].parent;
  3624. }
  3625. parent = (struct br_style){0};
  3626. parent.font_px = 16;
  3627. parent.display = BR_DISPLAY_BLOCK;
  3628. for (i = n; i > 0; i--) {
  3629. br_style_for(&doc, path[i - 1], &parent, &st);
  3630. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  3631. st.opacity_hidden)
  3632. return 1;
  3633. parent = st;
  3634. }
  3635. return 0;
  3636. }
  3637. static struct br_style base_style(void);
  3638. static void style_for_node(unsigned int node, struct br_style *out)
  3639. {
  3640. unsigned int p = doc.nodes[node].parent;
  3641. struct br_style parent;
  3642. if (p) {
  3643. style_for_node(p, &parent);
  3644. br_style_for(&doc, node, &parent, out);
  3645. } else {
  3646. parent = base_style();
  3647. br_style_for(&doc, node, &parent, out);
  3648. }
  3649. }
  3650. /* ---- parallel image preloading ---- *
  3651. *
  3652. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  3653. * preload_step() only starts jobs and harvests completed ones; the browser
  3654. * main loop keeps drawing between calls, instead of blocking on one fetch.
  3655. */
  3656. static int preload_active_jobs(void)
  3657. {
  3658. int i, n = 0;
  3659. for (i = 0; i < FETCH_WORKERS; i++)
  3660. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  3661. n++;
  3662. return n;
  3663. }
  3664. static void preload_job_error(struct fetch_worker *w)
  3665. {
  3666. if (w->node < doc.nnode) {
  3667. if (w->bg)
  3668. doc.nodes[w->node].bg_img_index = -2;
  3669. else
  3670. doc.nodes[w->node].img_index = -2;
  3671. ngui_invalidate(&ui);
  3672. }
  3673. }
  3674. static void preload_decode(unsigned int node, int bg,
  3675. const unsigned char *data, unsigned int len,
  3676. const char *url)
  3677. {
  3678. if (image_count >= BR_MAX_IMAGES) {
  3679. if (bg)
  3680. doc.nodes[node].bg_img_index = -2;
  3681. else
  3682. doc.nodes[node].img_index = -2;
  3683. return;
  3684. }
  3685. if (decode_image_data(data, len, &images[image_count],
  3686. bg && node < BR_MAX_NODES &&
  3687. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  3688. bg && node < BR_MAX_NODES &&
  3689. layout_boxes[node].valid ? layout_boxes[node].h : 0) == 0) {
  3690. /* An <img> bitmap only depends on its URL, so the next
  3691. * <img> with the same source reuses it (heise repeats one
  3692. * comment icon 85 times). Backgrounds are scaled to their
  3693. * box and are not shared. */
  3694. images[image_count].url_hash =
  3695. !bg && url ? script_cache_hash(url) | 1u : 0;
  3696. if (bg)
  3697. doc.nodes[node].bg_img_index = (short)image_count;
  3698. else
  3699. doc.nodes[node].img_index = (short)image_count;
  3700. image_count++;
  3701. preload_loaded++;
  3702. layout_valid = 0;
  3703. } else {
  3704. if (bg)
  3705. doc.nodes[node].bg_img_index = -2;
  3706. else
  3707. doc.nodes[node].img_index = -2;
  3708. }
  3709. ngui_invalidate(&ui);
  3710. }
  3711. /* Harvest one completed worker. Returns 1 when a job was finished. */
  3712. static int preload_finish_worker(struct fetch_worker *w)
  3713. {
  3714. char err[64];
  3715. int rv, tr = 0;
  3716. rv = fetch_worker_poll(w, err, sizeof(err));
  3717. if (rv < 0) {
  3718. preload_job_error(w);
  3719. fetch_worker_release(w);
  3720. return 1;
  3721. }
  3722. if (rv == 0)
  3723. return 0;
  3724. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  3725. image_comp_buf, BR_IMG_FILE_MAX,
  3726. &tr, err, sizeof(err));
  3727. if (rv >= 0)
  3728. preload_decode(w->node, w->bg, image_file_buf,
  3729. (unsigned int)rv, w->url);
  3730. else
  3731. preload_job_error(w);
  3732. fetch_worker_release(w);
  3733. return 1;
  3734. }
  3735. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  3736. * the number of jobs started. */
  3737. static int preload_fill_jobs(void)
  3738. {
  3739. int started = 0;
  3740. char err[64];
  3741. while (preload_active && preload_node < doc.nnode) {
  3742. unsigned int i = preload_node;
  3743. struct br_node *nd = &doc.nodes[i];
  3744. const char *src;
  3745. char url[BR_URL_MAX];
  3746. struct fetch_worker *w;
  3747. if (preload_active_jobs() >= preload_max_jobs)
  3748. break;
  3749. if (nd->type != BR_NODE_ELEM) {
  3750. preload_node++;
  3751. continue;
  3752. }
  3753. if (nd->tag != BR_TAG_IMG) {
  3754. if (nd->bg_img_index == -1) {
  3755. struct br_style bs;
  3756. style_for_node(i, &bs);
  3757. if (bs.display != BR_DISPLAY_NONE &&
  3758. !bs.vis_hidden && bs.bg_image) {
  3759. const char *bsrc =
  3760. br_bg_image_url(bs.bg_image - 1);
  3761. /* Lazy like <img>: a background box
  3762. * below the viewport (or not laid
  3763. * out yet) waits for the next scan. */
  3764. if (bsrc[0] &&
  3765. (!layout_boxes[i].valid ||
  3766. block_top[i] >
  3767. (unsigned int)(page_scroll.offset +
  3768. page_rect.h + 160))) {
  3769. preload_pending = 1;
  3770. preload_node++;
  3771. continue;
  3772. }
  3773. if (bsrc[0] &&
  3774. !starts_with(bsrc, "data:") &&
  3775. resolve_link(page_url, bsrc, url,
  3776. sizeof(url)) == 0) {
  3777. if (image_count +
  3778. preload_active_jobs() >=
  3779. BR_MAX_IMAGES) {
  3780. preload_node = doc.nnode;
  3781. break;
  3782. }
  3783. if (url[0] == '/') {
  3784. unsigned char *data = 0;
  3785. unsigned int len = 0;
  3786. preload_node = i + 1;
  3787. if (fetch_image(url,
  3788. BR_IMG_FILE_MAX,
  3789. &data, &len,
  3790. err,
  3791. sizeof(err)) == 0)
  3792. preload_decode(i, 1, data, len, 0);
  3793. else
  3794. nd->bg_img_index = -2;
  3795. continue;
  3796. }
  3797. w = fetch_worker_alloc();
  3798. if (!w)
  3799. return started;
  3800. preload_node = i + 1;
  3801. if (fetch_worker_submit(w, url,
  3802. BR_IMG_FILE_MAX,
  3803. 0, 0, i, 1,
  3804. err,
  3805. sizeof(err)) != 0) {
  3806. nd->bg_img_index = -2;
  3807. fetch_worker_release(w);
  3808. continue;
  3809. }
  3810. w->image_job = 1;
  3811. w->deadline = u_ticks_ms() +
  3812. BR_IMG_JOB_TIMEOUT_MS;
  3813. /* in flight: rescans skip it */
  3814. nd->bg_img_index = -3;
  3815. started++;
  3816. continue;
  3817. }
  3818. }
  3819. nd->bg_img_index = -2;
  3820. }
  3821. preload_node++;
  3822. continue;
  3823. }
  3824. if (nd->img_index != -1) {
  3825. preload_node++;
  3826. continue;
  3827. }
  3828. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  3829. preload_node++;
  3830. continue;
  3831. }
  3832. src = br_src(&doc, i);
  3833. if (!src[0] || starts_with(src, "data:")) {
  3834. preload_node++;
  3835. continue;
  3836. }
  3837. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  3838. preload_node++;
  3839. continue;
  3840. }
  3841. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  3842. preload_node = doc.nnode;
  3843. break;
  3844. }
  3845. /* Do not stop at the first below-fold image: DOM order is
  3846. * not visual order, and a footer/ad image early in the DOM
  3847. * used to hide every later article image from the loader. */
  3848. if (img_top[i] >
  3849. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  3850. preload_pending = 1;
  3851. preload_node++;
  3852. continue;
  3853. }
  3854. {
  3855. unsigned int uh = script_cache_hash(url) | 1u;
  3856. int k;
  3857. for (k = 0; k < image_count; k++)
  3858. if (images[k].state == 1 &&
  3859. images[k].url_hash == uh)
  3860. break;
  3861. if (k < image_count) {
  3862. nd->img_index = (short)k;
  3863. layout_valid = 0;
  3864. preload_node = i + 1;
  3865. ngui_invalidate(&ui);
  3866. continue;
  3867. }
  3868. }
  3869. if (url[0] == '/') {
  3870. unsigned char *data = 0;
  3871. unsigned int len = 0;
  3872. preload_node = i + 1;
  3873. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  3874. err, sizeof(err)) == 0)
  3875. preload_decode(i, 0, data, len, url);
  3876. else
  3877. nd->img_index = -2;
  3878. continue;
  3879. }
  3880. w = fetch_worker_alloc();
  3881. if (!w)
  3882. return started;
  3883. preload_node = i + 1;
  3884. {
  3885. char msg[64];
  3886. unsigned int n = 0;
  3887. s_append(msg, &n, "Loading images ", sizeof(msg));
  3888. s_append_dec(msg, &n,
  3889. (unsigned int)preload_loaded + 1,
  3890. sizeof(msg));
  3891. s_append(msg, &n, "...", sizeof(msg));
  3892. set_status(msg, 0, 0);
  3893. }
  3894. if (fetch_worker_submit(w, url, BR_IMG_FILE_MAX, 0, 0, i, 0,
  3895. err, sizeof(err)) != 0) {
  3896. nd->img_index = -2;
  3897. fetch_worker_release(w);
  3898. continue;
  3899. }
  3900. w->image_job = 1;
  3901. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  3902. nd->img_index = -3; /* in flight: rescans skip it */
  3903. started++;
  3904. }
  3905. return started;
  3906. }
  3907. static void preload_step(void)
  3908. {
  3909. int i;
  3910. if (!preload_active)
  3911. return;
  3912. if (cancel_fetch || pending_action) {
  3913. preload_active = 0;
  3914. preload_pending = 0;
  3915. fetch_workers_cancel_busy();
  3916. return;
  3917. }
  3918. preload_fill_jobs();
  3919. /* Decode at most one completed image per main-loop pass. A full-size
  3920. * JPEG decode blocks this single-threaded UI for a long time, and
  3921. * harvesting a batch back-to-back starved the TCP pump (and therefore
  3922. * every other image download) on slow CPUs: requests looked stuck
  3923. * while four decodes ran in a row. */
  3924. for (i = 0; i < FETCH_WORKERS; i++) {
  3925. if (!fetch_workers[i].busy)
  3926. continue;
  3927. if (preload_finish_worker(&fetch_workers[i]))
  3928. return;
  3929. }
  3930. if (preload_active && preload_node >= doc.nnode &&
  3931. preload_active_jobs() == 0) {
  3932. preload_active = 0;
  3933. if (preload_pending)
  3934. preload_scroll = page_scroll.offset;
  3935. else
  3936. preload_pending = 0;
  3937. /* Keep the now idle helpers and their connections; a later
  3938. * navigation reuses them. They exit after ten idle seconds,
  3939. * and losing window focus stops them at once. */
  3940. set_status(post_status_text, post_status_error, post_status_ttl);
  3941. ngui_invalidate(&ui);
  3942. }
  3943. }
  3944. /* Set by navigate() when it turned a typed bare host into https://; the next
  3945. * load_page() consumes it and may retry over http. */
  3946. static int nav_https_upgraded;
  3947. /* Errors that mean "https is not served here" rather than "the site is
  3948. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  3949. static int https_fallback_error(int e)
  3950. {
  3951. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  3952. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  3953. e == UHTTP_ERR_RESET;
  3954. }
  3955. static void history_push(const char *url)
  3956. {
  3957. if (!url || !url[0])
  3958. return;
  3959. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  3960. s_eq(history[hist_pos], url))
  3961. return;
  3962. if (hist_len > 0 && hist_pos + 1 < hist_len)
  3963. hist_len = hist_pos + 1;
  3964. if (hist_len < BR_HISTORY) {
  3965. s_copy(history[hist_len], url, BR_URL_MAX);
  3966. hist_pos = hist_len;
  3967. hist_len++;
  3968. } else {
  3969. int i;
  3970. for (i = 1; i < BR_HISTORY; i++)
  3971. s_copy(history[i - 1], history[i], BR_URL_MAX);
  3972. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  3973. hist_pos = BR_HISTORY - 1;
  3974. }
  3975. }
  3976. static void load_page(const char *url, int local, int push)
  3977. {
  3978. unsigned char *body = 0;
  3979. unsigned int len = 0;
  3980. int truncated = 0;
  3981. struct img_info image_info;
  3982. char ctype[64];
  3983. char final[BR_URL_MAX];
  3984. char err[80];
  3985. const char *detail = 0;
  3986. const char *post = pending_post_is ? pending_post : 0;
  3987. unsigned int post_len = pending_post_len;
  3988. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  3989. /* Phase timings for the status line: where a slow load spends it. */
  3990. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  3991. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  3992. int upgraded = nav_https_upgraded;
  3993. int retried = 0;
  3994. int rv;
  3995. nav_https_upgraded = 0;
  3996. final[0] = '\0';
  3997. pending_post_len = 0;
  3998. pending_post_is = 0;
  3999. cancel_fetch = 0;
  4000. preload_active = 0;
  4001. preload_pending = 0;
  4002. fetch_workers_prepare_nav(url);
  4003. js_browser_stop();
  4004. js_last_status[0] = '\0';
  4005. js_last_error = 0;
  4006. heap_clear();
  4007. image_reset();
  4008. form_reset_state();
  4009. layout_valid = 0;
  4010. page_scroll.offset = 0;
  4011. page_scroll.dragging = 0;
  4012. page_title[0] = '\0';
  4013. page_loading = 1;
  4014. page_is_local = local;
  4015. s_copy(page_url, url, sizeof(page_url));
  4016. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4017. url_in.len = s_len(url_in.text);
  4018. url_in.cursor = url_in.len;
  4019. url_in.scroll = 0;
  4020. ngui_set_focus(&ui, 0);
  4021. if (final[0])
  4022. final[0] = '\0';
  4023. if (push)
  4024. history_push(url);
  4025. set_status("Loading...", 0, 0);
  4026. ngui_invalidate(&ui);
  4027. /* heap_clear() detaches the fonts, so attach them again before the
  4028. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  4029. if (heap_start() != 0) {
  4030. show_error("Out of memory", "Cannot allocate the page buffer");
  4031. return;
  4032. }
  4033. br_parse_plain(&doc, "", 0); /* blank while loading */
  4034. ngui_font_attach(&ui);
  4035. redraw_now();
  4036. browser_rules_alloc();
  4037. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  4038. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  4039. &truncated, post, post_len);
  4040. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  4041. fetch_last_error == UHTTP_ERR_DNS) {
  4042. /* A busy previous page can leave the receiver ring full just
  4043. * long enough to lose a DNS reply. Tear the old helpers down
  4044. * and try once more before giving up. */
  4045. retried = 1;
  4046. fetch_workers_stop_all();
  4047. u_sleep_ms(500);
  4048. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  4049. sizeof(ctype), final, sizeof(final), err,
  4050. sizeof(err), &truncated, post, post_len);
  4051. }
  4052. if (rv == FETCH_ABORT)
  4053. return;
  4054. t_fetch = u_ticks_ms() - t_start;
  4055. /* Capture the page timing before CSS/script/image fetches overwrite the
  4056. * shared fetch_meta block. */
  4057. if (rv == 0 && !local) {
  4058. page_open_ms = fetch_meta.open_ms;
  4059. page_first_ms = fetch_meta.first_ms;
  4060. page_total_ms = fetch_meta.total_ms;
  4061. }
  4062. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  4063. https_fallback_error(fetch_last_error)) {
  4064. char http_url[BR_URL_MAX];
  4065. unsigned int n = 0;
  4066. s_append(http_url, &n, "http://", sizeof(http_url));
  4067. s_append(http_url, &n, url + 8, sizeof(http_url));
  4068. /* Replace the https entry instead of adding a second one. */
  4069. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  4070. s_eq(history[hist_pos], url))
  4071. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  4072. load_page(http_url, 0, 0);
  4073. return;
  4074. }
  4075. if (rv != 0) {
  4076. detail = err;
  4077. show_error("Cannot load this page", detail);
  4078. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4079. url_in.len = s_len(url_in.text);
  4080. url_in.cursor = url_in.len;
  4081. url_in.scroll = 0;
  4082. return;
  4083. }
  4084. if (!local)
  4085. origin_cache_learn(url, final[0] ? final : url);
  4086. page_is_local = local;
  4087. if (final[0]) {
  4088. s_copy(page_url, final, sizeof(page_url));
  4089. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4090. url_in.len = s_len(url_in.text);
  4091. url_in.cursor = url_in.len;
  4092. url_in.scroll = 0;
  4093. }
  4094. if (contains_ci(ctype, "text/plain")) {
  4095. br_parse_plain(&doc, (const char *)body, len);
  4096. } else if (contains_ci(ctype, "image/") ||
  4097. (!contains_ci(ctype, "text/html") &&
  4098. img_sniff(body, len, &image_info) == 0)) {
  4099. unsigned int node = br_parse_image_doc(&doc, page_url);
  4100. if (node)
  4101. decode_direct_image(body, len, node);
  4102. s_copy(page_title, "Image", sizeof(page_title));
  4103. } else {
  4104. br_set_viewport(ui.w);
  4105. t_mark = u_ticks_ms();
  4106. br_parse(&doc, (const char *)body, len);
  4107. t_parse = u_ticks_ms() - t_mark;
  4108. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  4109. sizeof(page_title));
  4110. t_mark = u_ticks_ms();
  4111. if (load_stylesheets() == FETCH_ABORT)
  4112. return;
  4113. t_css = u_ticks_ms() - t_mark;
  4114. if (pending_action)
  4115. return;
  4116. }
  4117. preload_begin();
  4118. page_loading = 0;
  4119. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4120. url_in.len = s_len(url_in.text);
  4121. url_in.cursor = url_in.len;
  4122. url_in.scroll = 0;
  4123. ngui_set_focus(&ui, 0);
  4124. /* Paint the parsed page before fetching/running scripts. A slow
  4125. * remote <script src> then does not hide the page behind the loading
  4126. * screen; the fetch helper pumps this UI while it waits. */
  4127. set_status("Loading scripts...", 0, 0);
  4128. t_mark = u_ticks_ms();
  4129. redraw_now();
  4130. t_paint = u_ticks_ms() - t_mark;
  4131. /* Start one image download before the scripts. The other workers
  4132. * fetch the external script bodies in parallel, and the remaining
  4133. * images start as soon as the script phase ends. */
  4134. preload_max_jobs = 1;
  4135. preload_fill_jobs();
  4136. preload_wait = 0;
  4137. t_mark = u_ticks_ms();
  4138. run_page_scripts();
  4139. t_js = u_ticks_ms() - t_mark;
  4140. preload_max_jobs = FETCH_WORKERS;
  4141. if (pending_action)
  4142. return;
  4143. post_status_text[0] = '\0';
  4144. post_status_error = 0;
  4145. post_status_ttl = 0;
  4146. if (js_last_status[0]) {
  4147. s_copy(post_status_text, js_last_status,
  4148. sizeof(post_status_text));
  4149. post_status_error = js_last_error;
  4150. post_status_ttl = 8000;
  4151. } else if (truncated) {
  4152. s_copy(post_status_text, "Page truncated at the buffer limit",
  4153. sizeof(post_status_text));
  4154. post_status_ttl = 6000;
  4155. } else if (doc.truncated) {
  4156. s_copy(post_status_text, "Page truncated by the parser",
  4157. sizeof(post_status_text));
  4158. post_status_ttl = 6000;
  4159. } else if (page_total_ms) {
  4160. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  4161. * paint 220, js 1750" -- the phases of this load. */
  4162. unsigned int n = 0;
  4163. static const char *const names[] = {
  4164. ", parse ", ", css ", ", paint ", ", js "
  4165. };
  4166. unsigned int vals[4];
  4167. int k;
  4168. vals[0] = t_parse;
  4169. vals[1] = t_css;
  4170. vals[2] = t_paint;
  4171. vals[3] = t_js;
  4172. (void)page_first_ms;
  4173. if (starts_with(page_url, "https://"))
  4174. s_append(post_status_text, &n,
  4175. "HTTPS (not verified), ",
  4176. sizeof(post_status_text));
  4177. s_append(post_status_text, &n, "Loaded in ",
  4178. sizeof(post_status_text));
  4179. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  4180. sizeof(post_status_text));
  4181. s_append(post_status_text, &n, " ms: page ",
  4182. sizeof(post_status_text));
  4183. s_append_dec(post_status_text, &n, t_fetch,
  4184. sizeof(post_status_text));
  4185. s_append(post_status_text, &n, " (headers ",
  4186. sizeof(post_status_text));
  4187. s_append_dec(post_status_text, &n, page_open_ms,
  4188. sizeof(post_status_text));
  4189. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  4190. for (k = 0; k < 4; k++) {
  4191. s_append(post_status_text, &n, names[k],
  4192. sizeof(post_status_text));
  4193. s_append_dec(post_status_text, &n, vals[k],
  4194. sizeof(post_status_text));
  4195. }
  4196. post_status_ttl = 12000;
  4197. } else if (starts_with(page_url, "https://")) {
  4198. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  4199. sizeof(post_status_text));
  4200. post_status_ttl = 6000;
  4201. }
  4202. set_status(post_status_text, post_status_error, post_status_ttl);
  4203. ngui_invalidate(&ui);
  4204. }
  4205. static void load_home(int push)
  4206. {
  4207. pending_post_len = 0;
  4208. pending_post_is = 0;
  4209. cancel_fetch = 0;
  4210. preload_active = 0;
  4211. preload_pending = 0;
  4212. js_browser_stop();
  4213. js_last_status[0] = '\0';
  4214. js_last_error = 0;
  4215. heap_clear();
  4216. image_reset();
  4217. form_reset_state();
  4218. layout_valid = 0;
  4219. page_scroll.offset = 0;
  4220. page_scroll.dragging = 0;
  4221. page_loading = 1;
  4222. page_is_local = 0;
  4223. s_copy(page_url, "about:home", sizeof(page_url));
  4224. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4225. url_in.len = s_len(url_in.text);
  4226. url_in.cursor = url_in.len;
  4227. url_in.scroll = 0;
  4228. ngui_set_focus(&ui, 0);
  4229. if (push)
  4230. history_push(page_url);
  4231. ngui_invalidate(&ui);
  4232. /* See load_page(): reattach the fonts before the first redraw. */
  4233. if (heap_start() != 0) {
  4234. show_error("Out of memory", "Cannot allocate the browser heap");
  4235. return;
  4236. }
  4237. br_parse_plain(&doc, "", 0);
  4238. ngui_font_attach(&ui);
  4239. redraw_now();
  4240. browser_rules_alloc();
  4241. {
  4242. static const char home[] =
  4243. "<html><head><title>NebOS Browser</title><style>"
  4244. "body { margin: 10px; color: #e4e6f0; }"
  4245. "h1 { color: #7fb0ff; }"
  4246. ".box { background-color: #262b3a; margin: 12px; "
  4247. "padding: 10px; }"
  4248. "a { color: #7fb0ff; }"
  4249. "pre { background-color: #32384a; }"
  4250. "</style></head><body>"
  4251. "<h1>NebOS Browser</h1>"
  4252. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  4253. "shared HTTP client and the image library.</p>"
  4254. "<div class=\"box\"><b>Try:</b>"
  4255. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  4256. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  4257. "<li><a href=\"/floppy1/JS.HTM\">/"
  4258. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  4259. "<li><a href=\"http://10.0.2.2:8000/\">"
  4260. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  4261. "<li><a href=\"https://example.com/\">"
  4262. "https://example.com/</a> (TLS, not verified)</li>"
  4263. "</ul></div>"
  4264. "<p>Type a URL in the bar above. Esc closes the "
  4265. "window, Ctrl+L focuses the address bar.</p>"
  4266. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  4267. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  4268. "</body></html>";
  4269. br_set_viewport(ui.w);
  4270. br_parse(&doc, home, sizeof(home) - 1);
  4271. br_parse_inline_css(&doc);
  4272. br_reset_styles(&doc);
  4273. s_copy(page_title, doc.title, sizeof(page_title));
  4274. }
  4275. post_status_text[0] = '\0';
  4276. post_status_error = 0;
  4277. post_status_ttl = 0;
  4278. page_loading = 0;
  4279. set_status("", 0, 0);
  4280. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4281. url_in.len = s_len(url_in.text);
  4282. url_in.cursor = url_in.len;
  4283. url_in.scroll = 0;
  4284. ngui_set_focus(&ui, 0);
  4285. ngui_invalidate(&ui);
  4286. }
  4287. /* Extensions the browser opens from the local filesystem. A dotted input
  4288. * with one of these still resolves relative to the cwd. */
  4289. static int local_file_ext(const char *s)
  4290. {
  4291. static const char *const exts[] = {
  4292. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  4293. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  4294. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  4295. "cfg", "conf", 0
  4296. };
  4297. unsigned int i = 0, start = 0, len = 0, e;
  4298. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  4299. s[i] != '#') {
  4300. if (s[i] == '.') {
  4301. start = i + 1;
  4302. len = 0;
  4303. } else if (start) {
  4304. len++;
  4305. }
  4306. i++;
  4307. }
  4308. if (!len)
  4309. return 0;
  4310. for (e = 0; exts[e]; e++) {
  4311. const char *x = exts[e];
  4312. unsigned int xn = s_len(x), k;
  4313. if (xn != len)
  4314. continue;
  4315. for (k = 0; k < len; k++) {
  4316. char a = s[start + k];
  4317. if (a >= 'A' && a <= 'Z')
  4318. a = (char)(a - 'A' + 'a');
  4319. if (a != x[k])
  4320. break;
  4321. }
  4322. if (k == len)
  4323. return 1;
  4324. }
  4325. return 0;
  4326. }
  4327. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  4328. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  4329. * Enter to the first network request. */
  4330. static int looks_like_host(const char *s)
  4331. {
  4332. unsigned int i = 0;
  4333. int dot = 0;
  4334. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  4335. s[i] != ':') {
  4336. char c = s[i];
  4337. if (c == '.') {
  4338. dot = 1;
  4339. } else if (!((c >= 'a' && c <= 'z') ||
  4340. (c >= 'A' && c <= 'Z') ||
  4341. (c >= '0' && c <= '9') ||
  4342. c == '-' || c == '_')) {
  4343. return 0;
  4344. }
  4345. i++;
  4346. }
  4347. return dot && i > 0 && !local_file_ext(s);
  4348. }
  4349. static void load_remote(const char *url, int push)
  4350. {
  4351. char canon[BR_URL_MAX];
  4352. s_copy(canon, url, sizeof(canon));
  4353. origin_cache_apply(canon, sizeof(canon));
  4354. load_page(canon, 0, push);
  4355. }
  4356. static void navigate(const char *input, int push)
  4357. {
  4358. char target[BR_URL_MAX];
  4359. char *t;
  4360. if (!input)
  4361. return;
  4362. s_copy(target, input, sizeof(target));
  4363. t = trim(target);
  4364. if (!t[0])
  4365. return;
  4366. if (s_eq(t, "about:home")) {
  4367. load_home(push);
  4368. return;
  4369. }
  4370. if (starts_with(t, "file://")) {
  4371. make_abs_local(t + 7, target, sizeof(target));
  4372. load_page(target, 1, push);
  4373. return;
  4374. }
  4375. if (is_http(t)) {
  4376. load_remote(t, push);
  4377. return;
  4378. }
  4379. if (t[0] == '/') {
  4380. make_abs_local(t, target, sizeof(target));
  4381. load_page(target, 1, push);
  4382. return;
  4383. }
  4384. if (!looks_like_host(t)) {
  4385. struct sys_stat st;
  4386. if (u_stat(t, &st) == 0 && !st.is_dir) {
  4387. make_abs_local(t, target, sizeof(target));
  4388. load_page(target, 1, push);
  4389. return;
  4390. }
  4391. }
  4392. {
  4393. /* A typed bare host tries https first: nearly every site
  4394. * redirects http -> https anyway, and that hop costs a whole
  4395. * extra connection. load_page() falls back to http when the
  4396. * https connection itself fails. */
  4397. char with_scheme[BR_URL_MAX];
  4398. unsigned int n = 0;
  4399. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  4400. s_append(with_scheme, &n, t, sizeof(with_scheme));
  4401. nav_https_upgraded = 1;
  4402. load_remote(with_scheme, push);
  4403. }
  4404. }
  4405. /* ---- layout ---- */
  4406. static struct ufont_face *style_face(const struct br_style *st)
  4407. {
  4408. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  4409. return font_faces[st->font_face - 1];
  4410. return 0;
  4411. }
  4412. static struct ufont_face *run_face(const struct lay_run *r)
  4413. {
  4414. if (r->font_face && r->font_face <= BR_MAX_FACES)
  4415. return font_faces[r->font_face - 1];
  4416. return 0;
  4417. }
  4418. static unsigned int face_text_width(struct ngui *gui,
  4419. const struct br_style *st,
  4420. const char *s, unsigned int n)
  4421. {
  4422. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  4423. st->bold, st->italic, st->mono);
  4424. }
  4425. static int face_line_height(struct ngui *gui, const struct br_style *st)
  4426. {
  4427. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  4428. st->mono);
  4429. }
  4430. static unsigned int run_text_width(struct ngui *gui,
  4431. const struct lay_run *r,
  4432. const char *s, unsigned int n)
  4433. {
  4434. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  4435. r->bold, r->italic, r->mono);
  4436. }
  4437. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  4438. {
  4439. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  4440. r->mono);
  4441. }
  4442. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  4443. {
  4444. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  4445. }
  4446. static struct br_style base_style(void)
  4447. {
  4448. struct br_style s = { 0 };
  4449. s.color = ui.theme.text;
  4450. s.bg = ui.theme.bg;
  4451. s.has_bg = 0;
  4452. for (int i = 0; i < 4; i++) {
  4453. s.border_c[i] = 0;
  4454. s.border_w[i] = 0;
  4455. s.border_s[i] = BR_BORDER_SOLID;
  4456. }
  4457. s.font_px = 16;
  4458. s.bold = 0;
  4459. s.italic = 0;
  4460. s.mono = 0;
  4461. s.underline = 0;
  4462. s.strike = 0;
  4463. s.overline = 0;
  4464. s.align = BR_ALIGN_LEFT;
  4465. s.display = BR_DISPLAY_BLOCK;
  4466. s.no_bullet = 0;
  4467. s.list_style = BR_LIST_AUTO;
  4468. s.uppercase = 0;
  4469. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  4470. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  4471. s.width = s.max_width = s.min_width = 0;
  4472. s.height = s.min_height = s.max_height = 0;
  4473. s.box_sizing = 0;
  4474. s.ml_auto = s.mr_auto = 0;
  4475. s.line_h_pct = 0;
  4476. s.line_h_px = 0;
  4477. s.mt = s.mb = s.ml = s.mr = 0;
  4478. s.pt = s.pb = s.pl = s.pr = 0;
  4479. return s;
  4480. }
  4481. /* Resolve a margin/padding raw value. Percentages use the containing
  4482. * block width for all four sides, as CSS specifies. */
  4483. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  4484. {
  4485. if (unit == 1)
  4486. return base * v / 10000;
  4487. if (unit == 2)
  4488. return st->font_px * v / 100;
  4489. if (unit == 3)
  4490. return (int)br_root_font_px() * v / 100;
  4491. if (unit == 4)
  4492. return 0;
  4493. return v;
  4494. }
  4495. static int mp_px(const struct br_style *st, int side, int base)
  4496. {
  4497. int raw;
  4498. switch (side) {
  4499. case 0: raw = st->mt; break;
  4500. case 1: raw = st->mr; break;
  4501. case 2: raw = st->mb; break;
  4502. case 3: raw = st->ml; break;
  4503. case 4: raw = st->pt; break;
  4504. case 5: raw = st->pr; break;
  4505. case 6: raw = st->pb; break;
  4506. default: raw = st->pl; break;
  4507. }
  4508. if (st->mp_unit[side] == 5)
  4509. return base * raw / 100 + st->mp_calc_px[side];
  4510. return css_mp_px(st, raw, st->mp_unit[side], base);
  4511. }
  4512. static int style_width_px(const struct br_style *st, int base)
  4513. {
  4514. if (st->width_kind == 1)
  4515. return st->width;
  4516. if (st->width_kind == 2)
  4517. return base * (int)st->width / 100;
  4518. if (st->width_kind == 3)
  4519. return base * st->width_calc_pct / 100 + st->width_calc_px;
  4520. return 0;
  4521. }
  4522. static int style_height_px(const struct br_style *st, int base)
  4523. {
  4524. if (st->height_kind == 1)
  4525. return st->height;
  4526. if (st->height_kind == 2)
  4527. return base * (int)st->height / 100;
  4528. if (st->height_kind == 3)
  4529. return base * st->height_calc_pct / 100 + st->height_calc_px;
  4530. return 0;
  4531. }
  4532. static int css_size(unsigned char kind, int val, int base)
  4533. {
  4534. if (kind == 1)
  4535. return val;
  4536. if (kind == 2)
  4537. return base * val / 100;
  4538. return -1;
  4539. }
  4540. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  4541. int thick, int horizontal, unsigned short color,
  4542. unsigned char style)
  4543. {
  4544. int pos;
  4545. if (len <= 0 || thick <= 0)
  4546. return;
  4547. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  4548. if (horizontal)
  4549. ngui_fill_rect(ui, (struct ngui_rect){
  4550. x, y, len, thick}, color);
  4551. else
  4552. ngui_fill_rect(ui, (struct ngui_rect){
  4553. x, y, thick, len}, color);
  4554. return;
  4555. }
  4556. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  4557. int seg = len - pos;
  4558. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  4559. seg = style == BR_BORDER_DASHED ? 4 : 2;
  4560. if (horizontal)
  4561. ngui_fill_rect(ui, (struct ngui_rect){
  4562. x + pos, y, seg, thick}, color);
  4563. else
  4564. ngui_fill_rect(ui, (struct ngui_rect){
  4565. x, y + pos, thick, seg}, color);
  4566. }
  4567. }
  4568. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  4569. const struct br_style *st)
  4570. {
  4571. int top = st->border_w[0], right = st->border_w[1];
  4572. int bottom = st->border_w[2], left = st->border_w[3];
  4573. if (r.w <= 0 || r.h <= 0)
  4574. return;
  4575. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  4576. int i;
  4577. for (i = 0; i < 4; i++)
  4578. if (st->border_w[i] && !st->border_t[i]) {
  4579. ngui_fill_rect(ui, r, st->border_c[i]);
  4580. break;
  4581. }
  4582. return;
  4583. }
  4584. if (top && !st->border_t[0])
  4585. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  4586. st->border_c[0], st->border_s[0]);
  4587. if (bottom && !st->border_t[2])
  4588. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  4589. st->border_c[2], st->border_s[2]);
  4590. if (left && !st->border_t[3])
  4591. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  4592. left, 0, st->border_c[3], st->border_s[3]);
  4593. if (right && !st->border_t[1])
  4594. draw_border_side(ui, r.x + r.w - right, r.y + top,
  4595. r.h - top - bottom, right, 0,
  4596. st->border_c[1], st->border_s[1]);
  4597. }
  4598. static void transform_origin(const struct br_style *st, int w, int h,
  4599. int *ox, int *oy)
  4600. {
  4601. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  4602. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  4603. }
  4604. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  4605. unsigned int a)
  4606. {
  4607. unsigned int dr, dg, db, sr, sg, sb;
  4608. if (a >= 255)
  4609. return s;
  4610. dr = (d >> 11) & 31;
  4611. dg = (d >> 5) & 63;
  4612. db = d & 31;
  4613. sr = (s >> 11) & 31;
  4614. sg = (s >> 5) & 63;
  4615. sb = s & 31;
  4616. dr = (dr * (255 - a) + sr * a) / 255;
  4617. dg = (dg * (255 - a) + sg * a) / 255;
  4618. db = (db * (255 - a) + sb * a) / 255;
  4619. return (unsigned short)((dr << 11) | (dg << 5) | db);
  4620. }
  4621. /* Paint a solid box through scale()/rotate() around transform-origin. This
  4622. * transforms the element's own background box; text and descendants keep
  4623. * their layout (documented approximation). */
  4624. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  4625. unsigned short color,
  4626. const struct br_style *st)
  4627. {
  4628. double sx = st->scale_x / 100.0;
  4629. double sy = st->scale_y / 100.0;
  4630. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  4631. double c = cos(th), sn = sin(th);
  4632. int ox, oy, minx, miny, maxx, maxy, x, y;
  4633. double ax, ay;
  4634. double px[4], py[4];
  4635. int cx1, cy1, cx2, cy2, i;
  4636. if (sx == 0)
  4637. sx = 0.01;
  4638. if (sy == 0)
  4639. sy = 0.01;
  4640. transform_origin(st, box.w, box.h, &ox, &oy);
  4641. ax = box.x + ox;
  4642. ay = box.y + oy;
  4643. px[0] = -ox; py[0] = -oy;
  4644. px[1] = box.w - ox; py[1] = -oy;
  4645. px[2] = box.w - ox; py[2] = box.h - oy;
  4646. px[3] = -ox; py[3] = box.h - oy;
  4647. minx = miny = 1000000;
  4648. maxx = maxy = -1000000;
  4649. for (i = 0; i < 4; i++) {
  4650. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  4651. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  4652. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  4653. if (dx < minx) minx = dx;
  4654. if (dx > maxx) maxx = dx;
  4655. if (dy < miny) miny = dy;
  4656. if (dy > maxy) maxy = dy;
  4657. }
  4658. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  4659. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  4660. cx2 = page_rect.x + page_rect.w - 12;
  4661. cy2 = page_rect.y + page_rect.h;
  4662. if (cx2 > gui->w) cx2 = gui->w;
  4663. if (cy2 > gui->h) cy2 = gui->h;
  4664. if (minx < cx1) minx = cx1;
  4665. if (miny < cy1) miny = cy1;
  4666. if (maxx > cx2 - 1) maxx = cx2 - 1;
  4667. if (maxy > cy2 - 1) maxy = cy2 - 1;
  4668. for (y = miny; y <= maxy; y++) {
  4669. for (x = minx; x <= maxx; x++) {
  4670. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  4671. double rx = dx * c + dy * sn;
  4672. double ry = -dx * sn + dy * c;
  4673. double bx = rx / sx + ox;
  4674. double by = ry / sy + oy;
  4675. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  4676. gui->px[y * gui->w + x] = color;
  4677. }
  4678. }
  4679. }
  4680. static void draw_image_transformed(struct ngui *gui,
  4681. const struct img_image *im,
  4682. int x, int y, int w, int h,
  4683. int sx100, int sy100, int rot100,
  4684. int origin_x, int origin_y,
  4685. int origin_x_kind, int origin_y_kind)
  4686. {
  4687. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  4688. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  4689. double c = cos(th), sn = sin(th);
  4690. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  4691. double ax, ay;
  4692. double bx[4], by[4];
  4693. int cx1, cy1, cx2, cy2;
  4694. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  4695. return;
  4696. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  4697. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  4698. ax = x + ox;
  4699. ay = y + oy;
  4700. bx[0] = -ox; by[0] = -oy;
  4701. bx[1] = w - ox; by[1] = -oy;
  4702. bx[2] = w - ox; by[2] = h - oy;
  4703. bx[3] = -ox; by[3] = h - oy;
  4704. minx = miny = 1000000;
  4705. maxx = maxy = -1000000;
  4706. for (i = 0; i < 4; i++) {
  4707. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  4708. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  4709. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  4710. if (dx < minx) minx = dx;
  4711. if (dx > maxx) maxx = dx;
  4712. if (dy < miny) miny = dy;
  4713. if (dy > maxy) maxy = dy;
  4714. }
  4715. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  4716. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  4717. cx2 = page_rect.x + page_rect.w - 12;
  4718. cy2 = page_rect.y + page_rect.h;
  4719. if (cx2 > gui->w) cx2 = gui->w;
  4720. if (cy2 > gui->h) cy2 = gui->h;
  4721. if (minx < cx1) minx = cx1;
  4722. if (miny < cy1) miny = cy1;
  4723. if (maxx > cx2 - 1) maxx = cx2 - 1;
  4724. if (maxy > cy2 - 1) maxy = cy2 - 1;
  4725. for (py = miny; py <= maxy; py++) {
  4726. for (px = minx; px <= maxx; px++) {
  4727. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  4728. double rx = dx * c + dy * sn;
  4729. double ry = -dx * sn + dy * c;
  4730. double fx = rx / sx + ox;
  4731. double fy = ry / sy + oy;
  4732. int ix, iy;
  4733. unsigned int si, a;
  4734. unsigned short src;
  4735. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  4736. continue;
  4737. ix = (int)(fx * (double)im->w / w);
  4738. iy = (int)(fy * (double)im->h / h);
  4739. if (ix < 0 || ix >= (int)im->w ||
  4740. iy < 0 || iy >= (int)im->h)
  4741. continue;
  4742. si = (unsigned int)iy * im->w + (unsigned int)ix;
  4743. src = im->px[si];
  4744. a = im->alpha ? im->alpha[si] : 255;
  4745. gui->px[py * gui->w + px] =
  4746. a >= 255 ? src :
  4747. blend_rgb565(gui->px[py * gui->w + px],
  4748. src, a);
  4749. }
  4750. }
  4751. }
  4752. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  4753. unsigned int node, const struct br_style *st);
  4754. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  4755. * first and every pixel outside a corner's arc is restored afterwards. */
  4756. #define BG_ROUND_MAX 64
  4757. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  4758. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  4759. unsigned int node, const struct br_style *st,
  4760. int rtl, int rtr, int rbr, int rbl)
  4761. {
  4762. struct ngui *ui = l->ui;
  4763. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  4764. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  4765. if (ui->nclip > 0)
  4766. clip = ui->clip[ui->nclip - 1];
  4767. for (c = 0; c < 4; c++) {
  4768. if (r[c] > BG_ROUND_MAX)
  4769. r[c] = BG_ROUND_MAX;
  4770. if (r[c] > box.w / 2)
  4771. r[c] = box.w / 2;
  4772. if (r[c] > box.h / 2)
  4773. r[c] = box.h / 2;
  4774. }
  4775. for (c = 0; c < 4; c++) {
  4776. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  4777. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  4778. for (dy = 0; dy < r[c]; dy++)
  4779. for (dx = 0; dx < r[c]; dx++) {
  4780. int px = ox + dx, py = oy + dy;
  4781. if (px >= clip.x && py >= clip.y &&
  4782. px < clip.x + clip.w && py < clip.y + clip.h)
  4783. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  4784. ui->px[py * ui->w + px];
  4785. }
  4786. }
  4787. draw_bg_image(l, box, node, st);
  4788. for (c = 0; c < 4; c++) {
  4789. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  4790. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  4791. /* arc centre, in corner-square coordinates */
  4792. int cx = (c == 1 || c == 2) ? 0 : r[c];
  4793. int cy = (c >= 2) ? 0 : r[c];
  4794. for (dy = 0; dy < r[c]; dy++)
  4795. for (dx = 0; dx < r[c]; dx++) {
  4796. int px = ox + dx, py = oy + dy;
  4797. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  4798. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  4799. continue;
  4800. if (px >= clip.x && py >= clip.y &&
  4801. px < clip.x + clip.w && py < clip.y + clip.h)
  4802. ui->px[py * ui->w + px] =
  4803. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  4804. }
  4805. }
  4806. }
  4807. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  4808. unsigned int node, const struct br_style *st)
  4809. {
  4810. struct br_image *bi;
  4811. struct img_blit b;
  4812. int tw, th, x, y, rep_x, rep_y, posx, posy;
  4813. unsigned int scale = 65536;
  4814. int legacy, tiles = 0, rows = 0;
  4815. int cx1, cy1, cx2, cy2;
  4816. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  4817. return;
  4818. if (doc.nodes[node].bg_img_index < 0 ||
  4819. doc.nodes[node].bg_img_index >= image_count)
  4820. return;
  4821. bi = &images[doc.nodes[node].bg_img_index];
  4822. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  4823. return;
  4824. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  4825. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  4826. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  4827. if (legacy) {
  4828. scale = ((unsigned int)box.w << 16) / bi->img.w;
  4829. tw = box.w;
  4830. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  4831. x = box.x;
  4832. y = box.y;
  4833. rep_x = rep_y = 0;
  4834. } else {
  4835. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  4836. unsigned int sx = ((unsigned int)box.w << 16) /
  4837. bi->img.w;
  4838. unsigned int sy = ((unsigned int)box.h << 16) /
  4839. bi->img.h;
  4840. scale = st->bg_size_kind == 3 ?
  4841. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  4842. } else if (st->bg_size_kind == 1 ||
  4843. st->bg_size_kind == 2) {
  4844. int w = st->bg_size_w;
  4845. int h = st->bg_size_h;
  4846. if (st->bg_size_kind == 2) {
  4847. if (w)
  4848. w = box.w * w / 100;
  4849. if (h)
  4850. h = box.h * h / 100;
  4851. }
  4852. if (w)
  4853. scale = ((unsigned int)w << 16) / bi->img.w;
  4854. else if (h)
  4855. scale = ((unsigned int)h << 16) / bi->img.h;
  4856. }
  4857. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  4858. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  4859. if (tw < 1)
  4860. tw = 1;
  4861. if (th < 1)
  4862. th = 1;
  4863. posx = st->bg_pos_x_kind == 1 ?
  4864. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  4865. posy = st->bg_pos_y_kind == 1 ?
  4866. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  4867. x = box.x + posx;
  4868. y = box.y + posy;
  4869. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  4870. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  4871. if (rep_x) {
  4872. int m = (x - box.x) % tw;
  4873. if (m > 0)
  4874. m -= tw;
  4875. x = box.x + m;
  4876. }
  4877. if (rep_y) {
  4878. int m = (y - box.y) % th;
  4879. if (m > 0)
  4880. m -= th;
  4881. y = box.y + m;
  4882. }
  4883. }
  4884. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  4885. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  4886. cx2 = box.x + box.w;
  4887. cy2 = box.y + box.h;
  4888. if (cx2 > page_rect.x + page_rect.w - 12)
  4889. cx2 = page_rect.x + page_rect.w - 12;
  4890. if (cy2 > page_rect.y + page_rect.h)
  4891. cy2 = page_rect.y + page_rect.h;
  4892. if (cx1 >= cx2 || cy1 >= cy2)
  4893. return;
  4894. b.dst = l->ui->px;
  4895. b.dst_w = l->ui->w;
  4896. b.dst_h = l->ui->h;
  4897. b.clip_x = cx1;
  4898. b.clip_y = cy1;
  4899. b.clip_w = cx2 - cx1;
  4900. b.clip_h = cy2 - cy1;
  4901. b.scale = scale;
  4902. b.bg = ui.theme.bg;
  4903. b.bg2 = ui.theme.bg;
  4904. b.flags = IMG_BLIT_OVER_DST;
  4905. {
  4906. int row_x = x;
  4907. for (;;) {
  4908. for (;;) {
  4909. b.x = x;
  4910. b.y = y;
  4911. img_draw(&bi->img, &b);
  4912. if (!rep_x || ++tiles > 512)
  4913. break;
  4914. x += tw;
  4915. if (x >= box.x + box.w)
  4916. break;
  4917. }
  4918. if (!rep_y || ++rows > 64)
  4919. break;
  4920. y += th;
  4921. if (y >= box.y + box.h)
  4922. break;
  4923. x = row_x;
  4924. }
  4925. }
  4926. }
  4927. static int run_width(const struct lay_run *r)
  4928. {
  4929. if (r->img >= 0)
  4930. return r->iw;
  4931. if (r->img == -2)
  4932. return r->iw;
  4933. return (int)r->w;
  4934. }
  4935. static void start_line(struct lay *l, const struct br_style *st)
  4936. {
  4937. (void)st;
  4938. if (l->nruns == 0) {
  4939. l->line_y = l->y;
  4940. l->line_h = 0;
  4941. }
  4942. l->line_left = l->left;
  4943. l->line_right = l->right;
  4944. if (l->float_active && l->line_y < l->float_bottom) {
  4945. if (l->float_left > l->line_left)
  4946. l->line_left = l->float_left;
  4947. if (l->float_right < l->line_right)
  4948. l->line_right = l->float_right;
  4949. }
  4950. if (l->line_right < l->line_left + 8)
  4951. l->line_right = l->line_left + 8;
  4952. l->line_x = l->line_left;
  4953. l->run_x = l->line_left;
  4954. }
  4955. static void flush_line(struct lay *l)
  4956. {
  4957. int total, x, i, vis;
  4958. if (!l->nruns && l->line_x == l->line_left) {
  4959. l->line_h = 0;
  4960. return;
  4961. }
  4962. total = l->line_x - l->line_left;
  4963. x = l->line_left;
  4964. vis = 1;
  4965. if (l->draw) {
  4966. int lh = l->line_h ? l->line_h : 16;
  4967. vis = l->line_y + lh >= page_rect.y &&
  4968. l->line_y <= page_rect.y + page_rect.h;
  4969. }
  4970. if (l->align == BR_ALIGN_CENTER)
  4971. x += (l->line_right - l->line_left - total) / 2;
  4972. else if (l->align == BR_ALIGN_RIGHT)
  4973. x = l->line_right - total;
  4974. if (x < l->line_left)
  4975. x = l->line_left;
  4976. for (i = 0; i < l->nruns; i++) {
  4977. struct lay_run *r = &l->runs[i];
  4978. int w = run_width(r);
  4979. int ry = l->line_y + r->dy;
  4980. x += r->gap;
  4981. if (l->draw && vis) {
  4982. if (r->form) {
  4983. unsigned int node = r->form - 1;
  4984. struct form_state *fs = form_get(node, 1);
  4985. int hh = r->ih ? r->ih : 20;
  4986. int focused = form_focus == node;
  4987. int disabled = r->form_disabled;
  4988. unsigned short bg = l->ui->theme.panel_alt;
  4989. unsigned short fg = disabled ? 0x8410 : r->color;
  4990. struct ngui_rect box = {x, ry, w, hh};
  4991. if (r->form_kind == FORM_CHECKBOX ||
  4992. r->form_kind == FORM_RADIO) {
  4993. ngui_fill_rect(l->ui, box, bg);
  4994. ngui_frame(l->ui, box,
  4995. focused ? l->ui->theme.accent :
  4996. l->ui->theme.border);
  4997. if (fs && fs->checked) {
  4998. struct ngui_rect dot = {
  4999. x + 4, ry + 4,
  5000. w > 8 ? w - 8 : 1,
  5001. hh > 8 ? hh - 8 : 1
  5002. };
  5003. if (r->form_kind == FORM_RADIO)
  5004. ngui_fill_round_rect(
  5005. l->ui, dot, 4,
  5006. 4, 4, 4,
  5007. l->ui->theme.accent);
  5008. else
  5009. ngui_fill_rect(l->ui,
  5010. dot,
  5011. l->ui->theme.accent);
  5012. }
  5013. } else {
  5014. int editable =
  5015. r->form_kind == FORM_TEXT ||
  5016. r->form_kind == FORM_PASSWORD ||
  5017. r->form_kind == FORM_TEXTAREA;
  5018. int scroll = 0;
  5019. /* Editable fields draw the live value
  5020. * (r->lit is a short copy). */
  5021. static char shown[FORM_VALUE_MAX + 1];
  5022. const char *txt = r->lit;
  5023. unsigned int tl = s_len(r->lit);
  5024. if (editable && fs && fs->len) {
  5025. unsigned int k;
  5026. if (r->form_kind == FORM_PASSWORD) {
  5027. for (k = 0; k < fs->len; k++)
  5028. shown[k] = '*';
  5029. shown[k] = '\0';
  5030. txt = shown;
  5031. } else {
  5032. txt = fs->value;
  5033. }
  5034. tl = fs->len;
  5035. }
  5036. /* The box is drawn in theme colours, so
  5037. * the text is too: the page's CSS colour
  5038. * (dark on a light page) would vanish on
  5039. * the dark field. */
  5040. if (!disabled)
  5041. fg = editable && fs && !fs->len ?
  5042. l->ui->theme.text_dim :
  5043. l->ui->theme.text;
  5044. ngui_fill_rect(l->ui, box, bg);
  5045. ngui_frame(l->ui, box,
  5046. focused ? l->ui->theme.accent :
  5047. l->ui->theme.border);
  5048. /* A value wider than the field shows its
  5049. * tail (where typing happens). */
  5050. if (editable && fs && fs->len && w > 12) {
  5051. int tw = (int)run_text_width(l->ui,
  5052. r, txt, tl);
  5053. if (tw > w - 12)
  5054. scroll = tw - (w - 12);
  5055. }
  5056. ngui_push_clip(l->ui, (struct ngui_rect){
  5057. x + 1, ry + 1,
  5058. w > 2 ? w - 2 : 1,
  5059. hh > 2 ? hh - 2 : 1 });
  5060. ngui_text_px_face(l->ui, run_face(r),
  5061. x + 6 - scroll,
  5062. ry + (hh - r->font_px) / 2 - 1,
  5063. txt, tl, fg, r->font_px,
  5064. r->bold, r->italic, r->mono);
  5065. if (focused && fs && editable) {
  5066. int cw = 0;
  5067. if (fs->len && fs->caret)
  5068. cw = (int)run_text_width(
  5069. l->ui, r, txt,
  5070. fs->caret < fs->len ?
  5071. fs->caret : fs->len);
  5072. ngui_fill_rect(l->ui,
  5073. (struct ngui_rect){
  5074. x + 6 + cw - scroll,
  5075. ry + 4, 1,
  5076. hh > 8 ? hh - 8 : 1
  5077. },
  5078. l->ui->theme.accent);
  5079. }
  5080. ngui_pop_clip(l->ui);
  5081. if (r->form_kind == FORM_SELECT) {
  5082. ngui_text_px(l->ui, x + w - 12,
  5083. ry + 2, "v", 1, fg,
  5084. r->font_px, 0, 0, 0);
  5085. }
  5086. }
  5087. } else if (r->img == -2) {
  5088. int hh = r->ih ? r->ih : 20;
  5089. ngui_fill_rect(l->ui,
  5090. (struct ngui_rect){x, ry, w, hh},
  5091. l->ui->theme.panel_alt);
  5092. ngui_frame(l->ui,
  5093. (struct ngui_rect){x, ry, w, hh},
  5094. l->ui->theme.border);
  5095. ngui_text_px_face(l->ui, run_face(r),
  5096. x + 6, ry + 2, r->lit,
  5097. s_len(r->lit), r->color,
  5098. r->font_px, r->bold, r->italic,
  5099. r->mono);
  5100. } else if (r->img >= 0) {
  5101. struct br_image *bi = &images[r->img];
  5102. if (bi->state == 1 && r->transform_scale) {
  5103. draw_image_transformed(l->ui, &bi->img,
  5104. x, ry, r->iw, r->ih,
  5105. r->scale_x, r->scale_y,
  5106. r->rotate_x100, r->origin_x,
  5107. r->origin_y, r->origin_x_kind,
  5108. r->origin_y_kind);
  5109. } else if (bi->state == 1) {
  5110. struct img_blit b;
  5111. b.dst = l->ui->px;
  5112. b.dst_w = l->ui->w;
  5113. b.dst_h = l->ui->h;
  5114. b.clip_x = page_rect.x;
  5115. b.clip_y = page_rect.y;
  5116. b.clip_w = page_rect.w - 12;
  5117. b.clip_h = page_rect.h;
  5118. b.x = x;
  5119. b.y = ry;
  5120. b.scale = ((unsigned int)r->iw << 16) /
  5121. bi->img.w;
  5122. b.bg = ui.theme.bg;
  5123. b.bg2 = ui.theme.bg;
  5124. b.flags = IMG_BLIT_OVER_DST;
  5125. img_draw(&bi->img, &b);
  5126. }
  5127. } else {
  5128. const char *s = r->has_lit ? r->lit :
  5129. doc.text + r->off;
  5130. unsigned int n = r->has_lit ? s_len(r->lit) :
  5131. r->len;
  5132. ngui_text_px_face(l->ui, run_face(r), x, ry,
  5133. s, n, r->color, r->font_px,
  5134. r->bold, r->italic, r->mono);
  5135. if (r->underline)
  5136. ngui_fill_rect(l->ui,
  5137. (struct ngui_rect){x,
  5138. ry + run_ascent(l->ui, r) + 2,
  5139. w, 1}, r->color);
  5140. if (r->strike)
  5141. ngui_fill_rect(l->ui,
  5142. (struct ngui_rect){x,
  5143. ry + run_ascent(l->ui, r) -
  5144. (r->font_px > 3 ?
  5145. r->font_px / 3 : 1),
  5146. w, 1}, r->color);
  5147. if (r->overline)
  5148. ngui_fill_rect(l->ui,
  5149. (struct ngui_rect){x, ry,
  5150. w, 1}, r->color);
  5151. }
  5152. if (r->form || r->href) {
  5153. if (nhits < HIT_MAX) {
  5154. struct hit *h = &hits[nhits];
  5155. unsigned int target = r->form ?
  5156. r->form - 1 : r->href;
  5157. int hh = (r->form || r->img >= 0) ?
  5158. r->ih :
  5159. run_line_height(l->ui, r);
  5160. int merge = nhits > 0 &&
  5161. hits[nhits - 1].node == target &&
  5162. hits[nhits - 1].y == ry &&
  5163. hits[nhits - 1].h == hh &&
  5164. x <= hits[nhits - 1].x +
  5165. hits[nhits - 1].w + 2;
  5166. if (merge) {
  5167. struct hit *p = &hits[nhits - 1];
  5168. int end = x + w;
  5169. if (end > p->x + p->w)
  5170. p->w = end - p->x;
  5171. } else {
  5172. h->x = x;
  5173. h->y = ry;
  5174. h->w = w;
  5175. h->h = hh;
  5176. h->node = (unsigned short)target;
  5177. nhits++;
  5178. }
  5179. }
  5180. }
  5181. }
  5182. x += w;
  5183. }
  5184. l->y += l->line_h + 2;
  5185. if (l->float_active && l->y >= l->float_bottom)
  5186. l->float_active = 0;
  5187. l->nruns = 0;
  5188. l->line_x = l->left;
  5189. l->run_x = l->left;
  5190. l->line_left = l->left;
  5191. l->line_right = l->right;
  5192. l->line_h = 0;
  5193. l->space_pending = 0;
  5194. }
  5195. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  5196. const struct br_style *st, unsigned short href,
  5197. const char *lit)
  5198. {
  5199. unsigned int n = lit ? s_len(lit) : len;
  5200. const char *tp = lit ? lit : doc.text + off;
  5201. int w = (int)face_text_width(l->ui, st, tp, n);
  5202. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  5203. flush_line(l);
  5204. if (l->nruns == 0) {
  5205. l->line_y = l->y;
  5206. l->line_h = 0;
  5207. start_line(l, st);
  5208. }
  5209. {
  5210. struct lay_run *r = &l->runs[l->nruns++];
  5211. int gap = l->line_x - l->run_x;
  5212. if (gap < 0)
  5213. gap = 0;
  5214. r->gap = (unsigned short)gap;
  5215. r->off = off;
  5216. r->len = len;
  5217. r->color = st->color;
  5218. r->href = href;
  5219. r->dy = 0;
  5220. r->has_lit = 0;
  5221. r->form = 0;
  5222. r->form_kind = 0;
  5223. r->form_disabled = 0;
  5224. r->lit[0] = '\0';
  5225. if (lit && lit[0]) {
  5226. unsigned int i;
  5227. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  5228. r->lit[i] = lit[i];
  5229. r->lit[i] = '\0';
  5230. r->has_lit = 1;
  5231. }
  5232. r->img = -1;
  5233. r->iw = r->ih = 0;
  5234. r->font_px = st->font_px;
  5235. r->bold = st->bold;
  5236. r->italic = st->italic;
  5237. r->mono = st->mono;
  5238. r->font_face = st->font_face;
  5239. /* A control with its own background is a button, not body copy;
  5240. * an inherited link underline would strike through the fill. */
  5241. r->underline = st->underline && !st->has_bg;
  5242. r->strike = st->strike && !st->has_bg;
  5243. r->overline = st->overline && !st->has_bg;
  5244. r->w = (unsigned short)w;
  5245. if (r->has_lit)
  5246. r->w = (unsigned short)run_text_width(
  5247. l->ui, r, r->lit, s_len(r->lit));
  5248. w = r->w;
  5249. }
  5250. l->line_x += w;
  5251. l->run_x = l->line_x;
  5252. {
  5253. int lh = face_line_height(l->ui, st);
  5254. if (st->line_h_px)
  5255. lh = st->line_h_px;
  5256. else if (st->line_h_pct)
  5257. lh = st->font_px * st->line_h_pct / 100;
  5258. if (lh < face_line_height(l->ui, st))
  5259. lh = face_line_height(l->ui, st);
  5260. if (l->line_h < lh)
  5261. l->line_h = lh;
  5262. }
  5263. }
  5264. static void add_image_run(struct lay *l, unsigned int node,
  5265. const struct br_style *st, unsigned short href)
  5266. {
  5267. struct br_image *bi = 0;
  5268. int idx = doc.nodes[node].img_index;
  5269. int dw, dh, maxw;
  5270. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  5271. bi = &images[idx];
  5272. if (l->nruns == 0)
  5273. start_line(l, st);
  5274. if (l->space_pending &&
  5275. (l->nruns > 0 || l->line_x > l->line_left)) {
  5276. int sp = (int)face_text_width(l->ui, st, " ", 1);
  5277. if (l->line_x + sp <= l->line_right)
  5278. l->line_x += sp;
  5279. }
  5280. l->space_pending = 0;
  5281. if (!bi) {
  5282. const char *alt = br_alt(&doc, node);
  5283. struct br_style gs = *st;
  5284. char tmp[96];
  5285. unsigned int n = 0;
  5286. int w;
  5287. gs.color = BR_GRAY;
  5288. gs.underline = 0;
  5289. s_append(tmp, &n, "[", sizeof(tmp));
  5290. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  5291. s_append(tmp, &n, "]", sizeof(tmp));
  5292. w = (int)face_text_width(l->ui, &gs, tmp, n);
  5293. if (l->line_x + w > l->line_right &&
  5294. (l->nruns > 0 || l->line_x > l->line_left))
  5295. flush_line(l);
  5296. add_run(l, 0, 0, &gs, href, tmp);
  5297. if (!l->draw) {
  5298. int t = l->line_y < 0 ? 0 : l->line_y;
  5299. int hh = face_line_height(l->ui, &gs);
  5300. if (t > 65535)
  5301. t = 65535;
  5302. if (hh > 65535)
  5303. hh = 65535;
  5304. img_top[node] = (unsigned short)t;
  5305. img_h[node] = (unsigned short)hh;
  5306. }
  5307. return;
  5308. }
  5309. maxw = l->line_right - l->line_left;
  5310. if (maxw < 8)
  5311. maxw = 8;
  5312. {
  5313. int iw = bi->native_w, ih = bi->native_h;
  5314. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  5315. if (iw <= 0 || ih <= 0) {
  5316. iw = (int)bi->img.w;
  5317. ih = (int)bi->img.h;
  5318. }
  5319. dw = iw;
  5320. dh = ih;
  5321. if (doc.nodes[node].width_attr) {
  5322. int want = doc.nodes[node].width_attr;
  5323. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  5324. have_w = 1;
  5325. }
  5326. if (doc.nodes[node].height_attr) {
  5327. int want = doc.nodes[node].height_attr;
  5328. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  5329. have_h = 1;
  5330. }
  5331. if (have_w && !have_h)
  5332. dh = ih ? ih * dw / iw : 0;
  5333. if (have_h && !have_w)
  5334. dw = iw ? iw * dh / ih : 0;
  5335. if (st->width_kind) {
  5336. css_w = 1;
  5337. if (st->width_kind == 3)
  5338. dw = maxw * st->width_calc_pct / 100 +
  5339. st->width_calc_px;
  5340. else
  5341. dw = st->width_kind == 2 ?
  5342. maxw * (int)st->width / 100 :
  5343. (int)st->width;
  5344. }
  5345. if (st->height_kind) {
  5346. css_h = 1;
  5347. if (st->height_kind == 3)
  5348. dh = maxw * st->height_calc_pct / 100 +
  5349. st->height_calc_px;
  5350. else
  5351. dh = st->height_kind == 2 ?
  5352. maxw * (int)st->height / 100 :
  5353. (int)st->height;
  5354. }
  5355. if (css_w && !css_h)
  5356. dh = ih ? ih * dw / iw : 0;
  5357. if (css_h && !css_w)
  5358. dw = iw ? iw * dh / ih : 0;
  5359. if (st->max_width_kind) {
  5360. int mw = st->max_width_kind == 3 ?
  5361. maxw * st->max_width_calc_pct / 100 +
  5362. st->max_width_calc_px :
  5363. st->max_width_kind == 2 ?
  5364. maxw * (int)st->max_width / 100 :
  5365. (int)st->max_width;
  5366. if (mw > 0 && dw > mw) {
  5367. dh = iw ? ih * mw / iw : 0;
  5368. dw = mw;
  5369. }
  5370. }
  5371. }
  5372. if (dw < 8)
  5373. dw = 8;
  5374. if (dh < 8)
  5375. dh = 8;
  5376. if (dw > maxw) {
  5377. dh = dw ? dh * maxw / dw : dh;
  5378. dw = maxw;
  5379. }
  5380. if (!l->draw) {
  5381. int t = l->line_y < 0 ? 0 : l->line_y;
  5382. if (t > 65535)
  5383. t = 65535;
  5384. if (dh > 65535)
  5385. dh = 65535;
  5386. img_top[node] = (unsigned short)t;
  5387. img_h[node] = (unsigned short)dh;
  5388. }
  5389. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  5390. l->line_x > l->line_left))
  5391. flush_line(l);
  5392. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  5393. flush_line(l);
  5394. if (l->nruns == 0) {
  5395. l->line_y = l->y;
  5396. l->line_h = 0;
  5397. start_line(l, st);
  5398. }
  5399. {
  5400. struct lay_run *r = &l->runs[l->nruns++];
  5401. int gap = l->line_x - l->run_x;
  5402. if (gap < 0)
  5403. gap = 0;
  5404. r->gap = (unsigned short)gap;
  5405. r->off = 0;
  5406. r->len = 0;
  5407. r->color = 0;
  5408. r->href = href;
  5409. r->form = 0;
  5410. r->form_kind = 0;
  5411. r->form_disabled = 0;
  5412. /* Inline replaced elements honour their vertical margins; this
  5413. * is how Bootstrap's negative logo margins centre the wordmark. */
  5414. {
  5415. int idy = mp_px(st, 0, l->right - l->left);
  5416. if (idy < -2048)
  5417. idy = -2048;
  5418. if (idy > 2048)
  5419. idy = 2048;
  5420. r->dy = (signed short)idy;
  5421. }
  5422. r->has_lit = 0;
  5423. r->lit[0] = '\0';
  5424. r->img = (short)idx;
  5425. r->iw = (unsigned short)dw;
  5426. r->ih = (unsigned short)dh;
  5427. r->w = (unsigned short)dw;
  5428. r->font_px = st->font_px;
  5429. r->bold = st->bold;
  5430. r->italic = st->italic;
  5431. r->mono = st->mono;
  5432. r->font_face = st->font_face;
  5433. r->transform_scale = st->transform_scale;
  5434. r->scale_x = st->scale_x;
  5435. r->scale_y = st->scale_y;
  5436. r->rotate_x100 = st->rotate_x100;
  5437. r->origin_x = st->origin_x;
  5438. r->origin_y = st->origin_y;
  5439. r->origin_x_kind = st->origin_x_kind;
  5440. r->origin_y_kind = st->origin_y_kind;
  5441. r->underline = 0;
  5442. }
  5443. if (node < BR_MAX_NODES) {
  5444. layout_boxes[node].x = l->line_x;
  5445. layout_boxes[node].y = l->line_y +
  5446. mp_px(st, 0, l->right - l->left);
  5447. layout_boxes[node].w = dw;
  5448. layout_boxes[node].h = dh;
  5449. layout_boxes[node].valid = 1;
  5450. }
  5451. l->line_x += dw;
  5452. l->run_x = l->line_x;
  5453. if (l->line_h < dh)
  5454. l->line_h = dh;
  5455. }
  5456. static int text_width(struct lay *l, const char *s, unsigned int n,
  5457. const struct br_style *st)
  5458. {
  5459. return (int)face_text_width(l->ui, st, s, n);
  5460. }
  5461. /* Longest prefix that fits in maxw, at least one byte. */
  5462. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  5463. const struct br_style *st, int maxw)
  5464. {
  5465. unsigned int take = 0;
  5466. while (take < n) {
  5467. if (text_width(l, s, take + 1, st) > maxw)
  5468. break;
  5469. take++;
  5470. }
  5471. return take ? take : 1;
  5472. }
  5473. static void emit_word(struct lay *l, const char *s, unsigned int start,
  5474. unsigned int n, unsigned int base,
  5475. const struct br_style *st, unsigned short href)
  5476. {
  5477. int avail;
  5478. int w = text_width(l, s + start, n, st);
  5479. unsigned int off = start;
  5480. if (l->nruns == 0)
  5481. start_line(l, st);
  5482. avail = l->line_right - l->line_left;
  5483. if (st->nowrap) {
  5484. if (n)
  5485. add_run(l, base + start,
  5486. (unsigned short)n, st, href, 0);
  5487. return;
  5488. }
  5489. /* A padded/bordered one-word button can be a few pixels wider than
  5490. * the content box; keep it on one line instead of splitting it. */
  5491. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  5492. add_run(l, base + start,
  5493. (unsigned short)n, st, href, 0);
  5494. return;
  5495. }
  5496. if (l->line_x + w > l->line_right &&
  5497. (l->nruns > 0 || l->line_x > l->line_left)) {
  5498. flush_line(l);
  5499. start_line(l, st);
  5500. avail = l->line_right - l->line_left;
  5501. }
  5502. if (w <= avail) {
  5503. if (n)
  5504. add_run(l, base + start,
  5505. (unsigned short)n, st, href, 0);
  5506. return;
  5507. }
  5508. while (n > 0) {
  5509. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  5510. add_run(l, base + off,
  5511. (unsigned short)take, st, href, 0);
  5512. off += take;
  5513. n -= take;
  5514. if (n) {
  5515. flush_line(l);
  5516. start_line(l, st);
  5517. avail = l->line_right - l->line_left;
  5518. }
  5519. }
  5520. }
  5521. static void emit_text(struct lay *l, const char *s, unsigned int len,
  5522. const struct br_style *st, unsigned short href, int pre)
  5523. {
  5524. unsigned int i = 0;
  5525. unsigned int base;
  5526. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  5527. if (!s || !len)
  5528. return;
  5529. if (space_w <= 0)
  5530. space_w = 8;
  5531. if (l->nruns == 0)
  5532. start_line(l, st);
  5533. base = (unsigned int)(s - doc.text);
  5534. if (st->uppercase) {
  5535. char *p = (char *)s;
  5536. unsigned int j;
  5537. for (j = 0; j < len; j++)
  5538. if (p[j] >= 'a' && p[j] <= 'z')
  5539. p[j] = (char)(p[j] - 'a' + 'A');
  5540. }
  5541. if (pre) {
  5542. while (i < len) {
  5543. unsigned int start;
  5544. if (s[i] == '\n') {
  5545. flush_line(l);
  5546. start_line(l, st);
  5547. i++;
  5548. continue;
  5549. }
  5550. if (s[i] == ' ') {
  5551. if (l->line_x + space_w > l->line_right &&
  5552. (l->nruns > 0 || l->line_x > l->line_left)) {
  5553. flush_line(l);
  5554. start_line(l, st);
  5555. } else {
  5556. l->line_x += space_w;
  5557. }
  5558. i++;
  5559. continue;
  5560. }
  5561. start = i;
  5562. while (i < len && s[i] != ' ' && s[i] != '\n')
  5563. i++;
  5564. emit_word(l, s, start, i - start, base, st, href);
  5565. }
  5566. return;
  5567. }
  5568. while (i < len) {
  5569. unsigned int start, n;
  5570. if (s[i] == ' ') {
  5571. l->space_pending = 1;
  5572. i++;
  5573. continue;
  5574. }
  5575. start = i;
  5576. while (i < len && s[i] != ' ')
  5577. i++;
  5578. n = i - start;
  5579. if (l->space_pending &&
  5580. (l->nruns > 0 || l->line_x > l->line_left)) {
  5581. if (st->nowrap ||
  5582. l->line_x + space_w <= l->line_right)
  5583. l->line_x += space_w;
  5584. }
  5585. l->space_pending = 0;
  5586. emit_word(l, s, start, n, base, st, href);
  5587. }
  5588. }
  5589. static int list_index(unsigned int parent, unsigned int node)
  5590. {
  5591. unsigned int n = 0, i;
  5592. for (i = doc.nodes[parent].first; i && i != node;
  5593. i = doc.nodes[i].next)
  5594. if (doc.nodes[i].tag == BR_TAG_LI)
  5595. n++;
  5596. return (int)n + 1;
  5597. }
  5598. static void list_roman(char *m, unsigned int *n, int v, int upper,
  5599. unsigned int cap)
  5600. {
  5601. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  5602. 50, 40, 10, 9, 5, 4, 1 };
  5603. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  5604. "l", "xl", "x", "ix", "v", "iv", "i" };
  5605. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  5606. "L", "XL", "X", "IX", "V", "IV", "I" };
  5607. unsigned int i;
  5608. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  5609. while (v >= val[i] && *n + 1 < cap) {
  5610. const char *s = upper ? up[i] : lo[i];
  5611. while (*s && *n + 1 < cap)
  5612. m[(*n)++] = *s++;
  5613. v -= val[i];
  5614. }
  5615. }
  5616. }
  5617. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  5618. {
  5619. unsigned int n = 0;
  5620. if (style == BR_LIST_DISC) {
  5621. m[n++] = '-';
  5622. } else if (style == BR_LIST_CIRCLE) {
  5623. m[n++] = 'o';
  5624. } else if (style == BR_LIST_SQUARE) {
  5625. m[n++] = '+';
  5626. } else if (style == BR_LIST_LOWER_ALPHA ||
  5627. style == BR_LIST_UPPER_ALPHA) {
  5628. if (idx >= 1 && idx <= 26)
  5629. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  5630. 'A' : 'a') + idx - 1);
  5631. else
  5632. m[n++] = '?';
  5633. m[n++] = '.';
  5634. } else if (style == BR_LIST_LOWER_ROMAN ||
  5635. style == BR_LIST_UPPER_ROMAN) {
  5636. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  5637. if (n + 1 < cap)
  5638. m[n++] = '.';
  5639. } else {
  5640. s_append_dec(m, &n, (unsigned int)idx, cap);
  5641. if (n + 1 < cap)
  5642. m[n++] = '.';
  5643. }
  5644. m[n] = '\0';
  5645. }
  5646. /* Set by the layout when the control is stretched to its line: a flex item
  5647. * (its box width was assigned by the flex row) or a child of a flex column,
  5648. * whose default align-items: stretch makes inputs full width. */
  5649. static int form_fill_line;
  5650. static void add_form_run(struct lay *l, unsigned int node,
  5651. const struct br_style *st, unsigned short href)
  5652. {
  5653. struct form_state *fs = form_get(node, 1);
  5654. char shown[FORM_VALUE_MAX + 1];
  5655. char opt[64];
  5656. const char *text = "";
  5657. struct lay_run *r;
  5658. int kind = form_kind_of(node);
  5659. int disabled = form_disabled(node);
  5660. int tw, w = 120, h = 20, i;
  5661. if (!fs)
  5662. return;
  5663. if (l->nruns == 0)
  5664. start_line(l, st);
  5665. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  5666. text = "";
  5667. w = 16;
  5668. h = 16;
  5669. } else if (kind == FORM_SELECT) {
  5670. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  5671. s_copy(opt, "Select", sizeof(opt));
  5672. text = opt;
  5673. w = 120;
  5674. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  5675. kind == FORM_RESET) {
  5676. if (fs->len)
  5677. text = fs->value;
  5678. else
  5679. text = kind == FORM_SUBMIT ? "Submit" :
  5680. kind == FORM_RESET ? "Reset" : "Button";
  5681. } else if (kind == FORM_PASSWORD) {
  5682. for (i = 0; i < fs->len; i++)
  5683. shown[i] = '*';
  5684. shown[fs->len] = '\0';
  5685. text = fs->len ? shown : br_placeholder(&doc, node);
  5686. } else {
  5687. if (fs->len)
  5688. text = fs->value;
  5689. else
  5690. text = br_placeholder(&doc, node);
  5691. if (kind == FORM_TEXTAREA) {
  5692. w = 180;
  5693. h = 40;
  5694. }
  5695. }
  5696. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  5697. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  5698. w = tw + 18;
  5699. if (w < 64)
  5700. w = 64;
  5701. h = 22;
  5702. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD) {
  5703. int line_w = l->line_right - l->line_left;
  5704. if (st->width_kind == 1)
  5705. w = st->width;
  5706. else if (st->width_kind == 2)
  5707. w = css_size(st->width_kind, st->width, line_w);
  5708. else if (form_fill_line || st->display == BR_DISPLAY_BLOCK)
  5709. w = line_w - (l->line_x - l->line_left);
  5710. else
  5711. w = 120;
  5712. /* Taller fields for large text (min-height/padding on login
  5713. * pages): keep the box around the glyphs. */
  5714. if (st->font_px + 8 > h)
  5715. h = st->font_px + 8;
  5716. } else if (kind == FORM_SELECT) {
  5717. w = st->width_kind == 1 ? st->width : 120;
  5718. }
  5719. if (w > l->line_right - l->line_left)
  5720. w = l->line_right - l->line_left;
  5721. if (w < 8)
  5722. w = 8;
  5723. if (l->line_x + w > l->line_right &&
  5724. (l->nruns > 0 || l->line_x > l->line_left))
  5725. flush_line(l);
  5726. if (l->nruns >= 96)
  5727. return;
  5728. if (l->nruns == 0) {
  5729. l->line_y = l->y;
  5730. l->line_h = 0;
  5731. start_line(l, st);
  5732. }
  5733. r = &l->runs[l->nruns++];
  5734. r->gap = (unsigned short)(l->line_x - l->run_x);
  5735. r->off = r->len = 0;
  5736. r->color = st->color;
  5737. r->href = href;
  5738. r->dy = 0;
  5739. r->has_lit = 1;
  5740. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  5741. r->lit[i] = text[i];
  5742. r->lit[i] = '\0';
  5743. r->img = -2;
  5744. r->iw = (unsigned short)w;
  5745. r->ih = (unsigned short)h;
  5746. r->w = (unsigned short)w;
  5747. r->font_px = st->font_px;
  5748. r->bold = st->bold;
  5749. r->italic = st->italic;
  5750. r->mono = st->mono;
  5751. r->font_face = st->font_face;
  5752. r->underline = 0;
  5753. r->form = node + 1;
  5754. r->form_kind = (unsigned char)kind;
  5755. r->form_disabled = (unsigned char)disabled;
  5756. if (node < BR_MAX_NODES) {
  5757. layout_boxes[node].x = l->line_x;
  5758. layout_boxes[node].y = l->line_y;
  5759. layout_boxes[node].w = w;
  5760. layout_boxes[node].h = h;
  5761. layout_boxes[node].valid = 1;
  5762. }
  5763. l->line_x += w;
  5764. l->run_x = l->line_x;
  5765. if (l->line_h < h)
  5766. l->line_h = h;
  5767. }
  5768. /* A poster wrapper is absolutely positioned over the media slot; the
  5769. * measured height of its picture is normally added back to the flow. When a
  5770. * loading-skeleton sibling already reserves that slot, adding both doubles
  5771. * the media height and pushes the article text a full screen down. */
  5772. static int has_skeleton_sibling(unsigned int node)
  5773. {
  5774. unsigned int p = doc.nodes[node].parent, c;
  5775. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  5776. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  5777. continue;
  5778. if (doc.nodes[c].class_off &&
  5779. contains_ci(doc.attrs + doc.nodes[c].class_off,
  5780. "skeleton"))
  5781. return 1;
  5782. }
  5783. return 0;
  5784. }
  5785. static void layout_children(struct lay *l, unsigned int parent,
  5786. const struct br_style *pst, int depth,
  5787. unsigned short link);
  5788. static void layout_flex_children(struct lay *l, unsigned int parent,
  5789. const struct br_style *pst, int depth,
  5790. unsigned short link);
  5791. static void layout_grid_children(struct lay *l, unsigned int parent,
  5792. const struct br_style *pst, int depth,
  5793. unsigned short link);
  5794. static void layout_grid_auto(struct lay *l, unsigned int parent,
  5795. const struct br_style *pst, int depth,
  5796. unsigned short link);
  5797. static int flex_item_width(struct lay *l, unsigned int n,
  5798. const struct br_style *cs, int avail);
  5799. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  5800. const struct br_style *pst, int depth,
  5801. unsigned short link);
  5802. static void layout_table_row(struct lay *l, unsigned int row,
  5803. const struct br_style *pst, int depth,
  5804. unsigned short link);
  5805. static int table_has_rowspan(unsigned int table);
  5806. static void layout_table(struct lay *l, unsigned int table,
  5807. const struct br_style *st, int depth,
  5808. unsigned short link);
  5809. /* A flex container whose items are only inline spans is usually just a
  5810. * heading/icon pair. Our flex row positions such items without emitting
  5811. * their inline text in some deep page contexts; normal inline flow renders
  5812. * the same content correctly. */
  5813. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  5814. {
  5815. unsigned int c;
  5816. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  5817. struct br_node *nd = &doc.nodes[c];
  5818. struct br_style cs;
  5819. if (nd->type == BR_NODE_TEXT)
  5820. continue;
  5821. br_style_for(&doc, c, pst, &cs);
  5822. if (cs.display == BR_DISPLAY_NONE)
  5823. continue;
  5824. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  5825. cs.width_kind || cs.has_bg ||
  5826. cs.border_w[0] || cs.border_w[1] ||
  5827. cs.border_w[2] || cs.border_w[3] ||
  5828. nd->tag == BR_TAG_IMG)
  5829. return 1;
  5830. }
  5831. return 0;
  5832. }
  5833. static int css_radius(const struct br_style *st, int corner,
  5834. int w, int h)
  5835. {
  5836. int r = st->radius[corner];
  5837. if (r <= 0)
  5838. return 0;
  5839. if (r > w / 2)
  5840. r = w / 2;
  5841. if (r > h / 2)
  5842. r = h / 2;
  5843. return r;
  5844. }
  5845. /* ---- inline SVG ----
  5846. *
  5847. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  5848. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  5849. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  5850. * opacity and solid paint; a gradient paints the average of its stops) and
  5851. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  5852. #define SVG_CACHE_MAX 48
  5853. #define SVG_CACHE_PIXELS (640 * 1024)
  5854. #define SVG_MAX_POINTS 24576
  5855. struct svg_cache_ent {
  5856. unsigned int node;
  5857. int w, h;
  5858. unsigned short *px;
  5859. unsigned char *a;
  5860. unsigned int stamp;
  5861. };
  5862. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  5863. static unsigned int svg_cache_pixels, svg_cache_clock;
  5864. static struct svgr svg_geom;
  5865. static void *svg_geom_buf;
  5866. /* Current viewport in user units: percentage lengths resolve against it
  5867. * (the viewBox size, not the device pixels). */
  5868. static double svg_vp_w = 300, svg_vp_h = 150;
  5869. /* The layers live in the page heap: forget them before heap_reset(). */
  5870. static void svg_cache_clear(void)
  5871. {
  5872. memset(svg_cache, 0, sizeof(svg_cache));
  5873. svg_cache_pixels = 0;
  5874. svg_geom_buf = 0;
  5875. }
  5876. static int svg_name_is(const char *a, const char *b)
  5877. {
  5878. while (*a && *b) {
  5879. char x = *a, y = *b;
  5880. if (x >= 'A' && x <= 'Z')
  5881. x = (char)(x - 'A' + 'a');
  5882. if (x != y)
  5883. return 0;
  5884. a++;
  5885. b++;
  5886. }
  5887. return *a == *b;
  5888. }
  5889. static const char *svg_elem_name(unsigned int node)
  5890. {
  5891. const struct br_node *nd = &doc.nodes[node];
  5892. if (nd->name_off)
  5893. return doc.attrs + nd->name_off;
  5894. return br_tag_name(nd->tag);
  5895. }
  5896. /* A numeric attribute; a percentage resolves against `base`. */
  5897. static double svg_attr_num(unsigned int node, const char *name, double def,
  5898. double base)
  5899. {
  5900. const char *v = br_find_attr(&doc, node, name);
  5901. const char *p = v;
  5902. int ok = 0;
  5903. double x;
  5904. if (!v)
  5905. return def;
  5906. x = svgr_num(&p, &ok);
  5907. if (!ok)
  5908. return def;
  5909. if (*p == '%')
  5910. x = x * base / 100.0;
  5911. return x;
  5912. }
  5913. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  5914. static int svg_viewbox4(unsigned int node, double vb[4])
  5915. {
  5916. const char *v = br_find_attr(&doc, node, "viewbox");
  5917. const char *p = v;
  5918. int i, ok = 1;
  5919. if (!v)
  5920. return 0;
  5921. for (i = 0; i < 4 && ok; i++)
  5922. vb[i] = svgr_num(&p, &ok);
  5923. return ok && vb[2] > 0 && vb[3] > 0;
  5924. }
  5925. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  5926. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  5927. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  5928. double w, double h, double m[6])
  5929. {
  5930. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  5931. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  5932. int ax = 1, ay = 1;
  5933. if (par && contains_ci(par, "none")) {
  5934. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  5935. m[4] = -vb[0] * sx;
  5936. m[5] = -vb[1] * sy;
  5937. return;
  5938. }
  5939. if (par) {
  5940. if (contains_ci(par, "xmin"))
  5941. ax = 0;
  5942. else if (contains_ci(par, "xmax"))
  5943. ax = 2;
  5944. if (contains_ci(par, "ymin"))
  5945. ay = 0;
  5946. else if (contains_ci(par, "ymax"))
  5947. ay = 2;
  5948. }
  5949. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  5950. (sx < sy ? sx : sy);
  5951. tx = (w - vb[2] * s) * ax / 2.0;
  5952. ty = (h - vb[3] * s) * ay / 2.0;
  5953. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  5954. m[4] = tx - vb[0] * s;
  5955. m[5] = ty - vb[1] * s;
  5956. }
  5957. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  5958. * the paint attribute, then average the gradient's stops. */
  5959. static int svg_url_paint(unsigned int node, const char *attr,
  5960. unsigned short *color, unsigned int *alpha)
  5961. {
  5962. const char *v = 0, *h;
  5963. char id[64];
  5964. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  5965. for (k = 0; node && k < 32 && !v; k++) {
  5966. v = br_find_attr(&doc, node, attr);
  5967. if (!v) {
  5968. const char *style = br_find_attr(&doc, node, "style");
  5969. if (style && contains_ci(style, "url(#"))
  5970. v = strstr(style, "url(#");
  5971. }
  5972. if (v && !contains_ci(v, "url("))
  5973. v = 0;
  5974. node = doc.nodes[node].parent;
  5975. }
  5976. if (!v || !(h = strstr(v, "#")))
  5977. return 0;
  5978. h++;
  5979. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  5980. id[n++] = *h++;
  5981. id[n] = '\0';
  5982. g = br_find_id(&doc, id);
  5983. /* Follow href chains (a gradient that only references another one's
  5984. * stops), at most a few hops. */
  5985. for (k = 0; g && k < 4; k++) {
  5986. unsigned int gi = g - 1;
  5987. const char *ref;
  5988. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  5989. const char *nm, *sc, *so;
  5990. unsigned short col = 0;
  5991. double op = 1;
  5992. if (doc.nodes[c].type != BR_NODE_ELEM)
  5993. continue;
  5994. nm = svg_elem_name(c);
  5995. if (!svg_name_is(nm, "stop"))
  5996. continue;
  5997. sc = br_find_attr(&doc, c, "stop-color");
  5998. so = br_find_attr(&doc, c, "stop-opacity");
  5999. {
  6000. const char *st = br_find_attr(&doc, c, "style");
  6001. const char *q;
  6002. if (st && (q = strstr(st, "stop-color:")) != 0)
  6003. sc = q + 11;
  6004. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  6005. so = q + 13;
  6006. }
  6007. if (sc) {
  6008. unsigned int L = 0;
  6009. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  6010. L++;
  6011. if (!br_parse_color(sc, L, &col))
  6012. col = 0;
  6013. }
  6014. if (so) {
  6015. const char *p = so;
  6016. int ok = 0;
  6017. double x = svgr_num(&p, &ok);
  6018. if (ok)
  6019. op = x < 0 ? 0 : x > 1 ? 1 : x;
  6020. }
  6021. sr += (col >> 11) & 31;
  6022. sg += (col >> 5) & 63;
  6023. sb += col & 31;
  6024. sa += (unsigned int)(op * 255);
  6025. cnt++;
  6026. }
  6027. if (cnt)
  6028. break;
  6029. ref = br_find_attr(&doc, gi, "href");
  6030. if (!ref)
  6031. ref = br_find_attr(&doc, gi, "xlink:href");
  6032. if (!ref || ref[0] != '#')
  6033. break;
  6034. g = br_find_id(&doc, ref + 1);
  6035. }
  6036. if (!cnt)
  6037. return 0;
  6038. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  6039. (sb / cnt));
  6040. *alpha = sa / cnt;
  6041. return 1;
  6042. }
  6043. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  6044. unsigned short *color, unsigned int *alpha)
  6045. {
  6046. int mode = fill ? st->fill_mode : st->stroke_mode;
  6047. const char *op = br_find_attr(&doc, node,
  6048. fill ? "fill-opacity" : "stroke-opacity");
  6049. *alpha = 255;
  6050. switch (mode) {
  6051. case BR_PAINT_UNSET:
  6052. if (!fill)
  6053. return 0;
  6054. *color = 0;
  6055. break;
  6056. case BR_PAINT_COLOR:
  6057. *color = fill ? st->fill : st->stroke;
  6058. break;
  6059. case BR_PAINT_CURRENT:
  6060. *color = st->color;
  6061. break;
  6062. case BR_PAINT_URL:
  6063. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  6064. alpha))
  6065. return 0;
  6066. break;
  6067. default:
  6068. return 0;
  6069. }
  6070. if (op) {
  6071. const char *p = op;
  6072. int ok = 0;
  6073. double x = svgr_num(&p, &ok);
  6074. if (ok)
  6075. *alpha = (unsigned int)(*alpha *
  6076. (x < 0 ? 0 : x > 1 ? 1 : x));
  6077. }
  6078. return *alpha > 0;
  6079. }
  6080. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  6081. const double m[6], const struct br_style *pst,
  6082. unsigned int alpha, int depth);
  6083. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  6084. const double m[6], const struct br_style *st,
  6085. unsigned int alpha, int depth)
  6086. {
  6087. unsigned int c;
  6088. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  6089. if (doc.nodes[c].type == BR_NODE_ELEM)
  6090. svg_draw_node(L, c, m, st, alpha, depth + 1);
  6091. }
  6092. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  6093. const double pm[6], const struct br_style *pst,
  6094. unsigned int alpha, int depth)
  6095. {
  6096. struct br_style st;
  6097. const char *nm = svg_elem_name(node);
  6098. const char *tf;
  6099. double m[6];
  6100. unsigned short color;
  6101. unsigned int pa;
  6102. int shape = 0, fillable = 1;
  6103. if (depth > 24 || !nm)
  6104. return;
  6105. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  6106. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  6107. svg_name_is(nm, "lineargradient") ||
  6108. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  6109. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  6110. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  6111. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  6112. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  6113. svg_name_is(nm, "foreignobject"))
  6114. return;
  6115. br_style_for(&doc, node, pst, &st);
  6116. if (st.display == BR_DISPLAY_NONE)
  6117. return;
  6118. memcpy(m, pm, sizeof(m));
  6119. tf = br_find_attr(&doc, node, "transform");
  6120. if (tf)
  6121. svgr_transform(m, tf);
  6122. {
  6123. const char *op = br_find_attr(&doc, node, "opacity");
  6124. if (op) {
  6125. const char *p = op;
  6126. int ok = 0;
  6127. double x = svgr_num(&p, &ok);
  6128. if (ok)
  6129. alpha = (unsigned int)(alpha *
  6130. (x < 0 ? 0 :
  6131. x > 1 ? 1 : x));
  6132. }
  6133. }
  6134. if (!alpha)
  6135. return;
  6136. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  6137. svg_name_is(nm, "switch")) {
  6138. svg_draw_children(L, node, m, &st, alpha, depth);
  6139. return;
  6140. }
  6141. if (svg_name_is(nm, "svg")) {
  6142. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  6143. y = svg_attr_num(node, "y", 0, 0);
  6144. double t[6] = { 1, 0, 0, 1, 0, 0 };
  6145. t[4] = x;
  6146. t[5] = y;
  6147. svgr_mat_mul(m, m, t);
  6148. double ow = svg_vp_w, oh = svg_vp_h;
  6149. if (svg_viewbox4(node, vb)) {
  6150. double w = svg_attr_num(node, "width", vb[2], ow);
  6151. double h = svg_attr_num(node, "height", vb[3], oh);
  6152. double vm[6];
  6153. svg_viewport_matrix(node, vb, w, h, vm);
  6154. svgr_mat_mul(m, m, vm);
  6155. svg_vp_w = vb[2];
  6156. svg_vp_h = vb[3];
  6157. }
  6158. svg_draw_children(L, node, m, &st, alpha, depth);
  6159. svg_vp_w = ow;
  6160. svg_vp_h = oh;
  6161. return;
  6162. }
  6163. if (svg_name_is(nm, "use")) {
  6164. const char *ref = br_find_attr(&doc, node, "href");
  6165. unsigned int tgt;
  6166. double t[6] = { 1, 0, 0, 1, 0, 0 };
  6167. if (!ref)
  6168. ref = br_find_attr(&doc, node, "xlink:href");
  6169. if (!ref || ref[0] != '#')
  6170. return;
  6171. tgt = br_find_id(&doc, ref + 1);
  6172. if (!tgt || tgt - 1 == node)
  6173. return;
  6174. tgt--;
  6175. t[4] = svg_attr_num(node, "x", 0, 0);
  6176. t[5] = svg_attr_num(node, "y", 0, 0);
  6177. svgr_mat_mul(m, m, t);
  6178. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  6179. double vb[4];
  6180. double ow = svg_vp_w, oh = svg_vp_h;
  6181. if (svg_viewbox4(tgt, vb)) {
  6182. double w = svg_attr_num(node, "width", vb[2],
  6183. ow);
  6184. double h = svg_attr_num(node, "height", vb[3],
  6185. oh);
  6186. double vm[6];
  6187. svg_viewport_matrix(tgt, vb, w, h, vm);
  6188. svgr_mat_mul(m, m, vm);
  6189. svg_vp_w = vb[2];
  6190. svg_vp_h = vb[3];
  6191. }
  6192. svg_draw_children(L, tgt, m, &st, alpha, depth);
  6193. svg_vp_w = ow;
  6194. svg_vp_h = oh;
  6195. } else {
  6196. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  6197. }
  6198. return;
  6199. }
  6200. svgr_reset(&svg_geom, m);
  6201. if (svg_name_is(nm, "path")) {
  6202. const char *d = br_find_attr(&doc, node, "d");
  6203. if (d) {
  6204. svgr_path(&svg_geom, d);
  6205. shape = 1;
  6206. }
  6207. } else if (svg_name_is(nm, "rect")) {
  6208. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  6209. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  6210. double rx = svg_attr_num(node, "rx", -1, w);
  6211. double ry = svg_attr_num(node, "ry", -1, h);
  6212. if (rx < 0)
  6213. rx = ry < 0 ? 0 : ry;
  6214. if (ry < 0)
  6215. ry = rx;
  6216. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  6217. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  6218. shape = 1;
  6219. } else if (svg_name_is(nm, "circle")) {
  6220. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  6221. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  6222. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  6223. shape = 1;
  6224. } else if (svg_name_is(nm, "ellipse")) {
  6225. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  6226. svg_attr_num(node, "cy", 0, svg_vp_h),
  6227. svg_attr_num(node, "rx", 0, svg_vp_w),
  6228. svg_attr_num(node, "ry", 0, svg_vp_h));
  6229. shape = 1;
  6230. } else if (svg_name_is(nm, "line")) {
  6231. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  6232. svg_attr_num(node, "y1", 0, svg_vp_h));
  6233. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  6234. svg_attr_num(node, "y2", 0, svg_vp_h));
  6235. shape = 1;
  6236. fillable = 0;
  6237. } else if (svg_name_is(nm, "polyline") ||
  6238. svg_name_is(nm, "polygon")) {
  6239. const char *pts = br_find_attr(&doc, node, "points");
  6240. if (pts) {
  6241. svgr_points(&svg_geom, pts,
  6242. svg_name_is(nm, "polygon"));
  6243. shape = 1;
  6244. }
  6245. }
  6246. if (!shape)
  6247. return;
  6248. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  6249. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  6250. st.fill_evenodd);
  6251. if (svg_paint(node, &st, 0, &color, &pa)) {
  6252. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  6253. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  6254. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  6255. }
  6256. }
  6257. /* <text> elements: drawn straight onto the page every frame (the glyph
  6258. * renderer targets the ngui canvas, not a layer). x/y map through the
  6259. * accumulated transform; the font size scales with it. */
  6260. static void svg_draw_text(struct ngui *ui, unsigned int node,
  6261. const double pm[6], const struct br_style *pst,
  6262. int ox, int oy, int depth)
  6263. {
  6264. unsigned int c;
  6265. if (depth > 24)
  6266. return;
  6267. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  6268. struct br_style st;
  6269. const char *nm, *tf;
  6270. double m[6];
  6271. if (doc.nodes[c].type != BR_NODE_ELEM)
  6272. continue;
  6273. nm = svg_elem_name(c);
  6274. if (!nm || svg_name_is(nm, "defs") ||
  6275. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  6276. svg_name_is(nm, "clippath"))
  6277. continue;
  6278. br_style_for(&doc, c, pst, &st);
  6279. if (st.display == BR_DISPLAY_NONE)
  6280. continue;
  6281. memcpy(m, pm, sizeof(m));
  6282. tf = br_find_attr(&doc, c, "transform");
  6283. if (tf)
  6284. svgr_transform(m, tf);
  6285. if (svg_name_is(nm, "text")) {
  6286. unsigned int t = doc.nodes[c].first;
  6287. const char *s;
  6288. unsigned int n, tw;
  6289. double x = svg_attr_num(c, "x", 0, 0),
  6290. y = svg_attr_num(c, "y", 0, 0);
  6291. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  6292. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  6293. int tx, ty, anchor;
  6294. unsigned short col;
  6295. unsigned int pa;
  6296. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  6297. continue;
  6298. if (px < 6)
  6299. px = 6;
  6300. if (px > 72)
  6301. px = 72;
  6302. if (!svg_paint(c, &st, 1, &col, &pa))
  6303. continue;
  6304. s = doc.text + doc.nodes[t].text_off;
  6305. n = doc.nodes[t].text_len;
  6306. st.font_px = (unsigned char)px;
  6307. tw = face_text_width(ui, &st, s, n);
  6308. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  6309. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  6310. ngui_text_ascent_face(ui, style_face(&st), px,
  6311. st.mono);
  6312. anchor = st.align;
  6313. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  6314. anchor = BR_ALIGN_CENTER;
  6315. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  6316. anchor = BR_ALIGN_RIGHT;
  6317. if (anchor == BR_ALIGN_CENTER)
  6318. tx -= (int)tw / 2;
  6319. else if (anchor == BR_ALIGN_RIGHT)
  6320. tx -= (int)tw;
  6321. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  6322. col, px, st.bold, st.italic,
  6323. st.mono);
  6324. } else {
  6325. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  6326. }
  6327. }
  6328. }
  6329. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  6330. {
  6331. double vb[4];
  6332. if (svg_viewbox4(node, vb)) {
  6333. svg_viewport_matrix(node, vb, w, h, m);
  6334. } else {
  6335. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  6336. }
  6337. }
  6338. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  6339. const struct br_style *st)
  6340. {
  6341. struct svg_cache_ent *e = 0;
  6342. struct svgr_layer L;
  6343. double m[6];
  6344. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  6345. svg_cache_clock++;
  6346. for (i = 0; i < SVG_CACHE_MAX; i++)
  6347. if (svg_cache[i].px && svg_cache[i].node == node &&
  6348. svg_cache[i].w == w && svg_cache[i].h == h) {
  6349. svg_cache[i].stamp = svg_cache_clock;
  6350. return &svg_cache[i];
  6351. }
  6352. if (need > SVG_CACHE_PIXELS)
  6353. return 0;
  6354. /* Evict least recently used layers until this one fits. */
  6355. for (;;) {
  6356. struct svg_cache_ent *lru = 0, *free_slot = 0;
  6357. for (i = 0; i < SVG_CACHE_MAX; i++) {
  6358. if (!svg_cache[i].px) {
  6359. if (!free_slot)
  6360. free_slot = &svg_cache[i];
  6361. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  6362. lru = &svg_cache[i];
  6363. }
  6364. }
  6365. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  6366. e = free_slot;
  6367. break;
  6368. }
  6369. if (!lru)
  6370. return 0;
  6371. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  6372. free(lru->px);
  6373. free(lru->a);
  6374. memset(lru, 0, sizeof(*lru));
  6375. }
  6376. if (!svg_geom_buf) {
  6377. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  6378. if (!svg_geom_buf)
  6379. return 0;
  6380. }
  6381. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  6382. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  6383. e->a = (unsigned char *)calloc(need, 1);
  6384. if (!e->px || !e->a) {
  6385. free(e->px);
  6386. free(e->a);
  6387. memset(e, 0, sizeof(*e));
  6388. return 0;
  6389. }
  6390. e->node = node;
  6391. e->w = w;
  6392. e->h = h;
  6393. e->stamp = svg_cache_clock;
  6394. svg_cache_pixels += need;
  6395. L.px = e->px;
  6396. L.a = e->a;
  6397. L.w = w;
  6398. L.h = h;
  6399. svg_root_matrix(node, w, h, m);
  6400. {
  6401. double vb[4];
  6402. if (svg_viewbox4(node, vb)) {
  6403. svg_vp_w = vb[2];
  6404. svg_vp_h = vb[3];
  6405. } else {
  6406. svg_vp_w = w;
  6407. svg_vp_h = h;
  6408. }
  6409. }
  6410. svg_draw_children(&L, node, m, st, 255, 0);
  6411. return e;
  6412. }
  6413. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  6414. *
  6415. * The markup is parsed into a detached subtree of the page document and
  6416. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  6417. * bitmap, which then behaves like any decoded image. currentColor is
  6418. * black (an image has no inherited text colour); <text> is not drawn. */
  6419. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  6420. {
  6421. unsigned int i = 0;
  6422. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  6423. i = 3;
  6424. while (i < len) {
  6425. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  6426. d[i] == '\r' || d[i] == '\n'))
  6427. i++;
  6428. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  6429. return 1;
  6430. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  6431. i += 4;
  6432. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  6433. i++;
  6434. i += 3;
  6435. continue;
  6436. }
  6437. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  6438. while (i < len && d[i] != '>')
  6439. i++;
  6440. i++;
  6441. continue;
  6442. }
  6443. return 0;
  6444. }
  6445. return 0;
  6446. }
  6447. static int svg_len_attr(unsigned int node, const char *name)
  6448. {
  6449. const char *v = br_find_attr(&doc, node, name);
  6450. int n = 0, any = 0;
  6451. if (!v)
  6452. return 0;
  6453. while (*v == ' ')
  6454. v++;
  6455. while (*v >= '0' && *v <= '9') {
  6456. n = n * 10 + (*v++ - '0');
  6457. any = 1;
  6458. }
  6459. if (*v == '.')
  6460. while (*++v >= '0' && *v <= '9')
  6461. ;
  6462. if (!any || *v == '%')
  6463. return 0;
  6464. return n;
  6465. }
  6466. static int svg_decode_image(const unsigned char *data, unsigned int len,
  6467. struct br_image *bi, int box_w, int box_h)
  6468. {
  6469. unsigned int holder, svg = 0, c, need, i;
  6470. struct br_style base = base_style(), st;
  6471. struct svgr_layer L;
  6472. double vb[4], m[6];
  6473. int w, h, have_vb, nat_w, nat_h;
  6474. holder = br_create_element(&doc, "div", 3);
  6475. if (!holder) {
  6476. s_copy(bi->err, "page is full", sizeof(bi->err));
  6477. return -1;
  6478. }
  6479. holder--;
  6480. br_set_inner_html(&doc, holder, (const char *)data, len);
  6481. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  6482. if (doc.nodes[c].type == BR_NODE_ELEM &&
  6483. doc.nodes[c].tag == BR_TAG_SVG) {
  6484. svg = c;
  6485. break;
  6486. }
  6487. if (!svg) {
  6488. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  6489. return -1;
  6490. }
  6491. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  6492. w = svg_len_attr(svg, "width");
  6493. h = svg_len_attr(svg, "height");
  6494. if (box_w > 0 && box_h > 0) {
  6495. w = box_w;
  6496. h = box_h;
  6497. } else if (!w && !h) {
  6498. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  6499. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  6500. } else if (!w) {
  6501. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  6502. } else if (!h) {
  6503. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  6504. }
  6505. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  6506. * so CSS scaling stays crisp. */
  6507. nat_w = w;
  6508. nat_h = h;
  6509. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  6510. w *= 2;
  6511. h *= 2;
  6512. }
  6513. if (w > BR_IMG_LAYOUT_W) {
  6514. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  6515. w = BR_IMG_LAYOUT_W;
  6516. }
  6517. if (h > 2048)
  6518. h = 2048;
  6519. if (w < 1)
  6520. w = 1;
  6521. if (h < 1)
  6522. h = 1;
  6523. need = (unsigned int)w * (unsigned int)h;
  6524. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  6525. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  6526. return -1;
  6527. }
  6528. if (!svg_geom_buf) {
  6529. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  6530. if (!svg_geom_buf) {
  6531. s_copy(bi->err, "out of memory", sizeof(bi->err));
  6532. return -1;
  6533. }
  6534. }
  6535. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  6536. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  6537. L.a = (unsigned char *)calloc(need, 1);
  6538. if (!L.px || !L.a) {
  6539. free(L.px);
  6540. free(L.a);
  6541. s_copy(bi->err, "out of memory", sizeof(bi->err));
  6542. return -1;
  6543. }
  6544. for (i = 0; i < need; i++)
  6545. L.px[i] = 0xFFFF;
  6546. L.w = w;
  6547. L.h = h;
  6548. base.color = 0x0000;
  6549. br_style_for(&doc, svg, &base, &st);
  6550. svg_root_matrix(svg, w, h, m);
  6551. svg_vp_w = have_vb ? vb[2] : w;
  6552. svg_vp_h = have_vb ? vb[3] : h;
  6553. svg_draw_children(&L, svg, m, &st, 255, 0);
  6554. bi->native_w = nat_w;
  6555. bi->native_h = nat_h;
  6556. bi->img.format = 0;
  6557. bi->img.w = (unsigned int)w;
  6558. bi->img.h = (unsigned int)h;
  6559. bi->img.px = L.px;
  6560. bi->img.alpha = L.a;
  6561. bi->img.flags = 0;
  6562. bi->state = 1;
  6563. image_pixels += need;
  6564. return 0;
  6565. }
  6566. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  6567. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  6568. int *out_w, int *out_h)
  6569. {
  6570. double vb[4];
  6571. int has_vb = svg_viewbox4(node, vb);
  6572. double aw = svg_attr_num(node, "width", -1, cw);
  6573. double ah = svg_attr_num(node, "height", -1, 0);
  6574. int w, h;
  6575. if (st->width_kind)
  6576. w = cw;
  6577. else if (aw > 0)
  6578. w = (int)(aw + 0.5);
  6579. else if (st->height_kind == 1 && has_vb)
  6580. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  6581. else if (ah > 0 && has_vb)
  6582. w = (int)(ah * vb[2] / vb[3] + 0.5);
  6583. else if (has_vb)
  6584. w = cw;
  6585. else
  6586. w = 300;
  6587. if (st->max_width_kind == 1 && w > st->max_width)
  6588. w = st->max_width;
  6589. if (w > cw && cw > 0 && !(aw > 0))
  6590. w = cw;
  6591. if (w < 1)
  6592. w = 1;
  6593. if (w > 2000)
  6594. w = 2000;
  6595. if (st->height_kind == 1)
  6596. h = st->height;
  6597. else if (ah > 0)
  6598. h = (int)(ah + 0.5);
  6599. else if (has_vb)
  6600. h = (int)(w * vb[3] / vb[2] + 0.5);
  6601. else
  6602. h = 150;
  6603. if (h < 1)
  6604. h = 1;
  6605. if (h > 1400)
  6606. h = 1400;
  6607. *out_w = w;
  6608. *out_h = h;
  6609. }
  6610. static void svg_paint_box(struct ngui *ui, unsigned int node,
  6611. const struct br_style *st, int x, int y, int w, int h)
  6612. {
  6613. struct svg_cache_ent *e;
  6614. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  6615. int cx0, cy0, cx1, cy1, px, py;
  6616. double m[6];
  6617. if (ui->nclip > 0)
  6618. clip = ui->clip[ui->nclip - 1];
  6619. cx0 = r.x > clip.x ? r.x : clip.x;
  6620. cy0 = r.y > clip.y ? r.y : clip.y;
  6621. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  6622. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  6623. if (cx0 >= cx1 || cy0 >= cy1)
  6624. return;
  6625. e = svg_layer(node, w, h, st);
  6626. if (e) {
  6627. for (py = cy0; py < cy1; py++) {
  6628. unsigned int srow = (unsigned int)(py - y) *
  6629. (unsigned int)w;
  6630. unsigned short *dst = ui->px + py * ui->w;
  6631. for (px = cx0; px < cx1; px++) {
  6632. unsigned int si = srow + (unsigned int)(px - x);
  6633. unsigned int a = e->a[si];
  6634. if (!a)
  6635. continue;
  6636. dst[px] = a >= 255 ? e->px[si] :
  6637. blend_rgb565(dst[px], e->px[si], a);
  6638. }
  6639. }
  6640. }
  6641. svg_root_matrix(node, w, h, m);
  6642. ngui_push_clip(ui, r);
  6643. svg_draw_text(ui, node, m, st, x, y, 0);
  6644. ngui_pop_clip(ui);
  6645. }
  6646. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  6647. * keep using add_image_run(); this covers the CSS `position:absolute;
  6648. * width:100%` poster pattern used by news sites. */
  6649. static void image_block_size(unsigned int node, const struct br_style *st,
  6650. int cbw, int *out_w, int *out_h)
  6651. {
  6652. struct br_node *nd = &doc.nodes[node];
  6653. int idx = nd->img_index;
  6654. int iw = 0, ih = 0, w, h;
  6655. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  6656. iw = (int)images[idx].img.w;
  6657. ih = (int)images[idx].img.h;
  6658. if (iw <= 0 || ih <= 0) {
  6659. iw = (int)images[idx].native_w;
  6660. ih = (int)images[idx].native_h;
  6661. }
  6662. }
  6663. if (st->width_kind)
  6664. w = style_width_px(st, cbw);
  6665. else if (nd->width_attr)
  6666. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  6667. (int)nd->width_attr;
  6668. else if (iw)
  6669. w = iw;
  6670. else
  6671. w = 64;
  6672. if (w < 8)
  6673. w = 8;
  6674. if (cbw > 0 && w > cbw)
  6675. w = cbw;
  6676. if (st->height_kind)
  6677. h = style_height_px(st, cbw);
  6678. else if (nd->height_attr)
  6679. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  6680. (int)nd->height_attr;
  6681. else if (iw && ih)
  6682. h = w * ih / iw;
  6683. else
  6684. h = 64;
  6685. if (h < 8)
  6686. h = 8;
  6687. *out_w = w;
  6688. *out_h = h;
  6689. }
  6690. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  6691. int dw, int dh)
  6692. {
  6693. int idx = doc.nodes[node].img_index;
  6694. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  6695. struct img_blit b;
  6696. b.dst = l->ui->px;
  6697. b.dst_w = l->ui->w;
  6698. b.dst_h = l->ui->h;
  6699. b.clip_x = page_rect.x;
  6700. b.clip_y = page_rect.y;
  6701. b.clip_w = page_rect.w - 12;
  6702. b.clip_h = page_rect.h;
  6703. b.x = x;
  6704. b.y = y;
  6705. b.scale = ((unsigned int)dw << 16) / images[idx].img.w;
  6706. b.bg = ui.theme.bg;
  6707. b.bg2 = ui.theme.bg;
  6708. b.flags = IMG_BLIT_OVER_DST;
  6709. img_draw(&images[idx].img, &b);
  6710. } else if (l->draw) {
  6711. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  6712. 0xD69A);
  6713. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  6714. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  6715. }
  6716. }
  6717. static void layout_block(struct lay *l, unsigned int node,
  6718. const struct br_style *st, int depth,
  6719. unsigned short link)
  6720. {
  6721. int old_left = l->left, old_right = l->right, old_align = l->align;
  6722. int parent_cb_h = l->cb_h;
  6723. int saved_parent_top = l->parent_top;
  6724. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  6725. int saved_cb_top = l->cb_top;
  6726. int top, l0, r0;
  6727. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  6728. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  6729. int deco_w, deco_h, content_w, content_h, box_h;
  6730. int img_dh = 0;
  6731. int definite_w = 0;
  6732. int normal_top = 0;
  6733. int rel_dx = 0, rel_dy = 0;
  6734. int clip_pushed = 0;
  6735. struct ngui_rect clip_rect;
  6736. /* A DOM level costs about two depth units (layout_block ->
  6737. * layout_children), so 48 covers a ~24-level page. Real news pages
  6738. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  6739. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  6740. return;
  6741. flow_y = l->y;
  6742. flow_left = l->left;
  6743. flow_right = l->right;
  6744. positioned = st->pos == 1 || st->pos == 2;
  6745. relative = st->pos == 3;
  6746. sticky = st->pos == 4;
  6747. shifted = relative || sticky || st->transform_set;
  6748. if (positioned) {
  6749. int def_w = st->width_kind == 1 ? st->width : -1;
  6750. if (st->pos == 2) {
  6751. int avail_w = page_rect.w - 12;
  6752. if (st->right_set && def_w >= 0)
  6753. l->left = page_rect.x + avail_w - st->right -
  6754. def_w;
  6755. else
  6756. l->left = page_rect.x +
  6757. (st->left_set ? st->left : 0);
  6758. l->right = def_w >= 0 ? l->left + def_w :
  6759. page_rect.x + avail_w;
  6760. if (st->bottom_set && st->height_kind)
  6761. l->y = page_rect.y + page_rect.h -
  6762. st->bottom -
  6763. style_height_px(st, page_rect.w);
  6764. else
  6765. l->y = page_rect.y +
  6766. (st->top_set ? st->top : 0);
  6767. } else {
  6768. int left = flow_left + (st->left_set ? st->left : 0);
  6769. unsigned int parent = doc.nodes[node].parent;
  6770. if (st->right_set && def_w >= 0)
  6771. left = flow_right - st->right - def_w;
  6772. l->left = left;
  6773. l->right = def_w >= 0 ? left + def_w :
  6774. flow_right +
  6775. (st->left_set ? st->left : 0);
  6776. l->y = flow_y + (st->top_set ? st->top : 0);
  6777. if (st->bottom_set && st->height_kind &&
  6778. parent < BR_MAX_NODES && block_h[parent] > 0)
  6779. l->y = flow_y + block_h[parent] - st->bottom -
  6780. style_height_px(st, old_right - old_left);
  6781. }
  6782. old_left = l->left;
  6783. old_right = l->right;
  6784. } else if (relative) {
  6785. rel_dx = st->left_set ? st->left :
  6786. (st->right_set ? -st->right : 0);
  6787. rel_dy = st->top_set ? st->top :
  6788. (st->bottom_set ? -st->bottom : 0);
  6789. }
  6790. if (st->transform_set) {
  6791. rel_dx += st->tx;
  6792. rel_dy += st->ty;
  6793. }
  6794. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  6795. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  6796. doc.nodes[node].tag == BR_TAG_SELECT ||
  6797. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  6798. !button_has_elements(node)) {
  6799. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  6800. s_eq(br_type(&doc, node), "hidden"))
  6801. return;
  6802. /* Reached as a block-level box (a flex item): the control
  6803. * fills the box the caller assigned, and its line is flushed
  6804. * here; flex layout resets the run list for the next item, so
  6805. * a queued run would never be drawn. */
  6806. form_fill_line = 1;
  6807. add_form_run(l, node, st, link);
  6808. form_fill_line = 0;
  6809. flush_line(l);
  6810. return;
  6811. }
  6812. flush_line(l);
  6813. cbw = old_right - old_left;
  6814. if (cbw < 8)
  6815. cbw = 8;
  6816. l->y += mp_px(st, 0, cbw);
  6817. top = l->y;
  6818. ml = mp_px(st, 3, cbw);
  6819. mr = mp_px(st, 1, cbw);
  6820. bl = st->border_w[3];
  6821. br = st->border_w[1];
  6822. pl = mp_px(st, 7, cbw);
  6823. pr = mp_px(st, 5, cbw);
  6824. bt = st->border_w[0];
  6825. bb = st->border_w[2];
  6826. pt = mp_px(st, 4, cbw);
  6827. pb = mp_px(st, 6, cbw);
  6828. deco_w = bl + br + pl + pr;
  6829. deco_h = bt + bb + pt + pb;
  6830. if (st->width_kind) {
  6831. int w;
  6832. if (st->width_kind == 3)
  6833. w = cbw * st->width_calc_pct / 100 +
  6834. st->width_calc_px;
  6835. else
  6836. w = css_size(st->width_kind, st->width, cbw);
  6837. if (w < 0)
  6838. w = 0;
  6839. content_w = st->box_sizing ? w - deco_w : w;
  6840. definite_w = 1;
  6841. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  6842. doc.nodes[node].tag == BR_TAG_TD ||
  6843. doc.nodes[node].tag == BR_TAG_TH) &&
  6844. doc.nodes[node].width_attr) {
  6845. /* Legacy table/cell width attributes: percentages resolve
  6846. * against the containing block, bare numbers are pixels. */
  6847. int w = doc.nodes[node].width_pct ?
  6848. cbw * doc.nodes[node].width_attr / 100 :
  6849. doc.nodes[node].width_attr;
  6850. if (w < 0)
  6851. w = 0;
  6852. content_w = st->box_sizing ? w - deco_w : w;
  6853. definite_w = 1;
  6854. } else {
  6855. content_w = cbw - ml - mr - deco_w;
  6856. }
  6857. if (content_w < 0)
  6858. content_w = 0;
  6859. if (st->max_width_kind) {
  6860. int mw = st->max_width_kind == 3 ?
  6861. cbw * st->max_width_calc_pct / 100 +
  6862. st->max_width_calc_px :
  6863. css_size(st->max_width_kind, st->max_width, cbw);
  6864. int max_box = st->box_sizing ? mw : mw + deco_w;
  6865. if (content_w + deco_w > max_box)
  6866. content_w = max_box - deco_w;
  6867. }
  6868. if (st->min_width_kind) {
  6869. int mw = st->min_width_kind == 3 ?
  6870. cbw * st->min_width_calc_pct / 100 +
  6871. st->min_width_calc_px :
  6872. css_size(st->min_width_kind, st->min_width, cbw);
  6873. int min_box = st->box_sizing ? mw : mw + deco_w;
  6874. if (content_w + deco_w < min_box) {
  6875. content_w = min_box - deco_w;
  6876. definite_w = 1;
  6877. }
  6878. }
  6879. if (content_w < 8)
  6880. content_w = 8;
  6881. if (definite_w) {
  6882. int free_w = cbw - ml - mr - deco_w - content_w;
  6883. if (free_w < 0)
  6884. free_w = 0;
  6885. if (st->ml_auto && st->mr_auto) {
  6886. ml = free_w / 2;
  6887. mr = free_w - ml;
  6888. } else if (st->ml_auto) {
  6889. ml = free_w;
  6890. } else if (st->mr_auto) {
  6891. mr = free_w;
  6892. }
  6893. }
  6894. if (doc.nodes[node].tag == BR_TAG_IMG) {
  6895. int iw, ih;
  6896. image_block_size(node, st, cbw, &iw, &ih);
  6897. content_w = iw;
  6898. img_dh = ih;
  6899. }
  6900. l0 = old_left + ml;
  6901. r0 = l0 + deco_w + content_w;
  6902. if (r0 < l0 + 8)
  6903. r0 = l0 + 8;
  6904. normal_top = top;
  6905. if (sticky) {
  6906. if (st->top_set) {
  6907. int stick = page_rect.y + 4 + st->top;
  6908. if (normal_top < stick)
  6909. rel_dy += stick - normal_top;
  6910. } else if (st->bottom_set && block_h[node]) {
  6911. int stick = page_rect.y + page_rect.h - st->bottom -
  6912. block_h[node];
  6913. if (normal_top > stick)
  6914. rel_dy += stick - normal_top;
  6915. }
  6916. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  6917. block_h[doc.nodes[node].parent]) {
  6918. unsigned int p = doc.nodes[node].parent;
  6919. int ptop = l->parent_top;
  6920. int pbottom = ptop + block_h[p];
  6921. int eh = block_h[node];
  6922. int moved_top = normal_top + rel_dy;
  6923. int moved_bottom = moved_top + eh;
  6924. if (moved_bottom > pbottom)
  6925. rel_dy -= moved_bottom - pbottom;
  6926. moved_top = normal_top + rel_dy;
  6927. if (moved_top < ptop)
  6928. rel_dy += ptop - moved_top;
  6929. }
  6930. }
  6931. if (shifted && l->draw) {
  6932. top += rel_dy;
  6933. l0 += rel_dx;
  6934. r0 += rel_dx;
  6935. }
  6936. l->parent_top = top;
  6937. if (st->pos != 0) {
  6938. /* Positioned boxes establish the containing block for their
  6939. * absolutely positioned descendants. */
  6940. l->cb_left = l0;
  6941. l->cb_right = r0;
  6942. l->cb_top = top;
  6943. }
  6944. if (l->draw && block_h[node] &&
  6945. top < page_rect.y + page_rect.h &&
  6946. top + block_h[node] > page_rect.y) {
  6947. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  6948. int rtl = css_radius(st, 0, box.w, box.h);
  6949. int rtr = css_radius(st, 1, box.w, box.h);
  6950. int rbr = css_radius(st, 2, box.w, box.h);
  6951. int rbl = css_radius(st, 3, box.w, box.h);
  6952. if (st->transform_scale) {
  6953. if (st->has_bg)
  6954. fill_transformed_rect(l->ui, box, st->bg, st);
  6955. } else if (rtl || rtr || rbr || rbl) {
  6956. if (st->has_bg) {
  6957. int bw = st->border_w[0];
  6958. if (bw > 0 && !st->border_t[0] &&
  6959. st->border_c[0] != st->bg &&
  6960. box.w > bw * 2 && box.h > bw * 2) {
  6961. struct ngui_rect inner = {
  6962. box.x + bw, box.y + bw,
  6963. box.w - bw * 2, box.h - bw * 2
  6964. };
  6965. int itl = rtl > bw ? rtl - bw : 0;
  6966. int itr = rtr > bw ? rtr - bw : 0;
  6967. int ibr = rbr > bw ? rbr - bw : 0;
  6968. int ibl = rbl > bw ? rbl - bw : 0;
  6969. ngui_fill_round_rect(l->ui, box, rtl,
  6970. rtr, rbr, rbl,
  6971. st->border_c[0]);
  6972. ngui_fill_round_rect(l->ui, inner,
  6973. itl, itr, ibr,
  6974. ibl, st->bg);
  6975. } else {
  6976. ngui_fill_round_rect(l->ui, box, rtl,
  6977. rtr, rbr, rbl,
  6978. st->bg);
  6979. }
  6980. } else if (st->border_w[0] && !st->border_t[0]) {
  6981. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  6982. rbl, st->border_w[0],
  6983. st->border_c[0]);
  6984. }
  6985. /* Rounded boxes paint their background image too
  6986. * (app icons are rounded squares), kept inside the
  6987. * corner arcs. */
  6988. if (st->bg_image)
  6989. draw_bg_image_round(l, box, node, st, rtl, rtr,
  6990. rbr, rbl);
  6991. } else {
  6992. if (st->has_bg)
  6993. ngui_fill_rect(l->ui, box, st->bg);
  6994. if (st->bg_image)
  6995. draw_bg_image(l, box, node, st);
  6996. if (st->border_w[0] || st->border_w[1] ||
  6997. st->border_w[2] || st->border_w[3])
  6998. draw_border_box(l->ui, box, st);
  6999. }
  7000. }
  7001. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  7002. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  7003. content_w, img_dh);
  7004. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  7005. l->ui && l->ui->nclip < 4) {
  7006. clip_rect.x = l0 + bl;
  7007. clip_rect.y = top + bt;
  7008. clip_rect.w = (r0 - l0) - bl - br;
  7009. clip_rect.h = (int)block_h[node] - bt - bb;
  7010. if (clip_rect.w > 0 && clip_rect.h > 0) {
  7011. ngui_push_clip(l->ui, clip_rect);
  7012. clip_pushed = 1;
  7013. }
  7014. }
  7015. l->left = l0 + bl + pl;
  7016. l->right = l->left + content_w;
  7017. if (l->right < l->left + 8)
  7018. l->right = l->left + 8;
  7019. l->align = st->align;
  7020. l->line_left = l->left;
  7021. l->line_right = l->right;
  7022. l->y = top + bt + pt;
  7023. if (doc.nodes[node].tag == BR_TAG_HR) {
  7024. if (l->draw)
  7025. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  7026. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  7027. l->y += 8;
  7028. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  7029. int vw = l->right - l->left;
  7030. int vh;
  7031. if (doc.nodes[node].width_pct)
  7032. vw = vw * doc.nodes[node].width_attr / 100;
  7033. else if (doc.nodes[node].width_attr)
  7034. vw = doc.nodes[node].width_attr;
  7035. if (vw > l->right - l->left)
  7036. vw = l->right - l->left;
  7037. if (vw < 8)
  7038. vw = 8;
  7039. vh = vw * 9 / 16;
  7040. if (vh > 240)
  7041. vh = 240;
  7042. if (vh < 80)
  7043. vh = 80;
  7044. if (l->draw) {
  7045. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  7046. vw, vh}, 0xD69A);
  7047. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  7048. vw, vh}, 0x8410);
  7049. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  7050. 0x4208);
  7051. }
  7052. l->y += vh + 4;
  7053. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  7054. int dw, dh, cw = l->right - l->left;
  7055. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  7056. if (l->draw && l->y < page_rect.y + page_rect.h &&
  7057. l->y + dh > page_rect.y)
  7058. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  7059. l->y += dh;
  7060. } else {
  7061. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  7062. !st->no_bullet) {
  7063. char *m = li_marker[node];
  7064. if (!m[0]) {
  7065. unsigned int parent = doc.nodes[node].parent;
  7066. int style = st->list_style;
  7067. int idx = parent ? list_index(parent, node) : 1;
  7068. if (style == BR_LIST_AUTO)
  7069. style = (parent &&
  7070. doc.nodes[parent].tag ==
  7071. BR_TAG_OL) ?
  7072. BR_LIST_DECIMAL : BR_LIST_DISC;
  7073. list_marker_text(m, sizeof(li_marker[node]),
  7074. style, idx);
  7075. }
  7076. if (l->draw && m[0]) {
  7077. int mw = (int)ngui_text_width_ui(l->ui, m);
  7078. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  7079. st->color);
  7080. }
  7081. }
  7082. /* This box's definite content height, for its children's
  7083. * percentage heights. */
  7084. if (doc.nodes[node].tag == BR_TAG_HTML ||
  7085. doc.nodes[node].tag == BR_TAG_BODY)
  7086. l->cb_h = layout_view_h;
  7087. else if (st->height_kind == 1)
  7088. l->cb_h = (int)st->height -
  7089. (st->box_sizing ? deco_h : 0);
  7090. else if (st->height_kind == 2 && parent_cb_h > 0)
  7091. l->cb_h = parent_cb_h * (int)st->height / 100 -
  7092. (st->box_sizing ? deco_h : 0);
  7093. else
  7094. l->cb_h = 0;
  7095. if (l->cb_h < 0)
  7096. l->cb_h = 0;
  7097. if (doc.nodes[node].tag == BR_TAG_TR)
  7098. layout_table_row(l, node, st, depth + 1, link);
  7099. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  7100. table_has_rowspan(node))
  7101. layout_table(l, node, st, depth + 1, link);
  7102. else if (st->grid_auto)
  7103. layout_grid_auto(l, node, st, depth + 1, link);
  7104. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  7105. st->grid_gap > 0)
  7106. layout_grid_children(l, node, st, depth + 1, link);
  7107. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  7108. flex_wants_row(node, st))
  7109. layout_flex_children(l, node, st, depth + 1, link);
  7110. else if (st->display == BR_DISPLAY_FLEX && st->flex_col &&
  7111. st->align_items == 1) {
  7112. /* align-items: center in a column: the items' lines
  7113. * (an app card's icon and label) are centred; a child
  7114. * with its own text-align keeps it. */
  7115. struct br_style cst = *st;
  7116. cst.align = BR_ALIGN_CENTER;
  7117. l->align = BR_ALIGN_CENTER;
  7118. layout_children(l, node, &cst, depth + 1, link);
  7119. } else
  7120. layout_children(l, node, st, depth + 1, link);
  7121. l->cb_h = parent_cb_h;
  7122. }
  7123. flush_line(l);
  7124. if (clip_pushed)
  7125. ngui_pop_clip(l->ui);
  7126. if (l->float_active) {
  7127. if (l->y < l->float_bottom)
  7128. l->y = l->float_bottom;
  7129. l->float_active = 0;
  7130. }
  7131. if (doc.nodes[node].tag == BR_TAG_IMG) {
  7132. content_h = img_dh;
  7133. } else if (st->height_kind == 2 &&
  7134. doc.nodes[node].tag != BR_TAG_HTML &&
  7135. doc.nodes[node].tag != BR_TAG_BODY) {
  7136. /* A percentage of the containing block's definite height, or
  7137. * auto when it has none (it used to resolve against the
  7138. * width). The result is a minimum: without scrollable inner
  7139. * boxes, an app shell's height:100%; overflow:hidden column
  7140. * would otherwise clip everything past the first screen. */
  7141. int auto_h = l->y - (top + bt + pt);
  7142. content_h = parent_cb_h > 0 ?
  7143. parent_cb_h * (int)st->height / 100 -
  7144. (st->box_sizing ? deco_h : 0) : 0;
  7145. if (content_h < auto_h)
  7146. content_h = auto_h;
  7147. } else if (st->height_kind &&
  7148. !((doc.nodes[node].tag == BR_TAG_HTML ||
  7149. doc.nodes[node].tag == BR_TAG_BODY) &&
  7150. st->height_kind == 2)) {
  7151. content_h = style_height_px(st, cbw);
  7152. if (st->box_sizing)
  7153. content_h -= deco_h;
  7154. } else {
  7155. /* Percentage heights on html/body resolve against the
  7156. * viewport, but their content still defines the document
  7157. * scroll height. Treating them as auto avoids collapsing
  7158. * the measured page to the containing block width. */
  7159. content_h = l->y - (top + bt + pt);
  7160. }
  7161. if (content_h < 0)
  7162. content_h = 0;
  7163. if (st->max_height_kind) {
  7164. int mh = st->max_height_kind == 3 ?
  7165. cbw * st->max_height_calc_pct / 100 +
  7166. st->max_height_calc_px :
  7167. css_size(st->max_height_kind, st->max_height, cbw);
  7168. int max_box = st->box_sizing ? mh : mh + deco_h;
  7169. if (content_h + deco_h > max_box)
  7170. content_h = max_box - deco_h;
  7171. }
  7172. if (st->min_height_kind &&
  7173. !((doc.nodes[node].tag == BR_TAG_HTML ||
  7174. doc.nodes[node].tag == BR_TAG_BODY) &&
  7175. st->min_height_kind == 2)) {
  7176. int mh = st->min_height_kind == 3 ?
  7177. cbw * st->min_height_calc_pct / 100 +
  7178. st->min_height_calc_px :
  7179. css_size(st->min_height_kind, st->min_height, cbw);
  7180. int min_box = st->box_sizing ? mh : mh + deco_h;
  7181. if (content_h + deco_h < min_box)
  7182. content_h = min_box - deco_h;
  7183. }
  7184. if (content_h < 0)
  7185. content_h = 0;
  7186. box_h = deco_h + content_h;
  7187. if (box_h < 0)
  7188. box_h = 0;
  7189. l->y = (shifted ? normal_top : top) + box_h;
  7190. if (node < BR_MAX_NODES) {
  7191. layout_boxes[node].x = l0;
  7192. layout_boxes[node].y = top;
  7193. layout_boxes[node].w = r0 - l0;
  7194. layout_boxes[node].h = box_h;
  7195. layout_boxes[node].valid = r0 > l0;
  7196. }
  7197. l->left = old_left;
  7198. l->right = old_right;
  7199. l->align = old_align;
  7200. l->y += mp_px(st, 2, cbw);
  7201. if (!l->draw) {
  7202. if (box_h > 65535)
  7203. box_h = 65535;
  7204. block_h[node] = (unsigned short)box_h;
  7205. block_top[node] = (unsigned short)(top < 0 ? 0 :
  7206. top > 65535 ? 65535 : top);
  7207. }
  7208. if (positioned) {
  7209. l->y = flow_y;
  7210. l->left = flow_left;
  7211. l->right = flow_right;
  7212. }
  7213. l->parent_top = saved_parent_top;
  7214. l->cb_left = saved_cb_left;
  7215. l->cb_right = saved_cb_right;
  7216. l->cb_top = saved_cb_top;
  7217. }
  7218. static int text_node_blank(const struct br_node *nd)
  7219. {
  7220. const char *t = doc.text + nd->text_off;
  7221. unsigned int i;
  7222. for (i = 0; i < nd->text_len; i++)
  7223. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  7224. t[i] != '\r')
  7225. return 0;
  7226. return 1;
  7227. }
  7228. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  7229. * text/image widths in the subtree, plus padding and margins. This keeps
  7230. * Bootstrap's floated nav items on one line instead of giving each the whole
  7231. * row. */
  7232. static int text_space(char c)
  7233. {
  7234. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  7235. }
  7236. static int intrinsic_width(struct ngui *ui, unsigned int node,
  7237. const struct br_style *pst, int depth, int base)
  7238. {
  7239. unsigned int c;
  7240. int line_w = 0, max_w = 0;
  7241. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  7242. if (depth > 32)
  7243. return 0;
  7244. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7245. struct br_node *nd = &doc.nodes[c];
  7246. struct br_style cs;
  7247. if (nd->type == BR_NODE_TEXT) {
  7248. const char *t = doc.text + nd->text_off;
  7249. unsigned int tn = nd->text_len;
  7250. if (doc.nodes[node].tag == BR_TAG_PRE) {
  7251. line_w += (int)face_text_width(ui, pst, t, tn);
  7252. } else {
  7253. unsigned int ti = 0;
  7254. int first = 1;
  7255. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  7256. int sp = (int)face_text_width(ui, pst, " ", 1);
  7257. while (ti < tn) {
  7258. unsigned int ts;
  7259. while (ti < tn && text_space(t[ti]))
  7260. ti++;
  7261. ts = ti;
  7262. while (ti < tn && !text_space(t[ti]))
  7263. ti++;
  7264. if (ti == ts)
  7265. break;
  7266. if (!first || lead)
  7267. line_w += sp;
  7268. lead = 0;
  7269. line_w += (int)face_text_width(ui, pst,
  7270. t + ts, ti - ts);
  7271. first = 0;
  7272. }
  7273. }
  7274. continue;
  7275. }
  7276. br_style_for(&doc, c, pst, &cs);
  7277. if (cs.display == BR_DISPLAY_NONE)
  7278. continue;
  7279. if (nd->tag == BR_TAG_BR) {
  7280. if (line_w > max_w)
  7281. max_w = line_w;
  7282. line_w = 0;
  7283. continue;
  7284. }
  7285. if (nd->tag == BR_TAG_IMG) {
  7286. /* Measure the image as layout will draw it: a CSS or
  7287. * attribute height keeps the intrinsic aspect ratio, and
  7288. * a CSS width overrides the native pixel width. Bootstrap
  7289. * sizes the Cloudron logo with height:40px only. */
  7290. int idx = nd->img_index;
  7291. int iw = 0, ih = 0;
  7292. if (idx >= 0 && idx < image_count &&
  7293. images[idx].state == 1) {
  7294. iw = (int)images[idx].native_w;
  7295. ih = (int)images[idx].native_h;
  7296. if (iw <= 0 || ih <= 0) {
  7297. iw = (int)images[idx].img.w;
  7298. ih = (int)images[idx].img.h;
  7299. }
  7300. }
  7301. if (cs.width_kind) {
  7302. int ww = style_width_px(&cs, base);
  7303. line_w += ww > 0 ? ww : 64;
  7304. } else if (nd->width_attr) {
  7305. line_w += nd->width_attr;
  7306. } else if (nd->height_attr && iw && ih) {
  7307. line_w += iw * (int)nd->height_attr / ih;
  7308. } else if (cs.height_kind && iw && ih) {
  7309. int hh = style_height_px(&cs, base);
  7310. line_w += hh > 0 ? iw * hh / ih : iw;
  7311. } else if (iw) {
  7312. line_w += iw;
  7313. } else {
  7314. line_w += 64;
  7315. }
  7316. continue;
  7317. }
  7318. {
  7319. int cw = mp_px(&cs, 7, base) +
  7320. mp_px(&cs, 5, base) +
  7321. mp_px(&cs, 3, base) +
  7322. mp_px(&cs, 1, base) +
  7323. cs.border_w[1] + cs.border_w[3];
  7324. /* width/height do not apply to non-replaced inline
  7325. * boxes. The tagesschau home label is an inline span
  7326. * with width:1px for the mobile icon-only header; using
  7327. * that width made the whole subnav collapse to a
  7328. * one-character column. */
  7329. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  7330. cw += cs.width_kind == 1 ? cs.width :
  7331. style_width_px(&cs, base);
  7332. else
  7333. cw += intrinsic_width(ui, c, &cs, depth + 1,
  7334. base);
  7335. if (flex_row || cs.float_left ||
  7336. cs.display == BR_DISPLAY_INLINE ||
  7337. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  7338. line_w += cw;
  7339. } else {
  7340. if (line_w > max_w)
  7341. max_w = line_w;
  7342. line_w = 0;
  7343. if (cw > max_w)
  7344. max_w = cw;
  7345. }
  7346. }
  7347. if (line_w > 4096 || max_w > 4096)
  7348. break;
  7349. }
  7350. return line_w > max_w ? line_w : max_w;
  7351. }
  7352. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  7353. * the main user: .row > .col-md-* with float:left and a percentage width.
  7354. * Each column is laid out with its own left/right edge and the row advances
  7355. * to the tallest column. Returns the first child not consumed. */
  7356. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  7357. const struct br_style *pst, int depth,
  7358. unsigned short link)
  7359. {
  7360. unsigned int n = first;
  7361. int row_left = l->left, row_right = l->right;
  7362. int row_top, row_bottom, xl, xr, any = 0;
  7363. int fl_left = row_left, fl_right = row_right, fl_bottom;
  7364. flush_line(l);
  7365. row_top = l->y;
  7366. row_bottom = l->y;
  7367. fl_bottom = row_top;
  7368. xl = row_left;
  7369. xr = row_right;
  7370. while (n) {
  7371. struct br_node *nd = &doc.nodes[n];
  7372. struct br_style cs;
  7373. unsigned short lk = link;
  7374. int colw, right;
  7375. if (nd->type == BR_NODE_TEXT) {
  7376. if (text_node_blank(nd)) {
  7377. n = nd->next;
  7378. continue;
  7379. }
  7380. break;
  7381. }
  7382. br_style_for(&doc, n, pst, &cs);
  7383. if (cs.display == BR_DISPLAY_NONE) {
  7384. n = nd->next;
  7385. continue;
  7386. }
  7387. /* A float blockifies its box: Bootstrap floats inline
  7388. * anchors too (the navbar brand and its text links), and
  7389. * their padding must be honoured. */
  7390. if (!cs.float_left)
  7391. break;
  7392. if (nd->tag == BR_TAG_A && nd->href_off)
  7393. lk = (unsigned short)n;
  7394. right = cs.float_left == 2;
  7395. if (cs.width_kind == 2 || cs.width_kind == 3) {
  7396. colw = style_width_px(&cs, row_right - row_left);
  7397. } else if (cs.width_kind == 1) {
  7398. colw = (int)cs.width;
  7399. } else {
  7400. int base = row_right - row_left;
  7401. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  7402. mp_px(&cs, 7, base) +
  7403. mp_px(&cs, 5, base) +
  7404. mp_px(&cs, 3, base) +
  7405. mp_px(&cs, 1, base);
  7406. if (colw < 8)
  7407. colw = 8;
  7408. }
  7409. if (colw < 8)
  7410. colw = 8;
  7411. if (colw > row_right - row_left)
  7412. colw = row_right - row_left;
  7413. /* The float column width is already resolved. */
  7414. cs.width_kind = 0;
  7415. cs.max_width_kind = 0;
  7416. if (right) {
  7417. if (any && xr - colw < xl) {
  7418. row_top = row_bottom;
  7419. row_bottom = row_top;
  7420. xl = row_left;
  7421. xr = row_right;
  7422. }
  7423. if (xr - colw < xl)
  7424. colw = xr - xl;
  7425. if (colw < 8)
  7426. colw = 8;
  7427. l->left = xr - colw;
  7428. if (l->left < row_left)
  7429. l->left = row_left;
  7430. l->right = xr;
  7431. xr = l->left;
  7432. if (xr < fl_right)
  7433. fl_right = xr;
  7434. } else {
  7435. if (any && xl + colw > xr) {
  7436. row_top = row_bottom;
  7437. row_bottom = row_top;
  7438. xl = row_left;
  7439. xr = row_right;
  7440. }
  7441. l->left = xl;
  7442. l->right = xl + colw;
  7443. xl += colw;
  7444. if (xl > fl_left)
  7445. fl_left = xl;
  7446. }
  7447. if (l->right < l->left + 8)
  7448. l->right = l->left + 8;
  7449. l->y = row_top;
  7450. l->line_x = l->left;
  7451. l->run_x = l->left;
  7452. l->line_y = l->y;
  7453. l->line_h = 0;
  7454. l->nruns = 0;
  7455. l->space_pending = 0;
  7456. l->align = cs.align;
  7457. layout_block(l, n, &cs, depth + 1, lk);
  7458. if (l->y > row_bottom)
  7459. row_bottom = l->y;
  7460. if (l->y > fl_bottom)
  7461. fl_bottom = l->y;
  7462. any = 1;
  7463. n = nd->next;
  7464. }
  7465. l->left = row_left;
  7466. l->right = row_right;
  7467. if (n && any) {
  7468. struct br_node *nd = &doc.nodes[n];
  7469. int inline_next = 0;
  7470. if (nd->type == BR_NODE_TEXT) {
  7471. inline_next = 1;
  7472. } else if (nd->type == BR_NODE_ELEM) {
  7473. struct br_style cs;
  7474. br_style_for(&doc, n, pst, &cs);
  7475. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  7476. cs.display != BR_DISPLAY_NONE &&
  7477. !br_tag_is_block(nd->tag);
  7478. }
  7479. if (inline_next) {
  7480. if (l->float_active) {
  7481. if (l->float_left > fl_left)
  7482. fl_left = l->float_left;
  7483. if (l->float_right < fl_right)
  7484. fl_right = l->float_right;
  7485. if (l->float_bottom > fl_bottom)
  7486. fl_bottom = l->float_bottom;
  7487. }
  7488. l->float_active = 1;
  7489. l->float_left = fl_left;
  7490. l->float_right = fl_right;
  7491. l->float_bottom = fl_bottom;
  7492. l->y = row_top;
  7493. } else {
  7494. l->float_active = 0;
  7495. l->y = row_bottom;
  7496. }
  7497. } else {
  7498. l->float_active = 0;
  7499. l->y = row_bottom;
  7500. }
  7501. l->line_x = l->left;
  7502. l->run_x = l->left;
  7503. l->line_left = l->left;
  7504. l->line_right = l->right;
  7505. l->line_y = l->y;
  7506. l->line_h = 0;
  7507. l->nruns = 0;
  7508. l->space_pending = 0;
  7509. return n;
  7510. }
  7511. static int flex_item_width(struct lay *l, unsigned int n,
  7512. const struct br_style *cs, int avail)
  7513. {
  7514. struct br_node *nd = &doc.nodes[n];
  7515. (void)l;
  7516. int w;
  7517. if (cs->width_kind == 2 || cs->width_kind == 3)
  7518. w = style_width_px(cs, avail);
  7519. else if (cs->width_kind == 1)
  7520. w = (int)cs->width;
  7521. else if (nd->tag == BR_TAG_IMG) {
  7522. int idx = nd->img_index;
  7523. if (idx >= 0 && idx < image_count &&
  7524. images[idx].state == 1)
  7525. w = (int)images[idx].img.w;
  7526. else if (nd->width_attr)
  7527. w = (int)nd->width_attr;
  7528. else
  7529. w = 64;
  7530. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  7531. nd->tag == BR_TAG_TEXTAREA) {
  7532. /* A control has no content to measure: its default size
  7533. * (a search field in a filter bar). */
  7534. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  7535. } else {
  7536. w = intrinsic_width(l->ui, n, cs, 0, avail);
  7537. }
  7538. /* Explicit widths are content-box sizes; the flex item's outer width
  7539. * must include padding, borders and margins. */
  7540. w += mp_px(cs, 7, avail);
  7541. w += mp_px(cs, 5, avail);
  7542. w += mp_px(cs, 3, avail);
  7543. w += mp_px(cs, 1, avail);
  7544. w += cs->border_w[1] + cs->border_w[3];
  7545. if (w < 24)
  7546. w = 24;
  7547. if (w > avail)
  7548. w = avail;
  7549. return w;
  7550. }
  7551. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  7552. * on one line, not one full-width block each. Place intrinsic widths from
  7553. * left to right and wrap when the row is full. */
  7554. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  7555. const struct br_style *pst, int depth,
  7556. unsigned short link)
  7557. {
  7558. unsigned int n = first;
  7559. int row_left = l->left, row_right = l->right;
  7560. int avail = row_right - row_left;
  7561. int x = row_left, y = l->y, row_h = 0, any = 0;
  7562. /* Each box sets l->align from its own style; the text after the row
  7563. * must keep the container's (a centred .fa-fw icon centred the menu
  7564. * label that followed it). */
  7565. unsigned char row_align = l->align;
  7566. flush_line(l);
  7567. y = l->y;
  7568. while (n) {
  7569. struct br_node *nd = &doc.nodes[n];
  7570. struct br_style cs;
  7571. unsigned short lk = link;
  7572. int colw, h;
  7573. if (nd->type == BR_NODE_TEXT) {
  7574. if (!text_node_blank(nd))
  7575. break;
  7576. if (any)
  7577. x += 4;
  7578. n = nd->next;
  7579. continue;
  7580. }
  7581. br_style_for(&doc, n, pst, &cs);
  7582. if (cs.display == BR_DISPLAY_NONE) {
  7583. n = nd->next;
  7584. continue;
  7585. }
  7586. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  7587. break;
  7588. if (nd->tag == BR_TAG_A && nd->href_off)
  7589. lk = (unsigned short)n;
  7590. colw = flex_item_width(l, n, &cs, avail);
  7591. /* A few pixels of slack keep a single long token (boot.S)
  7592. * from wrapping at the exact content width. */
  7593. colw += 8;
  7594. if (colw > avail)
  7595. colw = avail;
  7596. cs.width_kind = 0;
  7597. cs.max_width_kind = 0;
  7598. if (any && x + colw > row_right) {
  7599. y += row_h + 2;
  7600. x = row_left;
  7601. row_h = 0;
  7602. any = 0;
  7603. }
  7604. if (any && x > row_left)
  7605. x += 4;
  7606. l->left = x;
  7607. l->right = x + colw;
  7608. if (l->right < l->left + 8)
  7609. l->right = l->left + 8;
  7610. l->y = y;
  7611. l->line_x = l->left;
  7612. l->run_x = l->left;
  7613. l->line_y = l->y;
  7614. l->line_h = 0;
  7615. l->nruns = 0;
  7616. l->space_pending = 0;
  7617. l->align = cs.align;
  7618. layout_block(l, n, &cs, depth + 1, lk);
  7619. h = l->y - y;
  7620. if (h > row_h)
  7621. row_h = h;
  7622. x += colw;
  7623. any = 1;
  7624. n = nd->next;
  7625. }
  7626. if (any)
  7627. y += row_h;
  7628. l->left = row_left;
  7629. l->right = row_right;
  7630. l->align = row_align;
  7631. l->y = y;
  7632. l->line_x = l->left;
  7633. l->run_x = l->left;
  7634. l->line_y = l->y;
  7635. l->line_h = 0;
  7636. l->nruns = 0;
  7637. l->space_pending = 0;
  7638. return n;
  7639. }
  7640. struct flex_item {
  7641. unsigned int node;
  7642. unsigned short link;
  7643. int w;
  7644. };
  7645. static void layout_flex_children(struct lay *l, unsigned int parent,
  7646. const struct br_style *pst, int depth,
  7647. unsigned short link)
  7648. {
  7649. struct flex_item it[32];
  7650. unsigned int c;
  7651. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  7652. int row_left = l->left, row_right = l->right;
  7653. int avail = row_right - row_left;
  7654. int idx, row_top;
  7655. unsigned char row_align = l->align;
  7656. if (avail < 160 || depth > 48) {
  7657. layout_children(l, parent, pst, depth, link);
  7658. return;
  7659. }
  7660. /* If direct text is not just whitespace, normal block flow handles it
  7661. * better than pretending it is a flex item. */
  7662. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7663. struct br_node *nd = &doc.nodes[c];
  7664. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7665. layout_children(l, parent, pst, depth, link);
  7666. return;
  7667. }
  7668. }
  7669. for (c = doc.nodes[parent].first;
  7670. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  7671. c = doc.nodes[c].next) {
  7672. struct br_node *nd = &doc.nodes[c];
  7673. struct br_style cs;
  7674. if (nd->type == BR_NODE_TEXT)
  7675. continue;
  7676. br_style_for(&doc, c, pst, &cs);
  7677. if (cs.display == BR_DISPLAY_NONE)
  7678. continue;
  7679. it[nitem].node = c;
  7680. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  7681. (unsigned short)c : link;
  7682. it[nitem].w = 0;
  7683. if (cs.flex_grow && !cs.width_kind)
  7684. grow_count++;
  7685. else
  7686. fixed += flex_item_width(l, c, &cs, avail);
  7687. nitem++;
  7688. }
  7689. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  7690. if (grow_w < 96)
  7691. grow_w = 96;
  7692. for (idx = 0; idx < nitem; idx++) {
  7693. struct br_style cs;
  7694. br_style_for(&doc, it[idx].node, pst, &cs);
  7695. if (cs.flex_grow && !cs.width_kind)
  7696. it[idx].w = grow_w;
  7697. else
  7698. it[idx].w = flex_item_width(l, it[idx].node, &cs, avail);
  7699. if (it[idx].w > avail)
  7700. it[idx].w = avail;
  7701. if (it[idx].w < 8)
  7702. it[idx].w = 8;
  7703. }
  7704. row_top = l->y;
  7705. idx = 0;
  7706. while (idx < nitem) {
  7707. int start = idx, count = 0, row_w = 0;
  7708. int free_w, x, extra = 0, row_h = 0, k;
  7709. while (idx < nitem) {
  7710. int add = it[idx].w + (count ? gap : 0);
  7711. /* CSS default is nowrap; only flex-wrap: wrap (1)
  7712. * starts a new row. */
  7713. if (count && pst->flex_wrap == 1 &&
  7714. row_w + add > avail)
  7715. break;
  7716. row_w += add;
  7717. count++;
  7718. idx++;
  7719. }
  7720. if (!count) {
  7721. count = 1;
  7722. row_w = it[start].w;
  7723. idx = start + 1;
  7724. }
  7725. free_w = avail - row_w;
  7726. if (free_w < 0)
  7727. free_w = 0;
  7728. x = row_left;
  7729. if (pst->justify == 1) {
  7730. x += free_w / 2;
  7731. } else if (pst->justify == 2) {
  7732. x += free_w;
  7733. } else if (pst->justify == 3) {
  7734. extra = count > 1 ? free_w / (count - 1) : 0;
  7735. } else if (pst->justify == 4) {
  7736. extra = count ? free_w / count : 0;
  7737. x += extra / 2;
  7738. } else if (pst->justify == 5) {
  7739. extra = count ? free_w / (count + 1) : 0;
  7740. x += extra;
  7741. }
  7742. for (k = 0; k < count; k++) {
  7743. int node = (int)it[start + k].node;
  7744. int h = block_h[node];
  7745. if (h > row_h)
  7746. row_h = h;
  7747. }
  7748. if (pst->height_kind) {
  7749. int hh = style_height_px(pst, avail);
  7750. if (hh > row_h)
  7751. row_h = hh;
  7752. }
  7753. for (k = 0; k < count; k++) {
  7754. struct br_style cs;
  7755. int node = (int)it[start + k].node;
  7756. int yoff = 0;
  7757. br_style_for(&doc, node, pst, &cs);
  7758. cs.width_kind = 0;
  7759. cs.max_width_kind = 0;
  7760. if (l->draw && pst->align_items &&
  7761. row_h > block_h[node]) {
  7762. if (pst->align_items == 1)
  7763. yoff = (row_h - block_h[node]) / 2;
  7764. else if (pst->align_items == 2)
  7765. yoff = row_h - block_h[node];
  7766. }
  7767. l->left = x;
  7768. l->right = x + it[start + k].w;
  7769. if (l->right < l->left + 8)
  7770. l->right = l->left + 8;
  7771. l->y = row_top + yoff;
  7772. l->line_x = l->left;
  7773. l->run_x = l->left;
  7774. l->line_y = l->y;
  7775. l->line_h = 0;
  7776. l->nruns = 0;
  7777. l->space_pending = 0;
  7778. l->align = cs.align;
  7779. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  7780. if (!l->draw) {
  7781. int h = l->y - row_top;
  7782. if (h > row_h)
  7783. row_h = h;
  7784. }
  7785. x += it[start + k].w;
  7786. if (k + 1 < count)
  7787. x += gap + extra;
  7788. }
  7789. row_top += row_h;
  7790. }
  7791. l->left = row_left;
  7792. l->right = row_right;
  7793. l->align = row_align;
  7794. l->y = row_top;
  7795. l->line_x = l->left;
  7796. l->run_x = l->left;
  7797. l->line_y = l->y;
  7798. l->line_h = 0;
  7799. l->nruns = 0;
  7800. l->space_pending = 0;
  7801. }
  7802. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  7803. * plus the grid-area hints used by site shells (site notice/footer full
  7804. * width, column-start left, page-content right). Anything more elaborate
  7805. * falls back to normal block flow. */
  7806. static int grid_track_width(unsigned char kind, unsigned short val,
  7807. int avail, int other)
  7808. {
  7809. if (kind == 2)
  7810. return avail * (int)val / 100;
  7811. if (kind == 1)
  7812. return val;
  7813. return other;
  7814. }
  7815. static void layout_grid_children(struct lay *l, unsigned int parent,
  7816. const struct br_style *pst, int depth,
  7817. unsigned short link)
  7818. {
  7819. unsigned int n;
  7820. int row_left = l->left, row_right = l->right;
  7821. int avail = row_right - row_left;
  7822. int gap = pst->grid_gap;
  7823. int track_total = avail - gap;
  7824. int col0, col1, x0, x1;
  7825. int row_y, row_bottom, have_left = 0, have_right = 0;
  7826. unsigned int c;
  7827. if (avail < 32 || depth > 48)
  7828. return;
  7829. if (track_total < 16)
  7830. track_total = 16;
  7831. col0 = grid_track_width((unsigned char)(pst->width_kind),
  7832. pst->width, track_total, 0);
  7833. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  7834. pst->max_width, track_total, 0);
  7835. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  7836. int w0 = pst->width ? pst->width : 1;
  7837. int w1 = pst->max_width ? pst->max_width : 1;
  7838. col0 = track_total * w0 / (w0 + w1);
  7839. col1 = track_total - col0;
  7840. } else if (pst->width_kind == 3) {
  7841. col0 = track_total - col1;
  7842. if (col0 < 24)
  7843. col0 = 24;
  7844. } else if (pst->max_width_kind == 3) {
  7845. col1 = track_total - col0;
  7846. if (col1 < 24)
  7847. col1 = 24;
  7848. }
  7849. if (col0 < 24)
  7850. col0 = 24;
  7851. if (col1 < 24)
  7852. col1 = 24;
  7853. if (col0 + col1 > track_total) {
  7854. col1 = track_total - col0;
  7855. if (col1 < 24)
  7856. col1 = 24;
  7857. }
  7858. x0 = row_left;
  7859. x1 = row_left + col0 + gap;
  7860. /* Direct text makes a grid ambiguous; use block flow instead. */
  7861. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7862. struct br_node *nd = &doc.nodes[c];
  7863. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7864. layout_children(l, parent, pst, depth, link);
  7865. return;
  7866. }
  7867. }
  7868. row_y = row_bottom = l->y;
  7869. n = doc.nodes[parent].first;
  7870. while (n) {
  7871. struct br_node *nd = &doc.nodes[n];
  7872. struct br_style cs;
  7873. unsigned short lk = link;
  7874. int slot, x, w;
  7875. if (nd->type == BR_NODE_TEXT) {
  7876. n = nd->next;
  7877. continue;
  7878. }
  7879. br_style_for(&doc, n, pst, &cs);
  7880. if (cs.display == BR_DISPLAY_NONE) {
  7881. n = nd->next;
  7882. continue;
  7883. }
  7884. if (nd->tag == BR_TAG_A && nd->href_off)
  7885. lk = (unsigned short)n;
  7886. slot = cs.grid_slot;
  7887. if (!slot) {
  7888. if (!have_left)
  7889. slot = 2;
  7890. else if (!have_right)
  7891. slot = 3;
  7892. else
  7893. slot = 2;
  7894. }
  7895. if (slot == 1) {
  7896. if (have_left || have_right) {
  7897. row_y = row_bottom;
  7898. have_left = have_right = 0;
  7899. }
  7900. x = row_left;
  7901. w = avail;
  7902. } else if (slot == 2) {
  7903. if (have_left) {
  7904. row_y = row_bottom;
  7905. have_left = have_right = 0;
  7906. }
  7907. x = x0;
  7908. w = col0;
  7909. have_left = 1;
  7910. } else {
  7911. if (have_right) {
  7912. row_y = row_bottom;
  7913. have_left = have_right = 0;
  7914. }
  7915. x = x1;
  7916. w = col1;
  7917. have_right = 1;
  7918. }
  7919. cs.width_kind = 0;
  7920. cs.max_width_kind = 0;
  7921. l->left = x;
  7922. l->right = x + w;
  7923. if (l->right < l->left + 8)
  7924. l->right = l->left + 8;
  7925. l->y = row_y;
  7926. l->line_x = l->left;
  7927. l->run_x = l->left;
  7928. l->line_y = l->y;
  7929. l->line_h = 0;
  7930. l->nruns = 0;
  7931. l->space_pending = 0;
  7932. l->align = cs.align;
  7933. layout_block(l, n, &cs, depth + 1, lk);
  7934. if (l->y > row_bottom)
  7935. row_bottom = l->y;
  7936. n = nd->next;
  7937. }
  7938. l->left = row_left;
  7939. l->right = row_right;
  7940. l->y = row_bottom;
  7941. l->line_x = l->left;
  7942. l->run_x = l->left;
  7943. l->line_y = l->y;
  7944. l->line_h = 0;
  7945. l->nruns = 0;
  7946. l->space_pending = 0;
  7947. }
  7948. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  7949. * capped at four. Used by the project docs' card grids. */
  7950. static void layout_grid_auto(struct lay *l, unsigned int parent,
  7951. const struct br_style *pst, int depth,
  7952. unsigned short link)
  7953. {
  7954. unsigned int n, c;
  7955. int row_left = l->left, row_right = l->right;
  7956. int avail = row_right - row_left;
  7957. int gap = pst->grid_gap;
  7958. int minw = pst->width_kind == 1 ? pst->width : 200;
  7959. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  7960. if (avail < 32 || depth > 48) {
  7961. layout_children(l, parent, pst, depth, link);
  7962. return;
  7963. }
  7964. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7965. struct br_node *nd = &doc.nodes[c];
  7966. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7967. layout_children(l, parent, pst, depth, link);
  7968. return;
  7969. }
  7970. }
  7971. if (minw < 80)
  7972. minw = 80;
  7973. ncols = (avail + gap) / (minw + gap);
  7974. if (ncols < 1)
  7975. ncols = 1;
  7976. if (ncols > 4)
  7977. ncols = 4;
  7978. colw = (avail - gap * (ncols - 1)) / ncols;
  7979. if (colw < 24)
  7980. colw = 24;
  7981. x = row_left;
  7982. n = doc.nodes[parent].first;
  7983. while (n) {
  7984. struct br_node *nd = &doc.nodes[n];
  7985. struct br_style cs;
  7986. unsigned short lk = link;
  7987. int h;
  7988. if (nd->type == BR_NODE_TEXT) {
  7989. n = nd->next;
  7990. continue;
  7991. }
  7992. br_style_for(&doc, n, pst, &cs);
  7993. if (cs.display == BR_DISPLAY_NONE) {
  7994. n = nd->next;
  7995. continue;
  7996. }
  7997. if (nd->tag == BR_TAG_A && nd->href_off)
  7998. lk = (unsigned short)n;
  7999. cs.width_kind = 0;
  8000. cs.max_width_kind = 0;
  8001. l->left = x;
  8002. l->right = x + colw;
  8003. if (l->right < l->left + 8)
  8004. l->right = l->left + 8;
  8005. l->y = y;
  8006. l->line_x = l->left;
  8007. l->run_x = l->left;
  8008. l->line_y = l->y;
  8009. l->line_h = 0;
  8010. l->nruns = 0;
  8011. l->space_pending = 0;
  8012. l->align = cs.align;
  8013. layout_block(l, n, &cs, depth + 1, lk);
  8014. h = l->y - y;
  8015. if (h > row_h)
  8016. row_h = h;
  8017. col++;
  8018. n = nd->next;
  8019. if (col == ncols) {
  8020. y += row_h + gap;
  8021. x = row_left;
  8022. row_h = 0;
  8023. col = 0;
  8024. } else {
  8025. x += colw + gap;
  8026. }
  8027. }
  8028. if (col)
  8029. y += row_h;
  8030. else if (y > start_y)
  8031. y -= gap;
  8032. l->left = row_left;
  8033. l->right = row_right;
  8034. l->y = y;
  8035. l->line_x = l->left;
  8036. l->run_x = l->left;
  8037. l->line_y = l->y;
  8038. l->line_h = 0;
  8039. l->nruns = 0;
  8040. l->space_pending = 0;
  8041. }
  8042. /* Column widths are the widest cell in each column across every row, so all
  8043. * rows line up. The table model is still deliberately basic: no colspan,
  8044. * border-collapse or percentage columns. */
  8045. static void table_columns(struct lay *l, unsigned int table,
  8046. const struct br_style *pst, int avail,
  8047. int *raw, int maxcols, int *out_cols,
  8048. int *out_total)
  8049. {
  8050. unsigned int r, c;
  8051. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  8052. int fixed[12];
  8053. for (c = 0; c < (unsigned int)maxcols; c++) {
  8054. raw[c] = 0;
  8055. fixed[c] = 0;
  8056. }
  8057. /* Intrinsic widths of single-column cells. */
  8058. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  8059. struct br_node *rn = &doc.nodes[r];
  8060. int col = 0;
  8061. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  8062. continue;
  8063. for (c = rn->first; c; c = doc.nodes[c].next) {
  8064. struct br_node *cn = &doc.nodes[c];
  8065. struct br_style cs;
  8066. int w, span;
  8067. if (cn->type != BR_NODE_ELEM ||
  8068. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  8069. continue;
  8070. span = cn->colspan ? cn->colspan : 1;
  8071. br_style_for(&doc, c, pst, &cs);
  8072. if (cs.display == BR_DISPLAY_NONE)
  8073. continue;
  8074. if (col + span > maxcols)
  8075. span = maxcols - col;
  8076. if (span < 1)
  8077. break;
  8078. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  8079. mp_px(&cs, 7, avail) +
  8080. mp_px(&cs, 5, avail) +
  8081. mp_px(&cs, 3, avail) +
  8082. mp_px(&cs, 1, avail) +
  8083. cs.border_w[0] + cs.border_w[1] +
  8084. cs.border_w[2] + cs.border_w[3];
  8085. if (w < 24)
  8086. w = 24;
  8087. if (span == 1) {
  8088. if (w > raw[col])
  8089. raw[col] = w;
  8090. }
  8091. if (col + span > cols)
  8092. cols = col + span;
  8093. col += span;
  8094. }
  8095. }
  8096. /* A colspan cell only has to be as wide as the sum of its columns. */
  8097. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  8098. struct br_node *rn = &doc.nodes[r];
  8099. int col = 0;
  8100. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  8101. continue;
  8102. for (c = rn->first; c; c = doc.nodes[c].next) {
  8103. struct br_node *cn = &doc.nodes[c];
  8104. struct br_style cs;
  8105. int span, w, sum, i;
  8106. if (cn->type != BR_NODE_ELEM ||
  8107. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  8108. continue;
  8109. span = cn->colspan ? cn->colspan : 1;
  8110. if (col + span > maxcols)
  8111. span = maxcols - col;
  8112. if (span < 1)
  8113. break;
  8114. if (span > 1) {
  8115. br_style_for(&doc, c, pst, &cs);
  8116. if (cs.display != BR_DISPLAY_NONE) {
  8117. w = intrinsic_width(l->ui, c, &cs,
  8118. 0, avail) +
  8119. mp_px(&cs, 7, avail) +
  8120. mp_px(&cs, 5, avail) +
  8121. mp_px(&cs, 3, avail) +
  8122. mp_px(&cs, 1, avail) +
  8123. cs.border_w[0] + cs.border_w[1] +
  8124. cs.border_w[2] + cs.border_w[3];
  8125. sum = 0;
  8126. for (i = 0; i < span; i++)
  8127. sum += raw[col + i];
  8128. if (w > sum)
  8129. raw[col + span - 1] += w - sum;
  8130. }
  8131. }
  8132. col += span;
  8133. }
  8134. }
  8135. /* Explicit and percentage widths override intrinsic widths. */
  8136. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  8137. struct br_node *rn = &doc.nodes[r];
  8138. int col = 0;
  8139. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  8140. continue;
  8141. for (c = rn->first; c; c = doc.nodes[c].next) {
  8142. struct br_node *cn = &doc.nodes[c];
  8143. struct br_style cs;
  8144. int span;
  8145. if (cn->type != BR_NODE_ELEM ||
  8146. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  8147. continue;
  8148. span = cn->colspan ? cn->colspan : 1;
  8149. if (col + span > maxcols)
  8150. span = maxcols - col;
  8151. if (span < 1)
  8152. break;
  8153. if (span == 1) {
  8154. br_style_for(&doc, c, pst, &cs);
  8155. if (cs.display != BR_DISPLAY_NONE) {
  8156. if (cs.width_kind == 1) {
  8157. raw[col] = cs.width;
  8158. fixed[col] = 1;
  8159. } else if (cs.width_kind == 2 ||
  8160. cs.width_kind == 3) {
  8161. raw[col] = style_width_px(&cs,
  8162. avail);
  8163. fixed[col] = 1;
  8164. }
  8165. }
  8166. }
  8167. col += span;
  8168. }
  8169. }
  8170. for (c = 0; c < (unsigned int)cols; c++) {
  8171. if (raw[c] < 8)
  8172. raw[c] = 8;
  8173. total += raw[c];
  8174. if (fixed[c])
  8175. fixed_sum += raw[c];
  8176. else {
  8177. free_raw += raw[c];
  8178. free_cols++;
  8179. }
  8180. }
  8181. if (fixed_sum > 0 && fixed_sum < avail) {
  8182. int free_avail = avail - fixed_sum;
  8183. int i;
  8184. if (free_raw > 0) {
  8185. for (i = 0; i < cols; i++)
  8186. if (!fixed[i])
  8187. raw[i] = free_avail * raw[i] /
  8188. free_raw;
  8189. } else if (free_cols > 0) {
  8190. for (i = 0; i < cols; i++)
  8191. if (!fixed[i])
  8192. raw[i] = free_avail / free_cols;
  8193. }
  8194. total = 0;
  8195. for (i = 0; i < cols; i++)
  8196. total += raw[i];
  8197. } else if (total < avail && total > 0) {
  8198. int i;
  8199. for (i = 0; i < cols; i++)
  8200. raw[i] = raw[i] * avail / total;
  8201. total = 0;
  8202. for (i = 0; i < cols; i++)
  8203. total += raw[i];
  8204. }
  8205. *out_cols = cols;
  8206. *out_total = total;
  8207. }
  8208. static void layout_table_row(struct lay *l, unsigned int row,
  8209. const struct br_style *pst, int depth,
  8210. unsigned short link)
  8211. {
  8212. unsigned int n, cell[12];
  8213. int raw[12], colstart[12], colspan[12];
  8214. int prefix[13];
  8215. int ncell = 0, total = 0, cols = 0, col = 0;
  8216. int row_left = l->left, row_right = l->right;
  8217. int avail = row_right - row_left;
  8218. int y = l->y, bottom = l->y;
  8219. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  8220. struct br_node *nd = &doc.nodes[n];
  8221. struct br_style cs;
  8222. int span;
  8223. if (nd->type == BR_NODE_TEXT) {
  8224. if (text_node_blank(nd))
  8225. continue;
  8226. layout_children(l, row, pst, depth, link);
  8227. return;
  8228. }
  8229. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  8230. layout_children(l, row, pst, depth, link);
  8231. return;
  8232. }
  8233. br_style_for(&doc, n, pst, &cs);
  8234. if (cs.display == BR_DISPLAY_NONE)
  8235. continue;
  8236. if (ncell >= 12) {
  8237. layout_children(l, row, pst, depth, link);
  8238. return;
  8239. }
  8240. span = nd->colspan ? nd->colspan : 1;
  8241. if (span > 12 - col)
  8242. span = 12 - col;
  8243. if (span < 1)
  8244. continue;
  8245. cell[ncell] = n;
  8246. colstart[ncell] = col;
  8247. colspan[ncell] = span;
  8248. col += span;
  8249. ncell++;
  8250. }
  8251. if (ncell < 1 || avail < 32) {
  8252. layout_children(l, row, pst, depth, link);
  8253. return;
  8254. }
  8255. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  8256. &total);
  8257. if (cols < 2 || total <= 0) {
  8258. int c;
  8259. total = 0;
  8260. for (c = 0; c < ncell; c++) {
  8261. struct br_style cs;
  8262. br_style_for(&doc, cell[c], pst, &cs);
  8263. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  8264. avail) +
  8265. mp_px(&cs, 7, avail) +
  8266. mp_px(&cs, 5, avail) +
  8267. mp_px(&cs, 3, avail) +
  8268. mp_px(&cs, 1, avail);
  8269. if (raw[c] < 24)
  8270. raw[c] = 24;
  8271. total += raw[c];
  8272. }
  8273. /* A one-column table still has to fill its own width; the
  8274. * intrinsic fallback above otherwise leaves the cell at its
  8275. * text width (HN's outer table and nested story table). */
  8276. if (total > 0 && total < avail) {
  8277. int c;
  8278. for (c = 0; c < ncell; c++)
  8279. raw[c] = raw[c] * avail / total;
  8280. total = avail;
  8281. }
  8282. }
  8283. prefix[0] = row_left;
  8284. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  8285. prefix[n + 1] = prefix[n] + raw[n];
  8286. for (n = 0; n < (unsigned int)ncell; n++) {
  8287. struct br_style cs;
  8288. int start = colstart[n];
  8289. int end = start + colspan[n];
  8290. int w;
  8291. if (end > cols)
  8292. end = cols;
  8293. if (start >= cols)
  8294. continue;
  8295. w = prefix[end] - prefix[start];
  8296. br_style_for(&doc, cell[n], pst, &cs);
  8297. /* The column width already reflects the cell's width property. */
  8298. cs.width_kind = 0;
  8299. cs.max_width_kind = 0;
  8300. if (w < 24)
  8301. w = 24;
  8302. if (w < 8)
  8303. w = 8;
  8304. l->left = prefix[start];
  8305. l->right = l->left + w;
  8306. l->y = y;
  8307. l->line_x = l->left;
  8308. l->run_x = l->left;
  8309. l->line_y = l->y;
  8310. l->line_h = 0;
  8311. l->nruns = 0;
  8312. l->space_pending = 0;
  8313. l->align = cs.align;
  8314. layout_block(l, cell[n], &cs, depth + 1, link);
  8315. if (l->y > bottom)
  8316. bottom = l->y;
  8317. }
  8318. l->left = row_left;
  8319. l->right = row_right;
  8320. l->y = bottom;
  8321. l->line_x = l->left;
  8322. l->run_x = l->left;
  8323. l->line_y = l->y;
  8324. l->line_h = 0;
  8325. l->nruns = 0;
  8326. l->space_pending = 0;
  8327. }
  8328. #define TBL_MAX_ROWS 32
  8329. #define TBL_MAX_COLS 12
  8330. #define TBL_MAX_CELLS 128
  8331. struct tbl_cell {
  8332. unsigned int node;
  8333. unsigned char row, col, rowspan, colspan;
  8334. int height;
  8335. };
  8336. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  8337. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  8338. static int table_active;
  8339. static int table_has_rowspan(unsigned int table)
  8340. {
  8341. unsigned int r, c;
  8342. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  8343. struct br_node *rn = &doc.nodes[r];
  8344. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  8345. continue;
  8346. for (c = rn->first; c; c = doc.nodes[c].next) {
  8347. struct br_node *cn = &doc.nodes[c];
  8348. if (cn->type == BR_NODE_ELEM &&
  8349. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  8350. cn->rowspan > 1)
  8351. return 1;
  8352. }
  8353. }
  8354. return 0;
  8355. }
  8356. static void table_cell_style(unsigned int row, unsigned int cell,
  8357. const struct br_style *st, struct br_style *out)
  8358. {
  8359. struct br_style trs;
  8360. br_style_for(&doc, row, st, &trs);
  8361. br_style_for(&doc, cell, &trs, out);
  8362. }
  8363. /* Tables that use rowspan need row heights before anything is painted. This
  8364. * path builds a small occupancy grid, measures the natural cell heights, then
  8365. * lays every cell out at its row/column position. Tables without rowspan
  8366. * keep the lighter per-row path in layout_table_row(). */
  8367. static void layout_table(struct lay *l, unsigned int table,
  8368. const struct br_style *st, int depth,
  8369. unsigned short link)
  8370. {
  8371. unsigned int rows[TBL_MAX_ROWS];
  8372. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  8373. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  8374. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  8375. int free_raw = 0, free_cols = 0;
  8376. int table_left = l->left, table_right = l->right;
  8377. int top = l->y, avail = table_right - table_left;
  8378. unsigned int r, c;
  8379. int i, rr, cc;
  8380. if (depth > 48 || table_active) {
  8381. layout_children(l, table, st, depth, link);
  8382. return;
  8383. }
  8384. table_active = 1;
  8385. for (r = doc.nodes[table].first;
  8386. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  8387. struct br_node *rn = &doc.nodes[r];
  8388. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  8389. rows[nrows++] = r;
  8390. }
  8391. if (!nrows) {
  8392. table_active = 0;
  8393. layout_children(l, table, st, depth, link);
  8394. return;
  8395. }
  8396. for (rr = 0; rr < nrows; rr++)
  8397. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  8398. tbl_at[rr][cc] = 0;
  8399. for (rr = 0; rr < nrows; rr++) {
  8400. int col = 0;
  8401. for (c = doc.nodes[rows[rr]].first; c;
  8402. c = doc.nodes[c].next) {
  8403. struct br_node *cn = &doc.nodes[c];
  8404. struct br_style cs;
  8405. int rs, csn;
  8406. if (cn->type != BR_NODE_ELEM ||
  8407. (cn->tag != BR_TAG_TD &&
  8408. cn->tag != BR_TAG_TH))
  8409. continue;
  8410. table_cell_style(rows[rr], c, st, &cs);
  8411. if (cs.display == BR_DISPLAY_NONE)
  8412. continue;
  8413. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  8414. col++;
  8415. if (col >= TBL_MAX_COLS)
  8416. break;
  8417. rs = cn->rowspan ? cn->rowspan : 1;
  8418. csn = cn->colspan ? cn->colspan : 1;
  8419. if (rr + rs > nrows)
  8420. rs = nrows - rr;
  8421. if (col + csn > TBL_MAX_COLS)
  8422. csn = TBL_MAX_COLS - col;
  8423. if (rs < 1 || csn < 1)
  8424. continue;
  8425. if (ncells >= TBL_MAX_CELLS)
  8426. break;
  8427. tbl_cells[ncells].node = c;
  8428. tbl_cells[ncells].row = (unsigned char)rr;
  8429. tbl_cells[ncells].col = (unsigned char)col;
  8430. tbl_cells[ncells].rowspan = (unsigned char)rs;
  8431. tbl_cells[ncells].colspan = (unsigned char)csn;
  8432. tbl_cells[ncells].height = 0;
  8433. for (i = rr; i < rr + rs; i++)
  8434. for (int j = col; j < col + csn; j++)
  8435. tbl_at[i][j] =
  8436. (unsigned short)(ncells + 1);
  8437. ncells++;
  8438. col += csn;
  8439. if (col > cols)
  8440. cols = col;
  8441. }
  8442. }
  8443. if (!ncells || cols < 1) {
  8444. table_active = 0;
  8445. layout_children(l, table, st, depth, link);
  8446. return;
  8447. }
  8448. for (i = 0; i < cols; i++) {
  8449. raw[i] = 0;
  8450. fixed[i] = 0;
  8451. }
  8452. /* Intrinsic widths of single-column cells. */
  8453. for (i = 0; i < ncells; i++) {
  8454. struct br_style cs;
  8455. int w;
  8456. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8457. st, &cs);
  8458. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  8459. mp_px(&cs, 7, avail) +
  8460. mp_px(&cs, 5, avail) +
  8461. mp_px(&cs, 3, avail) +
  8462. mp_px(&cs, 1, avail) +
  8463. cs.border_w[0] + cs.border_w[1] +
  8464. cs.border_w[2] + cs.border_w[3];
  8465. if (w < 24)
  8466. w = 24;
  8467. if (tbl_cells[i].colspan == 1) {
  8468. int col = tbl_cells[i].col;
  8469. if (w > raw[col])
  8470. raw[col] = w;
  8471. }
  8472. }
  8473. /* A spanning cell only needs the sum of its columns to be large
  8474. * enough; put the deficit in the last column. */
  8475. for (i = 0; i < ncells; i++) {
  8476. struct br_style cs;
  8477. int w, sum, col, span;
  8478. if (tbl_cells[i].colspan < 2)
  8479. continue;
  8480. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8481. st, &cs);
  8482. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  8483. mp_px(&cs, 7, avail) +
  8484. mp_px(&cs, 5, avail) +
  8485. mp_px(&cs, 3, avail) +
  8486. mp_px(&cs, 1, avail) +
  8487. cs.border_w[0] + cs.border_w[1] +
  8488. cs.border_w[2] + cs.border_w[3];
  8489. col = tbl_cells[i].col;
  8490. span = tbl_cells[i].colspan;
  8491. sum = 0;
  8492. for (int j = 0; j < span; j++)
  8493. sum += raw[col + j];
  8494. if (w > sum)
  8495. raw[col + span - 1] += w - sum;
  8496. }
  8497. /* Explicit/percentage widths, as in table_columns(). */
  8498. for (i = 0; i < ncells; i++) {
  8499. struct br_style cs;
  8500. int col;
  8501. if (tbl_cells[i].colspan != 1)
  8502. continue;
  8503. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8504. st, &cs);
  8505. col = tbl_cells[i].col;
  8506. if (cs.width_kind == 1) {
  8507. raw[col] = cs.width;
  8508. fixed[col] = 1;
  8509. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  8510. raw[col] = style_width_px(&cs, avail);
  8511. fixed[col] = 1;
  8512. }
  8513. }
  8514. for (i = 0; i < cols; i++) {
  8515. if (raw[i] < 8)
  8516. raw[i] = 8;
  8517. total += raw[i];
  8518. if (fixed[i])
  8519. fixed_sum += raw[i];
  8520. else {
  8521. free_raw += raw[i];
  8522. free_cols++;
  8523. }
  8524. }
  8525. if (fixed_sum > 0 && fixed_sum < avail) {
  8526. int free_avail = avail - fixed_sum;
  8527. if (free_raw > 0) {
  8528. for (i = 0; i < cols; i++)
  8529. if (!fixed[i])
  8530. raw[i] = free_avail * raw[i] /
  8531. free_raw;
  8532. } else if (free_cols > 0) {
  8533. for (i = 0; i < cols; i++)
  8534. if (!fixed[i])
  8535. raw[i] = free_avail / free_cols;
  8536. }
  8537. } else if (total < avail && total > 0) {
  8538. for (i = 0; i < cols; i++)
  8539. raw[i] = raw[i] * avail / total;
  8540. }
  8541. prefix[0] = table_left;
  8542. for (i = 0; i < cols; i++)
  8543. prefix[i + 1] = prefix[i] + raw[i];
  8544. /* Measure natural cell heights with the column widths. */
  8545. for (i = 0; i < ncells; i++) {
  8546. struct br_style cs;
  8547. int col = tbl_cells[i].col;
  8548. int span = tbl_cells[i].colspan;
  8549. int w = prefix[col + span] - prefix[col];
  8550. int sl = l->left, sr = l->right, sy = l->y;
  8551. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  8552. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  8553. int sal = l->align, sdraw = l->draw;
  8554. struct ngui *sui = l->ui;
  8555. if (w < 8)
  8556. w = 8;
  8557. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8558. st, &cs);
  8559. cs.width_kind = 0;
  8560. cs.max_width_kind = 0;
  8561. l->draw = 0;
  8562. l->ui = 0;
  8563. l->left = prefix[col];
  8564. l->right = l->left + w;
  8565. l->y = 0;
  8566. l->line_x = l->left;
  8567. l->run_x = l->left;
  8568. l->line_y = 0;
  8569. l->line_h = 0;
  8570. l->nruns = 0;
  8571. l->space_pending = 0;
  8572. l->align = cs.align;
  8573. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  8574. tbl_cells[i].height = block_h[tbl_cells[i].node];
  8575. l->left = sl;
  8576. l->right = sr;
  8577. l->y = sy;
  8578. l->line_x = slx;
  8579. l->run_x = srx;
  8580. l->line_y = sly;
  8581. l->line_h = slh;
  8582. l->nruns = snr;
  8583. l->space_pending = ssp;
  8584. l->align = sal;
  8585. l->draw = sdraw;
  8586. l->ui = sui;
  8587. }
  8588. for (i = 0; i < nrows; i++)
  8589. rowh[i] = 0;
  8590. for (i = 0; i < ncells; i++) {
  8591. int row = tbl_cells[i].row;
  8592. if (tbl_cells[i].rowspan == 1) {
  8593. if (tbl_cells[i].height > rowh[row])
  8594. rowh[row] = tbl_cells[i].height;
  8595. }
  8596. }
  8597. for (i = 0; i < ncells; i++) {
  8598. int row = tbl_cells[i].row;
  8599. int span = tbl_cells[i].rowspan;
  8600. int sum = 0;
  8601. if (span < 2)
  8602. continue;
  8603. for (int j = 0; j < span; j++)
  8604. sum += rowh[row + j];
  8605. if (sum < tbl_cells[i].height)
  8606. rowh[row + span - 1] +=
  8607. tbl_cells[i].height - sum;
  8608. }
  8609. for (i = 0; i < nrows; i++)
  8610. if (rowh[i] < 8)
  8611. rowh[i] = 8;
  8612. rowy[0] = top;
  8613. for (i = 1; i < nrows; i++)
  8614. rowy[i] = rowy[i - 1] + rowh[i - 1];
  8615. if (!l->draw) {
  8616. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  8617. table_active = 0;
  8618. return;
  8619. }
  8620. for (i = 0; i < ncells; i++) {
  8621. struct br_style cs;
  8622. int col = tbl_cells[i].col;
  8623. int span = tbl_cells[i].colspan;
  8624. int row = tbl_cells[i].row;
  8625. int rspan = tbl_cells[i].rowspan;
  8626. int w = prefix[col + span] - prefix[col];
  8627. int h = 0;
  8628. int sl = l->left, sr = l->right, sy = l->y;
  8629. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  8630. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  8631. int sal = l->align;
  8632. int deco;
  8633. for (int j = 0; j < rspan; j++)
  8634. h += rowh[row + j];
  8635. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  8636. cs.width_kind = 0;
  8637. cs.max_width_kind = 0;
  8638. cs.box_sizing = 0;
  8639. deco = mp_px(&cs, 4, avail) +
  8640. mp_px(&cs, 6, avail) +
  8641. cs.border_w[0] + cs.border_w[2];
  8642. cs.height_kind = 1;
  8643. cs.height = h > deco ? h - deco : 0;
  8644. /* The block painter reads block_h[] from the measure pass; make
  8645. * the table cell fill its row/rowspan, not just its content. */
  8646. if (h > 0 && h < 65536)
  8647. block_h[tbl_cells[i].node] = (unsigned short)h;
  8648. l->left = prefix[col];
  8649. l->right = l->left + w;
  8650. l->y = rowy[row];
  8651. l->line_x = l->left;
  8652. l->run_x = l->left;
  8653. l->line_y = l->y;
  8654. l->line_h = 0;
  8655. l->nruns = 0;
  8656. l->space_pending = 0;
  8657. l->align = cs.align;
  8658. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  8659. l->left = sl;
  8660. l->right = sr;
  8661. l->y = sy;
  8662. l->line_x = slx;
  8663. l->run_x = srx;
  8664. l->line_y = sly;
  8665. l->line_h = slh;
  8666. l->nruns = snr;
  8667. l->space_pending = ssp;
  8668. l->align = sal;
  8669. }
  8670. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  8671. table_active = 0;
  8672. }
  8673. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  8674. * flow so they sit above it, like CSS painting order. Their flow origin is
  8675. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  8676. struct br_deferred {
  8677. unsigned int node;
  8678. int flow_y, flow_left, flow_right;
  8679. unsigned short link;
  8680. signed short z_index;
  8681. unsigned char z_set;
  8682. unsigned int order;
  8683. };
  8684. /* Positioned boxes painted after the flow. News front pages have one or two
  8685. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  8686. * old 16 entries the rest fell back into the flow, so a hero image landed
  8687. * below its padding-top aspect box instead of on top of it. */
  8688. #define BR_MAX_DEFERRED 256
  8689. static struct br_deferred deferred[BR_MAX_DEFERRED];
  8690. static int ndeferred;
  8691. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  8692. * element's line. A block-level pseudo-element gets its own line; its box
  8693. * (margins, padding, background) is not drawn. */
  8694. static void emit_pseudo(struct lay *l, unsigned int node,
  8695. const struct br_style *st, int pe, unsigned short link)
  8696. {
  8697. char buf[160];
  8698. struct br_style ps;
  8699. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  8700. unsigned int i = 0;
  8701. int block, space_w;
  8702. if (!n)
  8703. return;
  8704. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  8705. if (block)
  8706. flush_line(l);
  8707. if (ps.uppercase)
  8708. for (i = 0; i < n; i++)
  8709. if (buf[i] >= 'a' && buf[i] <= 'z')
  8710. buf[i] = (char)(buf[i] - 'a' + 'A');
  8711. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  8712. if (space_w <= 0)
  8713. space_w = 8;
  8714. i = 0;
  8715. while (i < n) {
  8716. char word[28];
  8717. unsigned int k = 0;
  8718. int w;
  8719. if (buf[i] == ' ') {
  8720. l->space_pending = 1;
  8721. i++;
  8722. continue;
  8723. }
  8724. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  8725. word[k++] = buf[i++];
  8726. word[k] = '\0';
  8727. if (l->space_pending &&
  8728. (l->nruns > 0 || l->line_x > l->line_left) &&
  8729. l->line_x + space_w <= l->line_right)
  8730. l->line_x += space_w;
  8731. l->space_pending = 0;
  8732. w = (int)face_text_width(l->ui, &ps, word, k);
  8733. if (l->line_x + w > l->line_right &&
  8734. (l->nruns > 0 || l->line_x > l->line_left))
  8735. flush_line(l);
  8736. add_run(l, 0, 0, &ps, link, word);
  8737. }
  8738. if (block)
  8739. flush_line(l);
  8740. }
  8741. static void layout_children(struct lay *l, unsigned int parent,
  8742. const struct br_style *pst, int depth,
  8743. unsigned short link)
  8744. {
  8745. unsigned int n;
  8746. if (depth > 48)
  8747. return;
  8748. emit_pseudo(l, parent, pst, 1, link);
  8749. n = doc.nodes[parent].first;
  8750. while (n) {
  8751. struct br_node *nd = &doc.nodes[n];
  8752. struct br_style cs;
  8753. unsigned short lk = link;
  8754. if (nd->type == BR_NODE_TEXT) {
  8755. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  8756. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  8757. n = nd->next;
  8758. continue;
  8759. }
  8760. br_style_for(&doc, n, pst, &cs);
  8761. if (cs.display == BR_DISPLAY_NONE) {
  8762. n = nd->next;
  8763. continue;
  8764. }
  8765. if (cs.clear && l->float_active) {
  8766. flush_line(l);
  8767. if (l->y < l->float_bottom)
  8768. l->y = l->float_bottom;
  8769. l->float_active = 0;
  8770. l->line_x = l->left;
  8771. l->run_x = l->left;
  8772. l->line_left = l->left;
  8773. l->line_right = l->right;
  8774. l->line_y = l->y;
  8775. l->line_h = 0;
  8776. l->nruns = 0;
  8777. l->space_pending = 0;
  8778. }
  8779. if (nd->tag == BR_TAG_A && nd->href_off)
  8780. lk = (unsigned short)n;
  8781. if (cs.pos == 1 || cs.pos == 2 ||
  8782. (cs.pos == 3 && cs.z_set)) {
  8783. if (cs.pos == 3 && l->draw &&
  8784. ndeferred < BR_MAX_DEFERRED) {
  8785. /* Relative z-index: measure and advance the flow
  8786. * without painting, then paint it in the
  8787. * deferred (stacked) pass. */
  8788. int fy = l->y, fl = l->left, fr = l->right;
  8789. int save_draw = l->draw;
  8790. l->draw = 0;
  8791. layout_block(l, n, &cs, depth + 1, lk);
  8792. l->draw = save_draw;
  8793. deferred[ndeferred].node = n;
  8794. deferred[ndeferred].flow_y = fy;
  8795. deferred[ndeferred].flow_left = fl;
  8796. deferred[ndeferred].flow_right = fr;
  8797. deferred[ndeferred].link = lk;
  8798. deferred[ndeferred].z_index = cs.z_index;
  8799. deferred[ndeferred].z_set = cs.z_set;
  8800. deferred[ndeferred].order = (unsigned int)ndeferred;
  8801. ndeferred++;
  8802. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  8803. deferred[ndeferred].node = n;
  8804. deferred[ndeferred].flow_y =
  8805. cs.pos == 1 ? l->cb_top : l->y;
  8806. deferred[ndeferred].flow_left =
  8807. cs.pos == 1 ? l->cb_left : l->left;
  8808. deferred[ndeferred].flow_right =
  8809. cs.pos == 1 ? l->cb_right : l->right;
  8810. deferred[ndeferred].link = lk;
  8811. deferred[ndeferred].z_index = cs.z_index;
  8812. deferred[ndeferred].z_set = cs.z_set;
  8813. deferred[ndeferred].order = (unsigned int)ndeferred;
  8814. ndeferred++;
  8815. } else if (l->draw && cs.pos == 1) {
  8816. /* Deferred list full: paint in place, but still
  8817. * against the containing block, not the flow. */
  8818. int fy = l->y, fl = l->left, fr = l->right;
  8819. l->y = l->cb_top;
  8820. l->left = l->cb_left;
  8821. l->right = l->cb_right;
  8822. layout_block(l, n, &cs, depth + 1, lk);
  8823. l->y = fy;
  8824. l->left = fl;
  8825. l->right = fr;
  8826. } else {
  8827. layout_block(l, n, &cs, depth + 1, lk);
  8828. }
  8829. if (cs.pos == 1 && block_h[n] &&
  8830. doc.nodes[n].class_off) {
  8831. const char *cl = doc.attrs +
  8832. doc.nodes[n].class_off;
  8833. if ((contains_ci(cl, "poster-wrapper") ||
  8834. contains_ci(cl, "ts-picture")) &&
  8835. !has_skeleton_sibling(n))
  8836. l->y += block_h[n];
  8837. }
  8838. n = nd->next;
  8839. continue;
  8840. }
  8841. if (nd->tag == BR_TAG_BR) {
  8842. flush_line(l);
  8843. n = nd->next;
  8844. continue;
  8845. }
  8846. if (nd->tag == BR_TAG_HR) {
  8847. flush_line(l);
  8848. if (l->draw)
  8849. ngui_fill_rect(l->ui,
  8850. (struct ngui_rect){l->left, l->y + 2,
  8851. l->right - l->left, 1}, BR_GRAY);
  8852. l->y += 8;
  8853. n = nd->next;
  8854. continue;
  8855. }
  8856. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  8857. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  8858. !button_has_elements(n)) {
  8859. if (!(nd->tag == BR_TAG_INPUT &&
  8860. s_eq(br_type(&doc, n), "hidden"))) {
  8861. form_fill_line = pst->display ==
  8862. BR_DISPLAY_FLEX &&
  8863. pst->flex_col;
  8864. add_form_run(l, n, &cs, lk);
  8865. form_fill_line = 0;
  8866. }
  8867. n = nd->next;
  8868. continue;
  8869. }
  8870. if (nd->tag == BR_TAG_IMG) {
  8871. add_image_run(l, n, &cs, lk);
  8872. n = nd->next;
  8873. continue;
  8874. }
  8875. if (nd->tag == BR_TAG_VIDEO) {
  8876. layout_block(l, n, &cs, depth + 1, lk);
  8877. n = nd->next;
  8878. continue;
  8879. }
  8880. if (cs.float_left) {
  8881. n = layout_float_group(l, n, pst, depth, lk);
  8882. continue;
  8883. }
  8884. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8885. n = layout_inline_blocks(l, n, pst, depth, link);
  8886. continue;
  8887. }
  8888. /* A flex container is block-level like any block box even when
  8889. * the element is an inline tag such as <a> (a link card with
  8890. * display:flex is common on news sites). Without the block box
  8891. * its children were laid out in the parent flow with a 0x0 box
  8892. * of their own. */
  8893. /* inline-flex around inline content only ("| mehr" link
  8894. * tails, icon+label pills) stays in the text line. */
  8895. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  8896. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  8897. !flex_wants_row(n, &cs)) {
  8898. layout_children(l, n, &cs, depth + 1, lk);
  8899. } else if (cs.display == BR_DISPLAY_BLOCK ||
  8900. cs.display == BR_DISPLAY_FLEX ||
  8901. br_tag_is_block(nd->tag))
  8902. layout_block(l, n, &cs, depth + 1, lk);
  8903. else {
  8904. layout_children(l, n, &cs, depth + 1, lk);
  8905. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  8906. l->space_pending = 1;
  8907. }
  8908. n = nd->next;
  8909. }
  8910. emit_pseudo(l, parent, pst, 2, link);
  8911. }
  8912. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  8913. * runs and a recursive page can otherwise overflow the stack. */
  8914. static struct lay layout_state;
  8915. static int measure_page(int left, int right)
  8916. {
  8917. struct lay *l = &layout_state;
  8918. struct br_style base = base_style();
  8919. unsigned int i;
  8920. for (i = 0; i < BR_MAX_NODES; i++) {
  8921. block_h[i] = 0;
  8922. img_top[i] = 0;
  8923. block_top[i] = 0;
  8924. img_h[i] = 0;
  8925. layout_boxes[i].valid = 0;
  8926. }
  8927. memset(li_marker, 0, sizeof(li_marker));
  8928. l->draw = 0;
  8929. l->ui = &ui;
  8930. l->left = left;
  8931. l->right = right;
  8932. l->y = 0;
  8933. l->line_x = left;
  8934. l->run_x = left;
  8935. l->line_left = left;
  8936. l->line_right = right;
  8937. l->line_y = 0;
  8938. l->line_h = 0;
  8939. l->align = BR_ALIGN_LEFT;
  8940. l->cb_h = layout_view_h;
  8941. l->float_active = 0;
  8942. l->parent_top = 0;
  8943. l->cb_left = left;
  8944. l->cb_right = right;
  8945. l->cb_top = 0;
  8946. l->depth = 0;
  8947. l->nruns = 0;
  8948. l->space_pending = 0;
  8949. layout_children(l, doc.root, &base, 0, 0);
  8950. return l->y + 8;
  8951. }
  8952. static int deferred_cmp(const struct br_deferred *a,
  8953. const struct br_deferred *b)
  8954. {
  8955. int az = a->z_set ? a->z_index : 0;
  8956. int bz = b->z_set ? b->z_index : 0;
  8957. if (az != bz)
  8958. return az < bz ? -1 : 1;
  8959. if (a->order != b->order)
  8960. return a->order < b->order ? -1 : 1;
  8961. return 0;
  8962. }
  8963. static void sort_deferred(void)
  8964. {
  8965. int i;
  8966. for (i = 1; i < ndeferred; i++) {
  8967. struct br_deferred key = deferred[i];
  8968. int j = i;
  8969. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  8970. deferred[j] = deferred[j - 1];
  8971. j--;
  8972. }
  8973. deferred[j] = key;
  8974. }
  8975. }
  8976. static void render_page(int left, int right, int y0)
  8977. {
  8978. struct lay *l = &layout_state;
  8979. struct br_style base = base_style();
  8980. l->draw = 1;
  8981. l->ui = &ui;
  8982. l->left = left;
  8983. l->right = right;
  8984. l->y = y0;
  8985. l->line_x = left;
  8986. l->run_x = left;
  8987. l->line_left = left;
  8988. l->line_right = right;
  8989. l->line_y = y0;
  8990. l->line_h = 0;
  8991. l->align = BR_ALIGN_LEFT;
  8992. l->cb_h = layout_view_h;
  8993. l->float_active = 0;
  8994. l->parent_top = 0;
  8995. l->cb_left = left;
  8996. l->cb_right = right;
  8997. l->cb_top = y0;
  8998. l->depth = 0;
  8999. l->nruns = 0;
  9000. l->space_pending = 0;
  9001. nhits = 0;
  9002. ndeferred = 0;
  9003. layout_children(l, doc.root, &base, 0, 0);
  9004. sort_deferred();
  9005. {
  9006. int i;
  9007. for (i = 0; i < ndeferred; i++) {
  9008. struct br_style st;
  9009. br_style_for(&doc, deferred[i].node, &base, &st);
  9010. if (st.display == BR_DISPLAY_NONE)
  9011. continue;
  9012. l->draw = 1;
  9013. l->left = deferred[i].flow_left;
  9014. l->right = deferred[i].flow_right;
  9015. l->y = deferred[i].flow_y;
  9016. l->line_x = l->left;
  9017. l->run_x = l->left;
  9018. l->line_y = l->y;
  9019. l->line_h = 0;
  9020. l->nruns = 0;
  9021. l->space_pending = 0;
  9022. l->align = st.align;
  9023. if (st.pos == 2 && block_h[deferred[i].node]) {
  9024. struct ngui_rect clip;
  9025. int ch = block_h[deferred[i].node] + 24;
  9026. clip.x = page_rect.x;
  9027. clip.y = page_rect.y;
  9028. clip.w = page_rect.w - 12;
  9029. if (ch > page_rect.h)
  9030. ch = page_rect.h;
  9031. clip.h = ch;
  9032. ngui_push_clip(&ui, clip);
  9033. if (st.has_bg)
  9034. ngui_fill_rect(&ui, clip, st.bg);
  9035. layout_block(l, deferred[i].node, &st, 0,
  9036. deferred[i].link);
  9037. ngui_pop_clip(&ui);
  9038. } else {
  9039. layout_block(l, deferred[i].node, &st, 0,
  9040. deferred[i].link);
  9041. }
  9042. }
  9043. }
  9044. }
  9045. /* ---- UI ---- */
  9046. static int find_hit(int x, int y)
  9047. {
  9048. int i;
  9049. for (i = nhits - 1; i >= 0; i--) {
  9050. struct hit *h = &hits[i];
  9051. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  9052. y < h->y + h->h)
  9053. return (int)h->node;
  9054. }
  9055. return 0;
  9056. }
  9057. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  9058. {
  9059. int x = r.x + 4, y = r.y + 4, h = 22;
  9060. int compact = r.w < 560;
  9061. int go_w = r.w < 420 ? 32 : 42;
  9062. int in_x, in_w, res;
  9063. ngui_fill_rect(&ui, r, ui.theme.panel);
  9064. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  9065. ui.theme.border);
  9066. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  9067. NGUI_ICON_CHEVRON_LEFT))
  9068. *action |= ACT_BACK;
  9069. x += 32;
  9070. if (!compact) {
  9071. if (ngui_icon_button(&ui, ID_FORWARD,
  9072. (struct ngui_rect){x, y, 28, h},
  9073. NGUI_ICON_CHEVRON_RIGHT))
  9074. *action |= ACT_FORWARD;
  9075. x += 32;
  9076. }
  9077. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  9078. NGUI_ICON_REFRESH))
  9079. *action |= ACT_RELOAD;
  9080. x += 32;
  9081. if (!compact) {
  9082. if (ngui_icon_button(&ui, ID_HOME,
  9083. (struct ngui_rect){x, y, 28, h},
  9084. NGUI_ICON_HOME))
  9085. *action |= ACT_HOME;
  9086. x += 32;
  9087. }
  9088. in_x = x + 2;
  9089. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  9090. if (in_w < 60)
  9091. in_w = 60;
  9092. res = ngui_text_input(&ui, ID_URL,
  9093. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  9094. if (res & NGUI_INPUT_SUBMIT)
  9095. *action |= ACT_NAV;
  9096. if (res & NGUI_INPUT_CANCEL)
  9097. ngui_set_focus(&ui, 0);
  9098. if (ngui_button(&ui, ID_GO,
  9099. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  9100. "Go"))
  9101. *action |= ACT_NAV;
  9102. }
  9103. static int page_hover_node(void)
  9104. {
  9105. if (!ui.inside)
  9106. return 0;
  9107. if (ui.mouse_x < page_rect.x ||
  9108. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  9109. ui.mouse_y < page_rect.y ||
  9110. ui.mouse_y >= page_rect.y + page_rect.h)
  9111. return 0;
  9112. return find_hit(ui.mouse_x, ui.mouse_y);
  9113. }
  9114. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  9115. {
  9116. int x, y, w = page.w, h = page.h;
  9117. if (!src || w <= 0 || h <= 0)
  9118. return;
  9119. for (y = 0; y < h; y++) {
  9120. unsigned short *s = src + (page.y + y) * sw + page.x;
  9121. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  9122. for (x = 0; x + 1 < w; x += 2) {
  9123. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  9124. }
  9125. if (x < w)
  9126. d[x] = s[x];
  9127. }
  9128. }
  9129. static void draw_page(struct ngui_rect page)
  9130. {
  9131. int left, right, ch;
  9132. int old_panel, old_dim;
  9133. unsigned short *saved_px;
  9134. unsigned short page_bg = ui.theme.bg;
  9135. int saved_w, saved_h, use_buf;
  9136. page_rect = page;
  9137. {
  9138. unsigned int root = doc.nnode > 1 ?
  9139. br_find_tag(&doc, BR_TAG_HTML) : 0;
  9140. unsigned int body = doc.nnode > 1 ?
  9141. br_find_tag(&doc, BR_TAG_BODY) : 0;
  9142. struct br_style bs;
  9143. if (root) {
  9144. style_for_node(root - 1, &bs);
  9145. if (bs.has_bg)
  9146. page_bg = bs.bg;
  9147. }
  9148. if (body) {
  9149. style_for_node(body - 1, &bs);
  9150. if (bs.has_bg)
  9151. page_bg = bs.bg;
  9152. }
  9153. }
  9154. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  9155. page_cache_valid && layout_valid &&
  9156. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  9157. !(ui.scroll_y &&
  9158. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  9159. page_scroll.offset == page_cache_scroll &&
  9160. page_cache_nnode == doc.nnode &&
  9161. page_cache_x == page.x && page_cache_y == page.y &&
  9162. page_cache_w == page.w && page_cache_h == page.h) {
  9163. blit_page(page, page_backbuf, pagebuf_w);
  9164. return;
  9165. }
  9166. ngui_fill_rect(&ui, page, page_bg);
  9167. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  9168. const char *s = page_loading ? "Loading..." : "No page";
  9169. int w = (int)ngui_text_width_ui(&ui, s);
  9170. ngui_text(&ui, page.x + (page.w - w) / 2,
  9171. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  9172. page_scroll.content_h = 0;
  9173. page_scroll.view_h = page.h;
  9174. page_cache_valid = 0;
  9175. return;
  9176. }
  9177. if (page.w < 40 || page.h < 40) {
  9178. page_cache_valid = 0;
  9179. return;
  9180. }
  9181. saved_px = ui.px;
  9182. saved_w = ui.w;
  9183. saved_h = ui.h;
  9184. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  9185. if (use_buf) {
  9186. ui.px = page_backbuf;
  9187. ui.w = pagebuf_w;
  9188. ui.h = pagebuf_h;
  9189. ngui_fill_rect(&ui, page, page_bg);
  9190. }
  9191. left = page.x + 8;
  9192. right = page.x + page.w - 16;
  9193. if (!layout_valid || left != layout_left || right != layout_right ||
  9194. layout_nnode != doc.nnode) {
  9195. layout_view_h = page.h - 8;
  9196. layout_content_h = measure_page(left, right);
  9197. layout_valid = 1;
  9198. layout_left = left;
  9199. layout_right = right;
  9200. layout_nnode = doc.nnode;
  9201. /* Scripts that measured before any layout (offsetWidth on
  9202. * mount) get a resize event once real boxes exist, and again
  9203. * whenever the page width changes. */
  9204. if (js_browser_active() && right - left != resize_sent_w)
  9205. resize_pending = 1;
  9206. }
  9207. ch = layout_content_h;
  9208. page_scroll.content_h = ch;
  9209. page_scroll.view_h = page.h;
  9210. ngui_scroll_begin(&ui, page, &page_scroll);
  9211. ngui_scroll_wheel(&ui, page, &page_scroll);
  9212. render_page(left, right, page.y + 4 - page_scroll.offset);
  9213. old_panel = ui.theme.panel_alt;
  9214. old_dim = ui.theme.text_dim;
  9215. ui.theme.panel_alt = 0xC618;
  9216. ui.theme.text_dim = 0x8410;
  9217. ngui_scroll_end(&ui, page, &page_scroll);
  9218. ui.theme.panel_alt = old_panel;
  9219. ui.theme.text_dim = old_dim;
  9220. if (use_buf) {
  9221. ui.px = saved_px;
  9222. ui.w = saved_w;
  9223. ui.h = saved_h;
  9224. blit_page(page, page_backbuf, pagebuf_w);
  9225. page_cache_valid = 1;
  9226. page_cache_scroll = page_scroll.offset;
  9227. page_cache_nnode = doc.nnode;
  9228. page_cache_x = page.x;
  9229. page_cache_y = page.y;
  9230. page_cache_w = page.w;
  9231. page_cache_h = page.h;
  9232. } else {
  9233. page_cache_valid = 0;
  9234. }
  9235. }
  9236. static void draw_status(struct ngui_rect r)
  9237. {
  9238. char msg[BR_URL_MAX + 32];
  9239. unsigned int n = 0;
  9240. int hover = page_hover_node();
  9241. unsigned short color;
  9242. const char *kind;
  9243. ngui_fill_rect(&ui, r, ui.theme.panel);
  9244. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  9245. ui.theme.border);
  9246. if (hover) {
  9247. const char *href = br_href(&doc, (unsigned int)hover);
  9248. char url[BR_URL_MAX];
  9249. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  9250. s_append(msg, &n, "Link: ", sizeof(msg));
  9251. s_append(msg, &n, url, sizeof(msg));
  9252. } else {
  9253. s_copy(msg, "Link", sizeof(msg));
  9254. }
  9255. color = ui.theme.accent;
  9256. } else if (status_text[0]) {
  9257. s_copy(msg, status_text, sizeof(msg));
  9258. color = status_error ? ui.theme.error : ui.theme.text;
  9259. } else if (page_title[0]) {
  9260. s_copy(msg, page_title, sizeof(msg));
  9261. color = ui.theme.text;
  9262. } else {
  9263. s_copy(msg, "Ready", sizeof(msg));
  9264. color = ui.theme.text_dim;
  9265. }
  9266. kind = s_eq(page_url, "about:home") ? "HOME" :
  9267. page_is_local ? "FILE" :
  9268. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  9269. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  9270. {
  9271. int kw = (int)ngui_text_width_ui(&ui, kind);
  9272. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  9273. ui.theme.text_dim);
  9274. }
  9275. }
  9276. static void draw(unsigned int *action)
  9277. {
  9278. struct ngui_rect r = {0, 0, ui.w, ui.h};
  9279. struct ngui_rect toolbar, status, page;
  9280. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  9281. status = ngui_cut_bottom(&r, BR_STATUS_H);
  9282. page = r;
  9283. draw_toolbar(toolbar, action);
  9284. draw_page(page);
  9285. draw_status(status);
  9286. }
  9287. static void redraw_now(void)
  9288. {
  9289. unsigned int action = 0;
  9290. ngui_begin(&ui);
  9291. draw(&action);
  9292. ngui_end(&ui);
  9293. }
  9294. static void handle_keys(unsigned int *action)
  9295. {
  9296. int k, scrolled = 0;
  9297. if (form_focus >= doc.nnode)
  9298. form_focus = 0;
  9299. if (form_focus && !ngui_focus(&ui)) {
  9300. while ((k = ngui_key(&ui)) != 0)
  9301. form_key(k);
  9302. return;
  9303. }
  9304. /* Batch queued page keys: a slow full-page render must not make a
  9305. * held Page Down advance only once every few frames. */
  9306. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  9307. scrolled++;
  9308. if (scrolled)
  9309. ngui_invalidate(&ui);
  9310. if (ngui_focus(&ui))
  9311. return;
  9312. while ((k = ngui_key(&ui)) != 0) {
  9313. switch (k) {
  9314. case NGUI_KEY_ESC:
  9315. *action |= ACT_CLOSE;
  9316. break;
  9317. case NGUI_KEY_TAB:
  9318. case 0x0C: /* Ctrl+L */
  9319. ngui_set_focus(&ui, ID_URL);
  9320. break;
  9321. case 0x12: /* Ctrl+R */
  9322. *action |= ACT_RELOAD;
  9323. break;
  9324. case NGUI_KEY_BACKSPACE:
  9325. *action |= ACT_BACK;
  9326. break;
  9327. case NGUI_KEY_UP:
  9328. ngui_scroll_to(&page_scroll,
  9329. page_scroll.offset - 24);
  9330. ngui_invalidate(&ui);
  9331. break;
  9332. case NGUI_KEY_DOWN:
  9333. ngui_scroll_to(&page_scroll,
  9334. page_scroll.offset + 24);
  9335. ngui_invalidate(&ui);
  9336. break;
  9337. case NGUI_KEY_HOME:
  9338. ngui_scroll_to(&page_scroll, 0);
  9339. ngui_invalidate(&ui);
  9340. break;
  9341. case NGUI_KEY_END:
  9342. ngui_scroll_to(&page_scroll,
  9343. page_scroll.content_h -
  9344. page_scroll.view_h);
  9345. ngui_invalidate(&ui);
  9346. break;
  9347. default:
  9348. break;
  9349. }
  9350. }
  9351. }
  9352. static unsigned int form_ancestor(unsigned int node)
  9353. {
  9354. unsigned int p = node;
  9355. while (p && p < doc.nnode) {
  9356. if (doc.nodes[p].tag == BR_TAG_FORM &&
  9357. doc.nodes[p].type == BR_NODE_ELEM)
  9358. return p;
  9359. p = doc.nodes[p].parent;
  9360. }
  9361. return 0;
  9362. }
  9363. static int form_descendant(unsigned int node, unsigned int form)
  9364. {
  9365. unsigned int p = node;
  9366. while (p && p < doc.nnode) {
  9367. if (p == form)
  9368. return 1;
  9369. p = doc.nodes[p].parent;
  9370. }
  9371. return 0;
  9372. }
  9373. static void form_reset_form(unsigned int form)
  9374. {
  9375. unsigned int i;
  9376. for (i = 0; i < FORM_MAX; i++)
  9377. if (form_states[i].used &&
  9378. form_descendant(form_states[i].node, form))
  9379. form_states[i].used = 0;
  9380. form_focus = 0;
  9381. }
  9382. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  9383. const char *s)
  9384. {
  9385. static const char hex[] = "0123456789ABCDEF";
  9386. while (s && *s && *n + 1 < cap) {
  9387. unsigned char c = (unsigned char)*s++;
  9388. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  9389. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  9390. c == '.' || c == '~') {
  9391. dst[(*n)++] = (char)c;
  9392. } else if (c == ' ') {
  9393. dst[(*n)++] = '+';
  9394. } else if (*n + 3 < cap) {
  9395. dst[(*n)++] = '%';
  9396. dst[(*n)++] = hex[c >> 4];
  9397. dst[(*n)++] = hex[c & 15];
  9398. }
  9399. }
  9400. dst[*n] = '\0';
  9401. }
  9402. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  9403. const char *name, const char *value, int *first)
  9404. {
  9405. if (!name || !name[0])
  9406. return;
  9407. if (!*first && *n + 1 < cap)
  9408. dst[(*n)++] = '&';
  9409. *first = 0;
  9410. form_url_append(dst, n, cap, name);
  9411. if (*n + 1 < cap)
  9412. dst[(*n)++] = '=';
  9413. form_url_append(dst, n, cap, value ? value : "");
  9414. dst[*n] = '\0';
  9415. }
  9416. static int form_submit_form(unsigned int node, int fire_event)
  9417. {
  9418. unsigned int form = form_ancestor(node);
  9419. char action[BR_URL_MAX], query[2048];
  9420. unsigned int qn = 0, i;
  9421. int first = 1, is_post = 0;
  9422. const char *a, *method;
  9423. if (!form)
  9424. return 0;
  9425. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  9426. return 0;
  9427. method = br_find_attr(&doc, form, "method");
  9428. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  9429. is_post = 1;
  9430. a = br_find_attr(&doc, form, "action");
  9431. if (a && a[0]) {
  9432. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  9433. return 0;
  9434. } else {
  9435. s_copy(action, page_url, sizeof(action));
  9436. }
  9437. query[0] = '\0';
  9438. for (i = 0; i < doc.nnode; i++) {
  9439. struct br_node *nd = &doc.nodes[i];
  9440. struct form_state *fs;
  9441. const char *name;
  9442. const char *value = "";
  9443. if (nd->type != BR_NODE_ELEM || i == form ||
  9444. !form_descendant(i, form))
  9445. continue;
  9446. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  9447. nd->tag != BR_TAG_SELECT)
  9448. continue;
  9449. if (form_disabled(i))
  9450. continue;
  9451. name = br_find_attr(&doc, i, "name");
  9452. if (!name || !name[0])
  9453. continue;
  9454. fs = form_get(i, 1);
  9455. if (!fs)
  9456. continue;
  9457. if (nd->tag == BR_TAG_SELECT) {
  9458. char opt[64];
  9459. if (!form_option_text(i, fs->selected, opt,
  9460. sizeof(opt)))
  9461. s_copy(opt, "", sizeof(opt));
  9462. value = opt;
  9463. {
  9464. unsigned int c, oi = 0;
  9465. for (c = nd->first; c;
  9466. c = doc.nodes[c].next) {
  9467. if (doc.nodes[c].type != BR_NODE_ELEM ||
  9468. doc.nodes[c].tag != BR_TAG_OPTION)
  9469. continue;
  9470. if (oi == fs->selected) {
  9471. const char *v =
  9472. br_value(&doc, c);
  9473. if (v && v[0])
  9474. value = v;
  9475. break;
  9476. }
  9477. oi++;
  9478. }
  9479. }
  9480. } else if (nd->tag == BR_TAG_INPUT) {
  9481. int kind = form_kind_of(i);
  9482. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  9483. if (!fs->checked)
  9484. continue;
  9485. value = br_value(&doc, i);
  9486. if (!value || !value[0])
  9487. value = "on";
  9488. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  9489. kind == FORM_BUTTON) {
  9490. if (i != node)
  9491. continue;
  9492. value = fs->value;
  9493. } else {
  9494. value = fs->value;
  9495. }
  9496. } else {
  9497. value = fs->value;
  9498. }
  9499. form_add_param(query, &qn, sizeof(query), name, value, &first);
  9500. }
  9501. if (is_post) {
  9502. if (action[0] == '/') {
  9503. set_status("POST forms need an HTTP action URL", 1, 4000);
  9504. ngui_invalidate(&ui);
  9505. return 0;
  9506. }
  9507. if (qn >= sizeof(pending_post))
  9508. qn = sizeof(pending_post) - 1;
  9509. if (qn)
  9510. memcpy(pending_post, query, qn);
  9511. pending_post[qn] = '\0';
  9512. pending_post_len = qn;
  9513. pending_post_is = 1;
  9514. } else {
  9515. pending_post_len = 0;
  9516. pending_post_is = 0;
  9517. if (qn) {
  9518. unsigned int an = s_len(action);
  9519. if (an + qn + 2 < sizeof(action)) {
  9520. action[an++] = strchr(action, '?') ? '&' : '?';
  9521. action[an] = '\0';
  9522. s_copy(action + an, query,
  9523. sizeof(action) - an);
  9524. }
  9525. }
  9526. }
  9527. s_copy(pending_url, action, sizeof(pending_url));
  9528. pending_action |= ACT_NAV;
  9529. cancel_fetch = 1;
  9530. ngui_invalidate(&ui);
  9531. return 1;
  9532. }
  9533. static void form_reset_event(unsigned int form)
  9534. {
  9535. if (form && !js_browser_event(form, "reset", 1, 1))
  9536. return;
  9537. if (form)
  9538. form_reset_form(form);
  9539. else
  9540. form_reset_state();
  9541. form_dirty = 0;
  9542. layout_valid = 0;
  9543. ngui_invalidate(&ui);
  9544. }
  9545. static void form_blur(void)
  9546. {
  9547. unsigned int node = form_focus;
  9548. form_focus = 0;
  9549. if (node && form_dirty) {
  9550. form_dirty = 0;
  9551. js_browser_event(node, "change", 1, 0);
  9552. }
  9553. }
  9554. static void form_click(unsigned int node)
  9555. {
  9556. struct form_state *fs;
  9557. int kind, changed = 0;
  9558. if (!form_is_control(node) || form_disabled(node))
  9559. return;
  9560. if (form_focus != node)
  9561. form_blur();
  9562. if (!js_browser_event(node, "click", 1, 1))
  9563. return;
  9564. fs = form_get(node, 1);
  9565. if (!fs)
  9566. return;
  9567. kind = form_kind_of(node);
  9568. form_focus = node;
  9569. form_dirty = 0;
  9570. if (kind == FORM_CHECKBOX) {
  9571. fs->checked = !fs->checked;
  9572. changed = 1;
  9573. } else if (kind == FORM_RADIO) {
  9574. const char *name = br_find_attr(&doc, node, "name");
  9575. unsigned int i;
  9576. fs->checked = 1;
  9577. changed = 1;
  9578. if (name) {
  9579. for (i = 0; i < FORM_MAX; i++) {
  9580. struct form_state *o = &form_states[i];
  9581. if (!o->used || o->node == node)
  9582. continue;
  9583. if (form_kind_of(o->node) == FORM_RADIO) {
  9584. const char *on = br_find_attr(&doc,
  9585. o->node,
  9586. "name");
  9587. if (on && s_eq(on, name))
  9588. o->checked = 0;
  9589. }
  9590. }
  9591. }
  9592. } else if (kind == FORM_SELECT) {
  9593. unsigned int n = form_option_count(node);
  9594. if (n) {
  9595. fs->selected = (unsigned char)
  9596. ((fs->selected + 1) % n);
  9597. changed = 1;
  9598. }
  9599. } else if (kind == FORM_SUBMIT) {
  9600. form_submit_form(node, 1);
  9601. return;
  9602. } else if (kind == FORM_RESET) {
  9603. form_reset_event(form_ancestor(node));
  9604. return;
  9605. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  9606. kind == FORM_TEXTAREA) {
  9607. fs->caret = fs->len;
  9608. }
  9609. if (changed) {
  9610. js_browser_event(node, "input", 1, 0);
  9611. js_browser_event(node, "change", 1, 0);
  9612. }
  9613. layout_valid = 0;
  9614. ngui_invalidate(&ui);
  9615. }
  9616. static void form_focus_next(void)
  9617. {
  9618. unsigned int start = form_focus ? form_focus + 1 : 0;
  9619. unsigned int i;
  9620. form_blur();
  9621. for (i = start; i < doc.nnode; i++) {
  9622. if (form_is_control(i) && !form_disabled(i) &&
  9623. !s_eq(br_type(&doc, i), "hidden")) {
  9624. form_focus = i;
  9625. layout_valid = 0;
  9626. ngui_invalidate(&ui);
  9627. return;
  9628. }
  9629. }
  9630. form_focus = 0;
  9631. layout_valid = 0;
  9632. ngui_invalidate(&ui);
  9633. }
  9634. static void form_key(int k)
  9635. {
  9636. struct form_state *fs;
  9637. int kind;
  9638. if (!form_focus || form_focus >= doc.nnode) {
  9639. form_focus = 0;
  9640. return;
  9641. }
  9642. fs = form_get(form_focus, 1);
  9643. if (!fs || form_disabled(form_focus))
  9644. return;
  9645. kind = form_kind_of(form_focus);
  9646. if (kind == FORM_SELECT) {
  9647. unsigned int n = form_option_count(form_focus);
  9648. int changed = 0;
  9649. if (k == NGUI_KEY_UP && n) {
  9650. fs->selected = (unsigned char)
  9651. ((fs->selected + n - 1) % n);
  9652. changed = 1;
  9653. } else if (k == NGUI_KEY_DOWN && n) {
  9654. fs->selected = (unsigned char)
  9655. ((fs->selected + 1) % n);
  9656. changed = 1;
  9657. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  9658. form_blur();
  9659. layout_valid = 0;
  9660. ngui_invalidate(&ui);
  9661. return;
  9662. } else {
  9663. return;
  9664. }
  9665. if (changed) {
  9666. js_browser_event(form_focus, "input", 1, 0);
  9667. js_browser_event(form_focus, "change", 1, 0);
  9668. }
  9669. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  9670. if (k == ' ') {
  9671. form_click(form_focus);
  9672. return;
  9673. }
  9674. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  9675. form_blur();
  9676. layout_valid = 0;
  9677. ngui_invalidate(&ui);
  9678. }
  9679. return;
  9680. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  9681. kind == FORM_RESET) {
  9682. if (k == NGUI_KEY_ESC) {
  9683. form_blur();
  9684. layout_valid = 0;
  9685. ngui_invalidate(&ui);
  9686. } else if (k == '\r' || k == '\n' || k == ' ') {
  9687. form_click(form_focus);
  9688. }
  9689. return;
  9690. } else if (k == NGUI_KEY_TAB) {
  9691. form_focus_next();
  9692. return;
  9693. } else if (k == NGUI_KEY_ESC) {
  9694. form_blur();
  9695. layout_valid = 0;
  9696. ngui_invalidate(&ui);
  9697. return;
  9698. } else if (k == '\r' || k == '\n') {
  9699. unsigned int node = form_focus;
  9700. form_blur();
  9701. if (form_ancestor(node))
  9702. form_submit_form(node, 1);
  9703. layout_valid = 0;
  9704. ngui_invalidate(&ui);
  9705. return;
  9706. } else if (k == NGUI_KEY_BACKSPACE) {
  9707. if (fs->caret) {
  9708. unsigned int i = --fs->caret;
  9709. for (; i < fs->len; i++)
  9710. fs->value[i] = fs->value[i + 1];
  9711. if (fs->len)
  9712. fs->len--;
  9713. form_dirty = 1;
  9714. js_browser_event(form_focus, "input", 1, 0);
  9715. }
  9716. } else if (k == NGUI_KEY_DELETE) {
  9717. if (fs->caret < fs->len) {
  9718. unsigned int i;
  9719. for (i = fs->caret; i < fs->len; i++)
  9720. fs->value[i] = fs->value[i + 1];
  9721. fs->len--;
  9722. form_dirty = 1;
  9723. js_browser_event(form_focus, "input", 1, 0);
  9724. }
  9725. } else if (k == NGUI_KEY_LEFT) {
  9726. if (fs->caret)
  9727. fs->caret--;
  9728. } else if (k == NGUI_KEY_RIGHT) {
  9729. if (fs->caret < fs->len)
  9730. fs->caret++;
  9731. } else if (k == NGUI_KEY_HOME) {
  9732. fs->caret = 0;
  9733. } else if (k == NGUI_KEY_END) {
  9734. fs->caret = fs->len;
  9735. } else if (k >= 32 && k < 127) {
  9736. if (fs->len < FORM_VALUE_MAX) {
  9737. unsigned int i;
  9738. for (i = fs->len; i > fs->caret; i--)
  9739. fs->value[i] = fs->value[i - 1];
  9740. fs->value[fs->caret++] = (char)k;
  9741. fs->len++;
  9742. form_dirty = 1;
  9743. js_browser_event(form_focus, "input", 1, 0);
  9744. }
  9745. } else {
  9746. return;
  9747. }
  9748. fs->value[fs->len] = '\0';
  9749. layout_valid = 0;
  9750. ngui_invalidate(&ui);
  9751. }
  9752. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  9753. * a same-document navigation: update the URL and fire hashchange. Returns
  9754. * 1 when handled. */
  9755. static int link_fragment_nav(unsigned int node)
  9756. {
  9757. const char *href = br_href(&doc, node);
  9758. char url[BR_URL_MAX];
  9759. unsigned int n = 0;
  9760. if (!href || !href[0] || !js_browser_active())
  9761. return 0;
  9762. if (href[0] == '#') {
  9763. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  9764. url[n] = page_url[n];
  9765. n++;
  9766. }
  9767. url[n] = '\0';
  9768. s_append(url, &n, href, sizeof(url));
  9769. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  9770. return 0;
  9771. }
  9772. if (!same_doc_fragment(url))
  9773. return href[0] == '#';
  9774. page_set_fragment(url, 1);
  9775. js_browser_hashchange();
  9776. return 1;
  9777. }
  9778. /* The innermost laid-out box under a screen point: the smallest valid box
  9779. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  9780. * Used to deliver clicks to elements that are neither links nor controls
  9781. * (a Vue <div role="button">, a card with a click listener). */
  9782. static unsigned int find_box_hit(int x, int y)
  9783. {
  9784. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  9785. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  9786. const struct br_layout_box *b = &layout_boxes[i];
  9787. unsigned int area;
  9788. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  9789. x < b->x || y < b->y || x >= b->x + b->w ||
  9790. y >= b->y + b->h)
  9791. continue;
  9792. area = (unsigned int)b->w * (unsigned int)b->h;
  9793. if (area <= best_area) {
  9794. best = i;
  9795. best_area = area;
  9796. }
  9797. }
  9798. return best;
  9799. }
  9800. static void handle_page_click(unsigned int *action)
  9801. {
  9802. int node;
  9803. char url[BR_URL_MAX];
  9804. if (!ui.pressed)
  9805. return;
  9806. if (ui.press_x < page_rect.x ||
  9807. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  9808. ui.press_y < page_rect.y ||
  9809. ui.press_y >= page_rect.y + page_rect.h)
  9810. return;
  9811. node = find_hit(ui.press_x, ui.press_y);
  9812. if (!node) {
  9813. unsigned int box;
  9814. if (!js_browser_active())
  9815. return;
  9816. box = find_box_hit(ui.press_x, ui.press_y);
  9817. if (box) {
  9818. form_blur();
  9819. js_browser_event(box, "click", 1, 1);
  9820. }
  9821. return;
  9822. }
  9823. if (form_is_control((unsigned int)node)) {
  9824. form_click((unsigned int)node);
  9825. return;
  9826. }
  9827. form_blur();
  9828. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  9829. return;
  9830. if (link_fragment_nav((unsigned int)node))
  9831. return;
  9832. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  9833. sizeof(url)) != 0)
  9834. return;
  9835. s_copy(click_url, url, sizeof(click_url));
  9836. *action |= ACT_NAV;
  9837. }
  9838. void _start(const char *arg)
  9839. {
  9840. struct win_info wi;
  9841. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  9842. u_win_create(960, 640, "Browser", &wi) != 0 &&
  9843. u_win_create(780, 540, "Browser", &wi) != 0) {
  9844. u_puts("browser: no graphics window\n");
  9845. u_exit(1);
  9846. }
  9847. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  9848. url_in.placeholder = "http://...";
  9849. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  9850. ui.theme.accent);
  9851. br_set_viewport(wi.width);
  9852. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  9853. s_copy(cwd, "/", sizeof(cwd));
  9854. heap_clear();
  9855. origin_cache_load();
  9856. css_cache_init();
  9857. script_cache_init();
  9858. persist_restore();
  9859. page_scroll.offset = 0;
  9860. page_scroll.content_h = 0;
  9861. if (arg && arg[0]) {
  9862. navigate(arg, 1);
  9863. } else {
  9864. load_home(1);
  9865. /* Start ready to type: keep the home page, but leave the address
  9866. * bar empty instead of showing "about:home". */
  9867. ngui_input_set(&url_in, "");
  9868. ngui_set_focus(&ui, ID_URL);
  9869. }
  9870. for (;;) {
  9871. unsigned int action = 0;
  9872. unsigned int now;
  9873. click_url[0] = '\0';
  9874. if (pending_action) {
  9875. action |= pending_action & ACT_WAIT_NAV;
  9876. if (pending_url[0])
  9877. s_copy(click_url, pending_url, sizeof(click_url));
  9878. pending_action = 0;
  9879. pending_url[0] = '\0';
  9880. cancel_fetch = 0;
  9881. } else if (preload_active) {
  9882. if (preload_wait)
  9883. preload_wait = 0;
  9884. else
  9885. preload_step();
  9886. } else if ((preload_pending &&
  9887. page_scroll.offset != preload_scroll) ||
  9888. (preload_rescan && layout_valid)) {
  9889. preload_scroll = page_scroll.offset;
  9890. preload_rescan = 0;
  9891. preload_pending = 0;
  9892. preload_node = 0;
  9893. preload_active = 1;
  9894. }
  9895. js_browser_tick();
  9896. if (resize_pending && !pending_action) {
  9897. resize_pending = 0;
  9898. resize_sent_w = layout_right - layout_left;
  9899. js_browser_window_event("resize");
  9900. }
  9901. persist_tick();
  9902. if (pending_action)
  9903. continue;
  9904. now = u_ticks_ms();
  9905. if (status_until && (int)(now - status_until) >= 0) {
  9906. status_text[0] = '\0';
  9907. status_until = 0;
  9908. status_error = 0;
  9909. ngui_invalidate(&ui);
  9910. }
  9911. if (!ngui_begin(&ui)) {
  9912. /* A queued navigation (e.g. Enter in the URL bar during
  9913. * a slow fetch) must be handled even when this frame
  9914. * needs no redraw. */
  9915. if (!action) {
  9916. fetch_workers_stop_if_unfocused();
  9917. u_sleep_ms(10);
  9918. continue;
  9919. }
  9920. } else {
  9921. draw(&action);
  9922. handle_keys(&action);
  9923. handle_page_click(&action);
  9924. ngui_end(&ui);
  9925. }
  9926. if (action & ACT_NAV) {
  9927. if (click_url[0]) {
  9928. navigate(click_url, 1);
  9929. click_url[0] = '\0';
  9930. } else {
  9931. navigate(url_in.text, 1);
  9932. }
  9933. }
  9934. if (action & ACT_BACK) {
  9935. if (hist_pos > 0) {
  9936. hist_pos--;
  9937. if (same_doc_fragment(history[hist_pos])) {
  9938. page_set_fragment(history[hist_pos], 0);
  9939. js_browser_hashchange();
  9940. } else {
  9941. navigate(history[hist_pos], 0);
  9942. }
  9943. }
  9944. }
  9945. if (action & ACT_FORWARD) {
  9946. if (hist_pos + 1 < hist_len) {
  9947. hist_pos++;
  9948. if (same_doc_fragment(history[hist_pos])) {
  9949. page_set_fragment(history[hist_pos], 0);
  9950. js_browser_hashchange();
  9951. } else {
  9952. navigate(history[hist_pos], 0);
  9953. }
  9954. }
  9955. }
  9956. if (action & ACT_RELOAD) {
  9957. if (s_eq(page_url, "about:home"))
  9958. load_home(0);
  9959. else
  9960. navigate(page_url, 0);
  9961. }
  9962. if (action & ACT_HOME)
  9963. load_home(1);
  9964. if (action & ACT_CLOSE)
  9965. quit = 1;
  9966. if (quit)
  9967. break;
  9968. if (pending_action)
  9969. continue;
  9970. fetch_workers_stop_if_unfocused();
  9971. u_sleep_ms(10);
  9972. }
  9973. fetch_workers_stop_all();
  9974. u_win_close();
  9975. u_exit(0);
  9976. }