browser.c 272 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603
  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. char err[32];
  89. };
  90. static struct ngui ui;
  91. static struct ngui_input url_in;
  92. static struct ngui_scroll page_scroll;
  93. static struct br_doc doc;
  94. static struct br_image images[BR_MAX_IMAGES];
  95. static int image_count;
  96. static unsigned int image_pixels;
  97. /* Painted border boxes, in page/screen coordinates (layout starts at
  98. * page_rect.y + 4 - scroll). getBoundingClientRect() subtracts page_rect. */
  99. struct br_layout_box {
  100. int x, y;
  101. int w, h;
  102. unsigned char valid;
  103. };
  104. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  105. /* Images are loaded one per main-loop iteration so the parsed page stays
  106. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  107. static int preload_active;
  108. static int preload_max_jobs;
  109. static int preload_pending;
  110. static int preload_wait;
  111. static unsigned int preload_node;
  112. static int preload_loaded;
  113. static int preload_scroll;
  114. static int preload_rescan;
  115. static char post_status_text[BR_STATUS_MAX];
  116. static int post_status_error;
  117. static unsigned int post_status_ttl;
  118. /* Content-relative position/height of each <img>, recorded by the measure
  119. * pass so image loading can be deferred until it is near the viewport. */
  120. static unsigned short img_top[BR_MAX_NODES];
  121. static unsigned short img_h[BR_MAX_NODES];
  122. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  123. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  124. * body. Decode arenas are allocated per image instead of living here. */
  125. static unsigned char *image_io_buf;
  126. static struct ufont_face *font_faces[BR_MAX_FACES];
  127. #define image_file_buf (image_io_buf)
  128. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  129. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  130. static struct inflate image_inflate_ws;
  131. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  132. #error "CSS scratch must fit in image_io_buf"
  133. #endif
  134. static char page_url[BR_URL_MAX];
  135. static char page_title[BR_TITLE_MAX];
  136. static char cwd[64];
  137. static int page_is_local;
  138. static int page_loading;
  139. static char status_text[BR_STATUS_MAX];
  140. static unsigned int status_until;
  141. static int status_error;
  142. static char history[BR_HISTORY][BR_URL_MAX];
  143. static int hist_len, hist_pos;
  144. static char click_url[BR_URL_MAX];
  145. static char pending_url[BR_URL_MAX];
  146. #define BR_POST_MAX 4096
  147. static char pending_post[BR_POST_MAX];
  148. static unsigned int pending_post_len;
  149. /* The pending navigation is a POST even when its body is empty (a form
  150. * without fields, e.g. the OIDC consent auto-submit). */
  151. static int pending_post_is;
  152. /* window "resize" bookkeeping: the page width the last event was for. */
  153. static int resize_sent_w = -1;
  154. static int resize_pending;
  155. static unsigned int pending_action;
  156. static int cancel_fetch;
  157. static int quit;
  158. static struct ngui_rect page_rect;
  159. static unsigned short *page_backbuf;
  160. static int pagebuf_w, pagebuf_h;
  161. static int page_cache_valid;
  162. static int page_cache_scroll;
  163. static unsigned int page_cache_nnode;
  164. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  165. static int layout_valid, layout_left, layout_right;
  166. /* Height of the page viewport: what html/body height:100% resolves to. */
  167. static int layout_view_h;
  168. static unsigned int layout_nnode;
  169. static int layout_content_h;
  170. /* layout output */
  171. struct lay_run {
  172. unsigned int off;
  173. unsigned short len;
  174. unsigned short gap;
  175. unsigned short color;
  176. unsigned short href;
  177. char lit[28];
  178. short img;
  179. signed short dy; /* inline image vertical offset */
  180. unsigned short iw, ih;
  181. unsigned short w;
  182. unsigned char font_px, bold, italic, mono, underline, strike;
  183. unsigned char overline, font_face;
  184. unsigned char transform_scale;
  185. unsigned char origin_x_kind, origin_y_kind;
  186. signed short scale_x, scale_y, rotate_x100;
  187. signed short origin_x, origin_y;
  188. unsigned char has_lit;
  189. unsigned int form; /* node + 1, 0 = not a control */
  190. unsigned char form_kind;
  191. unsigned char form_disabled;
  192. };
  193. struct lay {
  194. int draw;
  195. struct ngui *ui;
  196. int left, right;
  197. int y;
  198. int line_x, line_y, line_h;
  199. int line_left, line_right;
  200. int parent_top;
  201. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  202. int cb_h; /* definite content height of the containing block for
  203. * percentage heights; 0 = indefinite (auto) */
  204. int run_x;
  205. int align;
  206. int depth;
  207. int space_pending;
  208. unsigned char float_active;
  209. int float_left, float_right, float_bottom;
  210. struct lay_run runs[96];
  211. int nruns;
  212. };
  213. struct hit {
  214. int x, y, w, h;
  215. unsigned short node;
  216. };
  217. /* Live form state; the DOM attributes stay the initial/default value. */
  218. #define FORM_MAX 64
  219. #define FORM_VALUE_MAX 63
  220. enum {
  221. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  222. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  223. };
  224. struct form_state {
  225. unsigned int node;
  226. char value[FORM_VALUE_MAX + 1];
  227. unsigned char len, caret, checked, selected, used;
  228. };
  229. static struct form_state form_states[FORM_MAX];
  230. static unsigned int form_focus;
  231. static unsigned int form_dirty;
  232. static int form_descendant(unsigned int node, unsigned int form);
  233. static int form_submit_form(unsigned int node, int fire_event);
  234. static int link_fragment_nav(unsigned int node);
  235. static void history_push(const char *url);
  236. static void form_reset_event(unsigned int form);
  237. static unsigned int s_len(const char *s);
  238. static int s_eq(const char *a, const char *b);
  239. static void form_key(int k);
  240. static void form_click(unsigned int node);
  241. static void style_for_node(unsigned int node, struct br_style *out);
  242. static int form_disabled(unsigned int node)
  243. {
  244. struct br_node *n = &doc.nodes[node];
  245. if (n->attr_flags & BR_ATTR_DISABLED)
  246. return 1;
  247. return br_find_attr(&doc, node, "disabled") != 0;
  248. }
  249. static int form_kind_of(unsigned int node)
  250. {
  251. const char *type = br_type(&doc, node);
  252. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  253. return FORM_TEXTAREA;
  254. if (doc.nodes[node].tag == BR_TAG_SELECT)
  255. return FORM_SELECT;
  256. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  257. if (s_eq(type, "reset"))
  258. return FORM_RESET;
  259. if (s_eq(type, "button"))
  260. return FORM_BUTTON;
  261. return FORM_SUBMIT;
  262. }
  263. if (s_eq(type, "password"))
  264. return FORM_PASSWORD;
  265. if (s_eq(type, "checkbox"))
  266. return FORM_CHECKBOX;
  267. if (s_eq(type, "radio"))
  268. return FORM_RADIO;
  269. if (s_eq(type, "submit"))
  270. return FORM_SUBMIT;
  271. if (s_eq(type, "reset"))
  272. return FORM_RESET;
  273. if (s_eq(type, "button"))
  274. return FORM_BUTTON;
  275. return FORM_TEXT;
  276. }
  277. static unsigned int form_option_count(unsigned int node)
  278. {
  279. unsigned int c, n = 0;
  280. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  281. if (doc.nodes[c].type == BR_NODE_ELEM &&
  282. doc.nodes[c].tag == BR_TAG_OPTION)
  283. n++;
  284. return n;
  285. }
  286. static unsigned int form_option_selected(unsigned int node)
  287. {
  288. unsigned int c, i = 0;
  289. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  290. if (doc.nodes[c].type != BR_NODE_ELEM ||
  291. doc.nodes[c].tag != BR_TAG_OPTION)
  292. continue;
  293. if (br_find_attr(&doc, c, "selected"))
  294. return i;
  295. i++;
  296. }
  297. return 0;
  298. }
  299. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  300. char *out, unsigned int cap)
  301. {
  302. unsigned int c, i = 0;
  303. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  304. if (doc.nodes[c].type != BR_NODE_ELEM ||
  305. doc.nodes[c].tag != BR_TAG_OPTION)
  306. continue;
  307. if (i == idx)
  308. return br_text_content(&doc, c, out, cap);
  309. i++;
  310. }
  311. return 0;
  312. }
  313. static struct form_state *form_get(unsigned int node, int create)
  314. {
  315. struct form_state *slot = 0;
  316. unsigned int i;
  317. for (i = 0; i < FORM_MAX; i++) {
  318. if (form_states[i].used) {
  319. if (form_states[i].node == node)
  320. return &form_states[i];
  321. } else if (!slot) {
  322. slot = &form_states[i];
  323. }
  324. }
  325. if (!create || !slot)
  326. return 0;
  327. slot->node = node;
  328. slot->len = 0;
  329. slot->caret = 0;
  330. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  331. slot->selected = form_option_selected(node);
  332. slot->used = 1;
  333. {
  334. unsigned int n = 0;
  335. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  336. n = br_text_content(&doc, node, slot->value,
  337. FORM_VALUE_MAX + 1);
  338. } else {
  339. const char *v = br_value(&doc, node);
  340. if (v) {
  341. n = s_len(v);
  342. if (n > FORM_VALUE_MAX)
  343. n = FORM_VALUE_MAX;
  344. for (unsigned int j = 0; j < n; j++)
  345. slot->value[j] = v[j];
  346. }
  347. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  348. n = br_text_content(&doc, node, slot->value,
  349. FORM_VALUE_MAX + 1);
  350. }
  351. if (n > FORM_VALUE_MAX)
  352. n = FORM_VALUE_MAX;
  353. slot->value[n] = '\0';
  354. slot->len = (unsigned char)n;
  355. slot->caret = (unsigned char)n;
  356. }
  357. return slot;
  358. }
  359. static void form_reset_state(void)
  360. {
  361. unsigned int i;
  362. for (i = 0; i < FORM_MAX; i++)
  363. form_states[i].used = 0;
  364. form_focus = 0;
  365. }
  366. static int form_is_control(unsigned int node)
  367. {
  368. unsigned int tag;
  369. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  370. return 0;
  371. tag = doc.nodes[node].tag;
  372. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  373. tag == BR_TAG_SELECT || tag == BR_TAG_BUTTON;
  374. }
  375. #define HIT_MAX 96
  376. static struct hit hits[HIT_MAX];
  377. static int nhits;
  378. static unsigned short block_h[BR_MAX_NODES];
  379. /* Measure-pass top of each block, in the same document coordinates as
  380. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  381. * paint, so it cannot drive the lazy background loader). */
  382. static unsigned short block_top[BR_MAX_NODES];
  383. static char li_marker[BR_MAX_NODES][12];
  384. /* one connection object; the browser fetches one resource at a time */
  385. /* ---- tiny strings ---- */
  386. static unsigned int s_len(const char *s)
  387. {
  388. unsigned int n = 0;
  389. while (s && s[n])
  390. n++;
  391. return n;
  392. }
  393. static void s_copy(char *d, const char *s, unsigned int cap)
  394. {
  395. unsigned int i = 0;
  396. if (!cap)
  397. return;
  398. while (s && s[i] && i + 1 < cap) {
  399. d[i] = s[i];
  400. i++;
  401. }
  402. d[i] = '\0';
  403. }
  404. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  405. {
  406. while (s && *s && *n + 1 < cap)
  407. d[(*n)++] = *s++;
  408. d[*n] = '\0';
  409. }
  410. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  411. unsigned int cap)
  412. {
  413. char tmp[12];
  414. unsigned int i = 0, j;
  415. do {
  416. tmp[i++] = (char)('0' + v % 10);
  417. v /= 10;
  418. } while (v && i < sizeof(tmp));
  419. for (j = 0; j < i && *n + 1 < cap; j++)
  420. d[(*n)++] = tmp[i - 1 - j];
  421. d[*n] = '\0';
  422. }
  423. static int s_eq(const char *a, const char *b)
  424. {
  425. while (*a && *b) {
  426. if (*a != *b)
  427. return 0;
  428. a++;
  429. b++;
  430. }
  431. return *a == *b;
  432. }
  433. static int starts_with(const char *s, const char *p)
  434. {
  435. unsigned int i = 0;
  436. while (p[i]) {
  437. if (s[i] != p[i])
  438. return 0;
  439. i++;
  440. }
  441. return 1;
  442. }
  443. static int contains_ci(const char *s, const char *p)
  444. {
  445. unsigned int i, j;
  446. for (i = 0; s[i]; i++) {
  447. for (j = 0; p[j]; j++) {
  448. char a = s[i + j];
  449. if (a >= 'A' && a <= 'Z')
  450. a = (char)(a - 'A' + 'a');
  451. if (a != p[j])
  452. break;
  453. }
  454. if (!p[j])
  455. return 1;
  456. }
  457. return 0;
  458. }
  459. static char *trim(char *s)
  460. {
  461. unsigned int n;
  462. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  463. s++;
  464. n = s_len(s);
  465. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  466. s[n - 1] == '\r' || s[n - 1] == '\n'))
  467. s[--n] = '\0';
  468. return s;
  469. }
  470. /* ---- per-process heap ---- */
  471. static int heap_start(void)
  472. {
  473. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  474. if (!image_io_buf)
  475. return -1;
  476. page_backbuf = (unsigned short *)malloc(
  477. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  478. pagebuf_w = page_backbuf ? ui.w : 0;
  479. pagebuf_h = page_backbuf ? ui.h : 0;
  480. page_cache_valid = 0;
  481. return 0;
  482. }
  483. static void heap_clear(void)
  484. {
  485. memset(font_faces, 0, sizeof(font_faces));
  486. ngui_font_detach(&ui);
  487. svg_cache_clear();
  488. decode_arena = 0; /* lives in the page heap too */
  489. decode_arena_size = 0;
  490. heap_reset();
  491. /* The document arenas live in that heap; drop the stale pointers so
  492. * the next br_parse_plain() allocates fresh ones. */
  493. doc.nodes = 0;
  494. doc.text = 0;
  495. doc.attrs = 0;
  496. image_io_buf = 0;
  497. page_backbuf = 0;
  498. pagebuf_w = pagebuf_h = 0;
  499. page_cache_valid = 0;
  500. }
  501. static void browser_rules_alloc(void)
  502. {
  503. struct br_rule *rules;
  504. rules = (struct br_rule *)malloc(
  505. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  506. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  507. }
  508. /* ---- status ---- */
  509. static void set_status(const char *s, int err, unsigned int ttl_ms)
  510. {
  511. s_copy(status_text, s, sizeof(status_text));
  512. status_error = err;
  513. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  514. ngui_invalidate(&ui);
  515. }
  516. /* ---- JavaScript ---- */
  517. static int resolve_link(const char *base, const char *href, char *out,
  518. unsigned int cap);
  519. static char js_last_status[BR_STATUS_MAX];
  520. static int js_last_error;
  521. static void js_host_status(const char *msg, int error)
  522. {
  523. s_copy(js_last_status, msg, sizeof(js_last_status));
  524. js_last_error = error;
  525. set_status(msg, error, 6000);
  526. }
  527. static void js_host_report(const char *msg)
  528. {
  529. u_puts("[js] ");
  530. u_puts(msg);
  531. u_putc('\n');
  532. s_copy(js_last_status, msg, sizeof(js_last_status));
  533. js_last_error = 1;
  534. set_status(msg, 1, 8000);
  535. }
  536. static void js_host_navigate(const char *url)
  537. {
  538. char resolved[BR_URL_MAX];
  539. if (!url || !url[0])
  540. return;
  541. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  542. return;
  543. s_copy(pending_url, resolved, sizeof(pending_url));
  544. pending_action |= ACT_NAV;
  545. cancel_fetch = 1;
  546. }
  547. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  548. * back/forward between fragments): the page URL, address bar and history
  549. * follow, nothing is reloaded. `push` adds a history entry. */
  550. static int page_set_fragment(const char *url, int push)
  551. {
  552. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  553. return -1;
  554. s_copy(page_url, url, sizeof(page_url));
  555. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  556. url_in.len = s_len(url_in.text);
  557. url_in.cursor = url_in.len;
  558. url_in.scroll = 0;
  559. if (push)
  560. history_push(page_url);
  561. ngui_invalidate(&ui);
  562. return 0;
  563. }
  564. static int js_host_set_hash(const char *url)
  565. {
  566. return page_set_fragment(url, 1);
  567. }
  568. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  569. * the page, so a hash router can react). */
  570. static int same_doc_fragment(const char *url)
  571. {
  572. unsigned int a = 0, b = 0;
  573. if (!js_browser_active() || !url)
  574. return 0;
  575. while (url[a] && url[a] != '#')
  576. a++;
  577. while (page_url[b] && page_url[b] != '#')
  578. b++;
  579. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  580. !s_eq(url, page_url);
  581. }
  582. static void js_host_changed(void)
  583. {
  584. /* Class/style/attribute mutations change computed styles, not just the
  585. * text: drop the per-node style cache before the next layout. */
  586. br_reset_styles(&doc);
  587. layout_valid = 0;
  588. /* Script-built content (Angular's ng-repeat cards) brings new images
  589. * and inline background styles: rescan once the main loop is idle. */
  590. preload_rescan = 1;
  591. ngui_invalidate(&ui);
  592. }
  593. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  594. {
  595. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  596. return 0;
  597. *x = layout_boxes[node].x - page_rect.x;
  598. *y = layout_boxes[node].y - page_rect.y;
  599. *w = layout_boxes[node].w;
  600. *h = layout_boxes[node].h;
  601. return 1;
  602. }
  603. static void form_copy_out(const char *s, char *buf, int cap)
  604. {
  605. int i = 0;
  606. if (!buf || cap <= 0)
  607. return;
  608. while (s && s[i] && i + 1 < cap) {
  609. buf[i] = s[i];
  610. i++;
  611. }
  612. buf[i] = '\0';
  613. }
  614. static int js_host_form_value(unsigned int node, char *buf, int cap)
  615. {
  616. struct form_state *fs;
  617. int kind;
  618. if (!form_is_control(node))
  619. return 0;
  620. kind = form_kind_of(node);
  621. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  622. return 0;
  623. if (kind == FORM_SELECT) {
  624. char opt[64] = "";
  625. unsigned int c, i = 0;
  626. fs = form_get(node, 1);
  627. if (!fs)
  628. return 0;
  629. form_option_text(node, fs->selected, opt, sizeof(opt));
  630. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  631. if (doc.nodes[c].type != BR_NODE_ELEM ||
  632. doc.nodes[c].tag != BR_TAG_OPTION)
  633. continue;
  634. if (i == fs->selected) {
  635. const char *v = br_value(&doc, c);
  636. if (v && v[0])
  637. form_copy_out(v, buf, cap);
  638. else
  639. form_copy_out(opt, buf, cap);
  640. return 1;
  641. }
  642. i++;
  643. }
  644. form_copy_out(opt, buf, cap);
  645. return 1;
  646. }
  647. fs = form_get(node, 1);
  648. if (!fs)
  649. return 0;
  650. form_copy_out(fs->value, buf, cap);
  651. return 1;
  652. }
  653. static int js_host_form_checked(unsigned int node)
  654. {
  655. struct form_state *fs;
  656. int kind;
  657. if (!form_is_control(node))
  658. return -1;
  659. kind = form_kind_of(node);
  660. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  661. return -1;
  662. fs = form_get(node, 1);
  663. return fs ? fs->checked : 0;
  664. }
  665. static int js_host_form_selected(unsigned int node)
  666. {
  667. struct form_state *fs;
  668. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  669. return -1;
  670. fs = form_get(node, 1);
  671. return fs ? fs->selected : 0;
  672. }
  673. static int js_host_form_set_value(unsigned int node, const char *value)
  674. {
  675. struct form_state *fs;
  676. unsigned int n;
  677. if (!form_is_control(node))
  678. return 0;
  679. fs = form_get(node, 1);
  680. if (!fs)
  681. return 0;
  682. n = s_len(value ? value : "");
  683. if (n > FORM_VALUE_MAX)
  684. n = FORM_VALUE_MAX;
  685. for (unsigned int i = 0; i < n; i++)
  686. fs->value[i] = value[i];
  687. fs->value[n] = '\0';
  688. fs->len = (unsigned char)n;
  689. fs->caret = (unsigned char)n;
  690. layout_valid = 0;
  691. ngui_invalidate(&ui);
  692. return 1;
  693. }
  694. static int js_host_form_set_checked(unsigned int node, int checked)
  695. {
  696. struct form_state *fs;
  697. int kind;
  698. if (!form_is_control(node))
  699. return 0;
  700. kind = form_kind_of(node);
  701. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  702. return 0;
  703. fs = form_get(node, 1);
  704. if (!fs)
  705. return 0;
  706. fs->checked = (unsigned char)(checked != 0);
  707. layout_valid = 0;
  708. ngui_invalidate(&ui);
  709. return 1;
  710. }
  711. static int js_host_form_set_selected(unsigned int node, int index)
  712. {
  713. struct form_state *fs;
  714. unsigned int n;
  715. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  716. return 0;
  717. fs = form_get(node, 1);
  718. if (!fs)
  719. return 0;
  720. n = form_option_count(node);
  721. if (index < 0)
  722. index = 0;
  723. if (n && (unsigned int)index >= n)
  724. index = (int)n - 1;
  725. fs->selected = (unsigned char)index;
  726. layout_valid = 0;
  727. ngui_invalidate(&ui);
  728. return 1;
  729. }
  730. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  731. {
  732. unsigned int i;
  733. int n = 0;
  734. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  735. doc.nodes[form].tag != BR_TAG_FORM)
  736. return 0;
  737. for (i = 0; i < doc.nnode && n < cap; i++) {
  738. struct br_node *nd = &doc.nodes[i];
  739. if (i == form || nd->type != BR_NODE_ELEM)
  740. continue;
  741. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  742. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  743. continue;
  744. if (!form_descendant(i, form))
  745. continue;
  746. out[n++] = i;
  747. }
  748. return n;
  749. }
  750. static int js_host_form_submit(unsigned int form)
  751. {
  752. form_submit_form(form, 0);
  753. return 1;
  754. }
  755. static int js_host_form_reset(unsigned int form)
  756. {
  757. form_reset_event(form);
  758. return 1;
  759. }
  760. static void css_computed_name(const char *p, char *out, int cap)
  761. {
  762. int n = 0;
  763. for (; p && *p && n + 2 < cap; p++) {
  764. char c = *p;
  765. if (c >= 'A' && c <= 'Z') {
  766. out[n++] = '-';
  767. c = (char)(c - 'A' + 'a');
  768. } else if (c == '_') {
  769. c = '-';
  770. } else if (c >= 'a' && c <= 'z') {
  771. /* keep */
  772. }
  773. out[n++] = c;
  774. }
  775. out[n] = '\0';
  776. if (!strcmp(out, "css-float"))
  777. strcpy(out, "float");
  778. }
  779. static void css_rgb(unsigned short c, char *buf, int cap)
  780. {
  781. int r = ((c >> 11) & 31) * 255 / 31;
  782. int g = ((c >> 5) & 63) * 255 / 63;
  783. int b = (c & 31) * 255 / 31;
  784. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  785. }
  786. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  787. int font_px)
  788. {
  789. if (unit == 4) {
  790. snprintf(buf, cap, "auto");
  791. } else if (unit == 0) {
  792. snprintf(buf, cap, "%dpx", raw);
  793. } else if (unit == 1) {
  794. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  795. } else if (unit == 2) {
  796. /* Chrome's getComputedStyle() reports used pixel values. */
  797. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  798. } else if (unit == 3) {
  799. snprintf(buf, cap, "%dpx",
  800. (int)br_root_font_px() * raw / 100);
  801. } else {
  802. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  803. raw / 100, raw % 100, px);
  804. }
  805. }
  806. static int js_host_computed(unsigned int node, const char *property,
  807. char *buf, int cap)
  808. {
  809. struct br_style st;
  810. char name[40];
  811. if (!buf || cap <= 0 || node >= doc.nnode || node == 0)
  812. return 0;
  813. buf[0] = '\0';
  814. css_computed_name(property, name, sizeof(name));
  815. style_for_node(node, &st);
  816. if (!strcmp(name, "display")) {
  817. const char *v = "inline";
  818. if (st.display == BR_DISPLAY_BLOCK)
  819. v = "block";
  820. else if (st.display == BR_DISPLAY_NONE)
  821. v = "none";
  822. else if (st.display == BR_DISPLAY_FLEX)
  823. v = "flex";
  824. else if (st.display == BR_DISPLAY_GRID)
  825. v = "grid";
  826. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  827. v = "inline-block";
  828. snprintf(buf, cap, "%s", v);
  829. } else if (!strcmp(name, "position")) {
  830. static const char *pos[] = {
  831. "static", "absolute", "fixed", "relative", "sticky"
  832. };
  833. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  834. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  835. int is_w = name[0] == 'w';
  836. int kind = is_w ? st.width_kind : st.height_kind;
  837. int val = is_w ? st.width : st.height;
  838. if (kind == 3) {
  839. if (is_w)
  840. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  841. st.width_calc_pct / 100,
  842. st.width_calc_pct % 100,
  843. st.width_calc_px);
  844. else
  845. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  846. st.height_calc_pct / 100,
  847. st.height_calc_pct % 100,
  848. st.height_calc_px);
  849. } else if (kind == 1) {
  850. snprintf(buf, cap, "%dpx", val);
  851. } else if (kind == 2) {
  852. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  853. } else {
  854. snprintf(buf, cap, "auto");
  855. }
  856. } else if (!strcmp(name, "color") ||
  857. !strcmp(name, "background-color")) {
  858. if (!strcmp(name, "background-color") && !st.has_bg)
  859. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  860. else
  861. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  862. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  863. int is_fill = name[0] == 'f';
  864. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  865. if (mode == BR_PAINT_COLOR)
  866. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  867. else if (mode == BR_PAINT_CURRENT)
  868. css_rgb(st.color, buf, cap);
  869. else if (mode == BR_PAINT_UNSET && is_fill)
  870. snprintf(buf, cap, "rgb(0, 0, 0)");
  871. else if (mode == BR_PAINT_URL)
  872. snprintf(buf, cap, "url()");
  873. else
  874. snprintf(buf, cap, "none");
  875. } else if (!strcmp(name, "font-size")) {
  876. snprintf(buf, cap, "%dpx", st.font_px);
  877. } else if (!strcmp(name, "font-weight")) {
  878. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  879. } else if (!strcmp(name, "font-style")) {
  880. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  881. } else if (!strcmp(name, "font-family")) {
  882. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  883. br_font_face_family(st.font_face)[0])
  884. snprintf(buf, cap, "%s",
  885. br_font_face_family(st.font_face));
  886. else
  887. snprintf(buf, cap, "%s",
  888. st.mono ? "monospace" : "sans-serif");
  889. } else if (!strcmp(name, "text-align")) {
  890. static const char *al[] = { "left", "center", "right", "justify" };
  891. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  892. } else if (!strcmp(name, "float")) {
  893. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  894. st.float_left == 2 ? "right" : "none");
  895. } else if (!strcmp(name, "clear")) {
  896. static const char *cl[] = { "none", "left", "right", "both" };
  897. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  898. } else if (!strcmp(name, "opacity")) {
  899. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  900. } else if (!strcmp(name, "visibility")) {
  901. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  902. } else if (!strcmp(name, "overflow")) {
  903. snprintf(buf, cap, "%s",
  904. st.overflow_hidden ? "hidden" : "visible");
  905. } else if (!strcmp(name, "white-space")) {
  906. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  907. } else if (!strcmp(name, "text-transform")) {
  908. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  909. } else if (!strcmp(name, "box-sizing")) {
  910. snprintf(buf, cap, "%s",
  911. st.box_sizing ? "border-box" : "content-box");
  912. } else if (!strcmp(name, "line-height")) {
  913. if (st.line_h_px)
  914. snprintf(buf, cap, "%dpx", st.line_h_px);
  915. else if (st.line_h_pct)
  916. snprintf(buf, cap, "%d%%", st.line_h_pct);
  917. else
  918. snprintf(buf, cap, "normal");
  919. } else if (!strcmp(name, "z-index")) {
  920. if (st.z_set)
  921. snprintf(buf, cap, "%d", st.z_index);
  922. else
  923. snprintf(buf, cap, "auto");
  924. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  925. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  926. int set = name[0] == 't' ? st.top_set :
  927. name[0] == 'l' ? st.left_set :
  928. name[0] == 'r' ? st.right_set : st.bottom_set;
  929. int v = name[0] == 't' ? st.top :
  930. name[0] == 'l' ? st.left :
  931. name[0] == 'r' ? st.right : st.bottom;
  932. if (set)
  933. snprintf(buf, cap, "%dpx", v);
  934. else
  935. snprintf(buf, cap, "auto");
  936. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  937. !strcmp(name, "margin-bottom") ||
  938. !strcmp(name, "margin-left") ||
  939. !strcmp(name, "padding-top") ||
  940. !strcmp(name, "padding-right") ||
  941. !strcmp(name, "padding-bottom") ||
  942. !strcmp(name, "padding-left")) {
  943. int is_pad = name[0] == 'p';
  944. int side = name[strlen(name) - 1] == 'p' ? 0 :
  945. name[strlen(name) - 1] == 't' ? 1 :
  946. name[strlen(name) - 1] == 'm' ? 2 : 3;
  947. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  948. if (!strcmp(name, "margin-right") ||
  949. !strcmp(name, "padding-right"))
  950. side = 1;
  951. else if (!strcmp(name, "margin-bottom") ||
  952. !strcmp(name, "padding-bottom"))
  953. side = 2;
  954. else if (!strcmp(name, "margin-left") ||
  955. !strcmp(name, "padding-left"))
  956. side = 3;
  957. else
  958. side = 0;
  959. side += is_pad ? 4 : 0;
  960. css_mp_value(buf, cap,
  961. side == 0 ? st.mt : side == 1 ? st.mr :
  962. side == 2 ? st.mb : side == 3 ? st.ml :
  963. side == 4 ? st.pt : side == 5 ? st.pr :
  964. side == 6 ? st.pb : st.pl,
  965. st.mp_unit[side], st.mp_calc_px[side],
  966. st.font_px);
  967. } else if (!strcmp(name, "border-top-width") ||
  968. !strcmp(name, "border-right-width") ||
  969. !strcmp(name, "border-bottom-width") ||
  970. !strcmp(name, "border-left-width")) {
  971. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  972. name[7] == 'b' ? 2 : 3;
  973. snprintf(buf, cap, "%dpx", st.border_w[side]);
  974. } else if (!strcmp(name, "border-top-color") ||
  975. !strcmp(name, "border-right-color") ||
  976. !strcmp(name, "border-bottom-color") ||
  977. !strcmp(name, "border-left-color")) {
  978. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  979. name[7] == 'b' ? 2 : 3;
  980. if (st.border_w[side] && !st.border_t[side])
  981. css_rgb(st.border_c[side], buf, cap);
  982. else
  983. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  984. } else if (!strcmp(name, "background-image")) {
  985. if (st.bg_image)
  986. snprintf(buf, cap, "url(\"%s\")",
  987. br_bg_image_url(st.bg_image - 1));
  988. else
  989. snprintf(buf, cap, "none");
  990. } else if (!strcmp(name, "background-repeat")) {
  991. static const char *rp[] = {
  992. "repeat", "no-repeat", "repeat-x", "repeat-y"
  993. };
  994. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  995. st.bg_repeat : 0]);
  996. } else if (!strcmp(name, "background-position")) {
  997. if (st.bg_pos_x_kind == 1)
  998. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  999. st.bg_pos_y);
  1000. else
  1001. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1002. st.bg_pos_y);
  1003. } else if (!strcmp(name, "background-size")) {
  1004. if (st.bg_size_kind == 3)
  1005. snprintf(buf, cap, "cover");
  1006. else if (st.bg_size_kind == 4)
  1007. snprintf(buf, cap, "contain");
  1008. else if (st.bg_size_kind == 1)
  1009. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1010. st.bg_size_h);
  1011. else if (st.bg_size_kind == 2)
  1012. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1013. st.bg_size_h);
  1014. else
  1015. snprintf(buf, cap, "auto");
  1016. } else if (!strcmp(name, "transform")) {
  1017. char tmp[128];
  1018. unsigned int n = 0;
  1019. if (!st.transform_set) {
  1020. snprintf(buf, cap, "none");
  1021. } else {
  1022. tmp[0] = '\0';
  1023. if (st.tx || st.ty) {
  1024. snprintf(tmp + n, sizeof(tmp) - n,
  1025. "translate(%dpx, %dpx)", st.tx, st.ty);
  1026. n = (unsigned int)strlen(tmp);
  1027. }
  1028. if (st.transform_scale) {
  1029. snprintf(tmp + n, sizeof(tmp) - n,
  1030. "%sscale(%d.%02d, %d.%02d)",
  1031. n ? " " : "", st.scale_x / 100,
  1032. st.scale_x % 100, st.scale_y / 100,
  1033. st.scale_y % 100);
  1034. n = (unsigned int)strlen(tmp);
  1035. if (st.rotate_x100) {
  1036. snprintf(tmp + n, sizeof(tmp) - n,
  1037. " rotate(%d.%02ddeg)",
  1038. st.rotate_x100 / 100,
  1039. st.rotate_x100 % 100);
  1040. }
  1041. } else if (st.rotate_x100) {
  1042. snprintf(tmp + n, sizeof(tmp) - n,
  1043. "%srotate(%d.%02ddeg)",
  1044. n ? " " : "", st.rotate_x100 / 100,
  1045. st.rotate_x100 % 100);
  1046. }
  1047. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1048. }
  1049. } else {
  1050. return 0;
  1051. }
  1052. return buf[0] != '\0';
  1053. }
  1054. static int js_host_click(unsigned int node)
  1055. {
  1056. char url[BR_URL_MAX];
  1057. const char *href;
  1058. if (node >= doc.nnode)
  1059. return 0;
  1060. if (form_is_control(node)) {
  1061. form_click(node); /* dispatches its own click event */
  1062. return 1;
  1063. }
  1064. /* element.click() fires a bubbling, cancelable click before the
  1065. * default action, like a real click (delegated list handlers). */
  1066. if (!js_browser_event(node, "click", 1, 1))
  1067. return 1;
  1068. if (link_fragment_nav(node))
  1069. return 1;
  1070. href = br_href(&doc, node);
  1071. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1072. return 0;
  1073. s_copy(pending_url, url, sizeof(pending_url));
  1074. pending_action |= ACT_NAV;
  1075. cancel_fetch = 1;
  1076. ngui_invalidate(&ui);
  1077. return 1;
  1078. }
  1079. static int fetch_script_text(const char *url, unsigned char **out,
  1080. unsigned int *outlen, char *err,
  1081. unsigned int errcap);
  1082. struct fetch_worker;
  1083. static struct fetch_worker *fetch_worker_alloc(void);
  1084. static void fetch_worker_release(struct fetch_worker *w);
  1085. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1086. unsigned int cap, const char *post,
  1087. unsigned int post_len, unsigned int node,
  1088. int bg, char *err, unsigned int errcap);
  1089. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1090. unsigned int errcap);
  1091. static int fetch_worker_read_body(struct fetch_worker *w,
  1092. unsigned char *plain,
  1093. unsigned int plaincap,
  1094. unsigned char *comp,
  1095. unsigned int compcap,
  1096. int *truncated, char *err,
  1097. unsigned int errcap);
  1098. static void fetch_workers_stop_all(void);
  1099. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1100. unsigned int cap, const char *method,
  1101. const char *ctype, const char *post,
  1102. unsigned int post_len, unsigned int node,
  1103. int bg, char *err, unsigned int errcap);
  1104. static int script_cache_has(const char *url);
  1105. static void script_cache_put(const char *url, const unsigned char *data,
  1106. unsigned int len);
  1107. static unsigned int script_cache_hash(const char *s);
  1108. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1109. unsigned int errcap);
  1110. static void fetch_workers_cancel_busy(void);
  1111. static void worker_wait_ui(void);
  1112. static int fetch_worker_status(const struct fetch_worker *w);
  1113. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1114. * module load: the wait must not pump input, or a click would dispatch DOM
  1115. * events into the middle of the running script. */
  1116. static int fetch_wait_passive;
  1117. static void script_error(const char *what, const char *url, const char *why)
  1118. {
  1119. char msg[192];
  1120. unsigned int n = 0;
  1121. s_append(msg, &n, what, sizeof(msg));
  1122. if (url && url[0]) {
  1123. s_append(msg, &n, " ", sizeof(msg));
  1124. s_append(msg, &n, url, sizeof(msg));
  1125. }
  1126. if (why && why[0]) {
  1127. s_append(msg, &n, ": ", sizeof(msg));
  1128. s_append(msg, &n, why, sizeof(msg));
  1129. }
  1130. js_host_report(msg);
  1131. }
  1132. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1133. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1134. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1135. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1136. #define JS_HTTP_POST_MAX (16u * 1024u)
  1137. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1138. static int js_worker_http(const char *method, const char *url,
  1139. const char *ctype, const char *body,
  1140. unsigned int body_len, struct js_http_resp *r,
  1141. char *err, int errcap);
  1142. static int js_host_http(const char *method, const char *url,
  1143. const char *ctype, const char *body,
  1144. unsigned int body_len, struct js_http_resp *r,
  1145. char *err, int errcap)
  1146. {
  1147. if (pending_action) {
  1148. s_copy(err, "page is navigating", (unsigned int)errcap);
  1149. return -1;
  1150. }
  1151. if (url[0] == '/') {
  1152. /* Local file: GET only. */
  1153. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1154. int rv;
  1155. if (!buf) {
  1156. s_copy(err, "out of memory", (unsigned int)errcap);
  1157. return -1;
  1158. }
  1159. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1160. (int)JS_HTTP_MAX);
  1161. r->status = rv < 0 ? 404 : 200;
  1162. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1163. buf[r->len] = '\0';
  1164. r->body = (char *)buf;
  1165. s_copy(r->url, url, sizeof(r->url));
  1166. if (contains_ci(url, ".json"))
  1167. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1168. return 0;
  1169. }
  1170. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1171. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1172. return -1;
  1173. }
  1174. if (body_len > JS_HTTP_POST_MAX) {
  1175. s_copy(err, "request body too large", (unsigned int)errcap);
  1176. return -1;
  1177. }
  1178. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1179. errcap);
  1180. }
  1181. /* Module source for the engine's loader: the boot script cache first, then
  1182. * one blocking fetch with input pumping disabled (the loader runs inside
  1183. * JavaScript). */
  1184. static char *js_host_load_script(const char *url, unsigned int *len)
  1185. {
  1186. unsigned char *data = 0;
  1187. char err[64];
  1188. int rv;
  1189. fetch_wait_passive++;
  1190. set_status("Loading module...", 0, 0);
  1191. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1192. fetch_wait_passive--;
  1193. if (rv != 0) {
  1194. script_error("Cannot load module", url,
  1195. rv == FETCH_ABORT ? "navigation" : err);
  1196. return 0;
  1197. }
  1198. return (char *)data;
  1199. }
  1200. /* Web Storage lives in /share, outside the page heap that every navigation
  1201. * resets: localStorage per origin for the boot, sessionStorage per origin
  1202. * and browser window. */
  1203. #define JS_ORIGIN_MAX 160
  1204. /* scheme://host[:port] of the page (a local page's whole path). */
  1205. static void js_page_origin(char *origin, unsigned int cap)
  1206. {
  1207. unsigned int i = 0, slashes = 0;
  1208. while (page_url[i] && i + 1 < cap) {
  1209. if (page_url[i] == '/' && ++slashes == 3)
  1210. break;
  1211. origin[i] = page_url[i];
  1212. i++;
  1213. }
  1214. origin[i] = '\0';
  1215. }
  1216. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1217. {
  1218. unsigned int n = 0;
  1219. s_append(out, &n, "/share/bls", cap);
  1220. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1221. }
  1222. static void js_storage_path(int kind, char *out, unsigned int cap)
  1223. {
  1224. char origin[JS_ORIGIN_MAX];
  1225. unsigned int n = 0;
  1226. js_page_origin(origin, sizeof(origin));
  1227. if (!kind) {
  1228. js_origin_path(origin, out, cap);
  1229. return;
  1230. }
  1231. s_append(out, &n, "/share/bss", cap);
  1232. if (kind) {
  1233. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1234. s_append(out, &n, "-", cap);
  1235. }
  1236. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1237. }
  1238. static void persist_mark_origin(const char *origin);
  1239. static int persist_store_lookup(const char *origin, char *out, int cap);
  1240. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1241. {
  1242. char path[48], origin[JS_ORIGIN_MAX];
  1243. int rv;
  1244. js_storage_path(kind, path, sizeof(path));
  1245. if (set) {
  1246. if (kind) {
  1247. if (!set[0] || !strcmp(set, "{}")) {
  1248. u_syscall1(SYS_UNLINK, (int)path);
  1249. return 0;
  1250. }
  1251. } else {
  1252. /* localStorage keeps an explicit "{}" rather than no
  1253. * file: a missing /share file means "not loaded from
  1254. * /data yet", and a cleared store must not come back
  1255. * from the disk copy before it is flushed. */
  1256. if (!set[0])
  1257. set = "{}";
  1258. js_page_origin(origin, sizeof(origin));
  1259. persist_mark_origin(origin);
  1260. }
  1261. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1262. (int)strlen(set)) < 0 ? -1 : 0;
  1263. }
  1264. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1265. if (rv < 0 && !kind) {
  1266. /* First use this boot: the persistent copy on /data. */
  1267. js_page_origin(origin, sizeof(origin));
  1268. rv = persist_store_lookup(origin, out, cap);
  1269. if (rv >= 0)
  1270. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1271. }
  1272. if (rv < 0)
  1273. return -1;
  1274. out[rv] = '\0';
  1275. return rv;
  1276. }
  1277. /* ---- persistence on /data ----
  1278. *
  1279. * /share is the working copy (RAM, shared by every helper and window); the
  1280. * installed disk's /data volume keeps the cookie jar and localStorage
  1281. * across reboots when it is mounted. The browser owns the disk copies: at
  1282. * start it restores the jar into /share, and its main loop writes back
  1283. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1284. * setItem updates costs one FAT write. The helpers only touch /share (they
  1285. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1286. * /data mount every disk access simply fails. Both files are plaintext
  1287. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1288. #define PERSIST_MS 3000u
  1289. #define SHARE_COOKIES "/share/bcookies"
  1290. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1291. #define DATA_STORE "/data/BSTORE.DAT"
  1292. #define DATA_STORE_MAGIC "NBLS1\n"
  1293. #define DATA_STORE_MAX (192u * 1024u)
  1294. #define PERSIST_DIRTY_MAX 8
  1295. static unsigned int persist_due;
  1296. static unsigned int cookie_sum_saved;
  1297. static int cookie_sum_valid;
  1298. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1299. static int persist_ndirty;
  1300. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1301. {
  1302. unsigned int h = 2166136261u, i;
  1303. for (i = 0; i < n; i++)
  1304. h = (h ^ p[i]) * 16777619u;
  1305. return h;
  1306. }
  1307. /* Called once at startup, before any helper runs. */
  1308. static void persist_restore(void)
  1309. {
  1310. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1311. int n;
  1312. if (!jar)
  1313. return;
  1314. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1315. (int)sizeof(struct uhttp_jar));
  1316. if (n != (int)sizeof(struct uhttp_jar)) {
  1317. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1318. (int)sizeof(struct uhttp_jar));
  1319. if (n == (int)sizeof(struct uhttp_jar)) {
  1320. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1321. (int)jar, n);
  1322. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1323. cookie_sum_valid = 1;
  1324. }
  1325. }
  1326. free(jar);
  1327. persist_due = u_ticks_ms() + PERSIST_MS;
  1328. }
  1329. static void persist_mark_origin(const char *origin)
  1330. {
  1331. int i;
  1332. for (i = 0; i < persist_ndirty; i++)
  1333. if (s_eq(persist_dirty[i], origin))
  1334. return;
  1335. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1336. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1337. }
  1338. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1339. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1340. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1341. unsigned int *o_off, unsigned int *o_len,
  1342. unsigned int *d_off, unsigned int *d_len,
  1343. unsigned int *rec_end)
  1344. {
  1345. unsigned int p = *pos, v = 0;
  1346. if (p >= len)
  1347. return 0;
  1348. *o_off = p;
  1349. while (p < len && buf[p] != '\n')
  1350. p++;
  1351. if (p >= len)
  1352. return 0;
  1353. *o_len = p - *o_off;
  1354. p++;
  1355. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1356. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1357. if (p >= len || buf[p] != '\n')
  1358. return 0;
  1359. p++;
  1360. if (v > len - p)
  1361. return 0;
  1362. *d_off = p;
  1363. *d_len = v;
  1364. p += v;
  1365. if (p < len && buf[p] == '\n')
  1366. p++;
  1367. *rec_end = p;
  1368. *pos = p;
  1369. return 1;
  1370. }
  1371. static int store_load(char **out)
  1372. {
  1373. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1374. int n;
  1375. *out = buf;
  1376. if (!buf)
  1377. return -1;
  1378. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1379. (int)DATA_STORE_MAX);
  1380. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1381. !starts_with(buf, DATA_STORE_MAGIC))
  1382. return 0;
  1383. return n;
  1384. }
  1385. static int persist_store_lookup(const char *origin, char *out, int cap)
  1386. {
  1387. char *buf;
  1388. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1389. unsigned int olen = s_len(origin);
  1390. int n = store_load(&buf), rv = -1;
  1391. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1392. &dl, &e)) {
  1393. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1394. if ((int)dl < cap) {
  1395. memcpy(out, buf + d, dl);
  1396. out[dl] = '\0';
  1397. rv = (int)dl;
  1398. }
  1399. break;
  1400. }
  1401. }
  1402. free(buf);
  1403. return rv;
  1404. }
  1405. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1406. static void persist_store_flush(void)
  1407. {
  1408. char *old, *nb, path[48];
  1409. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1410. int n = store_load(&old), i, w;
  1411. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1412. if (n < 0 || !nb) {
  1413. free(old);
  1414. free(nb);
  1415. return;
  1416. }
  1417. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1418. /* Untouched origins first, in their old order. */
  1419. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1420. &dl, &e)) {
  1421. int dirty = 0;
  1422. for (i = 0; i < persist_ndirty; i++)
  1423. if (s_len(persist_dirty[i]) == ol &&
  1424. !memcmp(persist_dirty[i], old + oo, ol))
  1425. dirty = 1;
  1426. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1427. continue;
  1428. memcpy(nb + nn, old + oo, e - oo);
  1429. nn += e - oo;
  1430. }
  1431. /* Then the changed ones (an emptied store is dropped). */
  1432. for (i = 0; i < persist_ndirty; i++) {
  1433. char num[12];
  1434. unsigned int k = 0;
  1435. js_origin_path(persist_dirty[i], path, sizeof(path));
  1436. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1437. (int)DATA_STORE_MAX);
  1438. if (w <= 2) /* missing or "{}" */
  1439. continue;
  1440. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1441. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1442. DATA_STORE_MAX) {
  1443. set_status("Saved site data is full; a site's "
  1444. "localStorage was not saved", 1, 6000);
  1445. continue;
  1446. }
  1447. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1448. nb[nn++] = '\n';
  1449. s_append(nb, &nn, num, DATA_STORE_MAX);
  1450. nb[nn++] = '\n';
  1451. memcpy(nb + nn, old, (unsigned int)w);
  1452. nn += (unsigned int)w;
  1453. nb[nn++] = '\n';
  1454. }
  1455. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1456. persist_ndirty = 0;
  1457. free(old);
  1458. free(nb);
  1459. }
  1460. static void persist_cookies_flush(void)
  1461. {
  1462. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1463. unsigned int sum;
  1464. int n;
  1465. if (!jar)
  1466. return;
  1467. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1468. (int)sizeof(struct uhttp_jar));
  1469. if (n == (int)sizeof(struct uhttp_jar)) {
  1470. sum = persist_sum(jar, (unsigned int)n);
  1471. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1472. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1473. (int)jar, n) >= 0) {
  1474. cookie_sum_saved = sum;
  1475. cookie_sum_valid = 1;
  1476. }
  1477. }
  1478. }
  1479. free(jar);
  1480. }
  1481. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1482. static void persist_tick(void)
  1483. {
  1484. unsigned int now = u_ticks_ms();
  1485. if ((int)(now - persist_due) < 0)
  1486. return;
  1487. persist_due = now + PERSIST_MS;
  1488. persist_cookies_flush();
  1489. if (persist_ndirty)
  1490. persist_store_flush();
  1491. }
  1492. /* <link rel="modulepreload">: download the page's module graph on all
  1493. * helpers at once into the boot script cache, before any script runs. The
  1494. * engine's module loader is sequential (one blocking fetch per import), so
  1495. * without this a Vite app with a dozen chunks pays every round trip in a
  1496. * row. Failures are ignored; the loader fetches what is missing. */
  1497. #define MODULE_PRELOAD_MAX 24
  1498. static void prefetch_module_preloads(void)
  1499. {
  1500. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1501. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1502. unsigned int count = 0, next = 0, done = 0, i;
  1503. char err[64];
  1504. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1505. struct br_node *nd = &doc.nodes[i];
  1506. const char *rel, *href;
  1507. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1508. continue;
  1509. rel = br_rel(&doc, i);
  1510. href = br_href(&doc, i);
  1511. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1512. continue;
  1513. if (resolve_link(page_url, href, urls[count],
  1514. sizeof(urls[count])) != 0 ||
  1515. urls[count][0] == '/' || script_cache_has(urls[count]))
  1516. continue;
  1517. slot[count++] = 0;
  1518. }
  1519. if (!count)
  1520. return;
  1521. set_status("Loading modules...", 0, 0);
  1522. while (done < count) {
  1523. struct fetch_worker *w;
  1524. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1525. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1526. 0, 0, 0, err,
  1527. sizeof(err)) != 0) {
  1528. fetch_worker_release(w);
  1529. done++;
  1530. } else {
  1531. slot[next] = w;
  1532. }
  1533. next++;
  1534. }
  1535. worker_wait_ui();
  1536. if (cancel_fetch || pending_action) {
  1537. fetch_workers_cancel_busy();
  1538. return;
  1539. }
  1540. for (i = 0; i < next; i++) {
  1541. unsigned char *body;
  1542. int rv, tr = 0;
  1543. if (!slot[i])
  1544. continue;
  1545. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1546. if (rv == 0)
  1547. continue;
  1548. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1549. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1550. if (body) {
  1551. rv = fetch_worker_read_body(slot[i], body,
  1552. BR_SCRIPT_MAX, image_io_buf,
  1553. BR_PAGE_COMP_MAX, &tr, err,
  1554. sizeof(err));
  1555. if (rv > 0 && !tr)
  1556. script_cache_put(urls[i], body,
  1557. (unsigned int)rv);
  1558. free(body);
  1559. }
  1560. fetch_worker_release(slot[i]);
  1561. slot[i] = 0;
  1562. done++;
  1563. }
  1564. u_sleep_ms(10);
  1565. }
  1566. }
  1567. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1568. * submitted to helper workers ahead of time, but scripts still execute in
  1569. * document order. */
  1570. #define SCRIPT_INLINE 0
  1571. #define SCRIPT_LOCAL 1
  1572. #define SCRIPT_REMOTE 2
  1573. #define SCRIPT_ERROR 3
  1574. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1575. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1576. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1577. static void script_submit_window(unsigned int *next, char *err,
  1578. unsigned int errcap)
  1579. {
  1580. while (*next < doc.nscripts) {
  1581. struct fetch_worker *w;
  1582. if (script_kind[*next] != SCRIPT_REMOTE) {
  1583. (*next)++;
  1584. continue;
  1585. }
  1586. w = fetch_worker_alloc();
  1587. if (!w)
  1588. return;
  1589. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1590. 0, 0, 0, 0, err, errcap) != 0) {
  1591. fetch_worker_release(w);
  1592. script_kind[*next] = SCRIPT_ERROR;
  1593. (*next)++;
  1594. continue;
  1595. }
  1596. script_slot[*next] = w;
  1597. (*next)++;
  1598. }
  1599. }
  1600. /* Run the page's scripts in document order. External bodies are prefetched
  1601. * in parallel so downloading script N+1 overlaps executing script N; inline
  1602. * bodies are copied because the engine needs NUL-terminated text. */
  1603. static void run_page_scripts(void)
  1604. {
  1605. struct js_browser_host host;
  1606. unsigned int i, next = 0;
  1607. char err[64], ferr[64];
  1608. if (!doc.nscripts)
  1609. return;
  1610. host.status = js_host_status;
  1611. host.report = js_host_report;
  1612. host.navigate = js_host_navigate;
  1613. host.changed = js_host_changed;
  1614. host.rect = js_host_rect;
  1615. host.form_value = js_host_form_value;
  1616. host.form_checked = js_host_form_checked;
  1617. host.form_selected = js_host_form_selected;
  1618. host.form_set_value = js_host_form_set_value;
  1619. host.form_set_checked = js_host_form_set_checked;
  1620. host.form_set_selected = js_host_form_set_selected;
  1621. host.form_elements = js_host_form_elements;
  1622. host.form_submit = js_host_form_submit;
  1623. host.form_reset = js_host_form_reset;
  1624. host.click = js_host_click;
  1625. host.computed = js_host_computed;
  1626. host.http = js_host_http;
  1627. host.load_script = js_host_load_script;
  1628. host.storage = js_host_storage;
  1629. host.set_hash = js_host_set_hash;
  1630. host.page_url = page_url;
  1631. host.width = ui.w;
  1632. host.height = ui.h;
  1633. if (js_browser_start(&doc, &host) != 0) {
  1634. js_host_status("JavaScript: out of memory", 1);
  1635. return;
  1636. }
  1637. resize_sent_w = -1;
  1638. resize_pending = 0;
  1639. prefetch_module_preloads();
  1640. for (i = 0; i < doc.nscripts; i++) {
  1641. struct br_script *script = &doc.scripts[i];
  1642. const char *src_attr = script->src_off ?
  1643. doc.attrs + script->src_off : "";
  1644. script_slot[i] = 0;
  1645. if (!script->src_off) {
  1646. script_kind[i] = SCRIPT_INLINE;
  1647. continue;
  1648. }
  1649. if (!src_attr[0] ||
  1650. resolve_link(page_url, src_attr, script_urls[i],
  1651. sizeof(script_urls[i])) != 0) {
  1652. script_urls[i][0] = '\0';
  1653. script_kind[i] = SCRIPT_ERROR;
  1654. continue;
  1655. }
  1656. if (script_urls[i][0] == '/' ||
  1657. script_cache_has(script_urls[i]))
  1658. script_kind[i] = SCRIPT_LOCAL;
  1659. else
  1660. script_kind[i] = SCRIPT_REMOTE;
  1661. }
  1662. script_submit_window(&next, ferr, sizeof(ferr));
  1663. for (i = 0; i < doc.nscripts; i++) {
  1664. struct br_script *script = &doc.scripts[i];
  1665. if (script_kind[i] == SCRIPT_INLINE) {
  1666. unsigned int off = script->off;
  1667. unsigned int len = script->len;
  1668. unsigned int k;
  1669. char *src = (char *)malloc(len + 1);
  1670. if (!src) {
  1671. js_host_status("JavaScript: out of memory", 1);
  1672. break;
  1673. }
  1674. for (k = 0; k < len; k++)
  1675. src[k] = doc.script_src[off + k];
  1676. src[len] = '\0';
  1677. if (script->module) {
  1678. /* A distinct module name per inline module
  1679. * (QuickJS registers modules by name); the
  1680. * fragment keeps relative imports resolving
  1681. * against the page. */
  1682. char mname[BR_URL_MAX + 16];
  1683. unsigned int mn = 0;
  1684. s_append(mname, &mn, page_url, sizeof(mname));
  1685. s_append(mname, &mn, "#module", sizeof(mname));
  1686. s_append_dec(mname, &mn, i, sizeof(mname));
  1687. js_browser_run_module(src, mname);
  1688. } else {
  1689. js_browser_run(src, page_url);
  1690. }
  1691. free(src);
  1692. } else if (script->src_off) {
  1693. const char *src_attr = doc.attrs + script->src_off;
  1694. if (script_kind[i] == SCRIPT_ERROR) {
  1695. script_error("Cannot load script", src_attr,
  1696. script_urls[i][0] ?
  1697. "network busy" :
  1698. "unsupported URL");
  1699. continue;
  1700. }
  1701. if (script_kind[i] == SCRIPT_LOCAL) {
  1702. unsigned char *data = 0;
  1703. unsigned int len = 0;
  1704. int rv;
  1705. set_status("Loading script...", 0, 0);
  1706. rv = fetch_script_text(script_urls[i], &data,
  1707. &len, err, sizeof(err));
  1708. if (rv == FETCH_ABORT)
  1709. break;
  1710. if (rv != 0) {
  1711. script_error("Cannot load script",
  1712. script_urls[i], err);
  1713. continue;
  1714. }
  1715. if (script->module)
  1716. js_browser_run_module(
  1717. (const char *)data,
  1718. script_urls[i]);
  1719. else
  1720. js_browser_run((const char *)data,
  1721. script_urls[i]);
  1722. free(data);
  1723. } else {
  1724. struct fetch_worker *w = script_slot[i];
  1725. unsigned char *body = 0;
  1726. int tr = 0, rv;
  1727. if (!w) {
  1728. w = fetch_worker_alloc();
  1729. if (!w)
  1730. continue;
  1731. if (fetch_worker_submit(w,
  1732. script_urls[i],
  1733. BR_SCRIPT_MAX,
  1734. 0, 0, 0, 0, err,
  1735. sizeof(err)) != 0) {
  1736. fetch_worker_release(w);
  1737. script_kind[i] = SCRIPT_ERROR;
  1738. if (i == next)
  1739. next++;
  1740. continue;
  1741. }
  1742. script_slot[i] = w;
  1743. if (i == next)
  1744. next++;
  1745. }
  1746. set_status("Loading script...", 0, 0);
  1747. rv = fetch_worker_wait(w, err, sizeof(err));
  1748. if (rv == FETCH_ABORT) {
  1749. fetch_workers_stop_all();
  1750. break;
  1751. }
  1752. /* The body gets its own buffer (scripts are up
  1753. * to 2 MB); image_io_buf takes the gzip
  1754. * stream. */
  1755. body = rv == 0 ? (unsigned char *)malloc(
  1756. BR_SCRIPT_MAX + 1) : 0;
  1757. if (body)
  1758. rv = fetch_worker_read_body(w, body,
  1759. BR_SCRIPT_MAX, image_io_buf,
  1760. BR_PAGE_COMP_MAX, &tr, err,
  1761. sizeof(err));
  1762. else {
  1763. if (rv == 0)
  1764. s_copy(err, "out of memory",
  1765. sizeof(err));
  1766. rv = -1;
  1767. }
  1768. fetch_worker_release(w);
  1769. script_slot[i] = 0;
  1770. script_submit_window(&next, ferr, sizeof(ferr));
  1771. if (rv <= 0)
  1772. script_error("Cannot load script",
  1773. script_urls[i], err);
  1774. else if (tr || (unsigned int)rv >=
  1775. BR_SCRIPT_MAX)
  1776. script_error("Cannot load script",
  1777. script_urls[i],
  1778. "script is too large");
  1779. else {
  1780. body[rv] = '\0';
  1781. script_cache_put(script_urls[i], body,
  1782. (unsigned int)rv);
  1783. if (script->module)
  1784. js_browser_run_module(
  1785. (const char *)body,
  1786. script_urls[i]);
  1787. else
  1788. js_browser_run(
  1789. (const char *)body,
  1790. script_urls[i]);
  1791. }
  1792. free(body);
  1793. }
  1794. }
  1795. if (pending_action)
  1796. break;
  1797. }
  1798. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  1799. * load_home() stop it before the next navigation. */
  1800. if (doc.scripts_truncated && !js_last_error)
  1801. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  1802. 1);
  1803. }
  1804. /* ---- images ---- */
  1805. static void image_reset(void)
  1806. {
  1807. int i;
  1808. for (i = 0; i < BR_MAX_IMAGES; i++) {
  1809. images[i].state = 0;
  1810. images[i].native_w = images[i].native_h = 0;
  1811. images[i].err[0] = '\0';
  1812. }
  1813. image_count = 0;
  1814. image_pixels = 0;
  1815. preload_active = 0;
  1816. preload_pending = 0;
  1817. preload_wait = 0;
  1818. preload_node = 0;
  1819. preload_loaded = 0;
  1820. }
  1821. /* Decode into the shared arena, then copy/scale the result into a display
  1822. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  1823. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  1824. * pixels. Transparent edges are composited over white. */
  1825. /* One decode scratch arena per page, reused across images. Allocating and
  1826. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  1827. * each small display bitmap landed in the hole the previous arena left, so
  1828. * the next arena no longer fit and the heap ratcheted up until an app
  1829. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  1830. * still released right after their one image. */
  1831. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  1832. static unsigned char *decode_arena_get(unsigned int bytes)
  1833. {
  1834. if (decode_arena && decode_arena_size >= bytes)
  1835. return decode_arena;
  1836. free(decode_arena);
  1837. decode_arena = (unsigned char *)malloc(bytes);
  1838. decode_arena_size = decode_arena ? bytes : 0;
  1839. return decode_arena;
  1840. }
  1841. static void decode_arena_put(void)
  1842. {
  1843. if (decode_arena_size > DECODE_ARENA_KEEP) {
  1844. free(decode_arena);
  1845. decode_arena = 0;
  1846. decode_arena_size = 0;
  1847. }
  1848. }
  1849. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  1850. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  1851. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  1852. static int decode_image_data(const unsigned char *data, unsigned int len,
  1853. struct br_image *bi, int box_w, int box_h)
  1854. {
  1855. struct img_info info;
  1856. struct img_options opt;
  1857. struct img_mem mem;
  1858. struct img_image decoded;
  1859. unsigned char *arena;
  1860. unsigned int est, bytes, i;
  1861. unsigned short *px;
  1862. unsigned char *alpha = 0;
  1863. int dw, dh, r;
  1864. if (img_sniff(data, len, &info) != 0) {
  1865. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  1866. return -1;
  1867. }
  1868. est = img_estimate(&info);
  1869. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  1870. s_copy(bi->err, "image too large", sizeof(bi->err));
  1871. return -1;
  1872. }
  1873. arena = decode_arena_get(est);
  1874. if (!arena) {
  1875. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1876. return -1;
  1877. }
  1878. img_mem_init(&mem, arena, est);
  1879. opt.max_pixels = BR_IMG_PIX_MAX;
  1880. r = img_decode(data, len, &opt, &mem, &decoded);
  1881. if (r != 0) {
  1882. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  1883. goto fail;
  1884. }
  1885. if (decoded.w == 0 || decoded.h == 0) {
  1886. s_copy(bi->err, "empty image", sizeof(bi->err));
  1887. goto fail;
  1888. }
  1889. bi->native_w = (int)decoded.w;
  1890. bi->native_h = (int)decoded.h;
  1891. dw = (int)decoded.w;
  1892. dh = (int)decoded.h;
  1893. if (box_w > 0 && box_h > 0) {
  1894. /* cover: scale so both box sides are filled, never up */
  1895. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  1896. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  1897. unsigned int sc = sw > sh ? sw : sh;
  1898. if (sc < 0x10000u) {
  1899. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  1900. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  1901. }
  1902. }
  1903. if (dw > BR_IMG_LAYOUT_W) {
  1904. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  1905. dw = BR_IMG_LAYOUT_W;
  1906. }
  1907. if (dh < 1)
  1908. dh = 1;
  1909. if (dw < 1)
  1910. dw = 1;
  1911. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  1912. BR_IMG_PIXEL_BUDGET) {
  1913. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  1914. goto fail;
  1915. }
  1916. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  1917. px = (unsigned short *)malloc(bytes);
  1918. if (!px) {
  1919. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1920. goto fail;
  1921. }
  1922. /* Keep the alpha plane for the scaled image so transparent logos and
  1923. * icons composite over the page instead of the browser's dark theme
  1924. * background. Very large alpha images stay flattened to bound the
  1925. * heap use. */
  1926. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  1927. alpha = (unsigned char *)malloc((unsigned int)dw *
  1928. (unsigned int)dh);
  1929. if (alpha) {
  1930. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1931. alpha[i] = 255;
  1932. }
  1933. }
  1934. /* With an alpha plane the colour under transparent pixels only shows
  1935. * through partially covered edge pixels of the downscale: use white,
  1936. * as documented above, not the dark browser theme (which left a dark
  1937. * fringe around scaled app icons). */
  1938. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1939. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  1940. {
  1941. struct img_blit b;
  1942. b.dst = px;
  1943. b.dst_w = dw;
  1944. b.dst_h = dh;
  1945. b.clip_x = 0;
  1946. b.clip_y = 0;
  1947. b.clip_w = dw;
  1948. b.clip_h = dh;
  1949. b.x = 0;
  1950. b.y = 0;
  1951. b.scale = ((unsigned int)dw << 16) / decoded.w;
  1952. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  1953. b.bg2 = b.bg;
  1954. b.dst_a = alpha;
  1955. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  1956. img_draw(&decoded, &b);
  1957. }
  1958. bi->img.format = decoded.format;
  1959. bi->img.w = (unsigned int)dw;
  1960. bi->img.h = (unsigned int)dh;
  1961. bi->img.px = px;
  1962. bi->img.alpha = alpha;
  1963. bi->img.flags = 0;
  1964. bi->state = 1;
  1965. image_pixels += (unsigned int)dw * (unsigned int)dh;
  1966. decode_arena_put();
  1967. return 0;
  1968. fail:
  1969. decode_arena_put();
  1970. return -1;
  1971. }
  1972. /* ---- URL / local path handling ---- */
  1973. static int is_http(const char *s)
  1974. {
  1975. return starts_with(s, "http://") || starts_with(s, "https://");
  1976. }
  1977. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  1978. static int normalize_abs(const char *in, char *out, unsigned int cap)
  1979. {
  1980. char seg[64];
  1981. unsigned int i = 0, o = 1;
  1982. int depth = 0;
  1983. int trailing;
  1984. if (!in || in[0] != '/' || cap < 2)
  1985. return -1;
  1986. trailing = 0;
  1987. {
  1988. unsigned int n = s_len(in);
  1989. if (n > 1 && in[n - 1] == '/')
  1990. trailing = 1;
  1991. }
  1992. out[0] = '/';
  1993. while (in[i]) {
  1994. unsigned int n = 0;
  1995. while (in[i] == '/')
  1996. i++;
  1997. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  1998. if (n + 1 < sizeof(seg))
  1999. seg[n++] = in[i];
  2000. i++;
  2001. }
  2002. seg[n] = '\0';
  2003. if (n == 0)
  2004. break;
  2005. if (s_eq(seg, "."))
  2006. continue;
  2007. if (s_eq(seg, "..")) {
  2008. if (depth > 0) {
  2009. while (o > 1 && out[o - 1] != '/')
  2010. o--;
  2011. if (o > 1)
  2012. o--;
  2013. depth--;
  2014. }
  2015. continue;
  2016. }
  2017. if (o > 1) {
  2018. if (o + 1 >= cap)
  2019. return -1;
  2020. out[o++] = '/';
  2021. }
  2022. if (o + n + 1 >= cap)
  2023. return -1;
  2024. {
  2025. unsigned int j;
  2026. for (j = 0; j < n; j++)
  2027. out[o++] = seg[j];
  2028. }
  2029. depth++;
  2030. }
  2031. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2032. if (o + 1 >= cap)
  2033. return -1;
  2034. out[o++] = '/';
  2035. }
  2036. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2037. if (in[i] == '?' || in[i] == '#') {
  2038. while (in[i]) {
  2039. if (o + 1 >= cap)
  2040. return -1;
  2041. out[o++] = in[i++];
  2042. }
  2043. }
  2044. out[o] = '\0';
  2045. return 0;
  2046. }
  2047. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2048. {
  2049. char joined[BR_URL_MAX];
  2050. if (!in || !in[0]) {
  2051. s_copy(out, cwd[0] ? cwd : "/", cap);
  2052. return;
  2053. }
  2054. if (in[0] == '/') {
  2055. if (normalize_abs(in, out, cap) != 0)
  2056. s_copy(out, in, cap);
  2057. return;
  2058. }
  2059. {
  2060. unsigned int n = 0;
  2061. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2062. s_append(joined, &n, "/", sizeof(joined));
  2063. s_append(joined, &n, in, sizeof(joined));
  2064. }
  2065. if (normalize_abs(joined, out, cap) != 0)
  2066. s_copy(out, joined, cap);
  2067. }
  2068. /* ---- canonical origin cache ---- *
  2069. *
  2070. * Sites commonly redirect http://host to https://host and then to
  2071. * https://www.host. Remember the final scheme/host of the last navigation so
  2072. * a bare domain typed again goes straight there instead of paying for two
  2073. * more connections and TLS handshakes. Only default-port requests are
  2074. * rewritten; explicit ports are left alone. */
  2075. #define ORIGIN_CACHE_MAX 8
  2076. #define ORIGIN_FILE "/share/borigins"
  2077. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2078. UHTTP_HOST_MAX + 2))
  2079. struct origin_cache_entry {
  2080. char host[UHTTP_HOST_MAX];
  2081. char origin[UHTTP_HOST_MAX + 16];
  2082. };
  2083. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2084. static int origin_count;
  2085. static char origin_buf[ORIGIN_BUF_SIZE];
  2086. static int default_port(const struct uhttp_url *u)
  2087. {
  2088. return u->secure ? u->port == 443 : u->port == 80;
  2089. }
  2090. static void url_origin(const struct uhttp_url *u, char *out,
  2091. unsigned int cap)
  2092. {
  2093. unsigned int n = 0;
  2094. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2095. s_append(out, &n, u->host, cap);
  2096. if (!default_port(u)) {
  2097. s_append(out, &n, ":", cap);
  2098. s_append_dec(out, &n, u->port, cap);
  2099. }
  2100. }
  2101. static void origin_cache_apply(char *url, unsigned int cap)
  2102. {
  2103. struct uhttp_url u;
  2104. char out[BR_URL_MAX];
  2105. unsigned int n = 0;
  2106. int i;
  2107. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2108. return;
  2109. for (i = 0; i < origin_count; i++) {
  2110. if (!s_eq(u.host, origins[i].host))
  2111. continue;
  2112. s_append(out, &n, origins[i].origin, sizeof(out));
  2113. s_append(out, &n, u.path, sizeof(out));
  2114. s_copy(url, out, cap);
  2115. return;
  2116. }
  2117. }
  2118. static void origin_cache_save(void)
  2119. {
  2120. unsigned int n = 0;
  2121. int i;
  2122. for (i = 0; i < origin_count; i++) {
  2123. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2124. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2125. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2126. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2127. }
  2128. if (n)
  2129. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2130. (int)origin_buf, (int)n);
  2131. }
  2132. static void origin_cache_load(void)
  2133. {
  2134. char *p;
  2135. int rn;
  2136. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2137. (int)(sizeof(origin_buf) - 1));
  2138. if (rn <= 0)
  2139. return;
  2140. origin_buf[rn] = '\0';
  2141. p = origin_buf;
  2142. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2143. char *line = p, *origin;
  2144. while (*p && *p != '\n')
  2145. p++;
  2146. if (*p)
  2147. *p++ = '\0';
  2148. if (!line[0])
  2149. continue;
  2150. origin = line;
  2151. while (*origin && *origin != ' ')
  2152. origin++;
  2153. if (!*origin)
  2154. continue;
  2155. *origin++ = '\0';
  2156. if (!line[0] || !is_http(origin))
  2157. continue;
  2158. {
  2159. struct uhttp_url uo;
  2160. if (uhttp_parse_url(origin, &uo) != 0 ||
  2161. !s_eq(uo.path, "/"))
  2162. continue;
  2163. }
  2164. s_copy(origins[origin_count].host, line,
  2165. sizeof(origins[origin_count].host));
  2166. s_copy(origins[origin_count].origin, origin,
  2167. sizeof(origins[origin_count].origin));
  2168. origin_count++;
  2169. }
  2170. }
  2171. static int host_is_www_of(const char *host, const char *base)
  2172. {
  2173. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2174. host[3] == '.' && s_eq(host + 4, base);
  2175. }
  2176. static void origin_cache_learn(const char *requested, const char *final)
  2177. {
  2178. struct uhttp_url from, to;
  2179. char origin[UHTTP_HOST_MAX + 16];
  2180. int i;
  2181. if (!is_http(requested) || !is_http(final))
  2182. return;
  2183. if (uhttp_parse_url(requested, &from) != 0 ||
  2184. uhttp_parse_url(final, &to) != 0)
  2185. return;
  2186. if (!default_port(&from))
  2187. return;
  2188. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2189. from.port == to.port)
  2190. return;
  2191. /* Only remember origin-level canonicalisation: the same path, and
  2192. * either the same host or its www./apex sibling. A path- or
  2193. * host-specific redirect (a shortener, a login page) must not poison
  2194. * every request to the typed host. */
  2195. if (!s_eq(from.path, to.path))
  2196. return;
  2197. if (!s_eq(from.host, to.host) &&
  2198. !host_is_www_of(to.host, from.host) &&
  2199. !host_is_www_of(from.host, to.host))
  2200. return;
  2201. url_origin(&to, origin, sizeof(origin));
  2202. for (i = 0; i < origin_count; i++) {
  2203. if (s_eq(origins[i].host, from.host)) {
  2204. if (!s_eq(origins[i].origin, origin)) {
  2205. s_copy(origins[i].origin, origin,
  2206. sizeof(origins[i].origin));
  2207. origin_cache_save();
  2208. }
  2209. return;
  2210. }
  2211. }
  2212. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2213. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2214. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2215. origin_cache_save();
  2216. }
  2217. static int path_dir(const char *path, char *out, unsigned int cap)
  2218. {
  2219. unsigned int i, last = 0;
  2220. for (i = 0; path[i]; i++)
  2221. if (path[i] == '/')
  2222. last = i;
  2223. if (last == 0) {
  2224. if (cap < 2)
  2225. return -1;
  2226. out[0] = '/';
  2227. out[1] = '\0';
  2228. return 0;
  2229. }
  2230. if (last + 1 >= cap)
  2231. return -1;
  2232. {
  2233. unsigned int j;
  2234. for (j = 0; j < last; j++)
  2235. out[j] = path[j];
  2236. out[last] = '\0';
  2237. }
  2238. return 0;
  2239. }
  2240. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2241. static int resolve_link(const char *base, const char *href, char *out,
  2242. unsigned int cap)
  2243. {
  2244. char joined[BR_URL_MAX];
  2245. if (!href || !href[0] || href[0] == '#')
  2246. return -1;
  2247. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2248. starts_with(href, "data:") || starts_with(href, "tel:"))
  2249. return -1;
  2250. if (starts_with(href, "about:")) {
  2251. s_copy(out, href, cap);
  2252. return 0;
  2253. }
  2254. if (is_http(href)) {
  2255. s_copy(out, href, cap);
  2256. return 0;
  2257. }
  2258. if (starts_with(href, "//")) {
  2259. if (is_http(base)) {
  2260. unsigned int n = 0;
  2261. s_append(out, &n, starts_with(base, "https:") ?
  2262. "https:" : "http:", cap);
  2263. s_append(out, &n, href, cap);
  2264. return 0;
  2265. }
  2266. return -1;
  2267. }
  2268. if (is_http(base)) {
  2269. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2270. }
  2271. /* local page */
  2272. if (href[0] == '/') {
  2273. if (normalize_abs(href, out, cap) != 0)
  2274. return -1;
  2275. return 0;
  2276. }
  2277. {
  2278. char dir[BR_URL_MAX];
  2279. unsigned int n = 0;
  2280. if (s_eq(base, "about:home"))
  2281. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2282. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2283. s_copy(dir, "/", sizeof(dir));
  2284. s_append(joined, &n, dir, sizeof(joined));
  2285. if (n == 0 || joined[n - 1] != '/')
  2286. s_append(joined, &n, "/", sizeof(joined));
  2287. s_append(joined, &n, href, sizeof(joined));
  2288. }
  2289. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2290. }
  2291. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2292. * rest instead of failing when a page or stylesheet is larger than the
  2293. * buffer. The stream is still walked to the end, so a normal page is
  2294. * verified; a truncated compressed input still returns whatever was decoded
  2295. * so far. */
  2296. struct trunc_buf {
  2297. unsigned char *dst;
  2298. unsigned int cap, pos;
  2299. int full;
  2300. };
  2301. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2302. {
  2303. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2304. if (len > m->cap - m->pos) {
  2305. unsigned int room = m->cap - m->pos;
  2306. if (room) {
  2307. unsigned int i;
  2308. for (i = 0; i < room; i++)
  2309. m->dst[m->pos + i] = data[i];
  2310. m->pos += room;
  2311. }
  2312. m->full = 1;
  2313. return 0;
  2314. }
  2315. {
  2316. unsigned int i;
  2317. for (i = 0; i < len; i++)
  2318. m->dst[m->pos + i] = data[i];
  2319. }
  2320. m->pos += len;
  2321. return 0;
  2322. }
  2323. static void worker_wait_ui(void);
  2324. static void inflate_ui_pump(void *ctx)
  2325. {
  2326. static unsigned int last;
  2327. unsigned int now = u_ticks_ms();
  2328. (void)ctx;
  2329. if ((int)(now - last) >= 50) {
  2330. last = now;
  2331. worker_wait_ui();
  2332. }
  2333. }
  2334. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2335. unsigned char *dst, unsigned int cap,
  2336. unsigned int *outlen, int gzip, int *truncated)
  2337. {
  2338. struct inflate_src in;
  2339. struct inflate_sink sink;
  2340. struct trunc_buf m;
  2341. unsigned int got = 0;
  2342. int r;
  2343. in.p = src;
  2344. in.len = len;
  2345. in.more = 0;
  2346. in.ctx = 0;
  2347. m.dst = dst;
  2348. m.cap = cap;
  2349. m.pos = 0;
  2350. m.full = 0;
  2351. sink.write = trunc_write;
  2352. sink.ctx = &m;
  2353. inflate_init(&image_inflate_ws, &in, &sink);
  2354. image_inflate_ws.progress = inflate_ui_pump;
  2355. image_inflate_ws.progress_ctx = 0;
  2356. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2357. inflate_zlib(&image_inflate_ws, &got);
  2358. *outlen = m.pos;
  2359. *truncated = m.full || r != 0;
  2360. if (r != 0 && m.pos == 0)
  2361. return -1;
  2362. return 0;
  2363. }
  2364. /* ---- headless fetch workers ------------------------------------------ *
  2365. *
  2366. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2367. * writes the raw response, a small metadata file and a done marker under
  2368. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2369. * or a multi-megabyte body never freezes the UI and images download in
  2370. * parallel.
  2371. */
  2372. struct fetch_meta {
  2373. int status;
  2374. int error;
  2375. int trunc;
  2376. unsigned int len;
  2377. unsigned int open_ms;
  2378. unsigned int first_ms;
  2379. unsigned int total_ms;
  2380. char encoding[16];
  2381. char ctype[64];
  2382. char final[BR_URL_MAX];
  2383. };
  2384. static void draw(unsigned int *action);
  2385. static void handle_keys(unsigned int *action);
  2386. static void handle_page_click(unsigned int *action);
  2387. #define FETCH_WORKERS 4
  2388. #define FETCH_PATH_MAX 32
  2389. /* One long-lived curl __serve helper per worker. Each worker has its own
  2390. * request/body/meta/done files under /share so several downloads can be in
  2391. * flight at once; the keep-alive connection stays in the helper process, so
  2392. * tls.c's per-process state remains valid. */
  2393. struct fetch_worker {
  2394. int pid;
  2395. int slot;
  2396. int busy;
  2397. int ready;
  2398. int image_job;
  2399. unsigned int seq;
  2400. unsigned int deadline;
  2401. int retried;
  2402. char req[FETCH_PATH_MAX];
  2403. char body[FETCH_PATH_MAX];
  2404. char meta[FETCH_PATH_MAX];
  2405. char done[FETCH_PATH_MAX];
  2406. char post[FETCH_PATH_MAX];
  2407. /* Optional preload job attached to this worker. */
  2408. unsigned int node;
  2409. int bg;
  2410. char url[BR_URL_MAX];
  2411. struct fetch_meta m;
  2412. };
  2413. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2414. static int fetch_tty = -2;
  2415. static void fetch_tty_drain(void);
  2416. static unsigned int fetch_session;
  2417. static unsigned int fetch_seq;
  2418. static struct fetch_meta fetch_meta;
  2419. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2420. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2421. static int fetch_last_error;
  2422. static unsigned int meta_uint(char **pp)
  2423. {
  2424. char *p = *pp;
  2425. unsigned int v = 0;
  2426. while (*p >= '0' && *p <= '9') {
  2427. v = v * 10 + (unsigned int)(*p - '0');
  2428. p++;
  2429. }
  2430. while (*p && *p != '\n')
  2431. p++;
  2432. if (*p == '\n')
  2433. p++;
  2434. *pp = p;
  2435. return v;
  2436. }
  2437. static void meta_str(char **pp, char *out, unsigned int cap)
  2438. {
  2439. char *p = *pp;
  2440. unsigned int n = 0;
  2441. while (*p && *p != '\n' && n + 1 < cap)
  2442. out[n++] = *p++;
  2443. out[n] = '\0';
  2444. while (*p && *p != '\n')
  2445. p++;
  2446. if (*p == '\n')
  2447. p++;
  2448. *pp = p;
  2449. }
  2450. static void worker_wait_ui(void)
  2451. {
  2452. unsigned int action = 0;
  2453. if (!ngui_begin(&ui))
  2454. return;
  2455. draw(&action);
  2456. handle_keys(&action);
  2457. handle_page_click(&action);
  2458. if (action & ACT_WAIT_NAV) {
  2459. pending_action |= action & ACT_WAIT_NAV;
  2460. if ((action & ACT_NAV) && click_url[0])
  2461. s_copy(pending_url, click_url, sizeof(pending_url));
  2462. click_url[0] = '\0';
  2463. cancel_fetch = 1;
  2464. }
  2465. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  2466. ngui_invalidate(&ui);
  2467. ngui_end(&ui);
  2468. }
  2469. static void fetch_path(char *out, unsigned int cap, const char *kind,
  2470. unsigned int session, int slot)
  2471. {
  2472. unsigned int n = 0;
  2473. s_append(out, &n, "/share/bf", cap);
  2474. s_append_dec(out, &n, session, cap);
  2475. s_append(out, &n, "_", cap);
  2476. s_append_dec(out, &n, (unsigned int)slot, cap);
  2477. s_append(out, &n, kind, cap);
  2478. }
  2479. static void fetch_pool_init(void)
  2480. {
  2481. static int ready;
  2482. int i;
  2483. if (ready)
  2484. return;
  2485. ready = 1;
  2486. fetch_session = ((unsigned int)u_getpid() << 16) ^
  2487. (u_ticks_ms() & 0xFFFFu);
  2488. if (!fetch_session)
  2489. fetch_session = 1;
  2490. for (i = 0; i < FETCH_WORKERS; i++) {
  2491. struct fetch_worker *w = &fetch_workers[i];
  2492. w->pid = -1;
  2493. w->slot = i;
  2494. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  2495. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  2496. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  2497. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  2498. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  2499. }
  2500. }
  2501. static void fetch_worker_stop(struct fetch_worker *w)
  2502. {
  2503. int i;
  2504. /* An abandoned image job leaves its node loadable again. */
  2505. if (w->busy && w->image_job && w->node < doc.nnode) {
  2506. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  2507. doc.nodes[w->node].bg_img_index = -1;
  2508. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  2509. doc.nodes[w->node].img_index = -1;
  2510. }
  2511. if (w->pid > 0) {
  2512. u_kill((unsigned int)w->pid);
  2513. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  2514. u_sleep_ms(5);
  2515. /* Let the reaper close the socket before we reuse the slot. */
  2516. u_sleep_ms(10);
  2517. }
  2518. w->pid = -1;
  2519. w->busy = 0;
  2520. w->ready = 0;
  2521. w->image_job = 0;
  2522. if (w->req[0]) {
  2523. u_syscall1(SYS_UNLINK, (int)w->done);
  2524. u_syscall1(SYS_UNLINK, (int)w->meta);
  2525. u_syscall1(SYS_UNLINK, (int)w->body);
  2526. u_syscall1(SYS_UNLINK, (int)w->post);
  2527. u_syscall1(SYS_UNLINK, (int)w->req);
  2528. }
  2529. }
  2530. static void fetch_workers_stop_all(void)
  2531. {
  2532. int i;
  2533. for (i = 0; i < FETCH_WORKERS; i++)
  2534. fetch_worker_stop(&fetch_workers[i]);
  2535. }
  2536. /* Abandon the transfers of the current page but keep idle helpers and their
  2537. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  2538. * because its response would otherwise land in a reused /share slot. */
  2539. static void fetch_workers_cancel_busy(void)
  2540. {
  2541. int i;
  2542. for (i = 0; i < FETCH_WORKERS; i++)
  2543. if (fetch_workers[i].busy)
  2544. fetch_worker_stop(&fetch_workers[i]);
  2545. }
  2546. static void fetch_workers_prepare_nav(const char *url)
  2547. {
  2548. int i;
  2549. (void)url;
  2550. for (i = 0; i < FETCH_WORKERS; i++) {
  2551. struct fetch_worker *w = &fetch_workers[i];
  2552. if (w->pid <= 0)
  2553. continue;
  2554. /* Only an in-flight transfer must be aborted. Idle helpers
  2555. * stay warm across origins: there are just FETCH_WORKERS of
  2556. * them, and uhttp_open drops the old connection when the
  2557. * next job is for another host. Killing and respawning all
  2558. * four on every navigation churned processes and sockets
  2559. * while images were still loading. */
  2560. if (w->busy)
  2561. fetch_worker_stop(w);
  2562. }
  2563. }
  2564. /* The browser is no longer the active window and no fetch is running: give
  2565. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  2566. static void fetch_workers_stop_if_unfocused(void)
  2567. {
  2568. int i;
  2569. fetch_tty_drain();
  2570. if (ui.focused || page_loading || preload_active)
  2571. return;
  2572. for (i = 0; i < FETCH_WORKERS; i++)
  2573. if (fetch_workers[i].pid > 0) {
  2574. fetch_workers_stop_all();
  2575. return;
  2576. }
  2577. }
  2578. /* The helpers (and this process, since u_tty_create() rebinds our own
  2579. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  2580. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  2581. * a dozen TLS connections every helper hung in its next log line, so the
  2582. * following cross-origin navigation sat at "Loading..." until it timed out.
  2583. * Drain and discard it from every wait/poll loop. */
  2584. static void fetch_tty_drain(void)
  2585. {
  2586. char sink[512];
  2587. int i;
  2588. if (fetch_tty <= 0)
  2589. return;
  2590. for (i = 0; i < 16; i++)
  2591. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  2592. break;
  2593. }
  2594. static int fetch_worker_start(struct fetch_worker *w, char *err,
  2595. unsigned int errcap)
  2596. {
  2597. char arg[40];
  2598. unsigned int n = 0;
  2599. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  2600. return 0;
  2601. w->pid = -1;
  2602. fetch_pool_init();
  2603. if (fetch_tty == -2) {
  2604. int t = u_tty_create();
  2605. fetch_tty = t > 0 ? t : 0;
  2606. }
  2607. s_append(arg, &n, "__serve ", sizeof(arg));
  2608. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  2609. s_append(arg, &n, " ", sizeof(arg));
  2610. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  2611. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  2612. if (w->pid <= 0) {
  2613. w->pid = -1;
  2614. s_copy(err, "cannot start network helper", errcap);
  2615. return -1;
  2616. }
  2617. return 0;
  2618. }
  2619. static struct fetch_worker *fetch_worker_alloc(void)
  2620. {
  2621. int i;
  2622. fetch_pool_init();
  2623. for (i = 0; i < FETCH_WORKERS; i++)
  2624. if (!fetch_workers[i].busy)
  2625. return &fetch_workers[i];
  2626. return 0;
  2627. }
  2628. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  2629. unsigned int cap, const char *method,
  2630. const char *ctype, const char *post,
  2631. unsigned int post_len, unsigned int node,
  2632. int bg, char *err, unsigned int errcap);
  2633. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  2634. unsigned int cap, const char *post,
  2635. unsigned int post_len, unsigned int node,
  2636. int bg, char *err, unsigned int errcap)
  2637. {
  2638. /* A body pointer with no bytes is still a POST: the classic request
  2639. * line would turn it into a GET. */
  2640. if (post && !post_len)
  2641. return fetch_worker_submit_req(w, url, cap, "POST",
  2642. "application/x-www-form-urlencoded", post, 0, node,
  2643. bg, err, errcap);
  2644. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  2645. node, bg, err, errcap);
  2646. }
  2647. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  2648. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  2649. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  2650. unsigned int cap, const char *method,
  2651. const char *ctype, const char *post,
  2652. unsigned int post_len, unsigned int node,
  2653. int bg, char *err, unsigned int errcap)
  2654. {
  2655. static char req[1024];
  2656. unsigned int n = 0;
  2657. fetch_seq++;
  2658. if (!fetch_seq)
  2659. fetch_seq = 1;
  2660. w->seq = fetch_seq;
  2661. w->ready = 0;
  2662. w->image_job = 0;
  2663. w->retried = 0;
  2664. w->m.error = 0;
  2665. w->node = node;
  2666. w->bg = bg;
  2667. s_copy(w->url, url, sizeof(w->url));
  2668. s_append_dec(req, &n, w->seq, sizeof(req));
  2669. s_append(req, &n, " ", sizeof(req));
  2670. s_append_dec(req, &n, cap, sizeof(req));
  2671. s_append(req, &n, " ", sizeof(req));
  2672. if (method) {
  2673. unsigned int k;
  2674. s_append(req, &n, "X ", sizeof(req));
  2675. s_append(req, &n, method, sizeof(req));
  2676. s_append(req, &n, " ", sizeof(req));
  2677. s_append_dec(req, &n, post_len, sizeof(req));
  2678. s_append(req, &n, " ", sizeof(req));
  2679. if (!ctype || !ctype[0])
  2680. s_append(req, &n, "-", sizeof(req));
  2681. /* One token on the request line: drop the spaces
  2682. * ("application/json; charset=utf-8" stays valid). */
  2683. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  2684. if (ctype[k] != ' ')
  2685. req[n++] = ctype[k];
  2686. req[n] = '\0';
  2687. s_append(req, &n, " ", sizeof(req));
  2688. } else if (post_len) {
  2689. s_append(req, &n, "POST ", sizeof(req));
  2690. s_append_dec(req, &n, post_len, sizeof(req));
  2691. s_append(req, &n, " ", sizeof(req));
  2692. }
  2693. s_append(req, &n, url, sizeof(req));
  2694. s_append(req, &n, "\n", sizeof(req));
  2695. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  2696. (int)post, (int)post_len) < 0) {
  2697. s_copy(err, "cannot queue form body", errcap);
  2698. return -1;
  2699. }
  2700. u_syscall1(SYS_UNLINK, (int)w->done);
  2701. u_syscall1(SYS_UNLINK, (int)w->meta);
  2702. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  2703. s_copy(err, "cannot queue network request", errcap);
  2704. return -1;
  2705. }
  2706. if (fetch_worker_start(w, err, errcap) != 0)
  2707. return -1;
  2708. w->busy = 1;
  2709. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  2710. return 0;
  2711. }
  2712. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  2713. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  2714. unsigned int errcap)
  2715. {
  2716. static char meta[1024];
  2717. char *p;
  2718. int rn, mseq;
  2719. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  2720. (int)(sizeof(meta) - 1));
  2721. if (rn <= 0) {
  2722. s_copy(err, "network helper failed", errcap);
  2723. return -1;
  2724. }
  2725. meta[rn] = '\0';
  2726. p = meta;
  2727. mseq = (int)meta_uint(&p);
  2728. if (mseq != (int)w->seq) {
  2729. s_copy(err, "stale network response", errcap);
  2730. return -1;
  2731. }
  2732. w->m.status = (int)meta_uint(&p);
  2733. w->m.error = (int)meta_uint(&p);
  2734. w->m.trunc = (int)meta_uint(&p);
  2735. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  2736. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  2737. meta_str(&p, w->m.final, sizeof(w->m.final));
  2738. w->m.len = meta_uint(&p);
  2739. w->m.open_ms = 0;
  2740. w->m.first_ms = 0;
  2741. w->m.total_ms = 0;
  2742. if (*p) {
  2743. w->m.open_ms = meta_uint(&p);
  2744. w->m.first_ms = meta_uint(&p);
  2745. w->m.total_ms = meta_uint(&p);
  2746. }
  2747. if (w->m.error) {
  2748. s_copy(err, uhttp_error_string(w->m.error), errcap);
  2749. return -1;
  2750. }
  2751. w->ready = 1;
  2752. return 0;
  2753. }
  2754. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  2755. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  2756. unsigned int errcap)
  2757. {
  2758. static char done[24];
  2759. char *p;
  2760. int rn, mseq;
  2761. fetch_tty_drain();
  2762. if (!w->busy)
  2763. return -1;
  2764. if (w->ready)
  2765. return 1;
  2766. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  2767. (int)(sizeof(done) - 1));
  2768. if (rn > 0) {
  2769. done[rn] = '\0';
  2770. p = done;
  2771. mseq = (int)meta_uint(&p);
  2772. if (mseq == (int)w->seq) {
  2773. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  2774. fetch_worker_stop(w);
  2775. return -1;
  2776. }
  2777. return 1;
  2778. }
  2779. }
  2780. if (!u_alive((unsigned int)w->pid)) {
  2781. w->pid = -1;
  2782. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  2783. w->retried = 1;
  2784. return 0;
  2785. }
  2786. s_copy(err, "network helper stopped", errcap);
  2787. fetch_worker_stop(w);
  2788. return -1;
  2789. }
  2790. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  2791. s_copy(err, "network request timed out", errcap);
  2792. fetch_worker_stop(w);
  2793. return -1;
  2794. }
  2795. return 0;
  2796. }
  2797. /* Copy the completed body, inflating it if the server ignored our identity
  2798. * request. Mirrors the old fetch_remote body path. */
  2799. static int fetch_worker_read_body(struct fetch_worker *w,
  2800. unsigned char *plain,
  2801. unsigned int plaincap,
  2802. unsigned char *comp,
  2803. unsigned int compcap,
  2804. int *truncated, char *err,
  2805. unsigned int errcap)
  2806. {
  2807. int rv, zr, was_trunc;
  2808. if (contains_ci(w->m.encoding, "gzip") ||
  2809. contains_ci(w->m.encoding, "deflate")) {
  2810. unsigned int comp_len = 0, plen = 0;
  2811. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  2812. (int)compcap);
  2813. if (rv < 0) {
  2814. s_copy(err, "empty response", errcap);
  2815. return -1;
  2816. }
  2817. comp_len = (unsigned int)rv;
  2818. if (comp_len < w->m.len) {
  2819. s_copy(err, "compressed response is too large", errcap);
  2820. return -1;
  2821. }
  2822. if (contains_ci(w->m.encoding, "deflate"))
  2823. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2824. &plen, 0, &was_trunc);
  2825. else
  2826. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2827. &plen, 1, &was_trunc);
  2828. if (zr != 0) {
  2829. s_copy(err, "compressed response is corrupt", errcap);
  2830. return -1;
  2831. }
  2832. *truncated = w->m.trunc || was_trunc;
  2833. return (int)plen;
  2834. }
  2835. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  2836. if (rv < 0) {
  2837. s_copy(err, "empty response", errcap);
  2838. return -1;
  2839. }
  2840. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  2841. return rv;
  2842. }
  2843. static void fetch_worker_release(struct fetch_worker *w)
  2844. {
  2845. u_syscall1(SYS_UNLINK, (int)w->done);
  2846. u_syscall1(SYS_UNLINK, (int)w->meta);
  2847. u_syscall1(SYS_UNLINK, (int)w->body);
  2848. u_syscall1(SYS_UNLINK, (int)w->post);
  2849. u_syscall1(SYS_UNLINK, (int)w->req);
  2850. w->busy = 0;
  2851. w->ready = 0;
  2852. w->image_job = 0;
  2853. }
  2854. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  2855. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  2856. unsigned int errcap)
  2857. {
  2858. for (;;) {
  2859. int rv;
  2860. if (!fetch_wait_passive)
  2861. worker_wait_ui();
  2862. if (cancel_fetch || pending_action) {
  2863. fetch_workers_cancel_busy();
  2864. return FETCH_ABORT;
  2865. }
  2866. rv = fetch_worker_poll(w, err, errcap);
  2867. if (rv != 0)
  2868. return rv == 1 ? 0 : -1;
  2869. u_sleep_ms(10);
  2870. }
  2871. }
  2872. static int fetch_remote(const char *url, unsigned int cap,
  2873. const char *post, unsigned int post_len,
  2874. unsigned char *plain, unsigned int plaincap,
  2875. unsigned char *comp, unsigned int compcap,
  2876. struct fetch_meta *m, int *truncated,
  2877. char *err, unsigned int errcap)
  2878. {
  2879. struct fetch_worker *w = fetch_worker_alloc();
  2880. int rv;
  2881. fetch_last_error = 0;
  2882. if (!w) {
  2883. s_copy(err, "network busy", errcap);
  2884. return -1;
  2885. }
  2886. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  2887. err, errcap) != 0) {
  2888. fetch_worker_release(w);
  2889. return -1;
  2890. }
  2891. rv = fetch_worker_wait(w, err, errcap);
  2892. if (rv == FETCH_ABORT) {
  2893. fetch_worker_release(w);
  2894. return FETCH_ABORT;
  2895. }
  2896. if (rv != 0) {
  2897. fetch_last_error = w->m.error;
  2898. fetch_worker_release(w);
  2899. return -1;
  2900. }
  2901. *m = w->m;
  2902. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  2903. truncated, err, errcap);
  2904. fetch_worker_release(w);
  2905. if (rv >= 0 && (cancel_fetch || pending_action))
  2906. return FETCH_ABORT;
  2907. return rv;
  2908. }
  2909. static int fetch_worker_status(const struct fetch_worker *w)
  2910. {
  2911. return w->m.status;
  2912. }
  2913. /* fetch()/XHR through a helper: one request, the status and body come back
  2914. * whatever the HTTP status (a 401 is an answer, not a network error). */
  2915. static int js_worker_http(const char *method, const char *url,
  2916. const char *ctype, const char *body,
  2917. unsigned int body_len, struct js_http_resp *r,
  2918. char *err, int errcap)
  2919. {
  2920. struct fetch_worker *w = fetch_worker_alloc();
  2921. unsigned char *plain;
  2922. int rv, tr = 0;
  2923. if (!w) {
  2924. s_copy(err, "network busy", (unsigned int)errcap);
  2925. return -1;
  2926. }
  2927. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  2928. body_len, 0, 0, err,
  2929. (unsigned int)errcap) != 0) {
  2930. fetch_worker_release(w);
  2931. return -1;
  2932. }
  2933. fetch_wait_passive++;
  2934. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  2935. fetch_wait_passive--;
  2936. if (rv != 0) {
  2937. if (rv == FETCH_ABORT)
  2938. s_copy(err, "page is navigating", (unsigned int)errcap);
  2939. fetch_worker_release(w);
  2940. return -1;
  2941. }
  2942. r->status = w->m.status;
  2943. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  2944. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  2945. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  2946. if (!plain) {
  2947. fetch_worker_release(w);
  2948. s_copy(err, "out of memory", (unsigned int)errcap);
  2949. return -1;
  2950. }
  2951. if (w->m.len == 0) {
  2952. rv = 0; /* 204, an empty 200: no body file */
  2953. } else {
  2954. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  2955. image_io_buf, BR_PAGE_COMP_MAX,
  2956. &tr, err, (unsigned int)errcap);
  2957. }
  2958. fetch_worker_release(w);
  2959. if (rv < 0) {
  2960. free(plain);
  2961. return -1;
  2962. }
  2963. plain[rv] = '\0';
  2964. r->body = (char *)plain;
  2965. r->len = (unsigned int)rv;
  2966. return 0;
  2967. }
  2968. /* ---- HTTP / file fetch ---- */
  2969. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  2970. unsigned int *outlen, int *is_local, char *ctype,
  2971. unsigned int ctcap, char *final, unsigned int finalcap,
  2972. char *err, unsigned int errcap, int *truncated,
  2973. const char *post, unsigned int post_len)
  2974. {
  2975. unsigned char *buf;
  2976. unsigned int len;
  2977. int tr = 0;
  2978. int rv;
  2979. *out = 0;
  2980. *outlen = 0;
  2981. *truncated = 0;
  2982. if (final && finalcap)
  2983. final[0] = '\0';
  2984. if (ctype && ctcap)
  2985. ctype[0] = '\0';
  2986. if (url[0] == '/') {
  2987. char pathbuf[BR_URL_MAX];
  2988. const char *open_url = url;
  2989. unsigned int i = 0;
  2990. /* A local form GET keeps ?query in the address bar but the
  2991. * file lookup uses the path alone, like a real browser. */
  2992. while (url[i] && url[i] != '?' && url[i] != '#')
  2993. i++;
  2994. if (url[i]) {
  2995. s_copy(pathbuf, url, i + 1);
  2996. open_url = pathbuf;
  2997. }
  2998. buf = (unsigned char *)malloc(cap);
  2999. if (!buf) {
  3000. s_copy(err, "out of memory", errcap);
  3001. return -1;
  3002. }
  3003. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  3004. if (rv < 0) {
  3005. free(buf);
  3006. s_copy(err, "file not found", errcap);
  3007. return -1;
  3008. }
  3009. *out = buf;
  3010. *outlen = (unsigned int)rv;
  3011. *is_local = 1;
  3012. if (ctype)
  3013. s_copy(ctype, "text/html", ctcap);
  3014. if (final)
  3015. s_copy(final, url, finalcap);
  3016. if ((unsigned int)rv == cap)
  3017. *truncated = 1;
  3018. return 0;
  3019. }
  3020. buf = (unsigned char *)malloc(cap);
  3021. if (!buf) {
  3022. s_copy(err, "out of memory", errcap);
  3023. return -1;
  3024. }
  3025. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3026. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3027. if (rv == FETCH_ABORT) {
  3028. free(buf);
  3029. return FETCH_ABORT;
  3030. }
  3031. if (rv < 0) {
  3032. free(buf);
  3033. return -1;
  3034. }
  3035. len = (unsigned int)rv;
  3036. if (len == 0) {
  3037. free(buf);
  3038. s_copy(err, "empty response", errcap);
  3039. return -1;
  3040. }
  3041. if (ctype)
  3042. s_copy(ctype, fetch_meta.ctype, ctcap);
  3043. if (final && fetch_meta.final[0])
  3044. s_copy(final, fetch_meta.final, finalcap);
  3045. *is_local = 0;
  3046. *out = buf;
  3047. *outlen = len;
  3048. *truncated = tr;
  3049. return 0;
  3050. }
  3051. /* Load every @font-face the parser registered. Local files go through
  3052. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  3053. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  3054. * to the built-in regular/bold/italic/mono set. */
  3055. static void load_font_faces(void)
  3056. {
  3057. unsigned int i;
  3058. memset(font_faces, 0, sizeof(font_faces));
  3059. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  3060. i <= BR_MAX_FACES; i++) {
  3061. const char *url = br_font_face_url((int)i);
  3062. const char *base = br_font_face_base((int)i);
  3063. char abs[BR_URL_MAX];
  3064. if (!url || !url[0])
  3065. continue;
  3066. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  3067. sizeof(abs)) != 0)
  3068. continue;
  3069. if (abs[0] == '/') {
  3070. font_faces[i - 1] = ufont_face_open_path(abs);
  3071. } else if (is_http(abs)) {
  3072. unsigned char *buf;
  3073. char err[64];
  3074. int rv, tr = 0;
  3075. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  3076. if (!buf)
  3077. continue;
  3078. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3079. UFONT_MAX_FILE, image_io_buf,
  3080. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  3081. err, sizeof(err));
  3082. if (rv > 0)
  3083. font_faces[i - 1] = ufont_face_open_mem(buf,
  3084. rv);
  3085. free(buf);
  3086. }
  3087. }
  3088. }
  3089. /* Remote scripts are cached under /share for the current boot, like the
  3090. * stylesheet cache, so reloads and later visits skip the network. */
  3091. static int script_cache_count;
  3092. static unsigned int script_cache_hash(const char *s)
  3093. {
  3094. unsigned int h = 2166136261u;
  3095. while (*s) {
  3096. h ^= (unsigned char)*s++;
  3097. h *= 16777619u;
  3098. }
  3099. return h;
  3100. }
  3101. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3102. {
  3103. unsigned int n = 0;
  3104. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3105. s_append_dec(out, &n, script_cache_hash(url), cap);
  3106. }
  3107. static void script_cache_clear(void)
  3108. {
  3109. struct sys_dirent d;
  3110. char path[96];
  3111. for (;;) {
  3112. int i, found = 0;
  3113. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3114. (int)&d) == 1; i++) {
  3115. unsigned int n = 0;
  3116. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3117. continue;
  3118. s_append(path, &n, "/share/", sizeof(path));
  3119. s_append(path, &n, d.name, sizeof(path));
  3120. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3121. return;
  3122. found = 1;
  3123. break;
  3124. }
  3125. if (!found)
  3126. break;
  3127. }
  3128. script_cache_count = 0;
  3129. }
  3130. static void script_cache_init(void)
  3131. {
  3132. struct sys_dirent d;
  3133. int i, count = 0;
  3134. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3135. (int)&d) == 1; i++)
  3136. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3137. count++;
  3138. if (count >= SCRIPT_CACHE_MAX) {
  3139. script_cache_clear();
  3140. return;
  3141. }
  3142. script_cache_count = count;
  3143. }
  3144. static int script_cache_get(const char *url, unsigned char **out,
  3145. unsigned int *outlen)
  3146. {
  3147. char path[96];
  3148. struct sys_stat st;
  3149. unsigned char *buf;
  3150. int rn;
  3151. script_cache_path(url, path, sizeof(path));
  3152. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3153. st.size >= SCRIPT_CACHE_FILE_MAX)
  3154. return 0;
  3155. buf = (unsigned char *)malloc(st.size + 1);
  3156. if (!buf)
  3157. return 0;
  3158. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3159. if (rn != (int)st.size) {
  3160. free(buf);
  3161. return 0;
  3162. }
  3163. buf[st.size] = '\0';
  3164. *out = buf;
  3165. *outlen = st.size;
  3166. return 1;
  3167. }
  3168. static void script_cache_put(const char *url, const unsigned char *data,
  3169. unsigned int len)
  3170. {
  3171. char path[96];
  3172. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3173. len >= SCRIPT_CACHE_FILE_MAX)
  3174. return;
  3175. script_cache_path(url, path, sizeof(path));
  3176. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3177. (int)len) >= 0)
  3178. script_cache_count++;
  3179. }
  3180. static int script_cache_has(const char *url)
  3181. {
  3182. char path[96];
  3183. struct sys_stat st;
  3184. script_cache_path(url, path, sizeof(path));
  3185. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3186. st.size < SCRIPT_CACHE_FILE_MAX;
  3187. }
  3188. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3189. static int fetch_script_text(const char *url, unsigned char **out,
  3190. unsigned int *outlen, char *err,
  3191. unsigned int errcap)
  3192. {
  3193. unsigned char *buf;
  3194. unsigned int len;
  3195. int local, truncated = 0;
  3196. char ctype[64], final[BR_URL_MAX];
  3197. int rv;
  3198. *out = 0;
  3199. *outlen = 0;
  3200. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3201. return 0;
  3202. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3203. sizeof(ctype), final, sizeof(final), err, errcap,
  3204. &truncated, 0, 0);
  3205. if (rv != 0)
  3206. return rv;
  3207. if (truncated || len >= BR_SCRIPT_MAX) {
  3208. free(buf);
  3209. s_copy(err, "script is too large", errcap);
  3210. return -1;
  3211. }
  3212. buf[len] = '\0';
  3213. if (!local)
  3214. script_cache_put(url, buf, len);
  3215. *out = buf;
  3216. *outlen = len;
  3217. return 0;
  3218. }
  3219. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  3220. * the heap, so images must not allocate their file body from it as well. */
  3221. static int fetch_image(const char *url, unsigned int cap,
  3222. unsigned char **out, unsigned int *outlen,
  3223. char *err, unsigned int errcap)
  3224. {
  3225. unsigned int len;
  3226. int tr = 0;
  3227. int rv;
  3228. *out = 0;
  3229. *outlen = 0;
  3230. if (cap > BR_IMG_FILE_MAX)
  3231. cap = BR_IMG_FILE_MAX;
  3232. if (url[0] == '/') {
  3233. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  3234. (int)cap);
  3235. if (rv < 0) {
  3236. s_copy(err, "file not found", errcap);
  3237. return -1;
  3238. }
  3239. *out = image_file_buf;
  3240. *outlen = (unsigned int)rv;
  3241. return 0;
  3242. }
  3243. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  3244. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  3245. if (rv == FETCH_ABORT)
  3246. return FETCH_ABORT;
  3247. if (rv < 0)
  3248. return -1;
  3249. len = (unsigned int)rv;
  3250. if (len == 0) {
  3251. s_copy(err, "empty image", errcap);
  3252. return -1;
  3253. }
  3254. *out = image_file_buf;
  3255. *outlen = len;
  3256. return 0;
  3257. }
  3258. /* Remote stylesheets are immutable enough for the current boot: keep
  3259. * successful responses under /share so a reload, a second visit or a fresh
  3260. * browser launch does not fetch the same five sheets over the network again.
  3261. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  3262. static int css_cache_count;
  3263. static unsigned int css_cache_hash(const char *s)
  3264. {
  3265. unsigned int h = 2166136261u;
  3266. while (*s) {
  3267. h ^= (unsigned char)*s++;
  3268. h *= 16777619u;
  3269. }
  3270. return h;
  3271. }
  3272. static void css_cache_path(const char *url, char *out, unsigned int cap)
  3273. {
  3274. unsigned int n = 0;
  3275. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  3276. s_append_dec(out, &n, css_cache_hash(url), cap);
  3277. }
  3278. static void css_cache_clear(void)
  3279. {
  3280. struct sys_dirent d;
  3281. char path[96];
  3282. for (;;) {
  3283. int i, found = 0;
  3284. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3285. (int)&d) == 1; i++) {
  3286. unsigned int n = 0;
  3287. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  3288. continue;
  3289. s_append(path, &n, "/share/", sizeof(path));
  3290. s_append(path, &n, d.name, sizeof(path));
  3291. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3292. return;
  3293. found = 1;
  3294. break;
  3295. }
  3296. if (!found)
  3297. break;
  3298. }
  3299. css_cache_count = 0;
  3300. }
  3301. static void css_cache_init(void)
  3302. {
  3303. struct sys_dirent d;
  3304. int i, count = 0;
  3305. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3306. (int)&d) == 1; i++)
  3307. if (starts_with(d.name, CSS_CACHE_PREFIX))
  3308. count++;
  3309. if (count >= CSS_CACHE_MAX) {
  3310. css_cache_clear();
  3311. return;
  3312. }
  3313. css_cache_count = count;
  3314. }
  3315. static int css_cache_get(const char *url, unsigned char **out,
  3316. unsigned int *outlen)
  3317. {
  3318. char path[96];
  3319. int rn;
  3320. css_cache_path(url, path, sizeof(path));
  3321. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  3322. (int)CSS_CACHE_FILE_MAX);
  3323. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  3324. return 0;
  3325. *out = image_io_buf;
  3326. *outlen = (unsigned int)rn;
  3327. return 1;
  3328. }
  3329. static void css_cache_put(const char *url, const unsigned char *data,
  3330. unsigned int len)
  3331. {
  3332. char path[96];
  3333. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  3334. len >= CSS_CACHE_FILE_MAX)
  3335. return;
  3336. css_cache_path(url, path, sizeof(path));
  3337. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3338. (int)len) >= 0)
  3339. css_cache_count++;
  3340. }
  3341. static int css_cache_has(const char *url)
  3342. {
  3343. char path[96];
  3344. struct sys_stat st;
  3345. css_cache_path(url, path, sizeof(path));
  3346. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3347. st.size < CSS_CACHE_FILE_MAX;
  3348. }
  3349. /* Read one stylesheet into the shared static buffer. CSS is parsed
  3350. * immediately, so it does not need the page heap; this leaves the heap for
  3351. * the 2 MB page body, the rules and the scaled image bitmaps. */
  3352. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  3353. char *err, unsigned int errcap)
  3354. {
  3355. unsigned int len;
  3356. int tr = 0;
  3357. int rv;
  3358. *out = 0;
  3359. *outlen = 0;
  3360. if (url[0] == '/') {
  3361. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  3362. (int)BR_CSS_MAX);
  3363. if (rv < 0) {
  3364. s_copy(err, "stylesheet not found", errcap);
  3365. return -1;
  3366. }
  3367. *out = image_io_buf;
  3368. *outlen = (unsigned int)rv;
  3369. return 0;
  3370. }
  3371. if (css_cache_get(url, out, outlen))
  3372. return 0;
  3373. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  3374. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  3375. &fetch_meta, &tr, err, errcap);
  3376. if (rv == FETCH_ABORT)
  3377. return FETCH_ABORT;
  3378. if (rv < 0)
  3379. return -1;
  3380. len = (unsigned int)rv;
  3381. if (len == 0) {
  3382. s_copy(err, "empty stylesheet", errcap);
  3383. return -1;
  3384. }
  3385. *out = image_io_buf;
  3386. *outlen = len;
  3387. css_cache_put(url, image_io_buf, len);
  3388. return 0;
  3389. }
  3390. static void redraw_now(void);
  3391. static char error_page[1024];
  3392. static void show_error(const char *title, const char *detail)
  3393. {
  3394. char *page = error_page;
  3395. unsigned int n = 0;
  3396. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  3397. s_append(page, &n, title, sizeof(error_page));
  3398. s_append(page, &n, "</h2><p>", sizeof(error_page));
  3399. {
  3400. const char *p = detail;
  3401. while (*p && n + 1 < sizeof(error_page)) {
  3402. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  3403. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  3404. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  3405. else page[n++] = *p;
  3406. p++;
  3407. }
  3408. }
  3409. page[n] = '\0';
  3410. s_append(page, &n, "</p><p>", sizeof(error_page));
  3411. s_append(page, &n, page_url, sizeof(error_page));
  3412. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  3413. sizeof(error_page));
  3414. br_parse(&doc, page, n);
  3415. layout_valid = 0;
  3416. preload_active = 0;
  3417. preload_pending = 0;
  3418. preload_wait = 0;
  3419. fetch_workers_cancel_busy();
  3420. s_copy(page_title, title, sizeof(page_title));
  3421. page_loading = 0;
  3422. set_status(title, 1, 0);
  3423. ngui_invalidate(&ui);
  3424. }
  3425. static int decode_direct_image(const unsigned char *data, unsigned int len,
  3426. unsigned int node)
  3427. {
  3428. if (image_count >= BR_MAX_IMAGES)
  3429. return -1;
  3430. if (decode_image_data(data, len, &images[0], 0, 0) != 0)
  3431. return -1;
  3432. doc.nodes[node].img_index = 0;
  3433. image_count = 1;
  3434. return 0;
  3435. }
  3436. static int ancestor_is(unsigned int node, unsigned int tag)
  3437. {
  3438. unsigned int p = doc.nodes[node].parent;
  3439. while (p) {
  3440. if (doc.nodes[p].tag == tag)
  3441. return 1;
  3442. p = doc.nodes[p].parent;
  3443. }
  3444. return 0;
  3445. }
  3446. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  3447. * parallel but parsed in document order, so the cascade is unchanged. */
  3448. static int load_stylesheets(void)
  3449. {
  3450. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  3451. static unsigned char remote[BR_MAX_SHEETS];
  3452. struct fetch_worker *slot[BR_MAX_SHEETS];
  3453. unsigned int i, n = 0, next = 0, k;
  3454. char err[64];
  3455. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  3456. struct br_node *nd = &doc.nodes[i];
  3457. const char *rel, *href;
  3458. char url[BR_URL_MAX];
  3459. int dup = 0;
  3460. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  3461. continue;
  3462. rel = br_rel(&doc, i);
  3463. if (!contains_ci(rel, "stylesheet"))
  3464. continue;
  3465. href = br_href(&doc, i);
  3466. if (!href[0])
  3467. continue;
  3468. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  3469. continue;
  3470. for (k = 0; k < n; k++)
  3471. if (s_eq(urls[k], url)) {
  3472. dup = 1;
  3473. break;
  3474. }
  3475. if (dup)
  3476. continue;
  3477. s_copy(urls[n], url, BR_URL_MAX);
  3478. remote[n] = url[0] != '/' && !css_cache_has(url);
  3479. n++;
  3480. }
  3481. for (i = 0; i < BR_MAX_SHEETS; i++)
  3482. slot[i] = 0;
  3483. /* Start as many remote sheets as there are free workers. */
  3484. for (; next < n; next++) {
  3485. struct fetch_worker *w;
  3486. if (!remote[next])
  3487. continue;
  3488. w = fetch_worker_alloc();
  3489. if (!w)
  3490. break;
  3491. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  3492. err, sizeof(err)) != 0) {
  3493. fetch_worker_release(w);
  3494. remote[next] = 0;
  3495. continue;
  3496. }
  3497. slot[next] = w;
  3498. }
  3499. for (i = 0; i < n; i++) {
  3500. unsigned char *data = 0;
  3501. unsigned int len = 0;
  3502. int rv;
  3503. if (!remote[i]) {
  3504. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  3505. if (rv == FETCH_ABORT) {
  3506. fetch_workers_stop_all();
  3507. return FETCH_ABORT;
  3508. }
  3509. if (rv != 0 || !len)
  3510. continue;
  3511. } else {
  3512. struct fetch_worker *w = slot[i];
  3513. int tr = 0;
  3514. if (!w) {
  3515. w = fetch_worker_alloc();
  3516. if (!w)
  3517. continue;
  3518. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  3519. 0, 0, 0, 0, err,
  3520. sizeof(err)) != 0) {
  3521. fetch_worker_release(w);
  3522. remote[i] = 0;
  3523. if (i == next)
  3524. next++;
  3525. continue;
  3526. }
  3527. slot[i] = w;
  3528. if (i == next)
  3529. next++;
  3530. }
  3531. rv = fetch_worker_wait(w, err, sizeof(err));
  3532. if (rv == FETCH_ABORT) {
  3533. fetch_workers_stop_all();
  3534. return FETCH_ABORT;
  3535. }
  3536. if (rv == 0)
  3537. rv = fetch_worker_read_body(w, image_io_buf,
  3538. BR_CSS_MAX,
  3539. image_io_buf + BR_CSS_MAX,
  3540. BR_CSS_COMP_MAX, &tr,
  3541. err, sizeof(err));
  3542. else
  3543. rv = -1;
  3544. fetch_worker_release(w);
  3545. slot[i] = 0;
  3546. /* Refill the worker window before parsing this sheet. */
  3547. for (; next < n; next++) {
  3548. struct fetch_worker *nw;
  3549. if (!remote[next])
  3550. continue;
  3551. nw = fetch_worker_alloc();
  3552. if (!nw)
  3553. break;
  3554. if (fetch_worker_submit(nw, urls[next],
  3555. BR_CSS_MAX, 0, 0, 0, 0,
  3556. err, sizeof(err)) != 0) {
  3557. fetch_worker_release(nw);
  3558. remote[next] = 0;
  3559. continue;
  3560. }
  3561. slot[next] = nw;
  3562. }
  3563. if (rv <= 0)
  3564. continue;
  3565. len = (unsigned int)rv;
  3566. data = image_io_buf;
  3567. css_cache_put(urls[i], data, len);
  3568. }
  3569. if (len) {
  3570. br_set_font_base(urls[i]);
  3571. br_parse_css_text(&doc, (const char *)data, len);
  3572. }
  3573. }
  3574. br_set_font_base(page_url);
  3575. br_parse_inline_css(&doc);
  3576. load_font_faces();
  3577. br_reset_styles(&doc);
  3578. layout_valid = 0;
  3579. return 0;
  3580. }
  3581. static void preload_begin(void)
  3582. {
  3583. preload_active = 1;
  3584. preload_pending = 0;
  3585. preload_wait = 1;
  3586. preload_max_jobs = FETCH_WORKERS;
  3587. preload_node = 0;
  3588. preload_loaded = 0;
  3589. preload_scroll = 0;
  3590. }
  3591. /* Styles are computed top-down during layout, but images inside a hidden
  3592. * menu/carousel are never visited and keep img_top == 0. Without this check
  3593. * the preloader walks the DOM in node order and spends the whole image
  3594. * budget on logos and off-canvas thumbnails the reader cannot see. */
  3595. static int node_hidden(unsigned int node)
  3596. {
  3597. unsigned int path[32], n = 0, p = node, i;
  3598. struct br_style st, parent;
  3599. while (p && n < sizeof(path) / sizeof(path[0])) {
  3600. path[n++] = p;
  3601. p = doc.nodes[p].parent;
  3602. }
  3603. parent = (struct br_style){0};
  3604. parent.font_px = 16;
  3605. parent.display = BR_DISPLAY_BLOCK;
  3606. for (i = n; i > 0; i--) {
  3607. br_style_for(&doc, path[i - 1], &parent, &st);
  3608. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  3609. st.opacity_hidden)
  3610. return 1;
  3611. parent = st;
  3612. }
  3613. return 0;
  3614. }
  3615. static struct br_style base_style(void);
  3616. static void style_for_node(unsigned int node, struct br_style *out)
  3617. {
  3618. unsigned int p = doc.nodes[node].parent;
  3619. struct br_style parent;
  3620. if (p) {
  3621. style_for_node(p, &parent);
  3622. br_style_for(&doc, node, &parent, out);
  3623. } else {
  3624. parent = base_style();
  3625. br_style_for(&doc, node, &parent, out);
  3626. }
  3627. }
  3628. /* ---- parallel image preloading ---- *
  3629. *
  3630. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  3631. * preload_step() only starts jobs and harvests completed ones; the browser
  3632. * main loop keeps drawing between calls, instead of blocking on one fetch.
  3633. */
  3634. static int preload_active_jobs(void)
  3635. {
  3636. int i, n = 0;
  3637. for (i = 0; i < FETCH_WORKERS; i++)
  3638. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  3639. n++;
  3640. return n;
  3641. }
  3642. static void preload_job_error(struct fetch_worker *w)
  3643. {
  3644. if (w->node < doc.nnode) {
  3645. if (w->bg)
  3646. doc.nodes[w->node].bg_img_index = -2;
  3647. else
  3648. doc.nodes[w->node].img_index = -2;
  3649. ngui_invalidate(&ui);
  3650. }
  3651. }
  3652. static void preload_decode(unsigned int node, int bg,
  3653. const unsigned char *data, unsigned int len)
  3654. {
  3655. if (image_count >= BR_MAX_IMAGES) {
  3656. if (bg)
  3657. doc.nodes[node].bg_img_index = -2;
  3658. else
  3659. doc.nodes[node].img_index = -2;
  3660. return;
  3661. }
  3662. if (decode_image_data(data, len, &images[image_count],
  3663. bg && node < BR_MAX_NODES &&
  3664. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  3665. bg && node < BR_MAX_NODES &&
  3666. layout_boxes[node].valid ? layout_boxes[node].h : 0) == 0) {
  3667. if (bg)
  3668. doc.nodes[node].bg_img_index = (short)image_count;
  3669. else
  3670. doc.nodes[node].img_index = (short)image_count;
  3671. image_count++;
  3672. preload_loaded++;
  3673. layout_valid = 0;
  3674. } else {
  3675. if (bg)
  3676. doc.nodes[node].bg_img_index = -2;
  3677. else
  3678. doc.nodes[node].img_index = -2;
  3679. }
  3680. ngui_invalidate(&ui);
  3681. }
  3682. /* Harvest one completed worker. Returns 1 when a job was finished. */
  3683. static int preload_finish_worker(struct fetch_worker *w)
  3684. {
  3685. char err[64];
  3686. int rv, tr = 0;
  3687. rv = fetch_worker_poll(w, err, sizeof(err));
  3688. if (rv < 0) {
  3689. preload_job_error(w);
  3690. fetch_worker_release(w);
  3691. return 1;
  3692. }
  3693. if (rv == 0)
  3694. return 0;
  3695. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  3696. image_comp_buf, BR_IMG_FILE_MAX,
  3697. &tr, err, sizeof(err));
  3698. if (rv >= 0)
  3699. preload_decode(w->node, w->bg, image_file_buf,
  3700. (unsigned int)rv);
  3701. else
  3702. preload_job_error(w);
  3703. fetch_worker_release(w);
  3704. return 1;
  3705. }
  3706. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  3707. * the number of jobs started. */
  3708. static int preload_fill_jobs(void)
  3709. {
  3710. int started = 0;
  3711. char err[64];
  3712. while (preload_active && preload_node < doc.nnode) {
  3713. unsigned int i = preload_node;
  3714. struct br_node *nd = &doc.nodes[i];
  3715. const char *src;
  3716. char url[BR_URL_MAX];
  3717. struct fetch_worker *w;
  3718. if (preload_active_jobs() >= preload_max_jobs)
  3719. break;
  3720. if (nd->type != BR_NODE_ELEM) {
  3721. preload_node++;
  3722. continue;
  3723. }
  3724. if (nd->tag != BR_TAG_IMG) {
  3725. if (nd->bg_img_index == -1) {
  3726. struct br_style bs;
  3727. style_for_node(i, &bs);
  3728. if (bs.display != BR_DISPLAY_NONE &&
  3729. !bs.vis_hidden && bs.bg_image) {
  3730. const char *bsrc =
  3731. br_bg_image_url(bs.bg_image - 1);
  3732. /* Lazy like <img>: a background box
  3733. * below the viewport (or not laid
  3734. * out yet) waits for the next scan. */
  3735. if (bsrc[0] &&
  3736. (!layout_boxes[i].valid ||
  3737. block_top[i] >
  3738. (unsigned int)(page_scroll.offset +
  3739. page_rect.h + 160))) {
  3740. preload_pending = 1;
  3741. preload_node++;
  3742. continue;
  3743. }
  3744. if (bsrc[0] &&
  3745. !contains_ci(bsrc, ".svg") &&
  3746. !starts_with(bsrc, "data:") &&
  3747. resolve_link(page_url, bsrc, url,
  3748. sizeof(url)) == 0) {
  3749. if (image_count +
  3750. preload_active_jobs() >=
  3751. BR_MAX_IMAGES) {
  3752. preload_node = doc.nnode;
  3753. break;
  3754. }
  3755. if (url[0] == '/') {
  3756. unsigned char *data = 0;
  3757. unsigned int len = 0;
  3758. preload_node = i + 1;
  3759. if (fetch_image(url,
  3760. BR_IMG_FILE_MAX,
  3761. &data, &len,
  3762. err,
  3763. sizeof(err)) == 0)
  3764. preload_decode(i, 1, data, len);
  3765. else
  3766. nd->bg_img_index = -2;
  3767. continue;
  3768. }
  3769. w = fetch_worker_alloc();
  3770. if (!w)
  3771. return started;
  3772. preload_node = i + 1;
  3773. if (fetch_worker_submit(w, url,
  3774. BR_IMG_FILE_MAX,
  3775. 0, 0, i, 1,
  3776. err,
  3777. sizeof(err)) != 0) {
  3778. nd->bg_img_index = -2;
  3779. fetch_worker_release(w);
  3780. continue;
  3781. }
  3782. w->image_job = 1;
  3783. w->deadline = u_ticks_ms() +
  3784. BR_IMG_JOB_TIMEOUT_MS;
  3785. /* in flight: rescans skip it */
  3786. nd->bg_img_index = -3;
  3787. started++;
  3788. continue;
  3789. }
  3790. }
  3791. nd->bg_img_index = -2;
  3792. }
  3793. preload_node++;
  3794. continue;
  3795. }
  3796. if (nd->img_index != -1) {
  3797. preload_node++;
  3798. continue;
  3799. }
  3800. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  3801. preload_node++;
  3802. continue;
  3803. }
  3804. src = br_src(&doc, i);
  3805. if (!src[0] || contains_ci(src, ".svg") ||
  3806. starts_with(src, "data:")) {
  3807. preload_node++;
  3808. continue;
  3809. }
  3810. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  3811. preload_node++;
  3812. continue;
  3813. }
  3814. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  3815. preload_node = doc.nnode;
  3816. break;
  3817. }
  3818. /* Do not stop at the first below-fold image: DOM order is
  3819. * not visual order, and a footer/ad image early in the DOM
  3820. * used to hide every later article image from the loader. */
  3821. if (img_top[i] >
  3822. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  3823. preload_pending = 1;
  3824. preload_node++;
  3825. continue;
  3826. }
  3827. if (url[0] == '/') {
  3828. unsigned char *data = 0;
  3829. unsigned int len = 0;
  3830. preload_node = i + 1;
  3831. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  3832. err, sizeof(err)) == 0)
  3833. preload_decode(i, 0, data, len);
  3834. else
  3835. nd->img_index = -2;
  3836. continue;
  3837. }
  3838. w = fetch_worker_alloc();
  3839. if (!w)
  3840. return started;
  3841. preload_node = i + 1;
  3842. {
  3843. char msg[64];
  3844. unsigned int n = 0;
  3845. s_append(msg, &n, "Loading images ", sizeof(msg));
  3846. s_append_dec(msg, &n,
  3847. (unsigned int)preload_loaded + 1,
  3848. sizeof(msg));
  3849. s_append(msg, &n, "...", sizeof(msg));
  3850. set_status(msg, 0, 0);
  3851. }
  3852. if (fetch_worker_submit(w, url, BR_IMG_FILE_MAX, 0, 0, i, 0,
  3853. err, sizeof(err)) != 0) {
  3854. nd->img_index = -2;
  3855. fetch_worker_release(w);
  3856. continue;
  3857. }
  3858. w->image_job = 1;
  3859. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  3860. nd->img_index = -3; /* in flight: rescans skip it */
  3861. started++;
  3862. }
  3863. return started;
  3864. }
  3865. static void preload_step(void)
  3866. {
  3867. int i;
  3868. if (!preload_active)
  3869. return;
  3870. if (cancel_fetch || pending_action) {
  3871. preload_active = 0;
  3872. preload_pending = 0;
  3873. fetch_workers_cancel_busy();
  3874. return;
  3875. }
  3876. preload_fill_jobs();
  3877. /* Decode at most one completed image per main-loop pass. A full-size
  3878. * JPEG decode blocks this single-threaded UI for a long time, and
  3879. * harvesting a batch back-to-back starved the TCP pump (and therefore
  3880. * every other image download) on slow CPUs: requests looked stuck
  3881. * while four decodes ran in a row. */
  3882. for (i = 0; i < FETCH_WORKERS; i++) {
  3883. if (!fetch_workers[i].busy)
  3884. continue;
  3885. if (preload_finish_worker(&fetch_workers[i]))
  3886. return;
  3887. }
  3888. if (preload_active && preload_node >= doc.nnode &&
  3889. preload_active_jobs() == 0) {
  3890. preload_active = 0;
  3891. if (preload_pending)
  3892. preload_scroll = page_scroll.offset;
  3893. else
  3894. preload_pending = 0;
  3895. /* Keep the now idle helpers and their connections; a later
  3896. * navigation reuses them. They exit after ten idle seconds,
  3897. * and losing window focus stops them at once. */
  3898. set_status(post_status_text, post_status_error, post_status_ttl);
  3899. ngui_invalidate(&ui);
  3900. }
  3901. }
  3902. /* Set by navigate() when it turned a typed bare host into https://; the next
  3903. * load_page() consumes it and may retry over http. */
  3904. static int nav_https_upgraded;
  3905. /* Errors that mean "https is not served here" rather than "the site is
  3906. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  3907. static int https_fallback_error(int e)
  3908. {
  3909. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  3910. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  3911. e == UHTTP_ERR_RESET;
  3912. }
  3913. static void history_push(const char *url)
  3914. {
  3915. if (!url || !url[0])
  3916. return;
  3917. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  3918. s_eq(history[hist_pos], url))
  3919. return;
  3920. if (hist_len > 0 && hist_pos + 1 < hist_len)
  3921. hist_len = hist_pos + 1;
  3922. if (hist_len < BR_HISTORY) {
  3923. s_copy(history[hist_len], url, BR_URL_MAX);
  3924. hist_pos = hist_len;
  3925. hist_len++;
  3926. } else {
  3927. int i;
  3928. for (i = 1; i < BR_HISTORY; i++)
  3929. s_copy(history[i - 1], history[i], BR_URL_MAX);
  3930. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  3931. hist_pos = BR_HISTORY - 1;
  3932. }
  3933. }
  3934. static void load_page(const char *url, int local, int push)
  3935. {
  3936. unsigned char *body = 0;
  3937. unsigned int len = 0;
  3938. int truncated = 0;
  3939. struct img_info image_info;
  3940. char ctype[64];
  3941. char final[BR_URL_MAX];
  3942. char err[80];
  3943. const char *detail = 0;
  3944. const char *post = pending_post_is ? pending_post : 0;
  3945. unsigned int post_len = pending_post_len;
  3946. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  3947. /* Phase timings for the status line: where a slow load spends it. */
  3948. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  3949. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  3950. int upgraded = nav_https_upgraded;
  3951. int retried = 0;
  3952. int rv;
  3953. nav_https_upgraded = 0;
  3954. final[0] = '\0';
  3955. pending_post_len = 0;
  3956. pending_post_is = 0;
  3957. cancel_fetch = 0;
  3958. preload_active = 0;
  3959. preload_pending = 0;
  3960. fetch_workers_prepare_nav(url);
  3961. js_browser_stop();
  3962. js_last_status[0] = '\0';
  3963. js_last_error = 0;
  3964. heap_clear();
  3965. image_reset();
  3966. form_reset_state();
  3967. layout_valid = 0;
  3968. page_scroll.offset = 0;
  3969. page_scroll.dragging = 0;
  3970. page_title[0] = '\0';
  3971. page_loading = 1;
  3972. page_is_local = local;
  3973. s_copy(page_url, url, sizeof(page_url));
  3974. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3975. url_in.len = s_len(url_in.text);
  3976. url_in.cursor = url_in.len;
  3977. url_in.scroll = 0;
  3978. ngui_set_focus(&ui, 0);
  3979. if (final[0])
  3980. final[0] = '\0';
  3981. if (push)
  3982. history_push(url);
  3983. set_status("Loading...", 0, 0);
  3984. ngui_invalidate(&ui);
  3985. /* heap_clear() detaches the fonts, so attach them again before the
  3986. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  3987. if (heap_start() != 0) {
  3988. show_error("Out of memory", "Cannot allocate the page buffer");
  3989. return;
  3990. }
  3991. br_parse_plain(&doc, "", 0); /* blank while loading */
  3992. ngui_font_attach(&ui);
  3993. redraw_now();
  3994. browser_rules_alloc();
  3995. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  3996. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  3997. &truncated, post, post_len);
  3998. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  3999. fetch_last_error == UHTTP_ERR_DNS) {
  4000. /* A busy previous page can leave the receiver ring full just
  4001. * long enough to lose a DNS reply. Tear the old helpers down
  4002. * and try once more before giving up. */
  4003. retried = 1;
  4004. fetch_workers_stop_all();
  4005. u_sleep_ms(500);
  4006. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  4007. sizeof(ctype), final, sizeof(final), err,
  4008. sizeof(err), &truncated, post, post_len);
  4009. }
  4010. if (rv == FETCH_ABORT)
  4011. return;
  4012. t_fetch = u_ticks_ms() - t_start;
  4013. /* Capture the page timing before CSS/script/image fetches overwrite the
  4014. * shared fetch_meta block. */
  4015. if (rv == 0 && !local) {
  4016. page_open_ms = fetch_meta.open_ms;
  4017. page_first_ms = fetch_meta.first_ms;
  4018. page_total_ms = fetch_meta.total_ms;
  4019. }
  4020. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  4021. https_fallback_error(fetch_last_error)) {
  4022. char http_url[BR_URL_MAX];
  4023. unsigned int n = 0;
  4024. s_append(http_url, &n, "http://", sizeof(http_url));
  4025. s_append(http_url, &n, url + 8, sizeof(http_url));
  4026. /* Replace the https entry instead of adding a second one. */
  4027. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  4028. s_eq(history[hist_pos], url))
  4029. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  4030. load_page(http_url, 0, 0);
  4031. return;
  4032. }
  4033. if (rv != 0) {
  4034. detail = err;
  4035. show_error("Cannot load this page", detail);
  4036. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4037. url_in.len = s_len(url_in.text);
  4038. url_in.cursor = url_in.len;
  4039. url_in.scroll = 0;
  4040. return;
  4041. }
  4042. if (!local)
  4043. origin_cache_learn(url, final[0] ? final : url);
  4044. page_is_local = local;
  4045. if (final[0]) {
  4046. s_copy(page_url, final, sizeof(page_url));
  4047. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4048. url_in.len = s_len(url_in.text);
  4049. url_in.cursor = url_in.len;
  4050. url_in.scroll = 0;
  4051. }
  4052. if (contains_ci(ctype, "text/plain")) {
  4053. br_parse_plain(&doc, (const char *)body, len);
  4054. } else if (contains_ci(ctype, "image/") ||
  4055. (!contains_ci(ctype, "text/html") &&
  4056. img_sniff(body, len, &image_info) == 0)) {
  4057. unsigned int node = br_parse_image_doc(&doc, page_url);
  4058. if (node)
  4059. decode_direct_image(body, len, node);
  4060. s_copy(page_title, "Image", sizeof(page_title));
  4061. } else {
  4062. br_set_viewport(ui.w);
  4063. t_mark = u_ticks_ms();
  4064. br_parse(&doc, (const char *)body, len);
  4065. t_parse = u_ticks_ms() - t_mark;
  4066. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  4067. sizeof(page_title));
  4068. t_mark = u_ticks_ms();
  4069. if (load_stylesheets() == FETCH_ABORT)
  4070. return;
  4071. t_css = u_ticks_ms() - t_mark;
  4072. if (pending_action)
  4073. return;
  4074. }
  4075. preload_begin();
  4076. page_loading = 0;
  4077. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4078. url_in.len = s_len(url_in.text);
  4079. url_in.cursor = url_in.len;
  4080. url_in.scroll = 0;
  4081. ngui_set_focus(&ui, 0);
  4082. /* Paint the parsed page before fetching/running scripts. A slow
  4083. * remote <script src> then does not hide the page behind the loading
  4084. * screen; the fetch helper pumps this UI while it waits. */
  4085. set_status("Loading scripts...", 0, 0);
  4086. t_mark = u_ticks_ms();
  4087. redraw_now();
  4088. t_paint = u_ticks_ms() - t_mark;
  4089. /* Start one image download before the scripts. The other workers
  4090. * fetch the external script bodies in parallel, and the remaining
  4091. * images start as soon as the script phase ends. */
  4092. preload_max_jobs = 1;
  4093. preload_fill_jobs();
  4094. preload_wait = 0;
  4095. t_mark = u_ticks_ms();
  4096. run_page_scripts();
  4097. t_js = u_ticks_ms() - t_mark;
  4098. preload_max_jobs = FETCH_WORKERS;
  4099. if (pending_action)
  4100. return;
  4101. post_status_text[0] = '\0';
  4102. post_status_error = 0;
  4103. post_status_ttl = 0;
  4104. if (js_last_status[0]) {
  4105. s_copy(post_status_text, js_last_status,
  4106. sizeof(post_status_text));
  4107. post_status_error = js_last_error;
  4108. post_status_ttl = 8000;
  4109. } else if (truncated) {
  4110. s_copy(post_status_text, "Page truncated at the buffer limit",
  4111. sizeof(post_status_text));
  4112. post_status_ttl = 6000;
  4113. } else if (doc.truncated) {
  4114. s_copy(post_status_text, "Page truncated by the parser",
  4115. sizeof(post_status_text));
  4116. post_status_ttl = 6000;
  4117. } else if (page_total_ms) {
  4118. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  4119. * paint 220, js 1750" -- the phases of this load. */
  4120. unsigned int n = 0;
  4121. static const char *const names[] = {
  4122. ", parse ", ", css ", ", paint ", ", js "
  4123. };
  4124. unsigned int vals[4];
  4125. int k;
  4126. vals[0] = t_parse;
  4127. vals[1] = t_css;
  4128. vals[2] = t_paint;
  4129. vals[3] = t_js;
  4130. (void)page_first_ms;
  4131. if (starts_with(page_url, "https://"))
  4132. s_append(post_status_text, &n,
  4133. "HTTPS (not verified), ",
  4134. sizeof(post_status_text));
  4135. s_append(post_status_text, &n, "Loaded in ",
  4136. sizeof(post_status_text));
  4137. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  4138. sizeof(post_status_text));
  4139. s_append(post_status_text, &n, " ms: page ",
  4140. sizeof(post_status_text));
  4141. s_append_dec(post_status_text, &n, t_fetch,
  4142. sizeof(post_status_text));
  4143. s_append(post_status_text, &n, " (headers ",
  4144. sizeof(post_status_text));
  4145. s_append_dec(post_status_text, &n, page_open_ms,
  4146. sizeof(post_status_text));
  4147. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  4148. for (k = 0; k < 4; k++) {
  4149. s_append(post_status_text, &n, names[k],
  4150. sizeof(post_status_text));
  4151. s_append_dec(post_status_text, &n, vals[k],
  4152. sizeof(post_status_text));
  4153. }
  4154. post_status_ttl = 12000;
  4155. } else if (starts_with(page_url, "https://")) {
  4156. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  4157. sizeof(post_status_text));
  4158. post_status_ttl = 6000;
  4159. }
  4160. set_status(post_status_text, post_status_error, post_status_ttl);
  4161. ngui_invalidate(&ui);
  4162. }
  4163. static void load_home(int push)
  4164. {
  4165. pending_post_len = 0;
  4166. pending_post_is = 0;
  4167. cancel_fetch = 0;
  4168. preload_active = 0;
  4169. preload_pending = 0;
  4170. js_browser_stop();
  4171. js_last_status[0] = '\0';
  4172. js_last_error = 0;
  4173. heap_clear();
  4174. image_reset();
  4175. form_reset_state();
  4176. layout_valid = 0;
  4177. page_scroll.offset = 0;
  4178. page_scroll.dragging = 0;
  4179. page_loading = 1;
  4180. page_is_local = 0;
  4181. s_copy(page_url, "about:home", sizeof(page_url));
  4182. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4183. url_in.len = s_len(url_in.text);
  4184. url_in.cursor = url_in.len;
  4185. url_in.scroll = 0;
  4186. ngui_set_focus(&ui, 0);
  4187. if (push)
  4188. history_push(page_url);
  4189. ngui_invalidate(&ui);
  4190. /* See load_page(): reattach the fonts before the first redraw. */
  4191. if (heap_start() != 0) {
  4192. show_error("Out of memory", "Cannot allocate the browser heap");
  4193. return;
  4194. }
  4195. br_parse_plain(&doc, "", 0);
  4196. ngui_font_attach(&ui);
  4197. redraw_now();
  4198. browser_rules_alloc();
  4199. {
  4200. static const char home[] =
  4201. "<html><head><title>NebOS Browser</title><style>"
  4202. "body { margin: 10px; color: #e4e6f0; }"
  4203. "h1 { color: #7fb0ff; }"
  4204. ".box { background-color: #262b3a; margin: 12px; "
  4205. "padding: 10px; }"
  4206. "a { color: #7fb0ff; }"
  4207. "pre { background-color: #32384a; }"
  4208. "</style></head><body>"
  4209. "<h1>NebOS Browser</h1>"
  4210. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  4211. "shared HTTP client and the image library.</p>"
  4212. "<div class=\"box\"><b>Try:</b>"
  4213. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  4214. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  4215. "<li><a href=\"/floppy1/JS.HTM\">/"
  4216. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  4217. "<li><a href=\"http://10.0.2.2:8000/\">"
  4218. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  4219. "<li><a href=\"https://example.com/\">"
  4220. "https://example.com/</a> (TLS, not verified)</li>"
  4221. "</ul></div>"
  4222. "<p>Type a URL in the bar above. Esc closes the "
  4223. "window, Ctrl+L focuses the address bar.</p>"
  4224. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  4225. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  4226. "</body></html>";
  4227. br_set_viewport(ui.w);
  4228. br_parse(&doc, home, sizeof(home) - 1);
  4229. br_parse_inline_css(&doc);
  4230. br_reset_styles(&doc);
  4231. s_copy(page_title, doc.title, sizeof(page_title));
  4232. }
  4233. post_status_text[0] = '\0';
  4234. post_status_error = 0;
  4235. post_status_ttl = 0;
  4236. page_loading = 0;
  4237. set_status("", 0, 0);
  4238. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4239. url_in.len = s_len(url_in.text);
  4240. url_in.cursor = url_in.len;
  4241. url_in.scroll = 0;
  4242. ngui_set_focus(&ui, 0);
  4243. ngui_invalidate(&ui);
  4244. }
  4245. /* Extensions the browser opens from the local filesystem. A dotted input
  4246. * with one of these still resolves relative to the cwd. */
  4247. static int local_file_ext(const char *s)
  4248. {
  4249. static const char *const exts[] = {
  4250. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  4251. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  4252. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  4253. "cfg", "conf", 0
  4254. };
  4255. unsigned int i = 0, start = 0, len = 0, e;
  4256. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  4257. s[i] != '#') {
  4258. if (s[i] == '.') {
  4259. start = i + 1;
  4260. len = 0;
  4261. } else if (start) {
  4262. len++;
  4263. }
  4264. i++;
  4265. }
  4266. if (!len)
  4267. return 0;
  4268. for (e = 0; exts[e]; e++) {
  4269. const char *x = exts[e];
  4270. unsigned int xn = s_len(x), k;
  4271. if (xn != len)
  4272. continue;
  4273. for (k = 0; k < len; k++) {
  4274. char a = s[start + k];
  4275. if (a >= 'A' && a <= 'Z')
  4276. a = (char)(a - 'A' + 'a');
  4277. if (a != x[k])
  4278. break;
  4279. }
  4280. if (k == len)
  4281. return 1;
  4282. }
  4283. return 0;
  4284. }
  4285. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  4286. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  4287. * Enter to the first network request. */
  4288. static int looks_like_host(const char *s)
  4289. {
  4290. unsigned int i = 0;
  4291. int dot = 0;
  4292. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  4293. s[i] != ':') {
  4294. char c = s[i];
  4295. if (c == '.') {
  4296. dot = 1;
  4297. } else if (!((c >= 'a' && c <= 'z') ||
  4298. (c >= 'A' && c <= 'Z') ||
  4299. (c >= '0' && c <= '9') ||
  4300. c == '-' || c == '_')) {
  4301. return 0;
  4302. }
  4303. i++;
  4304. }
  4305. return dot && i > 0 && !local_file_ext(s);
  4306. }
  4307. static void load_remote(const char *url, int push)
  4308. {
  4309. char canon[BR_URL_MAX];
  4310. s_copy(canon, url, sizeof(canon));
  4311. origin_cache_apply(canon, sizeof(canon));
  4312. load_page(canon, 0, push);
  4313. }
  4314. static void navigate(const char *input, int push)
  4315. {
  4316. char target[BR_URL_MAX];
  4317. char *t;
  4318. if (!input)
  4319. return;
  4320. s_copy(target, input, sizeof(target));
  4321. t = trim(target);
  4322. if (!t[0])
  4323. return;
  4324. if (s_eq(t, "about:home")) {
  4325. load_home(push);
  4326. return;
  4327. }
  4328. if (starts_with(t, "file://")) {
  4329. make_abs_local(t + 7, target, sizeof(target));
  4330. load_page(target, 1, push);
  4331. return;
  4332. }
  4333. if (is_http(t)) {
  4334. load_remote(t, push);
  4335. return;
  4336. }
  4337. if (t[0] == '/') {
  4338. make_abs_local(t, target, sizeof(target));
  4339. load_page(target, 1, push);
  4340. return;
  4341. }
  4342. if (!looks_like_host(t)) {
  4343. struct sys_stat st;
  4344. if (u_stat(t, &st) == 0 && !st.is_dir) {
  4345. make_abs_local(t, target, sizeof(target));
  4346. load_page(target, 1, push);
  4347. return;
  4348. }
  4349. }
  4350. {
  4351. /* A typed bare host tries https first: nearly every site
  4352. * redirects http -> https anyway, and that hop costs a whole
  4353. * extra connection. load_page() falls back to http when the
  4354. * https connection itself fails. */
  4355. char with_scheme[BR_URL_MAX];
  4356. unsigned int n = 0;
  4357. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  4358. s_append(with_scheme, &n, t, sizeof(with_scheme));
  4359. nav_https_upgraded = 1;
  4360. load_remote(with_scheme, push);
  4361. }
  4362. }
  4363. /* ---- layout ---- */
  4364. static struct ufont_face *style_face(const struct br_style *st)
  4365. {
  4366. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  4367. return font_faces[st->font_face - 1];
  4368. return 0;
  4369. }
  4370. static struct ufont_face *run_face(const struct lay_run *r)
  4371. {
  4372. if (r->font_face && r->font_face <= BR_MAX_FACES)
  4373. return font_faces[r->font_face - 1];
  4374. return 0;
  4375. }
  4376. static unsigned int face_text_width(struct ngui *gui,
  4377. const struct br_style *st,
  4378. const char *s, unsigned int n)
  4379. {
  4380. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  4381. st->bold, st->italic, st->mono);
  4382. }
  4383. static int face_line_height(struct ngui *gui, const struct br_style *st)
  4384. {
  4385. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  4386. st->mono);
  4387. }
  4388. static unsigned int run_text_width(struct ngui *gui,
  4389. const struct lay_run *r,
  4390. const char *s, unsigned int n)
  4391. {
  4392. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  4393. r->bold, r->italic, r->mono);
  4394. }
  4395. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  4396. {
  4397. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  4398. r->mono);
  4399. }
  4400. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  4401. {
  4402. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  4403. }
  4404. static struct br_style base_style(void)
  4405. {
  4406. struct br_style s = { 0 };
  4407. s.color = ui.theme.text;
  4408. s.bg = ui.theme.bg;
  4409. s.has_bg = 0;
  4410. for (int i = 0; i < 4; i++) {
  4411. s.border_c[i] = 0;
  4412. s.border_w[i] = 0;
  4413. s.border_s[i] = BR_BORDER_SOLID;
  4414. }
  4415. s.font_px = 16;
  4416. s.bold = 0;
  4417. s.italic = 0;
  4418. s.mono = 0;
  4419. s.underline = 0;
  4420. s.strike = 0;
  4421. s.overline = 0;
  4422. s.align = BR_ALIGN_LEFT;
  4423. s.display = BR_DISPLAY_BLOCK;
  4424. s.no_bullet = 0;
  4425. s.list_style = BR_LIST_AUTO;
  4426. s.uppercase = 0;
  4427. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  4428. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  4429. s.width = s.max_width = s.min_width = 0;
  4430. s.height = s.min_height = s.max_height = 0;
  4431. s.box_sizing = 0;
  4432. s.ml_auto = s.mr_auto = 0;
  4433. s.line_h_pct = 0;
  4434. s.line_h_px = 0;
  4435. s.mt = s.mb = s.ml = s.mr = 0;
  4436. s.pt = s.pb = s.pl = s.pr = 0;
  4437. return s;
  4438. }
  4439. /* Resolve a margin/padding raw value. Percentages use the containing
  4440. * block width for all four sides, as CSS specifies. */
  4441. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  4442. {
  4443. if (unit == 1)
  4444. return base * v / 10000;
  4445. if (unit == 2)
  4446. return st->font_px * v / 100;
  4447. if (unit == 3)
  4448. return (int)br_root_font_px() * v / 100;
  4449. if (unit == 4)
  4450. return 0;
  4451. return v;
  4452. }
  4453. static int mp_px(const struct br_style *st, int side, int base)
  4454. {
  4455. int raw;
  4456. switch (side) {
  4457. case 0: raw = st->mt; break;
  4458. case 1: raw = st->mr; break;
  4459. case 2: raw = st->mb; break;
  4460. case 3: raw = st->ml; break;
  4461. case 4: raw = st->pt; break;
  4462. case 5: raw = st->pr; break;
  4463. case 6: raw = st->pb; break;
  4464. default: raw = st->pl; break;
  4465. }
  4466. if (st->mp_unit[side] == 5)
  4467. return base * raw / 100 + st->mp_calc_px[side];
  4468. return css_mp_px(st, raw, st->mp_unit[side], base);
  4469. }
  4470. static int style_width_px(const struct br_style *st, int base)
  4471. {
  4472. if (st->width_kind == 1)
  4473. return st->width;
  4474. if (st->width_kind == 2)
  4475. return base * (int)st->width / 100;
  4476. if (st->width_kind == 3)
  4477. return base * st->width_calc_pct / 100 + st->width_calc_px;
  4478. return 0;
  4479. }
  4480. static int style_height_px(const struct br_style *st, int base)
  4481. {
  4482. if (st->height_kind == 1)
  4483. return st->height;
  4484. if (st->height_kind == 2)
  4485. return base * (int)st->height / 100;
  4486. if (st->height_kind == 3)
  4487. return base * st->height_calc_pct / 100 + st->height_calc_px;
  4488. return 0;
  4489. }
  4490. static int css_size(unsigned char kind, int val, int base)
  4491. {
  4492. if (kind == 1)
  4493. return val;
  4494. if (kind == 2)
  4495. return base * val / 100;
  4496. return -1;
  4497. }
  4498. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  4499. int thick, int horizontal, unsigned short color,
  4500. unsigned char style)
  4501. {
  4502. int pos;
  4503. if (len <= 0 || thick <= 0)
  4504. return;
  4505. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  4506. if (horizontal)
  4507. ngui_fill_rect(ui, (struct ngui_rect){
  4508. x, y, len, thick}, color);
  4509. else
  4510. ngui_fill_rect(ui, (struct ngui_rect){
  4511. x, y, thick, len}, color);
  4512. return;
  4513. }
  4514. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  4515. int seg = len - pos;
  4516. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  4517. seg = style == BR_BORDER_DASHED ? 4 : 2;
  4518. if (horizontal)
  4519. ngui_fill_rect(ui, (struct ngui_rect){
  4520. x + pos, y, seg, thick}, color);
  4521. else
  4522. ngui_fill_rect(ui, (struct ngui_rect){
  4523. x, y + pos, thick, seg}, color);
  4524. }
  4525. }
  4526. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  4527. const struct br_style *st)
  4528. {
  4529. int top = st->border_w[0], right = st->border_w[1];
  4530. int bottom = st->border_w[2], left = st->border_w[3];
  4531. if (r.w <= 0 || r.h <= 0)
  4532. return;
  4533. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  4534. int i;
  4535. for (i = 0; i < 4; i++)
  4536. if (st->border_w[i] && !st->border_t[i]) {
  4537. ngui_fill_rect(ui, r, st->border_c[i]);
  4538. break;
  4539. }
  4540. return;
  4541. }
  4542. if (top && !st->border_t[0])
  4543. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  4544. st->border_c[0], st->border_s[0]);
  4545. if (bottom && !st->border_t[2])
  4546. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  4547. st->border_c[2], st->border_s[2]);
  4548. if (left && !st->border_t[3])
  4549. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  4550. left, 0, st->border_c[3], st->border_s[3]);
  4551. if (right && !st->border_t[1])
  4552. draw_border_side(ui, r.x + r.w - right, r.y + top,
  4553. r.h - top - bottom, right, 0,
  4554. st->border_c[1], st->border_s[1]);
  4555. }
  4556. static void transform_origin(const struct br_style *st, int w, int h,
  4557. int *ox, int *oy)
  4558. {
  4559. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  4560. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  4561. }
  4562. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  4563. unsigned int a)
  4564. {
  4565. unsigned int dr, dg, db, sr, sg, sb;
  4566. if (a >= 255)
  4567. return s;
  4568. dr = (d >> 11) & 31;
  4569. dg = (d >> 5) & 63;
  4570. db = d & 31;
  4571. sr = (s >> 11) & 31;
  4572. sg = (s >> 5) & 63;
  4573. sb = s & 31;
  4574. dr = (dr * (255 - a) + sr * a) / 255;
  4575. dg = (dg * (255 - a) + sg * a) / 255;
  4576. db = (db * (255 - a) + sb * a) / 255;
  4577. return (unsigned short)((dr << 11) | (dg << 5) | db);
  4578. }
  4579. /* Paint a solid box through scale()/rotate() around transform-origin. This
  4580. * transforms the element's own background box; text and descendants keep
  4581. * their layout (documented approximation). */
  4582. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  4583. unsigned short color,
  4584. const struct br_style *st)
  4585. {
  4586. double sx = st->scale_x / 100.0;
  4587. double sy = st->scale_y / 100.0;
  4588. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  4589. double c = cos(th), sn = sin(th);
  4590. int ox, oy, minx, miny, maxx, maxy, x, y;
  4591. double ax, ay;
  4592. double px[4], py[4];
  4593. int cx1, cy1, cx2, cy2, i;
  4594. if (sx == 0)
  4595. sx = 0.01;
  4596. if (sy == 0)
  4597. sy = 0.01;
  4598. transform_origin(st, box.w, box.h, &ox, &oy);
  4599. ax = box.x + ox;
  4600. ay = box.y + oy;
  4601. px[0] = -ox; py[0] = -oy;
  4602. px[1] = box.w - ox; py[1] = -oy;
  4603. px[2] = box.w - ox; py[2] = box.h - oy;
  4604. px[3] = -ox; py[3] = box.h - oy;
  4605. minx = miny = 1000000;
  4606. maxx = maxy = -1000000;
  4607. for (i = 0; i < 4; i++) {
  4608. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  4609. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  4610. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  4611. if (dx < minx) minx = dx;
  4612. if (dx > maxx) maxx = dx;
  4613. if (dy < miny) miny = dy;
  4614. if (dy > maxy) maxy = dy;
  4615. }
  4616. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  4617. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  4618. cx2 = page_rect.x + page_rect.w - 12;
  4619. cy2 = page_rect.y + page_rect.h;
  4620. if (cx2 > gui->w) cx2 = gui->w;
  4621. if (cy2 > gui->h) cy2 = gui->h;
  4622. if (minx < cx1) minx = cx1;
  4623. if (miny < cy1) miny = cy1;
  4624. if (maxx > cx2 - 1) maxx = cx2 - 1;
  4625. if (maxy > cy2 - 1) maxy = cy2 - 1;
  4626. for (y = miny; y <= maxy; y++) {
  4627. for (x = minx; x <= maxx; x++) {
  4628. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  4629. double rx = dx * c + dy * sn;
  4630. double ry = -dx * sn + dy * c;
  4631. double bx = rx / sx + ox;
  4632. double by = ry / sy + oy;
  4633. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  4634. gui->px[y * gui->w + x] = color;
  4635. }
  4636. }
  4637. }
  4638. static void draw_image_transformed(struct ngui *gui,
  4639. const struct img_image *im,
  4640. int x, int y, int w, int h,
  4641. int sx100, int sy100, int rot100,
  4642. int origin_x, int origin_y,
  4643. int origin_x_kind, int origin_y_kind)
  4644. {
  4645. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  4646. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  4647. double c = cos(th), sn = sin(th);
  4648. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  4649. double ax, ay;
  4650. double bx[4], by[4];
  4651. int cx1, cy1, cx2, cy2;
  4652. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  4653. return;
  4654. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  4655. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  4656. ax = x + ox;
  4657. ay = y + oy;
  4658. bx[0] = -ox; by[0] = -oy;
  4659. bx[1] = w - ox; by[1] = -oy;
  4660. bx[2] = w - ox; by[2] = h - oy;
  4661. bx[3] = -ox; by[3] = h - oy;
  4662. minx = miny = 1000000;
  4663. maxx = maxy = -1000000;
  4664. for (i = 0; i < 4; i++) {
  4665. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  4666. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  4667. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  4668. if (dx < minx) minx = dx;
  4669. if (dx > maxx) maxx = dx;
  4670. if (dy < miny) miny = dy;
  4671. if (dy > maxy) maxy = dy;
  4672. }
  4673. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  4674. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  4675. cx2 = page_rect.x + page_rect.w - 12;
  4676. cy2 = page_rect.y + page_rect.h;
  4677. if (cx2 > gui->w) cx2 = gui->w;
  4678. if (cy2 > gui->h) cy2 = gui->h;
  4679. if (minx < cx1) minx = cx1;
  4680. if (miny < cy1) miny = cy1;
  4681. if (maxx > cx2 - 1) maxx = cx2 - 1;
  4682. if (maxy > cy2 - 1) maxy = cy2 - 1;
  4683. for (py = miny; py <= maxy; py++) {
  4684. for (px = minx; px <= maxx; px++) {
  4685. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  4686. double rx = dx * c + dy * sn;
  4687. double ry = -dx * sn + dy * c;
  4688. double fx = rx / sx + ox;
  4689. double fy = ry / sy + oy;
  4690. int ix, iy;
  4691. unsigned int si, a;
  4692. unsigned short src;
  4693. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  4694. continue;
  4695. ix = (int)(fx * (double)im->w / w);
  4696. iy = (int)(fy * (double)im->h / h);
  4697. if (ix < 0 || ix >= (int)im->w ||
  4698. iy < 0 || iy >= (int)im->h)
  4699. continue;
  4700. si = (unsigned int)iy * im->w + (unsigned int)ix;
  4701. src = im->px[si];
  4702. a = im->alpha ? im->alpha[si] : 255;
  4703. gui->px[py * gui->w + px] =
  4704. a >= 255 ? src :
  4705. blend_rgb565(gui->px[py * gui->w + px],
  4706. src, a);
  4707. }
  4708. }
  4709. }
  4710. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  4711. unsigned int node, const struct br_style *st);
  4712. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  4713. * first and every pixel outside a corner's arc is restored afterwards. */
  4714. #define BG_ROUND_MAX 64
  4715. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  4716. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  4717. unsigned int node, const struct br_style *st,
  4718. int rtl, int rtr, int rbr, int rbl)
  4719. {
  4720. struct ngui *ui = l->ui;
  4721. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  4722. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  4723. if (ui->nclip > 0)
  4724. clip = ui->clip[ui->nclip - 1];
  4725. for (c = 0; c < 4; c++) {
  4726. if (r[c] > BG_ROUND_MAX)
  4727. r[c] = BG_ROUND_MAX;
  4728. if (r[c] > box.w / 2)
  4729. r[c] = box.w / 2;
  4730. if (r[c] > box.h / 2)
  4731. r[c] = box.h / 2;
  4732. }
  4733. for (c = 0; c < 4; c++) {
  4734. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  4735. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  4736. for (dy = 0; dy < r[c]; dy++)
  4737. for (dx = 0; dx < r[c]; dx++) {
  4738. int px = ox + dx, py = oy + dy;
  4739. if (px >= clip.x && py >= clip.y &&
  4740. px < clip.x + clip.w && py < clip.y + clip.h)
  4741. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  4742. ui->px[py * ui->w + px];
  4743. }
  4744. }
  4745. draw_bg_image(l, box, node, st);
  4746. for (c = 0; c < 4; c++) {
  4747. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  4748. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  4749. /* arc centre, in corner-square coordinates */
  4750. int cx = (c == 1 || c == 2) ? 0 : r[c];
  4751. int cy = (c >= 2) ? 0 : r[c];
  4752. for (dy = 0; dy < r[c]; dy++)
  4753. for (dx = 0; dx < r[c]; dx++) {
  4754. int px = ox + dx, py = oy + dy;
  4755. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  4756. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  4757. continue;
  4758. if (px >= clip.x && py >= clip.y &&
  4759. px < clip.x + clip.w && py < clip.y + clip.h)
  4760. ui->px[py * ui->w + px] =
  4761. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  4762. }
  4763. }
  4764. }
  4765. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  4766. unsigned int node, const struct br_style *st)
  4767. {
  4768. struct br_image *bi;
  4769. struct img_blit b;
  4770. int tw, th, x, y, rep_x, rep_y, posx, posy;
  4771. unsigned int scale = 65536;
  4772. int legacy, tiles = 0, rows = 0;
  4773. int cx1, cy1, cx2, cy2;
  4774. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  4775. return;
  4776. if (doc.nodes[node].bg_img_index < 0 ||
  4777. doc.nodes[node].bg_img_index >= image_count)
  4778. return;
  4779. bi = &images[doc.nodes[node].bg_img_index];
  4780. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  4781. return;
  4782. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  4783. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  4784. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  4785. if (legacy) {
  4786. scale = ((unsigned int)box.w << 16) / bi->img.w;
  4787. tw = box.w;
  4788. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  4789. x = box.x;
  4790. y = box.y;
  4791. rep_x = rep_y = 0;
  4792. } else {
  4793. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  4794. unsigned int sx = ((unsigned int)box.w << 16) /
  4795. bi->img.w;
  4796. unsigned int sy = ((unsigned int)box.h << 16) /
  4797. bi->img.h;
  4798. scale = st->bg_size_kind == 3 ?
  4799. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  4800. } else if (st->bg_size_kind == 1 ||
  4801. st->bg_size_kind == 2) {
  4802. int w = st->bg_size_w;
  4803. int h = st->bg_size_h;
  4804. if (st->bg_size_kind == 2) {
  4805. if (w)
  4806. w = box.w * w / 100;
  4807. if (h)
  4808. h = box.h * h / 100;
  4809. }
  4810. if (w)
  4811. scale = ((unsigned int)w << 16) / bi->img.w;
  4812. else if (h)
  4813. scale = ((unsigned int)h << 16) / bi->img.h;
  4814. }
  4815. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  4816. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  4817. if (tw < 1)
  4818. tw = 1;
  4819. if (th < 1)
  4820. th = 1;
  4821. posx = st->bg_pos_x_kind == 1 ?
  4822. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  4823. posy = st->bg_pos_y_kind == 1 ?
  4824. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  4825. x = box.x + posx;
  4826. y = box.y + posy;
  4827. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  4828. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  4829. if (rep_x) {
  4830. int m = (x - box.x) % tw;
  4831. if (m > 0)
  4832. m -= tw;
  4833. x = box.x + m;
  4834. }
  4835. if (rep_y) {
  4836. int m = (y - box.y) % th;
  4837. if (m > 0)
  4838. m -= th;
  4839. y = box.y + m;
  4840. }
  4841. }
  4842. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  4843. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  4844. cx2 = box.x + box.w;
  4845. cy2 = box.y + box.h;
  4846. if (cx2 > page_rect.x + page_rect.w - 12)
  4847. cx2 = page_rect.x + page_rect.w - 12;
  4848. if (cy2 > page_rect.y + page_rect.h)
  4849. cy2 = page_rect.y + page_rect.h;
  4850. if (cx1 >= cx2 || cy1 >= cy2)
  4851. return;
  4852. b.dst = l->ui->px;
  4853. b.dst_w = l->ui->w;
  4854. b.dst_h = l->ui->h;
  4855. b.clip_x = cx1;
  4856. b.clip_y = cy1;
  4857. b.clip_w = cx2 - cx1;
  4858. b.clip_h = cy2 - cy1;
  4859. b.scale = scale;
  4860. b.bg = ui.theme.bg;
  4861. b.bg2 = ui.theme.bg;
  4862. b.flags = IMG_BLIT_OVER_DST;
  4863. {
  4864. int row_x = x;
  4865. for (;;) {
  4866. for (;;) {
  4867. b.x = x;
  4868. b.y = y;
  4869. img_draw(&bi->img, &b);
  4870. if (!rep_x || ++tiles > 512)
  4871. break;
  4872. x += tw;
  4873. if (x >= box.x + box.w)
  4874. break;
  4875. }
  4876. if (!rep_y || ++rows > 64)
  4877. break;
  4878. y += th;
  4879. if (y >= box.y + box.h)
  4880. break;
  4881. x = row_x;
  4882. }
  4883. }
  4884. }
  4885. static int run_width(const struct lay_run *r)
  4886. {
  4887. if (r->img >= 0)
  4888. return r->iw;
  4889. if (r->img == -2)
  4890. return r->iw;
  4891. return (int)r->w;
  4892. }
  4893. static void start_line(struct lay *l, const struct br_style *st)
  4894. {
  4895. (void)st;
  4896. if (l->nruns == 0) {
  4897. l->line_y = l->y;
  4898. l->line_h = 0;
  4899. }
  4900. l->line_left = l->left;
  4901. l->line_right = l->right;
  4902. if (l->float_active && l->line_y < l->float_bottom) {
  4903. if (l->float_left > l->line_left)
  4904. l->line_left = l->float_left;
  4905. if (l->float_right < l->line_right)
  4906. l->line_right = l->float_right;
  4907. }
  4908. if (l->line_right < l->line_left + 8)
  4909. l->line_right = l->line_left + 8;
  4910. l->line_x = l->line_left;
  4911. l->run_x = l->line_left;
  4912. }
  4913. static void flush_line(struct lay *l)
  4914. {
  4915. int total, x, i, vis;
  4916. if (!l->nruns && l->line_x == l->line_left) {
  4917. l->line_h = 0;
  4918. return;
  4919. }
  4920. total = l->line_x - l->line_left;
  4921. x = l->line_left;
  4922. vis = 1;
  4923. if (l->draw) {
  4924. int lh = l->line_h ? l->line_h : 16;
  4925. vis = l->line_y + lh >= page_rect.y &&
  4926. l->line_y <= page_rect.y + page_rect.h;
  4927. }
  4928. if (l->align == BR_ALIGN_CENTER)
  4929. x += (l->line_right - l->line_left - total) / 2;
  4930. else if (l->align == BR_ALIGN_RIGHT)
  4931. x = l->line_right - total;
  4932. if (x < l->line_left)
  4933. x = l->line_left;
  4934. for (i = 0; i < l->nruns; i++) {
  4935. struct lay_run *r = &l->runs[i];
  4936. int w = run_width(r);
  4937. int ry = l->line_y + r->dy;
  4938. x += r->gap;
  4939. if (l->draw && vis) {
  4940. if (r->form) {
  4941. unsigned int node = r->form - 1;
  4942. struct form_state *fs = form_get(node, 1);
  4943. int hh = r->ih ? r->ih : 20;
  4944. int focused = form_focus == node;
  4945. int disabled = r->form_disabled;
  4946. unsigned short bg = l->ui->theme.panel_alt;
  4947. unsigned short fg = disabled ? 0x8410 : r->color;
  4948. struct ngui_rect box = {x, ry, w, hh};
  4949. if (r->form_kind == FORM_CHECKBOX ||
  4950. r->form_kind == FORM_RADIO) {
  4951. ngui_fill_rect(l->ui, box, bg);
  4952. ngui_frame(l->ui, box,
  4953. focused ? l->ui->theme.accent :
  4954. l->ui->theme.border);
  4955. if (fs && fs->checked) {
  4956. struct ngui_rect dot = {
  4957. x + 4, ry + 4,
  4958. w > 8 ? w - 8 : 1,
  4959. hh > 8 ? hh - 8 : 1
  4960. };
  4961. if (r->form_kind == FORM_RADIO)
  4962. ngui_fill_round_rect(
  4963. l->ui, dot, 4,
  4964. 4, 4, 4,
  4965. l->ui->theme.accent);
  4966. else
  4967. ngui_fill_rect(l->ui,
  4968. dot,
  4969. l->ui->theme.accent);
  4970. }
  4971. } else {
  4972. int editable =
  4973. r->form_kind == FORM_TEXT ||
  4974. r->form_kind == FORM_PASSWORD ||
  4975. r->form_kind == FORM_TEXTAREA;
  4976. int scroll = 0;
  4977. /* Editable fields draw the live value
  4978. * (r->lit is a short copy). */
  4979. static char shown[FORM_VALUE_MAX + 1];
  4980. const char *txt = r->lit;
  4981. unsigned int tl = s_len(r->lit);
  4982. if (editable && fs && fs->len) {
  4983. unsigned int k;
  4984. if (r->form_kind == FORM_PASSWORD) {
  4985. for (k = 0; k < fs->len; k++)
  4986. shown[k] = '*';
  4987. shown[k] = '\0';
  4988. txt = shown;
  4989. } else {
  4990. txt = fs->value;
  4991. }
  4992. tl = fs->len;
  4993. }
  4994. /* The box is drawn in theme colours, so
  4995. * the text is too: the page's CSS colour
  4996. * (dark on a light page) would vanish on
  4997. * the dark field. */
  4998. if (!disabled)
  4999. fg = editable && fs && !fs->len ?
  5000. l->ui->theme.text_dim :
  5001. l->ui->theme.text;
  5002. ngui_fill_rect(l->ui, box, bg);
  5003. ngui_frame(l->ui, box,
  5004. focused ? l->ui->theme.accent :
  5005. l->ui->theme.border);
  5006. /* A value wider than the field shows its
  5007. * tail (where typing happens). */
  5008. if (editable && fs && fs->len && w > 12) {
  5009. int tw = (int)run_text_width(l->ui,
  5010. r, txt, tl);
  5011. if (tw > w - 12)
  5012. scroll = tw - (w - 12);
  5013. }
  5014. ngui_push_clip(l->ui, (struct ngui_rect){
  5015. x + 1, ry + 1,
  5016. w > 2 ? w - 2 : 1,
  5017. hh > 2 ? hh - 2 : 1 });
  5018. ngui_text_px_face(l->ui, run_face(r),
  5019. x + 6 - scroll,
  5020. ry + (hh - r->font_px) / 2 - 1,
  5021. txt, tl, fg, r->font_px,
  5022. r->bold, r->italic, r->mono);
  5023. if (focused && fs && editable) {
  5024. int cw = 0;
  5025. if (fs->len && fs->caret)
  5026. cw = (int)run_text_width(
  5027. l->ui, r, txt,
  5028. fs->caret < fs->len ?
  5029. fs->caret : fs->len);
  5030. ngui_fill_rect(l->ui,
  5031. (struct ngui_rect){
  5032. x + 6 + cw - scroll,
  5033. ry + 4, 1,
  5034. hh > 8 ? hh - 8 : 1
  5035. },
  5036. l->ui->theme.accent);
  5037. }
  5038. ngui_pop_clip(l->ui);
  5039. if (r->form_kind == FORM_SELECT) {
  5040. ngui_text_px(l->ui, x + w - 12,
  5041. ry + 2, "v", 1, fg,
  5042. r->font_px, 0, 0, 0);
  5043. }
  5044. }
  5045. } else if (r->img == -2) {
  5046. int hh = r->ih ? r->ih : 20;
  5047. ngui_fill_rect(l->ui,
  5048. (struct ngui_rect){x, ry, w, hh},
  5049. l->ui->theme.panel_alt);
  5050. ngui_frame(l->ui,
  5051. (struct ngui_rect){x, ry, w, hh},
  5052. l->ui->theme.border);
  5053. ngui_text_px_face(l->ui, run_face(r),
  5054. x + 6, ry + 2, r->lit,
  5055. s_len(r->lit), r->color,
  5056. r->font_px, r->bold, r->italic,
  5057. r->mono);
  5058. } else if (r->img >= 0) {
  5059. struct br_image *bi = &images[r->img];
  5060. if (bi->state == 1 && r->transform_scale) {
  5061. draw_image_transformed(l->ui, &bi->img,
  5062. x, ry, r->iw, r->ih,
  5063. r->scale_x, r->scale_y,
  5064. r->rotate_x100, r->origin_x,
  5065. r->origin_y, r->origin_x_kind,
  5066. r->origin_y_kind);
  5067. } else if (bi->state == 1) {
  5068. struct img_blit b;
  5069. b.dst = l->ui->px;
  5070. b.dst_w = l->ui->w;
  5071. b.dst_h = l->ui->h;
  5072. b.clip_x = page_rect.x;
  5073. b.clip_y = page_rect.y;
  5074. b.clip_w = page_rect.w - 12;
  5075. b.clip_h = page_rect.h;
  5076. b.x = x;
  5077. b.y = ry;
  5078. b.scale = ((unsigned int)r->iw << 16) /
  5079. bi->img.w;
  5080. b.bg = ui.theme.bg;
  5081. b.bg2 = ui.theme.bg;
  5082. b.flags = IMG_BLIT_OVER_DST;
  5083. img_draw(&bi->img, &b);
  5084. }
  5085. } else {
  5086. const char *s = r->has_lit ? r->lit :
  5087. doc.text + r->off;
  5088. unsigned int n = r->has_lit ? s_len(r->lit) :
  5089. r->len;
  5090. ngui_text_px_face(l->ui, run_face(r), x, ry,
  5091. s, n, r->color, r->font_px,
  5092. r->bold, r->italic, r->mono);
  5093. if (r->underline)
  5094. ngui_fill_rect(l->ui,
  5095. (struct ngui_rect){x,
  5096. ry + run_ascent(l->ui, r) + 2,
  5097. w, 1}, r->color);
  5098. if (r->strike)
  5099. ngui_fill_rect(l->ui,
  5100. (struct ngui_rect){x,
  5101. ry + run_ascent(l->ui, r) -
  5102. (r->font_px > 3 ?
  5103. r->font_px / 3 : 1),
  5104. w, 1}, r->color);
  5105. if (r->overline)
  5106. ngui_fill_rect(l->ui,
  5107. (struct ngui_rect){x, ry,
  5108. w, 1}, r->color);
  5109. }
  5110. if (r->form || r->href) {
  5111. if (nhits < HIT_MAX) {
  5112. struct hit *h = &hits[nhits];
  5113. unsigned int target = r->form ?
  5114. r->form - 1 : r->href;
  5115. int hh = (r->form || r->img >= 0) ?
  5116. r->ih :
  5117. run_line_height(l->ui, r);
  5118. int merge = nhits > 0 &&
  5119. hits[nhits - 1].node == target &&
  5120. hits[nhits - 1].y == ry &&
  5121. hits[nhits - 1].h == hh &&
  5122. x <= hits[nhits - 1].x +
  5123. hits[nhits - 1].w + 2;
  5124. if (merge) {
  5125. struct hit *p = &hits[nhits - 1];
  5126. int end = x + w;
  5127. if (end > p->x + p->w)
  5128. p->w = end - p->x;
  5129. } else {
  5130. h->x = x;
  5131. h->y = ry;
  5132. h->w = w;
  5133. h->h = hh;
  5134. h->node = (unsigned short)target;
  5135. nhits++;
  5136. }
  5137. }
  5138. }
  5139. }
  5140. x += w;
  5141. }
  5142. l->y += l->line_h + 2;
  5143. if (l->float_active && l->y >= l->float_bottom)
  5144. l->float_active = 0;
  5145. l->nruns = 0;
  5146. l->line_x = l->left;
  5147. l->run_x = l->left;
  5148. l->line_left = l->left;
  5149. l->line_right = l->right;
  5150. l->line_h = 0;
  5151. l->space_pending = 0;
  5152. }
  5153. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  5154. const struct br_style *st, unsigned short href,
  5155. const char *lit)
  5156. {
  5157. unsigned int n = lit ? s_len(lit) : len;
  5158. const char *tp = lit ? lit : doc.text + off;
  5159. int w = (int)face_text_width(l->ui, st, tp, n);
  5160. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  5161. flush_line(l);
  5162. if (l->nruns == 0) {
  5163. l->line_y = l->y;
  5164. l->line_h = 0;
  5165. start_line(l, st);
  5166. }
  5167. {
  5168. struct lay_run *r = &l->runs[l->nruns++];
  5169. int gap = l->line_x - l->run_x;
  5170. if (gap < 0)
  5171. gap = 0;
  5172. r->gap = (unsigned short)gap;
  5173. r->off = off;
  5174. r->len = len;
  5175. r->color = st->color;
  5176. r->href = href;
  5177. r->dy = 0;
  5178. r->has_lit = 0;
  5179. r->form = 0;
  5180. r->form_kind = 0;
  5181. r->form_disabled = 0;
  5182. r->lit[0] = '\0';
  5183. if (lit && lit[0]) {
  5184. unsigned int i;
  5185. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  5186. r->lit[i] = lit[i];
  5187. r->lit[i] = '\0';
  5188. r->has_lit = 1;
  5189. }
  5190. r->img = -1;
  5191. r->iw = r->ih = 0;
  5192. r->font_px = st->font_px;
  5193. r->bold = st->bold;
  5194. r->italic = st->italic;
  5195. r->mono = st->mono;
  5196. r->font_face = st->font_face;
  5197. /* A control with its own background is a button, not body copy;
  5198. * an inherited link underline would strike through the fill. */
  5199. r->underline = st->underline && !st->has_bg;
  5200. r->strike = st->strike && !st->has_bg;
  5201. r->overline = st->overline && !st->has_bg;
  5202. r->w = (unsigned short)w;
  5203. if (r->has_lit)
  5204. r->w = (unsigned short)run_text_width(
  5205. l->ui, r, r->lit, s_len(r->lit));
  5206. w = r->w;
  5207. }
  5208. l->line_x += w;
  5209. l->run_x = l->line_x;
  5210. {
  5211. int lh = face_line_height(l->ui, st);
  5212. if (st->line_h_px)
  5213. lh = st->line_h_px;
  5214. else if (st->line_h_pct)
  5215. lh = st->font_px * st->line_h_pct / 100;
  5216. if (lh < face_line_height(l->ui, st))
  5217. lh = face_line_height(l->ui, st);
  5218. if (l->line_h < lh)
  5219. l->line_h = lh;
  5220. }
  5221. }
  5222. static void add_image_run(struct lay *l, unsigned int node,
  5223. const struct br_style *st, unsigned short href)
  5224. {
  5225. struct br_image *bi = 0;
  5226. int idx = doc.nodes[node].img_index;
  5227. int dw, dh, maxw;
  5228. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  5229. bi = &images[idx];
  5230. if (l->nruns == 0)
  5231. start_line(l, st);
  5232. if (l->space_pending &&
  5233. (l->nruns > 0 || l->line_x > l->line_left)) {
  5234. int sp = (int)face_text_width(l->ui, st, " ", 1);
  5235. if (l->line_x + sp <= l->line_right)
  5236. l->line_x += sp;
  5237. }
  5238. l->space_pending = 0;
  5239. if (!bi) {
  5240. const char *alt = br_alt(&doc, node);
  5241. struct br_style gs = *st;
  5242. char tmp[96];
  5243. unsigned int n = 0;
  5244. int w;
  5245. gs.color = BR_GRAY;
  5246. gs.underline = 0;
  5247. s_append(tmp, &n, "[", sizeof(tmp));
  5248. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  5249. s_append(tmp, &n, "]", sizeof(tmp));
  5250. w = (int)face_text_width(l->ui, &gs, tmp, n);
  5251. if (l->line_x + w > l->line_right &&
  5252. (l->nruns > 0 || l->line_x > l->line_left))
  5253. flush_line(l);
  5254. add_run(l, 0, 0, &gs, href, tmp);
  5255. if (!l->draw) {
  5256. int t = l->line_y < 0 ? 0 : l->line_y;
  5257. int hh = face_line_height(l->ui, &gs);
  5258. if (t > 65535)
  5259. t = 65535;
  5260. if (hh > 65535)
  5261. hh = 65535;
  5262. img_top[node] = (unsigned short)t;
  5263. img_h[node] = (unsigned short)hh;
  5264. }
  5265. return;
  5266. }
  5267. maxw = l->line_right - l->line_left;
  5268. if (maxw < 8)
  5269. maxw = 8;
  5270. {
  5271. int iw = bi->native_w, ih = bi->native_h;
  5272. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  5273. if (iw <= 0 || ih <= 0) {
  5274. iw = (int)bi->img.w;
  5275. ih = (int)bi->img.h;
  5276. }
  5277. dw = iw;
  5278. dh = ih;
  5279. if (doc.nodes[node].width_attr) {
  5280. int want = doc.nodes[node].width_attr;
  5281. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  5282. have_w = 1;
  5283. }
  5284. if (doc.nodes[node].height_attr) {
  5285. int want = doc.nodes[node].height_attr;
  5286. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  5287. have_h = 1;
  5288. }
  5289. if (have_w && !have_h)
  5290. dh = ih ? ih * dw / iw : 0;
  5291. if (have_h && !have_w)
  5292. dw = iw ? iw * dh / ih : 0;
  5293. if (st->width_kind) {
  5294. css_w = 1;
  5295. if (st->width_kind == 3)
  5296. dw = maxw * st->width_calc_pct / 100 +
  5297. st->width_calc_px;
  5298. else
  5299. dw = st->width_kind == 2 ?
  5300. maxw * (int)st->width / 100 :
  5301. (int)st->width;
  5302. }
  5303. if (st->height_kind) {
  5304. css_h = 1;
  5305. if (st->height_kind == 3)
  5306. dh = maxw * st->height_calc_pct / 100 +
  5307. st->height_calc_px;
  5308. else
  5309. dh = st->height_kind == 2 ?
  5310. maxw * (int)st->height / 100 :
  5311. (int)st->height;
  5312. }
  5313. if (css_w && !css_h)
  5314. dh = ih ? ih * dw / iw : 0;
  5315. if (css_h && !css_w)
  5316. dw = iw ? iw * dh / ih : 0;
  5317. if (st->max_width_kind) {
  5318. int mw = st->max_width_kind == 3 ?
  5319. maxw * st->max_width_calc_pct / 100 +
  5320. st->max_width_calc_px :
  5321. st->max_width_kind == 2 ?
  5322. maxw * (int)st->max_width / 100 :
  5323. (int)st->max_width;
  5324. if (mw > 0 && dw > mw) {
  5325. dh = iw ? ih * mw / iw : 0;
  5326. dw = mw;
  5327. }
  5328. }
  5329. }
  5330. if (dw < 8)
  5331. dw = 8;
  5332. if (dh < 8)
  5333. dh = 8;
  5334. if (dw > maxw) {
  5335. dh = dw ? dh * maxw / dw : dh;
  5336. dw = maxw;
  5337. }
  5338. if (!l->draw) {
  5339. int t = l->line_y < 0 ? 0 : l->line_y;
  5340. if (t > 65535)
  5341. t = 65535;
  5342. if (dh > 65535)
  5343. dh = 65535;
  5344. img_top[node] = (unsigned short)t;
  5345. img_h[node] = (unsigned short)dh;
  5346. }
  5347. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  5348. l->line_x > l->line_left))
  5349. flush_line(l);
  5350. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  5351. flush_line(l);
  5352. if (l->nruns == 0) {
  5353. l->line_y = l->y;
  5354. l->line_h = 0;
  5355. start_line(l, st);
  5356. }
  5357. {
  5358. struct lay_run *r = &l->runs[l->nruns++];
  5359. int gap = l->line_x - l->run_x;
  5360. if (gap < 0)
  5361. gap = 0;
  5362. r->gap = (unsigned short)gap;
  5363. r->off = 0;
  5364. r->len = 0;
  5365. r->color = 0;
  5366. r->href = href;
  5367. r->form = 0;
  5368. r->form_kind = 0;
  5369. r->form_disabled = 0;
  5370. /* Inline replaced elements honour their vertical margins; this
  5371. * is how Bootstrap's negative logo margins centre the wordmark. */
  5372. {
  5373. int idy = mp_px(st, 0, l->right - l->left);
  5374. if (idy < -2048)
  5375. idy = -2048;
  5376. if (idy > 2048)
  5377. idy = 2048;
  5378. r->dy = (signed short)idy;
  5379. }
  5380. r->has_lit = 0;
  5381. r->lit[0] = '\0';
  5382. r->img = (short)idx;
  5383. r->iw = (unsigned short)dw;
  5384. r->ih = (unsigned short)dh;
  5385. r->w = (unsigned short)dw;
  5386. r->font_px = st->font_px;
  5387. r->bold = st->bold;
  5388. r->italic = st->italic;
  5389. r->mono = st->mono;
  5390. r->font_face = st->font_face;
  5391. r->transform_scale = st->transform_scale;
  5392. r->scale_x = st->scale_x;
  5393. r->scale_y = st->scale_y;
  5394. r->rotate_x100 = st->rotate_x100;
  5395. r->origin_x = st->origin_x;
  5396. r->origin_y = st->origin_y;
  5397. r->origin_x_kind = st->origin_x_kind;
  5398. r->origin_y_kind = st->origin_y_kind;
  5399. r->underline = 0;
  5400. }
  5401. if (node < BR_MAX_NODES) {
  5402. layout_boxes[node].x = l->line_x;
  5403. layout_boxes[node].y = l->line_y +
  5404. mp_px(st, 0, l->right - l->left);
  5405. layout_boxes[node].w = dw;
  5406. layout_boxes[node].h = dh;
  5407. layout_boxes[node].valid = 1;
  5408. }
  5409. l->line_x += dw;
  5410. l->run_x = l->line_x;
  5411. if (l->line_h < dh)
  5412. l->line_h = dh;
  5413. }
  5414. static int text_width(struct lay *l, const char *s, unsigned int n,
  5415. const struct br_style *st)
  5416. {
  5417. return (int)face_text_width(l->ui, st, s, n);
  5418. }
  5419. /* Longest prefix that fits in maxw, at least one byte. */
  5420. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  5421. const struct br_style *st, int maxw)
  5422. {
  5423. unsigned int take = 0;
  5424. while (take < n) {
  5425. if (text_width(l, s, take + 1, st) > maxw)
  5426. break;
  5427. take++;
  5428. }
  5429. return take ? take : 1;
  5430. }
  5431. static void emit_word(struct lay *l, const char *s, unsigned int start,
  5432. unsigned int n, unsigned int base,
  5433. const struct br_style *st, unsigned short href)
  5434. {
  5435. int avail;
  5436. int w = text_width(l, s + start, n, st);
  5437. unsigned int off = start;
  5438. if (l->nruns == 0)
  5439. start_line(l, st);
  5440. avail = l->line_right - l->line_left;
  5441. if (st->nowrap) {
  5442. if (n)
  5443. add_run(l, base + start,
  5444. (unsigned short)n, st, href, 0);
  5445. return;
  5446. }
  5447. /* A padded/bordered one-word button can be a few pixels wider than
  5448. * the content box; keep it on one line instead of splitting it. */
  5449. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  5450. add_run(l, base + start,
  5451. (unsigned short)n, st, href, 0);
  5452. return;
  5453. }
  5454. if (l->line_x + w > l->line_right &&
  5455. (l->nruns > 0 || l->line_x > l->line_left)) {
  5456. flush_line(l);
  5457. start_line(l, st);
  5458. avail = l->line_right - l->line_left;
  5459. }
  5460. if (w <= avail) {
  5461. if (n)
  5462. add_run(l, base + start,
  5463. (unsigned short)n, st, href, 0);
  5464. return;
  5465. }
  5466. while (n > 0) {
  5467. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  5468. add_run(l, base + off,
  5469. (unsigned short)take, st, href, 0);
  5470. off += take;
  5471. n -= take;
  5472. if (n) {
  5473. flush_line(l);
  5474. start_line(l, st);
  5475. avail = l->line_right - l->line_left;
  5476. }
  5477. }
  5478. }
  5479. static void emit_text(struct lay *l, const char *s, unsigned int len,
  5480. const struct br_style *st, unsigned short href, int pre)
  5481. {
  5482. unsigned int i = 0;
  5483. unsigned int base;
  5484. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  5485. if (!s || !len)
  5486. return;
  5487. if (space_w <= 0)
  5488. space_w = 8;
  5489. if (l->nruns == 0)
  5490. start_line(l, st);
  5491. base = (unsigned int)(s - doc.text);
  5492. if (st->uppercase) {
  5493. char *p = (char *)s;
  5494. unsigned int j;
  5495. for (j = 0; j < len; j++)
  5496. if (p[j] >= 'a' && p[j] <= 'z')
  5497. p[j] = (char)(p[j] - 'a' + 'A');
  5498. }
  5499. if (pre) {
  5500. while (i < len) {
  5501. unsigned int start;
  5502. if (s[i] == '\n') {
  5503. flush_line(l);
  5504. start_line(l, st);
  5505. i++;
  5506. continue;
  5507. }
  5508. if (s[i] == ' ') {
  5509. if (l->line_x + space_w > l->line_right &&
  5510. (l->nruns > 0 || l->line_x > l->line_left)) {
  5511. flush_line(l);
  5512. start_line(l, st);
  5513. } else {
  5514. l->line_x += space_w;
  5515. }
  5516. i++;
  5517. continue;
  5518. }
  5519. start = i;
  5520. while (i < len && s[i] != ' ' && s[i] != '\n')
  5521. i++;
  5522. emit_word(l, s, start, i - start, base, st, href);
  5523. }
  5524. return;
  5525. }
  5526. while (i < len) {
  5527. unsigned int start, n;
  5528. if (s[i] == ' ') {
  5529. l->space_pending = 1;
  5530. i++;
  5531. continue;
  5532. }
  5533. start = i;
  5534. while (i < len && s[i] != ' ')
  5535. i++;
  5536. n = i - start;
  5537. if (l->space_pending &&
  5538. (l->nruns > 0 || l->line_x > l->line_left)) {
  5539. if (st->nowrap ||
  5540. l->line_x + space_w <= l->line_right)
  5541. l->line_x += space_w;
  5542. }
  5543. l->space_pending = 0;
  5544. emit_word(l, s, start, n, base, st, href);
  5545. }
  5546. }
  5547. static int list_index(unsigned int parent, unsigned int node)
  5548. {
  5549. unsigned int n = 0, i;
  5550. for (i = doc.nodes[parent].first; i && i != node;
  5551. i = doc.nodes[i].next)
  5552. if (doc.nodes[i].tag == BR_TAG_LI)
  5553. n++;
  5554. return (int)n + 1;
  5555. }
  5556. static void list_roman(char *m, unsigned int *n, int v, int upper,
  5557. unsigned int cap)
  5558. {
  5559. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  5560. 50, 40, 10, 9, 5, 4, 1 };
  5561. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  5562. "l", "xl", "x", "ix", "v", "iv", "i" };
  5563. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  5564. "L", "XL", "X", "IX", "V", "IV", "I" };
  5565. unsigned int i;
  5566. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  5567. while (v >= val[i] && *n + 1 < cap) {
  5568. const char *s = upper ? up[i] : lo[i];
  5569. while (*s && *n + 1 < cap)
  5570. m[(*n)++] = *s++;
  5571. v -= val[i];
  5572. }
  5573. }
  5574. }
  5575. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  5576. {
  5577. unsigned int n = 0;
  5578. if (style == BR_LIST_DISC) {
  5579. m[n++] = '-';
  5580. } else if (style == BR_LIST_CIRCLE) {
  5581. m[n++] = 'o';
  5582. } else if (style == BR_LIST_SQUARE) {
  5583. m[n++] = '+';
  5584. } else if (style == BR_LIST_LOWER_ALPHA ||
  5585. style == BR_LIST_UPPER_ALPHA) {
  5586. if (idx >= 1 && idx <= 26)
  5587. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  5588. 'A' : 'a') + idx - 1);
  5589. else
  5590. m[n++] = '?';
  5591. m[n++] = '.';
  5592. } else if (style == BR_LIST_LOWER_ROMAN ||
  5593. style == BR_LIST_UPPER_ROMAN) {
  5594. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  5595. if (n + 1 < cap)
  5596. m[n++] = '.';
  5597. } else {
  5598. s_append_dec(m, &n, (unsigned int)idx, cap);
  5599. if (n + 1 < cap)
  5600. m[n++] = '.';
  5601. }
  5602. m[n] = '\0';
  5603. }
  5604. /* Set by the layout when the control is stretched to its line: a flex item
  5605. * (its box width was assigned by the flex row) or a child of a flex column,
  5606. * whose default align-items: stretch makes inputs full width. */
  5607. static int form_fill_line;
  5608. static void add_form_run(struct lay *l, unsigned int node,
  5609. const struct br_style *st, unsigned short href)
  5610. {
  5611. struct form_state *fs = form_get(node, 1);
  5612. char shown[FORM_VALUE_MAX + 1];
  5613. char opt[64];
  5614. const char *text = "";
  5615. struct lay_run *r;
  5616. int kind = form_kind_of(node);
  5617. int disabled = form_disabled(node);
  5618. int tw, w = 120, h = 20, i;
  5619. if (!fs)
  5620. return;
  5621. if (l->nruns == 0)
  5622. start_line(l, st);
  5623. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  5624. text = "";
  5625. w = 16;
  5626. h = 16;
  5627. } else if (kind == FORM_SELECT) {
  5628. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  5629. s_copy(opt, "Select", sizeof(opt));
  5630. text = opt;
  5631. w = 120;
  5632. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  5633. kind == FORM_RESET) {
  5634. if (fs->len)
  5635. text = fs->value;
  5636. else
  5637. text = kind == FORM_SUBMIT ? "Submit" :
  5638. kind == FORM_RESET ? "Reset" : "Button";
  5639. } else if (kind == FORM_PASSWORD) {
  5640. for (i = 0; i < fs->len; i++)
  5641. shown[i] = '*';
  5642. shown[fs->len] = '\0';
  5643. text = fs->len ? shown : br_placeholder(&doc, node);
  5644. } else {
  5645. if (fs->len)
  5646. text = fs->value;
  5647. else
  5648. text = br_placeholder(&doc, node);
  5649. if (kind == FORM_TEXTAREA) {
  5650. w = 180;
  5651. h = 40;
  5652. }
  5653. }
  5654. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  5655. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  5656. w = tw + 18;
  5657. if (w < 64)
  5658. w = 64;
  5659. h = 22;
  5660. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD) {
  5661. int line_w = l->line_right - l->line_left;
  5662. if (st->width_kind == 1)
  5663. w = st->width;
  5664. else if (st->width_kind == 2)
  5665. w = css_size(st->width_kind, st->width, line_w);
  5666. else if (form_fill_line || st->display == BR_DISPLAY_BLOCK)
  5667. w = line_w - (l->line_x - l->line_left);
  5668. else
  5669. w = 120;
  5670. /* Taller fields for large text (min-height/padding on login
  5671. * pages): keep the box around the glyphs. */
  5672. if (st->font_px + 8 > h)
  5673. h = st->font_px + 8;
  5674. } else if (kind == FORM_SELECT) {
  5675. w = st->width_kind == 1 ? st->width : 120;
  5676. }
  5677. if (w > l->line_right - l->line_left)
  5678. w = l->line_right - l->line_left;
  5679. if (w < 8)
  5680. w = 8;
  5681. if (l->line_x + w > l->line_right &&
  5682. (l->nruns > 0 || l->line_x > l->line_left))
  5683. flush_line(l);
  5684. if (l->nruns >= 96)
  5685. return;
  5686. if (l->nruns == 0) {
  5687. l->line_y = l->y;
  5688. l->line_h = 0;
  5689. start_line(l, st);
  5690. }
  5691. r = &l->runs[l->nruns++];
  5692. r->gap = (unsigned short)(l->line_x - l->run_x);
  5693. r->off = r->len = 0;
  5694. r->color = st->color;
  5695. r->href = href;
  5696. r->dy = 0;
  5697. r->has_lit = 1;
  5698. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  5699. r->lit[i] = text[i];
  5700. r->lit[i] = '\0';
  5701. r->img = -2;
  5702. r->iw = (unsigned short)w;
  5703. r->ih = (unsigned short)h;
  5704. r->w = (unsigned short)w;
  5705. r->font_px = st->font_px;
  5706. r->bold = st->bold;
  5707. r->italic = st->italic;
  5708. r->mono = st->mono;
  5709. r->font_face = st->font_face;
  5710. r->underline = 0;
  5711. r->form = node + 1;
  5712. r->form_kind = (unsigned char)kind;
  5713. r->form_disabled = (unsigned char)disabled;
  5714. if (node < BR_MAX_NODES) {
  5715. layout_boxes[node].x = l->line_x;
  5716. layout_boxes[node].y = l->line_y;
  5717. layout_boxes[node].w = w;
  5718. layout_boxes[node].h = h;
  5719. layout_boxes[node].valid = 1;
  5720. }
  5721. l->line_x += w;
  5722. l->run_x = l->line_x;
  5723. if (l->line_h < h)
  5724. l->line_h = h;
  5725. }
  5726. /* A poster wrapper is absolutely positioned over the media slot; the
  5727. * measured height of its picture is normally added back to the flow. When a
  5728. * loading-skeleton sibling already reserves that slot, adding both doubles
  5729. * the media height and pushes the article text a full screen down. */
  5730. static int has_skeleton_sibling(unsigned int node)
  5731. {
  5732. unsigned int p = doc.nodes[node].parent, c;
  5733. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  5734. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  5735. continue;
  5736. if (doc.nodes[c].class_off &&
  5737. contains_ci(doc.attrs + doc.nodes[c].class_off,
  5738. "skeleton"))
  5739. return 1;
  5740. }
  5741. return 0;
  5742. }
  5743. static void layout_children(struct lay *l, unsigned int parent,
  5744. const struct br_style *pst, int depth,
  5745. unsigned short link);
  5746. static void layout_flex_children(struct lay *l, unsigned int parent,
  5747. const struct br_style *pst, int depth,
  5748. unsigned short link);
  5749. static void layout_grid_children(struct lay *l, unsigned int parent,
  5750. const struct br_style *pst, int depth,
  5751. unsigned short link);
  5752. static void layout_grid_auto(struct lay *l, unsigned int parent,
  5753. const struct br_style *pst, int depth,
  5754. unsigned short link);
  5755. static int flex_item_width(struct lay *l, unsigned int n,
  5756. const struct br_style *cs, int avail);
  5757. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  5758. const struct br_style *pst, int depth,
  5759. unsigned short link);
  5760. static void layout_table_row(struct lay *l, unsigned int row,
  5761. const struct br_style *pst, int depth,
  5762. unsigned short link);
  5763. static int table_has_rowspan(unsigned int table);
  5764. static void layout_table(struct lay *l, unsigned int table,
  5765. const struct br_style *st, int depth,
  5766. unsigned short link);
  5767. /* A flex container whose items are only inline spans is usually just a
  5768. * heading/icon pair. Our flex row positions such items without emitting
  5769. * their inline text in some deep page contexts; normal inline flow renders
  5770. * the same content correctly. */
  5771. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  5772. {
  5773. unsigned int c;
  5774. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  5775. struct br_node *nd = &doc.nodes[c];
  5776. struct br_style cs;
  5777. if (nd->type == BR_NODE_TEXT)
  5778. continue;
  5779. br_style_for(&doc, c, pst, &cs);
  5780. if (cs.display == BR_DISPLAY_NONE)
  5781. continue;
  5782. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  5783. cs.width_kind || cs.has_bg ||
  5784. cs.border_w[0] || cs.border_w[1] ||
  5785. cs.border_w[2] || cs.border_w[3] ||
  5786. nd->tag == BR_TAG_IMG)
  5787. return 1;
  5788. }
  5789. return 0;
  5790. }
  5791. static int css_radius(const struct br_style *st, int corner,
  5792. int w, int h)
  5793. {
  5794. int r = st->radius[corner];
  5795. if (r <= 0)
  5796. return 0;
  5797. if (r > w / 2)
  5798. r = w / 2;
  5799. if (r > h / 2)
  5800. r = h / 2;
  5801. return r;
  5802. }
  5803. /* ---- inline SVG ----
  5804. *
  5805. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  5806. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  5807. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  5808. * opacity and solid paint; a gradient paints the average of its stops) and
  5809. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  5810. #define SVG_CACHE_MAX 48
  5811. #define SVG_CACHE_PIXELS (640 * 1024)
  5812. #define SVG_MAX_POINTS 24576
  5813. struct svg_cache_ent {
  5814. unsigned int node;
  5815. int w, h;
  5816. unsigned short *px;
  5817. unsigned char *a;
  5818. unsigned int stamp;
  5819. };
  5820. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  5821. static unsigned int svg_cache_pixels, svg_cache_clock;
  5822. static struct svgr svg_geom;
  5823. static void *svg_geom_buf;
  5824. /* Current viewport in user units: percentage lengths resolve against it
  5825. * (the viewBox size, not the device pixels). */
  5826. static double svg_vp_w = 300, svg_vp_h = 150;
  5827. /* The layers live in the page heap: forget them before heap_reset(). */
  5828. static void svg_cache_clear(void)
  5829. {
  5830. memset(svg_cache, 0, sizeof(svg_cache));
  5831. svg_cache_pixels = 0;
  5832. svg_geom_buf = 0;
  5833. }
  5834. static int svg_name_is(const char *a, const char *b)
  5835. {
  5836. while (*a && *b) {
  5837. char x = *a, y = *b;
  5838. if (x >= 'A' && x <= 'Z')
  5839. x = (char)(x - 'A' + 'a');
  5840. if (x != y)
  5841. return 0;
  5842. a++;
  5843. b++;
  5844. }
  5845. return *a == *b;
  5846. }
  5847. static const char *svg_elem_name(unsigned int node)
  5848. {
  5849. const struct br_node *nd = &doc.nodes[node];
  5850. if (nd->name_off)
  5851. return doc.attrs + nd->name_off;
  5852. return br_tag_name(nd->tag);
  5853. }
  5854. /* A numeric attribute; a percentage resolves against `base`. */
  5855. static double svg_attr_num(unsigned int node, const char *name, double def,
  5856. double base)
  5857. {
  5858. const char *v = br_find_attr(&doc, node, name);
  5859. const char *p = v;
  5860. int ok = 0;
  5861. double x;
  5862. if (!v)
  5863. return def;
  5864. x = svgr_num(&p, &ok);
  5865. if (!ok)
  5866. return def;
  5867. if (*p == '%')
  5868. x = x * base / 100.0;
  5869. return x;
  5870. }
  5871. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  5872. static int svg_viewbox4(unsigned int node, double vb[4])
  5873. {
  5874. const char *v = br_find_attr(&doc, node, "viewbox");
  5875. const char *p = v;
  5876. int i, ok = 1;
  5877. if (!v)
  5878. return 0;
  5879. for (i = 0; i < 4 && ok; i++)
  5880. vb[i] = svgr_num(&p, &ok);
  5881. return ok && vb[2] > 0 && vb[3] > 0;
  5882. }
  5883. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  5884. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  5885. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  5886. double w, double h, double m[6])
  5887. {
  5888. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  5889. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  5890. int ax = 1, ay = 1;
  5891. if (par && contains_ci(par, "none")) {
  5892. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  5893. m[4] = -vb[0] * sx;
  5894. m[5] = -vb[1] * sy;
  5895. return;
  5896. }
  5897. if (par) {
  5898. if (contains_ci(par, "xmin"))
  5899. ax = 0;
  5900. else if (contains_ci(par, "xmax"))
  5901. ax = 2;
  5902. if (contains_ci(par, "ymin"))
  5903. ay = 0;
  5904. else if (contains_ci(par, "ymax"))
  5905. ay = 2;
  5906. }
  5907. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  5908. (sx < sy ? sx : sy);
  5909. tx = (w - vb[2] * s) * ax / 2.0;
  5910. ty = (h - vb[3] * s) * ay / 2.0;
  5911. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  5912. m[4] = tx - vb[0] * s;
  5913. m[5] = ty - vb[1] * s;
  5914. }
  5915. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  5916. * the paint attribute, then average the gradient's stops. */
  5917. static int svg_url_paint(unsigned int node, const char *attr,
  5918. unsigned short *color, unsigned int *alpha)
  5919. {
  5920. const char *v = 0, *h;
  5921. char id[64];
  5922. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  5923. for (k = 0; node && k < 32 && !v; k++) {
  5924. v = br_find_attr(&doc, node, attr);
  5925. if (!v) {
  5926. const char *style = br_find_attr(&doc, node, "style");
  5927. if (style && contains_ci(style, "url(#"))
  5928. v = strstr(style, "url(#");
  5929. }
  5930. if (v && !contains_ci(v, "url("))
  5931. v = 0;
  5932. node = doc.nodes[node].parent;
  5933. }
  5934. if (!v || !(h = strstr(v, "#")))
  5935. return 0;
  5936. h++;
  5937. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  5938. id[n++] = *h++;
  5939. id[n] = '\0';
  5940. g = br_find_id(&doc, id);
  5941. /* Follow href chains (a gradient that only references another one's
  5942. * stops), at most a few hops. */
  5943. for (k = 0; g && k < 4; k++) {
  5944. unsigned int gi = g - 1;
  5945. const char *ref;
  5946. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  5947. const char *nm, *sc, *so;
  5948. unsigned short col = 0;
  5949. double op = 1;
  5950. if (doc.nodes[c].type != BR_NODE_ELEM)
  5951. continue;
  5952. nm = svg_elem_name(c);
  5953. if (!svg_name_is(nm, "stop"))
  5954. continue;
  5955. sc = br_find_attr(&doc, c, "stop-color");
  5956. so = br_find_attr(&doc, c, "stop-opacity");
  5957. {
  5958. const char *st = br_find_attr(&doc, c, "style");
  5959. const char *q;
  5960. if (st && (q = strstr(st, "stop-color:")) != 0)
  5961. sc = q + 11;
  5962. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  5963. so = q + 13;
  5964. }
  5965. if (sc) {
  5966. unsigned int L = 0;
  5967. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  5968. L++;
  5969. if (!br_parse_color(sc, L, &col))
  5970. col = 0;
  5971. }
  5972. if (so) {
  5973. const char *p = so;
  5974. int ok = 0;
  5975. double x = svgr_num(&p, &ok);
  5976. if (ok)
  5977. op = x < 0 ? 0 : x > 1 ? 1 : x;
  5978. }
  5979. sr += (col >> 11) & 31;
  5980. sg += (col >> 5) & 63;
  5981. sb += col & 31;
  5982. sa += (unsigned int)(op * 255);
  5983. cnt++;
  5984. }
  5985. if (cnt)
  5986. break;
  5987. ref = br_find_attr(&doc, gi, "href");
  5988. if (!ref)
  5989. ref = br_find_attr(&doc, gi, "xlink:href");
  5990. if (!ref || ref[0] != '#')
  5991. break;
  5992. g = br_find_id(&doc, ref + 1);
  5993. }
  5994. if (!cnt)
  5995. return 0;
  5996. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  5997. (sb / cnt));
  5998. *alpha = sa / cnt;
  5999. return 1;
  6000. }
  6001. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  6002. unsigned short *color, unsigned int *alpha)
  6003. {
  6004. int mode = fill ? st->fill_mode : st->stroke_mode;
  6005. const char *op = br_find_attr(&doc, node,
  6006. fill ? "fill-opacity" : "stroke-opacity");
  6007. *alpha = 255;
  6008. switch (mode) {
  6009. case BR_PAINT_UNSET:
  6010. if (!fill)
  6011. return 0;
  6012. *color = 0;
  6013. break;
  6014. case BR_PAINT_COLOR:
  6015. *color = fill ? st->fill : st->stroke;
  6016. break;
  6017. case BR_PAINT_CURRENT:
  6018. *color = st->color;
  6019. break;
  6020. case BR_PAINT_URL:
  6021. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  6022. alpha))
  6023. return 0;
  6024. break;
  6025. default:
  6026. return 0;
  6027. }
  6028. if (op) {
  6029. const char *p = op;
  6030. int ok = 0;
  6031. double x = svgr_num(&p, &ok);
  6032. if (ok)
  6033. *alpha = (unsigned int)(*alpha *
  6034. (x < 0 ? 0 : x > 1 ? 1 : x));
  6035. }
  6036. return *alpha > 0;
  6037. }
  6038. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  6039. const double m[6], const struct br_style *pst,
  6040. unsigned int alpha, int depth);
  6041. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  6042. const double m[6], const struct br_style *st,
  6043. unsigned int alpha, int depth)
  6044. {
  6045. unsigned int c;
  6046. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  6047. if (doc.nodes[c].type == BR_NODE_ELEM)
  6048. svg_draw_node(L, c, m, st, alpha, depth + 1);
  6049. }
  6050. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  6051. const double pm[6], const struct br_style *pst,
  6052. unsigned int alpha, int depth)
  6053. {
  6054. struct br_style st;
  6055. const char *nm = svg_elem_name(node);
  6056. const char *tf;
  6057. double m[6];
  6058. unsigned short color;
  6059. unsigned int pa;
  6060. int shape = 0, fillable = 1;
  6061. if (depth > 24 || !nm)
  6062. return;
  6063. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  6064. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  6065. svg_name_is(nm, "lineargradient") ||
  6066. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  6067. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  6068. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  6069. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  6070. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  6071. svg_name_is(nm, "foreignobject"))
  6072. return;
  6073. br_style_for(&doc, node, pst, &st);
  6074. if (st.display == BR_DISPLAY_NONE)
  6075. return;
  6076. memcpy(m, pm, sizeof(m));
  6077. tf = br_find_attr(&doc, node, "transform");
  6078. if (tf)
  6079. svgr_transform(m, tf);
  6080. {
  6081. const char *op = br_find_attr(&doc, node, "opacity");
  6082. if (op) {
  6083. const char *p = op;
  6084. int ok = 0;
  6085. double x = svgr_num(&p, &ok);
  6086. if (ok)
  6087. alpha = (unsigned int)(alpha *
  6088. (x < 0 ? 0 :
  6089. x > 1 ? 1 : x));
  6090. }
  6091. }
  6092. if (!alpha)
  6093. return;
  6094. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  6095. svg_name_is(nm, "switch")) {
  6096. svg_draw_children(L, node, m, &st, alpha, depth);
  6097. return;
  6098. }
  6099. if (svg_name_is(nm, "svg")) {
  6100. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  6101. y = svg_attr_num(node, "y", 0, 0);
  6102. double t[6] = { 1, 0, 0, 1, 0, 0 };
  6103. t[4] = x;
  6104. t[5] = y;
  6105. svgr_mat_mul(m, m, t);
  6106. double ow = svg_vp_w, oh = svg_vp_h;
  6107. if (svg_viewbox4(node, vb)) {
  6108. double w = svg_attr_num(node, "width", vb[2], ow);
  6109. double h = svg_attr_num(node, "height", vb[3], oh);
  6110. double vm[6];
  6111. svg_viewport_matrix(node, vb, w, h, vm);
  6112. svgr_mat_mul(m, m, vm);
  6113. svg_vp_w = vb[2];
  6114. svg_vp_h = vb[3];
  6115. }
  6116. svg_draw_children(L, node, m, &st, alpha, depth);
  6117. svg_vp_w = ow;
  6118. svg_vp_h = oh;
  6119. return;
  6120. }
  6121. if (svg_name_is(nm, "use")) {
  6122. const char *ref = br_find_attr(&doc, node, "href");
  6123. unsigned int tgt;
  6124. double t[6] = { 1, 0, 0, 1, 0, 0 };
  6125. if (!ref)
  6126. ref = br_find_attr(&doc, node, "xlink:href");
  6127. if (!ref || ref[0] != '#')
  6128. return;
  6129. tgt = br_find_id(&doc, ref + 1);
  6130. if (!tgt || tgt - 1 == node)
  6131. return;
  6132. tgt--;
  6133. t[4] = svg_attr_num(node, "x", 0, 0);
  6134. t[5] = svg_attr_num(node, "y", 0, 0);
  6135. svgr_mat_mul(m, m, t);
  6136. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  6137. double vb[4];
  6138. double ow = svg_vp_w, oh = svg_vp_h;
  6139. if (svg_viewbox4(tgt, vb)) {
  6140. double w = svg_attr_num(node, "width", vb[2],
  6141. ow);
  6142. double h = svg_attr_num(node, "height", vb[3],
  6143. oh);
  6144. double vm[6];
  6145. svg_viewport_matrix(tgt, vb, w, h, vm);
  6146. svgr_mat_mul(m, m, vm);
  6147. svg_vp_w = vb[2];
  6148. svg_vp_h = vb[3];
  6149. }
  6150. svg_draw_children(L, tgt, m, &st, alpha, depth);
  6151. svg_vp_w = ow;
  6152. svg_vp_h = oh;
  6153. } else {
  6154. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  6155. }
  6156. return;
  6157. }
  6158. svgr_reset(&svg_geom, m);
  6159. if (svg_name_is(nm, "path")) {
  6160. const char *d = br_find_attr(&doc, node, "d");
  6161. if (d) {
  6162. svgr_path(&svg_geom, d);
  6163. shape = 1;
  6164. }
  6165. } else if (svg_name_is(nm, "rect")) {
  6166. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  6167. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  6168. double rx = svg_attr_num(node, "rx", -1, w);
  6169. double ry = svg_attr_num(node, "ry", -1, h);
  6170. if (rx < 0)
  6171. rx = ry < 0 ? 0 : ry;
  6172. if (ry < 0)
  6173. ry = rx;
  6174. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  6175. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  6176. shape = 1;
  6177. } else if (svg_name_is(nm, "circle")) {
  6178. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  6179. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  6180. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  6181. shape = 1;
  6182. } else if (svg_name_is(nm, "ellipse")) {
  6183. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  6184. svg_attr_num(node, "cy", 0, svg_vp_h),
  6185. svg_attr_num(node, "rx", 0, svg_vp_w),
  6186. svg_attr_num(node, "ry", 0, svg_vp_h));
  6187. shape = 1;
  6188. } else if (svg_name_is(nm, "line")) {
  6189. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  6190. svg_attr_num(node, "y1", 0, svg_vp_h));
  6191. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  6192. svg_attr_num(node, "y2", 0, svg_vp_h));
  6193. shape = 1;
  6194. fillable = 0;
  6195. } else if (svg_name_is(nm, "polyline") ||
  6196. svg_name_is(nm, "polygon")) {
  6197. const char *pts = br_find_attr(&doc, node, "points");
  6198. if (pts) {
  6199. svgr_points(&svg_geom, pts,
  6200. svg_name_is(nm, "polygon"));
  6201. shape = 1;
  6202. }
  6203. }
  6204. if (!shape)
  6205. return;
  6206. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  6207. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  6208. st.fill_evenodd);
  6209. if (svg_paint(node, &st, 0, &color, &pa)) {
  6210. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  6211. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  6212. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  6213. }
  6214. }
  6215. /* <text> elements: drawn straight onto the page every frame (the glyph
  6216. * renderer targets the ngui canvas, not a layer). x/y map through the
  6217. * accumulated transform; the font size scales with it. */
  6218. static void svg_draw_text(struct ngui *ui, unsigned int node,
  6219. const double pm[6], const struct br_style *pst,
  6220. int ox, int oy, int depth)
  6221. {
  6222. unsigned int c;
  6223. if (depth > 24)
  6224. return;
  6225. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  6226. struct br_style st;
  6227. const char *nm, *tf;
  6228. double m[6];
  6229. if (doc.nodes[c].type != BR_NODE_ELEM)
  6230. continue;
  6231. nm = svg_elem_name(c);
  6232. if (!nm || svg_name_is(nm, "defs") ||
  6233. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  6234. svg_name_is(nm, "clippath"))
  6235. continue;
  6236. br_style_for(&doc, c, pst, &st);
  6237. if (st.display == BR_DISPLAY_NONE)
  6238. continue;
  6239. memcpy(m, pm, sizeof(m));
  6240. tf = br_find_attr(&doc, c, "transform");
  6241. if (tf)
  6242. svgr_transform(m, tf);
  6243. if (svg_name_is(nm, "text")) {
  6244. unsigned int t = doc.nodes[c].first;
  6245. const char *s;
  6246. unsigned int n, tw;
  6247. double x = svg_attr_num(c, "x", 0, 0),
  6248. y = svg_attr_num(c, "y", 0, 0);
  6249. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  6250. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  6251. int tx, ty, anchor;
  6252. unsigned short col;
  6253. unsigned int pa;
  6254. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  6255. continue;
  6256. if (px < 6)
  6257. px = 6;
  6258. if (px > 72)
  6259. px = 72;
  6260. if (!svg_paint(c, &st, 1, &col, &pa))
  6261. continue;
  6262. s = doc.text + doc.nodes[t].text_off;
  6263. n = doc.nodes[t].text_len;
  6264. st.font_px = (unsigned char)px;
  6265. tw = face_text_width(ui, &st, s, n);
  6266. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  6267. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  6268. ngui_text_ascent_face(ui, style_face(&st), px,
  6269. st.mono);
  6270. anchor = st.align;
  6271. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  6272. anchor = BR_ALIGN_CENTER;
  6273. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  6274. anchor = BR_ALIGN_RIGHT;
  6275. if (anchor == BR_ALIGN_CENTER)
  6276. tx -= (int)tw / 2;
  6277. else if (anchor == BR_ALIGN_RIGHT)
  6278. tx -= (int)tw;
  6279. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  6280. col, px, st.bold, st.italic,
  6281. st.mono);
  6282. } else {
  6283. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  6284. }
  6285. }
  6286. }
  6287. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  6288. {
  6289. double vb[4];
  6290. if (svg_viewbox4(node, vb)) {
  6291. svg_viewport_matrix(node, vb, w, h, m);
  6292. } else {
  6293. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  6294. }
  6295. }
  6296. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  6297. const struct br_style *st)
  6298. {
  6299. struct svg_cache_ent *e = 0;
  6300. struct svgr_layer L;
  6301. double m[6];
  6302. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  6303. svg_cache_clock++;
  6304. for (i = 0; i < SVG_CACHE_MAX; i++)
  6305. if (svg_cache[i].px && svg_cache[i].node == node &&
  6306. svg_cache[i].w == w && svg_cache[i].h == h) {
  6307. svg_cache[i].stamp = svg_cache_clock;
  6308. return &svg_cache[i];
  6309. }
  6310. if (need > SVG_CACHE_PIXELS)
  6311. return 0;
  6312. /* Evict least recently used layers until this one fits. */
  6313. for (;;) {
  6314. struct svg_cache_ent *lru = 0, *free_slot = 0;
  6315. for (i = 0; i < SVG_CACHE_MAX; i++) {
  6316. if (!svg_cache[i].px) {
  6317. if (!free_slot)
  6318. free_slot = &svg_cache[i];
  6319. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  6320. lru = &svg_cache[i];
  6321. }
  6322. }
  6323. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  6324. e = free_slot;
  6325. break;
  6326. }
  6327. if (!lru)
  6328. return 0;
  6329. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  6330. free(lru->px);
  6331. free(lru->a);
  6332. memset(lru, 0, sizeof(*lru));
  6333. }
  6334. if (!svg_geom_buf) {
  6335. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  6336. if (!svg_geom_buf)
  6337. return 0;
  6338. }
  6339. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  6340. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  6341. e->a = (unsigned char *)calloc(need, 1);
  6342. if (!e->px || !e->a) {
  6343. free(e->px);
  6344. free(e->a);
  6345. memset(e, 0, sizeof(*e));
  6346. return 0;
  6347. }
  6348. e->node = node;
  6349. e->w = w;
  6350. e->h = h;
  6351. e->stamp = svg_cache_clock;
  6352. svg_cache_pixels += need;
  6353. L.px = e->px;
  6354. L.a = e->a;
  6355. L.w = w;
  6356. L.h = h;
  6357. svg_root_matrix(node, w, h, m);
  6358. {
  6359. double vb[4];
  6360. if (svg_viewbox4(node, vb)) {
  6361. svg_vp_w = vb[2];
  6362. svg_vp_h = vb[3];
  6363. } else {
  6364. svg_vp_w = w;
  6365. svg_vp_h = h;
  6366. }
  6367. }
  6368. svg_draw_children(&L, node, m, st, 255, 0);
  6369. return e;
  6370. }
  6371. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  6372. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  6373. int *out_w, int *out_h)
  6374. {
  6375. double vb[4];
  6376. int has_vb = svg_viewbox4(node, vb);
  6377. double aw = svg_attr_num(node, "width", -1, cw);
  6378. double ah = svg_attr_num(node, "height", -1, 0);
  6379. int w, h;
  6380. if (st->width_kind)
  6381. w = cw;
  6382. else if (aw > 0)
  6383. w = (int)(aw + 0.5);
  6384. else if (st->height_kind == 1 && has_vb)
  6385. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  6386. else if (ah > 0 && has_vb)
  6387. w = (int)(ah * vb[2] / vb[3] + 0.5);
  6388. else if (has_vb)
  6389. w = cw;
  6390. else
  6391. w = 300;
  6392. if (st->max_width_kind == 1 && w > st->max_width)
  6393. w = st->max_width;
  6394. if (w > cw && cw > 0 && !(aw > 0))
  6395. w = cw;
  6396. if (w < 1)
  6397. w = 1;
  6398. if (w > 2000)
  6399. w = 2000;
  6400. if (st->height_kind == 1)
  6401. h = st->height;
  6402. else if (ah > 0)
  6403. h = (int)(ah + 0.5);
  6404. else if (has_vb)
  6405. h = (int)(w * vb[3] / vb[2] + 0.5);
  6406. else
  6407. h = 150;
  6408. if (h < 1)
  6409. h = 1;
  6410. if (h > 1400)
  6411. h = 1400;
  6412. *out_w = w;
  6413. *out_h = h;
  6414. }
  6415. static void svg_paint_box(struct ngui *ui, unsigned int node,
  6416. const struct br_style *st, int x, int y, int w, int h)
  6417. {
  6418. struct svg_cache_ent *e;
  6419. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  6420. int cx0, cy0, cx1, cy1, px, py;
  6421. double m[6];
  6422. if (ui->nclip > 0)
  6423. clip = ui->clip[ui->nclip - 1];
  6424. cx0 = r.x > clip.x ? r.x : clip.x;
  6425. cy0 = r.y > clip.y ? r.y : clip.y;
  6426. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  6427. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  6428. if (cx0 >= cx1 || cy0 >= cy1)
  6429. return;
  6430. e = svg_layer(node, w, h, st);
  6431. if (e) {
  6432. for (py = cy0; py < cy1; py++) {
  6433. unsigned int srow = (unsigned int)(py - y) *
  6434. (unsigned int)w;
  6435. unsigned short *dst = ui->px + py * ui->w;
  6436. for (px = cx0; px < cx1; px++) {
  6437. unsigned int si = srow + (unsigned int)(px - x);
  6438. unsigned int a = e->a[si];
  6439. if (!a)
  6440. continue;
  6441. dst[px] = a >= 255 ? e->px[si] :
  6442. blend_rgb565(dst[px], e->px[si], a);
  6443. }
  6444. }
  6445. }
  6446. svg_root_matrix(node, w, h, m);
  6447. ngui_push_clip(ui, r);
  6448. svg_draw_text(ui, node, m, st, x, y, 0);
  6449. ngui_pop_clip(ui);
  6450. }
  6451. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  6452. * keep using add_image_run(); this covers the CSS `position:absolute;
  6453. * width:100%` poster pattern used by news sites. */
  6454. static void image_block_size(unsigned int node, const struct br_style *st,
  6455. int cbw, int *out_w, int *out_h)
  6456. {
  6457. struct br_node *nd = &doc.nodes[node];
  6458. int idx = nd->img_index;
  6459. int iw = 0, ih = 0, w, h;
  6460. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  6461. iw = (int)images[idx].img.w;
  6462. ih = (int)images[idx].img.h;
  6463. if (iw <= 0 || ih <= 0) {
  6464. iw = (int)images[idx].native_w;
  6465. ih = (int)images[idx].native_h;
  6466. }
  6467. }
  6468. if (st->width_kind)
  6469. w = style_width_px(st, cbw);
  6470. else if (nd->width_attr)
  6471. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  6472. (int)nd->width_attr;
  6473. else if (iw)
  6474. w = iw;
  6475. else
  6476. w = 64;
  6477. if (w < 8)
  6478. w = 8;
  6479. if (cbw > 0 && w > cbw)
  6480. w = cbw;
  6481. if (st->height_kind)
  6482. h = style_height_px(st, cbw);
  6483. else if (nd->height_attr)
  6484. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  6485. (int)nd->height_attr;
  6486. else if (iw && ih)
  6487. h = w * ih / iw;
  6488. else
  6489. h = 64;
  6490. if (h < 8)
  6491. h = 8;
  6492. *out_w = w;
  6493. *out_h = h;
  6494. }
  6495. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  6496. int dw, int dh)
  6497. {
  6498. int idx = doc.nodes[node].img_index;
  6499. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  6500. struct img_blit b;
  6501. b.dst = l->ui->px;
  6502. b.dst_w = l->ui->w;
  6503. b.dst_h = l->ui->h;
  6504. b.clip_x = page_rect.x;
  6505. b.clip_y = page_rect.y;
  6506. b.clip_w = page_rect.w - 12;
  6507. b.clip_h = page_rect.h;
  6508. b.x = x;
  6509. b.y = y;
  6510. b.scale = ((unsigned int)dw << 16) / images[idx].img.w;
  6511. b.bg = ui.theme.bg;
  6512. b.bg2 = ui.theme.bg;
  6513. b.flags = IMG_BLIT_OVER_DST;
  6514. img_draw(&images[idx].img, &b);
  6515. } else if (l->draw) {
  6516. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  6517. 0xD69A);
  6518. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  6519. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  6520. }
  6521. }
  6522. static void layout_block(struct lay *l, unsigned int node,
  6523. const struct br_style *st, int depth,
  6524. unsigned short link)
  6525. {
  6526. int old_left = l->left, old_right = l->right, old_align = l->align;
  6527. int parent_cb_h = l->cb_h;
  6528. int saved_parent_top = l->parent_top;
  6529. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  6530. int saved_cb_top = l->cb_top;
  6531. int top, l0, r0;
  6532. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  6533. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  6534. int deco_w, deco_h, content_w, content_h, box_h;
  6535. int img_dh = 0;
  6536. int definite_w = 0;
  6537. int normal_top = 0;
  6538. int rel_dx = 0, rel_dy = 0;
  6539. int clip_pushed = 0;
  6540. struct ngui_rect clip_rect;
  6541. /* A DOM level costs about two depth units (layout_block ->
  6542. * layout_children), so 48 covers a ~24-level page. Real news pages
  6543. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  6544. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  6545. return;
  6546. flow_y = l->y;
  6547. flow_left = l->left;
  6548. flow_right = l->right;
  6549. positioned = st->pos == 1 || st->pos == 2;
  6550. relative = st->pos == 3;
  6551. sticky = st->pos == 4;
  6552. shifted = relative || sticky || st->transform_set;
  6553. if (positioned) {
  6554. int def_w = st->width_kind == 1 ? st->width : -1;
  6555. if (st->pos == 2) {
  6556. int avail_w = page_rect.w - 12;
  6557. if (st->right_set && def_w >= 0)
  6558. l->left = page_rect.x + avail_w - st->right -
  6559. def_w;
  6560. else
  6561. l->left = page_rect.x +
  6562. (st->left_set ? st->left : 0);
  6563. l->right = def_w >= 0 ? l->left + def_w :
  6564. page_rect.x + avail_w;
  6565. if (st->bottom_set && st->height_kind)
  6566. l->y = page_rect.y + page_rect.h -
  6567. st->bottom -
  6568. style_height_px(st, page_rect.w);
  6569. else
  6570. l->y = page_rect.y +
  6571. (st->top_set ? st->top : 0);
  6572. } else {
  6573. int left = flow_left + (st->left_set ? st->left : 0);
  6574. unsigned int parent = doc.nodes[node].parent;
  6575. if (st->right_set && def_w >= 0)
  6576. left = flow_right - st->right - def_w;
  6577. l->left = left;
  6578. l->right = def_w >= 0 ? left + def_w :
  6579. flow_right +
  6580. (st->left_set ? st->left : 0);
  6581. l->y = flow_y + (st->top_set ? st->top : 0);
  6582. if (st->bottom_set && st->height_kind &&
  6583. parent < BR_MAX_NODES && block_h[parent] > 0)
  6584. l->y = flow_y + block_h[parent] - st->bottom -
  6585. style_height_px(st, old_right - old_left);
  6586. }
  6587. old_left = l->left;
  6588. old_right = l->right;
  6589. } else if (relative) {
  6590. rel_dx = st->left_set ? st->left :
  6591. (st->right_set ? -st->right : 0);
  6592. rel_dy = st->top_set ? st->top :
  6593. (st->bottom_set ? -st->bottom : 0);
  6594. }
  6595. if (st->transform_set) {
  6596. rel_dx += st->tx;
  6597. rel_dy += st->ty;
  6598. }
  6599. if (doc.nodes[node].tag == BR_TAG_INPUT ||
  6600. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  6601. doc.nodes[node].tag == BR_TAG_SELECT ||
  6602. doc.nodes[node].tag == BR_TAG_BUTTON) {
  6603. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  6604. s_eq(br_type(&doc, node), "hidden"))
  6605. return;
  6606. /* Reached as a block-level box (a flex item): the control
  6607. * fills the box the caller assigned, and its line is flushed
  6608. * here; flex layout resets the run list for the next item, so
  6609. * a queued run would never be drawn. */
  6610. form_fill_line = 1;
  6611. add_form_run(l, node, st, link);
  6612. form_fill_line = 0;
  6613. flush_line(l);
  6614. return;
  6615. }
  6616. flush_line(l);
  6617. cbw = old_right - old_left;
  6618. if (cbw < 8)
  6619. cbw = 8;
  6620. l->y += mp_px(st, 0, cbw);
  6621. top = l->y;
  6622. ml = mp_px(st, 3, cbw);
  6623. mr = mp_px(st, 1, cbw);
  6624. bl = st->border_w[3];
  6625. br = st->border_w[1];
  6626. pl = mp_px(st, 7, cbw);
  6627. pr = mp_px(st, 5, cbw);
  6628. bt = st->border_w[0];
  6629. bb = st->border_w[2];
  6630. pt = mp_px(st, 4, cbw);
  6631. pb = mp_px(st, 6, cbw);
  6632. deco_w = bl + br + pl + pr;
  6633. deco_h = bt + bb + pt + pb;
  6634. if (st->width_kind) {
  6635. int w;
  6636. if (st->width_kind == 3)
  6637. w = cbw * st->width_calc_pct / 100 +
  6638. st->width_calc_px;
  6639. else
  6640. w = css_size(st->width_kind, st->width, cbw);
  6641. if (w < 0)
  6642. w = 0;
  6643. content_w = st->box_sizing ? w - deco_w : w;
  6644. definite_w = 1;
  6645. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  6646. doc.nodes[node].tag == BR_TAG_TD ||
  6647. doc.nodes[node].tag == BR_TAG_TH) &&
  6648. doc.nodes[node].width_attr) {
  6649. /* Legacy table/cell width attributes: percentages resolve
  6650. * against the containing block, bare numbers are pixels. */
  6651. int w = doc.nodes[node].width_pct ?
  6652. cbw * doc.nodes[node].width_attr / 100 :
  6653. doc.nodes[node].width_attr;
  6654. if (w < 0)
  6655. w = 0;
  6656. content_w = st->box_sizing ? w - deco_w : w;
  6657. definite_w = 1;
  6658. } else {
  6659. content_w = cbw - ml - mr - deco_w;
  6660. }
  6661. if (content_w < 0)
  6662. content_w = 0;
  6663. if (st->max_width_kind) {
  6664. int mw = st->max_width_kind == 3 ?
  6665. cbw * st->max_width_calc_pct / 100 +
  6666. st->max_width_calc_px :
  6667. css_size(st->max_width_kind, st->max_width, cbw);
  6668. int max_box = st->box_sizing ? mw : mw + deco_w;
  6669. if (content_w + deco_w > max_box)
  6670. content_w = max_box - deco_w;
  6671. }
  6672. if (st->min_width_kind) {
  6673. int mw = st->min_width_kind == 3 ?
  6674. cbw * st->min_width_calc_pct / 100 +
  6675. st->min_width_calc_px :
  6676. css_size(st->min_width_kind, st->min_width, cbw);
  6677. int min_box = st->box_sizing ? mw : mw + deco_w;
  6678. if (content_w + deco_w < min_box) {
  6679. content_w = min_box - deco_w;
  6680. definite_w = 1;
  6681. }
  6682. }
  6683. if (content_w < 8)
  6684. content_w = 8;
  6685. if (definite_w) {
  6686. int free_w = cbw - ml - mr - deco_w - content_w;
  6687. if (free_w < 0)
  6688. free_w = 0;
  6689. if (st->ml_auto && st->mr_auto) {
  6690. ml = free_w / 2;
  6691. mr = free_w - ml;
  6692. } else if (st->ml_auto) {
  6693. ml = free_w;
  6694. } else if (st->mr_auto) {
  6695. mr = free_w;
  6696. }
  6697. }
  6698. if (doc.nodes[node].tag == BR_TAG_IMG) {
  6699. int iw, ih;
  6700. image_block_size(node, st, cbw, &iw, &ih);
  6701. content_w = iw;
  6702. img_dh = ih;
  6703. }
  6704. l0 = old_left + ml;
  6705. r0 = l0 + deco_w + content_w;
  6706. if (r0 < l0 + 8)
  6707. r0 = l0 + 8;
  6708. normal_top = top;
  6709. if (sticky) {
  6710. if (st->top_set) {
  6711. int stick = page_rect.y + 4 + st->top;
  6712. if (normal_top < stick)
  6713. rel_dy += stick - normal_top;
  6714. } else if (st->bottom_set && block_h[node]) {
  6715. int stick = page_rect.y + page_rect.h - st->bottom -
  6716. block_h[node];
  6717. if (normal_top > stick)
  6718. rel_dy += stick - normal_top;
  6719. }
  6720. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  6721. block_h[doc.nodes[node].parent]) {
  6722. unsigned int p = doc.nodes[node].parent;
  6723. int ptop = l->parent_top;
  6724. int pbottom = ptop + block_h[p];
  6725. int eh = block_h[node];
  6726. int moved_top = normal_top + rel_dy;
  6727. int moved_bottom = moved_top + eh;
  6728. if (moved_bottom > pbottom)
  6729. rel_dy -= moved_bottom - pbottom;
  6730. moved_top = normal_top + rel_dy;
  6731. if (moved_top < ptop)
  6732. rel_dy += ptop - moved_top;
  6733. }
  6734. }
  6735. if (shifted && l->draw) {
  6736. top += rel_dy;
  6737. l0 += rel_dx;
  6738. r0 += rel_dx;
  6739. }
  6740. l->parent_top = top;
  6741. if (st->pos != 0) {
  6742. /* Positioned boxes establish the containing block for their
  6743. * absolutely positioned descendants. */
  6744. l->cb_left = l0;
  6745. l->cb_right = r0;
  6746. l->cb_top = top;
  6747. }
  6748. if (l->draw && block_h[node] &&
  6749. top < page_rect.y + page_rect.h &&
  6750. top + block_h[node] > page_rect.y) {
  6751. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  6752. int rtl = css_radius(st, 0, box.w, box.h);
  6753. int rtr = css_radius(st, 1, box.w, box.h);
  6754. int rbr = css_radius(st, 2, box.w, box.h);
  6755. int rbl = css_radius(st, 3, box.w, box.h);
  6756. if (st->transform_scale) {
  6757. if (st->has_bg)
  6758. fill_transformed_rect(l->ui, box, st->bg, st);
  6759. } else if (rtl || rtr || rbr || rbl) {
  6760. if (st->has_bg) {
  6761. int bw = st->border_w[0];
  6762. if (bw > 0 && !st->border_t[0] &&
  6763. st->border_c[0] != st->bg &&
  6764. box.w > bw * 2 && box.h > bw * 2) {
  6765. struct ngui_rect inner = {
  6766. box.x + bw, box.y + bw,
  6767. box.w - bw * 2, box.h - bw * 2
  6768. };
  6769. int itl = rtl > bw ? rtl - bw : 0;
  6770. int itr = rtr > bw ? rtr - bw : 0;
  6771. int ibr = rbr > bw ? rbr - bw : 0;
  6772. int ibl = rbl > bw ? rbl - bw : 0;
  6773. ngui_fill_round_rect(l->ui, box, rtl,
  6774. rtr, rbr, rbl,
  6775. st->border_c[0]);
  6776. ngui_fill_round_rect(l->ui, inner,
  6777. itl, itr, ibr,
  6778. ibl, st->bg);
  6779. } else {
  6780. ngui_fill_round_rect(l->ui, box, rtl,
  6781. rtr, rbr, rbl,
  6782. st->bg);
  6783. }
  6784. } else if (st->border_w[0] && !st->border_t[0]) {
  6785. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  6786. rbl, st->border_w[0],
  6787. st->border_c[0]);
  6788. }
  6789. /* Rounded boxes paint their background image too
  6790. * (app icons are rounded squares), kept inside the
  6791. * corner arcs. */
  6792. if (st->bg_image)
  6793. draw_bg_image_round(l, box, node, st, rtl, rtr,
  6794. rbr, rbl);
  6795. } else {
  6796. if (st->has_bg)
  6797. ngui_fill_rect(l->ui, box, st->bg);
  6798. if (st->bg_image)
  6799. draw_bg_image(l, box, node, st);
  6800. if (st->border_w[0] || st->border_w[1] ||
  6801. st->border_w[2] || st->border_w[3])
  6802. draw_border_box(l->ui, box, st);
  6803. }
  6804. }
  6805. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  6806. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  6807. content_w, img_dh);
  6808. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  6809. l->ui && l->ui->nclip < 4) {
  6810. clip_rect.x = l0 + bl;
  6811. clip_rect.y = top + bt;
  6812. clip_rect.w = (r0 - l0) - bl - br;
  6813. clip_rect.h = (int)block_h[node] - bt - bb;
  6814. if (clip_rect.w > 0 && clip_rect.h > 0) {
  6815. ngui_push_clip(l->ui, clip_rect);
  6816. clip_pushed = 1;
  6817. }
  6818. }
  6819. l->left = l0 + bl + pl;
  6820. l->right = l->left + content_w;
  6821. if (l->right < l->left + 8)
  6822. l->right = l->left + 8;
  6823. l->align = st->align;
  6824. l->line_left = l->left;
  6825. l->line_right = l->right;
  6826. l->y = top + bt + pt;
  6827. if (doc.nodes[node].tag == BR_TAG_HR) {
  6828. if (l->draw)
  6829. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  6830. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  6831. l->y += 8;
  6832. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  6833. int vw = l->right - l->left;
  6834. int vh;
  6835. if (doc.nodes[node].width_pct)
  6836. vw = vw * doc.nodes[node].width_attr / 100;
  6837. else if (doc.nodes[node].width_attr)
  6838. vw = doc.nodes[node].width_attr;
  6839. if (vw > l->right - l->left)
  6840. vw = l->right - l->left;
  6841. if (vw < 8)
  6842. vw = 8;
  6843. vh = vw * 9 / 16;
  6844. if (vh > 240)
  6845. vh = 240;
  6846. if (vh < 80)
  6847. vh = 80;
  6848. if (l->draw) {
  6849. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  6850. vw, vh}, 0xD69A);
  6851. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  6852. vw, vh}, 0x8410);
  6853. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  6854. 0x4208);
  6855. }
  6856. l->y += vh + 4;
  6857. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  6858. int dw, dh, cw = l->right - l->left;
  6859. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  6860. if (l->draw && l->y < page_rect.y + page_rect.h &&
  6861. l->y + dh > page_rect.y)
  6862. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  6863. l->y += dh;
  6864. } else {
  6865. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  6866. !st->no_bullet) {
  6867. char *m = li_marker[node];
  6868. if (!m[0]) {
  6869. unsigned int parent = doc.nodes[node].parent;
  6870. int style = st->list_style;
  6871. int idx = parent ? list_index(parent, node) : 1;
  6872. if (style == BR_LIST_AUTO)
  6873. style = (parent &&
  6874. doc.nodes[parent].tag ==
  6875. BR_TAG_OL) ?
  6876. BR_LIST_DECIMAL : BR_LIST_DISC;
  6877. list_marker_text(m, sizeof(li_marker[node]),
  6878. style, idx);
  6879. }
  6880. if (l->draw && m[0]) {
  6881. int mw = (int)ngui_text_width_ui(l->ui, m);
  6882. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  6883. st->color);
  6884. }
  6885. }
  6886. /* This box's definite content height, for its children's
  6887. * percentage heights. */
  6888. if (doc.nodes[node].tag == BR_TAG_HTML ||
  6889. doc.nodes[node].tag == BR_TAG_BODY)
  6890. l->cb_h = layout_view_h;
  6891. else if (st->height_kind == 1)
  6892. l->cb_h = (int)st->height -
  6893. (st->box_sizing ? deco_h : 0);
  6894. else if (st->height_kind == 2 && parent_cb_h > 0)
  6895. l->cb_h = parent_cb_h * (int)st->height / 100 -
  6896. (st->box_sizing ? deco_h : 0);
  6897. else
  6898. l->cb_h = 0;
  6899. if (l->cb_h < 0)
  6900. l->cb_h = 0;
  6901. if (doc.nodes[node].tag == BR_TAG_TR)
  6902. layout_table_row(l, node, st, depth + 1, link);
  6903. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  6904. table_has_rowspan(node))
  6905. layout_table(l, node, st, depth + 1, link);
  6906. else if (st->grid_auto)
  6907. layout_grid_auto(l, node, st, depth + 1, link);
  6908. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  6909. st->grid_gap > 0)
  6910. layout_grid_children(l, node, st, depth + 1, link);
  6911. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  6912. flex_wants_row(node, st))
  6913. layout_flex_children(l, node, st, depth + 1, link);
  6914. else if (st->display == BR_DISPLAY_FLEX && st->flex_col &&
  6915. st->align_items == 1) {
  6916. /* align-items: center in a column: the items' lines
  6917. * (an app card's icon and label) are centred; a child
  6918. * with its own text-align keeps it. */
  6919. struct br_style cst = *st;
  6920. cst.align = BR_ALIGN_CENTER;
  6921. l->align = BR_ALIGN_CENTER;
  6922. layout_children(l, node, &cst, depth + 1, link);
  6923. } else
  6924. layout_children(l, node, st, depth + 1, link);
  6925. l->cb_h = parent_cb_h;
  6926. }
  6927. flush_line(l);
  6928. if (clip_pushed)
  6929. ngui_pop_clip(l->ui);
  6930. if (l->float_active) {
  6931. if (l->y < l->float_bottom)
  6932. l->y = l->float_bottom;
  6933. l->float_active = 0;
  6934. }
  6935. if (doc.nodes[node].tag == BR_TAG_IMG) {
  6936. content_h = img_dh;
  6937. } else if (st->height_kind == 2 &&
  6938. doc.nodes[node].tag != BR_TAG_HTML &&
  6939. doc.nodes[node].tag != BR_TAG_BODY) {
  6940. /* A percentage of the containing block's definite height, or
  6941. * auto when it has none (it used to resolve against the
  6942. * width). The result is a minimum: without scrollable inner
  6943. * boxes, an app shell's height:100%; overflow:hidden column
  6944. * would otherwise clip everything past the first screen. */
  6945. int auto_h = l->y - (top + bt + pt);
  6946. content_h = parent_cb_h > 0 ?
  6947. parent_cb_h * (int)st->height / 100 -
  6948. (st->box_sizing ? deco_h : 0) : 0;
  6949. if (content_h < auto_h)
  6950. content_h = auto_h;
  6951. } else if (st->height_kind &&
  6952. !((doc.nodes[node].tag == BR_TAG_HTML ||
  6953. doc.nodes[node].tag == BR_TAG_BODY) &&
  6954. st->height_kind == 2)) {
  6955. content_h = style_height_px(st, cbw);
  6956. if (st->box_sizing)
  6957. content_h -= deco_h;
  6958. } else {
  6959. /* Percentage heights on html/body resolve against the
  6960. * viewport, but their content still defines the document
  6961. * scroll height. Treating them as auto avoids collapsing
  6962. * the measured page to the containing block width. */
  6963. content_h = l->y - (top + bt + pt);
  6964. }
  6965. if (content_h < 0)
  6966. content_h = 0;
  6967. if (st->max_height_kind) {
  6968. int mh = st->max_height_kind == 3 ?
  6969. cbw * st->max_height_calc_pct / 100 +
  6970. st->max_height_calc_px :
  6971. css_size(st->max_height_kind, st->max_height, cbw);
  6972. int max_box = st->box_sizing ? mh : mh + deco_h;
  6973. if (content_h + deco_h > max_box)
  6974. content_h = max_box - deco_h;
  6975. }
  6976. if (st->min_height_kind &&
  6977. !((doc.nodes[node].tag == BR_TAG_HTML ||
  6978. doc.nodes[node].tag == BR_TAG_BODY) &&
  6979. st->min_height_kind == 2)) {
  6980. int mh = st->min_height_kind == 3 ?
  6981. cbw * st->min_height_calc_pct / 100 +
  6982. st->min_height_calc_px :
  6983. css_size(st->min_height_kind, st->min_height, cbw);
  6984. int min_box = st->box_sizing ? mh : mh + deco_h;
  6985. if (content_h + deco_h < min_box)
  6986. content_h = min_box - deco_h;
  6987. }
  6988. if (content_h < 0)
  6989. content_h = 0;
  6990. box_h = deco_h + content_h;
  6991. if (box_h < 0)
  6992. box_h = 0;
  6993. l->y = (shifted ? normal_top : top) + box_h;
  6994. if (node < BR_MAX_NODES) {
  6995. layout_boxes[node].x = l0;
  6996. layout_boxes[node].y = top;
  6997. layout_boxes[node].w = r0 - l0;
  6998. layout_boxes[node].h = box_h;
  6999. layout_boxes[node].valid = r0 > l0;
  7000. }
  7001. l->left = old_left;
  7002. l->right = old_right;
  7003. l->align = old_align;
  7004. l->y += mp_px(st, 2, cbw);
  7005. if (!l->draw) {
  7006. if (box_h > 65535)
  7007. box_h = 65535;
  7008. block_h[node] = (unsigned short)box_h;
  7009. block_top[node] = (unsigned short)(top < 0 ? 0 :
  7010. top > 65535 ? 65535 : top);
  7011. }
  7012. if (positioned) {
  7013. l->y = flow_y;
  7014. l->left = flow_left;
  7015. l->right = flow_right;
  7016. }
  7017. l->parent_top = saved_parent_top;
  7018. l->cb_left = saved_cb_left;
  7019. l->cb_right = saved_cb_right;
  7020. l->cb_top = saved_cb_top;
  7021. }
  7022. static int text_node_blank(const struct br_node *nd)
  7023. {
  7024. const char *t = doc.text + nd->text_off;
  7025. unsigned int i;
  7026. for (i = 0; i < nd->text_len; i++)
  7027. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  7028. t[i] != '\r')
  7029. return 0;
  7030. return 1;
  7031. }
  7032. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  7033. * text/image widths in the subtree, plus padding and margins. This keeps
  7034. * Bootstrap's floated nav items on one line instead of giving each the whole
  7035. * row. */
  7036. static int text_space(char c)
  7037. {
  7038. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  7039. }
  7040. static int intrinsic_width(struct ngui *ui, unsigned int node,
  7041. const struct br_style *pst, int depth, int base)
  7042. {
  7043. unsigned int c;
  7044. int line_w = 0, max_w = 0;
  7045. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  7046. if (depth > 32)
  7047. return 0;
  7048. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7049. struct br_node *nd = &doc.nodes[c];
  7050. struct br_style cs;
  7051. if (nd->type == BR_NODE_TEXT) {
  7052. const char *t = doc.text + nd->text_off;
  7053. unsigned int tn = nd->text_len;
  7054. if (doc.nodes[node].tag == BR_TAG_PRE) {
  7055. line_w += (int)face_text_width(ui, pst, t, tn);
  7056. } else {
  7057. unsigned int ti = 0;
  7058. int first = 1;
  7059. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  7060. int sp = (int)face_text_width(ui, pst, " ", 1);
  7061. while (ti < tn) {
  7062. unsigned int ts;
  7063. while (ti < tn && text_space(t[ti]))
  7064. ti++;
  7065. ts = ti;
  7066. while (ti < tn && !text_space(t[ti]))
  7067. ti++;
  7068. if (ti == ts)
  7069. break;
  7070. if (!first || lead)
  7071. line_w += sp;
  7072. lead = 0;
  7073. line_w += (int)face_text_width(ui, pst,
  7074. t + ts, ti - ts);
  7075. first = 0;
  7076. }
  7077. }
  7078. continue;
  7079. }
  7080. br_style_for(&doc, c, pst, &cs);
  7081. if (cs.display == BR_DISPLAY_NONE)
  7082. continue;
  7083. if (nd->tag == BR_TAG_BR) {
  7084. if (line_w > max_w)
  7085. max_w = line_w;
  7086. line_w = 0;
  7087. continue;
  7088. }
  7089. if (nd->tag == BR_TAG_IMG) {
  7090. /* Measure the image as layout will draw it: a CSS or
  7091. * attribute height keeps the intrinsic aspect ratio, and
  7092. * a CSS width overrides the native pixel width. Bootstrap
  7093. * sizes the Cloudron logo with height:40px only. */
  7094. int idx = nd->img_index;
  7095. int iw = 0, ih = 0;
  7096. if (idx >= 0 && idx < image_count &&
  7097. images[idx].state == 1) {
  7098. iw = (int)images[idx].native_w;
  7099. ih = (int)images[idx].native_h;
  7100. if (iw <= 0 || ih <= 0) {
  7101. iw = (int)images[idx].img.w;
  7102. ih = (int)images[idx].img.h;
  7103. }
  7104. }
  7105. if (cs.width_kind) {
  7106. int ww = style_width_px(&cs, base);
  7107. line_w += ww > 0 ? ww : 64;
  7108. } else if (nd->width_attr) {
  7109. line_w += nd->width_attr;
  7110. } else if (nd->height_attr && iw && ih) {
  7111. line_w += iw * (int)nd->height_attr / ih;
  7112. } else if (cs.height_kind && iw && ih) {
  7113. int hh = style_height_px(&cs, base);
  7114. line_w += hh > 0 ? iw * hh / ih : iw;
  7115. } else if (iw) {
  7116. line_w += iw;
  7117. } else {
  7118. line_w += 64;
  7119. }
  7120. continue;
  7121. }
  7122. {
  7123. int cw = mp_px(&cs, 7, base) +
  7124. mp_px(&cs, 5, base) +
  7125. mp_px(&cs, 3, base) +
  7126. mp_px(&cs, 1, base) +
  7127. cs.border_w[1] + cs.border_w[3];
  7128. /* width/height do not apply to non-replaced inline
  7129. * boxes. The tagesschau home label is an inline span
  7130. * with width:1px for the mobile icon-only header; using
  7131. * that width made the whole subnav collapse to a
  7132. * one-character column. */
  7133. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  7134. cw += cs.width_kind == 1 ? cs.width :
  7135. style_width_px(&cs, base);
  7136. else
  7137. cw += intrinsic_width(ui, c, &cs, depth + 1,
  7138. base);
  7139. if (flex_row || cs.float_left ||
  7140. cs.display == BR_DISPLAY_INLINE ||
  7141. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  7142. line_w += cw;
  7143. } else {
  7144. if (line_w > max_w)
  7145. max_w = line_w;
  7146. line_w = 0;
  7147. if (cw > max_w)
  7148. max_w = cw;
  7149. }
  7150. }
  7151. if (line_w > 4096 || max_w > 4096)
  7152. break;
  7153. }
  7154. return line_w > max_w ? line_w : max_w;
  7155. }
  7156. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  7157. * the main user: .row > .col-md-* with float:left and a percentage width.
  7158. * Each column is laid out with its own left/right edge and the row advances
  7159. * to the tallest column. Returns the first child not consumed. */
  7160. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  7161. const struct br_style *pst, int depth,
  7162. unsigned short link)
  7163. {
  7164. unsigned int n = first;
  7165. int row_left = l->left, row_right = l->right;
  7166. int row_top, row_bottom, xl, xr, any = 0;
  7167. int fl_left = row_left, fl_right = row_right, fl_bottom;
  7168. flush_line(l);
  7169. row_top = l->y;
  7170. row_bottom = l->y;
  7171. fl_bottom = row_top;
  7172. xl = row_left;
  7173. xr = row_right;
  7174. while (n) {
  7175. struct br_node *nd = &doc.nodes[n];
  7176. struct br_style cs;
  7177. unsigned short lk = link;
  7178. int colw, right;
  7179. if (nd->type == BR_NODE_TEXT) {
  7180. if (text_node_blank(nd)) {
  7181. n = nd->next;
  7182. continue;
  7183. }
  7184. break;
  7185. }
  7186. br_style_for(&doc, n, pst, &cs);
  7187. if (cs.display == BR_DISPLAY_NONE) {
  7188. n = nd->next;
  7189. continue;
  7190. }
  7191. /* A float blockifies its box: Bootstrap floats inline
  7192. * anchors too (the navbar brand and its text links), and
  7193. * their padding must be honoured. */
  7194. if (!cs.float_left)
  7195. break;
  7196. if (nd->tag == BR_TAG_A && nd->href_off)
  7197. lk = (unsigned short)n;
  7198. right = cs.float_left == 2;
  7199. if (cs.width_kind == 2 || cs.width_kind == 3) {
  7200. colw = style_width_px(&cs, row_right - row_left);
  7201. } else if (cs.width_kind == 1) {
  7202. colw = (int)cs.width;
  7203. } else {
  7204. int base = row_right - row_left;
  7205. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  7206. mp_px(&cs, 7, base) +
  7207. mp_px(&cs, 5, base) +
  7208. mp_px(&cs, 3, base) +
  7209. mp_px(&cs, 1, base);
  7210. if (colw < 8)
  7211. colw = 8;
  7212. }
  7213. if (colw < 8)
  7214. colw = 8;
  7215. if (colw > row_right - row_left)
  7216. colw = row_right - row_left;
  7217. /* The float column width is already resolved. */
  7218. cs.width_kind = 0;
  7219. cs.max_width_kind = 0;
  7220. if (right) {
  7221. if (any && xr - colw < xl) {
  7222. row_top = row_bottom;
  7223. row_bottom = row_top;
  7224. xl = row_left;
  7225. xr = row_right;
  7226. }
  7227. if (xr - colw < xl)
  7228. colw = xr - xl;
  7229. if (colw < 8)
  7230. colw = 8;
  7231. l->left = xr - colw;
  7232. if (l->left < row_left)
  7233. l->left = row_left;
  7234. l->right = xr;
  7235. xr = l->left;
  7236. if (xr < fl_right)
  7237. fl_right = xr;
  7238. } else {
  7239. if (any && xl + colw > xr) {
  7240. row_top = row_bottom;
  7241. row_bottom = row_top;
  7242. xl = row_left;
  7243. xr = row_right;
  7244. }
  7245. l->left = xl;
  7246. l->right = xl + colw;
  7247. xl += colw;
  7248. if (xl > fl_left)
  7249. fl_left = xl;
  7250. }
  7251. if (l->right < l->left + 8)
  7252. l->right = l->left + 8;
  7253. l->y = row_top;
  7254. l->line_x = l->left;
  7255. l->run_x = l->left;
  7256. l->line_y = l->y;
  7257. l->line_h = 0;
  7258. l->nruns = 0;
  7259. l->space_pending = 0;
  7260. l->align = cs.align;
  7261. layout_block(l, n, &cs, depth + 1, lk);
  7262. if (l->y > row_bottom)
  7263. row_bottom = l->y;
  7264. if (l->y > fl_bottom)
  7265. fl_bottom = l->y;
  7266. any = 1;
  7267. n = nd->next;
  7268. }
  7269. l->left = row_left;
  7270. l->right = row_right;
  7271. if (n && any) {
  7272. struct br_node *nd = &doc.nodes[n];
  7273. int inline_next = 0;
  7274. if (nd->type == BR_NODE_TEXT) {
  7275. inline_next = 1;
  7276. } else if (nd->type == BR_NODE_ELEM) {
  7277. struct br_style cs;
  7278. br_style_for(&doc, n, pst, &cs);
  7279. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  7280. cs.display != BR_DISPLAY_NONE &&
  7281. !br_tag_is_block(nd->tag);
  7282. }
  7283. if (inline_next) {
  7284. if (l->float_active) {
  7285. if (l->float_left > fl_left)
  7286. fl_left = l->float_left;
  7287. if (l->float_right < fl_right)
  7288. fl_right = l->float_right;
  7289. if (l->float_bottom > fl_bottom)
  7290. fl_bottom = l->float_bottom;
  7291. }
  7292. l->float_active = 1;
  7293. l->float_left = fl_left;
  7294. l->float_right = fl_right;
  7295. l->float_bottom = fl_bottom;
  7296. l->y = row_top;
  7297. } else {
  7298. l->float_active = 0;
  7299. l->y = row_bottom;
  7300. }
  7301. } else {
  7302. l->float_active = 0;
  7303. l->y = row_bottom;
  7304. }
  7305. l->line_x = l->left;
  7306. l->run_x = l->left;
  7307. l->line_left = l->left;
  7308. l->line_right = l->right;
  7309. l->line_y = l->y;
  7310. l->line_h = 0;
  7311. l->nruns = 0;
  7312. l->space_pending = 0;
  7313. return n;
  7314. }
  7315. static int flex_item_width(struct lay *l, unsigned int n,
  7316. const struct br_style *cs, int avail)
  7317. {
  7318. struct br_node *nd = &doc.nodes[n];
  7319. (void)l;
  7320. int w;
  7321. if (cs->width_kind == 2 || cs->width_kind == 3)
  7322. w = style_width_px(cs, avail);
  7323. else if (cs->width_kind == 1)
  7324. w = (int)cs->width;
  7325. else if (nd->tag == BR_TAG_IMG) {
  7326. int idx = nd->img_index;
  7327. if (idx >= 0 && idx < image_count &&
  7328. images[idx].state == 1)
  7329. w = (int)images[idx].img.w;
  7330. else if (nd->width_attr)
  7331. w = (int)nd->width_attr;
  7332. else
  7333. w = 64;
  7334. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  7335. nd->tag == BR_TAG_TEXTAREA) {
  7336. /* A control has no content to measure: its default size
  7337. * (a search field in a filter bar). */
  7338. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  7339. } else {
  7340. w = intrinsic_width(l->ui, n, cs, 0, avail);
  7341. }
  7342. /* Explicit widths are content-box sizes; the flex item's outer width
  7343. * must include padding, borders and margins. */
  7344. w += mp_px(cs, 7, avail);
  7345. w += mp_px(cs, 5, avail);
  7346. w += mp_px(cs, 3, avail);
  7347. w += mp_px(cs, 1, avail);
  7348. w += cs->border_w[1] + cs->border_w[3];
  7349. if (w < 24)
  7350. w = 24;
  7351. if (w > avail)
  7352. w = avail;
  7353. return w;
  7354. }
  7355. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  7356. * on one line, not one full-width block each. Place intrinsic widths from
  7357. * left to right and wrap when the row is full. */
  7358. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  7359. const struct br_style *pst, int depth,
  7360. unsigned short link)
  7361. {
  7362. unsigned int n = first;
  7363. int row_left = l->left, row_right = l->right;
  7364. int avail = row_right - row_left;
  7365. int x = row_left, y = l->y, row_h = 0, any = 0;
  7366. /* Each box sets l->align from its own style; the text after the row
  7367. * must keep the container's (a centred .fa-fw icon centred the menu
  7368. * label that followed it). */
  7369. unsigned char row_align = l->align;
  7370. flush_line(l);
  7371. y = l->y;
  7372. while (n) {
  7373. struct br_node *nd = &doc.nodes[n];
  7374. struct br_style cs;
  7375. unsigned short lk = link;
  7376. int colw, h;
  7377. if (nd->type == BR_NODE_TEXT) {
  7378. if (!text_node_blank(nd))
  7379. break;
  7380. if (any)
  7381. x += 4;
  7382. n = nd->next;
  7383. continue;
  7384. }
  7385. br_style_for(&doc, n, pst, &cs);
  7386. if (cs.display == BR_DISPLAY_NONE) {
  7387. n = nd->next;
  7388. continue;
  7389. }
  7390. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  7391. break;
  7392. if (nd->tag == BR_TAG_A && nd->href_off)
  7393. lk = (unsigned short)n;
  7394. colw = flex_item_width(l, n, &cs, avail);
  7395. /* A few pixels of slack keep a single long token (boot.S)
  7396. * from wrapping at the exact content width. */
  7397. colw += 8;
  7398. if (colw > avail)
  7399. colw = avail;
  7400. cs.width_kind = 0;
  7401. cs.max_width_kind = 0;
  7402. if (any && x + colw > row_right) {
  7403. y += row_h + 2;
  7404. x = row_left;
  7405. row_h = 0;
  7406. any = 0;
  7407. }
  7408. if (any && x > row_left)
  7409. x += 4;
  7410. l->left = x;
  7411. l->right = x + colw;
  7412. if (l->right < l->left + 8)
  7413. l->right = l->left + 8;
  7414. l->y = y;
  7415. l->line_x = l->left;
  7416. l->run_x = l->left;
  7417. l->line_y = l->y;
  7418. l->line_h = 0;
  7419. l->nruns = 0;
  7420. l->space_pending = 0;
  7421. l->align = cs.align;
  7422. layout_block(l, n, &cs, depth + 1, lk);
  7423. h = l->y - y;
  7424. if (h > row_h)
  7425. row_h = h;
  7426. x += colw;
  7427. any = 1;
  7428. n = nd->next;
  7429. }
  7430. if (any)
  7431. y += row_h;
  7432. l->left = row_left;
  7433. l->right = row_right;
  7434. l->align = row_align;
  7435. l->y = y;
  7436. l->line_x = l->left;
  7437. l->run_x = l->left;
  7438. l->line_y = l->y;
  7439. l->line_h = 0;
  7440. l->nruns = 0;
  7441. l->space_pending = 0;
  7442. return n;
  7443. }
  7444. struct flex_item {
  7445. unsigned int node;
  7446. unsigned short link;
  7447. int w;
  7448. };
  7449. static void layout_flex_children(struct lay *l, unsigned int parent,
  7450. const struct br_style *pst, int depth,
  7451. unsigned short link)
  7452. {
  7453. struct flex_item it[32];
  7454. unsigned int c;
  7455. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  7456. int row_left = l->left, row_right = l->right;
  7457. int avail = row_right - row_left;
  7458. int idx, row_top;
  7459. unsigned char row_align = l->align;
  7460. if (avail < 160 || depth > 48) {
  7461. layout_children(l, parent, pst, depth, link);
  7462. return;
  7463. }
  7464. /* If direct text is not just whitespace, normal block flow handles it
  7465. * better than pretending it is a flex item. */
  7466. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7467. struct br_node *nd = &doc.nodes[c];
  7468. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7469. layout_children(l, parent, pst, depth, link);
  7470. return;
  7471. }
  7472. }
  7473. for (c = doc.nodes[parent].first;
  7474. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  7475. c = doc.nodes[c].next) {
  7476. struct br_node *nd = &doc.nodes[c];
  7477. struct br_style cs;
  7478. if (nd->type == BR_NODE_TEXT)
  7479. continue;
  7480. br_style_for(&doc, c, pst, &cs);
  7481. if (cs.display == BR_DISPLAY_NONE)
  7482. continue;
  7483. it[nitem].node = c;
  7484. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  7485. (unsigned short)c : link;
  7486. it[nitem].w = 0;
  7487. if (cs.flex_grow && !cs.width_kind)
  7488. grow_count++;
  7489. else
  7490. fixed += flex_item_width(l, c, &cs, avail);
  7491. nitem++;
  7492. }
  7493. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  7494. if (grow_w < 96)
  7495. grow_w = 96;
  7496. for (idx = 0; idx < nitem; idx++) {
  7497. struct br_style cs;
  7498. br_style_for(&doc, it[idx].node, pst, &cs);
  7499. if (cs.flex_grow && !cs.width_kind)
  7500. it[idx].w = grow_w;
  7501. else
  7502. it[idx].w = flex_item_width(l, it[idx].node, &cs, avail);
  7503. if (it[idx].w > avail)
  7504. it[idx].w = avail;
  7505. if (it[idx].w < 8)
  7506. it[idx].w = 8;
  7507. }
  7508. row_top = l->y;
  7509. idx = 0;
  7510. while (idx < nitem) {
  7511. int start = idx, count = 0, row_w = 0;
  7512. int free_w, x, extra = 0, row_h = 0, k;
  7513. while (idx < nitem) {
  7514. int add = it[idx].w + (count ? gap : 0);
  7515. /* CSS default is nowrap; only flex-wrap: wrap (1)
  7516. * starts a new row. */
  7517. if (count && pst->flex_wrap == 1 &&
  7518. row_w + add > avail)
  7519. break;
  7520. row_w += add;
  7521. count++;
  7522. idx++;
  7523. }
  7524. if (!count) {
  7525. count = 1;
  7526. row_w = it[start].w;
  7527. idx = start + 1;
  7528. }
  7529. free_w = avail - row_w;
  7530. if (free_w < 0)
  7531. free_w = 0;
  7532. x = row_left;
  7533. if (pst->justify == 1) {
  7534. x += free_w / 2;
  7535. } else if (pst->justify == 2) {
  7536. x += free_w;
  7537. } else if (pst->justify == 3) {
  7538. extra = count > 1 ? free_w / (count - 1) : 0;
  7539. } else if (pst->justify == 4) {
  7540. extra = count ? free_w / count : 0;
  7541. x += extra / 2;
  7542. } else if (pst->justify == 5) {
  7543. extra = count ? free_w / (count + 1) : 0;
  7544. x += extra;
  7545. }
  7546. for (k = 0; k < count; k++) {
  7547. int node = (int)it[start + k].node;
  7548. int h = block_h[node];
  7549. if (h > row_h)
  7550. row_h = h;
  7551. }
  7552. if (pst->height_kind) {
  7553. int hh = style_height_px(pst, avail);
  7554. if (hh > row_h)
  7555. row_h = hh;
  7556. }
  7557. for (k = 0; k < count; k++) {
  7558. struct br_style cs;
  7559. int node = (int)it[start + k].node;
  7560. int yoff = 0;
  7561. br_style_for(&doc, node, pst, &cs);
  7562. cs.width_kind = 0;
  7563. cs.max_width_kind = 0;
  7564. if (l->draw && pst->align_items &&
  7565. row_h > block_h[node]) {
  7566. if (pst->align_items == 1)
  7567. yoff = (row_h - block_h[node]) / 2;
  7568. else if (pst->align_items == 2)
  7569. yoff = row_h - block_h[node];
  7570. }
  7571. l->left = x;
  7572. l->right = x + it[start + k].w;
  7573. if (l->right < l->left + 8)
  7574. l->right = l->left + 8;
  7575. l->y = row_top + yoff;
  7576. l->line_x = l->left;
  7577. l->run_x = l->left;
  7578. l->line_y = l->y;
  7579. l->line_h = 0;
  7580. l->nruns = 0;
  7581. l->space_pending = 0;
  7582. l->align = cs.align;
  7583. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  7584. if (!l->draw) {
  7585. int h = l->y - row_top;
  7586. if (h > row_h)
  7587. row_h = h;
  7588. }
  7589. x += it[start + k].w;
  7590. if (k + 1 < count)
  7591. x += gap + extra;
  7592. }
  7593. row_top += row_h;
  7594. }
  7595. l->left = row_left;
  7596. l->right = row_right;
  7597. l->align = row_align;
  7598. l->y = row_top;
  7599. l->line_x = l->left;
  7600. l->run_x = l->left;
  7601. l->line_y = l->y;
  7602. l->line_h = 0;
  7603. l->nruns = 0;
  7604. l->space_pending = 0;
  7605. }
  7606. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  7607. * plus the grid-area hints used by site shells (site notice/footer full
  7608. * width, column-start left, page-content right). Anything more elaborate
  7609. * falls back to normal block flow. */
  7610. static int grid_track_width(unsigned char kind, unsigned short val,
  7611. int avail, int other)
  7612. {
  7613. if (kind == 2)
  7614. return avail * (int)val / 100;
  7615. if (kind == 1)
  7616. return val;
  7617. return other;
  7618. }
  7619. static void layout_grid_children(struct lay *l, unsigned int parent,
  7620. const struct br_style *pst, int depth,
  7621. unsigned short link)
  7622. {
  7623. unsigned int n;
  7624. int row_left = l->left, row_right = l->right;
  7625. int avail = row_right - row_left;
  7626. int gap = pst->grid_gap;
  7627. int track_total = avail - gap;
  7628. int col0, col1, x0, x1;
  7629. int row_y, row_bottom, have_left = 0, have_right = 0;
  7630. unsigned int c;
  7631. if (avail < 32 || depth > 48)
  7632. return;
  7633. if (track_total < 16)
  7634. track_total = 16;
  7635. col0 = grid_track_width((unsigned char)(pst->width_kind),
  7636. pst->width, track_total, 0);
  7637. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  7638. pst->max_width, track_total, 0);
  7639. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  7640. int w0 = pst->width ? pst->width : 1;
  7641. int w1 = pst->max_width ? pst->max_width : 1;
  7642. col0 = track_total * w0 / (w0 + w1);
  7643. col1 = track_total - col0;
  7644. } else if (pst->width_kind == 3) {
  7645. col0 = track_total - col1;
  7646. if (col0 < 24)
  7647. col0 = 24;
  7648. } else if (pst->max_width_kind == 3) {
  7649. col1 = track_total - col0;
  7650. if (col1 < 24)
  7651. col1 = 24;
  7652. }
  7653. if (col0 < 24)
  7654. col0 = 24;
  7655. if (col1 < 24)
  7656. col1 = 24;
  7657. if (col0 + col1 > track_total) {
  7658. col1 = track_total - col0;
  7659. if (col1 < 24)
  7660. col1 = 24;
  7661. }
  7662. x0 = row_left;
  7663. x1 = row_left + col0 + gap;
  7664. /* Direct text makes a grid ambiguous; use block flow instead. */
  7665. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7666. struct br_node *nd = &doc.nodes[c];
  7667. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7668. layout_children(l, parent, pst, depth, link);
  7669. return;
  7670. }
  7671. }
  7672. row_y = row_bottom = l->y;
  7673. n = doc.nodes[parent].first;
  7674. while (n) {
  7675. struct br_node *nd = &doc.nodes[n];
  7676. struct br_style cs;
  7677. unsigned short lk = link;
  7678. int slot, x, w;
  7679. if (nd->type == BR_NODE_TEXT) {
  7680. n = nd->next;
  7681. continue;
  7682. }
  7683. br_style_for(&doc, n, pst, &cs);
  7684. if (cs.display == BR_DISPLAY_NONE) {
  7685. n = nd->next;
  7686. continue;
  7687. }
  7688. if (nd->tag == BR_TAG_A && nd->href_off)
  7689. lk = (unsigned short)n;
  7690. slot = cs.grid_slot;
  7691. if (!slot) {
  7692. if (!have_left)
  7693. slot = 2;
  7694. else if (!have_right)
  7695. slot = 3;
  7696. else
  7697. slot = 2;
  7698. }
  7699. if (slot == 1) {
  7700. if (have_left || have_right) {
  7701. row_y = row_bottom;
  7702. have_left = have_right = 0;
  7703. }
  7704. x = row_left;
  7705. w = avail;
  7706. } else if (slot == 2) {
  7707. if (have_left) {
  7708. row_y = row_bottom;
  7709. have_left = have_right = 0;
  7710. }
  7711. x = x0;
  7712. w = col0;
  7713. have_left = 1;
  7714. } else {
  7715. if (have_right) {
  7716. row_y = row_bottom;
  7717. have_left = have_right = 0;
  7718. }
  7719. x = x1;
  7720. w = col1;
  7721. have_right = 1;
  7722. }
  7723. cs.width_kind = 0;
  7724. cs.max_width_kind = 0;
  7725. l->left = x;
  7726. l->right = x + w;
  7727. if (l->right < l->left + 8)
  7728. l->right = l->left + 8;
  7729. l->y = row_y;
  7730. l->line_x = l->left;
  7731. l->run_x = l->left;
  7732. l->line_y = l->y;
  7733. l->line_h = 0;
  7734. l->nruns = 0;
  7735. l->space_pending = 0;
  7736. l->align = cs.align;
  7737. layout_block(l, n, &cs, depth + 1, lk);
  7738. if (l->y > row_bottom)
  7739. row_bottom = l->y;
  7740. n = nd->next;
  7741. }
  7742. l->left = row_left;
  7743. l->right = row_right;
  7744. l->y = row_bottom;
  7745. l->line_x = l->left;
  7746. l->run_x = l->left;
  7747. l->line_y = l->y;
  7748. l->line_h = 0;
  7749. l->nruns = 0;
  7750. l->space_pending = 0;
  7751. }
  7752. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  7753. * capped at four. Used by the project docs' card grids. */
  7754. static void layout_grid_auto(struct lay *l, unsigned int parent,
  7755. const struct br_style *pst, int depth,
  7756. unsigned short link)
  7757. {
  7758. unsigned int n, c;
  7759. int row_left = l->left, row_right = l->right;
  7760. int avail = row_right - row_left;
  7761. int gap = pst->grid_gap;
  7762. int minw = pst->width_kind == 1 ? pst->width : 200;
  7763. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  7764. if (avail < 32 || depth > 48) {
  7765. layout_children(l, parent, pst, depth, link);
  7766. return;
  7767. }
  7768. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7769. struct br_node *nd = &doc.nodes[c];
  7770. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7771. layout_children(l, parent, pst, depth, link);
  7772. return;
  7773. }
  7774. }
  7775. if (minw < 80)
  7776. minw = 80;
  7777. ncols = (avail + gap) / (minw + gap);
  7778. if (ncols < 1)
  7779. ncols = 1;
  7780. if (ncols > 4)
  7781. ncols = 4;
  7782. colw = (avail - gap * (ncols - 1)) / ncols;
  7783. if (colw < 24)
  7784. colw = 24;
  7785. x = row_left;
  7786. n = doc.nodes[parent].first;
  7787. while (n) {
  7788. struct br_node *nd = &doc.nodes[n];
  7789. struct br_style cs;
  7790. unsigned short lk = link;
  7791. int h;
  7792. if (nd->type == BR_NODE_TEXT) {
  7793. n = nd->next;
  7794. continue;
  7795. }
  7796. br_style_for(&doc, n, pst, &cs);
  7797. if (cs.display == BR_DISPLAY_NONE) {
  7798. n = nd->next;
  7799. continue;
  7800. }
  7801. if (nd->tag == BR_TAG_A && nd->href_off)
  7802. lk = (unsigned short)n;
  7803. cs.width_kind = 0;
  7804. cs.max_width_kind = 0;
  7805. l->left = x;
  7806. l->right = x + colw;
  7807. if (l->right < l->left + 8)
  7808. l->right = l->left + 8;
  7809. l->y = y;
  7810. l->line_x = l->left;
  7811. l->run_x = l->left;
  7812. l->line_y = l->y;
  7813. l->line_h = 0;
  7814. l->nruns = 0;
  7815. l->space_pending = 0;
  7816. l->align = cs.align;
  7817. layout_block(l, n, &cs, depth + 1, lk);
  7818. h = l->y - y;
  7819. if (h > row_h)
  7820. row_h = h;
  7821. col++;
  7822. n = nd->next;
  7823. if (col == ncols) {
  7824. y += row_h + gap;
  7825. x = row_left;
  7826. row_h = 0;
  7827. col = 0;
  7828. } else {
  7829. x += colw + gap;
  7830. }
  7831. }
  7832. if (col)
  7833. y += row_h;
  7834. else if (y > start_y)
  7835. y -= gap;
  7836. l->left = row_left;
  7837. l->right = row_right;
  7838. l->y = y;
  7839. l->line_x = l->left;
  7840. l->run_x = l->left;
  7841. l->line_y = l->y;
  7842. l->line_h = 0;
  7843. l->nruns = 0;
  7844. l->space_pending = 0;
  7845. }
  7846. /* Column widths are the widest cell in each column across every row, so all
  7847. * rows line up. The table model is still deliberately basic: no colspan,
  7848. * border-collapse or percentage columns. */
  7849. static void table_columns(struct lay *l, unsigned int table,
  7850. const struct br_style *pst, int avail,
  7851. int *raw, int maxcols, int *out_cols,
  7852. int *out_total)
  7853. {
  7854. unsigned int r, c;
  7855. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  7856. int fixed[12];
  7857. for (c = 0; c < (unsigned int)maxcols; c++) {
  7858. raw[c] = 0;
  7859. fixed[c] = 0;
  7860. }
  7861. /* Intrinsic widths of single-column cells. */
  7862. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7863. struct br_node *rn = &doc.nodes[r];
  7864. int col = 0;
  7865. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7866. continue;
  7867. for (c = rn->first; c; c = doc.nodes[c].next) {
  7868. struct br_node *cn = &doc.nodes[c];
  7869. struct br_style cs;
  7870. int w, span;
  7871. if (cn->type != BR_NODE_ELEM ||
  7872. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  7873. continue;
  7874. span = cn->colspan ? cn->colspan : 1;
  7875. br_style_for(&doc, c, pst, &cs);
  7876. if (cs.display == BR_DISPLAY_NONE)
  7877. continue;
  7878. if (col + span > maxcols)
  7879. span = maxcols - col;
  7880. if (span < 1)
  7881. break;
  7882. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  7883. mp_px(&cs, 7, avail) +
  7884. mp_px(&cs, 5, avail) +
  7885. mp_px(&cs, 3, avail) +
  7886. mp_px(&cs, 1, avail) +
  7887. cs.border_w[0] + cs.border_w[1] +
  7888. cs.border_w[2] + cs.border_w[3];
  7889. if (w < 24)
  7890. w = 24;
  7891. if (span == 1) {
  7892. if (w > raw[col])
  7893. raw[col] = w;
  7894. }
  7895. if (col + span > cols)
  7896. cols = col + span;
  7897. col += span;
  7898. }
  7899. }
  7900. /* A colspan cell only has to be as wide as the sum of its columns. */
  7901. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7902. struct br_node *rn = &doc.nodes[r];
  7903. int col = 0;
  7904. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7905. continue;
  7906. for (c = rn->first; c; c = doc.nodes[c].next) {
  7907. struct br_node *cn = &doc.nodes[c];
  7908. struct br_style cs;
  7909. int span, w, sum, i;
  7910. if (cn->type != BR_NODE_ELEM ||
  7911. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  7912. continue;
  7913. span = cn->colspan ? cn->colspan : 1;
  7914. if (col + span > maxcols)
  7915. span = maxcols - col;
  7916. if (span < 1)
  7917. break;
  7918. if (span > 1) {
  7919. br_style_for(&doc, c, pst, &cs);
  7920. if (cs.display != BR_DISPLAY_NONE) {
  7921. w = intrinsic_width(l->ui, c, &cs,
  7922. 0, avail) +
  7923. mp_px(&cs, 7, avail) +
  7924. mp_px(&cs, 5, avail) +
  7925. mp_px(&cs, 3, avail) +
  7926. mp_px(&cs, 1, avail) +
  7927. cs.border_w[0] + cs.border_w[1] +
  7928. cs.border_w[2] + cs.border_w[3];
  7929. sum = 0;
  7930. for (i = 0; i < span; i++)
  7931. sum += raw[col + i];
  7932. if (w > sum)
  7933. raw[col + span - 1] += w - sum;
  7934. }
  7935. }
  7936. col += span;
  7937. }
  7938. }
  7939. /* Explicit and percentage widths override intrinsic widths. */
  7940. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7941. struct br_node *rn = &doc.nodes[r];
  7942. int col = 0;
  7943. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7944. continue;
  7945. for (c = rn->first; c; c = doc.nodes[c].next) {
  7946. struct br_node *cn = &doc.nodes[c];
  7947. struct br_style cs;
  7948. int span;
  7949. if (cn->type != BR_NODE_ELEM ||
  7950. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  7951. continue;
  7952. span = cn->colspan ? cn->colspan : 1;
  7953. if (col + span > maxcols)
  7954. span = maxcols - col;
  7955. if (span < 1)
  7956. break;
  7957. if (span == 1) {
  7958. br_style_for(&doc, c, pst, &cs);
  7959. if (cs.display != BR_DISPLAY_NONE) {
  7960. if (cs.width_kind == 1) {
  7961. raw[col] = cs.width;
  7962. fixed[col] = 1;
  7963. } else if (cs.width_kind == 2 ||
  7964. cs.width_kind == 3) {
  7965. raw[col] = style_width_px(&cs,
  7966. avail);
  7967. fixed[col] = 1;
  7968. }
  7969. }
  7970. }
  7971. col += span;
  7972. }
  7973. }
  7974. for (c = 0; c < (unsigned int)cols; c++) {
  7975. if (raw[c] < 8)
  7976. raw[c] = 8;
  7977. total += raw[c];
  7978. if (fixed[c])
  7979. fixed_sum += raw[c];
  7980. else {
  7981. free_raw += raw[c];
  7982. free_cols++;
  7983. }
  7984. }
  7985. if (fixed_sum > 0 && fixed_sum < avail) {
  7986. int free_avail = avail - fixed_sum;
  7987. int i;
  7988. if (free_raw > 0) {
  7989. for (i = 0; i < cols; i++)
  7990. if (!fixed[i])
  7991. raw[i] = free_avail * raw[i] /
  7992. free_raw;
  7993. } else if (free_cols > 0) {
  7994. for (i = 0; i < cols; i++)
  7995. if (!fixed[i])
  7996. raw[i] = free_avail / free_cols;
  7997. }
  7998. total = 0;
  7999. for (i = 0; i < cols; i++)
  8000. total += raw[i];
  8001. } else if (total < avail && total > 0) {
  8002. int i;
  8003. for (i = 0; i < cols; i++)
  8004. raw[i] = raw[i] * avail / total;
  8005. total = 0;
  8006. for (i = 0; i < cols; i++)
  8007. total += raw[i];
  8008. }
  8009. *out_cols = cols;
  8010. *out_total = total;
  8011. }
  8012. static void layout_table_row(struct lay *l, unsigned int row,
  8013. const struct br_style *pst, int depth,
  8014. unsigned short link)
  8015. {
  8016. unsigned int n, cell[12];
  8017. int raw[12], colstart[12], colspan[12];
  8018. int prefix[13];
  8019. int ncell = 0, total = 0, cols = 0, col = 0;
  8020. int row_left = l->left, row_right = l->right;
  8021. int avail = row_right - row_left;
  8022. int y = l->y, bottom = l->y;
  8023. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  8024. struct br_node *nd = &doc.nodes[n];
  8025. struct br_style cs;
  8026. int span;
  8027. if (nd->type == BR_NODE_TEXT) {
  8028. if (text_node_blank(nd))
  8029. continue;
  8030. layout_children(l, row, pst, depth, link);
  8031. return;
  8032. }
  8033. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  8034. layout_children(l, row, pst, depth, link);
  8035. return;
  8036. }
  8037. br_style_for(&doc, n, pst, &cs);
  8038. if (cs.display == BR_DISPLAY_NONE)
  8039. continue;
  8040. if (ncell >= 12) {
  8041. layout_children(l, row, pst, depth, link);
  8042. return;
  8043. }
  8044. span = nd->colspan ? nd->colspan : 1;
  8045. if (span > 12 - col)
  8046. span = 12 - col;
  8047. if (span < 1)
  8048. continue;
  8049. cell[ncell] = n;
  8050. colstart[ncell] = col;
  8051. colspan[ncell] = span;
  8052. col += span;
  8053. ncell++;
  8054. }
  8055. if (ncell < 1 || avail < 32) {
  8056. layout_children(l, row, pst, depth, link);
  8057. return;
  8058. }
  8059. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  8060. &total);
  8061. if (cols < 2 || total <= 0) {
  8062. int c;
  8063. total = 0;
  8064. for (c = 0; c < ncell; c++) {
  8065. struct br_style cs;
  8066. br_style_for(&doc, cell[c], pst, &cs);
  8067. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  8068. avail) +
  8069. mp_px(&cs, 7, avail) +
  8070. mp_px(&cs, 5, avail) +
  8071. mp_px(&cs, 3, avail) +
  8072. mp_px(&cs, 1, avail);
  8073. if (raw[c] < 24)
  8074. raw[c] = 24;
  8075. total += raw[c];
  8076. }
  8077. /* A one-column table still has to fill its own width; the
  8078. * intrinsic fallback above otherwise leaves the cell at its
  8079. * text width (HN's outer table and nested story table). */
  8080. if (total > 0 && total < avail) {
  8081. int c;
  8082. for (c = 0; c < ncell; c++)
  8083. raw[c] = raw[c] * avail / total;
  8084. total = avail;
  8085. }
  8086. }
  8087. prefix[0] = row_left;
  8088. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  8089. prefix[n + 1] = prefix[n] + raw[n];
  8090. for (n = 0; n < (unsigned int)ncell; n++) {
  8091. struct br_style cs;
  8092. int start = colstart[n];
  8093. int end = start + colspan[n];
  8094. int w;
  8095. if (end > cols)
  8096. end = cols;
  8097. if (start >= cols)
  8098. continue;
  8099. w = prefix[end] - prefix[start];
  8100. br_style_for(&doc, cell[n], pst, &cs);
  8101. /* The column width already reflects the cell's width property. */
  8102. cs.width_kind = 0;
  8103. cs.max_width_kind = 0;
  8104. if (w < 24)
  8105. w = 24;
  8106. if (w < 8)
  8107. w = 8;
  8108. l->left = prefix[start];
  8109. l->right = l->left + w;
  8110. l->y = y;
  8111. l->line_x = l->left;
  8112. l->run_x = l->left;
  8113. l->line_y = l->y;
  8114. l->line_h = 0;
  8115. l->nruns = 0;
  8116. l->space_pending = 0;
  8117. l->align = cs.align;
  8118. layout_block(l, cell[n], &cs, depth + 1, link);
  8119. if (l->y > bottom)
  8120. bottom = l->y;
  8121. }
  8122. l->left = row_left;
  8123. l->right = row_right;
  8124. l->y = bottom;
  8125. l->line_x = l->left;
  8126. l->run_x = l->left;
  8127. l->line_y = l->y;
  8128. l->line_h = 0;
  8129. l->nruns = 0;
  8130. l->space_pending = 0;
  8131. }
  8132. #define TBL_MAX_ROWS 32
  8133. #define TBL_MAX_COLS 12
  8134. #define TBL_MAX_CELLS 128
  8135. struct tbl_cell {
  8136. unsigned int node;
  8137. unsigned char row, col, rowspan, colspan;
  8138. int height;
  8139. };
  8140. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  8141. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  8142. static int table_active;
  8143. static int table_has_rowspan(unsigned int table)
  8144. {
  8145. unsigned int r, c;
  8146. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  8147. struct br_node *rn = &doc.nodes[r];
  8148. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  8149. continue;
  8150. for (c = rn->first; c; c = doc.nodes[c].next) {
  8151. struct br_node *cn = &doc.nodes[c];
  8152. if (cn->type == BR_NODE_ELEM &&
  8153. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  8154. cn->rowspan > 1)
  8155. return 1;
  8156. }
  8157. }
  8158. return 0;
  8159. }
  8160. static void table_cell_style(unsigned int row, unsigned int cell,
  8161. const struct br_style *st, struct br_style *out)
  8162. {
  8163. struct br_style trs;
  8164. br_style_for(&doc, row, st, &trs);
  8165. br_style_for(&doc, cell, &trs, out);
  8166. }
  8167. /* Tables that use rowspan need row heights before anything is painted. This
  8168. * path builds a small occupancy grid, measures the natural cell heights, then
  8169. * lays every cell out at its row/column position. Tables without rowspan
  8170. * keep the lighter per-row path in layout_table_row(). */
  8171. static void layout_table(struct lay *l, unsigned int table,
  8172. const struct br_style *st, int depth,
  8173. unsigned short link)
  8174. {
  8175. unsigned int rows[TBL_MAX_ROWS];
  8176. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  8177. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  8178. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  8179. int free_raw = 0, free_cols = 0;
  8180. int table_left = l->left, table_right = l->right;
  8181. int top = l->y, avail = table_right - table_left;
  8182. unsigned int r, c;
  8183. int i, rr, cc;
  8184. if (depth > 48 || table_active) {
  8185. layout_children(l, table, st, depth, link);
  8186. return;
  8187. }
  8188. table_active = 1;
  8189. for (r = doc.nodes[table].first;
  8190. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  8191. struct br_node *rn = &doc.nodes[r];
  8192. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  8193. rows[nrows++] = r;
  8194. }
  8195. if (!nrows) {
  8196. table_active = 0;
  8197. layout_children(l, table, st, depth, link);
  8198. return;
  8199. }
  8200. for (rr = 0; rr < nrows; rr++)
  8201. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  8202. tbl_at[rr][cc] = 0;
  8203. for (rr = 0; rr < nrows; rr++) {
  8204. int col = 0;
  8205. for (c = doc.nodes[rows[rr]].first; c;
  8206. c = doc.nodes[c].next) {
  8207. struct br_node *cn = &doc.nodes[c];
  8208. struct br_style cs;
  8209. int rs, csn;
  8210. if (cn->type != BR_NODE_ELEM ||
  8211. (cn->tag != BR_TAG_TD &&
  8212. cn->tag != BR_TAG_TH))
  8213. continue;
  8214. table_cell_style(rows[rr], c, st, &cs);
  8215. if (cs.display == BR_DISPLAY_NONE)
  8216. continue;
  8217. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  8218. col++;
  8219. if (col >= TBL_MAX_COLS)
  8220. break;
  8221. rs = cn->rowspan ? cn->rowspan : 1;
  8222. csn = cn->colspan ? cn->colspan : 1;
  8223. if (rr + rs > nrows)
  8224. rs = nrows - rr;
  8225. if (col + csn > TBL_MAX_COLS)
  8226. csn = TBL_MAX_COLS - col;
  8227. if (rs < 1 || csn < 1)
  8228. continue;
  8229. if (ncells >= TBL_MAX_CELLS)
  8230. break;
  8231. tbl_cells[ncells].node = c;
  8232. tbl_cells[ncells].row = (unsigned char)rr;
  8233. tbl_cells[ncells].col = (unsigned char)col;
  8234. tbl_cells[ncells].rowspan = (unsigned char)rs;
  8235. tbl_cells[ncells].colspan = (unsigned char)csn;
  8236. tbl_cells[ncells].height = 0;
  8237. for (i = rr; i < rr + rs; i++)
  8238. for (int j = col; j < col + csn; j++)
  8239. tbl_at[i][j] =
  8240. (unsigned short)(ncells + 1);
  8241. ncells++;
  8242. col += csn;
  8243. if (col > cols)
  8244. cols = col;
  8245. }
  8246. }
  8247. if (!ncells || cols < 1) {
  8248. table_active = 0;
  8249. layout_children(l, table, st, depth, link);
  8250. return;
  8251. }
  8252. for (i = 0; i < cols; i++) {
  8253. raw[i] = 0;
  8254. fixed[i] = 0;
  8255. }
  8256. /* Intrinsic widths of single-column cells. */
  8257. for (i = 0; i < ncells; i++) {
  8258. struct br_style cs;
  8259. int w;
  8260. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8261. st, &cs);
  8262. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  8263. mp_px(&cs, 7, avail) +
  8264. mp_px(&cs, 5, avail) +
  8265. mp_px(&cs, 3, avail) +
  8266. mp_px(&cs, 1, avail) +
  8267. cs.border_w[0] + cs.border_w[1] +
  8268. cs.border_w[2] + cs.border_w[3];
  8269. if (w < 24)
  8270. w = 24;
  8271. if (tbl_cells[i].colspan == 1) {
  8272. int col = tbl_cells[i].col;
  8273. if (w > raw[col])
  8274. raw[col] = w;
  8275. }
  8276. }
  8277. /* A spanning cell only needs the sum of its columns to be large
  8278. * enough; put the deficit in the last column. */
  8279. for (i = 0; i < ncells; i++) {
  8280. struct br_style cs;
  8281. int w, sum, col, span;
  8282. if (tbl_cells[i].colspan < 2)
  8283. continue;
  8284. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8285. st, &cs);
  8286. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  8287. mp_px(&cs, 7, avail) +
  8288. mp_px(&cs, 5, avail) +
  8289. mp_px(&cs, 3, avail) +
  8290. mp_px(&cs, 1, avail) +
  8291. cs.border_w[0] + cs.border_w[1] +
  8292. cs.border_w[2] + cs.border_w[3];
  8293. col = tbl_cells[i].col;
  8294. span = tbl_cells[i].colspan;
  8295. sum = 0;
  8296. for (int j = 0; j < span; j++)
  8297. sum += raw[col + j];
  8298. if (w > sum)
  8299. raw[col + span - 1] += w - sum;
  8300. }
  8301. /* Explicit/percentage widths, as in table_columns(). */
  8302. for (i = 0; i < ncells; i++) {
  8303. struct br_style cs;
  8304. int col;
  8305. if (tbl_cells[i].colspan != 1)
  8306. continue;
  8307. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8308. st, &cs);
  8309. col = tbl_cells[i].col;
  8310. if (cs.width_kind == 1) {
  8311. raw[col] = cs.width;
  8312. fixed[col] = 1;
  8313. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  8314. raw[col] = style_width_px(&cs, avail);
  8315. fixed[col] = 1;
  8316. }
  8317. }
  8318. for (i = 0; i < cols; i++) {
  8319. if (raw[i] < 8)
  8320. raw[i] = 8;
  8321. total += raw[i];
  8322. if (fixed[i])
  8323. fixed_sum += raw[i];
  8324. else {
  8325. free_raw += raw[i];
  8326. free_cols++;
  8327. }
  8328. }
  8329. if (fixed_sum > 0 && fixed_sum < avail) {
  8330. int free_avail = avail - fixed_sum;
  8331. if (free_raw > 0) {
  8332. for (i = 0; i < cols; i++)
  8333. if (!fixed[i])
  8334. raw[i] = free_avail * raw[i] /
  8335. free_raw;
  8336. } else if (free_cols > 0) {
  8337. for (i = 0; i < cols; i++)
  8338. if (!fixed[i])
  8339. raw[i] = free_avail / free_cols;
  8340. }
  8341. } else if (total < avail && total > 0) {
  8342. for (i = 0; i < cols; i++)
  8343. raw[i] = raw[i] * avail / total;
  8344. }
  8345. prefix[0] = table_left;
  8346. for (i = 0; i < cols; i++)
  8347. prefix[i + 1] = prefix[i] + raw[i];
  8348. /* Measure natural cell heights with the column widths. */
  8349. for (i = 0; i < ncells; i++) {
  8350. struct br_style cs;
  8351. int col = tbl_cells[i].col;
  8352. int span = tbl_cells[i].colspan;
  8353. int w = prefix[col + span] - prefix[col];
  8354. int sl = l->left, sr = l->right, sy = l->y;
  8355. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  8356. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  8357. int sal = l->align, sdraw = l->draw;
  8358. struct ngui *sui = l->ui;
  8359. if (w < 8)
  8360. w = 8;
  8361. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8362. st, &cs);
  8363. cs.width_kind = 0;
  8364. cs.max_width_kind = 0;
  8365. l->draw = 0;
  8366. l->ui = 0;
  8367. l->left = prefix[col];
  8368. l->right = l->left + w;
  8369. l->y = 0;
  8370. l->line_x = l->left;
  8371. l->run_x = l->left;
  8372. l->line_y = 0;
  8373. l->line_h = 0;
  8374. l->nruns = 0;
  8375. l->space_pending = 0;
  8376. l->align = cs.align;
  8377. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  8378. tbl_cells[i].height = block_h[tbl_cells[i].node];
  8379. l->left = sl;
  8380. l->right = sr;
  8381. l->y = sy;
  8382. l->line_x = slx;
  8383. l->run_x = srx;
  8384. l->line_y = sly;
  8385. l->line_h = slh;
  8386. l->nruns = snr;
  8387. l->space_pending = ssp;
  8388. l->align = sal;
  8389. l->draw = sdraw;
  8390. l->ui = sui;
  8391. }
  8392. for (i = 0; i < nrows; i++)
  8393. rowh[i] = 0;
  8394. for (i = 0; i < ncells; i++) {
  8395. int row = tbl_cells[i].row;
  8396. if (tbl_cells[i].rowspan == 1) {
  8397. if (tbl_cells[i].height > rowh[row])
  8398. rowh[row] = tbl_cells[i].height;
  8399. }
  8400. }
  8401. for (i = 0; i < ncells; i++) {
  8402. int row = tbl_cells[i].row;
  8403. int span = tbl_cells[i].rowspan;
  8404. int sum = 0;
  8405. if (span < 2)
  8406. continue;
  8407. for (int j = 0; j < span; j++)
  8408. sum += rowh[row + j];
  8409. if (sum < tbl_cells[i].height)
  8410. rowh[row + span - 1] +=
  8411. tbl_cells[i].height - sum;
  8412. }
  8413. for (i = 0; i < nrows; i++)
  8414. if (rowh[i] < 8)
  8415. rowh[i] = 8;
  8416. rowy[0] = top;
  8417. for (i = 1; i < nrows; i++)
  8418. rowy[i] = rowy[i - 1] + rowh[i - 1];
  8419. if (!l->draw) {
  8420. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  8421. table_active = 0;
  8422. return;
  8423. }
  8424. for (i = 0; i < ncells; i++) {
  8425. struct br_style cs;
  8426. int col = tbl_cells[i].col;
  8427. int span = tbl_cells[i].colspan;
  8428. int row = tbl_cells[i].row;
  8429. int rspan = tbl_cells[i].rowspan;
  8430. int w = prefix[col + span] - prefix[col];
  8431. int h = 0;
  8432. int sl = l->left, sr = l->right, sy = l->y;
  8433. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  8434. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  8435. int sal = l->align;
  8436. int deco;
  8437. for (int j = 0; j < rspan; j++)
  8438. h += rowh[row + j];
  8439. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  8440. cs.width_kind = 0;
  8441. cs.max_width_kind = 0;
  8442. cs.box_sizing = 0;
  8443. deco = mp_px(&cs, 4, avail) +
  8444. mp_px(&cs, 6, avail) +
  8445. cs.border_w[0] + cs.border_w[2];
  8446. cs.height_kind = 1;
  8447. cs.height = h > deco ? h - deco : 0;
  8448. /* The block painter reads block_h[] from the measure pass; make
  8449. * the table cell fill its row/rowspan, not just its content. */
  8450. if (h > 0 && h < 65536)
  8451. block_h[tbl_cells[i].node] = (unsigned short)h;
  8452. l->left = prefix[col];
  8453. l->right = l->left + w;
  8454. l->y = rowy[row];
  8455. l->line_x = l->left;
  8456. l->run_x = l->left;
  8457. l->line_y = l->y;
  8458. l->line_h = 0;
  8459. l->nruns = 0;
  8460. l->space_pending = 0;
  8461. l->align = cs.align;
  8462. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  8463. l->left = sl;
  8464. l->right = sr;
  8465. l->y = sy;
  8466. l->line_x = slx;
  8467. l->run_x = srx;
  8468. l->line_y = sly;
  8469. l->line_h = slh;
  8470. l->nruns = snr;
  8471. l->space_pending = ssp;
  8472. l->align = sal;
  8473. }
  8474. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  8475. table_active = 0;
  8476. }
  8477. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  8478. * flow so they sit above it, like CSS painting order. Their flow origin is
  8479. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  8480. struct br_deferred {
  8481. unsigned int node;
  8482. int flow_y, flow_left, flow_right;
  8483. unsigned short link;
  8484. signed short z_index;
  8485. unsigned char z_set;
  8486. unsigned int order;
  8487. };
  8488. /* Positioned boxes painted after the flow. News front pages have one or two
  8489. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  8490. * old 16 entries the rest fell back into the flow, so a hero image landed
  8491. * below its padding-top aspect box instead of on top of it. */
  8492. #define BR_MAX_DEFERRED 256
  8493. static struct br_deferred deferred[BR_MAX_DEFERRED];
  8494. static int ndeferred;
  8495. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  8496. * element's line. A block-level pseudo-element gets its own line; its box
  8497. * (margins, padding, background) is not drawn. */
  8498. static void emit_pseudo(struct lay *l, unsigned int node,
  8499. const struct br_style *st, int pe, unsigned short link)
  8500. {
  8501. char buf[160];
  8502. struct br_style ps;
  8503. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  8504. unsigned int i = 0;
  8505. int block, space_w;
  8506. if (!n)
  8507. return;
  8508. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  8509. if (block)
  8510. flush_line(l);
  8511. if (ps.uppercase)
  8512. for (i = 0; i < n; i++)
  8513. if (buf[i] >= 'a' && buf[i] <= 'z')
  8514. buf[i] = (char)(buf[i] - 'a' + 'A');
  8515. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  8516. if (space_w <= 0)
  8517. space_w = 8;
  8518. i = 0;
  8519. while (i < n) {
  8520. char word[28];
  8521. unsigned int k = 0;
  8522. int w;
  8523. if (buf[i] == ' ') {
  8524. l->space_pending = 1;
  8525. i++;
  8526. continue;
  8527. }
  8528. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  8529. word[k++] = buf[i++];
  8530. word[k] = '\0';
  8531. if (l->space_pending &&
  8532. (l->nruns > 0 || l->line_x > l->line_left) &&
  8533. l->line_x + space_w <= l->line_right)
  8534. l->line_x += space_w;
  8535. l->space_pending = 0;
  8536. w = (int)face_text_width(l->ui, &ps, word, k);
  8537. if (l->line_x + w > l->line_right &&
  8538. (l->nruns > 0 || l->line_x > l->line_left))
  8539. flush_line(l);
  8540. add_run(l, 0, 0, &ps, link, word);
  8541. }
  8542. if (block)
  8543. flush_line(l);
  8544. }
  8545. static void layout_children(struct lay *l, unsigned int parent,
  8546. const struct br_style *pst, int depth,
  8547. unsigned short link)
  8548. {
  8549. unsigned int n;
  8550. if (depth > 48)
  8551. return;
  8552. emit_pseudo(l, parent, pst, 1, link);
  8553. n = doc.nodes[parent].first;
  8554. while (n) {
  8555. struct br_node *nd = &doc.nodes[n];
  8556. struct br_style cs;
  8557. unsigned short lk = link;
  8558. if (nd->type == BR_NODE_TEXT) {
  8559. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  8560. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  8561. n = nd->next;
  8562. continue;
  8563. }
  8564. br_style_for(&doc, n, pst, &cs);
  8565. if (cs.display == BR_DISPLAY_NONE) {
  8566. n = nd->next;
  8567. continue;
  8568. }
  8569. if (cs.clear && l->float_active) {
  8570. flush_line(l);
  8571. if (l->y < l->float_bottom)
  8572. l->y = l->float_bottom;
  8573. l->float_active = 0;
  8574. l->line_x = l->left;
  8575. l->run_x = l->left;
  8576. l->line_left = l->left;
  8577. l->line_right = l->right;
  8578. l->line_y = l->y;
  8579. l->line_h = 0;
  8580. l->nruns = 0;
  8581. l->space_pending = 0;
  8582. }
  8583. if (nd->tag == BR_TAG_A && nd->href_off)
  8584. lk = (unsigned short)n;
  8585. if (cs.pos == 1 || cs.pos == 2 ||
  8586. (cs.pos == 3 && cs.z_set)) {
  8587. if (cs.pos == 3 && l->draw &&
  8588. ndeferred < BR_MAX_DEFERRED) {
  8589. /* Relative z-index: measure and advance the flow
  8590. * without painting, then paint it in the
  8591. * deferred (stacked) pass. */
  8592. int fy = l->y, fl = l->left, fr = l->right;
  8593. int save_draw = l->draw;
  8594. l->draw = 0;
  8595. layout_block(l, n, &cs, depth + 1, lk);
  8596. l->draw = save_draw;
  8597. deferred[ndeferred].node = n;
  8598. deferred[ndeferred].flow_y = fy;
  8599. deferred[ndeferred].flow_left = fl;
  8600. deferred[ndeferred].flow_right = fr;
  8601. deferred[ndeferred].link = lk;
  8602. deferred[ndeferred].z_index = cs.z_index;
  8603. deferred[ndeferred].z_set = cs.z_set;
  8604. deferred[ndeferred].order = (unsigned int)ndeferred;
  8605. ndeferred++;
  8606. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  8607. deferred[ndeferred].node = n;
  8608. deferred[ndeferred].flow_y =
  8609. cs.pos == 1 ? l->cb_top : l->y;
  8610. deferred[ndeferred].flow_left =
  8611. cs.pos == 1 ? l->cb_left : l->left;
  8612. deferred[ndeferred].flow_right =
  8613. cs.pos == 1 ? l->cb_right : l->right;
  8614. deferred[ndeferred].link = lk;
  8615. deferred[ndeferred].z_index = cs.z_index;
  8616. deferred[ndeferred].z_set = cs.z_set;
  8617. deferred[ndeferred].order = (unsigned int)ndeferred;
  8618. ndeferred++;
  8619. } else if (l->draw && cs.pos == 1) {
  8620. /* Deferred list full: paint in place, but still
  8621. * against the containing block, not the flow. */
  8622. int fy = l->y, fl = l->left, fr = l->right;
  8623. l->y = l->cb_top;
  8624. l->left = l->cb_left;
  8625. l->right = l->cb_right;
  8626. layout_block(l, n, &cs, depth + 1, lk);
  8627. l->y = fy;
  8628. l->left = fl;
  8629. l->right = fr;
  8630. } else {
  8631. layout_block(l, n, &cs, depth + 1, lk);
  8632. }
  8633. if (cs.pos == 1 && block_h[n] &&
  8634. doc.nodes[n].class_off) {
  8635. const char *cl = doc.attrs +
  8636. doc.nodes[n].class_off;
  8637. if ((contains_ci(cl, "poster-wrapper") ||
  8638. contains_ci(cl, "ts-picture")) &&
  8639. !has_skeleton_sibling(n))
  8640. l->y += block_h[n];
  8641. }
  8642. n = nd->next;
  8643. continue;
  8644. }
  8645. if (nd->tag == BR_TAG_BR) {
  8646. flush_line(l);
  8647. n = nd->next;
  8648. continue;
  8649. }
  8650. if (nd->tag == BR_TAG_HR) {
  8651. flush_line(l);
  8652. if (l->draw)
  8653. ngui_fill_rect(l->ui,
  8654. (struct ngui_rect){l->left, l->y + 2,
  8655. l->right - l->left, 1}, BR_GRAY);
  8656. l->y += 8;
  8657. n = nd->next;
  8658. continue;
  8659. }
  8660. if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  8661. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) {
  8662. if (!(nd->tag == BR_TAG_INPUT &&
  8663. s_eq(br_type(&doc, n), "hidden"))) {
  8664. form_fill_line = pst->display ==
  8665. BR_DISPLAY_FLEX &&
  8666. pst->flex_col;
  8667. add_form_run(l, n, &cs, lk);
  8668. form_fill_line = 0;
  8669. }
  8670. n = nd->next;
  8671. continue;
  8672. }
  8673. if (nd->tag == BR_TAG_IMG) {
  8674. add_image_run(l, n, &cs, lk);
  8675. n = nd->next;
  8676. continue;
  8677. }
  8678. if (nd->tag == BR_TAG_VIDEO) {
  8679. layout_block(l, n, &cs, depth + 1, lk);
  8680. n = nd->next;
  8681. continue;
  8682. }
  8683. if (cs.float_left) {
  8684. n = layout_float_group(l, n, pst, depth, lk);
  8685. continue;
  8686. }
  8687. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8688. n = layout_inline_blocks(l, n, pst, depth, link);
  8689. continue;
  8690. }
  8691. /* A flex container is block-level like any block box even when
  8692. * the element is an inline tag such as <a> (a link card with
  8693. * display:flex is common on news sites). Without the block box
  8694. * its children were laid out in the parent flow with a 0x0 box
  8695. * of their own. */
  8696. /* inline-flex around inline content only ("| mehr" link
  8697. * tails, icon+label pills) stays in the text line. */
  8698. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  8699. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  8700. !flex_wants_row(n, &cs)) {
  8701. layout_children(l, n, &cs, depth + 1, lk);
  8702. } else if (cs.display == BR_DISPLAY_BLOCK ||
  8703. cs.display == BR_DISPLAY_FLEX ||
  8704. br_tag_is_block(nd->tag))
  8705. layout_block(l, n, &cs, depth + 1, lk);
  8706. else {
  8707. layout_children(l, n, &cs, depth + 1, lk);
  8708. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  8709. l->space_pending = 1;
  8710. }
  8711. n = nd->next;
  8712. }
  8713. emit_pseudo(l, parent, pst, 2, link);
  8714. }
  8715. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  8716. * runs and a recursive page can otherwise overflow the stack. */
  8717. static struct lay layout_state;
  8718. static int measure_page(int left, int right)
  8719. {
  8720. struct lay *l = &layout_state;
  8721. struct br_style base = base_style();
  8722. unsigned int i;
  8723. for (i = 0; i < BR_MAX_NODES; i++) {
  8724. block_h[i] = 0;
  8725. img_top[i] = 0;
  8726. block_top[i] = 0;
  8727. img_h[i] = 0;
  8728. layout_boxes[i].valid = 0;
  8729. }
  8730. memset(li_marker, 0, sizeof(li_marker));
  8731. l->draw = 0;
  8732. l->ui = &ui;
  8733. l->left = left;
  8734. l->right = right;
  8735. l->y = 0;
  8736. l->line_x = left;
  8737. l->run_x = left;
  8738. l->line_left = left;
  8739. l->line_right = right;
  8740. l->line_y = 0;
  8741. l->line_h = 0;
  8742. l->align = BR_ALIGN_LEFT;
  8743. l->cb_h = layout_view_h;
  8744. l->float_active = 0;
  8745. l->parent_top = 0;
  8746. l->cb_left = left;
  8747. l->cb_right = right;
  8748. l->cb_top = 0;
  8749. l->depth = 0;
  8750. l->nruns = 0;
  8751. l->space_pending = 0;
  8752. layout_children(l, doc.root, &base, 0, 0);
  8753. return l->y + 8;
  8754. }
  8755. static int deferred_cmp(const struct br_deferred *a,
  8756. const struct br_deferred *b)
  8757. {
  8758. int az = a->z_set ? a->z_index : 0;
  8759. int bz = b->z_set ? b->z_index : 0;
  8760. if (az != bz)
  8761. return az < bz ? -1 : 1;
  8762. if (a->order != b->order)
  8763. return a->order < b->order ? -1 : 1;
  8764. return 0;
  8765. }
  8766. static void sort_deferred(void)
  8767. {
  8768. int i;
  8769. for (i = 1; i < ndeferred; i++) {
  8770. struct br_deferred key = deferred[i];
  8771. int j = i;
  8772. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  8773. deferred[j] = deferred[j - 1];
  8774. j--;
  8775. }
  8776. deferred[j] = key;
  8777. }
  8778. }
  8779. static void render_page(int left, int right, int y0)
  8780. {
  8781. struct lay *l = &layout_state;
  8782. struct br_style base = base_style();
  8783. l->draw = 1;
  8784. l->ui = &ui;
  8785. l->left = left;
  8786. l->right = right;
  8787. l->y = y0;
  8788. l->line_x = left;
  8789. l->run_x = left;
  8790. l->line_left = left;
  8791. l->line_right = right;
  8792. l->line_y = y0;
  8793. l->line_h = 0;
  8794. l->align = BR_ALIGN_LEFT;
  8795. l->cb_h = layout_view_h;
  8796. l->float_active = 0;
  8797. l->parent_top = 0;
  8798. l->cb_left = left;
  8799. l->cb_right = right;
  8800. l->cb_top = y0;
  8801. l->depth = 0;
  8802. l->nruns = 0;
  8803. l->space_pending = 0;
  8804. nhits = 0;
  8805. ndeferred = 0;
  8806. layout_children(l, doc.root, &base, 0, 0);
  8807. sort_deferred();
  8808. {
  8809. int i;
  8810. for (i = 0; i < ndeferred; i++) {
  8811. struct br_style st;
  8812. br_style_for(&doc, deferred[i].node, &base, &st);
  8813. if (st.display == BR_DISPLAY_NONE)
  8814. continue;
  8815. l->draw = 1;
  8816. l->left = deferred[i].flow_left;
  8817. l->right = deferred[i].flow_right;
  8818. l->y = deferred[i].flow_y;
  8819. l->line_x = l->left;
  8820. l->run_x = l->left;
  8821. l->line_y = l->y;
  8822. l->line_h = 0;
  8823. l->nruns = 0;
  8824. l->space_pending = 0;
  8825. l->align = st.align;
  8826. if (st.pos == 2 && block_h[deferred[i].node]) {
  8827. struct ngui_rect clip;
  8828. int ch = block_h[deferred[i].node] + 24;
  8829. clip.x = page_rect.x;
  8830. clip.y = page_rect.y;
  8831. clip.w = page_rect.w - 12;
  8832. if (ch > page_rect.h)
  8833. ch = page_rect.h;
  8834. clip.h = ch;
  8835. ngui_push_clip(&ui, clip);
  8836. if (st.has_bg)
  8837. ngui_fill_rect(&ui, clip, st.bg);
  8838. layout_block(l, deferred[i].node, &st, 0,
  8839. deferred[i].link);
  8840. ngui_pop_clip(&ui);
  8841. } else {
  8842. layout_block(l, deferred[i].node, &st, 0,
  8843. deferred[i].link);
  8844. }
  8845. }
  8846. }
  8847. }
  8848. /* ---- UI ---- */
  8849. static int find_hit(int x, int y)
  8850. {
  8851. int i;
  8852. for (i = nhits - 1; i >= 0; i--) {
  8853. struct hit *h = &hits[i];
  8854. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  8855. y < h->y + h->h)
  8856. return (int)h->node;
  8857. }
  8858. return 0;
  8859. }
  8860. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  8861. {
  8862. int x = r.x + 4, y = r.y + 4, h = 22;
  8863. int compact = r.w < 560;
  8864. int go_w = r.w < 420 ? 32 : 42;
  8865. int in_x, in_w, res;
  8866. ngui_fill_rect(&ui, r, ui.theme.panel);
  8867. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  8868. ui.theme.border);
  8869. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  8870. NGUI_ICON_CHEVRON_LEFT))
  8871. *action |= ACT_BACK;
  8872. x += 32;
  8873. if (!compact) {
  8874. if (ngui_icon_button(&ui, ID_FORWARD,
  8875. (struct ngui_rect){x, y, 28, h},
  8876. NGUI_ICON_CHEVRON_RIGHT))
  8877. *action |= ACT_FORWARD;
  8878. x += 32;
  8879. }
  8880. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  8881. NGUI_ICON_REFRESH))
  8882. *action |= ACT_RELOAD;
  8883. x += 32;
  8884. if (!compact) {
  8885. if (ngui_icon_button(&ui, ID_HOME,
  8886. (struct ngui_rect){x, y, 28, h},
  8887. NGUI_ICON_HOME))
  8888. *action |= ACT_HOME;
  8889. x += 32;
  8890. }
  8891. in_x = x + 2;
  8892. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  8893. if (in_w < 60)
  8894. in_w = 60;
  8895. res = ngui_text_input(&ui, ID_URL,
  8896. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  8897. if (res & NGUI_INPUT_SUBMIT)
  8898. *action |= ACT_NAV;
  8899. if (res & NGUI_INPUT_CANCEL)
  8900. ngui_set_focus(&ui, 0);
  8901. if (ngui_button(&ui, ID_GO,
  8902. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  8903. "Go"))
  8904. *action |= ACT_NAV;
  8905. }
  8906. static int page_hover_node(void)
  8907. {
  8908. if (!ui.inside)
  8909. return 0;
  8910. if (ui.mouse_x < page_rect.x ||
  8911. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  8912. ui.mouse_y < page_rect.y ||
  8913. ui.mouse_y >= page_rect.y + page_rect.h)
  8914. return 0;
  8915. return find_hit(ui.mouse_x, ui.mouse_y);
  8916. }
  8917. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  8918. {
  8919. int x, y, w = page.w, h = page.h;
  8920. if (!src || w <= 0 || h <= 0)
  8921. return;
  8922. for (y = 0; y < h; y++) {
  8923. unsigned short *s = src + (page.y + y) * sw + page.x;
  8924. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  8925. for (x = 0; x + 1 < w; x += 2) {
  8926. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  8927. }
  8928. if (x < w)
  8929. d[x] = s[x];
  8930. }
  8931. }
  8932. static void draw_page(struct ngui_rect page)
  8933. {
  8934. int left, right, ch;
  8935. int old_panel, old_dim;
  8936. unsigned short *saved_px;
  8937. unsigned short page_bg = ui.theme.bg;
  8938. int saved_w, saved_h, use_buf;
  8939. page_rect = page;
  8940. {
  8941. unsigned int root = doc.nnode > 1 ?
  8942. br_find_tag(&doc, BR_TAG_HTML) : 0;
  8943. unsigned int body = doc.nnode > 1 ?
  8944. br_find_tag(&doc, BR_TAG_BODY) : 0;
  8945. struct br_style bs;
  8946. if (root) {
  8947. style_for_node(root - 1, &bs);
  8948. if (bs.has_bg)
  8949. page_bg = bs.bg;
  8950. }
  8951. if (body) {
  8952. style_for_node(body - 1, &bs);
  8953. if (bs.has_bg)
  8954. page_bg = bs.bg;
  8955. }
  8956. }
  8957. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  8958. page_cache_valid && layout_valid &&
  8959. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  8960. !(ui.scroll_y &&
  8961. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  8962. page_scroll.offset == page_cache_scroll &&
  8963. page_cache_nnode == doc.nnode &&
  8964. page_cache_x == page.x && page_cache_y == page.y &&
  8965. page_cache_w == page.w && page_cache_h == page.h) {
  8966. blit_page(page, page_backbuf, pagebuf_w);
  8967. return;
  8968. }
  8969. ngui_fill_rect(&ui, page, page_bg);
  8970. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  8971. const char *s = page_loading ? "Loading..." : "No page";
  8972. int w = (int)ngui_text_width_ui(&ui, s);
  8973. ngui_text(&ui, page.x + (page.w - w) / 2,
  8974. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  8975. page_scroll.content_h = 0;
  8976. page_scroll.view_h = page.h;
  8977. page_cache_valid = 0;
  8978. return;
  8979. }
  8980. if (page.w < 40 || page.h < 40) {
  8981. page_cache_valid = 0;
  8982. return;
  8983. }
  8984. saved_px = ui.px;
  8985. saved_w = ui.w;
  8986. saved_h = ui.h;
  8987. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  8988. if (use_buf) {
  8989. ui.px = page_backbuf;
  8990. ui.w = pagebuf_w;
  8991. ui.h = pagebuf_h;
  8992. ngui_fill_rect(&ui, page, page_bg);
  8993. }
  8994. left = page.x + 8;
  8995. right = page.x + page.w - 16;
  8996. if (!layout_valid || left != layout_left || right != layout_right ||
  8997. layout_nnode != doc.nnode) {
  8998. layout_view_h = page.h - 8;
  8999. layout_content_h = measure_page(left, right);
  9000. layout_valid = 1;
  9001. layout_left = left;
  9002. layout_right = right;
  9003. layout_nnode = doc.nnode;
  9004. /* Scripts that measured before any layout (offsetWidth on
  9005. * mount) get a resize event once real boxes exist, and again
  9006. * whenever the page width changes. */
  9007. if (js_browser_active() && right - left != resize_sent_w)
  9008. resize_pending = 1;
  9009. }
  9010. ch = layout_content_h;
  9011. page_scroll.content_h = ch;
  9012. page_scroll.view_h = page.h;
  9013. ngui_scroll_begin(&ui, page, &page_scroll);
  9014. ngui_scroll_wheel(&ui, page, &page_scroll);
  9015. render_page(left, right, page.y + 4 - page_scroll.offset);
  9016. old_panel = ui.theme.panel_alt;
  9017. old_dim = ui.theme.text_dim;
  9018. ui.theme.panel_alt = 0xC618;
  9019. ui.theme.text_dim = 0x8410;
  9020. ngui_scroll_end(&ui, page, &page_scroll);
  9021. ui.theme.panel_alt = old_panel;
  9022. ui.theme.text_dim = old_dim;
  9023. if (use_buf) {
  9024. ui.px = saved_px;
  9025. ui.w = saved_w;
  9026. ui.h = saved_h;
  9027. blit_page(page, page_backbuf, pagebuf_w);
  9028. page_cache_valid = 1;
  9029. page_cache_scroll = page_scroll.offset;
  9030. page_cache_nnode = doc.nnode;
  9031. page_cache_x = page.x;
  9032. page_cache_y = page.y;
  9033. page_cache_w = page.w;
  9034. page_cache_h = page.h;
  9035. } else {
  9036. page_cache_valid = 0;
  9037. }
  9038. }
  9039. static void draw_status(struct ngui_rect r)
  9040. {
  9041. char msg[BR_URL_MAX + 32];
  9042. unsigned int n = 0;
  9043. int hover = page_hover_node();
  9044. unsigned short color;
  9045. const char *kind;
  9046. ngui_fill_rect(&ui, r, ui.theme.panel);
  9047. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  9048. ui.theme.border);
  9049. if (hover) {
  9050. const char *href = br_href(&doc, (unsigned int)hover);
  9051. char url[BR_URL_MAX];
  9052. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  9053. s_append(msg, &n, "Link: ", sizeof(msg));
  9054. s_append(msg, &n, url, sizeof(msg));
  9055. } else {
  9056. s_copy(msg, "Link", sizeof(msg));
  9057. }
  9058. color = ui.theme.accent;
  9059. } else if (status_text[0]) {
  9060. s_copy(msg, status_text, sizeof(msg));
  9061. color = status_error ? ui.theme.error : ui.theme.text;
  9062. } else if (page_title[0]) {
  9063. s_copy(msg, page_title, sizeof(msg));
  9064. color = ui.theme.text;
  9065. } else {
  9066. s_copy(msg, "Ready", sizeof(msg));
  9067. color = ui.theme.text_dim;
  9068. }
  9069. kind = s_eq(page_url, "about:home") ? "HOME" :
  9070. page_is_local ? "FILE" :
  9071. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  9072. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  9073. {
  9074. int kw = (int)ngui_text_width_ui(&ui, kind);
  9075. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  9076. ui.theme.text_dim);
  9077. }
  9078. }
  9079. static void draw(unsigned int *action)
  9080. {
  9081. struct ngui_rect r = {0, 0, ui.w, ui.h};
  9082. struct ngui_rect toolbar, status, page;
  9083. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  9084. status = ngui_cut_bottom(&r, BR_STATUS_H);
  9085. page = r;
  9086. draw_toolbar(toolbar, action);
  9087. draw_page(page);
  9088. draw_status(status);
  9089. }
  9090. static void redraw_now(void)
  9091. {
  9092. unsigned int action = 0;
  9093. ngui_begin(&ui);
  9094. draw(&action);
  9095. ngui_end(&ui);
  9096. }
  9097. static void handle_keys(unsigned int *action)
  9098. {
  9099. int k, scrolled = 0;
  9100. if (form_focus >= doc.nnode)
  9101. form_focus = 0;
  9102. if (form_focus && !ngui_focus(&ui)) {
  9103. while ((k = ngui_key(&ui)) != 0)
  9104. form_key(k);
  9105. return;
  9106. }
  9107. /* Batch queued page keys: a slow full-page render must not make a
  9108. * held Page Down advance only once every few frames. */
  9109. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  9110. scrolled++;
  9111. if (scrolled)
  9112. ngui_invalidate(&ui);
  9113. if (ngui_focus(&ui))
  9114. return;
  9115. while ((k = ngui_key(&ui)) != 0) {
  9116. switch (k) {
  9117. case NGUI_KEY_ESC:
  9118. *action |= ACT_CLOSE;
  9119. break;
  9120. case NGUI_KEY_TAB:
  9121. case 0x0C: /* Ctrl+L */
  9122. ngui_set_focus(&ui, ID_URL);
  9123. break;
  9124. case 0x12: /* Ctrl+R */
  9125. *action |= ACT_RELOAD;
  9126. break;
  9127. case NGUI_KEY_BACKSPACE:
  9128. *action |= ACT_BACK;
  9129. break;
  9130. case NGUI_KEY_UP:
  9131. ngui_scroll_to(&page_scroll,
  9132. page_scroll.offset - 24);
  9133. ngui_invalidate(&ui);
  9134. break;
  9135. case NGUI_KEY_DOWN:
  9136. ngui_scroll_to(&page_scroll,
  9137. page_scroll.offset + 24);
  9138. ngui_invalidate(&ui);
  9139. break;
  9140. case NGUI_KEY_HOME:
  9141. ngui_scroll_to(&page_scroll, 0);
  9142. ngui_invalidate(&ui);
  9143. break;
  9144. case NGUI_KEY_END:
  9145. ngui_scroll_to(&page_scroll,
  9146. page_scroll.content_h -
  9147. page_scroll.view_h);
  9148. ngui_invalidate(&ui);
  9149. break;
  9150. default:
  9151. break;
  9152. }
  9153. }
  9154. }
  9155. static unsigned int form_ancestor(unsigned int node)
  9156. {
  9157. unsigned int p = node;
  9158. while (p && p < doc.nnode) {
  9159. if (doc.nodes[p].tag == BR_TAG_FORM &&
  9160. doc.nodes[p].type == BR_NODE_ELEM)
  9161. return p;
  9162. p = doc.nodes[p].parent;
  9163. }
  9164. return 0;
  9165. }
  9166. static int form_descendant(unsigned int node, unsigned int form)
  9167. {
  9168. unsigned int p = node;
  9169. while (p && p < doc.nnode) {
  9170. if (p == form)
  9171. return 1;
  9172. p = doc.nodes[p].parent;
  9173. }
  9174. return 0;
  9175. }
  9176. static void form_reset_form(unsigned int form)
  9177. {
  9178. unsigned int i;
  9179. for (i = 0; i < FORM_MAX; i++)
  9180. if (form_states[i].used &&
  9181. form_descendant(form_states[i].node, form))
  9182. form_states[i].used = 0;
  9183. form_focus = 0;
  9184. }
  9185. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  9186. const char *s)
  9187. {
  9188. static const char hex[] = "0123456789ABCDEF";
  9189. while (s && *s && *n + 1 < cap) {
  9190. unsigned char c = (unsigned char)*s++;
  9191. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  9192. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  9193. c == '.' || c == '~') {
  9194. dst[(*n)++] = (char)c;
  9195. } else if (c == ' ') {
  9196. dst[(*n)++] = '+';
  9197. } else if (*n + 3 < cap) {
  9198. dst[(*n)++] = '%';
  9199. dst[(*n)++] = hex[c >> 4];
  9200. dst[(*n)++] = hex[c & 15];
  9201. }
  9202. }
  9203. dst[*n] = '\0';
  9204. }
  9205. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  9206. const char *name, const char *value, int *first)
  9207. {
  9208. if (!name || !name[0])
  9209. return;
  9210. if (!*first && *n + 1 < cap)
  9211. dst[(*n)++] = '&';
  9212. *first = 0;
  9213. form_url_append(dst, n, cap, name);
  9214. if (*n + 1 < cap)
  9215. dst[(*n)++] = '=';
  9216. form_url_append(dst, n, cap, value ? value : "");
  9217. dst[*n] = '\0';
  9218. }
  9219. static int form_submit_form(unsigned int node, int fire_event)
  9220. {
  9221. unsigned int form = form_ancestor(node);
  9222. char action[BR_URL_MAX], query[2048];
  9223. unsigned int qn = 0, i;
  9224. int first = 1, is_post = 0;
  9225. const char *a, *method;
  9226. if (!form)
  9227. return 0;
  9228. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  9229. return 0;
  9230. method = br_find_attr(&doc, form, "method");
  9231. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  9232. is_post = 1;
  9233. a = br_find_attr(&doc, form, "action");
  9234. if (a && a[0]) {
  9235. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  9236. return 0;
  9237. } else {
  9238. s_copy(action, page_url, sizeof(action));
  9239. }
  9240. query[0] = '\0';
  9241. for (i = 0; i < doc.nnode; i++) {
  9242. struct br_node *nd = &doc.nodes[i];
  9243. struct form_state *fs;
  9244. const char *name;
  9245. const char *value = "";
  9246. if (nd->type != BR_NODE_ELEM || i == form ||
  9247. !form_descendant(i, form))
  9248. continue;
  9249. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  9250. nd->tag != BR_TAG_SELECT)
  9251. continue;
  9252. if (form_disabled(i))
  9253. continue;
  9254. name = br_find_attr(&doc, i, "name");
  9255. if (!name || !name[0])
  9256. continue;
  9257. fs = form_get(i, 1);
  9258. if (!fs)
  9259. continue;
  9260. if (nd->tag == BR_TAG_SELECT) {
  9261. char opt[64];
  9262. if (!form_option_text(i, fs->selected, opt,
  9263. sizeof(opt)))
  9264. s_copy(opt, "", sizeof(opt));
  9265. value = opt;
  9266. {
  9267. unsigned int c, oi = 0;
  9268. for (c = nd->first; c;
  9269. c = doc.nodes[c].next) {
  9270. if (doc.nodes[c].type != BR_NODE_ELEM ||
  9271. doc.nodes[c].tag != BR_TAG_OPTION)
  9272. continue;
  9273. if (oi == fs->selected) {
  9274. const char *v =
  9275. br_value(&doc, c);
  9276. if (v && v[0])
  9277. value = v;
  9278. break;
  9279. }
  9280. oi++;
  9281. }
  9282. }
  9283. } else if (nd->tag == BR_TAG_INPUT) {
  9284. int kind = form_kind_of(i);
  9285. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  9286. if (!fs->checked)
  9287. continue;
  9288. value = br_value(&doc, i);
  9289. if (!value || !value[0])
  9290. value = "on";
  9291. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  9292. kind == FORM_BUTTON) {
  9293. if (i != node)
  9294. continue;
  9295. value = fs->value;
  9296. } else {
  9297. value = fs->value;
  9298. }
  9299. } else {
  9300. value = fs->value;
  9301. }
  9302. form_add_param(query, &qn, sizeof(query), name, value, &first);
  9303. }
  9304. if (is_post) {
  9305. if (action[0] == '/') {
  9306. set_status("POST forms need an HTTP action URL", 1, 4000);
  9307. ngui_invalidate(&ui);
  9308. return 0;
  9309. }
  9310. if (qn >= sizeof(pending_post))
  9311. qn = sizeof(pending_post) - 1;
  9312. if (qn)
  9313. memcpy(pending_post, query, qn);
  9314. pending_post[qn] = '\0';
  9315. pending_post_len = qn;
  9316. pending_post_is = 1;
  9317. } else {
  9318. pending_post_len = 0;
  9319. pending_post_is = 0;
  9320. if (qn) {
  9321. unsigned int an = s_len(action);
  9322. if (an + qn + 2 < sizeof(action)) {
  9323. action[an++] = strchr(action, '?') ? '&' : '?';
  9324. action[an] = '\0';
  9325. s_copy(action + an, query,
  9326. sizeof(action) - an);
  9327. }
  9328. }
  9329. }
  9330. s_copy(pending_url, action, sizeof(pending_url));
  9331. pending_action |= ACT_NAV;
  9332. cancel_fetch = 1;
  9333. ngui_invalidate(&ui);
  9334. return 1;
  9335. }
  9336. static void form_reset_event(unsigned int form)
  9337. {
  9338. if (form && !js_browser_event(form, "reset", 1, 1))
  9339. return;
  9340. if (form)
  9341. form_reset_form(form);
  9342. else
  9343. form_reset_state();
  9344. form_dirty = 0;
  9345. layout_valid = 0;
  9346. ngui_invalidate(&ui);
  9347. }
  9348. static void form_blur(void)
  9349. {
  9350. unsigned int node = form_focus;
  9351. form_focus = 0;
  9352. if (node && form_dirty) {
  9353. form_dirty = 0;
  9354. js_browser_event(node, "change", 1, 0);
  9355. }
  9356. }
  9357. static void form_click(unsigned int node)
  9358. {
  9359. struct form_state *fs;
  9360. int kind, changed = 0;
  9361. if (!form_is_control(node) || form_disabled(node))
  9362. return;
  9363. if (form_focus != node)
  9364. form_blur();
  9365. if (!js_browser_event(node, "click", 1, 1))
  9366. return;
  9367. fs = form_get(node, 1);
  9368. if (!fs)
  9369. return;
  9370. kind = form_kind_of(node);
  9371. form_focus = node;
  9372. form_dirty = 0;
  9373. if (kind == FORM_CHECKBOX) {
  9374. fs->checked = !fs->checked;
  9375. changed = 1;
  9376. } else if (kind == FORM_RADIO) {
  9377. const char *name = br_find_attr(&doc, node, "name");
  9378. unsigned int i;
  9379. fs->checked = 1;
  9380. changed = 1;
  9381. if (name) {
  9382. for (i = 0; i < FORM_MAX; i++) {
  9383. struct form_state *o = &form_states[i];
  9384. if (!o->used || o->node == node)
  9385. continue;
  9386. if (form_kind_of(o->node) == FORM_RADIO) {
  9387. const char *on = br_find_attr(&doc,
  9388. o->node,
  9389. "name");
  9390. if (on && s_eq(on, name))
  9391. o->checked = 0;
  9392. }
  9393. }
  9394. }
  9395. } else if (kind == FORM_SELECT) {
  9396. unsigned int n = form_option_count(node);
  9397. if (n) {
  9398. fs->selected = (unsigned char)
  9399. ((fs->selected + 1) % n);
  9400. changed = 1;
  9401. }
  9402. } else if (kind == FORM_SUBMIT) {
  9403. form_submit_form(node, 1);
  9404. return;
  9405. } else if (kind == FORM_RESET) {
  9406. form_reset_event(form_ancestor(node));
  9407. return;
  9408. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  9409. kind == FORM_TEXTAREA) {
  9410. fs->caret = fs->len;
  9411. }
  9412. if (changed) {
  9413. js_browser_event(node, "input", 1, 0);
  9414. js_browser_event(node, "change", 1, 0);
  9415. }
  9416. layout_valid = 0;
  9417. ngui_invalidate(&ui);
  9418. }
  9419. static void form_focus_next(void)
  9420. {
  9421. unsigned int start = form_focus ? form_focus + 1 : 0;
  9422. unsigned int i;
  9423. form_blur();
  9424. for (i = start; i < doc.nnode; i++) {
  9425. if (form_is_control(i) && !form_disabled(i) &&
  9426. !s_eq(br_type(&doc, i), "hidden")) {
  9427. form_focus = i;
  9428. layout_valid = 0;
  9429. ngui_invalidate(&ui);
  9430. return;
  9431. }
  9432. }
  9433. form_focus = 0;
  9434. layout_valid = 0;
  9435. ngui_invalidate(&ui);
  9436. }
  9437. static void form_key(int k)
  9438. {
  9439. struct form_state *fs;
  9440. int kind;
  9441. if (!form_focus || form_focus >= doc.nnode) {
  9442. form_focus = 0;
  9443. return;
  9444. }
  9445. fs = form_get(form_focus, 1);
  9446. if (!fs || form_disabled(form_focus))
  9447. return;
  9448. kind = form_kind_of(form_focus);
  9449. if (kind == FORM_SELECT) {
  9450. unsigned int n = form_option_count(form_focus);
  9451. int changed = 0;
  9452. if (k == NGUI_KEY_UP && n) {
  9453. fs->selected = (unsigned char)
  9454. ((fs->selected + n - 1) % n);
  9455. changed = 1;
  9456. } else if (k == NGUI_KEY_DOWN && n) {
  9457. fs->selected = (unsigned char)
  9458. ((fs->selected + 1) % n);
  9459. changed = 1;
  9460. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  9461. form_blur();
  9462. layout_valid = 0;
  9463. ngui_invalidate(&ui);
  9464. return;
  9465. } else {
  9466. return;
  9467. }
  9468. if (changed) {
  9469. js_browser_event(form_focus, "input", 1, 0);
  9470. js_browser_event(form_focus, "change", 1, 0);
  9471. }
  9472. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  9473. if (k == ' ') {
  9474. form_click(form_focus);
  9475. return;
  9476. }
  9477. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  9478. form_blur();
  9479. layout_valid = 0;
  9480. ngui_invalidate(&ui);
  9481. }
  9482. return;
  9483. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  9484. kind == FORM_RESET) {
  9485. if (k == NGUI_KEY_ESC) {
  9486. form_blur();
  9487. layout_valid = 0;
  9488. ngui_invalidate(&ui);
  9489. } else if (k == '\r' || k == '\n' || k == ' ') {
  9490. form_click(form_focus);
  9491. }
  9492. return;
  9493. } else if (k == NGUI_KEY_TAB) {
  9494. form_focus_next();
  9495. return;
  9496. } else if (k == NGUI_KEY_ESC) {
  9497. form_blur();
  9498. layout_valid = 0;
  9499. ngui_invalidate(&ui);
  9500. return;
  9501. } else if (k == '\r' || k == '\n') {
  9502. unsigned int node = form_focus;
  9503. form_blur();
  9504. if (form_ancestor(node))
  9505. form_submit_form(node, 1);
  9506. layout_valid = 0;
  9507. ngui_invalidate(&ui);
  9508. return;
  9509. } else if (k == NGUI_KEY_BACKSPACE) {
  9510. if (fs->caret) {
  9511. unsigned int i = --fs->caret;
  9512. for (; i < fs->len; i++)
  9513. fs->value[i] = fs->value[i + 1];
  9514. if (fs->len)
  9515. fs->len--;
  9516. form_dirty = 1;
  9517. js_browser_event(form_focus, "input", 1, 0);
  9518. }
  9519. } else if (k == NGUI_KEY_DELETE) {
  9520. if (fs->caret < fs->len) {
  9521. unsigned int i;
  9522. for (i = fs->caret; i < fs->len; i++)
  9523. fs->value[i] = fs->value[i + 1];
  9524. fs->len--;
  9525. form_dirty = 1;
  9526. js_browser_event(form_focus, "input", 1, 0);
  9527. }
  9528. } else if (k == NGUI_KEY_LEFT) {
  9529. if (fs->caret)
  9530. fs->caret--;
  9531. } else if (k == NGUI_KEY_RIGHT) {
  9532. if (fs->caret < fs->len)
  9533. fs->caret++;
  9534. } else if (k == NGUI_KEY_HOME) {
  9535. fs->caret = 0;
  9536. } else if (k == NGUI_KEY_END) {
  9537. fs->caret = fs->len;
  9538. } else if (k >= 32 && k < 127) {
  9539. if (fs->len < FORM_VALUE_MAX) {
  9540. unsigned int i;
  9541. for (i = fs->len; i > fs->caret; i--)
  9542. fs->value[i] = fs->value[i - 1];
  9543. fs->value[fs->caret++] = (char)k;
  9544. fs->len++;
  9545. form_dirty = 1;
  9546. js_browser_event(form_focus, "input", 1, 0);
  9547. }
  9548. } else {
  9549. return;
  9550. }
  9551. fs->value[fs->len] = '\0';
  9552. layout_valid = 0;
  9553. ngui_invalidate(&ui);
  9554. }
  9555. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  9556. * a same-document navigation: update the URL and fire hashchange. Returns
  9557. * 1 when handled. */
  9558. static int link_fragment_nav(unsigned int node)
  9559. {
  9560. const char *href = br_href(&doc, node);
  9561. char url[BR_URL_MAX];
  9562. unsigned int n = 0;
  9563. if (!href || !href[0] || !js_browser_active())
  9564. return 0;
  9565. if (href[0] == '#') {
  9566. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  9567. url[n] = page_url[n];
  9568. n++;
  9569. }
  9570. url[n] = '\0';
  9571. s_append(url, &n, href, sizeof(url));
  9572. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  9573. return 0;
  9574. }
  9575. if (!same_doc_fragment(url))
  9576. return href[0] == '#';
  9577. page_set_fragment(url, 1);
  9578. js_browser_hashchange();
  9579. return 1;
  9580. }
  9581. /* The innermost laid-out box under a screen point: the smallest valid box
  9582. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  9583. * Used to deliver clicks to elements that are neither links nor controls
  9584. * (a Vue <div role="button">, a card with a click listener). */
  9585. static unsigned int find_box_hit(int x, int y)
  9586. {
  9587. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  9588. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  9589. const struct br_layout_box *b = &layout_boxes[i];
  9590. unsigned int area;
  9591. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  9592. x < b->x || y < b->y || x >= b->x + b->w ||
  9593. y >= b->y + b->h)
  9594. continue;
  9595. area = (unsigned int)b->w * (unsigned int)b->h;
  9596. if (area <= best_area) {
  9597. best = i;
  9598. best_area = area;
  9599. }
  9600. }
  9601. return best;
  9602. }
  9603. static void handle_page_click(unsigned int *action)
  9604. {
  9605. int node;
  9606. char url[BR_URL_MAX];
  9607. if (!ui.pressed)
  9608. return;
  9609. if (ui.press_x < page_rect.x ||
  9610. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  9611. ui.press_y < page_rect.y ||
  9612. ui.press_y >= page_rect.y + page_rect.h)
  9613. return;
  9614. node = find_hit(ui.press_x, ui.press_y);
  9615. if (!node) {
  9616. unsigned int box;
  9617. if (!js_browser_active())
  9618. return;
  9619. box = find_box_hit(ui.press_x, ui.press_y);
  9620. if (box) {
  9621. form_blur();
  9622. js_browser_event(box, "click", 1, 1);
  9623. }
  9624. return;
  9625. }
  9626. if (form_is_control((unsigned int)node)) {
  9627. form_click((unsigned int)node);
  9628. return;
  9629. }
  9630. form_blur();
  9631. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  9632. return;
  9633. if (link_fragment_nav((unsigned int)node))
  9634. return;
  9635. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  9636. sizeof(url)) != 0)
  9637. return;
  9638. s_copy(click_url, url, sizeof(click_url));
  9639. *action |= ACT_NAV;
  9640. }
  9641. void _start(const char *arg)
  9642. {
  9643. struct win_info wi;
  9644. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  9645. u_win_create(960, 640, "Browser", &wi) != 0 &&
  9646. u_win_create(780, 540, "Browser", &wi) != 0) {
  9647. u_puts("browser: no graphics window\n");
  9648. u_exit(1);
  9649. }
  9650. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  9651. url_in.placeholder = "http://...";
  9652. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  9653. ui.theme.accent);
  9654. br_set_viewport(wi.width);
  9655. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  9656. s_copy(cwd, "/", sizeof(cwd));
  9657. heap_clear();
  9658. origin_cache_load();
  9659. css_cache_init();
  9660. script_cache_init();
  9661. persist_restore();
  9662. page_scroll.offset = 0;
  9663. page_scroll.content_h = 0;
  9664. if (arg && arg[0]) {
  9665. navigate(arg, 1);
  9666. } else {
  9667. load_home(1);
  9668. /* Start ready to type: keep the home page, but leave the address
  9669. * bar empty instead of showing "about:home". */
  9670. ngui_input_set(&url_in, "");
  9671. ngui_set_focus(&ui, ID_URL);
  9672. }
  9673. for (;;) {
  9674. unsigned int action = 0;
  9675. unsigned int now;
  9676. click_url[0] = '\0';
  9677. if (pending_action) {
  9678. action |= pending_action & ACT_WAIT_NAV;
  9679. if (pending_url[0])
  9680. s_copy(click_url, pending_url, sizeof(click_url));
  9681. pending_action = 0;
  9682. pending_url[0] = '\0';
  9683. cancel_fetch = 0;
  9684. } else if (preload_active) {
  9685. if (preload_wait)
  9686. preload_wait = 0;
  9687. else
  9688. preload_step();
  9689. } else if ((preload_pending &&
  9690. page_scroll.offset != preload_scroll) ||
  9691. (preload_rescan && layout_valid)) {
  9692. preload_scroll = page_scroll.offset;
  9693. preload_rescan = 0;
  9694. preload_pending = 0;
  9695. preload_node = 0;
  9696. preload_active = 1;
  9697. }
  9698. js_browser_tick();
  9699. if (resize_pending && !pending_action) {
  9700. resize_pending = 0;
  9701. resize_sent_w = layout_right - layout_left;
  9702. js_browser_window_event("resize");
  9703. }
  9704. persist_tick();
  9705. if (pending_action)
  9706. continue;
  9707. now = u_ticks_ms();
  9708. if (status_until && (int)(now - status_until) >= 0) {
  9709. status_text[0] = '\0';
  9710. status_until = 0;
  9711. status_error = 0;
  9712. ngui_invalidate(&ui);
  9713. }
  9714. if (!ngui_begin(&ui)) {
  9715. /* A queued navigation (e.g. Enter in the URL bar during
  9716. * a slow fetch) must be handled even when this frame
  9717. * needs no redraw. */
  9718. if (!action) {
  9719. fetch_workers_stop_if_unfocused();
  9720. u_sleep_ms(10);
  9721. continue;
  9722. }
  9723. } else {
  9724. draw(&action);
  9725. handle_keys(&action);
  9726. handle_page_click(&action);
  9727. ngui_end(&ui);
  9728. }
  9729. if (action & ACT_NAV) {
  9730. if (click_url[0]) {
  9731. navigate(click_url, 1);
  9732. click_url[0] = '\0';
  9733. } else {
  9734. navigate(url_in.text, 1);
  9735. }
  9736. }
  9737. if (action & ACT_BACK) {
  9738. if (hist_pos > 0) {
  9739. hist_pos--;
  9740. if (same_doc_fragment(history[hist_pos])) {
  9741. page_set_fragment(history[hist_pos], 0);
  9742. js_browser_hashchange();
  9743. } else {
  9744. navigate(history[hist_pos], 0);
  9745. }
  9746. }
  9747. }
  9748. if (action & ACT_FORWARD) {
  9749. if (hist_pos + 1 < hist_len) {
  9750. hist_pos++;
  9751. if (same_doc_fragment(history[hist_pos])) {
  9752. page_set_fragment(history[hist_pos], 0);
  9753. js_browser_hashchange();
  9754. } else {
  9755. navigate(history[hist_pos], 0);
  9756. }
  9757. }
  9758. }
  9759. if (action & ACT_RELOAD) {
  9760. if (s_eq(page_url, "about:home"))
  9761. load_home(0);
  9762. else
  9763. navigate(page_url, 0);
  9764. }
  9765. if (action & ACT_HOME)
  9766. load_home(1);
  9767. if (action & ACT_CLOSE)
  9768. quit = 1;
  9769. if (quit)
  9770. break;
  9771. if (pending_action)
  9772. continue;
  9773. fetch_workers_stop_if_unfocused();
  9774. u_sleep_ms(10);
  9775. }
  9776. fetch_workers_stop_all();
  9777. u_win_close();
  9778. u_exit(0);
  9779. }