browser.c 216 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759
  1. /* browser: a small HTML/CSS browser built on ngui, the image library and the
  2. * shared uhttp client.
  3. *
  4. * Inline JavaScript runs through the vendored MuJS engine (console.log,
  5. * alert, document.getElementById(...).textContent and location.href); forms
  6. * are not supported. External CSS is loaded over uhttp, and images are
  7. * decoded with img.c and drawn inline. Page-scoped buffers (page body,
  8. * rules and image bitmaps) come from the ring-3 libc heap; each image gets an
  9. * exact-size decode arena that is freed as soon as the scaled bitmap exists.
  10. * The DOM and the image/CSS I/O scratch use fixed static arenas.
  11. */
  12. #include <stdlib.h>
  13. #include <stdio.h>
  14. #include <string.h>
  15. #include <math.h>
  16. #include <ucmd_heap.h>
  17. #include "ucmd_lib.h"
  18. #include "ngui.h"
  19. #include "browser_html.h"
  20. #include "js_browser.h"
  21. #include "uhttp.h"
  22. #include "img.h"
  23. #include "inflate.h"
  24. #include "ufont.h"
  25. /* Start wide enough for the desktop nav; smaller screens fall back to
  26. * 960x640 and 780x540, which still fit a 1024x768 panel. */
  27. #define BR_W 1100
  28. #define BR_H 700
  29. #define BR_TOOLBAR_H 30
  30. #define BR_STATUS_H 18
  31. #define BR_PAGE_MAX (2u * 1024u * 1024u)
  32. #define BR_IMG_FILE_MAX (512u * 1024u)
  33. #define BR_IMG_PIX_MAX (8u * 1024u * 1024u)
  34. #define BR_MAX_IMAGES 16
  35. #define BR_IMG_ARENA_MAX (24u * 1024u * 1024u)
  36. #define BR_IMG_LAYOUT_W 1000
  37. #define BR_CSS_MAX (832u * 1024u)
  38. #define BR_CSS_COMP_MAX (192u * 1024u)
  39. #define BR_SCRIPT_MAX (512u * 1024u)
  40. #define FETCH_ABORT (-2)
  41. /* Session cache for remote stylesheets (per launch; cleared at startup). */
  42. #define CSS_CACHE_MAX 16
  43. #define CSS_CACHE_FILE_MAX (256u * 1024u)
  44. #define CSS_CACHE_PREFIX "bcss-"
  45. #define SCRIPT_CACHE_MAX 16
  46. #define SCRIPT_CACHE_FILE_MAX (512u * 1024u)
  47. #define SCRIPT_CACHE_PREFIX "bjs-"
  48. #define BR_MAX_SHEETS 6
  49. #define BR_HISTORY 16
  50. #define BR_URL_MAX 512
  51. #define BR_STATUS_MAX 200
  52. #define BR_IMG_RGB565(r, g, b) \
  53. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  54. #define BR_GRAY 0x8410
  55. enum {
  56. ID_URL = 1,
  57. ID_GO,
  58. ID_BACK,
  59. ID_FORWARD,
  60. ID_RELOAD,
  61. ID_HOME
  62. };
  63. #define ACT_NAV (1u << 0)
  64. #define ACT_BACK (1u << 1)
  65. #define ACT_FORWARD (1u << 2)
  66. #define ACT_RELOAD (1u << 3)
  67. #define ACT_HOME (1u << 4)
  68. #define ACT_CLOSE (1u << 5)
  69. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  70. ACT_HOME | ACT_CLOSE)
  71. struct br_image {
  72. int state; /* 0 empty, 1 ready */
  73. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  74. int native_w, native_h;
  75. char err[32];
  76. };
  77. static struct ngui ui;
  78. static struct ngui_input url_in;
  79. static struct ngui_scroll page_scroll;
  80. static struct br_doc doc;
  81. static struct br_image images[BR_MAX_IMAGES];
  82. static int image_count;
  83. /* Painted border boxes, in page/screen coordinates (layout starts at
  84. * page_rect.y + 4 - scroll). getBoundingClientRect() subtracts page_rect. */
  85. struct br_layout_box {
  86. int x, y;
  87. int w, h;
  88. unsigned char valid;
  89. };
  90. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  91. /* Images are loaded one per main-loop iteration so the parsed page stays
  92. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  93. static int preload_active;
  94. static int preload_max_jobs;
  95. static int preload_pending;
  96. static int preload_wait;
  97. static unsigned int preload_node;
  98. static int preload_loaded;
  99. static int preload_scroll;
  100. static char post_status_text[BR_STATUS_MAX];
  101. static int post_status_error;
  102. static unsigned int post_status_ttl;
  103. /* Content-relative position/height of each <img>, recorded by the measure
  104. * pass so image loading can be deferred until it is near the viewport. */
  105. static unsigned short img_top[BR_MAX_NODES];
  106. static unsigned short img_h[BR_MAX_NODES];
  107. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  108. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  109. * body. Decode arenas are allocated per image instead of living here. */
  110. static unsigned char *image_io_buf;
  111. static struct ufont_face *font_faces[BR_MAX_FACES];
  112. #define image_file_buf (image_io_buf)
  113. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  114. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  115. static struct inflate image_inflate_ws;
  116. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  117. #error "CSS scratch must fit in image_io_buf"
  118. #endif
  119. static char page_url[BR_URL_MAX];
  120. static char page_title[BR_TITLE_MAX];
  121. static char cwd[64];
  122. static int page_is_local;
  123. static int page_loading;
  124. static char status_text[BR_STATUS_MAX];
  125. static unsigned int status_until;
  126. static int status_error;
  127. static char history[BR_HISTORY][BR_URL_MAX];
  128. static int hist_len, hist_pos;
  129. static char click_url[BR_URL_MAX];
  130. static char pending_url[BR_URL_MAX];
  131. #define BR_POST_MAX 4096
  132. static char pending_post[BR_POST_MAX];
  133. static unsigned int pending_post_len;
  134. static unsigned int pending_action;
  135. static int cancel_fetch;
  136. static int quit;
  137. static struct ngui_rect page_rect;
  138. static unsigned short *page_backbuf;
  139. static int pagebuf_w, pagebuf_h;
  140. static int page_cache_valid;
  141. static int page_cache_scroll;
  142. static unsigned int page_cache_nnode;
  143. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  144. static int layout_valid, layout_left, layout_right;
  145. static unsigned int layout_nnode;
  146. static int layout_content_h;
  147. /* layout output */
  148. struct lay_run {
  149. unsigned short off, len;
  150. unsigned short gap;
  151. unsigned short color;
  152. unsigned short href;
  153. char lit[28];
  154. short img;
  155. signed short dy; /* inline image vertical offset */
  156. unsigned short iw, ih;
  157. unsigned short w;
  158. unsigned char font_px, bold, italic, mono, underline, strike;
  159. unsigned char overline, font_face;
  160. unsigned char transform_scale;
  161. unsigned char origin_x_kind, origin_y_kind;
  162. signed short scale_x, scale_y, rotate_x100;
  163. signed short origin_x, origin_y;
  164. unsigned char has_lit;
  165. unsigned int form; /* node + 1, 0 = not a control */
  166. unsigned char form_kind;
  167. unsigned char form_disabled;
  168. };
  169. struct lay {
  170. int draw;
  171. struct ngui *ui;
  172. int left, right;
  173. int y;
  174. int line_x, line_y, line_h;
  175. int line_left, line_right;
  176. int parent_top;
  177. int run_x;
  178. int align;
  179. int depth;
  180. int space_pending;
  181. unsigned char float_active;
  182. int float_left, float_right, float_bottom;
  183. struct lay_run runs[96];
  184. int nruns;
  185. };
  186. struct hit {
  187. int x, y, w, h;
  188. unsigned short node;
  189. };
  190. /* Live form state; the DOM attributes stay the initial/default value. */
  191. #define FORM_MAX 64
  192. #define FORM_VALUE_MAX 63
  193. enum {
  194. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  195. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  196. };
  197. struct form_state {
  198. unsigned int node;
  199. char value[FORM_VALUE_MAX + 1];
  200. unsigned char len, caret, checked, selected, used;
  201. };
  202. static struct form_state form_states[FORM_MAX];
  203. static unsigned int form_focus;
  204. static unsigned int form_dirty;
  205. static int form_descendant(unsigned int node, unsigned int form);
  206. static int form_submit_form(unsigned int node, int fire_event);
  207. static void form_reset_event(unsigned int form);
  208. static unsigned int s_len(const char *s);
  209. static int s_eq(const char *a, const char *b);
  210. static void form_key(int k);
  211. static void form_click(unsigned int node);
  212. static void style_for_node(unsigned int node, struct br_style *out);
  213. static int form_disabled(unsigned int node)
  214. {
  215. struct br_node *n = &doc.nodes[node];
  216. if (n->attr_flags & BR_ATTR_DISABLED)
  217. return 1;
  218. return br_find_attr(&doc, node, "disabled") != 0;
  219. }
  220. static int form_kind_of(unsigned int node)
  221. {
  222. const char *type = br_type(&doc, node);
  223. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  224. return FORM_TEXTAREA;
  225. if (doc.nodes[node].tag == BR_TAG_SELECT)
  226. return FORM_SELECT;
  227. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  228. if (s_eq(type, "reset"))
  229. return FORM_RESET;
  230. if (s_eq(type, "button"))
  231. return FORM_BUTTON;
  232. return FORM_SUBMIT;
  233. }
  234. if (s_eq(type, "password"))
  235. return FORM_PASSWORD;
  236. if (s_eq(type, "checkbox"))
  237. return FORM_CHECKBOX;
  238. if (s_eq(type, "radio"))
  239. return FORM_RADIO;
  240. if (s_eq(type, "submit"))
  241. return FORM_SUBMIT;
  242. if (s_eq(type, "reset"))
  243. return FORM_RESET;
  244. if (s_eq(type, "button"))
  245. return FORM_BUTTON;
  246. return FORM_TEXT;
  247. }
  248. static unsigned int form_option_count(unsigned int node)
  249. {
  250. unsigned int c, n = 0;
  251. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  252. if (doc.nodes[c].type == BR_NODE_ELEM &&
  253. doc.nodes[c].tag == BR_TAG_OPTION)
  254. n++;
  255. return n;
  256. }
  257. static unsigned int form_option_selected(unsigned int node)
  258. {
  259. unsigned int c, i = 0;
  260. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  261. if (doc.nodes[c].type != BR_NODE_ELEM ||
  262. doc.nodes[c].tag != BR_TAG_OPTION)
  263. continue;
  264. if (br_find_attr(&doc, c, "selected"))
  265. return i;
  266. i++;
  267. }
  268. return 0;
  269. }
  270. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  271. char *out, unsigned int cap)
  272. {
  273. unsigned int c, i = 0;
  274. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  275. if (doc.nodes[c].type != BR_NODE_ELEM ||
  276. doc.nodes[c].tag != BR_TAG_OPTION)
  277. continue;
  278. if (i == idx)
  279. return br_text_content(&doc, c, out, cap);
  280. i++;
  281. }
  282. return 0;
  283. }
  284. static struct form_state *form_get(unsigned int node, int create)
  285. {
  286. struct form_state *slot = 0;
  287. unsigned int i;
  288. for (i = 0; i < FORM_MAX; i++) {
  289. if (form_states[i].used) {
  290. if (form_states[i].node == node)
  291. return &form_states[i];
  292. } else if (!slot) {
  293. slot = &form_states[i];
  294. }
  295. }
  296. if (!create || !slot)
  297. return 0;
  298. slot->node = node;
  299. slot->len = 0;
  300. slot->caret = 0;
  301. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  302. slot->selected = form_option_selected(node);
  303. slot->used = 1;
  304. {
  305. unsigned int n = 0;
  306. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  307. n = br_text_content(&doc, node, slot->value,
  308. FORM_VALUE_MAX + 1);
  309. } else {
  310. const char *v = br_value(&doc, node);
  311. if (v) {
  312. n = s_len(v);
  313. if (n > FORM_VALUE_MAX)
  314. n = FORM_VALUE_MAX;
  315. for (unsigned int j = 0; j < n; j++)
  316. slot->value[j] = v[j];
  317. }
  318. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  319. n = br_text_content(&doc, node, slot->value,
  320. FORM_VALUE_MAX + 1);
  321. }
  322. if (n > FORM_VALUE_MAX)
  323. n = FORM_VALUE_MAX;
  324. slot->value[n] = '\0';
  325. slot->len = (unsigned char)n;
  326. slot->caret = (unsigned char)n;
  327. }
  328. return slot;
  329. }
  330. static void form_reset_state(void)
  331. {
  332. unsigned int i;
  333. for (i = 0; i < FORM_MAX; i++)
  334. form_states[i].used = 0;
  335. form_focus = 0;
  336. }
  337. static int form_is_control(unsigned int node)
  338. {
  339. unsigned int tag;
  340. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  341. return 0;
  342. tag = doc.nodes[node].tag;
  343. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  344. tag == BR_TAG_SELECT || tag == BR_TAG_BUTTON;
  345. }
  346. #define HIT_MAX 96
  347. static struct hit hits[HIT_MAX];
  348. static int nhits;
  349. static unsigned short block_h[BR_MAX_NODES];
  350. static char li_marker[BR_MAX_NODES][12];
  351. /* one connection object; the browser fetches one resource at a time */
  352. /* ---- tiny strings ---- */
  353. static unsigned int s_len(const char *s)
  354. {
  355. unsigned int n = 0;
  356. while (s && s[n])
  357. n++;
  358. return n;
  359. }
  360. static void s_copy(char *d, const char *s, unsigned int cap)
  361. {
  362. unsigned int i = 0;
  363. if (!cap)
  364. return;
  365. while (s && s[i] && i + 1 < cap) {
  366. d[i] = s[i];
  367. i++;
  368. }
  369. d[i] = '\0';
  370. }
  371. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  372. {
  373. while (s && *s && *n + 1 < cap)
  374. d[(*n)++] = *s++;
  375. d[*n] = '\0';
  376. }
  377. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  378. unsigned int cap)
  379. {
  380. char tmp[12];
  381. unsigned int i = 0, j;
  382. do {
  383. tmp[i++] = (char)('0' + v % 10);
  384. v /= 10;
  385. } while (v && i < sizeof(tmp));
  386. for (j = 0; j < i && *n + 1 < cap; j++)
  387. d[(*n)++] = tmp[i - 1 - j];
  388. d[*n] = '\0';
  389. }
  390. static int s_eq(const char *a, const char *b)
  391. {
  392. while (*a && *b) {
  393. if (*a != *b)
  394. return 0;
  395. a++;
  396. b++;
  397. }
  398. return *a == *b;
  399. }
  400. static int starts_with(const char *s, const char *p)
  401. {
  402. unsigned int i = 0;
  403. while (p[i]) {
  404. if (s[i] != p[i])
  405. return 0;
  406. i++;
  407. }
  408. return 1;
  409. }
  410. static int contains_ci(const char *s, const char *p)
  411. {
  412. unsigned int i, j;
  413. for (i = 0; s[i]; i++) {
  414. for (j = 0; p[j]; j++) {
  415. char a = s[i + j];
  416. if (a >= 'A' && a <= 'Z')
  417. a = (char)(a - 'A' + 'a');
  418. if (a != p[j])
  419. break;
  420. }
  421. if (!p[j])
  422. return 1;
  423. }
  424. return 0;
  425. }
  426. static char *trim(char *s)
  427. {
  428. unsigned int n;
  429. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  430. s++;
  431. n = s_len(s);
  432. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  433. s[n - 1] == '\r' || s[n - 1] == '\n'))
  434. s[--n] = '\0';
  435. return s;
  436. }
  437. /* ---- per-process heap ---- */
  438. static int heap_start(void)
  439. {
  440. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  441. if (!image_io_buf)
  442. return -1;
  443. page_backbuf = (unsigned short *)malloc(
  444. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  445. pagebuf_w = page_backbuf ? ui.w : 0;
  446. pagebuf_h = page_backbuf ? ui.h : 0;
  447. page_cache_valid = 0;
  448. return 0;
  449. }
  450. static void heap_clear(void)
  451. {
  452. memset(font_faces, 0, sizeof(font_faces));
  453. ngui_font_detach(&ui);
  454. heap_reset();
  455. /* The document arenas live in that heap; drop the stale pointers so
  456. * the next br_parse_plain() allocates fresh ones. */
  457. doc.nodes = 0;
  458. doc.text = 0;
  459. doc.attrs = 0;
  460. image_io_buf = 0;
  461. page_backbuf = 0;
  462. pagebuf_w = pagebuf_h = 0;
  463. page_cache_valid = 0;
  464. }
  465. static void browser_rules_alloc(void)
  466. {
  467. struct br_rule *rules;
  468. rules = (struct br_rule *)malloc(
  469. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  470. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  471. }
  472. /* ---- status ---- */
  473. static void set_status(const char *s, int err, unsigned int ttl_ms)
  474. {
  475. s_copy(status_text, s, sizeof(status_text));
  476. status_error = err;
  477. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  478. ngui_invalidate(&ui);
  479. }
  480. /* ---- JavaScript ---- */
  481. static int resolve_link(const char *base, const char *href, char *out,
  482. unsigned int cap);
  483. static char js_last_status[BR_STATUS_MAX];
  484. static int js_last_error;
  485. static void js_host_status(const char *msg, int error)
  486. {
  487. s_copy(js_last_status, msg, sizeof(js_last_status));
  488. js_last_error = error;
  489. set_status(msg, error, 6000);
  490. }
  491. static void js_host_report(const char *msg)
  492. {
  493. u_puts("[js] ");
  494. u_puts(msg);
  495. u_putc('\n');
  496. s_copy(js_last_status, msg, sizeof(js_last_status));
  497. js_last_error = 1;
  498. set_status(msg, 1, 8000);
  499. }
  500. static void js_host_navigate(const char *url)
  501. {
  502. char resolved[BR_URL_MAX];
  503. if (!url || !url[0])
  504. return;
  505. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  506. return;
  507. s_copy(pending_url, resolved, sizeof(pending_url));
  508. pending_action |= ACT_NAV;
  509. cancel_fetch = 1;
  510. }
  511. static void js_host_changed(void)
  512. {
  513. /* Class/style/attribute mutations change computed styles, not just the
  514. * text: drop the per-node style cache before the next layout. */
  515. br_reset_styles(&doc);
  516. layout_valid = 0;
  517. ngui_invalidate(&ui);
  518. }
  519. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  520. {
  521. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  522. return 0;
  523. *x = layout_boxes[node].x - page_rect.x;
  524. *y = layout_boxes[node].y - page_rect.y;
  525. *w = layout_boxes[node].w;
  526. *h = layout_boxes[node].h;
  527. return 1;
  528. }
  529. static void form_copy_out(const char *s, char *buf, int cap)
  530. {
  531. int i = 0;
  532. if (!buf || cap <= 0)
  533. return;
  534. while (s && s[i] && i + 1 < cap) {
  535. buf[i] = s[i];
  536. i++;
  537. }
  538. buf[i] = '\0';
  539. }
  540. static int js_host_form_value(unsigned int node, char *buf, int cap)
  541. {
  542. struct form_state *fs;
  543. int kind;
  544. if (!form_is_control(node))
  545. return 0;
  546. kind = form_kind_of(node);
  547. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  548. return 0;
  549. if (kind == FORM_SELECT) {
  550. char opt[64] = "";
  551. unsigned int c, i = 0;
  552. fs = form_get(node, 1);
  553. if (!fs)
  554. return 0;
  555. form_option_text(node, fs->selected, opt, sizeof(opt));
  556. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  557. if (doc.nodes[c].type != BR_NODE_ELEM ||
  558. doc.nodes[c].tag != BR_TAG_OPTION)
  559. continue;
  560. if (i == fs->selected) {
  561. const char *v = br_value(&doc, c);
  562. if (v && v[0])
  563. form_copy_out(v, buf, cap);
  564. else
  565. form_copy_out(opt, buf, cap);
  566. return 1;
  567. }
  568. i++;
  569. }
  570. form_copy_out(opt, buf, cap);
  571. return 1;
  572. }
  573. fs = form_get(node, 1);
  574. if (!fs)
  575. return 0;
  576. form_copy_out(fs->value, buf, cap);
  577. return 1;
  578. }
  579. static int js_host_form_checked(unsigned int node)
  580. {
  581. struct form_state *fs;
  582. int kind;
  583. if (!form_is_control(node))
  584. return -1;
  585. kind = form_kind_of(node);
  586. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  587. return -1;
  588. fs = form_get(node, 1);
  589. return fs ? fs->checked : 0;
  590. }
  591. static int js_host_form_selected(unsigned int node)
  592. {
  593. struct form_state *fs;
  594. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  595. return -1;
  596. fs = form_get(node, 1);
  597. return fs ? fs->selected : 0;
  598. }
  599. static int js_host_form_set_value(unsigned int node, const char *value)
  600. {
  601. struct form_state *fs;
  602. unsigned int n;
  603. if (!form_is_control(node))
  604. return 0;
  605. fs = form_get(node, 1);
  606. if (!fs)
  607. return 0;
  608. n = s_len(value ? value : "");
  609. if (n > FORM_VALUE_MAX)
  610. n = FORM_VALUE_MAX;
  611. for (unsigned int i = 0; i < n; i++)
  612. fs->value[i] = value[i];
  613. fs->value[n] = '\0';
  614. fs->len = (unsigned char)n;
  615. fs->caret = (unsigned char)n;
  616. layout_valid = 0;
  617. ngui_invalidate(&ui);
  618. return 1;
  619. }
  620. static int js_host_form_set_checked(unsigned int node, int checked)
  621. {
  622. struct form_state *fs;
  623. int kind;
  624. if (!form_is_control(node))
  625. return 0;
  626. kind = form_kind_of(node);
  627. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  628. return 0;
  629. fs = form_get(node, 1);
  630. if (!fs)
  631. return 0;
  632. fs->checked = (unsigned char)(checked != 0);
  633. layout_valid = 0;
  634. ngui_invalidate(&ui);
  635. return 1;
  636. }
  637. static int js_host_form_set_selected(unsigned int node, int index)
  638. {
  639. struct form_state *fs;
  640. unsigned int n;
  641. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  642. return 0;
  643. fs = form_get(node, 1);
  644. if (!fs)
  645. return 0;
  646. n = form_option_count(node);
  647. if (index < 0)
  648. index = 0;
  649. if (n && (unsigned int)index >= n)
  650. index = (int)n - 1;
  651. fs->selected = (unsigned char)index;
  652. layout_valid = 0;
  653. ngui_invalidate(&ui);
  654. return 1;
  655. }
  656. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  657. {
  658. unsigned int i;
  659. int n = 0;
  660. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  661. doc.nodes[form].tag != BR_TAG_FORM)
  662. return 0;
  663. for (i = 0; i < doc.nnode && n < cap; i++) {
  664. struct br_node *nd = &doc.nodes[i];
  665. if (i == form || nd->type != BR_NODE_ELEM)
  666. continue;
  667. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  668. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  669. continue;
  670. if (!form_descendant(i, form))
  671. continue;
  672. out[n++] = i;
  673. }
  674. return n;
  675. }
  676. static int js_host_form_submit(unsigned int form)
  677. {
  678. form_submit_form(form, 0);
  679. return 1;
  680. }
  681. static int js_host_form_reset(unsigned int form)
  682. {
  683. form_reset_event(form);
  684. return 1;
  685. }
  686. static void css_computed_name(const char *p, char *out, int cap)
  687. {
  688. int n = 0;
  689. for (; p && *p && n + 2 < cap; p++) {
  690. char c = *p;
  691. if (c >= 'A' && c <= 'Z') {
  692. out[n++] = '-';
  693. c = (char)(c - 'A' + 'a');
  694. } else if (c == '_') {
  695. c = '-';
  696. } else if (c >= 'a' && c <= 'z') {
  697. /* keep */
  698. }
  699. out[n++] = c;
  700. }
  701. out[n] = '\0';
  702. if (!strcmp(out, "css-float"))
  703. strcpy(out, "float");
  704. }
  705. static void css_rgb(unsigned short c, char *buf, int cap)
  706. {
  707. int r = ((c >> 11) & 31) * 255 / 31;
  708. int g = ((c >> 5) & 63) * 255 / 63;
  709. int b = (c & 31) * 255 / 31;
  710. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  711. }
  712. static void css_mp_value(char *buf, int cap, int raw, int unit, int px)
  713. {
  714. if (unit == 4) {
  715. snprintf(buf, cap, "auto");
  716. } else if (unit == 0) {
  717. snprintf(buf, cap, "%dpx", raw);
  718. } else if (unit == 1) {
  719. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  720. } else if (unit == 2) {
  721. snprintf(buf, cap, "%d.%02dem", raw / 100, raw % 100);
  722. } else if (unit == 3) {
  723. snprintf(buf, cap, "%d.%02drem", raw / 100, raw % 100);
  724. } else {
  725. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  726. raw / 100, raw % 100, px);
  727. }
  728. }
  729. static int js_host_computed(unsigned int node, const char *property,
  730. char *buf, int cap)
  731. {
  732. struct br_style st;
  733. char name[40];
  734. if (!buf || cap <= 0 || node >= doc.nnode || node == 0)
  735. return 0;
  736. buf[0] = '\0';
  737. css_computed_name(property, name, sizeof(name));
  738. style_for_node(node, &st);
  739. if (!strcmp(name, "display")) {
  740. const char *v = "inline";
  741. if (st.display == BR_DISPLAY_BLOCK)
  742. v = "block";
  743. else if (st.display == BR_DISPLAY_NONE)
  744. v = "none";
  745. else if (st.display == BR_DISPLAY_FLEX)
  746. v = "flex";
  747. else if (st.display == BR_DISPLAY_GRID)
  748. v = "grid";
  749. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  750. v = "inline-block";
  751. snprintf(buf, cap, "%s", v);
  752. } else if (!strcmp(name, "position")) {
  753. static const char *pos[] = {
  754. "static", "absolute", "fixed", "relative", "sticky"
  755. };
  756. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  757. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  758. int is_w = name[0] == 'w';
  759. int kind = is_w ? st.width_kind : st.height_kind;
  760. int val = is_w ? st.width : st.height;
  761. if (kind == 3) {
  762. if (is_w)
  763. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  764. st.width_calc_pct / 100,
  765. st.width_calc_pct % 100,
  766. st.width_calc_px);
  767. else
  768. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  769. st.height_calc_pct / 100,
  770. st.height_calc_pct % 100,
  771. st.height_calc_px);
  772. } else if (kind == 1) {
  773. snprintf(buf, cap, "%dpx", val);
  774. } else if (kind == 2) {
  775. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  776. } else {
  777. snprintf(buf, cap, "auto");
  778. }
  779. } else if (!strcmp(name, "color") ||
  780. !strcmp(name, "background-color")) {
  781. if (!strcmp(name, "background-color") && !st.has_bg)
  782. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  783. else
  784. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  785. } else if (!strcmp(name, "font-size")) {
  786. snprintf(buf, cap, "%dpx", st.font_px);
  787. } else if (!strcmp(name, "font-weight")) {
  788. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  789. } else if (!strcmp(name, "font-style")) {
  790. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  791. } else if (!strcmp(name, "font-family")) {
  792. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  793. br_font_face_family(st.font_face)[0])
  794. snprintf(buf, cap, "%s",
  795. br_font_face_family(st.font_face));
  796. else
  797. snprintf(buf, cap, "%s",
  798. st.mono ? "monospace" : "sans-serif");
  799. } else if (!strcmp(name, "text-align")) {
  800. static const char *al[] = { "left", "center", "right", "justify" };
  801. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  802. } else if (!strcmp(name, "float")) {
  803. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  804. st.float_left == 2 ? "right" : "none");
  805. } else if (!strcmp(name, "clear")) {
  806. static const char *cl[] = { "none", "left", "right", "both" };
  807. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  808. } else if (!strcmp(name, "opacity")) {
  809. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  810. } else if (!strcmp(name, "visibility")) {
  811. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  812. } else if (!strcmp(name, "overflow")) {
  813. snprintf(buf, cap, "%s",
  814. st.overflow_hidden ? "hidden" : "visible");
  815. } else if (!strcmp(name, "white-space")) {
  816. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  817. } else if (!strcmp(name, "text-transform")) {
  818. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  819. } else if (!strcmp(name, "box-sizing")) {
  820. snprintf(buf, cap, "%s",
  821. st.box_sizing ? "border-box" : "content-box");
  822. } else if (!strcmp(name, "line-height")) {
  823. if (st.line_h_px)
  824. snprintf(buf, cap, "%dpx", st.line_h_px);
  825. else if (st.line_h_pct)
  826. snprintf(buf, cap, "%d%%", st.line_h_pct);
  827. else
  828. snprintf(buf, cap, "normal");
  829. } else if (!strcmp(name, "z-index")) {
  830. if (st.z_set)
  831. snprintf(buf, cap, "%d", st.z_index);
  832. else
  833. snprintf(buf, cap, "auto");
  834. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  835. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  836. int set = name[0] == 't' ? st.top_set :
  837. name[0] == 'l' ? st.left_set :
  838. name[0] == 'r' ? st.right_set : st.bottom_set;
  839. int v = name[0] == 't' ? st.top :
  840. name[0] == 'l' ? st.left :
  841. name[0] == 'r' ? st.right : st.bottom;
  842. if (set)
  843. snprintf(buf, cap, "%dpx", v);
  844. else
  845. snprintf(buf, cap, "auto");
  846. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  847. !strcmp(name, "margin-bottom") ||
  848. !strcmp(name, "margin-left") ||
  849. !strcmp(name, "padding-top") ||
  850. !strcmp(name, "padding-right") ||
  851. !strcmp(name, "padding-bottom") ||
  852. !strcmp(name, "padding-left")) {
  853. int is_pad = name[0] == 'p';
  854. int side = name[strlen(name) - 1] == 'p' ? 0 :
  855. name[strlen(name) - 1] == 't' ? 1 :
  856. name[strlen(name) - 1] == 'm' ? 2 : 3;
  857. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  858. if (!strcmp(name, "margin-right") ||
  859. !strcmp(name, "padding-right"))
  860. side = 1;
  861. else if (!strcmp(name, "margin-bottom") ||
  862. !strcmp(name, "padding-bottom"))
  863. side = 2;
  864. else if (!strcmp(name, "margin-left") ||
  865. !strcmp(name, "padding-left"))
  866. side = 3;
  867. else
  868. side = 0;
  869. side += is_pad ? 4 : 0;
  870. css_mp_value(buf, cap,
  871. side == 0 ? st.mt : side == 1 ? st.mr :
  872. side == 2 ? st.mb : side == 3 ? st.ml :
  873. side == 4 ? st.pt : side == 5 ? st.pr :
  874. side == 6 ? st.pb : st.pl,
  875. st.mp_unit[side], st.mp_calc_px[side]);
  876. } else if (!strcmp(name, "border-top-width") ||
  877. !strcmp(name, "border-right-width") ||
  878. !strcmp(name, "border-bottom-width") ||
  879. !strcmp(name, "border-left-width")) {
  880. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  881. name[7] == 'b' ? 2 : 3;
  882. snprintf(buf, cap, "%dpx", st.border_w[side]);
  883. } else if (!strcmp(name, "border-top-color") ||
  884. !strcmp(name, "border-right-color") ||
  885. !strcmp(name, "border-bottom-color") ||
  886. !strcmp(name, "border-left-color")) {
  887. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  888. name[7] == 'b' ? 2 : 3;
  889. if (st.border_w[side])
  890. css_rgb(st.border_c[side], buf, cap);
  891. else
  892. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  893. } else if (!strcmp(name, "background-image")) {
  894. if (st.bg_image)
  895. snprintf(buf, cap, "url(\"%s\")",
  896. br_bg_image_url(st.bg_image - 1));
  897. else
  898. snprintf(buf, cap, "none");
  899. } else if (!strcmp(name, "background-repeat")) {
  900. static const char *rp[] = {
  901. "repeat", "no-repeat", "repeat-x", "repeat-y"
  902. };
  903. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  904. st.bg_repeat : 0]);
  905. } else if (!strcmp(name, "background-position")) {
  906. if (st.bg_pos_x_kind == 1)
  907. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  908. st.bg_pos_y);
  909. else
  910. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  911. st.bg_pos_y);
  912. } else if (!strcmp(name, "background-size")) {
  913. if (st.bg_size_kind == 3)
  914. snprintf(buf, cap, "cover");
  915. else if (st.bg_size_kind == 4)
  916. snprintf(buf, cap, "contain");
  917. else if (st.bg_size_kind == 1)
  918. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  919. st.bg_size_h);
  920. else if (st.bg_size_kind == 2)
  921. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  922. st.bg_size_h);
  923. else
  924. snprintf(buf, cap, "auto");
  925. } else if (!strcmp(name, "transform")) {
  926. char tmp[128];
  927. unsigned int n = 0;
  928. if (!st.transform_set) {
  929. snprintf(buf, cap, "none");
  930. } else {
  931. tmp[0] = '\0';
  932. if (st.tx || st.ty) {
  933. snprintf(tmp + n, sizeof(tmp) - n,
  934. "translate(%dpx, %dpx)", st.tx, st.ty);
  935. n = (unsigned int)strlen(tmp);
  936. }
  937. if (st.transform_scale) {
  938. snprintf(tmp + n, sizeof(tmp) - n,
  939. "%sscale(%d.%02d, %d.%02d)",
  940. n ? " " : "", st.scale_x / 100,
  941. st.scale_x % 100, st.scale_y / 100,
  942. st.scale_y % 100);
  943. n = (unsigned int)strlen(tmp);
  944. if (st.rotate_x100) {
  945. snprintf(tmp + n, sizeof(tmp) - n,
  946. " rotate(%d.%02ddeg)",
  947. st.rotate_x100 / 100,
  948. st.rotate_x100 % 100);
  949. }
  950. } else if (st.rotate_x100) {
  951. snprintf(tmp + n, sizeof(tmp) - n,
  952. "%srotate(%d.%02ddeg)",
  953. n ? " " : "", st.rotate_x100 / 100,
  954. st.rotate_x100 % 100);
  955. }
  956. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  957. }
  958. } else {
  959. return 0;
  960. }
  961. return buf[0] != '\0';
  962. }
  963. static int js_host_click(unsigned int node)
  964. {
  965. char url[BR_URL_MAX];
  966. const char *href;
  967. if (node >= doc.nnode)
  968. return 0;
  969. if (form_is_control(node)) {
  970. form_click(node);
  971. return 1;
  972. }
  973. href = br_href(&doc, node);
  974. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  975. return 0;
  976. s_copy(pending_url, url, sizeof(pending_url));
  977. pending_action |= ACT_NAV;
  978. cancel_fetch = 1;
  979. ngui_invalidate(&ui);
  980. return 1;
  981. }
  982. static int fetch_script_text(const char *url, unsigned char **out,
  983. unsigned int *outlen, char *err,
  984. unsigned int errcap);
  985. struct fetch_worker;
  986. static struct fetch_worker *fetch_worker_alloc(void);
  987. static void fetch_worker_release(struct fetch_worker *w);
  988. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  989. unsigned int cap, const char *post,
  990. unsigned int post_len, unsigned int node,
  991. int bg, char *err, unsigned int errcap);
  992. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  993. unsigned int errcap);
  994. static int fetch_worker_read_body(struct fetch_worker *w,
  995. unsigned char *plain,
  996. unsigned int plaincap,
  997. unsigned char *comp,
  998. unsigned int compcap,
  999. int *truncated, char *err,
  1000. unsigned int errcap);
  1001. static void fetch_workers_stop_all(void);
  1002. static int script_cache_has(const char *url);
  1003. static void script_cache_put(const char *url, const unsigned char *data,
  1004. unsigned int len);
  1005. static void script_error(const char *what, const char *url, const char *why)
  1006. {
  1007. char msg[192];
  1008. unsigned int n = 0;
  1009. s_append(msg, &n, what, sizeof(msg));
  1010. if (url && url[0]) {
  1011. s_append(msg, &n, " ", sizeof(msg));
  1012. s_append(msg, &n, url, sizeof(msg));
  1013. }
  1014. if (why && why[0]) {
  1015. s_append(msg, &n, ": ", sizeof(msg));
  1016. s_append(msg, &n, why, sizeof(msg));
  1017. }
  1018. js_host_report(msg);
  1019. }
  1020. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1021. * submitted to helper workers ahead of time, but scripts still execute in
  1022. * document order. */
  1023. #define SCRIPT_INLINE 0
  1024. #define SCRIPT_LOCAL 1
  1025. #define SCRIPT_REMOTE 2
  1026. #define SCRIPT_ERROR 3
  1027. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1028. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1029. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1030. static void script_submit_window(unsigned int *next, char *err,
  1031. unsigned int errcap)
  1032. {
  1033. while (*next < doc.nscripts) {
  1034. struct fetch_worker *w;
  1035. if (script_kind[*next] != SCRIPT_REMOTE) {
  1036. (*next)++;
  1037. continue;
  1038. }
  1039. w = fetch_worker_alloc();
  1040. if (!w)
  1041. return;
  1042. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1043. 0, 0, 0, 0, err, errcap) != 0) {
  1044. fetch_worker_release(w);
  1045. script_kind[*next] = SCRIPT_ERROR;
  1046. (*next)++;
  1047. continue;
  1048. }
  1049. script_slot[*next] = w;
  1050. (*next)++;
  1051. }
  1052. }
  1053. /* Run the page's scripts in document order. External bodies are prefetched
  1054. * in parallel so downloading script N+1 overlaps executing script N; inline
  1055. * bodies are copied because MuJS needs NUL-terminated text. */
  1056. static void run_page_scripts(void)
  1057. {
  1058. struct js_browser_host host;
  1059. unsigned int i, next = 0;
  1060. char err[64], ferr[64];
  1061. if (!doc.nscripts)
  1062. return;
  1063. host.status = js_host_status;
  1064. host.report = js_host_report;
  1065. host.navigate = js_host_navigate;
  1066. host.changed = js_host_changed;
  1067. host.rect = js_host_rect;
  1068. host.form_value = js_host_form_value;
  1069. host.form_checked = js_host_form_checked;
  1070. host.form_selected = js_host_form_selected;
  1071. host.form_set_value = js_host_form_set_value;
  1072. host.form_set_checked = js_host_form_set_checked;
  1073. host.form_set_selected = js_host_form_set_selected;
  1074. host.form_elements = js_host_form_elements;
  1075. host.form_submit = js_host_form_submit;
  1076. host.form_reset = js_host_form_reset;
  1077. host.click = js_host_click;
  1078. host.computed = js_host_computed;
  1079. host.page_url = page_url;
  1080. host.width = ui.w;
  1081. host.height = ui.h;
  1082. if (js_browser_start(&doc, &host) != 0) {
  1083. js_host_status("JavaScript: out of memory", 1);
  1084. return;
  1085. }
  1086. for (i = 0; i < doc.nscripts; i++) {
  1087. struct br_script *script = &doc.scripts[i];
  1088. const char *src_attr = script->src_off ?
  1089. doc.attrs + script->src_off : "";
  1090. script_slot[i] = 0;
  1091. if (!script->src_off) {
  1092. script_kind[i] = SCRIPT_INLINE;
  1093. continue;
  1094. }
  1095. if (!src_attr[0] ||
  1096. resolve_link(page_url, src_attr, script_urls[i],
  1097. sizeof(script_urls[i])) != 0) {
  1098. script_urls[i][0] = '\0';
  1099. script_kind[i] = SCRIPT_ERROR;
  1100. continue;
  1101. }
  1102. if (script_urls[i][0] == '/' ||
  1103. script_cache_has(script_urls[i]))
  1104. script_kind[i] = SCRIPT_LOCAL;
  1105. else
  1106. script_kind[i] = SCRIPT_REMOTE;
  1107. }
  1108. script_submit_window(&next, ferr, sizeof(ferr));
  1109. for (i = 0; i < doc.nscripts; i++) {
  1110. struct br_script *script = &doc.scripts[i];
  1111. if (script_kind[i] == SCRIPT_INLINE) {
  1112. unsigned int off = script->off;
  1113. unsigned int len = script->len;
  1114. unsigned int k;
  1115. char *src = (char *)malloc(len + 1);
  1116. if (!src) {
  1117. js_host_status("JavaScript: out of memory", 1);
  1118. break;
  1119. }
  1120. for (k = 0; k < len; k++)
  1121. src[k] = doc.script_src[off + k];
  1122. src[len] = '\0';
  1123. js_browser_run(src, page_url);
  1124. free(src);
  1125. } else if (script->src_off) {
  1126. const char *src_attr = doc.attrs + script->src_off;
  1127. if (script_kind[i] == SCRIPT_ERROR) {
  1128. script_error("Cannot load script", src_attr,
  1129. script_urls[i][0] ?
  1130. "network busy" :
  1131. "unsupported URL");
  1132. continue;
  1133. }
  1134. if (script_kind[i] == SCRIPT_LOCAL) {
  1135. unsigned char *data = 0;
  1136. unsigned int len = 0;
  1137. int rv;
  1138. set_status("Loading script...", 0, 0);
  1139. rv = fetch_script_text(script_urls[i], &data,
  1140. &len, err, sizeof(err));
  1141. if (rv == FETCH_ABORT)
  1142. break;
  1143. if (rv != 0) {
  1144. script_error("Cannot load script",
  1145. script_urls[i], err);
  1146. continue;
  1147. }
  1148. js_browser_run((const char *)data,
  1149. script_urls[i]);
  1150. free(data);
  1151. } else {
  1152. struct fetch_worker *w = script_slot[i];
  1153. int tr = 0, rv;
  1154. if (!w) {
  1155. w = fetch_worker_alloc();
  1156. if (!w)
  1157. continue;
  1158. if (fetch_worker_submit(w,
  1159. script_urls[i],
  1160. BR_SCRIPT_MAX,
  1161. 0, 0, 0, 0, err,
  1162. sizeof(err)) != 0) {
  1163. fetch_worker_release(w);
  1164. script_kind[i] = SCRIPT_ERROR;
  1165. if (i == next)
  1166. next++;
  1167. continue;
  1168. }
  1169. script_slot[i] = w;
  1170. if (i == next)
  1171. next++;
  1172. }
  1173. set_status("Loading script...", 0, 0);
  1174. rv = fetch_worker_wait(w, err, sizeof(err));
  1175. if (rv == FETCH_ABORT) {
  1176. fetch_workers_stop_all();
  1177. break;
  1178. }
  1179. if (rv == 0)
  1180. rv = fetch_worker_read_body(w,
  1181. image_io_buf, BR_SCRIPT_MAX,
  1182. image_io_buf + BR_SCRIPT_MAX,
  1183. BR_IMG_FILE_MAX, &tr, err,
  1184. sizeof(err));
  1185. else
  1186. rv = -1;
  1187. fetch_worker_release(w);
  1188. script_slot[i] = 0;
  1189. script_submit_window(&next, ferr, sizeof(ferr));
  1190. if (rv <= 0)
  1191. script_error("Cannot load script",
  1192. script_urls[i], err);
  1193. else if (tr || (unsigned int)rv >=
  1194. BR_SCRIPT_MAX)
  1195. script_error("Cannot load script",
  1196. script_urls[i],
  1197. "script is too large");
  1198. else {
  1199. image_io_buf[rv] = '\0';
  1200. script_cache_put(script_urls[i],
  1201. image_io_buf,
  1202. (unsigned int)rv);
  1203. js_browser_run(
  1204. (const char *)image_io_buf,
  1205. script_urls[i]);
  1206. }
  1207. }
  1208. }
  1209. if (pending_action)
  1210. break;
  1211. }
  1212. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  1213. * load_home() stop it before the next navigation. */
  1214. if (doc.scripts_truncated && !js_last_error)
  1215. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  1216. 1);
  1217. }
  1218. /* ---- images ---- */
  1219. static void image_reset(void)
  1220. {
  1221. int i;
  1222. for (i = 0; i < BR_MAX_IMAGES; i++) {
  1223. images[i].state = 0;
  1224. images[i].native_w = images[i].native_h = 0;
  1225. images[i].err[0] = '\0';
  1226. }
  1227. image_count = 0;
  1228. preload_active = 0;
  1229. preload_pending = 0;
  1230. preload_wait = 0;
  1231. preload_node = 0;
  1232. preload_loaded = 0;
  1233. }
  1234. /* Decode into the shared arena, then copy/scale the result into a display
  1235. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  1236. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  1237. * pixels. Transparent edges are composited over white. */
  1238. static int decode_image_data(const unsigned char *data, unsigned int len,
  1239. struct br_image *bi)
  1240. {
  1241. struct img_info info;
  1242. struct img_options opt;
  1243. struct img_mem mem;
  1244. struct img_image decoded;
  1245. unsigned char *arena;
  1246. unsigned int est, bytes, i;
  1247. unsigned short *px;
  1248. unsigned char *alpha = 0;
  1249. int dw, dh, r;
  1250. if (img_sniff(data, len, &info) != 0) {
  1251. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  1252. return -1;
  1253. }
  1254. est = img_estimate(&info);
  1255. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  1256. s_copy(bi->err, "image too large", sizeof(bi->err));
  1257. return -1;
  1258. }
  1259. arena = (unsigned char *)malloc(est);
  1260. if (!arena) {
  1261. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1262. return -1;
  1263. }
  1264. img_mem_init(&mem, arena, est);
  1265. opt.max_pixels = BR_IMG_PIX_MAX;
  1266. r = img_decode(data, len, &opt, &mem, &decoded);
  1267. if (r != 0) {
  1268. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  1269. goto fail;
  1270. }
  1271. if (decoded.w == 0 || decoded.h == 0) {
  1272. s_copy(bi->err, "empty image", sizeof(bi->err));
  1273. goto fail;
  1274. }
  1275. bi->native_w = (int)decoded.w;
  1276. bi->native_h = (int)decoded.h;
  1277. dw = (int)decoded.w;
  1278. dh = (int)decoded.h;
  1279. if (dw > BR_IMG_LAYOUT_W) {
  1280. dh = (int)((unsigned int)decoded.h * BR_IMG_LAYOUT_W /
  1281. decoded.w);
  1282. dw = BR_IMG_LAYOUT_W;
  1283. }
  1284. if (dh < 1)
  1285. dh = 1;
  1286. if (dw < 1)
  1287. dw = 1;
  1288. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  1289. px = (unsigned short *)malloc(bytes);
  1290. if (!px) {
  1291. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1292. goto fail;
  1293. }
  1294. /* Keep the alpha plane for the scaled image so transparent logos and
  1295. * icons composite over the page instead of the browser's dark theme
  1296. * background. Very large alpha images stay flattened to bound the
  1297. * heap use. */
  1298. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  1299. alpha = (unsigned char *)malloc((unsigned int)dw *
  1300. (unsigned int)dh);
  1301. if (alpha) {
  1302. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1303. alpha[i] = 255;
  1304. }
  1305. }
  1306. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1307. px[i] = ui.theme.bg;
  1308. {
  1309. struct img_blit b;
  1310. b.dst = px;
  1311. b.dst_w = dw;
  1312. b.dst_h = dh;
  1313. b.clip_x = 0;
  1314. b.clip_y = 0;
  1315. b.clip_w = dw;
  1316. b.clip_h = dh;
  1317. b.x = 0;
  1318. b.y = 0;
  1319. b.scale = ((unsigned int)dw << 16) / decoded.w;
  1320. b.bg = ui.theme.bg;
  1321. b.bg2 = ui.theme.bg;
  1322. b.dst_a = alpha;
  1323. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  1324. img_draw(&decoded, &b);
  1325. }
  1326. bi->img.format = decoded.format;
  1327. bi->img.w = (unsigned int)dw;
  1328. bi->img.h = (unsigned int)dh;
  1329. bi->img.px = px;
  1330. bi->img.alpha = alpha;
  1331. bi->img.flags = 0;
  1332. bi->state = 1;
  1333. free(arena);
  1334. return 0;
  1335. fail:
  1336. free(arena);
  1337. return -1;
  1338. }
  1339. /* ---- URL / local path handling ---- */
  1340. static int is_http(const char *s)
  1341. {
  1342. return starts_with(s, "http://") || starts_with(s, "https://");
  1343. }
  1344. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  1345. static int normalize_abs(const char *in, char *out, unsigned int cap)
  1346. {
  1347. char seg[64];
  1348. unsigned int i = 0, o = 1;
  1349. int depth = 0;
  1350. int trailing;
  1351. if (!in || in[0] != '/' || cap < 2)
  1352. return -1;
  1353. trailing = 0;
  1354. {
  1355. unsigned int n = s_len(in);
  1356. if (n > 1 && in[n - 1] == '/')
  1357. trailing = 1;
  1358. }
  1359. out[0] = '/';
  1360. while (in[i]) {
  1361. unsigned int n = 0;
  1362. while (in[i] == '/')
  1363. i++;
  1364. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  1365. if (n + 1 < sizeof(seg))
  1366. seg[n++] = in[i];
  1367. i++;
  1368. }
  1369. seg[n] = '\0';
  1370. if (n == 0)
  1371. break;
  1372. if (s_eq(seg, "."))
  1373. continue;
  1374. if (s_eq(seg, "..")) {
  1375. if (depth > 0) {
  1376. while (o > 1 && out[o - 1] != '/')
  1377. o--;
  1378. if (o > 1)
  1379. o--;
  1380. depth--;
  1381. }
  1382. continue;
  1383. }
  1384. if (o > 1) {
  1385. if (o + 1 >= cap)
  1386. return -1;
  1387. out[o++] = '/';
  1388. }
  1389. if (o + n + 1 >= cap)
  1390. return -1;
  1391. {
  1392. unsigned int j;
  1393. for (j = 0; j < n; j++)
  1394. out[o++] = seg[j];
  1395. }
  1396. depth++;
  1397. }
  1398. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  1399. if (o + 1 >= cap)
  1400. return -1;
  1401. out[o++] = '/';
  1402. }
  1403. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  1404. if (in[i] == '?' || in[i] == '#') {
  1405. while (in[i]) {
  1406. if (o + 1 >= cap)
  1407. return -1;
  1408. out[o++] = in[i++];
  1409. }
  1410. }
  1411. out[o] = '\0';
  1412. return 0;
  1413. }
  1414. static void make_abs_local(const char *in, char *out, unsigned int cap)
  1415. {
  1416. char joined[BR_URL_MAX];
  1417. if (!in || !in[0]) {
  1418. s_copy(out, cwd[0] ? cwd : "/", cap);
  1419. return;
  1420. }
  1421. if (in[0] == '/') {
  1422. if (normalize_abs(in, out, cap) != 0)
  1423. s_copy(out, in, cap);
  1424. return;
  1425. }
  1426. {
  1427. unsigned int n = 0;
  1428. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  1429. s_append(joined, &n, "/", sizeof(joined));
  1430. s_append(joined, &n, in, sizeof(joined));
  1431. }
  1432. if (normalize_abs(joined, out, cap) != 0)
  1433. s_copy(out, joined, cap);
  1434. }
  1435. /* ---- canonical origin cache ---- *
  1436. *
  1437. * Sites commonly redirect http://host to https://host and then to
  1438. * https://www.host. Remember the final scheme/host of the last navigation so
  1439. * a bare domain typed again goes straight there instead of paying for two
  1440. * more connections and TLS handshakes. Only default-port requests are
  1441. * rewritten; explicit ports are left alone. */
  1442. #define ORIGIN_CACHE_MAX 8
  1443. #define ORIGIN_FILE "/share/borigins"
  1444. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  1445. UHTTP_HOST_MAX + 2))
  1446. struct origin_cache_entry {
  1447. char host[UHTTP_HOST_MAX];
  1448. char origin[UHTTP_HOST_MAX + 16];
  1449. };
  1450. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  1451. static int origin_count;
  1452. static char origin_buf[ORIGIN_BUF_SIZE];
  1453. static int default_port(const struct uhttp_url *u)
  1454. {
  1455. return u->secure ? u->port == 443 : u->port == 80;
  1456. }
  1457. static void url_origin(const struct uhttp_url *u, char *out,
  1458. unsigned int cap)
  1459. {
  1460. unsigned int n = 0;
  1461. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  1462. s_append(out, &n, u->host, cap);
  1463. if (!default_port(u)) {
  1464. s_append(out, &n, ":", cap);
  1465. s_append_dec(out, &n, u->port, cap);
  1466. }
  1467. }
  1468. static void origin_cache_apply(char *url, unsigned int cap)
  1469. {
  1470. struct uhttp_url u;
  1471. char out[BR_URL_MAX];
  1472. unsigned int n = 0;
  1473. int i;
  1474. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  1475. return;
  1476. for (i = 0; i < origin_count; i++) {
  1477. if (!s_eq(u.host, origins[i].host))
  1478. continue;
  1479. s_append(out, &n, origins[i].origin, sizeof(out));
  1480. s_append(out, &n, u.path, sizeof(out));
  1481. s_copy(url, out, cap);
  1482. return;
  1483. }
  1484. }
  1485. static void origin_cache_save(void)
  1486. {
  1487. unsigned int n = 0;
  1488. int i;
  1489. for (i = 0; i < origin_count; i++) {
  1490. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  1491. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  1492. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  1493. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  1494. }
  1495. if (n)
  1496. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  1497. (int)origin_buf, (int)n);
  1498. }
  1499. static void origin_cache_load(void)
  1500. {
  1501. char *p;
  1502. int rn;
  1503. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  1504. (int)(sizeof(origin_buf) - 1));
  1505. if (rn <= 0)
  1506. return;
  1507. origin_buf[rn] = '\0';
  1508. p = origin_buf;
  1509. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  1510. char *line = p, *origin;
  1511. while (*p && *p != '\n')
  1512. p++;
  1513. if (*p)
  1514. *p++ = '\0';
  1515. if (!line[0])
  1516. continue;
  1517. origin = line;
  1518. while (*origin && *origin != ' ')
  1519. origin++;
  1520. if (!*origin)
  1521. continue;
  1522. *origin++ = '\0';
  1523. if (!line[0] || !is_http(origin))
  1524. continue;
  1525. {
  1526. struct uhttp_url uo;
  1527. if (uhttp_parse_url(origin, &uo) != 0 ||
  1528. !s_eq(uo.path, "/"))
  1529. continue;
  1530. }
  1531. s_copy(origins[origin_count].host, line,
  1532. sizeof(origins[origin_count].host));
  1533. s_copy(origins[origin_count].origin, origin,
  1534. sizeof(origins[origin_count].origin));
  1535. origin_count++;
  1536. }
  1537. }
  1538. static int host_is_www_of(const char *host, const char *base)
  1539. {
  1540. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  1541. host[3] == '.' && s_eq(host + 4, base);
  1542. }
  1543. static void origin_cache_learn(const char *requested, const char *final)
  1544. {
  1545. struct uhttp_url from, to;
  1546. char origin[UHTTP_HOST_MAX + 16];
  1547. int i;
  1548. if (!is_http(requested) || !is_http(final))
  1549. return;
  1550. if (uhttp_parse_url(requested, &from) != 0 ||
  1551. uhttp_parse_url(final, &to) != 0)
  1552. return;
  1553. if (!default_port(&from))
  1554. return;
  1555. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  1556. from.port == to.port)
  1557. return;
  1558. /* Only remember origin-level canonicalisation: the same path, and
  1559. * either the same host or its www./apex sibling. A path- or
  1560. * host-specific redirect (a shortener, a login page) must not poison
  1561. * every request to the typed host. */
  1562. if (!s_eq(from.path, to.path))
  1563. return;
  1564. if (!s_eq(from.host, to.host) &&
  1565. !host_is_www_of(to.host, from.host) &&
  1566. !host_is_www_of(from.host, to.host))
  1567. return;
  1568. url_origin(&to, origin, sizeof(origin));
  1569. for (i = 0; i < origin_count; i++) {
  1570. if (s_eq(origins[i].host, from.host)) {
  1571. if (!s_eq(origins[i].origin, origin)) {
  1572. s_copy(origins[i].origin, origin,
  1573. sizeof(origins[i].origin));
  1574. origin_cache_save();
  1575. }
  1576. return;
  1577. }
  1578. }
  1579. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  1580. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  1581. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  1582. origin_cache_save();
  1583. }
  1584. static int path_dir(const char *path, char *out, unsigned int cap)
  1585. {
  1586. unsigned int i, last = 0;
  1587. for (i = 0; path[i]; i++)
  1588. if (path[i] == '/')
  1589. last = i;
  1590. if (last == 0) {
  1591. if (cap < 2)
  1592. return -1;
  1593. out[0] = '/';
  1594. out[1] = '\0';
  1595. return 0;
  1596. }
  1597. if (last + 1 >= cap)
  1598. return -1;
  1599. {
  1600. unsigned int j;
  1601. for (j = 0; j < last; j++)
  1602. out[j] = path[j];
  1603. out[last] = '\0';
  1604. }
  1605. return 0;
  1606. }
  1607. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  1608. static int resolve_link(const char *base, const char *href, char *out,
  1609. unsigned int cap)
  1610. {
  1611. char joined[BR_URL_MAX];
  1612. if (!href || !href[0] || href[0] == '#')
  1613. return -1;
  1614. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  1615. starts_with(href, "data:") || starts_with(href, "tel:"))
  1616. return -1;
  1617. if (starts_with(href, "about:")) {
  1618. s_copy(out, href, cap);
  1619. return 0;
  1620. }
  1621. if (is_http(href)) {
  1622. s_copy(out, href, cap);
  1623. return 0;
  1624. }
  1625. if (starts_with(href, "//")) {
  1626. if (is_http(base)) {
  1627. unsigned int n = 0;
  1628. s_append(out, &n, starts_with(base, "https:") ?
  1629. "https:" : "http:", cap);
  1630. s_append(out, &n, href, cap);
  1631. return 0;
  1632. }
  1633. return -1;
  1634. }
  1635. if (is_http(base)) {
  1636. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  1637. }
  1638. /* local page */
  1639. if (href[0] == '/') {
  1640. if (normalize_abs(href, out, cap) != 0)
  1641. return -1;
  1642. return 0;
  1643. }
  1644. {
  1645. char dir[BR_URL_MAX];
  1646. unsigned int n = 0;
  1647. if (s_eq(base, "about:home"))
  1648. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  1649. else if (path_dir(base, dir, sizeof(dir)) != 0)
  1650. s_copy(dir, "/", sizeof(dir));
  1651. s_append(joined, &n, dir, sizeof(joined));
  1652. if (n == 0 || joined[n - 1] != '/')
  1653. s_append(joined, &n, "/", sizeof(joined));
  1654. s_append(joined, &n, href, sizeof(joined));
  1655. }
  1656. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  1657. }
  1658. /* Best-effort decompression: keep the first `cap` bytes and discard the
  1659. * rest instead of failing when a page or stylesheet is larger than the
  1660. * buffer. The stream is still walked to the end, so a normal page is
  1661. * verified; a truncated compressed input still returns whatever was decoded
  1662. * so far. */
  1663. struct trunc_buf {
  1664. unsigned char *dst;
  1665. unsigned int cap, pos;
  1666. int full;
  1667. };
  1668. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  1669. {
  1670. struct trunc_buf *m = (struct trunc_buf *)ctx;
  1671. if (len > m->cap - m->pos) {
  1672. unsigned int room = m->cap - m->pos;
  1673. if (room) {
  1674. unsigned int i;
  1675. for (i = 0; i < room; i++)
  1676. m->dst[m->pos + i] = data[i];
  1677. m->pos += room;
  1678. }
  1679. m->full = 1;
  1680. return 0;
  1681. }
  1682. {
  1683. unsigned int i;
  1684. for (i = 0; i < len; i++)
  1685. m->dst[m->pos + i] = data[i];
  1686. }
  1687. m->pos += len;
  1688. return 0;
  1689. }
  1690. static void worker_wait_ui(void);
  1691. static void inflate_ui_pump(void *ctx)
  1692. {
  1693. static unsigned int last;
  1694. unsigned int now = u_ticks_ms();
  1695. (void)ctx;
  1696. if ((int)(now - last) >= 50) {
  1697. last = now;
  1698. worker_wait_ui();
  1699. }
  1700. }
  1701. static int inflate_trunc(const unsigned char *src, unsigned int len,
  1702. unsigned char *dst, unsigned int cap,
  1703. unsigned int *outlen, int gzip, int *truncated)
  1704. {
  1705. struct inflate_src in;
  1706. struct inflate_sink sink;
  1707. struct trunc_buf m;
  1708. unsigned int got = 0;
  1709. int r;
  1710. in.p = src;
  1711. in.len = len;
  1712. in.more = 0;
  1713. in.ctx = 0;
  1714. m.dst = dst;
  1715. m.cap = cap;
  1716. m.pos = 0;
  1717. m.full = 0;
  1718. sink.write = trunc_write;
  1719. sink.ctx = &m;
  1720. inflate_init(&image_inflate_ws, &in, &sink);
  1721. image_inflate_ws.progress = inflate_ui_pump;
  1722. image_inflate_ws.progress_ctx = 0;
  1723. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  1724. inflate_zlib(&image_inflate_ws, &got);
  1725. *outlen = m.pos;
  1726. *truncated = m.full || r != 0;
  1727. if (r != 0 && m.pos == 0)
  1728. return -1;
  1729. return 0;
  1730. }
  1731. /* ---- headless fetch workers ------------------------------------------ *
  1732. *
  1733. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  1734. * writes the raw response, a small metadata file and a done marker under
  1735. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  1736. * or a multi-megabyte body never freezes the UI and images download in
  1737. * parallel.
  1738. */
  1739. struct fetch_meta {
  1740. int status;
  1741. int error;
  1742. int trunc;
  1743. unsigned int len;
  1744. unsigned int open_ms;
  1745. unsigned int first_ms;
  1746. unsigned int total_ms;
  1747. char encoding[16];
  1748. char ctype[64];
  1749. char final[BR_URL_MAX];
  1750. };
  1751. static void draw(unsigned int *action);
  1752. static void handle_keys(unsigned int *action);
  1753. static void handle_page_click(unsigned int *action);
  1754. #define FETCH_WORKERS 4
  1755. #define FETCH_PATH_MAX 32
  1756. /* One long-lived curl __serve helper per worker. Each worker has its own
  1757. * request/body/meta/done files under /share so several downloads can be in
  1758. * flight at once; the keep-alive connection stays in the helper process, so
  1759. * tls.c's per-process state remains valid. */
  1760. struct fetch_worker {
  1761. int pid;
  1762. int slot;
  1763. int busy;
  1764. int ready;
  1765. int image_job;
  1766. unsigned int seq;
  1767. unsigned int deadline;
  1768. int retried;
  1769. char req[FETCH_PATH_MAX];
  1770. char body[FETCH_PATH_MAX];
  1771. char meta[FETCH_PATH_MAX];
  1772. char done[FETCH_PATH_MAX];
  1773. char post[FETCH_PATH_MAX];
  1774. /* Optional preload job attached to this worker. */
  1775. unsigned int node;
  1776. int bg;
  1777. char url[BR_URL_MAX];
  1778. struct fetch_meta m;
  1779. };
  1780. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  1781. static int fetch_tty = -2;
  1782. static unsigned int fetch_session;
  1783. static unsigned int fetch_seq;
  1784. static struct fetch_meta fetch_meta;
  1785. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  1786. * an HTTP-level error (helper died, timeout in the browser, ...). */
  1787. static int fetch_last_error;
  1788. static unsigned int meta_uint(char **pp)
  1789. {
  1790. char *p = *pp;
  1791. unsigned int v = 0;
  1792. while (*p >= '0' && *p <= '9') {
  1793. v = v * 10 + (unsigned int)(*p - '0');
  1794. p++;
  1795. }
  1796. while (*p && *p != '\n')
  1797. p++;
  1798. if (*p == '\n')
  1799. p++;
  1800. *pp = p;
  1801. return v;
  1802. }
  1803. static void meta_str(char **pp, char *out, unsigned int cap)
  1804. {
  1805. char *p = *pp;
  1806. unsigned int n = 0;
  1807. while (*p && *p != '\n' && n + 1 < cap)
  1808. out[n++] = *p++;
  1809. out[n] = '\0';
  1810. while (*p && *p != '\n')
  1811. p++;
  1812. if (*p == '\n')
  1813. p++;
  1814. *pp = p;
  1815. }
  1816. static void worker_wait_ui(void)
  1817. {
  1818. unsigned int action = 0;
  1819. if (!ngui_begin(&ui))
  1820. return;
  1821. draw(&action);
  1822. handle_keys(&action);
  1823. handle_page_click(&action);
  1824. if (action & ACT_WAIT_NAV) {
  1825. pending_action |= action & ACT_WAIT_NAV;
  1826. if ((action & ACT_NAV) && click_url[0])
  1827. s_copy(pending_url, click_url, sizeof(pending_url));
  1828. click_url[0] = '\0';
  1829. cancel_fetch = 1;
  1830. }
  1831. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  1832. ngui_invalidate(&ui);
  1833. ngui_end(&ui);
  1834. }
  1835. static void fetch_path(char *out, unsigned int cap, const char *kind,
  1836. unsigned int session, int slot)
  1837. {
  1838. unsigned int n = 0;
  1839. s_append(out, &n, "/share/bf", cap);
  1840. s_append_dec(out, &n, session, cap);
  1841. s_append(out, &n, "_", cap);
  1842. s_append_dec(out, &n, (unsigned int)slot, cap);
  1843. s_append(out, &n, kind, cap);
  1844. }
  1845. static void fetch_pool_init(void)
  1846. {
  1847. static int ready;
  1848. int i;
  1849. if (ready)
  1850. return;
  1851. ready = 1;
  1852. fetch_session = ((unsigned int)u_getpid() << 16) ^
  1853. (u_ticks_ms() & 0xFFFFu);
  1854. if (!fetch_session)
  1855. fetch_session = 1;
  1856. for (i = 0; i < FETCH_WORKERS; i++) {
  1857. struct fetch_worker *w = &fetch_workers[i];
  1858. w->pid = -1;
  1859. w->slot = i;
  1860. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  1861. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  1862. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  1863. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  1864. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  1865. }
  1866. }
  1867. static void fetch_worker_stop(struct fetch_worker *w)
  1868. {
  1869. int i;
  1870. if (w->pid > 0) {
  1871. u_kill((unsigned int)w->pid);
  1872. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  1873. u_sleep_ms(5);
  1874. /* Let the reaper close the socket before we reuse the slot. */
  1875. u_sleep_ms(10);
  1876. }
  1877. w->pid = -1;
  1878. w->busy = 0;
  1879. w->ready = 0;
  1880. w->image_job = 0;
  1881. if (w->req[0]) {
  1882. u_syscall1(SYS_UNLINK, (int)w->done);
  1883. u_syscall1(SYS_UNLINK, (int)w->meta);
  1884. u_syscall1(SYS_UNLINK, (int)w->body);
  1885. u_syscall1(SYS_UNLINK, (int)w->post);
  1886. u_syscall1(SYS_UNLINK, (int)w->req);
  1887. }
  1888. }
  1889. static void fetch_workers_stop_all(void)
  1890. {
  1891. int i;
  1892. for (i = 0; i < FETCH_WORKERS; i++)
  1893. fetch_worker_stop(&fetch_workers[i]);
  1894. }
  1895. /* Abandon the transfers of the current page but keep idle helpers and their
  1896. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  1897. * because its response would otherwise land in a reused /share slot. */
  1898. static void fetch_workers_cancel_busy(void)
  1899. {
  1900. int i;
  1901. for (i = 0; i < FETCH_WORKERS; i++)
  1902. if (fetch_workers[i].busy)
  1903. fetch_worker_stop(&fetch_workers[i]);
  1904. }
  1905. /* A kept-alive worker is only useful for the next page if its last URL was
  1906. * on the same origin. Closing the others before a navigation avoids leaving
  1907. * a pile of idle TLS connections from the previous site. */
  1908. static int worker_same_origin(const struct fetch_worker *w,
  1909. const struct uhttp_url *u)
  1910. {
  1911. struct uhttp_url wu;
  1912. if (w->pid <= 0 || !w->m.final[0])
  1913. return 0;
  1914. if (uhttp_parse_url(w->m.final, &wu) != 0)
  1915. return 0;
  1916. return wu.secure == u->secure && wu.port == u->port &&
  1917. s_eq(wu.host, u->host);
  1918. }
  1919. static void fetch_workers_prepare_nav(const char *url)
  1920. {
  1921. struct uhttp_url u;
  1922. int have = url && uhttp_parse_url(url, &u) == 0;
  1923. int i;
  1924. for (i = 0; i < FETCH_WORKERS; i++) {
  1925. struct fetch_worker *w = &fetch_workers[i];
  1926. if (w->pid <= 0)
  1927. continue;
  1928. if (w->busy || !have || !worker_same_origin(w, &u))
  1929. fetch_worker_stop(w);
  1930. }
  1931. }
  1932. /* The browser is no longer the active window and no fetch is running: give
  1933. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  1934. static void fetch_workers_stop_if_unfocused(void)
  1935. {
  1936. int i;
  1937. if (ui.focused || page_loading || preload_active)
  1938. return;
  1939. for (i = 0; i < FETCH_WORKERS; i++)
  1940. if (fetch_workers[i].pid > 0) {
  1941. fetch_workers_stop_all();
  1942. return;
  1943. }
  1944. }
  1945. static int fetch_worker_start(struct fetch_worker *w, char *err,
  1946. unsigned int errcap)
  1947. {
  1948. char arg[40];
  1949. unsigned int n = 0;
  1950. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  1951. return 0;
  1952. w->pid = -1;
  1953. fetch_pool_init();
  1954. if (fetch_tty == -2) {
  1955. int t = u_tty_create();
  1956. fetch_tty = t > 0 ? t : 0;
  1957. }
  1958. s_append(arg, &n, "__serve ", sizeof(arg));
  1959. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  1960. s_append(arg, &n, " ", sizeof(arg));
  1961. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  1962. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  1963. if (w->pid <= 0) {
  1964. w->pid = -1;
  1965. s_copy(err, "cannot start network helper", errcap);
  1966. return -1;
  1967. }
  1968. return 0;
  1969. }
  1970. static struct fetch_worker *fetch_worker_alloc(void)
  1971. {
  1972. int i;
  1973. fetch_pool_init();
  1974. for (i = 0; i < FETCH_WORKERS; i++)
  1975. if (!fetch_workers[i].busy)
  1976. return &fetch_workers[i];
  1977. return 0;
  1978. }
  1979. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1980. unsigned int cap, const char *post,
  1981. unsigned int post_len, unsigned int node,
  1982. int bg, char *err, unsigned int errcap)
  1983. {
  1984. static char req[768];
  1985. unsigned int n = 0;
  1986. fetch_seq++;
  1987. if (!fetch_seq)
  1988. fetch_seq = 1;
  1989. w->seq = fetch_seq;
  1990. w->ready = 0;
  1991. w->image_job = 0;
  1992. w->retried = 0;
  1993. w->m.error = 0;
  1994. w->node = node;
  1995. w->bg = bg;
  1996. s_copy(w->url, url, sizeof(w->url));
  1997. s_append_dec(req, &n, w->seq, sizeof(req));
  1998. s_append(req, &n, " ", sizeof(req));
  1999. s_append_dec(req, &n, cap, sizeof(req));
  2000. s_append(req, &n, " ", sizeof(req));
  2001. if (post_len) {
  2002. s_append(req, &n, "POST ", sizeof(req));
  2003. s_append_dec(req, &n, post_len, sizeof(req));
  2004. s_append(req, &n, " ", sizeof(req));
  2005. }
  2006. s_append(req, &n, url, sizeof(req));
  2007. s_append(req, &n, "\n", sizeof(req));
  2008. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  2009. (int)post, (int)post_len) < 0) {
  2010. s_copy(err, "cannot queue form body", errcap);
  2011. return -1;
  2012. }
  2013. u_syscall1(SYS_UNLINK, (int)w->done);
  2014. u_syscall1(SYS_UNLINK, (int)w->meta);
  2015. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  2016. s_copy(err, "cannot queue network request", errcap);
  2017. return -1;
  2018. }
  2019. if (fetch_worker_start(w, err, errcap) != 0)
  2020. return -1;
  2021. w->busy = 1;
  2022. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  2023. return 0;
  2024. }
  2025. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  2026. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  2027. unsigned int errcap)
  2028. {
  2029. static char meta[1024];
  2030. char *p;
  2031. int rn, mseq;
  2032. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  2033. (int)(sizeof(meta) - 1));
  2034. if (rn <= 0) {
  2035. s_copy(err, "network helper failed", errcap);
  2036. return -1;
  2037. }
  2038. meta[rn] = '\0';
  2039. p = meta;
  2040. mseq = (int)meta_uint(&p);
  2041. if (mseq != (int)w->seq) {
  2042. s_copy(err, "stale network response", errcap);
  2043. return -1;
  2044. }
  2045. w->m.status = (int)meta_uint(&p);
  2046. w->m.error = (int)meta_uint(&p);
  2047. w->m.trunc = (int)meta_uint(&p);
  2048. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  2049. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  2050. meta_str(&p, w->m.final, sizeof(w->m.final));
  2051. w->m.len = meta_uint(&p);
  2052. w->m.open_ms = 0;
  2053. w->m.first_ms = 0;
  2054. w->m.total_ms = 0;
  2055. if (*p) {
  2056. w->m.open_ms = meta_uint(&p);
  2057. w->m.first_ms = meta_uint(&p);
  2058. w->m.total_ms = meta_uint(&p);
  2059. }
  2060. if (w->m.error) {
  2061. s_copy(err, uhttp_error_string(w->m.error), errcap);
  2062. return -1;
  2063. }
  2064. w->ready = 1;
  2065. return 0;
  2066. }
  2067. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  2068. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  2069. unsigned int errcap)
  2070. {
  2071. static char done[24];
  2072. char *p;
  2073. int rn, mseq;
  2074. if (!w->busy)
  2075. return -1;
  2076. if (w->ready)
  2077. return 1;
  2078. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  2079. (int)(sizeof(done) - 1));
  2080. if (rn > 0) {
  2081. done[rn] = '\0';
  2082. p = done;
  2083. mseq = (int)meta_uint(&p);
  2084. if (mseq == (int)w->seq) {
  2085. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  2086. fetch_worker_stop(w);
  2087. return -1;
  2088. }
  2089. return 1;
  2090. }
  2091. }
  2092. if (!u_alive((unsigned int)w->pid)) {
  2093. w->pid = -1;
  2094. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  2095. w->retried = 1;
  2096. return 0;
  2097. }
  2098. s_copy(err, "network helper stopped", errcap);
  2099. fetch_worker_stop(w);
  2100. return -1;
  2101. }
  2102. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  2103. s_copy(err, "network request timed out", errcap);
  2104. fetch_worker_stop(w);
  2105. return -1;
  2106. }
  2107. return 0;
  2108. }
  2109. /* Copy the completed body, inflating it if the server ignored our identity
  2110. * request. Mirrors the old fetch_remote body path. */
  2111. static int fetch_worker_read_body(struct fetch_worker *w,
  2112. unsigned char *plain,
  2113. unsigned int plaincap,
  2114. unsigned char *comp,
  2115. unsigned int compcap,
  2116. int *truncated, char *err,
  2117. unsigned int errcap)
  2118. {
  2119. int rv, zr, was_trunc;
  2120. if (contains_ci(w->m.encoding, "gzip") ||
  2121. contains_ci(w->m.encoding, "deflate")) {
  2122. unsigned int comp_len = 0, plen = 0;
  2123. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  2124. (int)compcap);
  2125. if (rv < 0) {
  2126. s_copy(err, "empty response", errcap);
  2127. return -1;
  2128. }
  2129. comp_len = (unsigned int)rv;
  2130. if (comp_len < w->m.len) {
  2131. s_copy(err, "compressed response is too large", errcap);
  2132. return -1;
  2133. }
  2134. if (contains_ci(w->m.encoding, "deflate"))
  2135. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2136. &plen, 0, &was_trunc);
  2137. else
  2138. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2139. &plen, 1, &was_trunc);
  2140. if (zr != 0) {
  2141. s_copy(err, "compressed response is corrupt", errcap);
  2142. return -1;
  2143. }
  2144. *truncated = w->m.trunc || was_trunc;
  2145. return (int)plen;
  2146. }
  2147. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  2148. if (rv < 0) {
  2149. s_copy(err, "empty response", errcap);
  2150. return -1;
  2151. }
  2152. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  2153. return rv;
  2154. }
  2155. static void fetch_worker_release(struct fetch_worker *w)
  2156. {
  2157. u_syscall1(SYS_UNLINK, (int)w->done);
  2158. u_syscall1(SYS_UNLINK, (int)w->meta);
  2159. u_syscall1(SYS_UNLINK, (int)w->body);
  2160. u_syscall1(SYS_UNLINK, (int)w->post);
  2161. u_syscall1(SYS_UNLINK, (int)w->req);
  2162. w->busy = 0;
  2163. w->ready = 0;
  2164. w->image_job = 0;
  2165. }
  2166. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  2167. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  2168. unsigned int errcap)
  2169. {
  2170. for (;;) {
  2171. int rv;
  2172. worker_wait_ui();
  2173. if (cancel_fetch || pending_action) {
  2174. fetch_workers_cancel_busy();
  2175. return FETCH_ABORT;
  2176. }
  2177. rv = fetch_worker_poll(w, err, errcap);
  2178. if (rv != 0)
  2179. return rv == 1 ? 0 : -1;
  2180. u_sleep_ms(10);
  2181. }
  2182. }
  2183. static int fetch_remote(const char *url, unsigned int cap,
  2184. const char *post, unsigned int post_len,
  2185. unsigned char *plain, unsigned int plaincap,
  2186. unsigned char *comp, unsigned int compcap,
  2187. struct fetch_meta *m, int *truncated,
  2188. char *err, unsigned int errcap)
  2189. {
  2190. struct fetch_worker *w = fetch_worker_alloc();
  2191. int rv;
  2192. fetch_last_error = 0;
  2193. if (!w) {
  2194. s_copy(err, "network busy", errcap);
  2195. return -1;
  2196. }
  2197. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  2198. err, errcap) != 0) {
  2199. fetch_worker_release(w);
  2200. return -1;
  2201. }
  2202. rv = fetch_worker_wait(w, err, errcap);
  2203. if (rv == FETCH_ABORT) {
  2204. fetch_worker_release(w);
  2205. return FETCH_ABORT;
  2206. }
  2207. if (rv != 0) {
  2208. fetch_last_error = w->m.error;
  2209. fetch_worker_release(w);
  2210. return -1;
  2211. }
  2212. *m = w->m;
  2213. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  2214. truncated, err, errcap);
  2215. fetch_worker_release(w);
  2216. if (rv >= 0 && (cancel_fetch || pending_action))
  2217. return FETCH_ABORT;
  2218. return rv;
  2219. }
  2220. /* ---- HTTP / file fetch ---- */
  2221. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  2222. unsigned int *outlen, int *is_local, char *ctype,
  2223. unsigned int ctcap, char *final, unsigned int finalcap,
  2224. char *err, unsigned int errcap, int *truncated,
  2225. const char *post, unsigned int post_len)
  2226. {
  2227. unsigned char *buf;
  2228. unsigned int len;
  2229. int tr = 0;
  2230. int rv;
  2231. *out = 0;
  2232. *outlen = 0;
  2233. *truncated = 0;
  2234. if (final && finalcap)
  2235. final[0] = '\0';
  2236. if (ctype && ctcap)
  2237. ctype[0] = '\0';
  2238. if (url[0] == '/') {
  2239. char pathbuf[BR_URL_MAX];
  2240. const char *open_url = url;
  2241. unsigned int i = 0;
  2242. /* A local form GET keeps ?query in the address bar but the
  2243. * file lookup uses the path alone, like a real browser. */
  2244. while (url[i] && url[i] != '?' && url[i] != '#')
  2245. i++;
  2246. if (url[i]) {
  2247. s_copy(pathbuf, url, i + 1);
  2248. open_url = pathbuf;
  2249. }
  2250. buf = (unsigned char *)malloc(cap);
  2251. if (!buf) {
  2252. s_copy(err, "out of memory", errcap);
  2253. return -1;
  2254. }
  2255. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  2256. if (rv < 0) {
  2257. free(buf);
  2258. s_copy(err, "file not found", errcap);
  2259. return -1;
  2260. }
  2261. *out = buf;
  2262. *outlen = (unsigned int)rv;
  2263. *is_local = 1;
  2264. if (ctype)
  2265. s_copy(ctype, "text/html", ctcap);
  2266. if (final)
  2267. s_copy(final, url, finalcap);
  2268. if ((unsigned int)rv == cap)
  2269. *truncated = 1;
  2270. return 0;
  2271. }
  2272. buf = (unsigned char *)malloc(cap);
  2273. if (!buf) {
  2274. s_copy(err, "out of memory", errcap);
  2275. return -1;
  2276. }
  2277. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  2278. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  2279. if (rv == FETCH_ABORT) {
  2280. free(buf);
  2281. return FETCH_ABORT;
  2282. }
  2283. if (rv < 0) {
  2284. free(buf);
  2285. return -1;
  2286. }
  2287. len = (unsigned int)rv;
  2288. if (len == 0) {
  2289. free(buf);
  2290. s_copy(err, "empty response", errcap);
  2291. return -1;
  2292. }
  2293. if (ctype)
  2294. s_copy(ctype, fetch_meta.ctype, ctcap);
  2295. if (final && fetch_meta.final[0])
  2296. s_copy(final, fetch_meta.final, finalcap);
  2297. *is_local = 0;
  2298. *out = buf;
  2299. *outlen = len;
  2300. *truncated = tr;
  2301. return 0;
  2302. }
  2303. /* Load every @font-face the parser registered. Local files go through
  2304. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  2305. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  2306. * to the built-in regular/bold/italic/mono set. */
  2307. static void load_font_faces(void)
  2308. {
  2309. unsigned int i;
  2310. memset(font_faces, 0, sizeof(font_faces));
  2311. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  2312. i <= BR_MAX_FACES; i++) {
  2313. const char *url = br_font_face_url((int)i);
  2314. const char *base = br_font_face_base((int)i);
  2315. char abs[BR_URL_MAX];
  2316. if (!url || !url[0])
  2317. continue;
  2318. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  2319. sizeof(abs)) != 0)
  2320. continue;
  2321. if (abs[0] == '/') {
  2322. font_faces[i - 1] = ufont_face_open_path(abs);
  2323. } else if (is_http(abs)) {
  2324. unsigned char *buf;
  2325. char err[64];
  2326. int rv, tr = 0;
  2327. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  2328. if (!buf)
  2329. continue;
  2330. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  2331. UFONT_MAX_FILE, image_io_buf,
  2332. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  2333. err, sizeof(err));
  2334. if (rv > 0)
  2335. font_faces[i - 1] = ufont_face_open_mem(buf,
  2336. rv);
  2337. free(buf);
  2338. }
  2339. }
  2340. }
  2341. /* Remote scripts are cached under /share for the current boot, like the
  2342. * stylesheet cache, so reloads and later visits skip the network. */
  2343. static int script_cache_count;
  2344. static unsigned int script_cache_hash(const char *s)
  2345. {
  2346. unsigned int h = 2166136261u;
  2347. while (*s) {
  2348. h ^= (unsigned char)*s++;
  2349. h *= 16777619u;
  2350. }
  2351. return h;
  2352. }
  2353. static void script_cache_path(const char *url, char *out, unsigned int cap)
  2354. {
  2355. unsigned int n = 0;
  2356. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  2357. s_append_dec(out, &n, script_cache_hash(url), cap);
  2358. }
  2359. static void script_cache_clear(void)
  2360. {
  2361. struct sys_dirent d;
  2362. char path[96];
  2363. for (;;) {
  2364. int i, found = 0;
  2365. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2366. (int)&d) == 1; i++) {
  2367. unsigned int n = 0;
  2368. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  2369. continue;
  2370. s_append(path, &n, "/share/", sizeof(path));
  2371. s_append(path, &n, d.name, sizeof(path));
  2372. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  2373. return;
  2374. found = 1;
  2375. break;
  2376. }
  2377. if (!found)
  2378. break;
  2379. }
  2380. script_cache_count = 0;
  2381. }
  2382. static void script_cache_init(void)
  2383. {
  2384. struct sys_dirent d;
  2385. int i, count = 0;
  2386. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2387. (int)&d) == 1; i++)
  2388. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  2389. count++;
  2390. if (count >= SCRIPT_CACHE_MAX) {
  2391. script_cache_clear();
  2392. return;
  2393. }
  2394. script_cache_count = count;
  2395. }
  2396. static int script_cache_get(const char *url, unsigned char **out,
  2397. unsigned int *outlen)
  2398. {
  2399. char path[96];
  2400. struct sys_stat st;
  2401. unsigned char *buf;
  2402. int rn;
  2403. script_cache_path(url, path, sizeof(path));
  2404. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  2405. st.size >= SCRIPT_CACHE_FILE_MAX)
  2406. return 0;
  2407. buf = (unsigned char *)malloc(st.size + 1);
  2408. if (!buf)
  2409. return 0;
  2410. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  2411. if (rn != (int)st.size) {
  2412. free(buf);
  2413. return 0;
  2414. }
  2415. buf[st.size] = '\0';
  2416. *out = buf;
  2417. *outlen = st.size;
  2418. return 1;
  2419. }
  2420. static void script_cache_put(const char *url, const unsigned char *data,
  2421. unsigned int len)
  2422. {
  2423. char path[96];
  2424. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  2425. len >= SCRIPT_CACHE_FILE_MAX)
  2426. return;
  2427. script_cache_path(url, path, sizeof(path));
  2428. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  2429. (int)len) >= 0)
  2430. script_cache_count++;
  2431. }
  2432. static int script_cache_has(const char *url)
  2433. {
  2434. char path[96];
  2435. struct sys_stat st;
  2436. script_cache_path(url, path, sizeof(path));
  2437. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  2438. st.size < SCRIPT_CACHE_FILE_MAX;
  2439. }
  2440. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  2441. static int fetch_script_text(const char *url, unsigned char **out,
  2442. unsigned int *outlen, char *err,
  2443. unsigned int errcap)
  2444. {
  2445. unsigned char *buf;
  2446. unsigned int len;
  2447. int local, truncated = 0;
  2448. char ctype[64], final[BR_URL_MAX];
  2449. int rv;
  2450. *out = 0;
  2451. *outlen = 0;
  2452. if (url[0] != '/' && script_cache_get(url, out, outlen))
  2453. return 0;
  2454. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  2455. sizeof(ctype), final, sizeof(final), err, errcap,
  2456. &truncated, 0, 0);
  2457. if (rv != 0)
  2458. return rv;
  2459. if (truncated || len >= BR_SCRIPT_MAX) {
  2460. free(buf);
  2461. s_copy(err, "script is too large", errcap);
  2462. return -1;
  2463. }
  2464. buf[len] = '\0';
  2465. if (!local)
  2466. script_cache_put(url, buf, len);
  2467. *out = buf;
  2468. *outlen = len;
  2469. return 0;
  2470. }
  2471. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  2472. * the heap, so images must not allocate their file body from it as well. */
  2473. static int fetch_image(const char *url, unsigned int cap,
  2474. unsigned char **out, unsigned int *outlen,
  2475. char *err, unsigned int errcap)
  2476. {
  2477. unsigned int len;
  2478. int tr = 0;
  2479. int rv;
  2480. *out = 0;
  2481. *outlen = 0;
  2482. if (cap > BR_IMG_FILE_MAX)
  2483. cap = BR_IMG_FILE_MAX;
  2484. if (url[0] == '/') {
  2485. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  2486. (int)cap);
  2487. if (rv < 0) {
  2488. s_copy(err, "file not found", errcap);
  2489. return -1;
  2490. }
  2491. *out = image_file_buf;
  2492. *outlen = (unsigned int)rv;
  2493. return 0;
  2494. }
  2495. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  2496. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  2497. if (rv == FETCH_ABORT)
  2498. return FETCH_ABORT;
  2499. if (rv < 0)
  2500. return -1;
  2501. len = (unsigned int)rv;
  2502. if (len == 0) {
  2503. s_copy(err, "empty image", errcap);
  2504. return -1;
  2505. }
  2506. *out = image_file_buf;
  2507. *outlen = len;
  2508. return 0;
  2509. }
  2510. /* Remote stylesheets are immutable enough for the current boot: keep
  2511. * successful responses under /share so a reload, a second visit or a fresh
  2512. * browser launch does not fetch the same five sheets over the network again.
  2513. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  2514. static int css_cache_count;
  2515. static unsigned int css_cache_hash(const char *s)
  2516. {
  2517. unsigned int h = 2166136261u;
  2518. while (*s) {
  2519. h ^= (unsigned char)*s++;
  2520. h *= 16777619u;
  2521. }
  2522. return h;
  2523. }
  2524. static void css_cache_path(const char *url, char *out, unsigned int cap)
  2525. {
  2526. unsigned int n = 0;
  2527. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  2528. s_append_dec(out, &n, css_cache_hash(url), cap);
  2529. }
  2530. static void css_cache_clear(void)
  2531. {
  2532. struct sys_dirent d;
  2533. char path[96];
  2534. for (;;) {
  2535. int i, found = 0;
  2536. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2537. (int)&d) == 1; i++) {
  2538. unsigned int n = 0;
  2539. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  2540. continue;
  2541. s_append(path, &n, "/share/", sizeof(path));
  2542. s_append(path, &n, d.name, sizeof(path));
  2543. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  2544. return;
  2545. found = 1;
  2546. break;
  2547. }
  2548. if (!found)
  2549. break;
  2550. }
  2551. css_cache_count = 0;
  2552. }
  2553. static void css_cache_init(void)
  2554. {
  2555. struct sys_dirent d;
  2556. int i, count = 0;
  2557. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2558. (int)&d) == 1; i++)
  2559. if (starts_with(d.name, CSS_CACHE_PREFIX))
  2560. count++;
  2561. if (count >= CSS_CACHE_MAX) {
  2562. css_cache_clear();
  2563. return;
  2564. }
  2565. css_cache_count = count;
  2566. }
  2567. static int css_cache_get(const char *url, unsigned char **out,
  2568. unsigned int *outlen)
  2569. {
  2570. char path[96];
  2571. int rn;
  2572. css_cache_path(url, path, sizeof(path));
  2573. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  2574. (int)CSS_CACHE_FILE_MAX);
  2575. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  2576. return 0;
  2577. *out = image_io_buf;
  2578. *outlen = (unsigned int)rn;
  2579. return 1;
  2580. }
  2581. static void css_cache_put(const char *url, const unsigned char *data,
  2582. unsigned int len)
  2583. {
  2584. char path[96];
  2585. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  2586. len >= CSS_CACHE_FILE_MAX)
  2587. return;
  2588. css_cache_path(url, path, sizeof(path));
  2589. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  2590. (int)len) >= 0)
  2591. css_cache_count++;
  2592. }
  2593. static int css_cache_has(const char *url)
  2594. {
  2595. char path[96];
  2596. struct sys_stat st;
  2597. css_cache_path(url, path, sizeof(path));
  2598. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  2599. st.size < CSS_CACHE_FILE_MAX;
  2600. }
  2601. /* Read one stylesheet into the shared static buffer. CSS is parsed
  2602. * immediately, so it does not need the page heap; this leaves the heap for
  2603. * the 2 MB page body, the rules and the scaled image bitmaps. */
  2604. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  2605. char *err, unsigned int errcap)
  2606. {
  2607. unsigned int len;
  2608. int tr = 0;
  2609. int rv;
  2610. *out = 0;
  2611. *outlen = 0;
  2612. if (url[0] == '/') {
  2613. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  2614. (int)BR_CSS_MAX);
  2615. if (rv < 0) {
  2616. s_copy(err, "stylesheet not found", errcap);
  2617. return -1;
  2618. }
  2619. *out = image_io_buf;
  2620. *outlen = (unsigned int)rv;
  2621. return 0;
  2622. }
  2623. if (css_cache_get(url, out, outlen))
  2624. return 0;
  2625. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  2626. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  2627. &fetch_meta, &tr, err, errcap);
  2628. if (rv == FETCH_ABORT)
  2629. return FETCH_ABORT;
  2630. if (rv < 0)
  2631. return -1;
  2632. len = (unsigned int)rv;
  2633. if (len == 0) {
  2634. s_copy(err, "empty stylesheet", errcap);
  2635. return -1;
  2636. }
  2637. *out = image_io_buf;
  2638. *outlen = len;
  2639. css_cache_put(url, image_io_buf, len);
  2640. return 0;
  2641. }
  2642. static void redraw_now(void);
  2643. static char error_page[1024];
  2644. static void show_error(const char *title, const char *detail)
  2645. {
  2646. char *page = error_page;
  2647. unsigned int n = 0;
  2648. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  2649. s_append(page, &n, title, sizeof(error_page));
  2650. s_append(page, &n, "</h2><p>", sizeof(error_page));
  2651. {
  2652. const char *p = detail;
  2653. while (*p && n + 1 < sizeof(error_page)) {
  2654. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  2655. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  2656. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  2657. else page[n++] = *p;
  2658. p++;
  2659. }
  2660. }
  2661. page[n] = '\0';
  2662. s_append(page, &n, "</p><p>", sizeof(error_page));
  2663. s_append(page, &n, page_url, sizeof(error_page));
  2664. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  2665. sizeof(error_page));
  2666. br_parse(&doc, page, n);
  2667. layout_valid = 0;
  2668. preload_active = 0;
  2669. preload_pending = 0;
  2670. preload_wait = 0;
  2671. fetch_workers_cancel_busy();
  2672. s_copy(page_title, title, sizeof(page_title));
  2673. page_loading = 0;
  2674. set_status(title, 1, 0);
  2675. ngui_invalidate(&ui);
  2676. }
  2677. static int decode_direct_image(const unsigned char *data, unsigned int len,
  2678. unsigned int node)
  2679. {
  2680. if (image_count >= BR_MAX_IMAGES)
  2681. return -1;
  2682. if (decode_image_data(data, len, &images[0]) != 0)
  2683. return -1;
  2684. doc.nodes[node].img_index = 0;
  2685. image_count = 1;
  2686. return 0;
  2687. }
  2688. static int ancestor_is(unsigned int node, unsigned int tag)
  2689. {
  2690. unsigned int p = doc.nodes[node].parent;
  2691. while (p) {
  2692. if (doc.nodes[p].tag == tag)
  2693. return 1;
  2694. p = doc.nodes[p].parent;
  2695. }
  2696. return 0;
  2697. }
  2698. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  2699. * parallel but parsed in document order, so the cascade is unchanged. */
  2700. static int load_stylesheets(void)
  2701. {
  2702. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  2703. static unsigned char remote[BR_MAX_SHEETS];
  2704. struct fetch_worker *slot[BR_MAX_SHEETS];
  2705. unsigned int i, n = 0, next = 0, k;
  2706. char err[64];
  2707. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  2708. struct br_node *nd = &doc.nodes[i];
  2709. const char *rel, *href;
  2710. char url[BR_URL_MAX];
  2711. int dup = 0;
  2712. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  2713. continue;
  2714. rel = br_rel(&doc, i);
  2715. if (!contains_ci(rel, "stylesheet"))
  2716. continue;
  2717. href = br_href(&doc, i);
  2718. if (!href[0])
  2719. continue;
  2720. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  2721. continue;
  2722. for (k = 0; k < n; k++)
  2723. if (s_eq(urls[k], url)) {
  2724. dup = 1;
  2725. break;
  2726. }
  2727. if (dup)
  2728. continue;
  2729. s_copy(urls[n], url, BR_URL_MAX);
  2730. remote[n] = url[0] != '/' && !css_cache_has(url);
  2731. n++;
  2732. }
  2733. for (i = 0; i < BR_MAX_SHEETS; i++)
  2734. slot[i] = 0;
  2735. /* Start as many remote sheets as there are free workers. */
  2736. for (; next < n; next++) {
  2737. struct fetch_worker *w;
  2738. if (!remote[next])
  2739. continue;
  2740. w = fetch_worker_alloc();
  2741. if (!w)
  2742. break;
  2743. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  2744. err, sizeof(err)) != 0) {
  2745. fetch_worker_release(w);
  2746. remote[next] = 0;
  2747. continue;
  2748. }
  2749. slot[next] = w;
  2750. }
  2751. for (i = 0; i < n; i++) {
  2752. unsigned char *data = 0;
  2753. unsigned int len = 0;
  2754. int rv;
  2755. if (!remote[i]) {
  2756. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  2757. if (rv == FETCH_ABORT) {
  2758. fetch_workers_stop_all();
  2759. return FETCH_ABORT;
  2760. }
  2761. if (rv != 0 || !len)
  2762. continue;
  2763. } else {
  2764. struct fetch_worker *w = slot[i];
  2765. int tr = 0;
  2766. if (!w) {
  2767. w = fetch_worker_alloc();
  2768. if (!w)
  2769. continue;
  2770. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  2771. 0, 0, 0, 0, err,
  2772. sizeof(err)) != 0) {
  2773. fetch_worker_release(w);
  2774. remote[i] = 0;
  2775. if (i == next)
  2776. next++;
  2777. continue;
  2778. }
  2779. slot[i] = w;
  2780. if (i == next)
  2781. next++;
  2782. }
  2783. rv = fetch_worker_wait(w, err, sizeof(err));
  2784. if (rv == FETCH_ABORT) {
  2785. fetch_workers_stop_all();
  2786. return FETCH_ABORT;
  2787. }
  2788. if (rv == 0)
  2789. rv = fetch_worker_read_body(w, image_io_buf,
  2790. BR_CSS_MAX,
  2791. image_io_buf + BR_CSS_MAX,
  2792. BR_CSS_COMP_MAX, &tr,
  2793. err, sizeof(err));
  2794. else
  2795. rv = -1;
  2796. fetch_worker_release(w);
  2797. slot[i] = 0;
  2798. /* Refill the worker window before parsing this sheet. */
  2799. for (; next < n; next++) {
  2800. struct fetch_worker *nw;
  2801. if (!remote[next])
  2802. continue;
  2803. nw = fetch_worker_alloc();
  2804. if (!nw)
  2805. break;
  2806. if (fetch_worker_submit(nw, urls[next],
  2807. BR_CSS_MAX, 0, 0, 0, 0,
  2808. err, sizeof(err)) != 0) {
  2809. fetch_worker_release(nw);
  2810. remote[next] = 0;
  2811. continue;
  2812. }
  2813. slot[next] = nw;
  2814. }
  2815. if (rv <= 0)
  2816. continue;
  2817. len = (unsigned int)rv;
  2818. data = image_io_buf;
  2819. css_cache_put(urls[i], data, len);
  2820. }
  2821. if (len) {
  2822. br_set_font_base(urls[i]);
  2823. br_parse_css_text(&doc, (const char *)data, len);
  2824. }
  2825. }
  2826. br_set_font_base(page_url);
  2827. br_parse_inline_css(&doc);
  2828. load_font_faces();
  2829. br_reset_styles(&doc);
  2830. layout_valid = 0;
  2831. return 0;
  2832. }
  2833. static void preload_begin(void)
  2834. {
  2835. preload_active = 1;
  2836. preload_pending = 0;
  2837. preload_wait = 1;
  2838. preload_max_jobs = FETCH_WORKERS;
  2839. preload_node = 0;
  2840. preload_loaded = 0;
  2841. preload_scroll = 0;
  2842. }
  2843. /* Styles are computed top-down during layout, but images inside a hidden
  2844. * menu/carousel are never visited and keep img_top == 0. Without this check
  2845. * the preloader walks the DOM in node order and spends the whole image
  2846. * budget on logos and off-canvas thumbnails the reader cannot see. */
  2847. static int node_hidden(unsigned int node)
  2848. {
  2849. unsigned int path[32], n = 0, p = node, i;
  2850. struct br_style st, parent;
  2851. while (p && n < sizeof(path) / sizeof(path[0])) {
  2852. path[n++] = p;
  2853. p = doc.nodes[p].parent;
  2854. }
  2855. parent = (struct br_style){0};
  2856. parent.font_px = 16;
  2857. parent.display = BR_DISPLAY_BLOCK;
  2858. for (i = n; i > 0; i--) {
  2859. br_style_for(&doc, path[i - 1], &parent, &st);
  2860. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  2861. st.opacity_hidden)
  2862. return 1;
  2863. parent = st;
  2864. }
  2865. return 0;
  2866. }
  2867. static struct br_style base_style(void);
  2868. static void style_for_node(unsigned int node, struct br_style *out)
  2869. {
  2870. unsigned int p = doc.nodes[node].parent;
  2871. struct br_style parent;
  2872. if (p) {
  2873. style_for_node(p, &parent);
  2874. br_style_for(&doc, node, &parent, out);
  2875. } else {
  2876. parent = base_style();
  2877. br_style_for(&doc, node, &parent, out);
  2878. }
  2879. }
  2880. /* ---- parallel image preloading ---- *
  2881. *
  2882. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  2883. * preload_step() only starts jobs and harvests completed ones; the browser
  2884. * main loop keeps drawing between calls, instead of blocking on one fetch.
  2885. */
  2886. static int preload_active_jobs(void)
  2887. {
  2888. int i, n = 0;
  2889. for (i = 0; i < FETCH_WORKERS; i++)
  2890. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  2891. n++;
  2892. return n;
  2893. }
  2894. static void preload_job_error(struct fetch_worker *w)
  2895. {
  2896. if (w->node < doc.nnode) {
  2897. if (w->bg)
  2898. doc.nodes[w->node].bg_img_index = -2;
  2899. else
  2900. doc.nodes[w->node].img_index = -2;
  2901. ngui_invalidate(&ui);
  2902. }
  2903. }
  2904. static void preload_decode(unsigned int node, int bg,
  2905. const unsigned char *data, unsigned int len)
  2906. {
  2907. if (image_count >= BR_MAX_IMAGES) {
  2908. if (bg)
  2909. doc.nodes[node].bg_img_index = -2;
  2910. else
  2911. doc.nodes[node].img_index = -2;
  2912. return;
  2913. }
  2914. if (decode_image_data(data, len, &images[image_count]) == 0) {
  2915. if (bg)
  2916. doc.nodes[node].bg_img_index = (short)image_count;
  2917. else
  2918. doc.nodes[node].img_index = (short)image_count;
  2919. image_count++;
  2920. preload_loaded++;
  2921. layout_valid = 0;
  2922. } else {
  2923. if (bg)
  2924. doc.nodes[node].bg_img_index = -2;
  2925. else
  2926. doc.nodes[node].img_index = -2;
  2927. }
  2928. ngui_invalidate(&ui);
  2929. }
  2930. /* Harvest one completed worker. Returns 1 when a job was finished. */
  2931. static int preload_finish_worker(struct fetch_worker *w)
  2932. {
  2933. char err[64];
  2934. int rv, tr = 0;
  2935. rv = fetch_worker_poll(w, err, sizeof(err));
  2936. if (rv < 0) {
  2937. preload_job_error(w);
  2938. fetch_worker_release(w);
  2939. return 1;
  2940. }
  2941. if (rv == 0)
  2942. return 0;
  2943. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  2944. image_comp_buf, BR_IMG_FILE_MAX,
  2945. &tr, err, sizeof(err));
  2946. if (rv >= 0)
  2947. preload_decode(w->node, w->bg, image_file_buf,
  2948. (unsigned int)rv);
  2949. else
  2950. preload_job_error(w);
  2951. fetch_worker_release(w);
  2952. return 1;
  2953. }
  2954. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  2955. * the number of jobs started. */
  2956. static int preload_fill_jobs(void)
  2957. {
  2958. int started = 0;
  2959. char err[64];
  2960. while (preload_active && preload_node < doc.nnode) {
  2961. unsigned int i = preload_node;
  2962. struct br_node *nd = &doc.nodes[i];
  2963. const char *src;
  2964. char url[BR_URL_MAX];
  2965. struct fetch_worker *w;
  2966. if (preload_active_jobs() >= preload_max_jobs)
  2967. break;
  2968. if (nd->type != BR_NODE_ELEM) {
  2969. preload_node++;
  2970. continue;
  2971. }
  2972. if (nd->tag != BR_TAG_IMG) {
  2973. if (nd->bg_img_index == -1) {
  2974. struct br_style bs;
  2975. style_for_node(i, &bs);
  2976. if (bs.display != BR_DISPLAY_NONE &&
  2977. !bs.vis_hidden && bs.bg_image) {
  2978. const char *bsrc =
  2979. br_bg_image_url(bs.bg_image - 1);
  2980. if (bsrc[0] &&
  2981. !contains_ci(bsrc, ".svg") &&
  2982. !starts_with(bsrc, "data:") &&
  2983. resolve_link(page_url, bsrc, url,
  2984. sizeof(url)) == 0) {
  2985. if (image_count +
  2986. preload_active_jobs() >=
  2987. BR_MAX_IMAGES) {
  2988. preload_node = doc.nnode;
  2989. break;
  2990. }
  2991. if (url[0] == '/') {
  2992. unsigned char *data = 0;
  2993. unsigned int len = 0;
  2994. preload_node = i + 1;
  2995. if (fetch_image(url,
  2996. BR_IMG_FILE_MAX,
  2997. &data, &len,
  2998. err,
  2999. sizeof(err)) == 0)
  3000. preload_decode(i, 1, data, len);
  3001. else
  3002. nd->bg_img_index = -2;
  3003. continue;
  3004. }
  3005. w = fetch_worker_alloc();
  3006. if (!w)
  3007. return started;
  3008. preload_node = i + 1;
  3009. if (fetch_worker_submit(w, url,
  3010. BR_IMG_FILE_MAX,
  3011. 0, 0, i, 1,
  3012. err,
  3013. sizeof(err)) != 0) {
  3014. nd->bg_img_index = -2;
  3015. fetch_worker_release(w);
  3016. continue;
  3017. }
  3018. w->image_job = 1;
  3019. started++;
  3020. continue;
  3021. }
  3022. }
  3023. nd->bg_img_index = -2;
  3024. }
  3025. preload_node++;
  3026. continue;
  3027. }
  3028. if (nd->img_index != -1) {
  3029. preload_node++;
  3030. continue;
  3031. }
  3032. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  3033. preload_node++;
  3034. continue;
  3035. }
  3036. src = br_src(&doc, i);
  3037. if (!src[0] || contains_ci(src, ".svg") ||
  3038. starts_with(src, "data:")) {
  3039. preload_node++;
  3040. continue;
  3041. }
  3042. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  3043. preload_node++;
  3044. continue;
  3045. }
  3046. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  3047. preload_node = doc.nnode;
  3048. break;
  3049. }
  3050. /* Do not stop at the first below-fold image: DOM order is
  3051. * not visual order, and a footer/ad image early in the DOM
  3052. * used to hide every later article image from the loader. */
  3053. if (img_top[i] >
  3054. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  3055. preload_pending = 1;
  3056. preload_node++;
  3057. continue;
  3058. }
  3059. if (url[0] == '/') {
  3060. unsigned char *data = 0;
  3061. unsigned int len = 0;
  3062. preload_node = i + 1;
  3063. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  3064. err, sizeof(err)) == 0)
  3065. preload_decode(i, 0, data, len);
  3066. else
  3067. nd->img_index = -2;
  3068. continue;
  3069. }
  3070. w = fetch_worker_alloc();
  3071. if (!w)
  3072. return started;
  3073. preload_node = i + 1;
  3074. {
  3075. char msg[64];
  3076. unsigned int n = 0;
  3077. s_append(msg, &n, "Loading images ", sizeof(msg));
  3078. s_append_dec(msg, &n,
  3079. (unsigned int)preload_loaded + 1,
  3080. sizeof(msg));
  3081. s_append(msg, &n, "...", sizeof(msg));
  3082. set_status(msg, 0, 0);
  3083. }
  3084. if (fetch_worker_submit(w, url, BR_IMG_FILE_MAX, 0, 0, i, 0,
  3085. err, sizeof(err)) != 0) {
  3086. nd->img_index = -2;
  3087. fetch_worker_release(w);
  3088. continue;
  3089. }
  3090. w->image_job = 1;
  3091. started++;
  3092. }
  3093. return started;
  3094. }
  3095. static void preload_step(void)
  3096. {
  3097. unsigned int batch = 0;
  3098. if (!preload_active)
  3099. return;
  3100. if (cancel_fetch || pending_action) {
  3101. preload_active = 0;
  3102. preload_pending = 0;
  3103. fetch_workers_cancel_busy();
  3104. return;
  3105. }
  3106. for (;;) {
  3107. int started = preload_fill_jobs();
  3108. int done = 0;
  3109. int i;
  3110. for (i = 0; i < FETCH_WORKERS; i++) {
  3111. if (!fetch_workers[i].busy)
  3112. continue;
  3113. if (preload_finish_worker(&fetch_workers[i]))
  3114. done++;
  3115. if (batch + done >= 4)
  3116. break;
  3117. }
  3118. batch += (unsigned int)done;
  3119. if (batch >= 4)
  3120. return;
  3121. if (!started && !done)
  3122. break;
  3123. }
  3124. if (preload_active && preload_node >= doc.nnode &&
  3125. preload_active_jobs() == 0) {
  3126. preload_active = 0;
  3127. if (preload_pending)
  3128. preload_scroll = page_scroll.offset;
  3129. else
  3130. preload_pending = 0;
  3131. /* Keep the now idle helpers and their connections; a later
  3132. * navigation reuses them. They exit after ten idle seconds,
  3133. * and losing window focus stops them at once. */
  3134. set_status(post_status_text, post_status_error, post_status_ttl);
  3135. ngui_invalidate(&ui);
  3136. }
  3137. }
  3138. /* Set by navigate() when it turned a typed bare host into https://; the next
  3139. * load_page() consumes it and may retry over http. */
  3140. static int nav_https_upgraded;
  3141. /* Errors that mean "https is not served here" rather than "the site is
  3142. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  3143. static int https_fallback_error(int e)
  3144. {
  3145. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  3146. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  3147. e == UHTTP_ERR_RESET;
  3148. }
  3149. static void history_push(const char *url)
  3150. {
  3151. if (!url || !url[0])
  3152. return;
  3153. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  3154. s_eq(history[hist_pos], url))
  3155. return;
  3156. if (hist_len > 0 && hist_pos + 1 < hist_len)
  3157. hist_len = hist_pos + 1;
  3158. if (hist_len < BR_HISTORY) {
  3159. s_copy(history[hist_len], url, BR_URL_MAX);
  3160. hist_pos = hist_len;
  3161. hist_len++;
  3162. } else {
  3163. int i;
  3164. for (i = 1; i < BR_HISTORY; i++)
  3165. s_copy(history[i - 1], history[i], BR_URL_MAX);
  3166. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  3167. hist_pos = BR_HISTORY - 1;
  3168. }
  3169. }
  3170. static void load_page(const char *url, int local, int push)
  3171. {
  3172. unsigned char *body = 0;
  3173. unsigned int len = 0;
  3174. int truncated = 0;
  3175. struct img_info image_info;
  3176. char ctype[64];
  3177. char final[BR_URL_MAX];
  3178. char err[80];
  3179. const char *detail = 0;
  3180. const char *post = pending_post_len ? pending_post : 0;
  3181. unsigned int post_len = pending_post_len;
  3182. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  3183. int upgraded = nav_https_upgraded;
  3184. int retried = 0;
  3185. int rv;
  3186. nav_https_upgraded = 0;
  3187. final[0] = '\0';
  3188. pending_post_len = 0;
  3189. cancel_fetch = 0;
  3190. preload_active = 0;
  3191. preload_pending = 0;
  3192. fetch_workers_prepare_nav(url);
  3193. js_browser_stop();
  3194. js_last_status[0] = '\0';
  3195. js_last_error = 0;
  3196. heap_clear();
  3197. image_reset();
  3198. form_reset_state();
  3199. layout_valid = 0;
  3200. page_scroll.offset = 0;
  3201. page_scroll.dragging = 0;
  3202. page_title[0] = '\0';
  3203. page_loading = 1;
  3204. page_is_local = local;
  3205. s_copy(page_url, url, sizeof(page_url));
  3206. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3207. url_in.len = s_len(url_in.text);
  3208. url_in.cursor = url_in.len;
  3209. url_in.scroll = 0;
  3210. ngui_set_focus(&ui, 0);
  3211. if (final[0])
  3212. final[0] = '\0';
  3213. if (push)
  3214. history_push(url);
  3215. set_status("Loading...", 0, 0);
  3216. ngui_invalidate(&ui);
  3217. /* heap_clear() detaches the fonts, so attach them again before the
  3218. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  3219. if (heap_start() != 0) {
  3220. show_error("Out of memory", "Cannot allocate the page buffer");
  3221. return;
  3222. }
  3223. br_parse_plain(&doc, "", 0); /* blank while loading */
  3224. ngui_font_attach(&ui);
  3225. redraw_now();
  3226. browser_rules_alloc();
  3227. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  3228. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  3229. &truncated, post, post_len);
  3230. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  3231. fetch_last_error == UHTTP_ERR_DNS) {
  3232. /* A busy previous page can leave the receiver ring full just
  3233. * long enough to lose a DNS reply. Tear the old helpers down
  3234. * and try once more before giving up. */
  3235. retried = 1;
  3236. fetch_workers_stop_all();
  3237. u_sleep_ms(500);
  3238. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  3239. sizeof(ctype), final, sizeof(final), err,
  3240. sizeof(err), &truncated, post, post_len);
  3241. }
  3242. if (rv == FETCH_ABORT)
  3243. return;
  3244. /* Capture the page timing before CSS/script/image fetches overwrite the
  3245. * shared fetch_meta block. */
  3246. if (rv == 0 && !local) {
  3247. page_open_ms = fetch_meta.open_ms;
  3248. page_first_ms = fetch_meta.first_ms;
  3249. page_total_ms = fetch_meta.total_ms;
  3250. }
  3251. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  3252. https_fallback_error(fetch_last_error)) {
  3253. char http_url[BR_URL_MAX];
  3254. unsigned int n = 0;
  3255. s_append(http_url, &n, "http://", sizeof(http_url));
  3256. s_append(http_url, &n, url + 8, sizeof(http_url));
  3257. /* Replace the https entry instead of adding a second one. */
  3258. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  3259. s_eq(history[hist_pos], url))
  3260. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  3261. load_page(http_url, 0, 0);
  3262. return;
  3263. }
  3264. if (rv != 0) {
  3265. detail = err;
  3266. show_error("Cannot load this page", detail);
  3267. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3268. url_in.len = s_len(url_in.text);
  3269. url_in.cursor = url_in.len;
  3270. url_in.scroll = 0;
  3271. return;
  3272. }
  3273. if (!local)
  3274. origin_cache_learn(url, final[0] ? final : url);
  3275. page_is_local = local;
  3276. if (final[0]) {
  3277. s_copy(page_url, final, sizeof(page_url));
  3278. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3279. url_in.len = s_len(url_in.text);
  3280. url_in.cursor = url_in.len;
  3281. url_in.scroll = 0;
  3282. }
  3283. if (contains_ci(ctype, "text/plain")) {
  3284. br_parse_plain(&doc, (const char *)body, len);
  3285. } else if (contains_ci(ctype, "image/") ||
  3286. (!contains_ci(ctype, "text/html") &&
  3287. img_sniff(body, len, &image_info) == 0)) {
  3288. unsigned int node = br_parse_image_doc(&doc, page_url);
  3289. if (node)
  3290. decode_direct_image(body, len, node);
  3291. s_copy(page_title, "Image", sizeof(page_title));
  3292. } else {
  3293. br_set_viewport(ui.w);
  3294. br_parse(&doc, (const char *)body, len);
  3295. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  3296. sizeof(page_title));
  3297. if (load_stylesheets() == FETCH_ABORT)
  3298. return;
  3299. if (pending_action)
  3300. return;
  3301. }
  3302. preload_begin();
  3303. page_loading = 0;
  3304. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3305. url_in.len = s_len(url_in.text);
  3306. url_in.cursor = url_in.len;
  3307. url_in.scroll = 0;
  3308. ngui_set_focus(&ui, 0);
  3309. /* Paint the parsed page before fetching/running scripts. A slow
  3310. * remote <script src> then does not hide the page behind the loading
  3311. * screen; the fetch helper pumps this UI while it waits. */
  3312. set_status("Loading scripts...", 0, 0);
  3313. redraw_now();
  3314. /* Start one image download before the scripts. The other workers
  3315. * fetch the external script bodies in parallel, and the remaining
  3316. * images start as soon as the script phase ends. */
  3317. preload_max_jobs = 1;
  3318. preload_fill_jobs();
  3319. preload_wait = 0;
  3320. run_page_scripts();
  3321. preload_max_jobs = FETCH_WORKERS;
  3322. if (pending_action)
  3323. return;
  3324. post_status_text[0] = '\0';
  3325. post_status_error = 0;
  3326. post_status_ttl = 0;
  3327. if (js_last_status[0]) {
  3328. s_copy(post_status_text, js_last_status,
  3329. sizeof(post_status_text));
  3330. post_status_error = js_last_error;
  3331. post_status_ttl = 8000;
  3332. } else if (truncated) {
  3333. s_copy(post_status_text, "Page truncated at the buffer limit",
  3334. sizeof(post_status_text));
  3335. post_status_ttl = 6000;
  3336. } else if (doc.truncated) {
  3337. s_copy(post_status_text, "Page truncated by the parser",
  3338. sizeof(post_status_text));
  3339. post_status_ttl = 6000;
  3340. } else if (page_total_ms) {
  3341. unsigned int n = 0;
  3342. if (starts_with(page_url, "https://"))
  3343. s_append(post_status_text, &n,
  3344. "HTTPS (not verified), ",
  3345. sizeof(post_status_text));
  3346. else
  3347. s_append(post_status_text, &n, "Loaded in ",
  3348. sizeof(post_status_text));
  3349. s_append_dec(post_status_text, &n, page_total_ms,
  3350. sizeof(post_status_text));
  3351. s_append(post_status_text, &n, " ms (headers ",
  3352. sizeof(post_status_text));
  3353. s_append_dec(post_status_text, &n, page_open_ms,
  3354. sizeof(post_status_text));
  3355. s_append(post_status_text, &n, " ms", sizeof(post_status_text));
  3356. if (page_first_ms) {
  3357. s_append(post_status_text, &n, ", first byte ",
  3358. sizeof(post_status_text));
  3359. s_append_dec(post_status_text, &n, page_first_ms,
  3360. sizeof(post_status_text));
  3361. s_append(post_status_text, &n, " ms",
  3362. sizeof(post_status_text));
  3363. }
  3364. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  3365. post_status_ttl = 6000;
  3366. } else if (starts_with(page_url, "https://")) {
  3367. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  3368. sizeof(post_status_text));
  3369. post_status_ttl = 6000;
  3370. }
  3371. set_status(post_status_text, post_status_error, post_status_ttl);
  3372. ngui_invalidate(&ui);
  3373. }
  3374. static void load_home(int push)
  3375. {
  3376. pending_post_len = 0;
  3377. cancel_fetch = 0;
  3378. preload_active = 0;
  3379. preload_pending = 0;
  3380. js_browser_stop();
  3381. js_last_status[0] = '\0';
  3382. js_last_error = 0;
  3383. heap_clear();
  3384. image_reset();
  3385. form_reset_state();
  3386. layout_valid = 0;
  3387. page_scroll.offset = 0;
  3388. page_scroll.dragging = 0;
  3389. page_loading = 1;
  3390. page_is_local = 0;
  3391. s_copy(page_url, "about:home", sizeof(page_url));
  3392. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3393. url_in.len = s_len(url_in.text);
  3394. url_in.cursor = url_in.len;
  3395. url_in.scroll = 0;
  3396. ngui_set_focus(&ui, 0);
  3397. if (push)
  3398. history_push(page_url);
  3399. ngui_invalidate(&ui);
  3400. /* See load_page(): reattach the fonts before the first redraw. */
  3401. if (heap_start() != 0) {
  3402. show_error("Out of memory", "Cannot allocate the browser heap");
  3403. return;
  3404. }
  3405. br_parse_plain(&doc, "", 0);
  3406. ngui_font_attach(&ui);
  3407. redraw_now();
  3408. browser_rules_alloc();
  3409. {
  3410. static const char home[] =
  3411. "<html><head><title>NebOS Browser</title><style>"
  3412. "body { margin: 10px; color: #e4e6f0; }"
  3413. "h1 { color: #7fb0ff; }"
  3414. ".box { background-color: #262b3a; margin: 12px; "
  3415. "padding: 10px; }"
  3416. "a { color: #7fb0ff; }"
  3417. "pre { background-color: #32384a; }"
  3418. "</style></head><body>"
  3419. "<h1>NebOS Browser</h1>"
  3420. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  3421. "shared HTTP client and the image library.</p>"
  3422. "<div class=\"box\"><b>Try:</b>"
  3423. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  3424. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  3425. "<li><a href=\"/floppy1/JS.HTM\">/"
  3426. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  3427. "<li><a href=\"http://10.0.2.2:8000/\">"
  3428. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  3429. "<li><a href=\"https://example.com/\">"
  3430. "https://example.com/</a> (TLS, not verified)</li>"
  3431. "</ul></div>"
  3432. "<p>Type a URL in the bar above. Esc closes the "
  3433. "window, Ctrl+L focuses the address bar.</p>"
  3434. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  3435. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  3436. "</body></html>";
  3437. br_set_viewport(ui.w);
  3438. br_parse(&doc, home, sizeof(home) - 1);
  3439. br_parse_inline_css(&doc);
  3440. br_reset_styles(&doc);
  3441. s_copy(page_title, doc.title, sizeof(page_title));
  3442. }
  3443. post_status_text[0] = '\0';
  3444. post_status_error = 0;
  3445. post_status_ttl = 0;
  3446. page_loading = 0;
  3447. set_status("", 0, 0);
  3448. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3449. url_in.len = s_len(url_in.text);
  3450. url_in.cursor = url_in.len;
  3451. url_in.scroll = 0;
  3452. ngui_set_focus(&ui, 0);
  3453. ngui_invalidate(&ui);
  3454. }
  3455. /* Extensions the browser opens from the local filesystem. A dotted input
  3456. * with one of these still resolves relative to the cwd. */
  3457. static int local_file_ext(const char *s)
  3458. {
  3459. static const char *const exts[] = {
  3460. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  3461. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  3462. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  3463. "cfg", "conf", 0
  3464. };
  3465. unsigned int i = 0, start = 0, len = 0, e;
  3466. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  3467. s[i] != '#') {
  3468. if (s[i] == '.') {
  3469. start = i + 1;
  3470. len = 0;
  3471. } else if (start) {
  3472. len++;
  3473. }
  3474. i++;
  3475. }
  3476. if (!len)
  3477. return 0;
  3478. for (e = 0; exts[e]; e++) {
  3479. const char *x = exts[e];
  3480. unsigned int xn = s_len(x), k;
  3481. if (xn != len)
  3482. continue;
  3483. for (k = 0; k < len; k++) {
  3484. char a = s[start + k];
  3485. if (a >= 'A' && a <= 'Z')
  3486. a = (char)(a - 'A' + 'a');
  3487. if (a != x[k])
  3488. break;
  3489. }
  3490. if (k == len)
  3491. return 1;
  3492. }
  3493. return 0;
  3494. }
  3495. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  3496. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  3497. * Enter to the first network request. */
  3498. static int looks_like_host(const char *s)
  3499. {
  3500. unsigned int i = 0;
  3501. int dot = 0;
  3502. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  3503. s[i] != ':') {
  3504. char c = s[i];
  3505. if (c == '.') {
  3506. dot = 1;
  3507. } else if (!((c >= 'a' && c <= 'z') ||
  3508. (c >= 'A' && c <= 'Z') ||
  3509. (c >= '0' && c <= '9') ||
  3510. c == '-' || c == '_')) {
  3511. return 0;
  3512. }
  3513. i++;
  3514. }
  3515. return dot && i > 0 && !local_file_ext(s);
  3516. }
  3517. static void load_remote(const char *url, int push)
  3518. {
  3519. char canon[BR_URL_MAX];
  3520. s_copy(canon, url, sizeof(canon));
  3521. origin_cache_apply(canon, sizeof(canon));
  3522. load_page(canon, 0, push);
  3523. }
  3524. static void navigate(const char *input, int push)
  3525. {
  3526. char target[BR_URL_MAX];
  3527. char *t;
  3528. if (!input)
  3529. return;
  3530. s_copy(target, input, sizeof(target));
  3531. t = trim(target);
  3532. if (!t[0])
  3533. return;
  3534. if (s_eq(t, "about:home")) {
  3535. load_home(push);
  3536. return;
  3537. }
  3538. if (starts_with(t, "file://")) {
  3539. make_abs_local(t + 7, target, sizeof(target));
  3540. load_page(target, 1, push);
  3541. return;
  3542. }
  3543. if (is_http(t)) {
  3544. load_remote(t, push);
  3545. return;
  3546. }
  3547. if (t[0] == '/') {
  3548. make_abs_local(t, target, sizeof(target));
  3549. load_page(target, 1, push);
  3550. return;
  3551. }
  3552. if (!looks_like_host(t)) {
  3553. struct sys_stat st;
  3554. if (u_stat(t, &st) == 0 && !st.is_dir) {
  3555. make_abs_local(t, target, sizeof(target));
  3556. load_page(target, 1, push);
  3557. return;
  3558. }
  3559. }
  3560. {
  3561. /* A typed bare host tries https first: nearly every site
  3562. * redirects http -> https anyway, and that hop costs a whole
  3563. * extra connection. load_page() falls back to http when the
  3564. * https connection itself fails. */
  3565. char with_scheme[BR_URL_MAX];
  3566. unsigned int n = 0;
  3567. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  3568. s_append(with_scheme, &n, t, sizeof(with_scheme));
  3569. nav_https_upgraded = 1;
  3570. load_remote(with_scheme, push);
  3571. }
  3572. }
  3573. /* ---- layout ---- */
  3574. static struct ufont_face *style_face(const struct br_style *st)
  3575. {
  3576. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  3577. return font_faces[st->font_face - 1];
  3578. return 0;
  3579. }
  3580. static struct ufont_face *run_face(const struct lay_run *r)
  3581. {
  3582. if (r->font_face && r->font_face <= BR_MAX_FACES)
  3583. return font_faces[r->font_face - 1];
  3584. return 0;
  3585. }
  3586. static unsigned int face_text_width(struct ngui *gui,
  3587. const struct br_style *st,
  3588. const char *s, unsigned int n)
  3589. {
  3590. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  3591. st->bold, st->italic, st->mono);
  3592. }
  3593. static int face_line_height(struct ngui *gui, const struct br_style *st)
  3594. {
  3595. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  3596. st->mono);
  3597. }
  3598. static unsigned int run_text_width(struct ngui *gui,
  3599. const struct lay_run *r,
  3600. const char *s, unsigned int n)
  3601. {
  3602. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  3603. r->bold, r->italic, r->mono);
  3604. }
  3605. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  3606. {
  3607. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  3608. r->mono);
  3609. }
  3610. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  3611. {
  3612. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  3613. }
  3614. static struct br_style base_style(void)
  3615. {
  3616. struct br_style s = { 0 };
  3617. s.color = ui.theme.text;
  3618. s.bg = ui.theme.bg;
  3619. s.has_bg = 0;
  3620. for (int i = 0; i < 4; i++) {
  3621. s.border_c[i] = 0;
  3622. s.border_w[i] = 0;
  3623. s.border_s[i] = BR_BORDER_SOLID;
  3624. }
  3625. s.font_px = 16;
  3626. s.bold = 0;
  3627. s.italic = 0;
  3628. s.mono = 0;
  3629. s.underline = 0;
  3630. s.strike = 0;
  3631. s.overline = 0;
  3632. s.align = BR_ALIGN_LEFT;
  3633. s.display = BR_DISPLAY_BLOCK;
  3634. s.no_bullet = 0;
  3635. s.list_style = BR_LIST_AUTO;
  3636. s.uppercase = 0;
  3637. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  3638. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  3639. s.width = s.max_width = s.min_width = 0;
  3640. s.height = s.min_height = s.max_height = 0;
  3641. s.box_sizing = 0;
  3642. s.ml_auto = s.mr_auto = 0;
  3643. s.line_h_pct = 0;
  3644. s.line_h_px = 0;
  3645. s.mt = s.mb = s.ml = s.mr = 0;
  3646. s.pt = s.pb = s.pl = s.pr = 0;
  3647. return s;
  3648. }
  3649. /* Resolve a margin/padding raw value. Percentages use the containing
  3650. * block width for all four sides, as CSS specifies. */
  3651. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  3652. {
  3653. if (unit == 1)
  3654. return base * v / 10000;
  3655. if (unit == 2)
  3656. return st->font_px * v / 100;
  3657. if (unit == 3)
  3658. return (int)br_root_font_px() * v / 100;
  3659. if (unit == 4)
  3660. return 0;
  3661. return v;
  3662. }
  3663. static int mp_px(const struct br_style *st, int side, int base)
  3664. {
  3665. int raw;
  3666. switch (side) {
  3667. case 0: raw = st->mt; break;
  3668. case 1: raw = st->mr; break;
  3669. case 2: raw = st->mb; break;
  3670. case 3: raw = st->ml; break;
  3671. case 4: raw = st->pt; break;
  3672. case 5: raw = st->pr; break;
  3673. case 6: raw = st->pb; break;
  3674. default: raw = st->pl; break;
  3675. }
  3676. if (st->mp_unit[side] == 5)
  3677. return base * raw / 100 + st->mp_calc_px[side];
  3678. return css_mp_px(st, raw, st->mp_unit[side], base);
  3679. }
  3680. static int style_width_px(const struct br_style *st, int base)
  3681. {
  3682. if (st->width_kind == 1)
  3683. return st->width;
  3684. if (st->width_kind == 2)
  3685. return base * (int)st->width / 100;
  3686. if (st->width_kind == 3)
  3687. return base * st->width_calc_pct / 100 + st->width_calc_px;
  3688. return 0;
  3689. }
  3690. static int style_height_px(const struct br_style *st, int base)
  3691. {
  3692. if (st->height_kind == 1)
  3693. return st->height;
  3694. if (st->height_kind == 2)
  3695. return base * (int)st->height / 100;
  3696. if (st->height_kind == 3)
  3697. return base * st->height_calc_pct / 100 + st->height_calc_px;
  3698. return 0;
  3699. }
  3700. static int css_size(unsigned char kind, int val, int base)
  3701. {
  3702. if (kind == 1)
  3703. return val;
  3704. if (kind == 2)
  3705. return base * val / 100;
  3706. return -1;
  3707. }
  3708. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  3709. int thick, int horizontal, unsigned short color,
  3710. unsigned char style)
  3711. {
  3712. int pos;
  3713. if (len <= 0 || thick <= 0)
  3714. return;
  3715. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  3716. if (horizontal)
  3717. ngui_fill_rect(ui, (struct ngui_rect){
  3718. x, y, len, thick}, color);
  3719. else
  3720. ngui_fill_rect(ui, (struct ngui_rect){
  3721. x, y, thick, len}, color);
  3722. return;
  3723. }
  3724. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  3725. int seg = len - pos;
  3726. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  3727. seg = style == BR_BORDER_DASHED ? 4 : 2;
  3728. if (horizontal)
  3729. ngui_fill_rect(ui, (struct ngui_rect){
  3730. x + pos, y, seg, thick}, color);
  3731. else
  3732. ngui_fill_rect(ui, (struct ngui_rect){
  3733. x, y + pos, thick, seg}, color);
  3734. }
  3735. }
  3736. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  3737. const struct br_style *st)
  3738. {
  3739. int top = st->border_w[0], right = st->border_w[1];
  3740. int bottom = st->border_w[2], left = st->border_w[3];
  3741. if (r.w <= 0 || r.h <= 0)
  3742. return;
  3743. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  3744. int i;
  3745. for (i = 0; i < 4; i++)
  3746. if (st->border_w[i]) {
  3747. ngui_fill_rect(ui, r, st->border_c[i]);
  3748. break;
  3749. }
  3750. return;
  3751. }
  3752. if (top)
  3753. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  3754. st->border_c[0], st->border_s[0]);
  3755. if (bottom)
  3756. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  3757. st->border_c[2], st->border_s[2]);
  3758. if (left)
  3759. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  3760. left, 0, st->border_c[3], st->border_s[3]);
  3761. if (right)
  3762. draw_border_side(ui, r.x + r.w - right, r.y + top,
  3763. r.h - top - bottom, right, 0,
  3764. st->border_c[1], st->border_s[1]);
  3765. }
  3766. static void transform_origin(const struct br_style *st, int w, int h,
  3767. int *ox, int *oy)
  3768. {
  3769. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  3770. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  3771. }
  3772. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  3773. unsigned int a)
  3774. {
  3775. unsigned int dr, dg, db, sr, sg, sb;
  3776. if (a >= 255)
  3777. return s;
  3778. dr = (d >> 11) & 31;
  3779. dg = (d >> 5) & 63;
  3780. db = d & 31;
  3781. sr = (s >> 11) & 31;
  3782. sg = (s >> 5) & 63;
  3783. sb = s & 31;
  3784. dr = (dr * (255 - a) + sr * a) / 255;
  3785. dg = (dg * (255 - a) + sg * a) / 255;
  3786. db = (db * (255 - a) + sb * a) / 255;
  3787. return (unsigned short)((dr << 11) | (dg << 5) | db);
  3788. }
  3789. /* Paint a solid box through scale()/rotate() around transform-origin. This
  3790. * transforms the element's own background box; text and descendants keep
  3791. * their layout (documented approximation). */
  3792. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  3793. unsigned short color,
  3794. const struct br_style *st)
  3795. {
  3796. double sx = st->scale_x / 100.0;
  3797. double sy = st->scale_y / 100.0;
  3798. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  3799. double c = cos(th), sn = sin(th);
  3800. int ox, oy, minx, miny, maxx, maxy, x, y;
  3801. double ax, ay;
  3802. double px[4], py[4];
  3803. int cx1, cy1, cx2, cy2, i;
  3804. if (sx == 0)
  3805. sx = 0.01;
  3806. if (sy == 0)
  3807. sy = 0.01;
  3808. transform_origin(st, box.w, box.h, &ox, &oy);
  3809. ax = box.x + ox;
  3810. ay = box.y + oy;
  3811. px[0] = -ox; py[0] = -oy;
  3812. px[1] = box.w - ox; py[1] = -oy;
  3813. px[2] = box.w - ox; py[2] = box.h - oy;
  3814. px[3] = -ox; py[3] = box.h - oy;
  3815. minx = miny = 1000000;
  3816. maxx = maxy = -1000000;
  3817. for (i = 0; i < 4; i++) {
  3818. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  3819. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  3820. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  3821. if (dx < minx) minx = dx;
  3822. if (dx > maxx) maxx = dx;
  3823. if (dy < miny) miny = dy;
  3824. if (dy > maxy) maxy = dy;
  3825. }
  3826. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  3827. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  3828. cx2 = page_rect.x + page_rect.w - 12;
  3829. cy2 = page_rect.y + page_rect.h;
  3830. if (cx2 > gui->w) cx2 = gui->w;
  3831. if (cy2 > gui->h) cy2 = gui->h;
  3832. if (minx < cx1) minx = cx1;
  3833. if (miny < cy1) miny = cy1;
  3834. if (maxx > cx2 - 1) maxx = cx2 - 1;
  3835. if (maxy > cy2 - 1) maxy = cy2 - 1;
  3836. for (y = miny; y <= maxy; y++) {
  3837. for (x = minx; x <= maxx; x++) {
  3838. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  3839. double rx = dx * c + dy * sn;
  3840. double ry = -dx * sn + dy * c;
  3841. double bx = rx / sx + ox;
  3842. double by = ry / sy + oy;
  3843. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  3844. gui->px[y * gui->w + x] = color;
  3845. }
  3846. }
  3847. }
  3848. static void draw_image_transformed(struct ngui *gui,
  3849. const struct img_image *im,
  3850. int x, int y, int w, int h,
  3851. int sx100, int sy100, int rot100,
  3852. int origin_x, int origin_y,
  3853. int origin_x_kind, int origin_y_kind)
  3854. {
  3855. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  3856. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  3857. double c = cos(th), sn = sin(th);
  3858. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  3859. double ax, ay;
  3860. double bx[4], by[4];
  3861. int cx1, cy1, cx2, cy2;
  3862. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  3863. return;
  3864. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  3865. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  3866. ax = x + ox;
  3867. ay = y + oy;
  3868. bx[0] = -ox; by[0] = -oy;
  3869. bx[1] = w - ox; by[1] = -oy;
  3870. bx[2] = w - ox; by[2] = h - oy;
  3871. bx[3] = -ox; by[3] = h - oy;
  3872. minx = miny = 1000000;
  3873. maxx = maxy = -1000000;
  3874. for (i = 0; i < 4; i++) {
  3875. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  3876. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  3877. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  3878. if (dx < minx) minx = dx;
  3879. if (dx > maxx) maxx = dx;
  3880. if (dy < miny) miny = dy;
  3881. if (dy > maxy) maxy = dy;
  3882. }
  3883. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  3884. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  3885. cx2 = page_rect.x + page_rect.w - 12;
  3886. cy2 = page_rect.y + page_rect.h;
  3887. if (cx2 > gui->w) cx2 = gui->w;
  3888. if (cy2 > gui->h) cy2 = gui->h;
  3889. if (minx < cx1) minx = cx1;
  3890. if (miny < cy1) miny = cy1;
  3891. if (maxx > cx2 - 1) maxx = cx2 - 1;
  3892. if (maxy > cy2 - 1) maxy = cy2 - 1;
  3893. for (py = miny; py <= maxy; py++) {
  3894. for (px = minx; px <= maxx; px++) {
  3895. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  3896. double rx = dx * c + dy * sn;
  3897. double ry = -dx * sn + dy * c;
  3898. double fx = rx / sx + ox;
  3899. double fy = ry / sy + oy;
  3900. int ix, iy;
  3901. unsigned int si, a;
  3902. unsigned short src;
  3903. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  3904. continue;
  3905. ix = (int)(fx * (double)im->w / w);
  3906. iy = (int)(fy * (double)im->h / h);
  3907. if (ix < 0 || ix >= (int)im->w ||
  3908. iy < 0 || iy >= (int)im->h)
  3909. continue;
  3910. si = (unsigned int)iy * im->w + (unsigned int)ix;
  3911. src = im->px[si];
  3912. a = im->alpha ? im->alpha[si] : 255;
  3913. gui->px[py * gui->w + px] =
  3914. a >= 255 ? src :
  3915. blend_rgb565(gui->px[py * gui->w + px],
  3916. src, a);
  3917. }
  3918. }
  3919. }
  3920. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  3921. unsigned int node, const struct br_style *st)
  3922. {
  3923. struct br_image *bi;
  3924. struct img_blit b;
  3925. int tw, th, x, y, rep_x, rep_y, posx, posy;
  3926. unsigned int scale = 65536;
  3927. int legacy, tiles = 0, rows = 0;
  3928. int cx1, cy1, cx2, cy2;
  3929. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  3930. return;
  3931. if (doc.nodes[node].bg_img_index < 0 ||
  3932. doc.nodes[node].bg_img_index >= image_count)
  3933. return;
  3934. bi = &images[doc.nodes[node].bg_img_index];
  3935. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  3936. return;
  3937. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  3938. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  3939. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  3940. if (legacy) {
  3941. scale = ((unsigned int)box.w << 16) / bi->img.w;
  3942. tw = box.w;
  3943. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  3944. x = box.x;
  3945. y = box.y;
  3946. rep_x = rep_y = 0;
  3947. } else {
  3948. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  3949. unsigned int sx = ((unsigned int)box.w << 16) /
  3950. bi->img.w;
  3951. unsigned int sy = ((unsigned int)box.h << 16) /
  3952. bi->img.h;
  3953. scale = st->bg_size_kind == 3 ?
  3954. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  3955. } else if (st->bg_size_kind == 1 ||
  3956. st->bg_size_kind == 2) {
  3957. int w = st->bg_size_w;
  3958. int h = st->bg_size_h;
  3959. if (st->bg_size_kind == 2) {
  3960. if (w)
  3961. w = box.w * w / 100;
  3962. if (h)
  3963. h = box.h * h / 100;
  3964. }
  3965. if (w)
  3966. scale = ((unsigned int)w << 16) / bi->img.w;
  3967. else if (h)
  3968. scale = ((unsigned int)h << 16) / bi->img.h;
  3969. }
  3970. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  3971. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  3972. if (tw < 1)
  3973. tw = 1;
  3974. if (th < 1)
  3975. th = 1;
  3976. posx = st->bg_pos_x_kind == 1 ?
  3977. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  3978. posy = st->bg_pos_y_kind == 1 ?
  3979. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  3980. x = box.x + posx;
  3981. y = box.y + posy;
  3982. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  3983. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  3984. if (rep_x) {
  3985. int m = (x - box.x) % tw;
  3986. if (m > 0)
  3987. m -= tw;
  3988. x = box.x + m;
  3989. }
  3990. if (rep_y) {
  3991. int m = (y - box.y) % th;
  3992. if (m > 0)
  3993. m -= th;
  3994. y = box.y + m;
  3995. }
  3996. }
  3997. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  3998. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  3999. cx2 = box.x + box.w;
  4000. cy2 = box.y + box.h;
  4001. if (cx2 > page_rect.x + page_rect.w - 12)
  4002. cx2 = page_rect.x + page_rect.w - 12;
  4003. if (cy2 > page_rect.y + page_rect.h)
  4004. cy2 = page_rect.y + page_rect.h;
  4005. if (cx1 >= cx2 || cy1 >= cy2)
  4006. return;
  4007. b.dst = l->ui->px;
  4008. b.dst_w = l->ui->w;
  4009. b.dst_h = l->ui->h;
  4010. b.clip_x = cx1;
  4011. b.clip_y = cy1;
  4012. b.clip_w = cx2 - cx1;
  4013. b.clip_h = cy2 - cy1;
  4014. b.scale = scale;
  4015. b.bg = ui.theme.bg;
  4016. b.bg2 = ui.theme.bg;
  4017. b.flags = IMG_BLIT_OVER_DST;
  4018. {
  4019. int row_x = x;
  4020. for (;;) {
  4021. for (;;) {
  4022. b.x = x;
  4023. b.y = y;
  4024. img_draw(&bi->img, &b);
  4025. if (!rep_x || ++tiles > 512)
  4026. break;
  4027. x += tw;
  4028. if (x >= box.x + box.w)
  4029. break;
  4030. }
  4031. if (!rep_y || ++rows > 64)
  4032. break;
  4033. y += th;
  4034. if (y >= box.y + box.h)
  4035. break;
  4036. x = row_x;
  4037. }
  4038. }
  4039. }
  4040. static int run_width(const struct lay_run *r)
  4041. {
  4042. if (r->img >= 0)
  4043. return r->iw;
  4044. if (r->img == -2)
  4045. return r->iw;
  4046. return (int)r->w;
  4047. }
  4048. static void start_line(struct lay *l, const struct br_style *st)
  4049. {
  4050. (void)st;
  4051. if (l->nruns == 0) {
  4052. l->line_y = l->y;
  4053. l->line_h = 0;
  4054. }
  4055. l->line_left = l->left;
  4056. l->line_right = l->right;
  4057. if (l->float_active && l->line_y < l->float_bottom) {
  4058. if (l->float_left > l->line_left)
  4059. l->line_left = l->float_left;
  4060. if (l->float_right < l->line_right)
  4061. l->line_right = l->float_right;
  4062. }
  4063. if (l->line_right < l->line_left + 8)
  4064. l->line_right = l->line_left + 8;
  4065. l->line_x = l->line_left;
  4066. l->run_x = l->line_left;
  4067. }
  4068. static void flush_line(struct lay *l)
  4069. {
  4070. int total, x, i, vis;
  4071. if (!l->nruns && l->line_x == l->line_left) {
  4072. l->line_h = 0;
  4073. return;
  4074. }
  4075. total = l->line_x - l->line_left;
  4076. x = l->line_left;
  4077. vis = 1;
  4078. if (l->draw) {
  4079. int lh = l->line_h ? l->line_h : 16;
  4080. vis = l->line_y + lh >= page_rect.y &&
  4081. l->line_y <= page_rect.y + page_rect.h;
  4082. }
  4083. if (l->align == BR_ALIGN_CENTER)
  4084. x += (l->line_right - l->line_left - total) / 2;
  4085. else if (l->align == BR_ALIGN_RIGHT)
  4086. x = l->line_right - total;
  4087. if (x < l->line_left)
  4088. x = l->line_left;
  4089. for (i = 0; i < l->nruns; i++) {
  4090. struct lay_run *r = &l->runs[i];
  4091. int w = run_width(r);
  4092. int ry = l->line_y + r->dy;
  4093. x += r->gap;
  4094. if (l->draw && vis) {
  4095. if (r->form) {
  4096. unsigned int node = r->form - 1;
  4097. struct form_state *fs = form_get(node, 1);
  4098. int hh = r->ih ? r->ih : 20;
  4099. int focused = form_focus == node;
  4100. int disabled = r->form_disabled;
  4101. unsigned short bg = l->ui->theme.panel_alt;
  4102. unsigned short fg = disabled ? 0x8410 : r->color;
  4103. struct ngui_rect box = {x, ry, w, hh};
  4104. if (r->form_kind == FORM_CHECKBOX ||
  4105. r->form_kind == FORM_RADIO) {
  4106. ngui_fill_rect(l->ui, box, bg);
  4107. ngui_frame(l->ui, box,
  4108. focused ? l->ui->theme.accent :
  4109. l->ui->theme.border);
  4110. if (fs && fs->checked) {
  4111. struct ngui_rect dot = {
  4112. x + 4, ry + 4,
  4113. w > 8 ? w - 8 : 1,
  4114. hh > 8 ? hh - 8 : 1
  4115. };
  4116. if (r->form_kind == FORM_RADIO)
  4117. ngui_fill_round_rect(
  4118. l->ui, dot, 4,
  4119. 4, 4, 4,
  4120. l->ui->theme.accent);
  4121. else
  4122. ngui_fill_rect(l->ui,
  4123. dot,
  4124. l->ui->theme.accent);
  4125. }
  4126. } else {
  4127. ngui_fill_rect(l->ui, box, bg);
  4128. ngui_frame(l->ui, box,
  4129. focused ? l->ui->theme.accent :
  4130. l->ui->theme.border);
  4131. ngui_text_px_face(l->ui, run_face(r),
  4132. x + 6, ry + 2,
  4133. r->lit, s_len(r->lit),
  4134. fg, r->font_px, r->bold,
  4135. r->italic, r->mono);
  4136. if (focused && fs &&
  4137. (r->form_kind == FORM_TEXT ||
  4138. r->form_kind == FORM_PASSWORD ||
  4139. r->form_kind == FORM_TEXTAREA)) {
  4140. int cw = 0;
  4141. if (fs->len && fs->caret)
  4142. cw = (int)run_text_width(
  4143. l->ui, r, r->lit,
  4144. fs->caret < fs->len ?
  4145. fs->caret : fs->len);
  4146. ngui_fill_rect(l->ui,
  4147. (struct ngui_rect){
  4148. x + 6 + cw,
  4149. ry + 4, 1,
  4150. hh > 8 ? hh - 8 : 1
  4151. },
  4152. l->ui->theme.accent);
  4153. }
  4154. if (r->form_kind == FORM_SELECT) {
  4155. ngui_text_px(l->ui, x + w - 12,
  4156. ry + 2, "v", 1, fg,
  4157. r->font_px, 0, 0, 0);
  4158. }
  4159. }
  4160. } else if (r->img == -2) {
  4161. int hh = r->ih ? r->ih : 20;
  4162. ngui_fill_rect(l->ui,
  4163. (struct ngui_rect){x, ry, w, hh},
  4164. l->ui->theme.panel_alt);
  4165. ngui_frame(l->ui,
  4166. (struct ngui_rect){x, ry, w, hh},
  4167. l->ui->theme.border);
  4168. ngui_text_px_face(l->ui, run_face(r),
  4169. x + 6, ry + 2, r->lit,
  4170. s_len(r->lit), r->color,
  4171. r->font_px, r->bold, r->italic,
  4172. r->mono);
  4173. } else if (r->img >= 0) {
  4174. struct br_image *bi = &images[r->img];
  4175. if (bi->state == 1 && r->transform_scale) {
  4176. draw_image_transformed(l->ui, &bi->img,
  4177. x, ry, r->iw, r->ih,
  4178. r->scale_x, r->scale_y,
  4179. r->rotate_x100, r->origin_x,
  4180. r->origin_y, r->origin_x_kind,
  4181. r->origin_y_kind);
  4182. } else if (bi->state == 1) {
  4183. struct img_blit b;
  4184. b.dst = l->ui->px;
  4185. b.dst_w = l->ui->w;
  4186. b.dst_h = l->ui->h;
  4187. b.clip_x = page_rect.x;
  4188. b.clip_y = page_rect.y;
  4189. b.clip_w = page_rect.w - 12;
  4190. b.clip_h = page_rect.h;
  4191. b.x = x;
  4192. b.y = ry;
  4193. b.scale = ((unsigned int)r->iw << 16) /
  4194. bi->img.w;
  4195. b.bg = ui.theme.bg;
  4196. b.bg2 = ui.theme.bg;
  4197. b.flags = IMG_BLIT_OVER_DST;
  4198. img_draw(&bi->img, &b);
  4199. }
  4200. } else {
  4201. const char *s = r->has_lit ? r->lit :
  4202. doc.text + r->off;
  4203. unsigned int n = r->has_lit ? s_len(r->lit) :
  4204. r->len;
  4205. ngui_text_px_face(l->ui, run_face(r), x, ry,
  4206. s, n, r->color, r->font_px,
  4207. r->bold, r->italic, r->mono);
  4208. if (r->underline)
  4209. ngui_fill_rect(l->ui,
  4210. (struct ngui_rect){x,
  4211. ry + run_ascent(l->ui, r) + 2,
  4212. w, 1}, r->color);
  4213. if (r->strike)
  4214. ngui_fill_rect(l->ui,
  4215. (struct ngui_rect){x,
  4216. ry + run_ascent(l->ui, r) -
  4217. (r->font_px > 3 ?
  4218. r->font_px / 3 : 1),
  4219. w, 1}, r->color);
  4220. if (r->overline)
  4221. ngui_fill_rect(l->ui,
  4222. (struct ngui_rect){x, ry,
  4223. w, 1}, r->color);
  4224. }
  4225. if (r->form || r->href) {
  4226. if (nhits < HIT_MAX) {
  4227. struct hit *h = &hits[nhits];
  4228. unsigned int target = r->form ?
  4229. r->form - 1 : r->href;
  4230. int hh = (r->form || r->img >= 0) ?
  4231. r->ih :
  4232. run_line_height(l->ui, r);
  4233. int merge = nhits > 0 &&
  4234. hits[nhits - 1].node == target &&
  4235. hits[nhits - 1].y == ry &&
  4236. hits[nhits - 1].h == hh &&
  4237. x <= hits[nhits - 1].x +
  4238. hits[nhits - 1].w + 2;
  4239. if (merge) {
  4240. struct hit *p = &hits[nhits - 1];
  4241. int end = x + w;
  4242. if (end > p->x + p->w)
  4243. p->w = end - p->x;
  4244. } else {
  4245. h->x = x;
  4246. h->y = ry;
  4247. h->w = w;
  4248. h->h = hh;
  4249. h->node = (unsigned short)target;
  4250. nhits++;
  4251. }
  4252. }
  4253. }
  4254. }
  4255. x += w;
  4256. }
  4257. l->y += l->line_h + 2;
  4258. if (l->float_active && l->y >= l->float_bottom)
  4259. l->float_active = 0;
  4260. l->nruns = 0;
  4261. l->line_x = l->left;
  4262. l->run_x = l->left;
  4263. l->line_left = l->left;
  4264. l->line_right = l->right;
  4265. l->line_h = 0;
  4266. l->space_pending = 0;
  4267. }
  4268. static void add_run(struct lay *l, unsigned short off, unsigned short len,
  4269. const struct br_style *st, unsigned short href,
  4270. const char *lit)
  4271. {
  4272. unsigned int n = lit ? s_len(lit) : len;
  4273. const char *tp = lit ? lit : doc.text + off;
  4274. int w = (int)face_text_width(l->ui, st, tp, n);
  4275. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  4276. flush_line(l);
  4277. if (l->nruns == 0) {
  4278. l->line_y = l->y;
  4279. l->line_h = 0;
  4280. start_line(l, st);
  4281. }
  4282. {
  4283. struct lay_run *r = &l->runs[l->nruns++];
  4284. int gap = l->line_x - l->run_x;
  4285. if (gap < 0)
  4286. gap = 0;
  4287. r->gap = (unsigned short)gap;
  4288. r->off = off;
  4289. r->len = len;
  4290. r->color = st->color;
  4291. r->href = href;
  4292. r->dy = 0;
  4293. r->has_lit = 0;
  4294. r->form = 0;
  4295. r->form_kind = 0;
  4296. r->form_disabled = 0;
  4297. r->lit[0] = '\0';
  4298. if (lit && lit[0]) {
  4299. unsigned int i;
  4300. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  4301. r->lit[i] = lit[i];
  4302. r->lit[i] = '\0';
  4303. r->has_lit = 1;
  4304. }
  4305. r->img = -1;
  4306. r->iw = r->ih = 0;
  4307. r->font_px = st->font_px;
  4308. r->bold = st->bold;
  4309. r->italic = st->italic;
  4310. r->mono = st->mono;
  4311. r->font_face = st->font_face;
  4312. /* A control with its own background is a button, not body copy;
  4313. * an inherited link underline would strike through the fill. */
  4314. r->underline = st->underline && !st->has_bg;
  4315. r->strike = st->strike && !st->has_bg;
  4316. r->overline = st->overline && !st->has_bg;
  4317. r->w = (unsigned short)w;
  4318. if (r->has_lit)
  4319. r->w = (unsigned short)run_text_width(
  4320. l->ui, r, r->lit, s_len(r->lit));
  4321. w = r->w;
  4322. }
  4323. l->line_x += w;
  4324. l->run_x = l->line_x;
  4325. {
  4326. int lh = face_line_height(l->ui, st);
  4327. if (st->line_h_px)
  4328. lh = st->line_h_px;
  4329. else if (st->line_h_pct)
  4330. lh = st->font_px * st->line_h_pct / 100;
  4331. if (lh < face_line_height(l->ui, st))
  4332. lh = face_line_height(l->ui, st);
  4333. if (l->line_h < lh)
  4334. l->line_h = lh;
  4335. }
  4336. }
  4337. static void add_image_run(struct lay *l, unsigned int node,
  4338. const struct br_style *st, unsigned short href)
  4339. {
  4340. struct br_image *bi = 0;
  4341. int idx = doc.nodes[node].img_index;
  4342. int dw, dh, maxw;
  4343. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  4344. bi = &images[idx];
  4345. if (l->nruns == 0)
  4346. start_line(l, st);
  4347. if (l->space_pending &&
  4348. (l->nruns > 0 || l->line_x > l->line_left)) {
  4349. int sp = (int)face_text_width(l->ui, st, " ", 1);
  4350. if (l->line_x + sp <= l->line_right)
  4351. l->line_x += sp;
  4352. }
  4353. l->space_pending = 0;
  4354. if (!bi) {
  4355. const char *alt = br_alt(&doc, node);
  4356. struct br_style gs = *st;
  4357. char tmp[96];
  4358. unsigned int n = 0;
  4359. int w;
  4360. gs.color = BR_GRAY;
  4361. gs.underline = 0;
  4362. s_append(tmp, &n, "[", sizeof(tmp));
  4363. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  4364. s_append(tmp, &n, "]", sizeof(tmp));
  4365. w = (int)face_text_width(l->ui, &gs, tmp, n);
  4366. if (l->line_x + w > l->line_right &&
  4367. (l->nruns > 0 || l->line_x > l->line_left))
  4368. flush_line(l);
  4369. add_run(l, 0, 0, &gs, href, tmp);
  4370. if (!l->draw) {
  4371. int t = l->line_y < 0 ? 0 : l->line_y;
  4372. int hh = face_line_height(l->ui, &gs);
  4373. if (t > 65535)
  4374. t = 65535;
  4375. if (hh > 65535)
  4376. hh = 65535;
  4377. img_top[node] = (unsigned short)t;
  4378. img_h[node] = (unsigned short)hh;
  4379. }
  4380. return;
  4381. }
  4382. maxw = l->line_right - l->line_left;
  4383. if (maxw < 8)
  4384. maxw = 8;
  4385. {
  4386. int iw = bi->native_w, ih = bi->native_h;
  4387. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  4388. if (iw <= 0 || ih <= 0) {
  4389. iw = (int)bi->img.w;
  4390. ih = (int)bi->img.h;
  4391. }
  4392. dw = iw;
  4393. dh = ih;
  4394. if (doc.nodes[node].width_attr) {
  4395. int want = doc.nodes[node].width_attr;
  4396. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  4397. have_w = 1;
  4398. }
  4399. if (doc.nodes[node].height_attr) {
  4400. int want = doc.nodes[node].height_attr;
  4401. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  4402. have_h = 1;
  4403. }
  4404. if (have_w && !have_h)
  4405. dh = ih ? ih * dw / iw : 0;
  4406. if (have_h && !have_w)
  4407. dw = iw ? iw * dh / ih : 0;
  4408. if (st->width_kind) {
  4409. css_w = 1;
  4410. if (st->width_kind == 3)
  4411. dw = maxw * st->width_calc_pct / 100 +
  4412. st->width_calc_px;
  4413. else
  4414. dw = st->width_kind == 2 ?
  4415. maxw * (int)st->width / 100 :
  4416. (int)st->width;
  4417. }
  4418. if (st->height_kind) {
  4419. css_h = 1;
  4420. if (st->height_kind == 3)
  4421. dh = maxw * st->height_calc_pct / 100 +
  4422. st->height_calc_px;
  4423. else
  4424. dh = st->height_kind == 2 ?
  4425. maxw * (int)st->height / 100 :
  4426. (int)st->height;
  4427. }
  4428. if (css_w && !css_h)
  4429. dh = ih ? ih * dw / iw : 0;
  4430. if (css_h && !css_w)
  4431. dw = iw ? iw * dh / ih : 0;
  4432. if (st->max_width_kind) {
  4433. int mw = st->max_width_kind == 3 ?
  4434. maxw * st->max_width_calc_pct / 100 +
  4435. st->max_width_calc_px :
  4436. st->max_width_kind == 2 ?
  4437. maxw * (int)st->max_width / 100 :
  4438. (int)st->max_width;
  4439. if (mw > 0 && dw > mw) {
  4440. dh = iw ? ih * mw / iw : 0;
  4441. dw = mw;
  4442. }
  4443. }
  4444. }
  4445. if (dw < 8)
  4446. dw = 8;
  4447. if (dh < 8)
  4448. dh = 8;
  4449. if (dw > maxw) {
  4450. dh = dw ? dh * maxw / dw : dh;
  4451. dw = maxw;
  4452. }
  4453. if (!l->draw) {
  4454. int t = l->line_y < 0 ? 0 : l->line_y;
  4455. if (t > 65535)
  4456. t = 65535;
  4457. if (dh > 65535)
  4458. dh = 65535;
  4459. img_top[node] = (unsigned short)t;
  4460. img_h[node] = (unsigned short)dh;
  4461. }
  4462. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  4463. l->line_x > l->line_left))
  4464. flush_line(l);
  4465. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  4466. flush_line(l);
  4467. if (l->nruns == 0) {
  4468. l->line_y = l->y;
  4469. l->line_h = 0;
  4470. start_line(l, st);
  4471. }
  4472. {
  4473. struct lay_run *r = &l->runs[l->nruns++];
  4474. int gap = l->line_x - l->run_x;
  4475. if (gap < 0)
  4476. gap = 0;
  4477. r->gap = (unsigned short)gap;
  4478. r->off = 0;
  4479. r->len = 0;
  4480. r->color = 0;
  4481. r->href = href;
  4482. r->form = 0;
  4483. r->form_kind = 0;
  4484. r->form_disabled = 0;
  4485. /* Inline replaced elements honour their vertical margins; this
  4486. * is how Bootstrap's negative logo margins centre the wordmark. */
  4487. {
  4488. int idy = mp_px(st, 0, l->right - l->left);
  4489. if (idy < -2048)
  4490. idy = -2048;
  4491. if (idy > 2048)
  4492. idy = 2048;
  4493. r->dy = (signed short)idy;
  4494. }
  4495. r->has_lit = 0;
  4496. r->lit[0] = '\0';
  4497. r->img = (short)idx;
  4498. r->iw = (unsigned short)dw;
  4499. r->ih = (unsigned short)dh;
  4500. r->w = (unsigned short)dw;
  4501. r->font_px = st->font_px;
  4502. r->bold = st->bold;
  4503. r->italic = st->italic;
  4504. r->mono = st->mono;
  4505. r->font_face = st->font_face;
  4506. r->transform_scale = st->transform_scale;
  4507. r->scale_x = st->scale_x;
  4508. r->scale_y = st->scale_y;
  4509. r->rotate_x100 = st->rotate_x100;
  4510. r->origin_x = st->origin_x;
  4511. r->origin_y = st->origin_y;
  4512. r->origin_x_kind = st->origin_x_kind;
  4513. r->origin_y_kind = st->origin_y_kind;
  4514. r->underline = 0;
  4515. }
  4516. if (node < BR_MAX_NODES) {
  4517. layout_boxes[node].x = l->line_x;
  4518. layout_boxes[node].y = l->line_y +
  4519. mp_px(st, 0, l->right - l->left);
  4520. layout_boxes[node].w = dw;
  4521. layout_boxes[node].h = dh;
  4522. layout_boxes[node].valid = 1;
  4523. }
  4524. l->line_x += dw;
  4525. l->run_x = l->line_x;
  4526. if (l->line_h < dh)
  4527. l->line_h = dh;
  4528. }
  4529. static int text_width(struct lay *l, const char *s, unsigned int n,
  4530. const struct br_style *st)
  4531. {
  4532. return (int)face_text_width(l->ui, st, s, n);
  4533. }
  4534. /* Longest prefix that fits in maxw, at least one byte. */
  4535. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  4536. const struct br_style *st, int maxw)
  4537. {
  4538. unsigned int take = 0;
  4539. while (take < n) {
  4540. if (text_width(l, s, take + 1, st) > maxw)
  4541. break;
  4542. take++;
  4543. }
  4544. return take ? take : 1;
  4545. }
  4546. static void emit_word(struct lay *l, const char *s, unsigned int start,
  4547. unsigned int n, unsigned int base,
  4548. const struct br_style *st, unsigned short href)
  4549. {
  4550. int avail;
  4551. int w = text_width(l, s + start, n, st);
  4552. unsigned int off = start;
  4553. if (l->nruns == 0)
  4554. start_line(l, st);
  4555. avail = l->line_right - l->line_left;
  4556. if (st->nowrap) {
  4557. if (n)
  4558. add_run(l, (unsigned short)(base + start),
  4559. (unsigned short)n, st, href, 0);
  4560. return;
  4561. }
  4562. /* A padded/bordered one-word button can be a few pixels wider than
  4563. * the content box; keep it on one line instead of splitting it. */
  4564. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  4565. add_run(l, (unsigned short)(base + start),
  4566. (unsigned short)n, st, href, 0);
  4567. return;
  4568. }
  4569. if (l->line_x + w > l->line_right &&
  4570. (l->nruns > 0 || l->line_x > l->line_left)) {
  4571. flush_line(l);
  4572. start_line(l, st);
  4573. avail = l->line_right - l->line_left;
  4574. }
  4575. if (w <= avail) {
  4576. if (n)
  4577. add_run(l, (unsigned short)(base + start),
  4578. (unsigned short)n, st, href, 0);
  4579. return;
  4580. }
  4581. while (n > 0) {
  4582. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  4583. add_run(l, (unsigned short)(base + off),
  4584. (unsigned short)take, st, href, 0);
  4585. off += take;
  4586. n -= take;
  4587. if (n) {
  4588. flush_line(l);
  4589. start_line(l, st);
  4590. avail = l->line_right - l->line_left;
  4591. }
  4592. }
  4593. }
  4594. static void emit_text(struct lay *l, const char *s, unsigned int len,
  4595. const struct br_style *st, unsigned short href, int pre)
  4596. {
  4597. unsigned int i = 0;
  4598. unsigned int base;
  4599. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  4600. if (!s || !len)
  4601. return;
  4602. if (space_w <= 0)
  4603. space_w = 8;
  4604. if (l->nruns == 0)
  4605. start_line(l, st);
  4606. base = (unsigned int)(s - doc.text);
  4607. if (st->uppercase) {
  4608. char *p = (char *)s;
  4609. unsigned int j;
  4610. for (j = 0; j < len; j++)
  4611. if (p[j] >= 'a' && p[j] <= 'z')
  4612. p[j] = (char)(p[j] - 'a' + 'A');
  4613. }
  4614. if (pre) {
  4615. while (i < len) {
  4616. unsigned int start;
  4617. if (s[i] == '\n') {
  4618. flush_line(l);
  4619. start_line(l, st);
  4620. i++;
  4621. continue;
  4622. }
  4623. if (s[i] == ' ') {
  4624. if (l->line_x + space_w > l->line_right &&
  4625. (l->nruns > 0 || l->line_x > l->line_left)) {
  4626. flush_line(l);
  4627. start_line(l, st);
  4628. } else {
  4629. l->line_x += space_w;
  4630. }
  4631. i++;
  4632. continue;
  4633. }
  4634. start = i;
  4635. while (i < len && s[i] != ' ' && s[i] != '\n')
  4636. i++;
  4637. emit_word(l, s, start, i - start, base, st, href);
  4638. }
  4639. return;
  4640. }
  4641. while (i < len) {
  4642. unsigned int start, n;
  4643. if (s[i] == ' ') {
  4644. l->space_pending = 1;
  4645. i++;
  4646. continue;
  4647. }
  4648. start = i;
  4649. while (i < len && s[i] != ' ')
  4650. i++;
  4651. n = i - start;
  4652. if (l->space_pending &&
  4653. (l->nruns > 0 || l->line_x > l->line_left)) {
  4654. if (st->nowrap ||
  4655. l->line_x + space_w <= l->line_right)
  4656. l->line_x += space_w;
  4657. }
  4658. l->space_pending = 0;
  4659. emit_word(l, s, start, n, base, st, href);
  4660. }
  4661. }
  4662. static int list_index(unsigned int parent, unsigned int node)
  4663. {
  4664. unsigned int n = 0, i;
  4665. for (i = doc.nodes[parent].first; i && i != node;
  4666. i = doc.nodes[i].next)
  4667. if (doc.nodes[i].tag == BR_TAG_LI)
  4668. n++;
  4669. return (int)n + 1;
  4670. }
  4671. static void list_roman(char *m, unsigned int *n, int v, int upper,
  4672. unsigned int cap)
  4673. {
  4674. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  4675. 50, 40, 10, 9, 5, 4, 1 };
  4676. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  4677. "l", "xl", "x", "ix", "v", "iv", "i" };
  4678. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  4679. "L", "XL", "X", "IX", "V", "IV", "I" };
  4680. unsigned int i;
  4681. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  4682. while (v >= val[i] && *n + 1 < cap) {
  4683. const char *s = upper ? up[i] : lo[i];
  4684. while (*s && *n + 1 < cap)
  4685. m[(*n)++] = *s++;
  4686. v -= val[i];
  4687. }
  4688. }
  4689. }
  4690. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  4691. {
  4692. unsigned int n = 0;
  4693. if (style == BR_LIST_DISC) {
  4694. m[n++] = '-';
  4695. } else if (style == BR_LIST_CIRCLE) {
  4696. m[n++] = 'o';
  4697. } else if (style == BR_LIST_SQUARE) {
  4698. m[n++] = '+';
  4699. } else if (style == BR_LIST_LOWER_ALPHA ||
  4700. style == BR_LIST_UPPER_ALPHA) {
  4701. if (idx >= 1 && idx <= 26)
  4702. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  4703. 'A' : 'a') + idx - 1);
  4704. else
  4705. m[n++] = '?';
  4706. m[n++] = '.';
  4707. } else if (style == BR_LIST_LOWER_ROMAN ||
  4708. style == BR_LIST_UPPER_ROMAN) {
  4709. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  4710. if (n + 1 < cap)
  4711. m[n++] = '.';
  4712. } else {
  4713. s_append_dec(m, &n, (unsigned int)idx, cap);
  4714. if (n + 1 < cap)
  4715. m[n++] = '.';
  4716. }
  4717. m[n] = '\0';
  4718. }
  4719. static void add_form_run(struct lay *l, unsigned int node,
  4720. const struct br_style *st, unsigned short href)
  4721. {
  4722. struct form_state *fs = form_get(node, 1);
  4723. char shown[FORM_VALUE_MAX + 1];
  4724. char opt[64];
  4725. const char *text = "";
  4726. struct lay_run *r;
  4727. int kind = form_kind_of(node);
  4728. int disabled = form_disabled(node);
  4729. int tw, w = 120, h = 20, i;
  4730. if (!fs)
  4731. return;
  4732. if (l->nruns == 0)
  4733. start_line(l, st);
  4734. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  4735. text = "";
  4736. w = 16;
  4737. h = 16;
  4738. } else if (kind == FORM_SELECT) {
  4739. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  4740. s_copy(opt, "Select", sizeof(opt));
  4741. text = opt;
  4742. w = 120;
  4743. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  4744. kind == FORM_RESET) {
  4745. if (fs->len)
  4746. text = fs->value;
  4747. else
  4748. text = kind == FORM_SUBMIT ? "Submit" :
  4749. kind == FORM_RESET ? "Reset" : "Button";
  4750. } else if (kind == FORM_PASSWORD) {
  4751. for (i = 0; i < fs->len; i++)
  4752. shown[i] = '*';
  4753. shown[fs->len] = '\0';
  4754. text = fs->len ? shown : br_placeholder(&doc, node);
  4755. } else {
  4756. if (fs->len)
  4757. text = fs->value;
  4758. else
  4759. text = br_placeholder(&doc, node);
  4760. if (kind == FORM_TEXTAREA) {
  4761. w = 180;
  4762. h = 40;
  4763. }
  4764. }
  4765. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  4766. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  4767. w = tw + 18;
  4768. if (w < 64)
  4769. w = 64;
  4770. h = 22;
  4771. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD) {
  4772. w = st->width_kind == 1 ? st->width : 120;
  4773. } else if (kind == FORM_SELECT) {
  4774. w = st->width_kind == 1 ? st->width : 120;
  4775. }
  4776. if (w > l->line_right - l->line_left)
  4777. w = l->line_right - l->line_left;
  4778. if (w < 8)
  4779. w = 8;
  4780. if (l->line_x + w > l->line_right &&
  4781. (l->nruns > 0 || l->line_x > l->line_left))
  4782. flush_line(l);
  4783. if (l->nruns >= 96)
  4784. return;
  4785. if (l->nruns == 0) {
  4786. l->line_y = l->y;
  4787. l->line_h = 0;
  4788. start_line(l, st);
  4789. }
  4790. r = &l->runs[l->nruns++];
  4791. r->gap = (unsigned short)(l->line_x - l->run_x);
  4792. r->off = r->len = 0;
  4793. r->color = st->color;
  4794. r->href = href;
  4795. r->dy = 0;
  4796. r->has_lit = 1;
  4797. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  4798. r->lit[i] = text[i];
  4799. r->lit[i] = '\0';
  4800. r->img = -2;
  4801. r->iw = (unsigned short)w;
  4802. r->ih = (unsigned short)h;
  4803. r->w = (unsigned short)w;
  4804. r->font_px = st->font_px;
  4805. r->bold = st->bold;
  4806. r->italic = st->italic;
  4807. r->mono = st->mono;
  4808. r->font_face = st->font_face;
  4809. r->underline = 0;
  4810. r->form = node + 1;
  4811. r->form_kind = (unsigned char)kind;
  4812. r->form_disabled = (unsigned char)disabled;
  4813. if (node < BR_MAX_NODES) {
  4814. layout_boxes[node].x = l->line_x;
  4815. layout_boxes[node].y = l->line_y;
  4816. layout_boxes[node].w = w;
  4817. layout_boxes[node].h = h;
  4818. layout_boxes[node].valid = 1;
  4819. }
  4820. l->line_x += w;
  4821. l->run_x = l->line_x;
  4822. if (l->line_h < h)
  4823. l->line_h = h;
  4824. }
  4825. /* A poster wrapper is absolutely positioned over the media slot; the
  4826. * measured height of its picture is normally added back to the flow. When a
  4827. * loading-skeleton sibling already reserves that slot, adding both doubles
  4828. * the media height and pushes the article text a full screen down. */
  4829. static int has_skeleton_sibling(unsigned int node)
  4830. {
  4831. unsigned int p = doc.nodes[node].parent, c;
  4832. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  4833. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  4834. continue;
  4835. if (doc.nodes[c].class_off &&
  4836. contains_ci(doc.attrs + doc.nodes[c].class_off,
  4837. "skeleton"))
  4838. return 1;
  4839. }
  4840. return 0;
  4841. }
  4842. static void layout_children(struct lay *l, unsigned int parent,
  4843. const struct br_style *pst, int depth,
  4844. unsigned short link);
  4845. static void layout_flex_children(struct lay *l, unsigned int parent,
  4846. const struct br_style *pst, int depth,
  4847. unsigned short link);
  4848. static void layout_grid_children(struct lay *l, unsigned int parent,
  4849. const struct br_style *pst, int depth,
  4850. unsigned short link);
  4851. static void layout_grid_auto(struct lay *l, unsigned int parent,
  4852. const struct br_style *pst, int depth,
  4853. unsigned short link);
  4854. static int flex_item_width(struct lay *l, unsigned int n,
  4855. const struct br_style *cs, int avail);
  4856. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  4857. const struct br_style *pst, int depth,
  4858. unsigned short link);
  4859. static void layout_table_row(struct lay *l, unsigned int row,
  4860. const struct br_style *pst, int depth,
  4861. unsigned short link);
  4862. static int table_has_rowspan(unsigned int table);
  4863. static void layout_table(struct lay *l, unsigned int table,
  4864. const struct br_style *st, int depth,
  4865. unsigned short link);
  4866. /* A flex container whose items are only inline spans is usually just a
  4867. * heading/icon pair. Our flex row positions such items without emitting
  4868. * their inline text in some deep page contexts; normal inline flow renders
  4869. * the same content correctly. */
  4870. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  4871. {
  4872. unsigned int c;
  4873. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  4874. struct br_node *nd = &doc.nodes[c];
  4875. struct br_style cs;
  4876. if (nd->type == BR_NODE_TEXT)
  4877. continue;
  4878. br_style_for(&doc, c, pst, &cs);
  4879. if (cs.display == BR_DISPLAY_NONE)
  4880. continue;
  4881. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  4882. cs.width_kind || cs.has_bg ||
  4883. cs.border_w[0] || cs.border_w[1] ||
  4884. cs.border_w[2] || cs.border_w[3] ||
  4885. nd->tag == BR_TAG_IMG)
  4886. return 1;
  4887. }
  4888. return 0;
  4889. }
  4890. static int css_radius(const struct br_style *st, int corner,
  4891. int w, int h)
  4892. {
  4893. int r = st->radius[corner];
  4894. if (r <= 0)
  4895. return 0;
  4896. if (r > w / 2)
  4897. r = w / 2;
  4898. if (r > h / 2)
  4899. r = h / 2;
  4900. return r;
  4901. }
  4902. static void svg_viewbox(unsigned node, int *vw, int *vh)
  4903. {
  4904. struct br_node *nd = &doc.nodes[node];
  4905. if (nd->width_attr && nd->height_attr) {
  4906. *vw = nd->width_attr;
  4907. *vh = nd->height_attr;
  4908. } else {
  4909. *vw = 300;
  4910. *vh = 150;
  4911. }
  4912. if (*vw < 1)
  4913. *vw = 1;
  4914. if (*vh < 1)
  4915. *vh = 1;
  4916. }
  4917. static int svg_num(const char **pp)
  4918. {
  4919. const char *p = *pp;
  4920. int neg = 0, v = 0, frac = 0, scale = 1;
  4921. while (*p == ' ' || *p == ',' || *p == '\t' ||
  4922. *p == '\n' || *p == '\r')
  4923. p++;
  4924. if (*p == '-') {
  4925. neg = 1;
  4926. p++;
  4927. } else if (*p == '+') {
  4928. p++;
  4929. }
  4930. while (*p >= '0' && *p <= '9') {
  4931. v = v * 10 + (*p - '0');
  4932. p++;
  4933. }
  4934. if (*p == '.') {
  4935. p++;
  4936. while (*p >= '0' && *p <= '9' && scale < 1000) {
  4937. frac = frac * 10 + (*p - '0');
  4938. scale *= 10;
  4939. p++;
  4940. }
  4941. }
  4942. v += frac / scale;
  4943. *pp = p;
  4944. return neg ? -v : v;
  4945. }
  4946. static void svg_path(struct ngui *ui, const char *d,
  4947. int ox, int oy, int dw, int dh, int vw, int vh,
  4948. unsigned short color)
  4949. {
  4950. int cx = 0, cy = 0, sx = 0, sy = 0;
  4951. char cmd = 0;
  4952. const char *p = d;
  4953. while (p && *p) {
  4954. int rel, nx, ny;
  4955. char c;
  4956. while (*p == ' ' || *p == ',' || *p == '\t' ||
  4957. *p == '\n' || *p == '\r')
  4958. p++;
  4959. if (!*p)
  4960. break;
  4961. if ((*p >= 'A' && *p <= 'Z') ||
  4962. (*p >= 'a' && *p <= 'z'))
  4963. cmd = *p++;
  4964. else if (!cmd) {
  4965. p++;
  4966. continue;
  4967. }
  4968. rel = cmd >= 'a' && cmd <= 'z';
  4969. c = rel ? (char)(cmd - 'a' + 'A') : cmd;
  4970. if (c == 'Z') {
  4971. ngui_line(ui, ox + cx * dw / vw, oy + cy * dh / vh,
  4972. ox + sx * dw / vw, oy + sy * dh / vh,
  4973. color);
  4974. cx = sx;
  4975. cy = sy;
  4976. cmd = 0;
  4977. continue;
  4978. }
  4979. if (c == 'H' || c == 'V') {
  4980. const char *save = p;
  4981. int a = svg_num(&p);
  4982. if (p == save) {
  4983. p++;
  4984. continue;
  4985. }
  4986. nx = cx;
  4987. ny = cy;
  4988. if (c == 'H')
  4989. nx = rel ? cx + a : a;
  4990. else
  4991. ny = rel ? cy + a : a;
  4992. } else {
  4993. const char *save = p;
  4994. int a = svg_num(&p);
  4995. int b = svg_num(&p);
  4996. if (p == save) {
  4997. p++;
  4998. continue;
  4999. }
  5000. if (c == 'M') {
  5001. nx = rel ? cx + a : a;
  5002. ny = rel ? cy + b : b;
  5003. cx = sx = nx;
  5004. cy = sy = ny;
  5005. cmd = rel ? 'l' : 'L';
  5006. continue;
  5007. }
  5008. if (c != 'L')
  5009. break;
  5010. nx = rel ? cx + a : a;
  5011. ny = rel ? cy + b : b;
  5012. }
  5013. ngui_line(ui, ox + cx * dw / vw, oy + cy * dh / vh,
  5014. ox + nx * dw / vw, oy + ny * dh / vh, color);
  5015. cx = nx;
  5016. cy = ny;
  5017. }
  5018. }
  5019. static void draw_svg(struct ngui *ui, unsigned node,
  5020. int ox, int oy, int dw, int dh, int vw, int vh,
  5021. const struct br_style *pst)
  5022. {
  5023. unsigned int c;
  5024. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  5025. struct br_node *nd = &doc.nodes[c];
  5026. struct br_style st;
  5027. const char *nm;
  5028. if (nd->type != BR_NODE_ELEM || !nd->name_off)
  5029. continue;
  5030. nm = doc.attrs + nd->name_off;
  5031. br_style_for(&doc, c, pst, &st);
  5032. if (s_eq(nm, "rect")) {
  5033. struct ngui_rect r;
  5034. int rx = (int)nd->svg_rx * dw / vw;
  5035. r.x = ox + (int)nd->svg_x * dw / vw;
  5036. r.y = oy + (int)nd->svg_y * dh / vh;
  5037. r.w = (int)nd->width_attr * dw / vw;
  5038. r.h = (int)nd->height_attr * dh / vh;
  5039. if (r.w < 1)
  5040. r.w = 1;
  5041. if (r.h < 1)
  5042. r.h = 1;
  5043. if (rx > r.w / 2)
  5044. rx = r.w / 2;
  5045. if (rx > r.h / 2)
  5046. rx = r.h / 2;
  5047. if (st.has_bg) {
  5048. if (rx)
  5049. ngui_fill_round_rect(ui, r, rx, rx,
  5050. rx, rx, st.bg);
  5051. else
  5052. ngui_fill_rect(ui, r, st.bg);
  5053. }
  5054. if (st.border_w[0]) {
  5055. if (rx)
  5056. ngui_frame_round(ui, r, rx, rx, rx, rx,
  5057. st.border_w[0],
  5058. st.border_c[0]);
  5059. else
  5060. draw_border_box(ui, r, &st);
  5061. }
  5062. } else if (s_eq(nm, "line")) {
  5063. if (st.border_w[0])
  5064. ngui_line(ui,
  5065. ox + (int)nd->svg_x * dw / vw,
  5066. oy + (int)nd->svg_y * dh / vh,
  5067. ox + (int)nd->width_attr * dw / vw,
  5068. oy + (int)nd->height_attr * dh / vh,
  5069. st.border_c[0]);
  5070. } else if (s_eq(nm, "path")) {
  5071. if (st.border_w[0] && nd->src_off)
  5072. svg_path(ui, doc.attrs + nd->src_off,
  5073. ox, oy, dw, dh, vw, vh,
  5074. st.border_c[0]);
  5075. } else if (s_eq(nm, "text")) {
  5076. unsigned int t = nd->first;
  5077. const char *s;
  5078. unsigned int n, tw;
  5079. int px = st.font_px ? st.font_px : 16;
  5080. int tx, ty, anchor;
  5081. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  5082. continue;
  5083. s = doc.text + doc.nodes[t].text_off;
  5084. n = doc.nodes[t].text_len;
  5085. tw = face_text_width(ui, &st, s, n);
  5086. tx = ox + (int)nd->svg_x * dw / vw;
  5087. ty = oy + (int)nd->svg_y * dh / vh -
  5088. ngui_text_ascent_face(ui, style_face(&st), px,
  5089. st.mono);
  5090. anchor = st.align;
  5091. if (nd->attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  5092. anchor = BR_ALIGN_CENTER;
  5093. else if (nd->attr_flags & BR_ATTR_ANCHOR_END)
  5094. anchor = BR_ALIGN_RIGHT;
  5095. if (anchor == BR_ALIGN_CENTER)
  5096. tx -= (int)tw / 2;
  5097. else if (anchor == BR_ALIGN_RIGHT)
  5098. tx -= (int)tw;
  5099. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  5100. st.color, px, st.bold, st.italic,
  5101. st.mono);
  5102. }
  5103. }
  5104. }
  5105. static void layout_block(struct lay *l, unsigned int node,
  5106. const struct br_style *st, int depth,
  5107. unsigned short link)
  5108. {
  5109. int old_left = l->left, old_right = l->right, old_align = l->align;
  5110. int saved_parent_top = l->parent_top;
  5111. int top, l0, r0;
  5112. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  5113. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  5114. int deco_w, deco_h, content_w, content_h, box_h;
  5115. int definite_w = 0;
  5116. int normal_top = 0;
  5117. int rel_dx = 0, rel_dy = 0;
  5118. int clip_pushed = 0;
  5119. struct ngui_rect clip_rect;
  5120. if (depth > 24 || st->display == BR_DISPLAY_NONE)
  5121. return;
  5122. flow_y = l->y;
  5123. flow_left = l->left;
  5124. flow_right = l->right;
  5125. positioned = st->pos == 1 || st->pos == 2;
  5126. relative = st->pos == 3;
  5127. sticky = st->pos == 4;
  5128. shifted = relative || sticky || st->transform_set;
  5129. if (positioned) {
  5130. int def_w = st->width_kind == 1 ? st->width : -1;
  5131. if (st->pos == 2) {
  5132. int avail_w = page_rect.w - 12;
  5133. if (st->right_set && def_w >= 0)
  5134. l->left = page_rect.x + avail_w - st->right -
  5135. def_w;
  5136. else
  5137. l->left = page_rect.x +
  5138. (st->left_set ? st->left : 0);
  5139. l->right = def_w >= 0 ? l->left + def_w :
  5140. page_rect.x + avail_w;
  5141. if (st->bottom_set && st->height_kind)
  5142. l->y = page_rect.y + page_rect.h -
  5143. st->bottom -
  5144. style_height_px(st, page_rect.w);
  5145. else
  5146. l->y = page_rect.y +
  5147. (st->top_set ? st->top : 0);
  5148. } else {
  5149. int left = flow_left + (st->left_set ? st->left : 0);
  5150. unsigned int parent = doc.nodes[node].parent;
  5151. if (st->right_set && def_w >= 0)
  5152. left = flow_right - st->right - def_w;
  5153. l->left = left;
  5154. l->right = def_w >= 0 ? left + def_w :
  5155. flow_right +
  5156. (st->left_set ? st->left : 0);
  5157. l->y = flow_y + (st->top_set ? st->top : 0);
  5158. if (st->bottom_set && st->height_kind &&
  5159. parent < BR_MAX_NODES && block_h[parent] > 0)
  5160. l->y = flow_y + block_h[parent] - st->bottom -
  5161. style_height_px(st, old_right - old_left);
  5162. }
  5163. old_left = l->left;
  5164. old_right = l->right;
  5165. } else if (relative) {
  5166. rel_dx = st->left_set ? st->left :
  5167. (st->right_set ? -st->right : 0);
  5168. rel_dy = st->top_set ? st->top :
  5169. (st->bottom_set ? -st->bottom : 0);
  5170. }
  5171. if (st->transform_set) {
  5172. rel_dx += st->tx;
  5173. rel_dy += st->ty;
  5174. }
  5175. if (doc.nodes[node].tag == BR_TAG_INPUT ||
  5176. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  5177. doc.nodes[node].tag == BR_TAG_SELECT ||
  5178. doc.nodes[node].tag == BR_TAG_BUTTON) {
  5179. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  5180. s_eq(br_type(&doc, node), "hidden"))
  5181. return;
  5182. add_form_run(l, node, st, link);
  5183. l->y += doc.nodes[node].tag == BR_TAG_TEXTAREA ? 40 :
  5184. doc.nodes[node].tag == BR_TAG_BUTTON ? 22 : 20;
  5185. return;
  5186. }
  5187. flush_line(l);
  5188. cbw = old_right - old_left;
  5189. if (cbw < 8)
  5190. cbw = 8;
  5191. l->y += mp_px(st, 0, cbw);
  5192. top = l->y;
  5193. ml = mp_px(st, 3, cbw);
  5194. mr = mp_px(st, 1, cbw);
  5195. bl = st->border_w[3];
  5196. br = st->border_w[1];
  5197. pl = mp_px(st, 7, cbw);
  5198. pr = mp_px(st, 5, cbw);
  5199. bt = st->border_w[0];
  5200. bb = st->border_w[2];
  5201. pt = mp_px(st, 4, cbw);
  5202. pb = mp_px(st, 6, cbw);
  5203. deco_w = bl + br + pl + pr;
  5204. deco_h = bt + bb + pt + pb;
  5205. if (st->width_kind) {
  5206. int w;
  5207. if (st->width_kind == 3)
  5208. w = cbw * st->width_calc_pct / 100 +
  5209. st->width_calc_px;
  5210. else
  5211. w = css_size(st->width_kind, st->width, cbw);
  5212. if (w < 0)
  5213. w = 0;
  5214. content_w = st->box_sizing ? w - deco_w : w;
  5215. definite_w = 1;
  5216. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  5217. doc.nodes[node].tag == BR_TAG_TD ||
  5218. doc.nodes[node].tag == BR_TAG_TH) &&
  5219. doc.nodes[node].width_attr) {
  5220. /* Legacy table/cell width attributes: percentages resolve
  5221. * against the containing block, bare numbers are pixels. */
  5222. int w = doc.nodes[node].width_pct ?
  5223. cbw * doc.nodes[node].width_attr / 100 :
  5224. doc.nodes[node].width_attr;
  5225. if (w < 0)
  5226. w = 0;
  5227. content_w = st->box_sizing ? w - deco_w : w;
  5228. definite_w = 1;
  5229. } else {
  5230. content_w = cbw - ml - mr - deco_w;
  5231. }
  5232. if (content_w < 0)
  5233. content_w = 0;
  5234. if (st->max_width_kind) {
  5235. int mw = st->max_width_kind == 3 ?
  5236. cbw * st->max_width_calc_pct / 100 +
  5237. st->max_width_calc_px :
  5238. css_size(st->max_width_kind, st->max_width, cbw);
  5239. int max_box = st->box_sizing ? mw : mw + deco_w;
  5240. if (content_w + deco_w > max_box)
  5241. content_w = max_box - deco_w;
  5242. }
  5243. if (st->min_width_kind) {
  5244. int mw = st->min_width_kind == 3 ?
  5245. cbw * st->min_width_calc_pct / 100 +
  5246. st->min_width_calc_px :
  5247. css_size(st->min_width_kind, st->min_width, cbw);
  5248. int min_box = st->box_sizing ? mw : mw + deco_w;
  5249. if (content_w + deco_w < min_box) {
  5250. content_w = min_box - deco_w;
  5251. definite_w = 1;
  5252. }
  5253. }
  5254. if (content_w < 8)
  5255. content_w = 8;
  5256. if (definite_w) {
  5257. int free_w = cbw - ml - mr - deco_w - content_w;
  5258. if (free_w < 0)
  5259. free_w = 0;
  5260. if (st->ml_auto && st->mr_auto) {
  5261. ml = free_w / 2;
  5262. mr = free_w - ml;
  5263. } else if (st->ml_auto) {
  5264. ml = free_w;
  5265. } else if (st->mr_auto) {
  5266. mr = free_w;
  5267. }
  5268. }
  5269. l0 = old_left + ml;
  5270. r0 = l0 + deco_w + content_w;
  5271. if (r0 < l0 + 8)
  5272. r0 = l0 + 8;
  5273. normal_top = top;
  5274. if (sticky) {
  5275. if (st->top_set) {
  5276. int stick = page_rect.y + 4 + st->top;
  5277. if (normal_top < stick)
  5278. rel_dy += stick - normal_top;
  5279. } else if (st->bottom_set && block_h[node]) {
  5280. int stick = page_rect.y + page_rect.h - st->bottom -
  5281. block_h[node];
  5282. if (normal_top > stick)
  5283. rel_dy += stick - normal_top;
  5284. }
  5285. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  5286. block_h[doc.nodes[node].parent]) {
  5287. unsigned int p = doc.nodes[node].parent;
  5288. int ptop = l->parent_top;
  5289. int pbottom = ptop + block_h[p];
  5290. int eh = block_h[node];
  5291. int moved_top = normal_top + rel_dy;
  5292. int moved_bottom = moved_top + eh;
  5293. if (moved_bottom > pbottom)
  5294. rel_dy -= moved_bottom - pbottom;
  5295. moved_top = normal_top + rel_dy;
  5296. if (moved_top < ptop)
  5297. rel_dy += ptop - moved_top;
  5298. }
  5299. }
  5300. if (shifted && l->draw) {
  5301. top += rel_dy;
  5302. l0 += rel_dx;
  5303. r0 += rel_dx;
  5304. }
  5305. l->parent_top = top;
  5306. if (l->draw && block_h[node] &&
  5307. top < page_rect.y + page_rect.h &&
  5308. top + block_h[node] > page_rect.y) {
  5309. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  5310. int rtl = css_radius(st, 0, box.w, box.h);
  5311. int rtr = css_radius(st, 1, box.w, box.h);
  5312. int rbr = css_radius(st, 2, box.w, box.h);
  5313. int rbl = css_radius(st, 3, box.w, box.h);
  5314. if (st->transform_scale) {
  5315. if (st->has_bg)
  5316. fill_transformed_rect(l->ui, box, st->bg, st);
  5317. } else if (rtl || rtr || rbr || rbl) {
  5318. if (st->has_bg) {
  5319. int bw = st->border_w[0];
  5320. if (bw > 0 && st->border_c[0] != st->bg &&
  5321. box.w > bw * 2 && box.h > bw * 2) {
  5322. struct ngui_rect inner = {
  5323. box.x + bw, box.y + bw,
  5324. box.w - bw * 2, box.h - bw * 2
  5325. };
  5326. int itl = rtl > bw ? rtl - bw : 0;
  5327. int itr = rtr > bw ? rtr - bw : 0;
  5328. int ibr = rbr > bw ? rbr - bw : 0;
  5329. int ibl = rbl > bw ? rbl - bw : 0;
  5330. ngui_fill_round_rect(l->ui, box, rtl,
  5331. rtr, rbr, rbl,
  5332. st->border_c[0]);
  5333. ngui_fill_round_rect(l->ui, inner,
  5334. itl, itr, ibr,
  5335. ibl, st->bg);
  5336. } else {
  5337. ngui_fill_round_rect(l->ui, box, rtl,
  5338. rtr, rbr, rbl,
  5339. st->bg);
  5340. }
  5341. } else if (st->border_w[0]) {
  5342. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  5343. rbl, st->border_w[0],
  5344. st->border_c[0]);
  5345. }
  5346. } else {
  5347. if (st->has_bg)
  5348. ngui_fill_rect(l->ui, box, st->bg);
  5349. if (st->bg_image)
  5350. draw_bg_image(l, box, node, st);
  5351. if (st->border_w[0] || st->border_w[1] ||
  5352. st->border_w[2] || st->border_w[3])
  5353. draw_border_box(l->ui, box, st);
  5354. }
  5355. }
  5356. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  5357. l->ui && l->ui->nclip < 4) {
  5358. clip_rect.x = l0 + bl;
  5359. clip_rect.y = top + bt;
  5360. clip_rect.w = (r0 - l0) - bl - br;
  5361. clip_rect.h = (int)block_h[node] - bt - bb;
  5362. if (clip_rect.w > 0 && clip_rect.h > 0) {
  5363. ngui_push_clip(l->ui, clip_rect);
  5364. clip_pushed = 1;
  5365. }
  5366. }
  5367. l->left = l0 + bl + pl;
  5368. l->right = l->left + content_w;
  5369. if (l->right < l->left + 8)
  5370. l->right = l->left + 8;
  5371. l->align = st->align;
  5372. l->line_left = l->left;
  5373. l->line_right = l->right;
  5374. l->y = top + bt + pt;
  5375. if (doc.nodes[node].tag == BR_TAG_HR) {
  5376. if (l->draw)
  5377. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  5378. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  5379. l->y += 8;
  5380. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  5381. int vw = l->right - l->left;
  5382. int vh;
  5383. if (doc.nodes[node].width_pct)
  5384. vw = vw * doc.nodes[node].width_attr / 100;
  5385. else if (doc.nodes[node].width_attr)
  5386. vw = doc.nodes[node].width_attr;
  5387. if (vw > l->right - l->left)
  5388. vw = l->right - l->left;
  5389. if (vw < 8)
  5390. vw = 8;
  5391. vh = vw * 9 / 16;
  5392. if (vh > 240)
  5393. vh = 240;
  5394. if (vh < 80)
  5395. vh = 80;
  5396. if (l->draw) {
  5397. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  5398. vw, vh}, 0xD69A);
  5399. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  5400. vw, vh}, 0x8410);
  5401. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  5402. 0x4208);
  5403. }
  5404. l->y += vh + 4;
  5405. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  5406. int vw, vh, dw = l->right - l->left;
  5407. int dh;
  5408. svg_viewbox(node, &vw, &vh);
  5409. if (dw < 8)
  5410. dw = 8;
  5411. dh = dw * vh / vw;
  5412. if (dh < 8)
  5413. dh = 8;
  5414. if (dh > 1400)
  5415. dh = 1400;
  5416. if (l->draw) {
  5417. struct ngui_rect clip = {l->left, l->y, dw, dh};
  5418. ngui_push_clip(l->ui, clip);
  5419. draw_svg(l->ui, node, l->left, l->y, dw, dh,
  5420. vw, vh, st);
  5421. ngui_pop_clip(l->ui);
  5422. }
  5423. l->y += dh;
  5424. } else {
  5425. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  5426. !st->no_bullet) {
  5427. char *m = li_marker[node];
  5428. if (!m[0]) {
  5429. unsigned int parent = doc.nodes[node].parent;
  5430. int style = st->list_style;
  5431. int idx = parent ? list_index(parent, node) : 1;
  5432. if (style == BR_LIST_AUTO)
  5433. style = (parent &&
  5434. doc.nodes[parent].tag ==
  5435. BR_TAG_OL) ?
  5436. BR_LIST_DECIMAL : BR_LIST_DISC;
  5437. list_marker_text(m, sizeof(li_marker[node]),
  5438. style, idx);
  5439. }
  5440. if (l->draw && m[0]) {
  5441. int mw = (int)ngui_text_width_ui(l->ui, m);
  5442. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  5443. st->color);
  5444. }
  5445. }
  5446. if (doc.nodes[node].tag == BR_TAG_TR)
  5447. layout_table_row(l, node, st, depth + 1, link);
  5448. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  5449. table_has_rowspan(node))
  5450. layout_table(l, node, st, depth + 1, link);
  5451. else if (st->grid_auto)
  5452. layout_grid_auto(l, node, st, depth + 1, link);
  5453. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  5454. st->grid_gap > 0)
  5455. layout_grid_children(l, node, st, depth + 1, link);
  5456. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  5457. flex_wants_row(node, st))
  5458. layout_flex_children(l, node, st, depth + 1, link);
  5459. else
  5460. layout_children(l, node, st, depth + 1, link);
  5461. }
  5462. flush_line(l);
  5463. if (clip_pushed)
  5464. ngui_pop_clip(l->ui);
  5465. if (l->float_active) {
  5466. if (l->y < l->float_bottom)
  5467. l->y = l->float_bottom;
  5468. l->float_active = 0;
  5469. }
  5470. if (st->height_kind &&
  5471. !((doc.nodes[node].tag == BR_TAG_HTML ||
  5472. doc.nodes[node].tag == BR_TAG_BODY) &&
  5473. st->height_kind == 2)) {
  5474. content_h = style_height_px(st, cbw);
  5475. if (st->box_sizing)
  5476. content_h -= deco_h;
  5477. } else {
  5478. /* Percentage heights on html/body resolve against the
  5479. * viewport, but their content still defines the document
  5480. * scroll height. Treating them as auto avoids collapsing
  5481. * the measured page to the containing block width. */
  5482. content_h = l->y - (top + bt + pt);
  5483. }
  5484. if (content_h < 0)
  5485. content_h = 0;
  5486. if (st->max_height_kind) {
  5487. int mh = st->max_height_kind == 3 ?
  5488. cbw * st->max_height_calc_pct / 100 +
  5489. st->max_height_calc_px :
  5490. css_size(st->max_height_kind, st->max_height, cbw);
  5491. int max_box = st->box_sizing ? mh : mh + deco_h;
  5492. if (content_h + deco_h > max_box)
  5493. content_h = max_box - deco_h;
  5494. }
  5495. if (st->min_height_kind &&
  5496. !((doc.nodes[node].tag == BR_TAG_HTML ||
  5497. doc.nodes[node].tag == BR_TAG_BODY) &&
  5498. st->min_height_kind == 2)) {
  5499. int mh = st->min_height_kind == 3 ?
  5500. cbw * st->min_height_calc_pct / 100 +
  5501. st->min_height_calc_px :
  5502. css_size(st->min_height_kind, st->min_height, cbw);
  5503. int min_box = st->box_sizing ? mh : mh + deco_h;
  5504. if (content_h + deco_h < min_box)
  5505. content_h = min_box - deco_h;
  5506. }
  5507. if (content_h < 0)
  5508. content_h = 0;
  5509. box_h = deco_h + content_h;
  5510. if (box_h < 0)
  5511. box_h = 0;
  5512. l->y = (shifted ? normal_top : top) + box_h;
  5513. if (node < BR_MAX_NODES) {
  5514. layout_boxes[node].x = l0;
  5515. layout_boxes[node].y = top;
  5516. layout_boxes[node].w = r0 - l0;
  5517. layout_boxes[node].h = box_h;
  5518. layout_boxes[node].valid = r0 > l0;
  5519. }
  5520. l->left = old_left;
  5521. l->right = old_right;
  5522. l->align = old_align;
  5523. l->y += mp_px(st, 2, cbw);
  5524. if (!l->draw) {
  5525. if (box_h > 65535)
  5526. box_h = 65535;
  5527. block_h[node] = (unsigned short)box_h;
  5528. }
  5529. if (positioned) {
  5530. l->y = flow_y;
  5531. l->left = flow_left;
  5532. l->right = flow_right;
  5533. }
  5534. l->parent_top = saved_parent_top;
  5535. }
  5536. static int text_node_blank(const struct br_node *nd)
  5537. {
  5538. const char *t = doc.text + nd->text_off;
  5539. unsigned int i;
  5540. for (i = 0; i < nd->text_len; i++)
  5541. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  5542. t[i] != '\r')
  5543. return 0;
  5544. return 1;
  5545. }
  5546. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  5547. * text/image widths in the subtree, plus padding and margins. This keeps
  5548. * Bootstrap's floated nav items on one line instead of giving each the whole
  5549. * row. */
  5550. static int text_space(char c)
  5551. {
  5552. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  5553. }
  5554. static int intrinsic_width(struct ngui *ui, unsigned int node,
  5555. const struct br_style *pst, int depth, int base)
  5556. {
  5557. unsigned int c;
  5558. int line_w = 0, max_w = 0;
  5559. if (depth > 12)
  5560. return 0;
  5561. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  5562. struct br_node *nd = &doc.nodes[c];
  5563. struct br_style cs;
  5564. if (nd->type == BR_NODE_TEXT) {
  5565. const char *t = doc.text + nd->text_off;
  5566. unsigned int tn = nd->text_len;
  5567. if (doc.nodes[node].tag == BR_TAG_PRE) {
  5568. line_w += (int)face_text_width(ui, pst, t, tn);
  5569. } else {
  5570. unsigned int ti = 0;
  5571. int first = 1;
  5572. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  5573. int sp = (int)face_text_width(ui, pst, " ", 1);
  5574. while (ti < tn) {
  5575. unsigned int ts;
  5576. while (ti < tn && text_space(t[ti]))
  5577. ti++;
  5578. ts = ti;
  5579. while (ti < tn && !text_space(t[ti]))
  5580. ti++;
  5581. if (ti == ts)
  5582. break;
  5583. if (!first || lead)
  5584. line_w += sp;
  5585. lead = 0;
  5586. line_w += (int)face_text_width(ui, pst,
  5587. t + ts, ti - ts);
  5588. first = 0;
  5589. }
  5590. }
  5591. continue;
  5592. }
  5593. br_style_for(&doc, c, pst, &cs);
  5594. if (cs.display == BR_DISPLAY_NONE)
  5595. continue;
  5596. if (nd->tag == BR_TAG_BR) {
  5597. if (line_w > max_w)
  5598. max_w = line_w;
  5599. line_w = 0;
  5600. continue;
  5601. }
  5602. if (nd->tag == BR_TAG_IMG) {
  5603. /* Measure the image as layout will draw it: a CSS or
  5604. * attribute height keeps the intrinsic aspect ratio, and
  5605. * a CSS width overrides the native pixel width. Bootstrap
  5606. * sizes the Cloudron logo with height:40px only. */
  5607. int idx = nd->img_index;
  5608. int iw = 0, ih = 0;
  5609. if (idx >= 0 && idx < image_count &&
  5610. images[idx].state == 1) {
  5611. iw = (int)images[idx].native_w;
  5612. ih = (int)images[idx].native_h;
  5613. if (iw <= 0 || ih <= 0) {
  5614. iw = (int)images[idx].img.w;
  5615. ih = (int)images[idx].img.h;
  5616. }
  5617. }
  5618. if (cs.width_kind) {
  5619. int ww = style_width_px(&cs, base);
  5620. line_w += ww > 0 ? ww : 64;
  5621. } else if (nd->width_attr) {
  5622. line_w += nd->width_attr;
  5623. } else if (nd->height_attr && iw && ih) {
  5624. line_w += iw * (int)nd->height_attr / ih;
  5625. } else if (cs.height_kind && iw && ih) {
  5626. int hh = style_height_px(&cs, base);
  5627. line_w += hh > 0 ? iw * hh / ih : iw;
  5628. } else if (iw) {
  5629. line_w += iw;
  5630. } else {
  5631. line_w += 64;
  5632. }
  5633. continue;
  5634. }
  5635. {
  5636. int cw = mp_px(&cs, 7, base) +
  5637. mp_px(&cs, 5, base) +
  5638. mp_px(&cs, 3, base) +
  5639. mp_px(&cs, 1, base) +
  5640. cs.border_w[1] + cs.border_w[3] +
  5641. intrinsic_width(ui, c, &cs, depth + 1, base);
  5642. if (cs.float_left || cs.display == BR_DISPLAY_INLINE ||
  5643. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  5644. line_w += cw;
  5645. } else {
  5646. if (line_w > max_w)
  5647. max_w = line_w;
  5648. line_w = 0;
  5649. if (cw > max_w)
  5650. max_w = cw;
  5651. }
  5652. }
  5653. if (line_w > 4096 || max_w > 4096)
  5654. break;
  5655. }
  5656. return line_w > max_w ? line_w : max_w;
  5657. }
  5658. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  5659. * the main user: .row > .col-md-* with float:left and a percentage width.
  5660. * Each column is laid out with its own left/right edge and the row advances
  5661. * to the tallest column. Returns the first child not consumed. */
  5662. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  5663. const struct br_style *pst, int depth,
  5664. unsigned short link)
  5665. {
  5666. unsigned int n = first;
  5667. int row_left = l->left, row_right = l->right;
  5668. int row_top, row_bottom, xl, xr, any = 0;
  5669. int fl_left = row_left, fl_right = row_right, fl_bottom;
  5670. flush_line(l);
  5671. row_top = l->y;
  5672. row_bottom = l->y;
  5673. fl_bottom = row_top;
  5674. xl = row_left;
  5675. xr = row_right;
  5676. while (n) {
  5677. struct br_node *nd = &doc.nodes[n];
  5678. struct br_style cs;
  5679. unsigned short lk = link;
  5680. int colw, right;
  5681. if (nd->type == BR_NODE_TEXT) {
  5682. if (text_node_blank(nd)) {
  5683. n = nd->next;
  5684. continue;
  5685. }
  5686. break;
  5687. }
  5688. br_style_for(&doc, n, pst, &cs);
  5689. if (cs.display == BR_DISPLAY_NONE) {
  5690. n = nd->next;
  5691. continue;
  5692. }
  5693. /* A float blockifies its box: Bootstrap floats inline
  5694. * anchors too (the navbar brand and its text links), and
  5695. * their padding must be honoured. */
  5696. if (!cs.float_left)
  5697. break;
  5698. if (nd->tag == BR_TAG_A && nd->href_off)
  5699. lk = (unsigned short)n;
  5700. right = cs.float_left == 2;
  5701. if (cs.width_kind == 2 || cs.width_kind == 3) {
  5702. colw = style_width_px(&cs, row_right - row_left);
  5703. } else if (cs.width_kind == 1) {
  5704. colw = (int)cs.width;
  5705. } else {
  5706. int base = row_right - row_left;
  5707. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  5708. mp_px(&cs, 7, base) +
  5709. mp_px(&cs, 5, base) +
  5710. mp_px(&cs, 3, base) +
  5711. mp_px(&cs, 1, base);
  5712. if (colw < 8)
  5713. colw = 8;
  5714. }
  5715. if (colw < 8)
  5716. colw = 8;
  5717. if (colw > row_right - row_left)
  5718. colw = row_right - row_left;
  5719. /* The float column width is already resolved. */
  5720. cs.width_kind = 0;
  5721. cs.max_width_kind = 0;
  5722. if (right) {
  5723. if (any && xr - colw < xl) {
  5724. row_top = row_bottom;
  5725. row_bottom = row_top;
  5726. xl = row_left;
  5727. xr = row_right;
  5728. }
  5729. if (xr - colw < xl)
  5730. colw = xr - xl;
  5731. if (colw < 8)
  5732. colw = 8;
  5733. l->left = xr - colw;
  5734. if (l->left < row_left)
  5735. l->left = row_left;
  5736. l->right = xr;
  5737. xr = l->left;
  5738. if (xr < fl_right)
  5739. fl_right = xr;
  5740. } else {
  5741. if (any && xl + colw > xr) {
  5742. row_top = row_bottom;
  5743. row_bottom = row_top;
  5744. xl = row_left;
  5745. xr = row_right;
  5746. }
  5747. l->left = xl;
  5748. l->right = xl + colw;
  5749. xl += colw;
  5750. if (xl > fl_left)
  5751. fl_left = xl;
  5752. }
  5753. if (l->right < l->left + 8)
  5754. l->right = l->left + 8;
  5755. l->y = row_top;
  5756. l->line_x = l->left;
  5757. l->run_x = l->left;
  5758. l->line_y = l->y;
  5759. l->line_h = 0;
  5760. l->nruns = 0;
  5761. l->space_pending = 0;
  5762. l->align = cs.align;
  5763. layout_block(l, n, &cs, depth + 1, lk);
  5764. if (l->y > row_bottom)
  5765. row_bottom = l->y;
  5766. if (l->y > fl_bottom)
  5767. fl_bottom = l->y;
  5768. any = 1;
  5769. n = nd->next;
  5770. }
  5771. l->left = row_left;
  5772. l->right = row_right;
  5773. if (n && any) {
  5774. struct br_node *nd = &doc.nodes[n];
  5775. int inline_next = 0;
  5776. if (nd->type == BR_NODE_TEXT) {
  5777. inline_next = 1;
  5778. } else if (nd->type == BR_NODE_ELEM) {
  5779. struct br_style cs;
  5780. br_style_for(&doc, n, pst, &cs);
  5781. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  5782. cs.display != BR_DISPLAY_NONE &&
  5783. !br_tag_is_block(nd->tag);
  5784. }
  5785. if (inline_next) {
  5786. if (l->float_active) {
  5787. if (l->float_left > fl_left)
  5788. fl_left = l->float_left;
  5789. if (l->float_right < fl_right)
  5790. fl_right = l->float_right;
  5791. if (l->float_bottom > fl_bottom)
  5792. fl_bottom = l->float_bottom;
  5793. }
  5794. l->float_active = 1;
  5795. l->float_left = fl_left;
  5796. l->float_right = fl_right;
  5797. l->float_bottom = fl_bottom;
  5798. l->y = row_top;
  5799. } else {
  5800. l->float_active = 0;
  5801. l->y = row_bottom;
  5802. }
  5803. } else {
  5804. l->float_active = 0;
  5805. l->y = row_bottom;
  5806. }
  5807. l->line_x = l->left;
  5808. l->run_x = l->left;
  5809. l->line_left = l->left;
  5810. l->line_right = l->right;
  5811. l->line_y = l->y;
  5812. l->line_h = 0;
  5813. l->nruns = 0;
  5814. l->space_pending = 0;
  5815. return n;
  5816. }
  5817. static int flex_item_width(struct lay *l, unsigned int n,
  5818. const struct br_style *cs, int avail)
  5819. {
  5820. struct br_node *nd = &doc.nodes[n];
  5821. (void)l;
  5822. int w;
  5823. if (cs->width_kind == 2 || cs->width_kind == 3)
  5824. w = style_width_px(cs, avail);
  5825. else if (cs->width_kind == 1)
  5826. w = (int)cs->width;
  5827. else if (nd->tag == BR_TAG_IMG) {
  5828. int idx = nd->img_index;
  5829. if (idx >= 0 && idx < image_count &&
  5830. images[idx].state == 1)
  5831. w = (int)images[idx].img.w;
  5832. else if (nd->width_attr)
  5833. w = (int)nd->width_attr;
  5834. else
  5835. w = 64;
  5836. } else {
  5837. w = intrinsic_width(l->ui, n, cs, 0, avail);
  5838. w += mp_px(cs, 7, avail);
  5839. w += mp_px(cs, 5, avail);
  5840. w += mp_px(cs, 3, avail);
  5841. w += mp_px(cs, 1, avail);
  5842. }
  5843. if (w < 24)
  5844. w = 24;
  5845. if (w > avail)
  5846. w = avail;
  5847. return w;
  5848. }
  5849. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  5850. * on one line, not one full-width block each. Place intrinsic widths from
  5851. * left to right and wrap when the row is full. */
  5852. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  5853. const struct br_style *pst, int depth,
  5854. unsigned short link)
  5855. {
  5856. unsigned int n = first;
  5857. int row_left = l->left, row_right = l->right;
  5858. int avail = row_right - row_left;
  5859. int x = row_left, y = l->y, row_h = 0, any = 0;
  5860. flush_line(l);
  5861. y = l->y;
  5862. while (n) {
  5863. struct br_node *nd = &doc.nodes[n];
  5864. struct br_style cs;
  5865. unsigned short lk = link;
  5866. int colw, h;
  5867. if (nd->type == BR_NODE_TEXT) {
  5868. if (!text_node_blank(nd))
  5869. break;
  5870. if (any)
  5871. x += 4;
  5872. n = nd->next;
  5873. continue;
  5874. }
  5875. br_style_for(&doc, n, pst, &cs);
  5876. if (cs.display == BR_DISPLAY_NONE) {
  5877. n = nd->next;
  5878. continue;
  5879. }
  5880. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  5881. break;
  5882. if (nd->tag == BR_TAG_A && nd->href_off)
  5883. lk = (unsigned short)n;
  5884. colw = flex_item_width(l, n, &cs, avail);
  5885. /* A few pixels of slack keep a single long token (boot.S)
  5886. * from wrapping at the exact content width. */
  5887. colw += 8;
  5888. if (colw > avail)
  5889. colw = avail;
  5890. cs.width_kind = 0;
  5891. cs.max_width_kind = 0;
  5892. if (any && x + colw > row_right) {
  5893. y += row_h + 2;
  5894. x = row_left;
  5895. row_h = 0;
  5896. any = 0;
  5897. }
  5898. if (any && x > row_left)
  5899. x += 4;
  5900. l->left = x;
  5901. l->right = x + colw;
  5902. if (l->right < l->left + 8)
  5903. l->right = l->left + 8;
  5904. l->y = y;
  5905. l->line_x = l->left;
  5906. l->run_x = l->left;
  5907. l->line_y = l->y;
  5908. l->line_h = 0;
  5909. l->nruns = 0;
  5910. l->space_pending = 0;
  5911. l->align = cs.align;
  5912. layout_block(l, n, &cs, depth + 1, lk);
  5913. h = l->y - y;
  5914. if (h > row_h)
  5915. row_h = h;
  5916. x += colw;
  5917. any = 1;
  5918. n = nd->next;
  5919. }
  5920. if (any)
  5921. y += row_h;
  5922. l->left = row_left;
  5923. l->right = row_right;
  5924. l->y = y;
  5925. l->line_x = l->left;
  5926. l->run_x = l->left;
  5927. l->line_y = l->y;
  5928. l->line_h = 0;
  5929. l->nruns = 0;
  5930. l->space_pending = 0;
  5931. return n;
  5932. }
  5933. struct flex_item {
  5934. unsigned int node;
  5935. unsigned short link;
  5936. int w;
  5937. };
  5938. static void layout_flex_children(struct lay *l, unsigned int parent,
  5939. const struct br_style *pst, int depth,
  5940. unsigned short link)
  5941. {
  5942. struct flex_item it[32];
  5943. unsigned int c;
  5944. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  5945. int row_left = l->left, row_right = l->right;
  5946. int avail = row_right - row_left;
  5947. int idx, row_top;
  5948. if (avail < 160 || depth > 24) {
  5949. layout_children(l, parent, pst, depth, link);
  5950. return;
  5951. }
  5952. /* If direct text is not just whitespace, normal block flow handles it
  5953. * better than pretending it is a flex item. */
  5954. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  5955. struct br_node *nd = &doc.nodes[c];
  5956. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  5957. layout_children(l, parent, pst, depth, link);
  5958. return;
  5959. }
  5960. }
  5961. for (c = doc.nodes[parent].first;
  5962. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  5963. c = doc.nodes[c].next) {
  5964. struct br_node *nd = &doc.nodes[c];
  5965. struct br_style cs;
  5966. if (nd->type == BR_NODE_TEXT)
  5967. continue;
  5968. br_style_for(&doc, c, pst, &cs);
  5969. if (cs.display == BR_DISPLAY_NONE)
  5970. continue;
  5971. it[nitem].node = c;
  5972. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  5973. (unsigned short)c : link;
  5974. it[nitem].w = 0;
  5975. if (cs.flex_grow && !cs.width_kind)
  5976. grow_count++;
  5977. else
  5978. fixed += flex_item_width(l, c, &cs, avail);
  5979. nitem++;
  5980. }
  5981. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  5982. if (grow_w < 96)
  5983. grow_w = 96;
  5984. for (idx = 0; idx < nitem; idx++) {
  5985. struct br_style cs;
  5986. br_style_for(&doc, it[idx].node, pst, &cs);
  5987. if (cs.flex_grow && !cs.width_kind)
  5988. it[idx].w = grow_w;
  5989. else
  5990. it[idx].w = flex_item_width(l, it[idx].node, &cs, avail);
  5991. if (it[idx].w > avail)
  5992. it[idx].w = avail;
  5993. if (it[idx].w < 8)
  5994. it[idx].w = 8;
  5995. }
  5996. row_top = l->y;
  5997. idx = 0;
  5998. while (idx < nitem) {
  5999. int start = idx, count = 0, row_w = 0;
  6000. int free_w, x, extra = 0, row_h = 0, k;
  6001. while (idx < nitem) {
  6002. int add = it[idx].w + (count ? gap : 0);
  6003. if (count && pst->flex_wrap != 2 &&
  6004. row_w + add > avail)
  6005. break;
  6006. row_w += add;
  6007. count++;
  6008. idx++;
  6009. }
  6010. if (!count) {
  6011. count = 1;
  6012. row_w = it[start].w;
  6013. idx = start + 1;
  6014. }
  6015. free_w = avail - row_w;
  6016. if (free_w < 0)
  6017. free_w = 0;
  6018. x = row_left;
  6019. if (pst->justify == 1) {
  6020. x += free_w / 2;
  6021. } else if (pst->justify == 2) {
  6022. x += free_w;
  6023. } else if (pst->justify == 3) {
  6024. extra = count > 1 ? free_w / (count - 1) : 0;
  6025. } else if (pst->justify == 4) {
  6026. extra = count ? free_w / count : 0;
  6027. x += extra / 2;
  6028. } else if (pst->justify == 5) {
  6029. extra = count ? free_w / (count + 1) : 0;
  6030. x += extra;
  6031. }
  6032. for (k = 0; k < count; k++) {
  6033. int node = (int)it[start + k].node;
  6034. int h = block_h[node];
  6035. if (h > row_h)
  6036. row_h = h;
  6037. }
  6038. if (pst->height_kind) {
  6039. int hh = style_height_px(pst, avail);
  6040. if (hh > row_h)
  6041. row_h = hh;
  6042. }
  6043. for (k = 0; k < count; k++) {
  6044. struct br_style cs;
  6045. int node = (int)it[start + k].node;
  6046. int yoff = 0;
  6047. br_style_for(&doc, node, pst, &cs);
  6048. cs.width_kind = 0;
  6049. cs.max_width_kind = 0;
  6050. if (l->draw && pst->align_items &&
  6051. row_h > block_h[node]) {
  6052. if (pst->align_items == 1)
  6053. yoff = (row_h - block_h[node]) / 2;
  6054. else if (pst->align_items == 2)
  6055. yoff = row_h - block_h[node];
  6056. }
  6057. l->left = x;
  6058. l->right = x + it[start + k].w;
  6059. if (l->right < l->left + 8)
  6060. l->right = l->left + 8;
  6061. l->y = row_top + yoff;
  6062. l->line_x = l->left;
  6063. l->run_x = l->left;
  6064. l->line_y = l->y;
  6065. l->line_h = 0;
  6066. l->nruns = 0;
  6067. l->space_pending = 0;
  6068. l->align = cs.align;
  6069. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  6070. if (!l->draw) {
  6071. int h = l->y - row_top;
  6072. if (h > row_h)
  6073. row_h = h;
  6074. }
  6075. x += it[start + k].w;
  6076. if (k + 1 < count)
  6077. x += gap + extra;
  6078. }
  6079. row_top += row_h;
  6080. }
  6081. l->left = row_left;
  6082. l->right = row_right;
  6083. l->y = row_top;
  6084. l->line_x = l->left;
  6085. l->run_x = l->left;
  6086. l->line_y = l->y;
  6087. l->line_h = 0;
  6088. l->nruns = 0;
  6089. l->space_pending = 0;
  6090. }
  6091. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  6092. * plus the grid-area hints used by site shells (site notice/footer full
  6093. * width, column-start left, page-content right). Anything more elaborate
  6094. * falls back to normal block flow. */
  6095. static int grid_track_width(unsigned char kind, unsigned short val,
  6096. int avail, int other)
  6097. {
  6098. if (kind == 2)
  6099. return avail * (int)val / 100;
  6100. if (kind == 1)
  6101. return val;
  6102. return other;
  6103. }
  6104. static void layout_grid_children(struct lay *l, unsigned int parent,
  6105. const struct br_style *pst, int depth,
  6106. unsigned short link)
  6107. {
  6108. unsigned int n;
  6109. int row_left = l->left, row_right = l->right;
  6110. int avail = row_right - row_left;
  6111. int gap = pst->grid_gap;
  6112. int track_total = avail - gap;
  6113. int col0, col1, x0, x1;
  6114. int row_y, row_bottom, have_left = 0, have_right = 0;
  6115. unsigned int c;
  6116. if (avail < 32 || depth > 24)
  6117. return;
  6118. if (track_total < 16)
  6119. track_total = 16;
  6120. col0 = grid_track_width((unsigned char)(pst->width_kind),
  6121. pst->width, track_total, 0);
  6122. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  6123. pst->max_width, track_total, 0);
  6124. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  6125. int w0 = pst->width ? pst->width : 1;
  6126. int w1 = pst->max_width ? pst->max_width : 1;
  6127. col0 = track_total * w0 / (w0 + w1);
  6128. col1 = track_total - col0;
  6129. } else if (pst->width_kind == 3) {
  6130. col0 = track_total - col1;
  6131. if (col0 < 24)
  6132. col0 = 24;
  6133. } else if (pst->max_width_kind == 3) {
  6134. col1 = track_total - col0;
  6135. if (col1 < 24)
  6136. col1 = 24;
  6137. }
  6138. if (col0 < 24)
  6139. col0 = 24;
  6140. if (col1 < 24)
  6141. col1 = 24;
  6142. if (col0 + col1 > track_total) {
  6143. col1 = track_total - col0;
  6144. if (col1 < 24)
  6145. col1 = 24;
  6146. }
  6147. x0 = row_left;
  6148. x1 = row_left + col0 + gap;
  6149. /* Direct text makes a grid ambiguous; use block flow instead. */
  6150. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  6151. struct br_node *nd = &doc.nodes[c];
  6152. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  6153. layout_children(l, parent, pst, depth, link);
  6154. return;
  6155. }
  6156. }
  6157. row_y = row_bottom = l->y;
  6158. n = doc.nodes[parent].first;
  6159. while (n) {
  6160. struct br_node *nd = &doc.nodes[n];
  6161. struct br_style cs;
  6162. unsigned short lk = link;
  6163. int slot, x, w;
  6164. if (nd->type == BR_NODE_TEXT) {
  6165. n = nd->next;
  6166. continue;
  6167. }
  6168. br_style_for(&doc, n, pst, &cs);
  6169. if (cs.display == BR_DISPLAY_NONE) {
  6170. n = nd->next;
  6171. continue;
  6172. }
  6173. if (nd->tag == BR_TAG_A && nd->href_off)
  6174. lk = (unsigned short)n;
  6175. slot = cs.grid_slot;
  6176. if (!slot) {
  6177. if (!have_left)
  6178. slot = 2;
  6179. else if (!have_right)
  6180. slot = 3;
  6181. else
  6182. slot = 2;
  6183. }
  6184. if (slot == 1) {
  6185. if (have_left || have_right) {
  6186. row_y = row_bottom;
  6187. have_left = have_right = 0;
  6188. }
  6189. x = row_left;
  6190. w = avail;
  6191. } else if (slot == 2) {
  6192. if (have_left) {
  6193. row_y = row_bottom;
  6194. have_left = have_right = 0;
  6195. }
  6196. x = x0;
  6197. w = col0;
  6198. have_left = 1;
  6199. } else {
  6200. if (have_right) {
  6201. row_y = row_bottom;
  6202. have_left = have_right = 0;
  6203. }
  6204. x = x1;
  6205. w = col1;
  6206. have_right = 1;
  6207. }
  6208. cs.width_kind = 0;
  6209. cs.max_width_kind = 0;
  6210. l->left = x;
  6211. l->right = x + w;
  6212. if (l->right < l->left + 8)
  6213. l->right = l->left + 8;
  6214. l->y = row_y;
  6215. l->line_x = l->left;
  6216. l->run_x = l->left;
  6217. l->line_y = l->y;
  6218. l->line_h = 0;
  6219. l->nruns = 0;
  6220. l->space_pending = 0;
  6221. l->align = cs.align;
  6222. layout_block(l, n, &cs, depth + 1, lk);
  6223. if (l->y > row_bottom)
  6224. row_bottom = l->y;
  6225. n = nd->next;
  6226. }
  6227. l->left = row_left;
  6228. l->right = row_right;
  6229. l->y = row_bottom;
  6230. l->line_x = l->left;
  6231. l->run_x = l->left;
  6232. l->line_y = l->y;
  6233. l->line_h = 0;
  6234. l->nruns = 0;
  6235. l->space_pending = 0;
  6236. }
  6237. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  6238. * capped at four. Used by the project docs' card grids. */
  6239. static void layout_grid_auto(struct lay *l, unsigned int parent,
  6240. const struct br_style *pst, int depth,
  6241. unsigned short link)
  6242. {
  6243. unsigned int n, c;
  6244. int row_left = l->left, row_right = l->right;
  6245. int avail = row_right - row_left;
  6246. int gap = pst->grid_gap;
  6247. int minw = pst->width_kind == 1 ? pst->width : 200;
  6248. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  6249. if (avail < 32 || depth > 24) {
  6250. layout_children(l, parent, pst, depth, link);
  6251. return;
  6252. }
  6253. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  6254. struct br_node *nd = &doc.nodes[c];
  6255. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  6256. layout_children(l, parent, pst, depth, link);
  6257. return;
  6258. }
  6259. }
  6260. if (minw < 80)
  6261. minw = 80;
  6262. ncols = (avail + gap) / (minw + gap);
  6263. if (ncols < 1)
  6264. ncols = 1;
  6265. if (ncols > 4)
  6266. ncols = 4;
  6267. colw = (avail - gap * (ncols - 1)) / ncols;
  6268. if (colw < 24)
  6269. colw = 24;
  6270. x = row_left;
  6271. n = doc.nodes[parent].first;
  6272. while (n) {
  6273. struct br_node *nd = &doc.nodes[n];
  6274. struct br_style cs;
  6275. unsigned short lk = link;
  6276. int h;
  6277. if (nd->type == BR_NODE_TEXT) {
  6278. n = nd->next;
  6279. continue;
  6280. }
  6281. br_style_for(&doc, n, pst, &cs);
  6282. if (cs.display == BR_DISPLAY_NONE) {
  6283. n = nd->next;
  6284. continue;
  6285. }
  6286. if (nd->tag == BR_TAG_A && nd->href_off)
  6287. lk = (unsigned short)n;
  6288. cs.width_kind = 0;
  6289. cs.max_width_kind = 0;
  6290. l->left = x;
  6291. l->right = x + colw;
  6292. if (l->right < l->left + 8)
  6293. l->right = l->left + 8;
  6294. l->y = y;
  6295. l->line_x = l->left;
  6296. l->run_x = l->left;
  6297. l->line_y = l->y;
  6298. l->line_h = 0;
  6299. l->nruns = 0;
  6300. l->space_pending = 0;
  6301. l->align = cs.align;
  6302. layout_block(l, n, &cs, depth + 1, lk);
  6303. h = l->y - y;
  6304. if (h > row_h)
  6305. row_h = h;
  6306. col++;
  6307. n = nd->next;
  6308. if (col == ncols) {
  6309. y += row_h + gap;
  6310. x = row_left;
  6311. row_h = 0;
  6312. col = 0;
  6313. } else {
  6314. x += colw + gap;
  6315. }
  6316. }
  6317. if (col)
  6318. y += row_h;
  6319. else if (y > start_y)
  6320. y -= gap;
  6321. l->left = row_left;
  6322. l->right = row_right;
  6323. l->y = y;
  6324. l->line_x = l->left;
  6325. l->run_x = l->left;
  6326. l->line_y = l->y;
  6327. l->line_h = 0;
  6328. l->nruns = 0;
  6329. l->space_pending = 0;
  6330. }
  6331. /* Column widths are the widest cell in each column across every row, so all
  6332. * rows line up. The table model is still deliberately basic: no colspan,
  6333. * border-collapse or percentage columns. */
  6334. static void table_columns(struct lay *l, unsigned int table,
  6335. const struct br_style *pst, int avail,
  6336. int *raw, int maxcols, int *out_cols,
  6337. int *out_total)
  6338. {
  6339. unsigned int r, c;
  6340. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  6341. int fixed[12];
  6342. for (c = 0; c < (unsigned int)maxcols; c++) {
  6343. raw[c] = 0;
  6344. fixed[c] = 0;
  6345. }
  6346. /* Intrinsic widths of single-column cells. */
  6347. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  6348. struct br_node *rn = &doc.nodes[r];
  6349. int col = 0;
  6350. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  6351. continue;
  6352. for (c = rn->first; c; c = doc.nodes[c].next) {
  6353. struct br_node *cn = &doc.nodes[c];
  6354. struct br_style cs;
  6355. int w, span;
  6356. if (cn->type != BR_NODE_ELEM ||
  6357. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  6358. continue;
  6359. span = cn->colspan ? cn->colspan : 1;
  6360. br_style_for(&doc, c, pst, &cs);
  6361. if (cs.display == BR_DISPLAY_NONE)
  6362. continue;
  6363. if (col + span > maxcols)
  6364. span = maxcols - col;
  6365. if (span < 1)
  6366. break;
  6367. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  6368. mp_px(&cs, 7, avail) +
  6369. mp_px(&cs, 5, avail) +
  6370. mp_px(&cs, 3, avail) +
  6371. mp_px(&cs, 1, avail) +
  6372. cs.border_w[0] + cs.border_w[1] +
  6373. cs.border_w[2] + cs.border_w[3];
  6374. if (w < 24)
  6375. w = 24;
  6376. if (span == 1) {
  6377. if (w > raw[col])
  6378. raw[col] = w;
  6379. }
  6380. if (col + span > cols)
  6381. cols = col + span;
  6382. col += span;
  6383. }
  6384. }
  6385. /* A colspan cell only has to be as wide as the sum of its columns. */
  6386. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  6387. struct br_node *rn = &doc.nodes[r];
  6388. int col = 0;
  6389. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  6390. continue;
  6391. for (c = rn->first; c; c = doc.nodes[c].next) {
  6392. struct br_node *cn = &doc.nodes[c];
  6393. struct br_style cs;
  6394. int span, w, sum, i;
  6395. if (cn->type != BR_NODE_ELEM ||
  6396. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  6397. continue;
  6398. span = cn->colspan ? cn->colspan : 1;
  6399. if (col + span > maxcols)
  6400. span = maxcols - col;
  6401. if (span < 1)
  6402. break;
  6403. if (span > 1) {
  6404. br_style_for(&doc, c, pst, &cs);
  6405. if (cs.display != BR_DISPLAY_NONE) {
  6406. w = intrinsic_width(l->ui, c, &cs,
  6407. 0, avail) +
  6408. mp_px(&cs, 7, avail) +
  6409. mp_px(&cs, 5, avail) +
  6410. mp_px(&cs, 3, avail) +
  6411. mp_px(&cs, 1, avail) +
  6412. cs.border_w[0] + cs.border_w[1] +
  6413. cs.border_w[2] + cs.border_w[3];
  6414. sum = 0;
  6415. for (i = 0; i < span; i++)
  6416. sum += raw[col + i];
  6417. if (w > sum)
  6418. raw[col + span - 1] += w - sum;
  6419. }
  6420. }
  6421. col += span;
  6422. }
  6423. }
  6424. /* Explicit and percentage widths override intrinsic widths. */
  6425. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  6426. struct br_node *rn = &doc.nodes[r];
  6427. int col = 0;
  6428. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  6429. continue;
  6430. for (c = rn->first; c; c = doc.nodes[c].next) {
  6431. struct br_node *cn = &doc.nodes[c];
  6432. struct br_style cs;
  6433. int span;
  6434. if (cn->type != BR_NODE_ELEM ||
  6435. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  6436. continue;
  6437. span = cn->colspan ? cn->colspan : 1;
  6438. if (col + span > maxcols)
  6439. span = maxcols - col;
  6440. if (span < 1)
  6441. break;
  6442. if (span == 1) {
  6443. br_style_for(&doc, c, pst, &cs);
  6444. if (cs.display != BR_DISPLAY_NONE) {
  6445. if (cs.width_kind == 1) {
  6446. raw[col] = cs.width;
  6447. fixed[col] = 1;
  6448. } else if (cs.width_kind == 2 ||
  6449. cs.width_kind == 3) {
  6450. raw[col] = style_width_px(&cs,
  6451. avail);
  6452. fixed[col] = 1;
  6453. }
  6454. }
  6455. }
  6456. col += span;
  6457. }
  6458. }
  6459. for (c = 0; c < (unsigned int)cols; c++) {
  6460. if (raw[c] < 8)
  6461. raw[c] = 8;
  6462. total += raw[c];
  6463. if (fixed[c])
  6464. fixed_sum += raw[c];
  6465. else {
  6466. free_raw += raw[c];
  6467. free_cols++;
  6468. }
  6469. }
  6470. if (fixed_sum > 0 && fixed_sum < avail) {
  6471. int free_avail = avail - fixed_sum;
  6472. int i;
  6473. if (free_raw > 0) {
  6474. for (i = 0; i < cols; i++)
  6475. if (!fixed[i])
  6476. raw[i] = free_avail * raw[i] /
  6477. free_raw;
  6478. } else if (free_cols > 0) {
  6479. for (i = 0; i < cols; i++)
  6480. if (!fixed[i])
  6481. raw[i] = free_avail / free_cols;
  6482. }
  6483. total = 0;
  6484. for (i = 0; i < cols; i++)
  6485. total += raw[i];
  6486. } else if (total < avail && total > 0) {
  6487. int i;
  6488. for (i = 0; i < cols; i++)
  6489. raw[i] = raw[i] * avail / total;
  6490. total = 0;
  6491. for (i = 0; i < cols; i++)
  6492. total += raw[i];
  6493. }
  6494. *out_cols = cols;
  6495. *out_total = total;
  6496. }
  6497. static void layout_table_row(struct lay *l, unsigned int row,
  6498. const struct br_style *pst, int depth,
  6499. unsigned short link)
  6500. {
  6501. unsigned int n, cell[12];
  6502. int raw[12], colstart[12], colspan[12];
  6503. int prefix[13];
  6504. int ncell = 0, total = 0, cols = 0, col = 0;
  6505. int row_left = l->left, row_right = l->right;
  6506. int avail = row_right - row_left;
  6507. int y = l->y, bottom = l->y;
  6508. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  6509. struct br_node *nd = &doc.nodes[n];
  6510. struct br_style cs;
  6511. int span;
  6512. if (nd->type == BR_NODE_TEXT) {
  6513. if (text_node_blank(nd))
  6514. continue;
  6515. layout_children(l, row, pst, depth, link);
  6516. return;
  6517. }
  6518. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  6519. layout_children(l, row, pst, depth, link);
  6520. return;
  6521. }
  6522. br_style_for(&doc, n, pst, &cs);
  6523. if (cs.display == BR_DISPLAY_NONE)
  6524. continue;
  6525. if (ncell >= 12) {
  6526. layout_children(l, row, pst, depth, link);
  6527. return;
  6528. }
  6529. span = nd->colspan ? nd->colspan : 1;
  6530. if (span > 12 - col)
  6531. span = 12 - col;
  6532. if (span < 1)
  6533. continue;
  6534. cell[ncell] = n;
  6535. colstart[ncell] = col;
  6536. colspan[ncell] = span;
  6537. col += span;
  6538. ncell++;
  6539. }
  6540. if (ncell < 1 || avail < 32) {
  6541. layout_children(l, row, pst, depth, link);
  6542. return;
  6543. }
  6544. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  6545. &total);
  6546. if (cols < 2 || total <= 0) {
  6547. int c;
  6548. total = 0;
  6549. for (c = 0; c < ncell; c++) {
  6550. struct br_style cs;
  6551. br_style_for(&doc, cell[c], pst, &cs);
  6552. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  6553. avail) +
  6554. mp_px(&cs, 7, avail) +
  6555. mp_px(&cs, 5, avail) +
  6556. mp_px(&cs, 3, avail) +
  6557. mp_px(&cs, 1, avail);
  6558. if (raw[c] < 24)
  6559. raw[c] = 24;
  6560. total += raw[c];
  6561. }
  6562. /* A one-column table still has to fill its own width; the
  6563. * intrinsic fallback above otherwise leaves the cell at its
  6564. * text width (HN's outer table and nested story table). */
  6565. if (total > 0 && total < avail) {
  6566. int c;
  6567. for (c = 0; c < ncell; c++)
  6568. raw[c] = raw[c] * avail / total;
  6569. total = avail;
  6570. }
  6571. }
  6572. prefix[0] = row_left;
  6573. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  6574. prefix[n + 1] = prefix[n] + raw[n];
  6575. for (n = 0; n < (unsigned int)ncell; n++) {
  6576. struct br_style cs;
  6577. int start = colstart[n];
  6578. int end = start + colspan[n];
  6579. int w;
  6580. if (end > cols)
  6581. end = cols;
  6582. if (start >= cols)
  6583. continue;
  6584. w = prefix[end] - prefix[start];
  6585. br_style_for(&doc, cell[n], pst, &cs);
  6586. /* The column width already reflects the cell's width property. */
  6587. cs.width_kind = 0;
  6588. cs.max_width_kind = 0;
  6589. if (w < 24)
  6590. w = 24;
  6591. if (w < 8)
  6592. w = 8;
  6593. l->left = prefix[start];
  6594. l->right = l->left + w;
  6595. l->y = y;
  6596. l->line_x = l->left;
  6597. l->run_x = l->left;
  6598. l->line_y = l->y;
  6599. l->line_h = 0;
  6600. l->nruns = 0;
  6601. l->space_pending = 0;
  6602. l->align = cs.align;
  6603. layout_block(l, cell[n], &cs, depth + 1, link);
  6604. if (l->y > bottom)
  6605. bottom = l->y;
  6606. }
  6607. l->left = row_left;
  6608. l->right = row_right;
  6609. l->y = bottom;
  6610. l->line_x = l->left;
  6611. l->run_x = l->left;
  6612. l->line_y = l->y;
  6613. l->line_h = 0;
  6614. l->nruns = 0;
  6615. l->space_pending = 0;
  6616. }
  6617. #define TBL_MAX_ROWS 32
  6618. #define TBL_MAX_COLS 12
  6619. #define TBL_MAX_CELLS 128
  6620. struct tbl_cell {
  6621. unsigned int node;
  6622. unsigned char row, col, rowspan, colspan;
  6623. int height;
  6624. };
  6625. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  6626. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  6627. static int table_active;
  6628. static int table_has_rowspan(unsigned int table)
  6629. {
  6630. unsigned int r, c;
  6631. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  6632. struct br_node *rn = &doc.nodes[r];
  6633. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  6634. continue;
  6635. for (c = rn->first; c; c = doc.nodes[c].next) {
  6636. struct br_node *cn = &doc.nodes[c];
  6637. if (cn->type == BR_NODE_ELEM &&
  6638. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  6639. cn->rowspan > 1)
  6640. return 1;
  6641. }
  6642. }
  6643. return 0;
  6644. }
  6645. static void table_cell_style(unsigned int row, unsigned int cell,
  6646. const struct br_style *st, struct br_style *out)
  6647. {
  6648. struct br_style trs;
  6649. br_style_for(&doc, row, st, &trs);
  6650. br_style_for(&doc, cell, &trs, out);
  6651. }
  6652. /* Tables that use rowspan need row heights before anything is painted. This
  6653. * path builds a small occupancy grid, measures the natural cell heights, then
  6654. * lays every cell out at its row/column position. Tables without rowspan
  6655. * keep the lighter per-row path in layout_table_row(). */
  6656. static void layout_table(struct lay *l, unsigned int table,
  6657. const struct br_style *st, int depth,
  6658. unsigned short link)
  6659. {
  6660. unsigned int rows[TBL_MAX_ROWS];
  6661. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  6662. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  6663. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  6664. int free_raw = 0, free_cols = 0;
  6665. int table_left = l->left, table_right = l->right;
  6666. int top = l->y, avail = table_right - table_left;
  6667. unsigned int r, c;
  6668. int i, rr, cc;
  6669. if (depth > 24 || table_active) {
  6670. layout_children(l, table, st, depth, link);
  6671. return;
  6672. }
  6673. table_active = 1;
  6674. for (r = doc.nodes[table].first;
  6675. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  6676. struct br_node *rn = &doc.nodes[r];
  6677. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  6678. rows[nrows++] = r;
  6679. }
  6680. if (!nrows) {
  6681. table_active = 0;
  6682. layout_children(l, table, st, depth, link);
  6683. return;
  6684. }
  6685. for (rr = 0; rr < nrows; rr++)
  6686. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  6687. tbl_at[rr][cc] = 0;
  6688. for (rr = 0; rr < nrows; rr++) {
  6689. int col = 0;
  6690. for (c = doc.nodes[rows[rr]].first; c;
  6691. c = doc.nodes[c].next) {
  6692. struct br_node *cn = &doc.nodes[c];
  6693. struct br_style cs;
  6694. int rs, csn;
  6695. if (cn->type != BR_NODE_ELEM ||
  6696. (cn->tag != BR_TAG_TD &&
  6697. cn->tag != BR_TAG_TH))
  6698. continue;
  6699. table_cell_style(rows[rr], c, st, &cs);
  6700. if (cs.display == BR_DISPLAY_NONE)
  6701. continue;
  6702. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  6703. col++;
  6704. if (col >= TBL_MAX_COLS)
  6705. break;
  6706. rs = cn->rowspan ? cn->rowspan : 1;
  6707. csn = cn->colspan ? cn->colspan : 1;
  6708. if (rr + rs > nrows)
  6709. rs = nrows - rr;
  6710. if (col + csn > TBL_MAX_COLS)
  6711. csn = TBL_MAX_COLS - col;
  6712. if (rs < 1 || csn < 1)
  6713. continue;
  6714. if (ncells >= TBL_MAX_CELLS)
  6715. break;
  6716. tbl_cells[ncells].node = c;
  6717. tbl_cells[ncells].row = (unsigned char)rr;
  6718. tbl_cells[ncells].col = (unsigned char)col;
  6719. tbl_cells[ncells].rowspan = (unsigned char)rs;
  6720. tbl_cells[ncells].colspan = (unsigned char)csn;
  6721. tbl_cells[ncells].height = 0;
  6722. for (i = rr; i < rr + rs; i++)
  6723. for (int j = col; j < col + csn; j++)
  6724. tbl_at[i][j] =
  6725. (unsigned short)(ncells + 1);
  6726. ncells++;
  6727. col += csn;
  6728. if (col > cols)
  6729. cols = col;
  6730. }
  6731. }
  6732. if (!ncells || cols < 1) {
  6733. table_active = 0;
  6734. layout_children(l, table, st, depth, link);
  6735. return;
  6736. }
  6737. for (i = 0; i < cols; i++) {
  6738. raw[i] = 0;
  6739. fixed[i] = 0;
  6740. }
  6741. /* Intrinsic widths of single-column cells. */
  6742. for (i = 0; i < ncells; i++) {
  6743. struct br_style cs;
  6744. int w;
  6745. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  6746. st, &cs);
  6747. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  6748. mp_px(&cs, 7, avail) +
  6749. mp_px(&cs, 5, avail) +
  6750. mp_px(&cs, 3, avail) +
  6751. mp_px(&cs, 1, avail) +
  6752. cs.border_w[0] + cs.border_w[1] +
  6753. cs.border_w[2] + cs.border_w[3];
  6754. if (w < 24)
  6755. w = 24;
  6756. if (tbl_cells[i].colspan == 1) {
  6757. int col = tbl_cells[i].col;
  6758. if (w > raw[col])
  6759. raw[col] = w;
  6760. }
  6761. }
  6762. /* A spanning cell only needs the sum of its columns to be large
  6763. * enough; put the deficit in the last column. */
  6764. for (i = 0; i < ncells; i++) {
  6765. struct br_style cs;
  6766. int w, sum, col, span;
  6767. if (tbl_cells[i].colspan < 2)
  6768. continue;
  6769. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  6770. st, &cs);
  6771. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  6772. mp_px(&cs, 7, avail) +
  6773. mp_px(&cs, 5, avail) +
  6774. mp_px(&cs, 3, avail) +
  6775. mp_px(&cs, 1, avail) +
  6776. cs.border_w[0] + cs.border_w[1] +
  6777. cs.border_w[2] + cs.border_w[3];
  6778. col = tbl_cells[i].col;
  6779. span = tbl_cells[i].colspan;
  6780. sum = 0;
  6781. for (int j = 0; j < span; j++)
  6782. sum += raw[col + j];
  6783. if (w > sum)
  6784. raw[col + span - 1] += w - sum;
  6785. }
  6786. /* Explicit/percentage widths, as in table_columns(). */
  6787. for (i = 0; i < ncells; i++) {
  6788. struct br_style cs;
  6789. int col;
  6790. if (tbl_cells[i].colspan != 1)
  6791. continue;
  6792. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  6793. st, &cs);
  6794. col = tbl_cells[i].col;
  6795. if (cs.width_kind == 1) {
  6796. raw[col] = cs.width;
  6797. fixed[col] = 1;
  6798. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  6799. raw[col] = style_width_px(&cs, avail);
  6800. fixed[col] = 1;
  6801. }
  6802. }
  6803. for (i = 0; i < cols; i++) {
  6804. if (raw[i] < 8)
  6805. raw[i] = 8;
  6806. total += raw[i];
  6807. if (fixed[i])
  6808. fixed_sum += raw[i];
  6809. else {
  6810. free_raw += raw[i];
  6811. free_cols++;
  6812. }
  6813. }
  6814. if (fixed_sum > 0 && fixed_sum < avail) {
  6815. int free_avail = avail - fixed_sum;
  6816. if (free_raw > 0) {
  6817. for (i = 0; i < cols; i++)
  6818. if (!fixed[i])
  6819. raw[i] = free_avail * raw[i] /
  6820. free_raw;
  6821. } else if (free_cols > 0) {
  6822. for (i = 0; i < cols; i++)
  6823. if (!fixed[i])
  6824. raw[i] = free_avail / free_cols;
  6825. }
  6826. } else if (total < avail && total > 0) {
  6827. for (i = 0; i < cols; i++)
  6828. raw[i] = raw[i] * avail / total;
  6829. }
  6830. prefix[0] = table_left;
  6831. for (i = 0; i < cols; i++)
  6832. prefix[i + 1] = prefix[i] + raw[i];
  6833. /* Measure natural cell heights with the column widths. */
  6834. for (i = 0; i < ncells; i++) {
  6835. struct br_style cs;
  6836. int col = tbl_cells[i].col;
  6837. int span = tbl_cells[i].colspan;
  6838. int w = prefix[col + span] - prefix[col];
  6839. int sl = l->left, sr = l->right, sy = l->y;
  6840. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  6841. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  6842. int sal = l->align, sdraw = l->draw;
  6843. struct ngui *sui = l->ui;
  6844. if (w < 8)
  6845. w = 8;
  6846. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  6847. st, &cs);
  6848. cs.width_kind = 0;
  6849. cs.max_width_kind = 0;
  6850. l->draw = 0;
  6851. l->ui = 0;
  6852. l->left = prefix[col];
  6853. l->right = l->left + w;
  6854. l->y = 0;
  6855. l->line_x = l->left;
  6856. l->run_x = l->left;
  6857. l->line_y = 0;
  6858. l->line_h = 0;
  6859. l->nruns = 0;
  6860. l->space_pending = 0;
  6861. l->align = cs.align;
  6862. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  6863. tbl_cells[i].height = block_h[tbl_cells[i].node];
  6864. l->left = sl;
  6865. l->right = sr;
  6866. l->y = sy;
  6867. l->line_x = slx;
  6868. l->run_x = srx;
  6869. l->line_y = sly;
  6870. l->line_h = slh;
  6871. l->nruns = snr;
  6872. l->space_pending = ssp;
  6873. l->align = sal;
  6874. l->draw = sdraw;
  6875. l->ui = sui;
  6876. }
  6877. for (i = 0; i < nrows; i++)
  6878. rowh[i] = 0;
  6879. for (i = 0; i < ncells; i++) {
  6880. int row = tbl_cells[i].row;
  6881. if (tbl_cells[i].rowspan == 1) {
  6882. if (tbl_cells[i].height > rowh[row])
  6883. rowh[row] = tbl_cells[i].height;
  6884. }
  6885. }
  6886. for (i = 0; i < ncells; i++) {
  6887. int row = tbl_cells[i].row;
  6888. int span = tbl_cells[i].rowspan;
  6889. int sum = 0;
  6890. if (span < 2)
  6891. continue;
  6892. for (int j = 0; j < span; j++)
  6893. sum += rowh[row + j];
  6894. if (sum < tbl_cells[i].height)
  6895. rowh[row + span - 1] +=
  6896. tbl_cells[i].height - sum;
  6897. }
  6898. for (i = 0; i < nrows; i++)
  6899. if (rowh[i] < 8)
  6900. rowh[i] = 8;
  6901. rowy[0] = top;
  6902. for (i = 1; i < nrows; i++)
  6903. rowy[i] = rowy[i - 1] + rowh[i - 1];
  6904. if (!l->draw) {
  6905. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  6906. table_active = 0;
  6907. return;
  6908. }
  6909. for (i = 0; i < ncells; i++) {
  6910. struct br_style cs;
  6911. int col = tbl_cells[i].col;
  6912. int span = tbl_cells[i].colspan;
  6913. int row = tbl_cells[i].row;
  6914. int rspan = tbl_cells[i].rowspan;
  6915. int w = prefix[col + span] - prefix[col];
  6916. int h = 0;
  6917. int sl = l->left, sr = l->right, sy = l->y;
  6918. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  6919. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  6920. int sal = l->align;
  6921. int deco;
  6922. for (int j = 0; j < rspan; j++)
  6923. h += rowh[row + j];
  6924. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  6925. cs.width_kind = 0;
  6926. cs.max_width_kind = 0;
  6927. cs.box_sizing = 0;
  6928. deco = mp_px(&cs, 4, avail) +
  6929. mp_px(&cs, 6, avail) +
  6930. cs.border_w[0] + cs.border_w[2];
  6931. cs.height_kind = 1;
  6932. cs.height = h > deco ? h - deco : 0;
  6933. /* The block painter reads block_h[] from the measure pass; make
  6934. * the table cell fill its row/rowspan, not just its content. */
  6935. if (h > 0 && h < 65536)
  6936. block_h[tbl_cells[i].node] = (unsigned short)h;
  6937. l->left = prefix[col];
  6938. l->right = l->left + w;
  6939. l->y = rowy[row];
  6940. l->line_x = l->left;
  6941. l->run_x = l->left;
  6942. l->line_y = l->y;
  6943. l->line_h = 0;
  6944. l->nruns = 0;
  6945. l->space_pending = 0;
  6946. l->align = cs.align;
  6947. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  6948. l->left = sl;
  6949. l->right = sr;
  6950. l->y = sy;
  6951. l->line_x = slx;
  6952. l->run_x = srx;
  6953. l->line_y = sly;
  6954. l->line_h = slh;
  6955. l->nruns = snr;
  6956. l->space_pending = ssp;
  6957. l->align = sal;
  6958. }
  6959. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  6960. table_active = 0;
  6961. }
  6962. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  6963. * flow so they sit above it, like CSS painting order. Their flow origin is
  6964. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  6965. struct br_deferred {
  6966. unsigned int node;
  6967. int flow_y, flow_left, flow_right;
  6968. unsigned short link;
  6969. signed short z_index;
  6970. unsigned char z_set;
  6971. unsigned int order;
  6972. };
  6973. static struct br_deferred deferred[16];
  6974. static int ndeferred;
  6975. static void layout_children(struct lay *l, unsigned int parent,
  6976. const struct br_style *pst, int depth,
  6977. unsigned short link)
  6978. {
  6979. unsigned int n;
  6980. if (depth > 24)
  6981. return;
  6982. n = doc.nodes[parent].first;
  6983. while (n) {
  6984. struct br_node *nd = &doc.nodes[n];
  6985. struct br_style cs;
  6986. unsigned short lk = link;
  6987. if (nd->type == BR_NODE_TEXT) {
  6988. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  6989. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  6990. n = nd->next;
  6991. continue;
  6992. }
  6993. br_style_for(&doc, n, pst, &cs);
  6994. if (cs.display == BR_DISPLAY_NONE) {
  6995. n = nd->next;
  6996. continue;
  6997. }
  6998. if (cs.clear && l->float_active) {
  6999. flush_line(l);
  7000. if (l->y < l->float_bottom)
  7001. l->y = l->float_bottom;
  7002. l->float_active = 0;
  7003. l->line_x = l->left;
  7004. l->run_x = l->left;
  7005. l->line_left = l->left;
  7006. l->line_right = l->right;
  7007. l->line_y = l->y;
  7008. l->line_h = 0;
  7009. l->nruns = 0;
  7010. l->space_pending = 0;
  7011. }
  7012. if (nd->tag == BR_TAG_A && nd->href_off)
  7013. lk = (unsigned short)n;
  7014. if (cs.pos == 1 || cs.pos == 2 ||
  7015. (cs.pos == 3 && cs.z_set)) {
  7016. if (cs.pos == 3 && l->draw && ndeferred < 16) {
  7017. /* Relative z-index: measure and advance the flow
  7018. * without painting, then paint it in the
  7019. * deferred (stacked) pass. */
  7020. int fy = l->y, fl = l->left, fr = l->right;
  7021. int save_draw = l->draw;
  7022. l->draw = 0;
  7023. layout_block(l, n, &cs, depth + 1, lk);
  7024. l->draw = save_draw;
  7025. deferred[ndeferred].node = n;
  7026. deferred[ndeferred].flow_y = fy;
  7027. deferred[ndeferred].flow_left = fl;
  7028. deferred[ndeferred].flow_right = fr;
  7029. deferred[ndeferred].link = lk;
  7030. deferred[ndeferred].z_index = cs.z_index;
  7031. deferred[ndeferred].z_set = cs.z_set;
  7032. deferred[ndeferred].order = (unsigned int)ndeferred;
  7033. ndeferred++;
  7034. } else if (l->draw && ndeferred < 16) {
  7035. deferred[ndeferred].node = n;
  7036. deferred[ndeferred].flow_y = l->y;
  7037. deferred[ndeferred].flow_left = l->left;
  7038. deferred[ndeferred].flow_right = l->right;
  7039. deferred[ndeferred].link = lk;
  7040. deferred[ndeferred].z_index = cs.z_index;
  7041. deferred[ndeferred].z_set = cs.z_set;
  7042. deferred[ndeferred].order = (unsigned int)ndeferred;
  7043. ndeferred++;
  7044. } else {
  7045. layout_block(l, n, &cs, depth + 1, lk);
  7046. }
  7047. if (cs.pos == 1 && block_h[n] &&
  7048. doc.nodes[n].class_off) {
  7049. const char *cl = doc.attrs +
  7050. doc.nodes[n].class_off;
  7051. if ((contains_ci(cl, "poster-wrapper") ||
  7052. contains_ci(cl, "ts-picture")) &&
  7053. !has_skeleton_sibling(n))
  7054. l->y += block_h[n];
  7055. }
  7056. n = nd->next;
  7057. continue;
  7058. }
  7059. if (nd->tag == BR_TAG_BR) {
  7060. flush_line(l);
  7061. n = nd->next;
  7062. continue;
  7063. }
  7064. if (nd->tag == BR_TAG_HR) {
  7065. flush_line(l);
  7066. if (l->draw)
  7067. ngui_fill_rect(l->ui,
  7068. (struct ngui_rect){l->left, l->y + 2,
  7069. l->right - l->left, 1}, BR_GRAY);
  7070. l->y += 8;
  7071. n = nd->next;
  7072. continue;
  7073. }
  7074. if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  7075. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) {
  7076. if (!(nd->tag == BR_TAG_INPUT &&
  7077. s_eq(br_type(&doc, n), "hidden")))
  7078. add_form_run(l, n, &cs, lk);
  7079. n = nd->next;
  7080. continue;
  7081. }
  7082. if (nd->tag == BR_TAG_IMG) {
  7083. add_image_run(l, n, &cs, lk);
  7084. n = nd->next;
  7085. continue;
  7086. }
  7087. if (nd->tag == BR_TAG_VIDEO) {
  7088. layout_block(l, n, &cs, depth + 1, lk);
  7089. n = nd->next;
  7090. continue;
  7091. }
  7092. if (cs.float_left) {
  7093. n = layout_float_group(l, n, pst, depth, lk);
  7094. continue;
  7095. }
  7096. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  7097. n = layout_inline_blocks(l, n, pst, depth, link);
  7098. continue;
  7099. }
  7100. if (cs.display == BR_DISPLAY_BLOCK || br_tag_is_block(nd->tag))
  7101. layout_block(l, n, &cs, depth + 1, lk);
  7102. else {
  7103. layout_children(l, n, &cs, depth + 1, lk);
  7104. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  7105. l->space_pending = 1;
  7106. }
  7107. n = nd->next;
  7108. }
  7109. }
  7110. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  7111. * runs and a recursive page can otherwise overflow the stack. */
  7112. static struct lay layout_state;
  7113. static int measure_page(int left, int right)
  7114. {
  7115. struct lay *l = &layout_state;
  7116. struct br_style base = base_style();
  7117. unsigned int i;
  7118. for (i = 0; i < BR_MAX_NODES; i++) {
  7119. block_h[i] = 0;
  7120. img_top[i] = 0;
  7121. img_h[i] = 0;
  7122. layout_boxes[i].valid = 0;
  7123. }
  7124. memset(li_marker, 0, sizeof(li_marker));
  7125. l->draw = 0;
  7126. l->ui = &ui;
  7127. l->left = left;
  7128. l->right = right;
  7129. l->y = 0;
  7130. l->line_x = left;
  7131. l->run_x = left;
  7132. l->line_left = left;
  7133. l->line_right = right;
  7134. l->line_y = 0;
  7135. l->line_h = 0;
  7136. l->align = BR_ALIGN_LEFT;
  7137. l->float_active = 0;
  7138. l->parent_top = 0;
  7139. l->depth = 0;
  7140. l->nruns = 0;
  7141. l->space_pending = 0;
  7142. layout_children(l, doc.root, &base, 0, 0);
  7143. return l->y + 8;
  7144. }
  7145. static int deferred_cmp(const struct br_deferred *a,
  7146. const struct br_deferred *b)
  7147. {
  7148. int az = a->z_set ? a->z_index : 0;
  7149. int bz = b->z_set ? b->z_index : 0;
  7150. if (az != bz)
  7151. return az < bz ? -1 : 1;
  7152. if (a->order != b->order)
  7153. return a->order < b->order ? -1 : 1;
  7154. return 0;
  7155. }
  7156. static void sort_deferred(void)
  7157. {
  7158. int i;
  7159. for (i = 1; i < ndeferred; i++) {
  7160. struct br_deferred key = deferred[i];
  7161. int j = i;
  7162. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  7163. deferred[j] = deferred[j - 1];
  7164. j--;
  7165. }
  7166. deferred[j] = key;
  7167. }
  7168. }
  7169. static void render_page(int left, int right, int y0)
  7170. {
  7171. struct lay *l = &layout_state;
  7172. struct br_style base = base_style();
  7173. l->draw = 1;
  7174. l->ui = &ui;
  7175. l->left = left;
  7176. l->right = right;
  7177. l->y = y0;
  7178. l->line_x = left;
  7179. l->run_x = left;
  7180. l->line_left = left;
  7181. l->line_right = right;
  7182. l->line_y = y0;
  7183. l->line_h = 0;
  7184. l->align = BR_ALIGN_LEFT;
  7185. l->float_active = 0;
  7186. l->parent_top = 0;
  7187. l->depth = 0;
  7188. l->nruns = 0;
  7189. l->space_pending = 0;
  7190. nhits = 0;
  7191. ndeferred = 0;
  7192. layout_children(l, doc.root, &base, 0, 0);
  7193. sort_deferred();
  7194. {
  7195. int i;
  7196. for (i = 0; i < ndeferred; i++) {
  7197. struct br_style st;
  7198. br_style_for(&doc, deferred[i].node, &base, &st);
  7199. if (st.display == BR_DISPLAY_NONE)
  7200. continue;
  7201. l->draw = 1;
  7202. l->left = deferred[i].flow_left;
  7203. l->right = deferred[i].flow_right;
  7204. l->y = deferred[i].flow_y;
  7205. l->line_x = l->left;
  7206. l->run_x = l->left;
  7207. l->line_y = l->y;
  7208. l->line_h = 0;
  7209. l->nruns = 0;
  7210. l->space_pending = 0;
  7211. l->align = st.align;
  7212. if (st.pos == 2 && block_h[deferred[i].node]) {
  7213. struct ngui_rect clip;
  7214. int ch = block_h[deferred[i].node] + 24;
  7215. clip.x = page_rect.x;
  7216. clip.y = page_rect.y;
  7217. clip.w = page_rect.w - 12;
  7218. if (ch > page_rect.h)
  7219. ch = page_rect.h;
  7220. clip.h = ch;
  7221. ngui_push_clip(&ui, clip);
  7222. if (st.has_bg)
  7223. ngui_fill_rect(&ui, clip, st.bg);
  7224. layout_block(l, deferred[i].node, &st, 0,
  7225. deferred[i].link);
  7226. ngui_pop_clip(&ui);
  7227. } else {
  7228. layout_block(l, deferred[i].node, &st, 0,
  7229. deferred[i].link);
  7230. }
  7231. }
  7232. }
  7233. }
  7234. /* ---- UI ---- */
  7235. static int find_hit(int x, int y)
  7236. {
  7237. int i;
  7238. for (i = nhits - 1; i >= 0; i--) {
  7239. struct hit *h = &hits[i];
  7240. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  7241. y < h->y + h->h)
  7242. return (int)h->node;
  7243. }
  7244. return 0;
  7245. }
  7246. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  7247. {
  7248. int x = r.x + 4, y = r.y + 4, h = 22;
  7249. int compact = r.w < 560;
  7250. int go_w = r.w < 420 ? 32 : 42;
  7251. int in_x, in_w, res;
  7252. ngui_fill_rect(&ui, r, ui.theme.panel);
  7253. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  7254. ui.theme.border);
  7255. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  7256. NGUI_ICON_CHEVRON_LEFT))
  7257. *action |= ACT_BACK;
  7258. x += 32;
  7259. if (!compact) {
  7260. if (ngui_icon_button(&ui, ID_FORWARD,
  7261. (struct ngui_rect){x, y, 28, h},
  7262. NGUI_ICON_CHEVRON_RIGHT))
  7263. *action |= ACT_FORWARD;
  7264. x += 32;
  7265. }
  7266. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  7267. NGUI_ICON_REFRESH))
  7268. *action |= ACT_RELOAD;
  7269. x += 32;
  7270. if (!compact) {
  7271. if (ngui_icon_button(&ui, ID_HOME,
  7272. (struct ngui_rect){x, y, 28, h},
  7273. NGUI_ICON_HOME))
  7274. *action |= ACT_HOME;
  7275. x += 32;
  7276. }
  7277. in_x = x + 2;
  7278. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  7279. if (in_w < 60)
  7280. in_w = 60;
  7281. res = ngui_text_input(&ui, ID_URL,
  7282. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  7283. if (res & NGUI_INPUT_SUBMIT)
  7284. *action |= ACT_NAV;
  7285. if (res & NGUI_INPUT_CANCEL)
  7286. ngui_set_focus(&ui, 0);
  7287. if (ngui_button(&ui, ID_GO,
  7288. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  7289. "Go"))
  7290. *action |= ACT_NAV;
  7291. }
  7292. static int page_hover_node(void)
  7293. {
  7294. if (!ui.inside)
  7295. return 0;
  7296. if (ui.mouse_x < page_rect.x ||
  7297. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  7298. ui.mouse_y < page_rect.y ||
  7299. ui.mouse_y >= page_rect.y + page_rect.h)
  7300. return 0;
  7301. return find_hit(ui.mouse_x, ui.mouse_y);
  7302. }
  7303. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  7304. {
  7305. int x, y, w = page.w, h = page.h;
  7306. if (!src || w <= 0 || h <= 0)
  7307. return;
  7308. for (y = 0; y < h; y++) {
  7309. unsigned short *s = src + (page.y + y) * sw + page.x;
  7310. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  7311. for (x = 0; x + 1 < w; x += 2) {
  7312. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  7313. }
  7314. if (x < w)
  7315. d[x] = s[x];
  7316. }
  7317. }
  7318. static void draw_page(struct ngui_rect page)
  7319. {
  7320. int left, right, ch;
  7321. int old_panel, old_dim;
  7322. unsigned short *saved_px;
  7323. unsigned short page_bg = ui.theme.bg;
  7324. int saved_w, saved_h, use_buf;
  7325. page_rect = page;
  7326. {
  7327. unsigned int root = doc.nnode > 1 ?
  7328. br_find_tag(&doc, BR_TAG_HTML) : 0;
  7329. unsigned int body = doc.nnode > 1 ?
  7330. br_find_tag(&doc, BR_TAG_BODY) : 0;
  7331. struct br_style bs;
  7332. if (root) {
  7333. style_for_node(root - 1, &bs);
  7334. if (bs.has_bg)
  7335. page_bg = bs.bg;
  7336. }
  7337. if (body) {
  7338. style_for_node(body - 1, &bs);
  7339. if (bs.has_bg)
  7340. page_bg = bs.bg;
  7341. }
  7342. }
  7343. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  7344. page_cache_valid && layout_valid &&
  7345. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  7346. !(ui.scroll_y &&
  7347. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  7348. page_scroll.offset == page_cache_scroll &&
  7349. page_cache_nnode == doc.nnode &&
  7350. page_cache_x == page.x && page_cache_y == page.y &&
  7351. page_cache_w == page.w && page_cache_h == page.h) {
  7352. blit_page(page, page_backbuf, pagebuf_w);
  7353. return;
  7354. }
  7355. ngui_fill_rect(&ui, page, page_bg);
  7356. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  7357. const char *s = page_loading ? "Loading..." : "No page";
  7358. int w = (int)ngui_text_width_ui(&ui, s);
  7359. ngui_text(&ui, page.x + (page.w - w) / 2,
  7360. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  7361. page_scroll.content_h = 0;
  7362. page_scroll.view_h = page.h;
  7363. page_cache_valid = 0;
  7364. return;
  7365. }
  7366. if (page.w < 40 || page.h < 40) {
  7367. page_cache_valid = 0;
  7368. return;
  7369. }
  7370. saved_px = ui.px;
  7371. saved_w = ui.w;
  7372. saved_h = ui.h;
  7373. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  7374. if (use_buf) {
  7375. ui.px = page_backbuf;
  7376. ui.w = pagebuf_w;
  7377. ui.h = pagebuf_h;
  7378. ngui_fill_rect(&ui, page, page_bg);
  7379. }
  7380. left = page.x + 8;
  7381. right = page.x + page.w - 16;
  7382. if (!layout_valid || left != layout_left || right != layout_right ||
  7383. layout_nnode != doc.nnode) {
  7384. layout_content_h = measure_page(left, right);
  7385. layout_valid = 1;
  7386. layout_left = left;
  7387. layout_right = right;
  7388. layout_nnode = doc.nnode;
  7389. }
  7390. ch = layout_content_h;
  7391. page_scroll.content_h = ch;
  7392. page_scroll.view_h = page.h;
  7393. ngui_scroll_begin(&ui, page, &page_scroll);
  7394. ngui_scroll_wheel(&ui, page, &page_scroll);
  7395. render_page(left, right, page.y + 4 - page_scroll.offset);
  7396. old_panel = ui.theme.panel_alt;
  7397. old_dim = ui.theme.text_dim;
  7398. ui.theme.panel_alt = 0xC618;
  7399. ui.theme.text_dim = 0x8410;
  7400. ngui_scroll_end(&ui, page, &page_scroll);
  7401. ui.theme.panel_alt = old_panel;
  7402. ui.theme.text_dim = old_dim;
  7403. if (use_buf) {
  7404. ui.px = saved_px;
  7405. ui.w = saved_w;
  7406. ui.h = saved_h;
  7407. blit_page(page, page_backbuf, pagebuf_w);
  7408. page_cache_valid = 1;
  7409. page_cache_scroll = page_scroll.offset;
  7410. page_cache_nnode = doc.nnode;
  7411. page_cache_x = page.x;
  7412. page_cache_y = page.y;
  7413. page_cache_w = page.w;
  7414. page_cache_h = page.h;
  7415. } else {
  7416. page_cache_valid = 0;
  7417. }
  7418. }
  7419. static void draw_status(struct ngui_rect r)
  7420. {
  7421. char msg[BR_URL_MAX + 32];
  7422. unsigned int n = 0;
  7423. int hover = page_hover_node();
  7424. unsigned short color;
  7425. const char *kind;
  7426. ngui_fill_rect(&ui, r, ui.theme.panel);
  7427. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  7428. ui.theme.border);
  7429. if (hover) {
  7430. const char *href = br_href(&doc, (unsigned int)hover);
  7431. char url[BR_URL_MAX];
  7432. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  7433. s_append(msg, &n, "Link: ", sizeof(msg));
  7434. s_append(msg, &n, url, sizeof(msg));
  7435. } else {
  7436. s_copy(msg, "Link", sizeof(msg));
  7437. }
  7438. color = ui.theme.accent;
  7439. } else if (status_text[0]) {
  7440. s_copy(msg, status_text, sizeof(msg));
  7441. color = status_error ? ui.theme.error : ui.theme.text;
  7442. } else if (page_title[0]) {
  7443. s_copy(msg, page_title, sizeof(msg));
  7444. color = ui.theme.text;
  7445. } else {
  7446. s_copy(msg, "Ready", sizeof(msg));
  7447. color = ui.theme.text_dim;
  7448. }
  7449. kind = s_eq(page_url, "about:home") ? "HOME" :
  7450. page_is_local ? "FILE" :
  7451. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  7452. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  7453. {
  7454. int kw = (int)ngui_text_width_ui(&ui, kind);
  7455. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  7456. ui.theme.text_dim);
  7457. }
  7458. }
  7459. static void draw(unsigned int *action)
  7460. {
  7461. struct ngui_rect r = {0, 0, ui.w, ui.h};
  7462. struct ngui_rect toolbar, status, page;
  7463. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  7464. status = ngui_cut_bottom(&r, BR_STATUS_H);
  7465. page = r;
  7466. draw_toolbar(toolbar, action);
  7467. draw_page(page);
  7468. draw_status(status);
  7469. }
  7470. static void redraw_now(void)
  7471. {
  7472. unsigned int action = 0;
  7473. ngui_begin(&ui);
  7474. draw(&action);
  7475. ngui_end(&ui);
  7476. }
  7477. static void handle_keys(unsigned int *action)
  7478. {
  7479. int k, scrolled = 0;
  7480. if (form_focus >= doc.nnode)
  7481. form_focus = 0;
  7482. if (form_focus && !ngui_focus(&ui)) {
  7483. while ((k = ngui_key(&ui)) != 0)
  7484. form_key(k);
  7485. return;
  7486. }
  7487. /* Batch queued page keys: a slow full-page render must not make a
  7488. * held Page Down advance only once every few frames. */
  7489. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  7490. scrolled++;
  7491. if (scrolled)
  7492. ngui_invalidate(&ui);
  7493. if (ngui_focus(&ui))
  7494. return;
  7495. while ((k = ngui_key(&ui)) != 0) {
  7496. switch (k) {
  7497. case NGUI_KEY_ESC:
  7498. *action |= ACT_CLOSE;
  7499. break;
  7500. case NGUI_KEY_TAB:
  7501. case 0x0C: /* Ctrl+L */
  7502. ngui_set_focus(&ui, ID_URL);
  7503. break;
  7504. case 0x12: /* Ctrl+R */
  7505. *action |= ACT_RELOAD;
  7506. break;
  7507. case NGUI_KEY_BACKSPACE:
  7508. *action |= ACT_BACK;
  7509. break;
  7510. case NGUI_KEY_UP:
  7511. ngui_scroll_to(&page_scroll,
  7512. page_scroll.offset - 24);
  7513. ngui_invalidate(&ui);
  7514. break;
  7515. case NGUI_KEY_DOWN:
  7516. ngui_scroll_to(&page_scroll,
  7517. page_scroll.offset + 24);
  7518. ngui_invalidate(&ui);
  7519. break;
  7520. case NGUI_KEY_HOME:
  7521. ngui_scroll_to(&page_scroll, 0);
  7522. ngui_invalidate(&ui);
  7523. break;
  7524. case NGUI_KEY_END:
  7525. ngui_scroll_to(&page_scroll,
  7526. page_scroll.content_h -
  7527. page_scroll.view_h);
  7528. ngui_invalidate(&ui);
  7529. break;
  7530. default:
  7531. break;
  7532. }
  7533. }
  7534. }
  7535. static unsigned int form_ancestor(unsigned int node)
  7536. {
  7537. unsigned int p = node;
  7538. while (p && p < doc.nnode) {
  7539. if (doc.nodes[p].tag == BR_TAG_FORM &&
  7540. doc.nodes[p].type == BR_NODE_ELEM)
  7541. return p;
  7542. p = doc.nodes[p].parent;
  7543. }
  7544. return 0;
  7545. }
  7546. static int form_descendant(unsigned int node, unsigned int form)
  7547. {
  7548. unsigned int p = node;
  7549. while (p && p < doc.nnode) {
  7550. if (p == form)
  7551. return 1;
  7552. p = doc.nodes[p].parent;
  7553. }
  7554. return 0;
  7555. }
  7556. static void form_reset_form(unsigned int form)
  7557. {
  7558. unsigned int i;
  7559. for (i = 0; i < FORM_MAX; i++)
  7560. if (form_states[i].used &&
  7561. form_descendant(form_states[i].node, form))
  7562. form_states[i].used = 0;
  7563. form_focus = 0;
  7564. }
  7565. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  7566. const char *s)
  7567. {
  7568. static const char hex[] = "0123456789ABCDEF";
  7569. while (s && *s && *n + 1 < cap) {
  7570. unsigned char c = (unsigned char)*s++;
  7571. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  7572. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  7573. c == '.' || c == '~') {
  7574. dst[(*n)++] = (char)c;
  7575. } else if (c == ' ') {
  7576. dst[(*n)++] = '+';
  7577. } else if (*n + 3 < cap) {
  7578. dst[(*n)++] = '%';
  7579. dst[(*n)++] = hex[c >> 4];
  7580. dst[(*n)++] = hex[c & 15];
  7581. }
  7582. }
  7583. dst[*n] = '\0';
  7584. }
  7585. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  7586. const char *name, const char *value, int *first)
  7587. {
  7588. if (!name || !name[0])
  7589. return;
  7590. if (!*first && *n + 1 < cap)
  7591. dst[(*n)++] = '&';
  7592. *first = 0;
  7593. form_url_append(dst, n, cap, name);
  7594. if (*n + 1 < cap)
  7595. dst[(*n)++] = '=';
  7596. form_url_append(dst, n, cap, value ? value : "");
  7597. dst[*n] = '\0';
  7598. }
  7599. static int form_submit_form(unsigned int node, int fire_event)
  7600. {
  7601. unsigned int form = form_ancestor(node);
  7602. char action[BR_URL_MAX], query[2048];
  7603. unsigned int qn = 0, i;
  7604. int first = 1, is_post = 0;
  7605. const char *a, *method;
  7606. if (!form)
  7607. return 0;
  7608. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  7609. return 0;
  7610. method = br_find_attr(&doc, form, "method");
  7611. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  7612. is_post = 1;
  7613. a = br_find_attr(&doc, form, "action");
  7614. if (a && a[0]) {
  7615. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  7616. return 0;
  7617. } else {
  7618. s_copy(action, page_url, sizeof(action));
  7619. }
  7620. query[0] = '\0';
  7621. for (i = 0; i < doc.nnode; i++) {
  7622. struct br_node *nd = &doc.nodes[i];
  7623. struct form_state *fs;
  7624. const char *name;
  7625. const char *value = "";
  7626. if (nd->type != BR_NODE_ELEM || i == form ||
  7627. !form_descendant(i, form))
  7628. continue;
  7629. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  7630. nd->tag != BR_TAG_SELECT)
  7631. continue;
  7632. if (form_disabled(i))
  7633. continue;
  7634. name = br_find_attr(&doc, i, "name");
  7635. if (!name || !name[0])
  7636. continue;
  7637. fs = form_get(i, 1);
  7638. if (!fs)
  7639. continue;
  7640. if (nd->tag == BR_TAG_SELECT) {
  7641. char opt[64];
  7642. if (!form_option_text(i, fs->selected, opt,
  7643. sizeof(opt)))
  7644. s_copy(opt, "", sizeof(opt));
  7645. value = opt;
  7646. {
  7647. unsigned int c, oi = 0;
  7648. for (c = nd->first; c;
  7649. c = doc.nodes[c].next) {
  7650. if (doc.nodes[c].type != BR_NODE_ELEM ||
  7651. doc.nodes[c].tag != BR_TAG_OPTION)
  7652. continue;
  7653. if (oi == fs->selected) {
  7654. const char *v =
  7655. br_value(&doc, c);
  7656. if (v && v[0])
  7657. value = v;
  7658. break;
  7659. }
  7660. oi++;
  7661. }
  7662. }
  7663. } else if (nd->tag == BR_TAG_INPUT) {
  7664. int kind = form_kind_of(i);
  7665. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  7666. if (!fs->checked)
  7667. continue;
  7668. value = br_value(&doc, i);
  7669. if (!value || !value[0])
  7670. value = "on";
  7671. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  7672. kind == FORM_BUTTON) {
  7673. if (i != node)
  7674. continue;
  7675. value = fs->value;
  7676. } else {
  7677. value = fs->value;
  7678. }
  7679. } else {
  7680. value = fs->value;
  7681. }
  7682. form_add_param(query, &qn, sizeof(query), name, value, &first);
  7683. }
  7684. if (is_post) {
  7685. if (action[0] == '/') {
  7686. set_status("POST forms need an HTTP action URL", 1, 4000);
  7687. ngui_invalidate(&ui);
  7688. return 0;
  7689. }
  7690. if (qn >= sizeof(pending_post))
  7691. qn = sizeof(pending_post) - 1;
  7692. if (qn)
  7693. memcpy(pending_post, query, qn);
  7694. pending_post[qn] = '\0';
  7695. pending_post_len = qn;
  7696. } else {
  7697. pending_post_len = 0;
  7698. if (qn) {
  7699. unsigned int an = s_len(action);
  7700. if (an + qn + 2 < sizeof(action)) {
  7701. action[an++] = strchr(action, '?') ? '&' : '?';
  7702. action[an] = '\0';
  7703. s_copy(action + an, query,
  7704. sizeof(action) - an);
  7705. }
  7706. }
  7707. }
  7708. s_copy(pending_url, action, sizeof(pending_url));
  7709. pending_action |= ACT_NAV;
  7710. cancel_fetch = 1;
  7711. ngui_invalidate(&ui);
  7712. return 1;
  7713. }
  7714. static void form_reset_event(unsigned int form)
  7715. {
  7716. if (form && !js_browser_event(form, "reset", 1, 1))
  7717. return;
  7718. if (form)
  7719. form_reset_form(form);
  7720. else
  7721. form_reset_state();
  7722. form_dirty = 0;
  7723. layout_valid = 0;
  7724. ngui_invalidate(&ui);
  7725. }
  7726. static void form_blur(void)
  7727. {
  7728. unsigned int node = form_focus;
  7729. form_focus = 0;
  7730. if (node && form_dirty) {
  7731. form_dirty = 0;
  7732. js_browser_event(node, "change", 1, 0);
  7733. }
  7734. }
  7735. static void form_click(unsigned int node)
  7736. {
  7737. struct form_state *fs;
  7738. int kind, changed = 0;
  7739. if (!form_is_control(node) || form_disabled(node))
  7740. return;
  7741. if (form_focus != node)
  7742. form_blur();
  7743. if (!js_browser_event(node, "click", 1, 1))
  7744. return;
  7745. fs = form_get(node, 1);
  7746. if (!fs)
  7747. return;
  7748. kind = form_kind_of(node);
  7749. form_focus = node;
  7750. form_dirty = 0;
  7751. if (kind == FORM_CHECKBOX) {
  7752. fs->checked = !fs->checked;
  7753. changed = 1;
  7754. } else if (kind == FORM_RADIO) {
  7755. const char *name = br_find_attr(&doc, node, "name");
  7756. unsigned int i;
  7757. fs->checked = 1;
  7758. changed = 1;
  7759. if (name) {
  7760. for (i = 0; i < FORM_MAX; i++) {
  7761. struct form_state *o = &form_states[i];
  7762. if (!o->used || o->node == node)
  7763. continue;
  7764. if (form_kind_of(o->node) == FORM_RADIO) {
  7765. const char *on = br_find_attr(&doc,
  7766. o->node,
  7767. "name");
  7768. if (on && s_eq(on, name))
  7769. o->checked = 0;
  7770. }
  7771. }
  7772. }
  7773. } else if (kind == FORM_SELECT) {
  7774. unsigned int n = form_option_count(node);
  7775. if (n) {
  7776. fs->selected = (unsigned char)
  7777. ((fs->selected + 1) % n);
  7778. changed = 1;
  7779. }
  7780. } else if (kind == FORM_SUBMIT) {
  7781. form_submit_form(node, 1);
  7782. return;
  7783. } else if (kind == FORM_RESET) {
  7784. form_reset_event(form_ancestor(node));
  7785. return;
  7786. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  7787. kind == FORM_TEXTAREA) {
  7788. fs->caret = fs->len;
  7789. }
  7790. if (changed) {
  7791. js_browser_event(node, "input", 1, 0);
  7792. js_browser_event(node, "change", 1, 0);
  7793. }
  7794. layout_valid = 0;
  7795. ngui_invalidate(&ui);
  7796. }
  7797. static void form_focus_next(void)
  7798. {
  7799. unsigned int start = form_focus ? form_focus + 1 : 0;
  7800. unsigned int i;
  7801. form_blur();
  7802. for (i = start; i < doc.nnode; i++) {
  7803. if (form_is_control(i) && !form_disabled(i) &&
  7804. !s_eq(br_type(&doc, i), "hidden")) {
  7805. form_focus = i;
  7806. layout_valid = 0;
  7807. ngui_invalidate(&ui);
  7808. return;
  7809. }
  7810. }
  7811. form_focus = 0;
  7812. layout_valid = 0;
  7813. ngui_invalidate(&ui);
  7814. }
  7815. static void form_key(int k)
  7816. {
  7817. struct form_state *fs;
  7818. int kind;
  7819. if (!form_focus || form_focus >= doc.nnode) {
  7820. form_focus = 0;
  7821. return;
  7822. }
  7823. fs = form_get(form_focus, 1);
  7824. if (!fs || form_disabled(form_focus))
  7825. return;
  7826. kind = form_kind_of(form_focus);
  7827. if (kind == FORM_SELECT) {
  7828. unsigned int n = form_option_count(form_focus);
  7829. int changed = 0;
  7830. if (k == NGUI_KEY_UP && n) {
  7831. fs->selected = (unsigned char)
  7832. ((fs->selected + n - 1) % n);
  7833. changed = 1;
  7834. } else if (k == NGUI_KEY_DOWN && n) {
  7835. fs->selected = (unsigned char)
  7836. ((fs->selected + 1) % n);
  7837. changed = 1;
  7838. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  7839. form_blur();
  7840. layout_valid = 0;
  7841. ngui_invalidate(&ui);
  7842. return;
  7843. } else {
  7844. return;
  7845. }
  7846. if (changed) {
  7847. js_browser_event(form_focus, "input", 1, 0);
  7848. js_browser_event(form_focus, "change", 1, 0);
  7849. }
  7850. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  7851. if (k == ' ') {
  7852. form_click(form_focus);
  7853. return;
  7854. }
  7855. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  7856. form_blur();
  7857. layout_valid = 0;
  7858. ngui_invalidate(&ui);
  7859. }
  7860. return;
  7861. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  7862. kind == FORM_RESET) {
  7863. if (k == NGUI_KEY_ESC) {
  7864. form_blur();
  7865. layout_valid = 0;
  7866. ngui_invalidate(&ui);
  7867. } else if (k == '\r' || k == '\n' || k == ' ') {
  7868. form_click(form_focus);
  7869. }
  7870. return;
  7871. } else if (k == NGUI_KEY_TAB) {
  7872. form_focus_next();
  7873. return;
  7874. } else if (k == NGUI_KEY_ESC) {
  7875. form_blur();
  7876. layout_valid = 0;
  7877. ngui_invalidate(&ui);
  7878. return;
  7879. } else if (k == '\r' || k == '\n') {
  7880. unsigned int node = form_focus;
  7881. form_blur();
  7882. if (form_ancestor(node))
  7883. form_submit_form(node, 1);
  7884. layout_valid = 0;
  7885. ngui_invalidate(&ui);
  7886. return;
  7887. } else if (k == NGUI_KEY_BACKSPACE) {
  7888. if (fs->caret) {
  7889. unsigned int i = --fs->caret;
  7890. for (; i < fs->len; i++)
  7891. fs->value[i] = fs->value[i + 1];
  7892. if (fs->len)
  7893. fs->len--;
  7894. form_dirty = 1;
  7895. js_browser_event(form_focus, "input", 1, 0);
  7896. }
  7897. } else if (k == NGUI_KEY_DELETE) {
  7898. if (fs->caret < fs->len) {
  7899. unsigned int i;
  7900. for (i = fs->caret; i < fs->len; i++)
  7901. fs->value[i] = fs->value[i + 1];
  7902. fs->len--;
  7903. form_dirty = 1;
  7904. js_browser_event(form_focus, "input", 1, 0);
  7905. }
  7906. } else if (k == NGUI_KEY_LEFT) {
  7907. if (fs->caret)
  7908. fs->caret--;
  7909. } else if (k == NGUI_KEY_RIGHT) {
  7910. if (fs->caret < fs->len)
  7911. fs->caret++;
  7912. } else if (k == NGUI_KEY_HOME) {
  7913. fs->caret = 0;
  7914. } else if (k == NGUI_KEY_END) {
  7915. fs->caret = fs->len;
  7916. } else if (k >= 32 && k < 127) {
  7917. if (fs->len < FORM_VALUE_MAX) {
  7918. unsigned int i;
  7919. for (i = fs->len; i > fs->caret; i--)
  7920. fs->value[i] = fs->value[i - 1];
  7921. fs->value[fs->caret++] = (char)k;
  7922. fs->len++;
  7923. form_dirty = 1;
  7924. js_browser_event(form_focus, "input", 1, 0);
  7925. }
  7926. } else {
  7927. return;
  7928. }
  7929. fs->value[fs->len] = '\0';
  7930. layout_valid = 0;
  7931. ngui_invalidate(&ui);
  7932. }
  7933. static void handle_page_click(unsigned int *action)
  7934. {
  7935. int node;
  7936. char url[BR_URL_MAX];
  7937. if (!ui.pressed)
  7938. return;
  7939. if (ui.press_x < page_rect.x ||
  7940. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  7941. ui.press_y < page_rect.y ||
  7942. ui.press_y >= page_rect.y + page_rect.h)
  7943. return;
  7944. node = find_hit(ui.press_x, ui.press_y);
  7945. if (!node)
  7946. return;
  7947. if (form_is_control((unsigned int)node)) {
  7948. form_click((unsigned int)node);
  7949. return;
  7950. }
  7951. form_blur();
  7952. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  7953. return;
  7954. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  7955. sizeof(url)) != 0)
  7956. return;
  7957. s_copy(click_url, url, sizeof(click_url));
  7958. *action |= ACT_NAV;
  7959. }
  7960. void _start(const char *arg)
  7961. {
  7962. struct win_info wi;
  7963. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  7964. u_win_create(960, 640, "Browser", &wi) != 0 &&
  7965. u_win_create(780, 540, "Browser", &wi) != 0) {
  7966. u_puts("browser: no graphics window\n");
  7967. u_exit(1);
  7968. }
  7969. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  7970. url_in.placeholder = "http://...";
  7971. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  7972. ui.theme.accent);
  7973. br_set_viewport(wi.width);
  7974. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  7975. s_copy(cwd, "/", sizeof(cwd));
  7976. heap_clear();
  7977. origin_cache_load();
  7978. css_cache_init();
  7979. script_cache_init();
  7980. page_scroll.offset = 0;
  7981. page_scroll.content_h = 0;
  7982. if (arg && arg[0]) {
  7983. navigate(arg, 1);
  7984. } else {
  7985. load_home(1);
  7986. /* Start ready to type: keep the home page, but leave the address
  7987. * bar empty instead of showing "about:home". */
  7988. ngui_input_set(&url_in, "");
  7989. ngui_set_focus(&ui, ID_URL);
  7990. }
  7991. for (;;) {
  7992. unsigned int action = 0;
  7993. unsigned int now;
  7994. click_url[0] = '\0';
  7995. if (pending_action) {
  7996. action |= pending_action & ACT_WAIT_NAV;
  7997. if (pending_url[0])
  7998. s_copy(click_url, pending_url, sizeof(click_url));
  7999. pending_action = 0;
  8000. pending_url[0] = '\0';
  8001. cancel_fetch = 0;
  8002. } else if (preload_active) {
  8003. if (preload_wait)
  8004. preload_wait = 0;
  8005. else
  8006. preload_step();
  8007. } else if (preload_pending &&
  8008. page_scroll.offset != preload_scroll) {
  8009. preload_scroll = page_scroll.offset;
  8010. preload_pending = 0;
  8011. preload_node = 0;
  8012. preload_active = 1;
  8013. }
  8014. js_browser_tick();
  8015. if (pending_action)
  8016. continue;
  8017. now = u_ticks_ms();
  8018. if (status_until && (int)(now - status_until) >= 0) {
  8019. status_text[0] = '\0';
  8020. status_until = 0;
  8021. status_error = 0;
  8022. ngui_invalidate(&ui);
  8023. }
  8024. if (!ngui_begin(&ui)) {
  8025. /* A queued navigation (e.g. Enter in the URL bar during
  8026. * a slow fetch) must be handled even when this frame
  8027. * needs no redraw. */
  8028. if (!action) {
  8029. fetch_workers_stop_if_unfocused();
  8030. u_sleep_ms(10);
  8031. continue;
  8032. }
  8033. } else {
  8034. draw(&action);
  8035. handle_keys(&action);
  8036. handle_page_click(&action);
  8037. ngui_end(&ui);
  8038. }
  8039. if (action & ACT_NAV) {
  8040. if (click_url[0]) {
  8041. navigate(click_url, 1);
  8042. click_url[0] = '\0';
  8043. } else {
  8044. navigate(url_in.text, 1);
  8045. }
  8046. }
  8047. if (action & ACT_BACK) {
  8048. if (hist_pos > 0) {
  8049. hist_pos--;
  8050. navigate(history[hist_pos], 0);
  8051. }
  8052. }
  8053. if (action & ACT_FORWARD) {
  8054. if (hist_pos + 1 < hist_len) {
  8055. hist_pos++;
  8056. navigate(history[hist_pos], 0);
  8057. }
  8058. }
  8059. if (action & ACT_RELOAD) {
  8060. if (s_eq(page_url, "about:home"))
  8061. load_home(0);
  8062. else
  8063. navigate(page_url, 0);
  8064. }
  8065. if (action & ACT_HOME)
  8066. load_home(1);
  8067. if (action & ACT_CLOSE)
  8068. quit = 1;
  8069. if (quit)
  8070. break;
  8071. if (pending_action)
  8072. continue;
  8073. fetch_workers_stop_if_unfocused();
  8074. u_sleep_ms(10);
  8075. }
  8076. fetch_workers_stop_all();
  8077. u_win_close();
  8078. u_exit(0);
  8079. }