browser.c 215 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714
  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. /* The browser is no longer the active window and no fetch is running: give
  1906. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  1907. static void fetch_workers_stop_if_unfocused(void)
  1908. {
  1909. int i;
  1910. if (ui.focused || page_loading || preload_active)
  1911. return;
  1912. for (i = 0; i < FETCH_WORKERS; i++)
  1913. if (fetch_workers[i].pid > 0) {
  1914. fetch_workers_stop_all();
  1915. return;
  1916. }
  1917. }
  1918. static int fetch_worker_start(struct fetch_worker *w, char *err,
  1919. unsigned int errcap)
  1920. {
  1921. char arg[40];
  1922. unsigned int n = 0;
  1923. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  1924. return 0;
  1925. w->pid = -1;
  1926. fetch_pool_init();
  1927. if (fetch_tty == -2) {
  1928. int t = u_tty_create();
  1929. fetch_tty = t > 0 ? t : 0;
  1930. }
  1931. s_append(arg, &n, "__serve ", sizeof(arg));
  1932. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  1933. s_append(arg, &n, " ", sizeof(arg));
  1934. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  1935. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  1936. if (w->pid <= 0) {
  1937. w->pid = -1;
  1938. s_copy(err, "cannot start network helper", errcap);
  1939. return -1;
  1940. }
  1941. return 0;
  1942. }
  1943. static struct fetch_worker *fetch_worker_alloc(void)
  1944. {
  1945. int i;
  1946. fetch_pool_init();
  1947. for (i = 0; i < FETCH_WORKERS; i++)
  1948. if (!fetch_workers[i].busy)
  1949. return &fetch_workers[i];
  1950. return 0;
  1951. }
  1952. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1953. unsigned int cap, const char *post,
  1954. unsigned int post_len, unsigned int node,
  1955. int bg, char *err, unsigned int errcap)
  1956. {
  1957. static char req[768];
  1958. unsigned int n = 0;
  1959. fetch_seq++;
  1960. if (!fetch_seq)
  1961. fetch_seq = 1;
  1962. w->seq = fetch_seq;
  1963. w->ready = 0;
  1964. w->image_job = 0;
  1965. w->retried = 0;
  1966. w->m.error = 0;
  1967. w->node = node;
  1968. w->bg = bg;
  1969. s_copy(w->url, url, sizeof(w->url));
  1970. s_append_dec(req, &n, w->seq, sizeof(req));
  1971. s_append(req, &n, " ", sizeof(req));
  1972. s_append_dec(req, &n, cap, sizeof(req));
  1973. s_append(req, &n, " ", sizeof(req));
  1974. if (post_len) {
  1975. s_append(req, &n, "POST ", sizeof(req));
  1976. s_append_dec(req, &n, post_len, sizeof(req));
  1977. s_append(req, &n, " ", sizeof(req));
  1978. }
  1979. s_append(req, &n, url, sizeof(req));
  1980. s_append(req, &n, "\n", sizeof(req));
  1981. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  1982. (int)post, (int)post_len) < 0) {
  1983. s_copy(err, "cannot queue form body", errcap);
  1984. return -1;
  1985. }
  1986. u_syscall1(SYS_UNLINK, (int)w->done);
  1987. u_syscall1(SYS_UNLINK, (int)w->meta);
  1988. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  1989. s_copy(err, "cannot queue network request", errcap);
  1990. return -1;
  1991. }
  1992. if (fetch_worker_start(w, err, errcap) != 0)
  1993. return -1;
  1994. w->busy = 1;
  1995. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  1996. return 0;
  1997. }
  1998. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  1999. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  2000. unsigned int errcap)
  2001. {
  2002. static char meta[1024];
  2003. char *p;
  2004. int rn, mseq;
  2005. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  2006. (int)(sizeof(meta) - 1));
  2007. if (rn <= 0) {
  2008. s_copy(err, "network helper failed", errcap);
  2009. return -1;
  2010. }
  2011. meta[rn] = '\0';
  2012. p = meta;
  2013. mseq = (int)meta_uint(&p);
  2014. if (mseq != (int)w->seq) {
  2015. s_copy(err, "stale network response", errcap);
  2016. return -1;
  2017. }
  2018. w->m.status = (int)meta_uint(&p);
  2019. w->m.error = (int)meta_uint(&p);
  2020. w->m.trunc = (int)meta_uint(&p);
  2021. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  2022. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  2023. meta_str(&p, w->m.final, sizeof(w->m.final));
  2024. w->m.len = meta_uint(&p);
  2025. w->m.open_ms = 0;
  2026. w->m.first_ms = 0;
  2027. w->m.total_ms = 0;
  2028. if (*p) {
  2029. w->m.open_ms = meta_uint(&p);
  2030. w->m.first_ms = meta_uint(&p);
  2031. w->m.total_ms = meta_uint(&p);
  2032. }
  2033. if (w->m.error) {
  2034. s_copy(err, uhttp_error_string(w->m.error), errcap);
  2035. return -1;
  2036. }
  2037. w->ready = 1;
  2038. return 0;
  2039. }
  2040. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  2041. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  2042. unsigned int errcap)
  2043. {
  2044. static char done[24];
  2045. char *p;
  2046. int rn, mseq;
  2047. if (!w->busy)
  2048. return -1;
  2049. if (w->ready)
  2050. return 1;
  2051. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  2052. (int)(sizeof(done) - 1));
  2053. if (rn > 0) {
  2054. done[rn] = '\0';
  2055. p = done;
  2056. mseq = (int)meta_uint(&p);
  2057. if (mseq == (int)w->seq) {
  2058. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  2059. fetch_worker_stop(w);
  2060. return -1;
  2061. }
  2062. return 1;
  2063. }
  2064. }
  2065. if (!u_alive((unsigned int)w->pid)) {
  2066. w->pid = -1;
  2067. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  2068. w->retried = 1;
  2069. return 0;
  2070. }
  2071. s_copy(err, "network helper stopped", errcap);
  2072. fetch_worker_stop(w);
  2073. return -1;
  2074. }
  2075. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  2076. s_copy(err, "network request timed out", errcap);
  2077. fetch_worker_stop(w);
  2078. return -1;
  2079. }
  2080. return 0;
  2081. }
  2082. /* Copy the completed body, inflating it if the server ignored our identity
  2083. * request. Mirrors the old fetch_remote body path. */
  2084. static int fetch_worker_read_body(struct fetch_worker *w,
  2085. unsigned char *plain,
  2086. unsigned int plaincap,
  2087. unsigned char *comp,
  2088. unsigned int compcap,
  2089. int *truncated, char *err,
  2090. unsigned int errcap)
  2091. {
  2092. int rv, zr, was_trunc;
  2093. if (contains_ci(w->m.encoding, "gzip") ||
  2094. contains_ci(w->m.encoding, "deflate")) {
  2095. unsigned int comp_len = 0, plen = 0;
  2096. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  2097. (int)compcap);
  2098. if (rv < 0) {
  2099. s_copy(err, "empty response", errcap);
  2100. return -1;
  2101. }
  2102. comp_len = (unsigned int)rv;
  2103. if (comp_len < w->m.len) {
  2104. s_copy(err, "compressed response is too large", errcap);
  2105. return -1;
  2106. }
  2107. if (contains_ci(w->m.encoding, "deflate"))
  2108. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2109. &plen, 0, &was_trunc);
  2110. else
  2111. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2112. &plen, 1, &was_trunc);
  2113. if (zr != 0) {
  2114. s_copy(err, "compressed response is corrupt", errcap);
  2115. return -1;
  2116. }
  2117. *truncated = w->m.trunc || was_trunc;
  2118. return (int)plen;
  2119. }
  2120. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  2121. if (rv < 0) {
  2122. s_copy(err, "empty response", errcap);
  2123. return -1;
  2124. }
  2125. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  2126. return rv;
  2127. }
  2128. static void fetch_worker_release(struct fetch_worker *w)
  2129. {
  2130. u_syscall1(SYS_UNLINK, (int)w->done);
  2131. u_syscall1(SYS_UNLINK, (int)w->meta);
  2132. u_syscall1(SYS_UNLINK, (int)w->body);
  2133. u_syscall1(SYS_UNLINK, (int)w->post);
  2134. u_syscall1(SYS_UNLINK, (int)w->req);
  2135. w->busy = 0;
  2136. w->ready = 0;
  2137. w->image_job = 0;
  2138. }
  2139. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  2140. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  2141. unsigned int errcap)
  2142. {
  2143. for (;;) {
  2144. int rv;
  2145. worker_wait_ui();
  2146. if (cancel_fetch || pending_action) {
  2147. fetch_workers_cancel_busy();
  2148. return FETCH_ABORT;
  2149. }
  2150. rv = fetch_worker_poll(w, err, errcap);
  2151. if (rv != 0)
  2152. return rv == 1 ? 0 : -1;
  2153. u_sleep_ms(10);
  2154. }
  2155. }
  2156. static int fetch_remote(const char *url, unsigned int cap,
  2157. const char *post, unsigned int post_len,
  2158. unsigned char *plain, unsigned int plaincap,
  2159. unsigned char *comp, unsigned int compcap,
  2160. struct fetch_meta *m, int *truncated,
  2161. char *err, unsigned int errcap)
  2162. {
  2163. struct fetch_worker *w = fetch_worker_alloc();
  2164. int rv;
  2165. fetch_last_error = 0;
  2166. if (!w) {
  2167. s_copy(err, "network busy", errcap);
  2168. return -1;
  2169. }
  2170. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  2171. err, errcap) != 0) {
  2172. fetch_worker_release(w);
  2173. return -1;
  2174. }
  2175. rv = fetch_worker_wait(w, err, errcap);
  2176. if (rv == FETCH_ABORT) {
  2177. fetch_worker_release(w);
  2178. return FETCH_ABORT;
  2179. }
  2180. if (rv != 0) {
  2181. fetch_last_error = w->m.error;
  2182. fetch_worker_release(w);
  2183. return -1;
  2184. }
  2185. *m = w->m;
  2186. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  2187. truncated, err, errcap);
  2188. fetch_worker_release(w);
  2189. if (rv >= 0 && (cancel_fetch || pending_action))
  2190. return FETCH_ABORT;
  2191. return rv;
  2192. }
  2193. /* ---- HTTP / file fetch ---- */
  2194. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  2195. unsigned int *outlen, int *is_local, char *ctype,
  2196. unsigned int ctcap, char *final, unsigned int finalcap,
  2197. char *err, unsigned int errcap, int *truncated,
  2198. const char *post, unsigned int post_len)
  2199. {
  2200. unsigned char *buf;
  2201. unsigned int len;
  2202. int tr = 0;
  2203. int rv;
  2204. *out = 0;
  2205. *outlen = 0;
  2206. *truncated = 0;
  2207. if (final && finalcap)
  2208. final[0] = '\0';
  2209. if (ctype && ctcap)
  2210. ctype[0] = '\0';
  2211. if (url[0] == '/') {
  2212. char pathbuf[BR_URL_MAX];
  2213. const char *open_url = url;
  2214. unsigned int i = 0;
  2215. /* A local form GET keeps ?query in the address bar but the
  2216. * file lookup uses the path alone, like a real browser. */
  2217. while (url[i] && url[i] != '?' && url[i] != '#')
  2218. i++;
  2219. if (url[i]) {
  2220. s_copy(pathbuf, url, i + 1);
  2221. open_url = pathbuf;
  2222. }
  2223. buf = (unsigned char *)malloc(cap);
  2224. if (!buf) {
  2225. s_copy(err, "out of memory", errcap);
  2226. return -1;
  2227. }
  2228. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  2229. if (rv < 0) {
  2230. free(buf);
  2231. s_copy(err, "file not found", errcap);
  2232. return -1;
  2233. }
  2234. *out = buf;
  2235. *outlen = (unsigned int)rv;
  2236. *is_local = 1;
  2237. if (ctype)
  2238. s_copy(ctype, "text/html", ctcap);
  2239. if (final)
  2240. s_copy(final, url, finalcap);
  2241. if ((unsigned int)rv == cap)
  2242. *truncated = 1;
  2243. return 0;
  2244. }
  2245. buf = (unsigned char *)malloc(cap);
  2246. if (!buf) {
  2247. s_copy(err, "out of memory", errcap);
  2248. return -1;
  2249. }
  2250. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  2251. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  2252. if (rv == FETCH_ABORT) {
  2253. free(buf);
  2254. return FETCH_ABORT;
  2255. }
  2256. if (rv < 0) {
  2257. free(buf);
  2258. return -1;
  2259. }
  2260. len = (unsigned int)rv;
  2261. if (len == 0) {
  2262. free(buf);
  2263. s_copy(err, "empty response", errcap);
  2264. return -1;
  2265. }
  2266. if (ctype)
  2267. s_copy(ctype, fetch_meta.ctype, ctcap);
  2268. if (final && fetch_meta.final[0])
  2269. s_copy(final, fetch_meta.final, finalcap);
  2270. *is_local = 0;
  2271. *out = buf;
  2272. *outlen = len;
  2273. *truncated = tr;
  2274. return 0;
  2275. }
  2276. /* Load every @font-face the parser registered. Local files go through
  2277. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  2278. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  2279. * to the built-in regular/bold/italic/mono set. */
  2280. static void load_font_faces(void)
  2281. {
  2282. unsigned int i;
  2283. memset(font_faces, 0, sizeof(font_faces));
  2284. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  2285. i <= BR_MAX_FACES; i++) {
  2286. const char *url = br_font_face_url((int)i);
  2287. const char *base = br_font_face_base((int)i);
  2288. char abs[BR_URL_MAX];
  2289. if (!url || !url[0])
  2290. continue;
  2291. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  2292. sizeof(abs)) != 0)
  2293. continue;
  2294. if (abs[0] == '/') {
  2295. font_faces[i - 1] = ufont_face_open_path(abs);
  2296. } else if (is_http(abs)) {
  2297. unsigned char *buf;
  2298. char err[64];
  2299. int rv, tr = 0;
  2300. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  2301. if (!buf)
  2302. continue;
  2303. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  2304. UFONT_MAX_FILE, image_io_buf,
  2305. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  2306. err, sizeof(err));
  2307. if (rv > 0)
  2308. font_faces[i - 1] = ufont_face_open_mem(buf,
  2309. rv);
  2310. free(buf);
  2311. }
  2312. }
  2313. }
  2314. /* Remote scripts are cached under /share for the current boot, like the
  2315. * stylesheet cache, so reloads and later visits skip the network. */
  2316. static int script_cache_count;
  2317. static unsigned int script_cache_hash(const char *s)
  2318. {
  2319. unsigned int h = 2166136261u;
  2320. while (*s) {
  2321. h ^= (unsigned char)*s++;
  2322. h *= 16777619u;
  2323. }
  2324. return h;
  2325. }
  2326. static void script_cache_path(const char *url, char *out, unsigned int cap)
  2327. {
  2328. unsigned int n = 0;
  2329. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  2330. s_append_dec(out, &n, script_cache_hash(url), cap);
  2331. }
  2332. static void script_cache_clear(void)
  2333. {
  2334. struct sys_dirent d;
  2335. char path[96];
  2336. for (;;) {
  2337. int i, found = 0;
  2338. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2339. (int)&d) == 1; i++) {
  2340. unsigned int n = 0;
  2341. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  2342. continue;
  2343. s_append(path, &n, "/share/", sizeof(path));
  2344. s_append(path, &n, d.name, sizeof(path));
  2345. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  2346. return;
  2347. found = 1;
  2348. break;
  2349. }
  2350. if (!found)
  2351. break;
  2352. }
  2353. script_cache_count = 0;
  2354. }
  2355. static void script_cache_init(void)
  2356. {
  2357. struct sys_dirent d;
  2358. int i, count = 0;
  2359. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2360. (int)&d) == 1; i++)
  2361. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  2362. count++;
  2363. if (count >= SCRIPT_CACHE_MAX) {
  2364. script_cache_clear();
  2365. return;
  2366. }
  2367. script_cache_count = count;
  2368. }
  2369. static int script_cache_get(const char *url, unsigned char **out,
  2370. unsigned int *outlen)
  2371. {
  2372. char path[96];
  2373. struct sys_stat st;
  2374. unsigned char *buf;
  2375. int rn;
  2376. script_cache_path(url, path, sizeof(path));
  2377. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  2378. st.size >= SCRIPT_CACHE_FILE_MAX)
  2379. return 0;
  2380. buf = (unsigned char *)malloc(st.size + 1);
  2381. if (!buf)
  2382. return 0;
  2383. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  2384. if (rn != (int)st.size) {
  2385. free(buf);
  2386. return 0;
  2387. }
  2388. buf[st.size] = '\0';
  2389. *out = buf;
  2390. *outlen = st.size;
  2391. return 1;
  2392. }
  2393. static void script_cache_put(const char *url, const unsigned char *data,
  2394. unsigned int len)
  2395. {
  2396. char path[96];
  2397. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  2398. len >= SCRIPT_CACHE_FILE_MAX)
  2399. return;
  2400. script_cache_path(url, path, sizeof(path));
  2401. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  2402. (int)len) >= 0)
  2403. script_cache_count++;
  2404. }
  2405. static int script_cache_has(const char *url)
  2406. {
  2407. char path[96];
  2408. struct sys_stat st;
  2409. script_cache_path(url, path, sizeof(path));
  2410. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  2411. st.size < SCRIPT_CACHE_FILE_MAX;
  2412. }
  2413. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  2414. static int fetch_script_text(const char *url, unsigned char **out,
  2415. unsigned int *outlen, char *err,
  2416. unsigned int errcap)
  2417. {
  2418. unsigned char *buf;
  2419. unsigned int len;
  2420. int local, truncated = 0;
  2421. char ctype[64], final[BR_URL_MAX];
  2422. int rv;
  2423. *out = 0;
  2424. *outlen = 0;
  2425. if (url[0] != '/' && script_cache_get(url, out, outlen))
  2426. return 0;
  2427. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  2428. sizeof(ctype), final, sizeof(final), err, errcap,
  2429. &truncated, 0, 0);
  2430. if (rv != 0)
  2431. return rv;
  2432. if (truncated || len >= BR_SCRIPT_MAX) {
  2433. free(buf);
  2434. s_copy(err, "script is too large", errcap);
  2435. return -1;
  2436. }
  2437. buf[len] = '\0';
  2438. if (!local)
  2439. script_cache_put(url, buf, len);
  2440. *out = buf;
  2441. *outlen = len;
  2442. return 0;
  2443. }
  2444. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  2445. * the heap, so images must not allocate their file body from it as well. */
  2446. static int fetch_image(const char *url, unsigned int cap,
  2447. unsigned char **out, unsigned int *outlen,
  2448. char *err, unsigned int errcap)
  2449. {
  2450. unsigned int len;
  2451. int tr = 0;
  2452. int rv;
  2453. *out = 0;
  2454. *outlen = 0;
  2455. if (cap > BR_IMG_FILE_MAX)
  2456. cap = BR_IMG_FILE_MAX;
  2457. if (url[0] == '/') {
  2458. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  2459. (int)cap);
  2460. if (rv < 0) {
  2461. s_copy(err, "file not found", errcap);
  2462. return -1;
  2463. }
  2464. *out = image_file_buf;
  2465. *outlen = (unsigned int)rv;
  2466. return 0;
  2467. }
  2468. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  2469. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  2470. if (rv == FETCH_ABORT)
  2471. return FETCH_ABORT;
  2472. if (rv < 0)
  2473. return -1;
  2474. len = (unsigned int)rv;
  2475. if (len == 0) {
  2476. s_copy(err, "empty image", errcap);
  2477. return -1;
  2478. }
  2479. *out = image_file_buf;
  2480. *outlen = len;
  2481. return 0;
  2482. }
  2483. /* Remote stylesheets are immutable enough for the current boot: keep
  2484. * successful responses under /share so a reload, a second visit or a fresh
  2485. * browser launch does not fetch the same five sheets over the network again.
  2486. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  2487. static int css_cache_count;
  2488. static unsigned int css_cache_hash(const char *s)
  2489. {
  2490. unsigned int h = 2166136261u;
  2491. while (*s) {
  2492. h ^= (unsigned char)*s++;
  2493. h *= 16777619u;
  2494. }
  2495. return h;
  2496. }
  2497. static void css_cache_path(const char *url, char *out, unsigned int cap)
  2498. {
  2499. unsigned int n = 0;
  2500. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  2501. s_append_dec(out, &n, css_cache_hash(url), cap);
  2502. }
  2503. static void css_cache_clear(void)
  2504. {
  2505. struct sys_dirent d;
  2506. char path[96];
  2507. for (;;) {
  2508. int i, found = 0;
  2509. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2510. (int)&d) == 1; i++) {
  2511. unsigned int n = 0;
  2512. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  2513. continue;
  2514. s_append(path, &n, "/share/", sizeof(path));
  2515. s_append(path, &n, d.name, sizeof(path));
  2516. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  2517. return;
  2518. found = 1;
  2519. break;
  2520. }
  2521. if (!found)
  2522. break;
  2523. }
  2524. css_cache_count = 0;
  2525. }
  2526. static void css_cache_init(void)
  2527. {
  2528. struct sys_dirent d;
  2529. int i, count = 0;
  2530. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2531. (int)&d) == 1; i++)
  2532. if (starts_with(d.name, CSS_CACHE_PREFIX))
  2533. count++;
  2534. if (count >= CSS_CACHE_MAX) {
  2535. css_cache_clear();
  2536. return;
  2537. }
  2538. css_cache_count = count;
  2539. }
  2540. static int css_cache_get(const char *url, unsigned char **out,
  2541. unsigned int *outlen)
  2542. {
  2543. char path[96];
  2544. int rn;
  2545. css_cache_path(url, path, sizeof(path));
  2546. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  2547. (int)CSS_CACHE_FILE_MAX);
  2548. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  2549. return 0;
  2550. *out = image_io_buf;
  2551. *outlen = (unsigned int)rn;
  2552. return 1;
  2553. }
  2554. static void css_cache_put(const char *url, const unsigned char *data,
  2555. unsigned int len)
  2556. {
  2557. char path[96];
  2558. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  2559. len >= CSS_CACHE_FILE_MAX)
  2560. return;
  2561. css_cache_path(url, path, sizeof(path));
  2562. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  2563. (int)len) >= 0)
  2564. css_cache_count++;
  2565. }
  2566. static int css_cache_has(const char *url)
  2567. {
  2568. char path[96];
  2569. struct sys_stat st;
  2570. css_cache_path(url, path, sizeof(path));
  2571. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  2572. st.size < CSS_CACHE_FILE_MAX;
  2573. }
  2574. /* Read one stylesheet into the shared static buffer. CSS is parsed
  2575. * immediately, so it does not need the page heap; this leaves the heap for
  2576. * the 2 MB page body, the rules and the scaled image bitmaps. */
  2577. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  2578. char *err, unsigned int errcap)
  2579. {
  2580. unsigned int len;
  2581. int tr = 0;
  2582. int rv;
  2583. *out = 0;
  2584. *outlen = 0;
  2585. if (url[0] == '/') {
  2586. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  2587. (int)BR_CSS_MAX);
  2588. if (rv < 0) {
  2589. s_copy(err, "stylesheet not found", errcap);
  2590. return -1;
  2591. }
  2592. *out = image_io_buf;
  2593. *outlen = (unsigned int)rv;
  2594. return 0;
  2595. }
  2596. if (css_cache_get(url, out, outlen))
  2597. return 0;
  2598. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  2599. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  2600. &fetch_meta, &tr, err, errcap);
  2601. if (rv == FETCH_ABORT)
  2602. return FETCH_ABORT;
  2603. if (rv < 0)
  2604. return -1;
  2605. len = (unsigned int)rv;
  2606. if (len == 0) {
  2607. s_copy(err, "empty stylesheet", errcap);
  2608. return -1;
  2609. }
  2610. *out = image_io_buf;
  2611. *outlen = len;
  2612. css_cache_put(url, image_io_buf, len);
  2613. return 0;
  2614. }
  2615. static void redraw_now(void);
  2616. static char error_page[1024];
  2617. static void show_error(const char *title, const char *detail)
  2618. {
  2619. char *page = error_page;
  2620. unsigned int n = 0;
  2621. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  2622. s_append(page, &n, title, sizeof(error_page));
  2623. s_append(page, &n, "</h2><p>", sizeof(error_page));
  2624. {
  2625. const char *p = detail;
  2626. while (*p && n + 1 < sizeof(error_page)) {
  2627. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  2628. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  2629. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  2630. else page[n++] = *p;
  2631. p++;
  2632. }
  2633. }
  2634. page[n] = '\0';
  2635. s_append(page, &n, "</p><p>", sizeof(error_page));
  2636. s_append(page, &n, page_url, sizeof(error_page));
  2637. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  2638. sizeof(error_page));
  2639. br_parse(&doc, page, n);
  2640. layout_valid = 0;
  2641. preload_active = 0;
  2642. preload_pending = 0;
  2643. preload_wait = 0;
  2644. fetch_workers_cancel_busy();
  2645. s_copy(page_title, title, sizeof(page_title));
  2646. page_loading = 0;
  2647. set_status(title, 1, 0);
  2648. ngui_invalidate(&ui);
  2649. }
  2650. static int decode_direct_image(const unsigned char *data, unsigned int len,
  2651. unsigned int node)
  2652. {
  2653. if (image_count >= BR_MAX_IMAGES)
  2654. return -1;
  2655. if (decode_image_data(data, len, &images[0]) != 0)
  2656. return -1;
  2657. doc.nodes[node].img_index = 0;
  2658. image_count = 1;
  2659. return 0;
  2660. }
  2661. static int ancestor_is(unsigned int node, unsigned int tag)
  2662. {
  2663. unsigned int p = doc.nodes[node].parent;
  2664. while (p) {
  2665. if (doc.nodes[p].tag == tag)
  2666. return 1;
  2667. p = doc.nodes[p].parent;
  2668. }
  2669. return 0;
  2670. }
  2671. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  2672. * parallel but parsed in document order, so the cascade is unchanged. */
  2673. static int load_stylesheets(void)
  2674. {
  2675. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  2676. static unsigned char remote[BR_MAX_SHEETS];
  2677. struct fetch_worker *slot[BR_MAX_SHEETS];
  2678. unsigned int i, n = 0, next = 0, k;
  2679. char err[64];
  2680. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  2681. struct br_node *nd = &doc.nodes[i];
  2682. const char *rel, *href;
  2683. char url[BR_URL_MAX];
  2684. int dup = 0;
  2685. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  2686. continue;
  2687. rel = br_rel(&doc, i);
  2688. if (!contains_ci(rel, "stylesheet"))
  2689. continue;
  2690. href = br_href(&doc, i);
  2691. if (!href[0])
  2692. continue;
  2693. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  2694. continue;
  2695. for (k = 0; k < n; k++)
  2696. if (s_eq(urls[k], url)) {
  2697. dup = 1;
  2698. break;
  2699. }
  2700. if (dup)
  2701. continue;
  2702. s_copy(urls[n], url, BR_URL_MAX);
  2703. remote[n] = url[0] != '/' && !css_cache_has(url);
  2704. n++;
  2705. }
  2706. for (i = 0; i < BR_MAX_SHEETS; i++)
  2707. slot[i] = 0;
  2708. /* Start as many remote sheets as there are free workers. */
  2709. for (; next < n; next++) {
  2710. struct fetch_worker *w;
  2711. if (!remote[next])
  2712. continue;
  2713. w = fetch_worker_alloc();
  2714. if (!w)
  2715. break;
  2716. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  2717. err, sizeof(err)) != 0) {
  2718. fetch_worker_release(w);
  2719. remote[next] = 0;
  2720. continue;
  2721. }
  2722. slot[next] = w;
  2723. }
  2724. for (i = 0; i < n; i++) {
  2725. unsigned char *data = 0;
  2726. unsigned int len = 0;
  2727. int rv;
  2728. if (!remote[i]) {
  2729. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  2730. if (rv == FETCH_ABORT) {
  2731. fetch_workers_stop_all();
  2732. return FETCH_ABORT;
  2733. }
  2734. if (rv != 0 || !len)
  2735. continue;
  2736. } else {
  2737. struct fetch_worker *w = slot[i];
  2738. int tr = 0;
  2739. if (!w) {
  2740. w = fetch_worker_alloc();
  2741. if (!w)
  2742. continue;
  2743. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  2744. 0, 0, 0, 0, err,
  2745. sizeof(err)) != 0) {
  2746. fetch_worker_release(w);
  2747. remote[i] = 0;
  2748. if (i == next)
  2749. next++;
  2750. continue;
  2751. }
  2752. slot[i] = w;
  2753. if (i == next)
  2754. next++;
  2755. }
  2756. rv = fetch_worker_wait(w, err, sizeof(err));
  2757. if (rv == FETCH_ABORT) {
  2758. fetch_workers_stop_all();
  2759. return FETCH_ABORT;
  2760. }
  2761. if (rv == 0)
  2762. rv = fetch_worker_read_body(w, image_io_buf,
  2763. BR_CSS_MAX,
  2764. image_io_buf + BR_CSS_MAX,
  2765. BR_CSS_COMP_MAX, &tr,
  2766. err, sizeof(err));
  2767. else
  2768. rv = -1;
  2769. fetch_worker_release(w);
  2770. slot[i] = 0;
  2771. /* Refill the worker window before parsing this sheet. */
  2772. for (; next < n; next++) {
  2773. struct fetch_worker *nw;
  2774. if (!remote[next])
  2775. continue;
  2776. nw = fetch_worker_alloc();
  2777. if (!nw)
  2778. break;
  2779. if (fetch_worker_submit(nw, urls[next],
  2780. BR_CSS_MAX, 0, 0, 0, 0,
  2781. err, sizeof(err)) != 0) {
  2782. fetch_worker_release(nw);
  2783. remote[next] = 0;
  2784. continue;
  2785. }
  2786. slot[next] = nw;
  2787. }
  2788. if (rv <= 0)
  2789. continue;
  2790. len = (unsigned int)rv;
  2791. data = image_io_buf;
  2792. css_cache_put(urls[i], data, len);
  2793. }
  2794. if (len) {
  2795. br_set_font_base(urls[i]);
  2796. br_parse_css_text(&doc, (const char *)data, len);
  2797. }
  2798. }
  2799. br_set_font_base(page_url);
  2800. br_parse_inline_css(&doc);
  2801. load_font_faces();
  2802. br_reset_styles(&doc);
  2803. layout_valid = 0;
  2804. return 0;
  2805. }
  2806. static void preload_begin(void)
  2807. {
  2808. preload_active = 1;
  2809. preload_pending = 0;
  2810. preload_wait = 1;
  2811. preload_max_jobs = FETCH_WORKERS;
  2812. preload_node = 0;
  2813. preload_loaded = 0;
  2814. preload_scroll = 0;
  2815. }
  2816. /* Styles are computed top-down during layout, but images inside a hidden
  2817. * menu/carousel are never visited and keep img_top == 0. Without this check
  2818. * the preloader walks the DOM in node order and spends the whole image
  2819. * budget on logos and off-canvas thumbnails the reader cannot see. */
  2820. static int node_hidden(unsigned int node)
  2821. {
  2822. unsigned int path[32], n = 0, p = node, i;
  2823. struct br_style st, parent;
  2824. while (p && n < sizeof(path) / sizeof(path[0])) {
  2825. path[n++] = p;
  2826. p = doc.nodes[p].parent;
  2827. }
  2828. parent = (struct br_style){0};
  2829. parent.font_px = 16;
  2830. parent.display = BR_DISPLAY_BLOCK;
  2831. for (i = n; i > 0; i--) {
  2832. br_style_for(&doc, path[i - 1], &parent, &st);
  2833. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  2834. st.opacity_hidden)
  2835. return 1;
  2836. parent = st;
  2837. }
  2838. return 0;
  2839. }
  2840. static struct br_style base_style(void);
  2841. static void style_for_node(unsigned int node, struct br_style *out)
  2842. {
  2843. unsigned int p = doc.nodes[node].parent;
  2844. struct br_style parent;
  2845. if (p) {
  2846. style_for_node(p, &parent);
  2847. br_style_for(&doc, node, &parent, out);
  2848. } else {
  2849. parent = base_style();
  2850. br_style_for(&doc, node, &parent, out);
  2851. }
  2852. }
  2853. /* ---- parallel image preloading ---- *
  2854. *
  2855. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  2856. * preload_step() only starts jobs and harvests completed ones; the browser
  2857. * main loop keeps drawing between calls, instead of blocking on one fetch.
  2858. */
  2859. static int preload_active_jobs(void)
  2860. {
  2861. int i, n = 0;
  2862. for (i = 0; i < FETCH_WORKERS; i++)
  2863. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  2864. n++;
  2865. return n;
  2866. }
  2867. static void preload_job_error(struct fetch_worker *w)
  2868. {
  2869. if (w->node < doc.nnode) {
  2870. if (w->bg)
  2871. doc.nodes[w->node].bg_img_index = -2;
  2872. else
  2873. doc.nodes[w->node].img_index = -2;
  2874. ngui_invalidate(&ui);
  2875. }
  2876. }
  2877. static void preload_decode(unsigned int node, int bg,
  2878. const unsigned char *data, unsigned int len)
  2879. {
  2880. if (image_count >= BR_MAX_IMAGES) {
  2881. if (bg)
  2882. doc.nodes[node].bg_img_index = -2;
  2883. else
  2884. doc.nodes[node].img_index = -2;
  2885. return;
  2886. }
  2887. if (decode_image_data(data, len, &images[image_count]) == 0) {
  2888. if (bg)
  2889. doc.nodes[node].bg_img_index = (short)image_count;
  2890. else
  2891. doc.nodes[node].img_index = (short)image_count;
  2892. image_count++;
  2893. preload_loaded++;
  2894. layout_valid = 0;
  2895. } else {
  2896. if (bg)
  2897. doc.nodes[node].bg_img_index = -2;
  2898. else
  2899. doc.nodes[node].img_index = -2;
  2900. }
  2901. ngui_invalidate(&ui);
  2902. }
  2903. /* Harvest one completed worker. Returns 1 when a job was finished. */
  2904. static int preload_finish_worker(struct fetch_worker *w)
  2905. {
  2906. char err[64];
  2907. int rv, tr = 0;
  2908. rv = fetch_worker_poll(w, err, sizeof(err));
  2909. if (rv < 0) {
  2910. preload_job_error(w);
  2911. fetch_worker_release(w);
  2912. return 1;
  2913. }
  2914. if (rv == 0)
  2915. return 0;
  2916. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  2917. image_comp_buf, BR_IMG_FILE_MAX,
  2918. &tr, err, sizeof(err));
  2919. if (rv >= 0)
  2920. preload_decode(w->node, w->bg, image_file_buf,
  2921. (unsigned int)rv);
  2922. else
  2923. preload_job_error(w);
  2924. fetch_worker_release(w);
  2925. return 1;
  2926. }
  2927. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  2928. * the number of jobs started. */
  2929. static int preload_fill_jobs(void)
  2930. {
  2931. int started = 0;
  2932. char err[64];
  2933. while (preload_active && preload_node < doc.nnode) {
  2934. unsigned int i = preload_node;
  2935. struct br_node *nd = &doc.nodes[i];
  2936. const char *src;
  2937. char url[BR_URL_MAX];
  2938. struct fetch_worker *w;
  2939. if (preload_active_jobs() >= preload_max_jobs)
  2940. break;
  2941. if (nd->type != BR_NODE_ELEM) {
  2942. preload_node++;
  2943. continue;
  2944. }
  2945. if (nd->tag != BR_TAG_IMG) {
  2946. if (nd->bg_img_index == -1) {
  2947. struct br_style bs;
  2948. style_for_node(i, &bs);
  2949. if (bs.display != BR_DISPLAY_NONE &&
  2950. !bs.vis_hidden && bs.bg_image) {
  2951. const char *bsrc =
  2952. br_bg_image_url(bs.bg_image - 1);
  2953. if (bsrc[0] &&
  2954. !contains_ci(bsrc, ".svg") &&
  2955. !starts_with(bsrc, "data:") &&
  2956. resolve_link(page_url, bsrc, url,
  2957. sizeof(url)) == 0) {
  2958. if (image_count +
  2959. preload_active_jobs() >=
  2960. BR_MAX_IMAGES) {
  2961. preload_node = doc.nnode;
  2962. break;
  2963. }
  2964. if (url[0] == '/') {
  2965. unsigned char *data = 0;
  2966. unsigned int len = 0;
  2967. preload_node = i + 1;
  2968. if (fetch_image(url,
  2969. BR_IMG_FILE_MAX,
  2970. &data, &len,
  2971. err,
  2972. sizeof(err)) == 0)
  2973. preload_decode(i, 1, data, len);
  2974. else
  2975. nd->bg_img_index = -2;
  2976. continue;
  2977. }
  2978. w = fetch_worker_alloc();
  2979. if (!w)
  2980. return started;
  2981. preload_node = i + 1;
  2982. if (fetch_worker_submit(w, url,
  2983. BR_IMG_FILE_MAX,
  2984. 0, 0, i, 1,
  2985. err,
  2986. sizeof(err)) != 0) {
  2987. nd->bg_img_index = -2;
  2988. fetch_worker_release(w);
  2989. continue;
  2990. }
  2991. w->image_job = 1;
  2992. started++;
  2993. continue;
  2994. }
  2995. }
  2996. nd->bg_img_index = -2;
  2997. }
  2998. preload_node++;
  2999. continue;
  3000. }
  3001. if (nd->img_index != -1) {
  3002. preload_node++;
  3003. continue;
  3004. }
  3005. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  3006. preload_node++;
  3007. continue;
  3008. }
  3009. src = br_src(&doc, i);
  3010. if (!src[0] || contains_ci(src, ".svg") ||
  3011. starts_with(src, "data:")) {
  3012. preload_node++;
  3013. continue;
  3014. }
  3015. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  3016. preload_node++;
  3017. continue;
  3018. }
  3019. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  3020. preload_node = doc.nnode;
  3021. break;
  3022. }
  3023. /* Do not stop at the first below-fold image: DOM order is
  3024. * not visual order, and a footer/ad image early in the DOM
  3025. * used to hide every later article image from the loader. */
  3026. if (img_top[i] >
  3027. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  3028. preload_pending = 1;
  3029. preload_node++;
  3030. continue;
  3031. }
  3032. if (url[0] == '/') {
  3033. unsigned char *data = 0;
  3034. unsigned int len = 0;
  3035. preload_node = i + 1;
  3036. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  3037. err, sizeof(err)) == 0)
  3038. preload_decode(i, 0, data, len);
  3039. else
  3040. nd->img_index = -2;
  3041. continue;
  3042. }
  3043. w = fetch_worker_alloc();
  3044. if (!w)
  3045. return started;
  3046. preload_node = i + 1;
  3047. {
  3048. char msg[64];
  3049. unsigned int n = 0;
  3050. s_append(msg, &n, "Loading images ", sizeof(msg));
  3051. s_append_dec(msg, &n,
  3052. (unsigned int)preload_loaded + 1,
  3053. sizeof(msg));
  3054. s_append(msg, &n, "...", sizeof(msg));
  3055. set_status(msg, 0, 0);
  3056. }
  3057. if (fetch_worker_submit(w, url, BR_IMG_FILE_MAX, 0, 0, i, 0,
  3058. err, sizeof(err)) != 0) {
  3059. nd->img_index = -2;
  3060. fetch_worker_release(w);
  3061. continue;
  3062. }
  3063. w->image_job = 1;
  3064. started++;
  3065. }
  3066. return started;
  3067. }
  3068. static void preload_step(void)
  3069. {
  3070. unsigned int batch = 0;
  3071. if (!preload_active)
  3072. return;
  3073. if (cancel_fetch || pending_action) {
  3074. preload_active = 0;
  3075. preload_pending = 0;
  3076. fetch_workers_cancel_busy();
  3077. return;
  3078. }
  3079. for (;;) {
  3080. int started = preload_fill_jobs();
  3081. int done = 0;
  3082. int i;
  3083. for (i = 0; i < FETCH_WORKERS; i++) {
  3084. if (!fetch_workers[i].busy)
  3085. continue;
  3086. if (preload_finish_worker(&fetch_workers[i]))
  3087. done++;
  3088. if (batch + done >= 4)
  3089. break;
  3090. }
  3091. batch += (unsigned int)done;
  3092. if (batch >= 4)
  3093. return;
  3094. if (!started && !done)
  3095. break;
  3096. }
  3097. if (preload_active && preload_node >= doc.nnode &&
  3098. preload_active_jobs() == 0) {
  3099. preload_active = 0;
  3100. if (preload_pending)
  3101. preload_scroll = page_scroll.offset;
  3102. else
  3103. preload_pending = 0;
  3104. /* Keep the now idle helpers and their connections; a later
  3105. * navigation reuses them. They exit after ten idle seconds,
  3106. * and losing window focus stops them at once. */
  3107. set_status(post_status_text, post_status_error, post_status_ttl);
  3108. ngui_invalidate(&ui);
  3109. }
  3110. }
  3111. /* Set by navigate() when it turned a typed bare host into https://; the next
  3112. * load_page() consumes it and may retry over http. */
  3113. static int nav_https_upgraded;
  3114. /* Errors that mean "https is not served here" rather than "the site is
  3115. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  3116. static int https_fallback_error(int e)
  3117. {
  3118. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  3119. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  3120. e == UHTTP_ERR_RESET;
  3121. }
  3122. static void history_push(const char *url)
  3123. {
  3124. if (!url || !url[0])
  3125. return;
  3126. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  3127. s_eq(history[hist_pos], url))
  3128. return;
  3129. if (hist_len > 0 && hist_pos + 1 < hist_len)
  3130. hist_len = hist_pos + 1;
  3131. if (hist_len < BR_HISTORY) {
  3132. s_copy(history[hist_len], url, BR_URL_MAX);
  3133. hist_pos = hist_len;
  3134. hist_len++;
  3135. } else {
  3136. int i;
  3137. for (i = 1; i < BR_HISTORY; i++)
  3138. s_copy(history[i - 1], history[i], BR_URL_MAX);
  3139. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  3140. hist_pos = BR_HISTORY - 1;
  3141. }
  3142. }
  3143. static void load_page(const char *url, int local, int push)
  3144. {
  3145. unsigned char *body = 0;
  3146. unsigned int len = 0;
  3147. int truncated = 0;
  3148. struct img_info image_info;
  3149. char ctype[64];
  3150. char final[BR_URL_MAX];
  3151. char err[80];
  3152. const char *detail = 0;
  3153. const char *post = pending_post_len ? pending_post : 0;
  3154. unsigned int post_len = pending_post_len;
  3155. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  3156. int upgraded = nav_https_upgraded;
  3157. int rv;
  3158. nav_https_upgraded = 0;
  3159. final[0] = '\0';
  3160. pending_post_len = 0;
  3161. cancel_fetch = 0;
  3162. preload_active = 0;
  3163. preload_pending = 0;
  3164. fetch_workers_cancel_busy();
  3165. js_browser_stop();
  3166. js_last_status[0] = '\0';
  3167. js_last_error = 0;
  3168. heap_clear();
  3169. image_reset();
  3170. form_reset_state();
  3171. layout_valid = 0;
  3172. page_scroll.offset = 0;
  3173. page_scroll.dragging = 0;
  3174. page_title[0] = '\0';
  3175. page_loading = 1;
  3176. page_is_local = local;
  3177. s_copy(page_url, url, sizeof(page_url));
  3178. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3179. url_in.len = s_len(url_in.text);
  3180. url_in.cursor = url_in.len;
  3181. url_in.scroll = 0;
  3182. ngui_set_focus(&ui, 0);
  3183. if (final[0])
  3184. final[0] = '\0';
  3185. if (push)
  3186. history_push(url);
  3187. set_status("Loading...", 0, 0);
  3188. ngui_invalidate(&ui);
  3189. /* heap_clear() detaches the fonts, so attach them again before the
  3190. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  3191. if (heap_start() != 0) {
  3192. show_error("Out of memory", "Cannot allocate the page buffer");
  3193. return;
  3194. }
  3195. br_parse_plain(&doc, "", 0); /* blank while loading */
  3196. ngui_font_attach(&ui);
  3197. redraw_now();
  3198. browser_rules_alloc();
  3199. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  3200. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  3201. &truncated, post, post_len);
  3202. if (rv == FETCH_ABORT)
  3203. return;
  3204. /* Capture the page timing before CSS/script/image fetches overwrite the
  3205. * shared fetch_meta block. */
  3206. if (rv == 0 && !local) {
  3207. page_open_ms = fetch_meta.open_ms;
  3208. page_first_ms = fetch_meta.first_ms;
  3209. page_total_ms = fetch_meta.total_ms;
  3210. }
  3211. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  3212. https_fallback_error(fetch_last_error)) {
  3213. char http_url[BR_URL_MAX];
  3214. unsigned int n = 0;
  3215. s_append(http_url, &n, "http://", sizeof(http_url));
  3216. s_append(http_url, &n, url + 8, sizeof(http_url));
  3217. /* Replace the https entry instead of adding a second one. */
  3218. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  3219. s_eq(history[hist_pos], url))
  3220. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  3221. load_page(http_url, 0, 0);
  3222. return;
  3223. }
  3224. if (rv != 0) {
  3225. detail = err;
  3226. show_error("Cannot load this page", detail);
  3227. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3228. url_in.len = s_len(url_in.text);
  3229. url_in.cursor = url_in.len;
  3230. url_in.scroll = 0;
  3231. return;
  3232. }
  3233. if (!local)
  3234. origin_cache_learn(url, final[0] ? final : url);
  3235. page_is_local = local;
  3236. if (final[0]) {
  3237. s_copy(page_url, final, sizeof(page_url));
  3238. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3239. url_in.len = s_len(url_in.text);
  3240. url_in.cursor = url_in.len;
  3241. url_in.scroll = 0;
  3242. }
  3243. if (contains_ci(ctype, "text/plain")) {
  3244. br_parse_plain(&doc, (const char *)body, len);
  3245. } else if (contains_ci(ctype, "image/") ||
  3246. (!contains_ci(ctype, "text/html") &&
  3247. img_sniff(body, len, &image_info) == 0)) {
  3248. unsigned int node = br_parse_image_doc(&doc, page_url);
  3249. if (node)
  3250. decode_direct_image(body, len, node);
  3251. s_copy(page_title, "Image", sizeof(page_title));
  3252. } else {
  3253. br_set_viewport(ui.w);
  3254. br_parse(&doc, (const char *)body, len);
  3255. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  3256. sizeof(page_title));
  3257. if (load_stylesheets() == FETCH_ABORT)
  3258. return;
  3259. if (pending_action)
  3260. return;
  3261. }
  3262. preload_begin();
  3263. page_loading = 0;
  3264. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3265. url_in.len = s_len(url_in.text);
  3266. url_in.cursor = url_in.len;
  3267. url_in.scroll = 0;
  3268. ngui_set_focus(&ui, 0);
  3269. /* Paint the parsed page before fetching/running scripts. A slow
  3270. * remote <script src> then does not hide the page behind the loading
  3271. * screen; the fetch helper pumps this UI while it waits. */
  3272. set_status("Loading scripts...", 0, 0);
  3273. redraw_now();
  3274. /* Start one image download before the scripts. The other workers
  3275. * fetch the external script bodies in parallel, and the remaining
  3276. * images start as soon as the script phase ends. */
  3277. preload_max_jobs = 1;
  3278. preload_fill_jobs();
  3279. preload_wait = 0;
  3280. run_page_scripts();
  3281. preload_max_jobs = FETCH_WORKERS;
  3282. if (pending_action)
  3283. return;
  3284. post_status_text[0] = '\0';
  3285. post_status_error = 0;
  3286. post_status_ttl = 0;
  3287. if (js_last_status[0]) {
  3288. s_copy(post_status_text, js_last_status,
  3289. sizeof(post_status_text));
  3290. post_status_error = js_last_error;
  3291. post_status_ttl = 8000;
  3292. } else if (truncated) {
  3293. s_copy(post_status_text, "Page truncated at the buffer limit",
  3294. sizeof(post_status_text));
  3295. post_status_ttl = 6000;
  3296. } else if (doc.truncated) {
  3297. s_copy(post_status_text, "Page truncated by the parser",
  3298. sizeof(post_status_text));
  3299. post_status_ttl = 6000;
  3300. } else if (page_total_ms) {
  3301. unsigned int n = 0;
  3302. if (starts_with(page_url, "https://"))
  3303. s_append(post_status_text, &n,
  3304. "HTTPS (not verified), ",
  3305. sizeof(post_status_text));
  3306. else
  3307. s_append(post_status_text, &n, "Loaded in ",
  3308. sizeof(post_status_text));
  3309. s_append_dec(post_status_text, &n, page_total_ms,
  3310. sizeof(post_status_text));
  3311. s_append(post_status_text, &n, " ms (headers ",
  3312. sizeof(post_status_text));
  3313. s_append_dec(post_status_text, &n, page_open_ms,
  3314. sizeof(post_status_text));
  3315. s_append(post_status_text, &n, " ms", sizeof(post_status_text));
  3316. if (page_first_ms) {
  3317. s_append(post_status_text, &n, ", first byte ",
  3318. sizeof(post_status_text));
  3319. s_append_dec(post_status_text, &n, page_first_ms,
  3320. sizeof(post_status_text));
  3321. s_append(post_status_text, &n, " ms",
  3322. sizeof(post_status_text));
  3323. }
  3324. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  3325. post_status_ttl = 6000;
  3326. } else if (starts_with(page_url, "https://")) {
  3327. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  3328. sizeof(post_status_text));
  3329. post_status_ttl = 6000;
  3330. }
  3331. set_status(post_status_text, post_status_error, post_status_ttl);
  3332. ngui_invalidate(&ui);
  3333. }
  3334. static void load_home(int push)
  3335. {
  3336. pending_post_len = 0;
  3337. cancel_fetch = 0;
  3338. preload_active = 0;
  3339. preload_pending = 0;
  3340. js_browser_stop();
  3341. js_last_status[0] = '\0';
  3342. js_last_error = 0;
  3343. heap_clear();
  3344. image_reset();
  3345. form_reset_state();
  3346. layout_valid = 0;
  3347. page_scroll.offset = 0;
  3348. page_scroll.dragging = 0;
  3349. page_loading = 1;
  3350. page_is_local = 0;
  3351. s_copy(page_url, "about:home", sizeof(page_url));
  3352. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3353. url_in.len = s_len(url_in.text);
  3354. url_in.cursor = url_in.len;
  3355. url_in.scroll = 0;
  3356. ngui_set_focus(&ui, 0);
  3357. if (push)
  3358. history_push(page_url);
  3359. ngui_invalidate(&ui);
  3360. /* See load_page(): reattach the fonts before the first redraw. */
  3361. if (heap_start() != 0) {
  3362. show_error("Out of memory", "Cannot allocate the browser heap");
  3363. return;
  3364. }
  3365. br_parse_plain(&doc, "", 0);
  3366. ngui_font_attach(&ui);
  3367. redraw_now();
  3368. browser_rules_alloc();
  3369. {
  3370. static const char home[] =
  3371. "<html><head><title>NebOS Browser</title><style>"
  3372. "body { margin: 10px; color: #e4e6f0; }"
  3373. "h1 { color: #7fb0ff; }"
  3374. ".box { background-color: #262b3a; margin: 12px; "
  3375. "padding: 10px; }"
  3376. "a { color: #7fb0ff; }"
  3377. "pre { background-color: #32384a; }"
  3378. "</style></head><body>"
  3379. "<h1>NebOS Browser</h1>"
  3380. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  3381. "shared HTTP client and the image library.</p>"
  3382. "<div class=\"box\"><b>Try:</b>"
  3383. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  3384. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  3385. "<li><a href=\"/floppy1/JS.HTM\">/"
  3386. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  3387. "<li><a href=\"http://10.0.2.2:8000/\">"
  3388. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  3389. "<li><a href=\"https://example.com/\">"
  3390. "https://example.com/</a> (TLS, not verified)</li>"
  3391. "</ul></div>"
  3392. "<p>Type a URL in the bar above. Esc closes the "
  3393. "window, Ctrl+L focuses the address bar.</p>"
  3394. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  3395. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  3396. "</body></html>";
  3397. br_set_viewport(ui.w);
  3398. br_parse(&doc, home, sizeof(home) - 1);
  3399. br_parse_inline_css(&doc);
  3400. br_reset_styles(&doc);
  3401. s_copy(page_title, doc.title, sizeof(page_title));
  3402. }
  3403. post_status_text[0] = '\0';
  3404. post_status_error = 0;
  3405. post_status_ttl = 0;
  3406. page_loading = 0;
  3407. set_status("", 0, 0);
  3408. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3409. url_in.len = s_len(url_in.text);
  3410. url_in.cursor = url_in.len;
  3411. url_in.scroll = 0;
  3412. ngui_set_focus(&ui, 0);
  3413. ngui_invalidate(&ui);
  3414. }
  3415. /* Extensions the browser opens from the local filesystem. A dotted input
  3416. * with one of these still resolves relative to the cwd. */
  3417. static int local_file_ext(const char *s)
  3418. {
  3419. static const char *const exts[] = {
  3420. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  3421. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  3422. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  3423. "cfg", "conf", 0
  3424. };
  3425. unsigned int i = 0, start = 0, len = 0, e;
  3426. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  3427. s[i] != '#') {
  3428. if (s[i] == '.') {
  3429. start = i + 1;
  3430. len = 0;
  3431. } else if (start) {
  3432. len++;
  3433. }
  3434. i++;
  3435. }
  3436. if (!len)
  3437. return 0;
  3438. for (e = 0; exts[e]; e++) {
  3439. const char *x = exts[e];
  3440. unsigned int xn = s_len(x), k;
  3441. if (xn != len)
  3442. continue;
  3443. for (k = 0; k < len; k++) {
  3444. char a = s[start + k];
  3445. if (a >= 'A' && a <= 'Z')
  3446. a = (char)(a - 'A' + 'a');
  3447. if (a != x[k])
  3448. break;
  3449. }
  3450. if (k == len)
  3451. return 1;
  3452. }
  3453. return 0;
  3454. }
  3455. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  3456. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  3457. * Enter to the first network request. */
  3458. static int looks_like_host(const char *s)
  3459. {
  3460. unsigned int i = 0;
  3461. int dot = 0;
  3462. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  3463. s[i] != ':') {
  3464. char c = s[i];
  3465. if (c == '.') {
  3466. dot = 1;
  3467. } else if (!((c >= 'a' && c <= 'z') ||
  3468. (c >= 'A' && c <= 'Z') ||
  3469. (c >= '0' && c <= '9') ||
  3470. c == '-' || c == '_')) {
  3471. return 0;
  3472. }
  3473. i++;
  3474. }
  3475. return dot && i > 0 && !local_file_ext(s);
  3476. }
  3477. static void load_remote(const char *url, int push)
  3478. {
  3479. char canon[BR_URL_MAX];
  3480. s_copy(canon, url, sizeof(canon));
  3481. origin_cache_apply(canon, sizeof(canon));
  3482. load_page(canon, 0, push);
  3483. }
  3484. static void navigate(const char *input, int push)
  3485. {
  3486. char target[BR_URL_MAX];
  3487. char *t;
  3488. if (!input)
  3489. return;
  3490. s_copy(target, input, sizeof(target));
  3491. t = trim(target);
  3492. if (!t[0])
  3493. return;
  3494. if (s_eq(t, "about:home")) {
  3495. load_home(push);
  3496. return;
  3497. }
  3498. if (starts_with(t, "file://")) {
  3499. make_abs_local(t + 7, target, sizeof(target));
  3500. load_page(target, 1, push);
  3501. return;
  3502. }
  3503. if (is_http(t)) {
  3504. load_remote(t, push);
  3505. return;
  3506. }
  3507. if (t[0] == '/') {
  3508. make_abs_local(t, target, sizeof(target));
  3509. load_page(target, 1, push);
  3510. return;
  3511. }
  3512. if (!looks_like_host(t)) {
  3513. struct sys_stat st;
  3514. if (u_stat(t, &st) == 0 && !st.is_dir) {
  3515. make_abs_local(t, target, sizeof(target));
  3516. load_page(target, 1, push);
  3517. return;
  3518. }
  3519. }
  3520. {
  3521. /* A typed bare host tries https first: nearly every site
  3522. * redirects http -> https anyway, and that hop costs a whole
  3523. * extra connection. load_page() falls back to http when the
  3524. * https connection itself fails. */
  3525. char with_scheme[BR_URL_MAX];
  3526. unsigned int n = 0;
  3527. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  3528. s_append(with_scheme, &n, t, sizeof(with_scheme));
  3529. nav_https_upgraded = 1;
  3530. load_remote(with_scheme, push);
  3531. }
  3532. }
  3533. /* ---- layout ---- */
  3534. static struct ufont_face *style_face(const struct br_style *st)
  3535. {
  3536. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  3537. return font_faces[st->font_face - 1];
  3538. return 0;
  3539. }
  3540. static struct ufont_face *run_face(const struct lay_run *r)
  3541. {
  3542. if (r->font_face && r->font_face <= BR_MAX_FACES)
  3543. return font_faces[r->font_face - 1];
  3544. return 0;
  3545. }
  3546. static unsigned int face_text_width(struct ngui *gui,
  3547. const struct br_style *st,
  3548. const char *s, unsigned int n)
  3549. {
  3550. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  3551. st->bold, st->italic, st->mono);
  3552. }
  3553. static int face_line_height(struct ngui *gui, const struct br_style *st)
  3554. {
  3555. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  3556. st->mono);
  3557. }
  3558. static unsigned int run_text_width(struct ngui *gui,
  3559. const struct lay_run *r,
  3560. const char *s, unsigned int n)
  3561. {
  3562. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  3563. r->bold, r->italic, r->mono);
  3564. }
  3565. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  3566. {
  3567. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  3568. r->mono);
  3569. }
  3570. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  3571. {
  3572. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  3573. }
  3574. static struct br_style base_style(void)
  3575. {
  3576. struct br_style s = { 0 };
  3577. s.color = ui.theme.text;
  3578. s.bg = ui.theme.bg;
  3579. s.has_bg = 0;
  3580. for (int i = 0; i < 4; i++) {
  3581. s.border_c[i] = 0;
  3582. s.border_w[i] = 0;
  3583. s.border_s[i] = BR_BORDER_SOLID;
  3584. }
  3585. s.font_px = 16;
  3586. s.bold = 0;
  3587. s.italic = 0;
  3588. s.mono = 0;
  3589. s.underline = 0;
  3590. s.strike = 0;
  3591. s.overline = 0;
  3592. s.align = BR_ALIGN_LEFT;
  3593. s.display = BR_DISPLAY_BLOCK;
  3594. s.no_bullet = 0;
  3595. s.list_style = BR_LIST_AUTO;
  3596. s.uppercase = 0;
  3597. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  3598. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  3599. s.width = s.max_width = s.min_width = 0;
  3600. s.height = s.min_height = s.max_height = 0;
  3601. s.box_sizing = 0;
  3602. s.ml_auto = s.mr_auto = 0;
  3603. s.line_h_pct = 0;
  3604. s.line_h_px = 0;
  3605. s.mt = s.mb = s.ml = s.mr = 0;
  3606. s.pt = s.pb = s.pl = s.pr = 0;
  3607. return s;
  3608. }
  3609. /* Resolve a margin/padding raw value. Percentages use the containing
  3610. * block width for all four sides, as CSS specifies. */
  3611. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  3612. {
  3613. if (unit == 1)
  3614. return base * v / 10000;
  3615. if (unit == 2)
  3616. return st->font_px * v / 100;
  3617. if (unit == 3)
  3618. return (int)br_root_font_px() * v / 100;
  3619. if (unit == 4)
  3620. return 0;
  3621. return v;
  3622. }
  3623. static int mp_px(const struct br_style *st, int side, int base)
  3624. {
  3625. int raw;
  3626. switch (side) {
  3627. case 0: raw = st->mt; break;
  3628. case 1: raw = st->mr; break;
  3629. case 2: raw = st->mb; break;
  3630. case 3: raw = st->ml; break;
  3631. case 4: raw = st->pt; break;
  3632. case 5: raw = st->pr; break;
  3633. case 6: raw = st->pb; break;
  3634. default: raw = st->pl; break;
  3635. }
  3636. if (st->mp_unit[side] == 5)
  3637. return base * raw / 100 + st->mp_calc_px[side];
  3638. return css_mp_px(st, raw, st->mp_unit[side], base);
  3639. }
  3640. static int style_width_px(const struct br_style *st, int base)
  3641. {
  3642. if (st->width_kind == 1)
  3643. return st->width;
  3644. if (st->width_kind == 2)
  3645. return base * (int)st->width / 100;
  3646. if (st->width_kind == 3)
  3647. return base * st->width_calc_pct / 100 + st->width_calc_px;
  3648. return 0;
  3649. }
  3650. static int style_height_px(const struct br_style *st, int base)
  3651. {
  3652. if (st->height_kind == 1)
  3653. return st->height;
  3654. if (st->height_kind == 2)
  3655. return base * (int)st->height / 100;
  3656. if (st->height_kind == 3)
  3657. return base * st->height_calc_pct / 100 + st->height_calc_px;
  3658. return 0;
  3659. }
  3660. static int css_size(unsigned char kind, int val, int base)
  3661. {
  3662. if (kind == 1)
  3663. return val;
  3664. if (kind == 2)
  3665. return base * val / 100;
  3666. return -1;
  3667. }
  3668. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  3669. int thick, int horizontal, unsigned short color,
  3670. unsigned char style)
  3671. {
  3672. int pos;
  3673. if (len <= 0 || thick <= 0)
  3674. return;
  3675. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  3676. if (horizontal)
  3677. ngui_fill_rect(ui, (struct ngui_rect){
  3678. x, y, len, thick}, color);
  3679. else
  3680. ngui_fill_rect(ui, (struct ngui_rect){
  3681. x, y, thick, len}, color);
  3682. return;
  3683. }
  3684. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  3685. int seg = len - pos;
  3686. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  3687. seg = style == BR_BORDER_DASHED ? 4 : 2;
  3688. if (horizontal)
  3689. ngui_fill_rect(ui, (struct ngui_rect){
  3690. x + pos, y, seg, thick}, color);
  3691. else
  3692. ngui_fill_rect(ui, (struct ngui_rect){
  3693. x, y + pos, thick, seg}, color);
  3694. }
  3695. }
  3696. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  3697. const struct br_style *st)
  3698. {
  3699. int top = st->border_w[0], right = st->border_w[1];
  3700. int bottom = st->border_w[2], left = st->border_w[3];
  3701. if (r.w <= 0 || r.h <= 0)
  3702. return;
  3703. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  3704. int i;
  3705. for (i = 0; i < 4; i++)
  3706. if (st->border_w[i]) {
  3707. ngui_fill_rect(ui, r, st->border_c[i]);
  3708. break;
  3709. }
  3710. return;
  3711. }
  3712. if (top)
  3713. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  3714. st->border_c[0], st->border_s[0]);
  3715. if (bottom)
  3716. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  3717. st->border_c[2], st->border_s[2]);
  3718. if (left)
  3719. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  3720. left, 0, st->border_c[3], st->border_s[3]);
  3721. if (right)
  3722. draw_border_side(ui, r.x + r.w - right, r.y + top,
  3723. r.h - top - bottom, right, 0,
  3724. st->border_c[1], st->border_s[1]);
  3725. }
  3726. static void transform_origin(const struct br_style *st, int w, int h,
  3727. int *ox, int *oy)
  3728. {
  3729. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  3730. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  3731. }
  3732. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  3733. unsigned int a)
  3734. {
  3735. unsigned int dr, dg, db, sr, sg, sb;
  3736. if (a >= 255)
  3737. return s;
  3738. dr = (d >> 11) & 31;
  3739. dg = (d >> 5) & 63;
  3740. db = d & 31;
  3741. sr = (s >> 11) & 31;
  3742. sg = (s >> 5) & 63;
  3743. sb = s & 31;
  3744. dr = (dr * (255 - a) + sr * a) / 255;
  3745. dg = (dg * (255 - a) + sg * a) / 255;
  3746. db = (db * (255 - a) + sb * a) / 255;
  3747. return (unsigned short)((dr << 11) | (dg << 5) | db);
  3748. }
  3749. /* Paint a solid box through scale()/rotate() around transform-origin. This
  3750. * transforms the element's own background box; text and descendants keep
  3751. * their layout (documented approximation). */
  3752. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  3753. unsigned short color,
  3754. const struct br_style *st)
  3755. {
  3756. double sx = st->scale_x / 100.0;
  3757. double sy = st->scale_y / 100.0;
  3758. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  3759. double c = cos(th), sn = sin(th);
  3760. int ox, oy, minx, miny, maxx, maxy, x, y;
  3761. double ax, ay;
  3762. double px[4], py[4];
  3763. int cx1, cy1, cx2, cy2, i;
  3764. if (sx == 0)
  3765. sx = 0.01;
  3766. if (sy == 0)
  3767. sy = 0.01;
  3768. transform_origin(st, box.w, box.h, &ox, &oy);
  3769. ax = box.x + ox;
  3770. ay = box.y + oy;
  3771. px[0] = -ox; py[0] = -oy;
  3772. px[1] = box.w - ox; py[1] = -oy;
  3773. px[2] = box.w - ox; py[2] = box.h - oy;
  3774. px[3] = -ox; py[3] = box.h - oy;
  3775. minx = miny = 1000000;
  3776. maxx = maxy = -1000000;
  3777. for (i = 0; i < 4; i++) {
  3778. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  3779. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  3780. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  3781. if (dx < minx) minx = dx;
  3782. if (dx > maxx) maxx = dx;
  3783. if (dy < miny) miny = dy;
  3784. if (dy > maxy) maxy = dy;
  3785. }
  3786. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  3787. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  3788. cx2 = page_rect.x + page_rect.w - 12;
  3789. cy2 = page_rect.y + page_rect.h;
  3790. if (cx2 > gui->w) cx2 = gui->w;
  3791. if (cy2 > gui->h) cy2 = gui->h;
  3792. if (minx < cx1) minx = cx1;
  3793. if (miny < cy1) miny = cy1;
  3794. if (maxx > cx2 - 1) maxx = cx2 - 1;
  3795. if (maxy > cy2 - 1) maxy = cy2 - 1;
  3796. for (y = miny; y <= maxy; y++) {
  3797. for (x = minx; x <= maxx; x++) {
  3798. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  3799. double rx = dx * c + dy * sn;
  3800. double ry = -dx * sn + dy * c;
  3801. double bx = rx / sx + ox;
  3802. double by = ry / sy + oy;
  3803. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  3804. gui->px[y * gui->w + x] = color;
  3805. }
  3806. }
  3807. }
  3808. static void draw_image_transformed(struct ngui *gui,
  3809. const struct img_image *im,
  3810. int x, int y, int w, int h,
  3811. int sx100, int sy100, int rot100,
  3812. int origin_x, int origin_y,
  3813. int origin_x_kind, int origin_y_kind)
  3814. {
  3815. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  3816. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  3817. double c = cos(th), sn = sin(th);
  3818. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  3819. double ax, ay;
  3820. double bx[4], by[4];
  3821. int cx1, cy1, cx2, cy2;
  3822. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  3823. return;
  3824. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  3825. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  3826. ax = x + ox;
  3827. ay = y + oy;
  3828. bx[0] = -ox; by[0] = -oy;
  3829. bx[1] = w - ox; by[1] = -oy;
  3830. bx[2] = w - ox; by[2] = h - oy;
  3831. bx[3] = -ox; by[3] = h - oy;
  3832. minx = miny = 1000000;
  3833. maxx = maxy = -1000000;
  3834. for (i = 0; i < 4; i++) {
  3835. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  3836. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  3837. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  3838. if (dx < minx) minx = dx;
  3839. if (dx > maxx) maxx = dx;
  3840. if (dy < miny) miny = dy;
  3841. if (dy > maxy) maxy = dy;
  3842. }
  3843. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  3844. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  3845. cx2 = page_rect.x + page_rect.w - 12;
  3846. cy2 = page_rect.y + page_rect.h;
  3847. if (cx2 > gui->w) cx2 = gui->w;
  3848. if (cy2 > gui->h) cy2 = gui->h;
  3849. if (minx < cx1) minx = cx1;
  3850. if (miny < cy1) miny = cy1;
  3851. if (maxx > cx2 - 1) maxx = cx2 - 1;
  3852. if (maxy > cy2 - 1) maxy = cy2 - 1;
  3853. for (py = miny; py <= maxy; py++) {
  3854. for (px = minx; px <= maxx; px++) {
  3855. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  3856. double rx = dx * c + dy * sn;
  3857. double ry = -dx * sn + dy * c;
  3858. double fx = rx / sx + ox;
  3859. double fy = ry / sy + oy;
  3860. int ix, iy;
  3861. unsigned int si, a;
  3862. unsigned short src;
  3863. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  3864. continue;
  3865. ix = (int)(fx * (double)im->w / w);
  3866. iy = (int)(fy * (double)im->h / h);
  3867. if (ix < 0 || ix >= (int)im->w ||
  3868. iy < 0 || iy >= (int)im->h)
  3869. continue;
  3870. si = (unsigned int)iy * im->w + (unsigned int)ix;
  3871. src = im->px[si];
  3872. a = im->alpha ? im->alpha[si] : 255;
  3873. gui->px[py * gui->w + px] =
  3874. a >= 255 ? src :
  3875. blend_rgb565(gui->px[py * gui->w + px],
  3876. src, a);
  3877. }
  3878. }
  3879. }
  3880. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  3881. unsigned int node, const struct br_style *st)
  3882. {
  3883. struct br_image *bi;
  3884. struct img_blit b;
  3885. int tw, th, x, y, rep_x, rep_y, posx, posy;
  3886. unsigned int scale = 65536;
  3887. int legacy, tiles = 0, rows = 0;
  3888. int cx1, cy1, cx2, cy2;
  3889. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  3890. return;
  3891. if (doc.nodes[node].bg_img_index < 0 ||
  3892. doc.nodes[node].bg_img_index >= image_count)
  3893. return;
  3894. bi = &images[doc.nodes[node].bg_img_index];
  3895. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  3896. return;
  3897. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  3898. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  3899. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  3900. if (legacy) {
  3901. scale = ((unsigned int)box.w << 16) / bi->img.w;
  3902. tw = box.w;
  3903. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  3904. x = box.x;
  3905. y = box.y;
  3906. rep_x = rep_y = 0;
  3907. } else {
  3908. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  3909. unsigned int sx = ((unsigned int)box.w << 16) /
  3910. bi->img.w;
  3911. unsigned int sy = ((unsigned int)box.h << 16) /
  3912. bi->img.h;
  3913. scale = st->bg_size_kind == 3 ?
  3914. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  3915. } else if (st->bg_size_kind == 1 ||
  3916. st->bg_size_kind == 2) {
  3917. int w = st->bg_size_w;
  3918. int h = st->bg_size_h;
  3919. if (st->bg_size_kind == 2) {
  3920. if (w)
  3921. w = box.w * w / 100;
  3922. if (h)
  3923. h = box.h * h / 100;
  3924. }
  3925. if (w)
  3926. scale = ((unsigned int)w << 16) / bi->img.w;
  3927. else if (h)
  3928. scale = ((unsigned int)h << 16) / bi->img.h;
  3929. }
  3930. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  3931. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  3932. if (tw < 1)
  3933. tw = 1;
  3934. if (th < 1)
  3935. th = 1;
  3936. posx = st->bg_pos_x_kind == 1 ?
  3937. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  3938. posy = st->bg_pos_y_kind == 1 ?
  3939. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  3940. x = box.x + posx;
  3941. y = box.y + posy;
  3942. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  3943. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  3944. if (rep_x) {
  3945. int m = (x - box.x) % tw;
  3946. if (m > 0)
  3947. m -= tw;
  3948. x = box.x + m;
  3949. }
  3950. if (rep_y) {
  3951. int m = (y - box.y) % th;
  3952. if (m > 0)
  3953. m -= th;
  3954. y = box.y + m;
  3955. }
  3956. }
  3957. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  3958. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  3959. cx2 = box.x + box.w;
  3960. cy2 = box.y + box.h;
  3961. if (cx2 > page_rect.x + page_rect.w - 12)
  3962. cx2 = page_rect.x + page_rect.w - 12;
  3963. if (cy2 > page_rect.y + page_rect.h)
  3964. cy2 = page_rect.y + page_rect.h;
  3965. if (cx1 >= cx2 || cy1 >= cy2)
  3966. return;
  3967. b.dst = l->ui->px;
  3968. b.dst_w = l->ui->w;
  3969. b.dst_h = l->ui->h;
  3970. b.clip_x = cx1;
  3971. b.clip_y = cy1;
  3972. b.clip_w = cx2 - cx1;
  3973. b.clip_h = cy2 - cy1;
  3974. b.scale = scale;
  3975. b.bg = ui.theme.bg;
  3976. b.bg2 = ui.theme.bg;
  3977. b.flags = IMG_BLIT_OVER_DST;
  3978. {
  3979. int row_x = x;
  3980. for (;;) {
  3981. for (;;) {
  3982. b.x = x;
  3983. b.y = y;
  3984. img_draw(&bi->img, &b);
  3985. if (!rep_x || ++tiles > 512)
  3986. break;
  3987. x += tw;
  3988. if (x >= box.x + box.w)
  3989. break;
  3990. }
  3991. if (!rep_y || ++rows > 64)
  3992. break;
  3993. y += th;
  3994. if (y >= box.y + box.h)
  3995. break;
  3996. x = row_x;
  3997. }
  3998. }
  3999. }
  4000. static int run_width(const struct lay_run *r)
  4001. {
  4002. if (r->img >= 0)
  4003. return r->iw;
  4004. if (r->img == -2)
  4005. return r->iw;
  4006. return (int)r->w;
  4007. }
  4008. static void start_line(struct lay *l, const struct br_style *st)
  4009. {
  4010. (void)st;
  4011. if (l->nruns == 0) {
  4012. l->line_y = l->y;
  4013. l->line_h = 0;
  4014. }
  4015. l->line_left = l->left;
  4016. l->line_right = l->right;
  4017. if (l->float_active && l->line_y < l->float_bottom) {
  4018. if (l->float_left > l->line_left)
  4019. l->line_left = l->float_left;
  4020. if (l->float_right < l->line_right)
  4021. l->line_right = l->float_right;
  4022. }
  4023. if (l->line_right < l->line_left + 8)
  4024. l->line_right = l->line_left + 8;
  4025. l->line_x = l->line_left;
  4026. l->run_x = l->line_left;
  4027. }
  4028. static void flush_line(struct lay *l)
  4029. {
  4030. int total, x, i, vis;
  4031. if (!l->nruns && l->line_x == l->line_left) {
  4032. l->line_h = 0;
  4033. return;
  4034. }
  4035. total = l->line_x - l->line_left;
  4036. x = l->line_left;
  4037. vis = 1;
  4038. if (l->draw) {
  4039. int lh = l->line_h ? l->line_h : 16;
  4040. vis = l->line_y + lh >= page_rect.y &&
  4041. l->line_y <= page_rect.y + page_rect.h;
  4042. }
  4043. if (l->align == BR_ALIGN_CENTER)
  4044. x += (l->line_right - l->line_left - total) / 2;
  4045. else if (l->align == BR_ALIGN_RIGHT)
  4046. x = l->line_right - total;
  4047. if (x < l->line_left)
  4048. x = l->line_left;
  4049. for (i = 0; i < l->nruns; i++) {
  4050. struct lay_run *r = &l->runs[i];
  4051. int w = run_width(r);
  4052. int ry = l->line_y + r->dy;
  4053. x += r->gap;
  4054. if (l->draw && vis) {
  4055. if (r->form) {
  4056. unsigned int node = r->form - 1;
  4057. struct form_state *fs = form_get(node, 1);
  4058. int hh = r->ih ? r->ih : 20;
  4059. int focused = form_focus == node;
  4060. int disabled = r->form_disabled;
  4061. unsigned short bg = l->ui->theme.panel_alt;
  4062. unsigned short fg = disabled ? 0x8410 : r->color;
  4063. struct ngui_rect box = {x, ry, w, hh};
  4064. if (r->form_kind == FORM_CHECKBOX ||
  4065. r->form_kind == FORM_RADIO) {
  4066. ngui_fill_rect(l->ui, box, bg);
  4067. ngui_frame(l->ui, box,
  4068. focused ? l->ui->theme.accent :
  4069. l->ui->theme.border);
  4070. if (fs && fs->checked) {
  4071. struct ngui_rect dot = {
  4072. x + 4, ry + 4,
  4073. w > 8 ? w - 8 : 1,
  4074. hh > 8 ? hh - 8 : 1
  4075. };
  4076. if (r->form_kind == FORM_RADIO)
  4077. ngui_fill_round_rect(
  4078. l->ui, dot, 4,
  4079. 4, 4, 4,
  4080. l->ui->theme.accent);
  4081. else
  4082. ngui_fill_rect(l->ui,
  4083. dot,
  4084. l->ui->theme.accent);
  4085. }
  4086. } else {
  4087. ngui_fill_rect(l->ui, box, bg);
  4088. ngui_frame(l->ui, box,
  4089. focused ? l->ui->theme.accent :
  4090. l->ui->theme.border);
  4091. ngui_text_px_face(l->ui, run_face(r),
  4092. x + 6, ry + 2,
  4093. r->lit, s_len(r->lit),
  4094. fg, r->font_px, r->bold,
  4095. r->italic, r->mono);
  4096. if (focused && fs &&
  4097. (r->form_kind == FORM_TEXT ||
  4098. r->form_kind == FORM_PASSWORD ||
  4099. r->form_kind == FORM_TEXTAREA)) {
  4100. int cw = 0;
  4101. if (fs->len && fs->caret)
  4102. cw = (int)run_text_width(
  4103. l->ui, r, r->lit,
  4104. fs->caret < fs->len ?
  4105. fs->caret : fs->len);
  4106. ngui_fill_rect(l->ui,
  4107. (struct ngui_rect){
  4108. x + 6 + cw,
  4109. ry + 4, 1,
  4110. hh > 8 ? hh - 8 : 1
  4111. },
  4112. l->ui->theme.accent);
  4113. }
  4114. if (r->form_kind == FORM_SELECT) {
  4115. ngui_text_px(l->ui, x + w - 12,
  4116. ry + 2, "v", 1, fg,
  4117. r->font_px, 0, 0, 0);
  4118. }
  4119. }
  4120. } else if (r->img == -2) {
  4121. int hh = r->ih ? r->ih : 20;
  4122. ngui_fill_rect(l->ui,
  4123. (struct ngui_rect){x, ry, w, hh},
  4124. l->ui->theme.panel_alt);
  4125. ngui_frame(l->ui,
  4126. (struct ngui_rect){x, ry, w, hh},
  4127. l->ui->theme.border);
  4128. ngui_text_px_face(l->ui, run_face(r),
  4129. x + 6, ry + 2, r->lit,
  4130. s_len(r->lit), r->color,
  4131. r->font_px, r->bold, r->italic,
  4132. r->mono);
  4133. } else if (r->img >= 0) {
  4134. struct br_image *bi = &images[r->img];
  4135. if (bi->state == 1 && r->transform_scale) {
  4136. draw_image_transformed(l->ui, &bi->img,
  4137. x, ry, r->iw, r->ih,
  4138. r->scale_x, r->scale_y,
  4139. r->rotate_x100, r->origin_x,
  4140. r->origin_y, r->origin_x_kind,
  4141. r->origin_y_kind);
  4142. } else if (bi->state == 1) {
  4143. struct img_blit b;
  4144. b.dst = l->ui->px;
  4145. b.dst_w = l->ui->w;
  4146. b.dst_h = l->ui->h;
  4147. b.clip_x = page_rect.x;
  4148. b.clip_y = page_rect.y;
  4149. b.clip_w = page_rect.w - 12;
  4150. b.clip_h = page_rect.h;
  4151. b.x = x;
  4152. b.y = ry;
  4153. b.scale = ((unsigned int)r->iw << 16) /
  4154. bi->img.w;
  4155. b.bg = ui.theme.bg;
  4156. b.bg2 = ui.theme.bg;
  4157. b.flags = IMG_BLIT_OVER_DST;
  4158. img_draw(&bi->img, &b);
  4159. }
  4160. } else {
  4161. const char *s = r->has_lit ? r->lit :
  4162. doc.text + r->off;
  4163. unsigned int n = r->has_lit ? s_len(r->lit) :
  4164. r->len;
  4165. ngui_text_px_face(l->ui, run_face(r), x, ry,
  4166. s, n, r->color, r->font_px,
  4167. r->bold, r->italic, r->mono);
  4168. if (r->underline)
  4169. ngui_fill_rect(l->ui,
  4170. (struct ngui_rect){x,
  4171. ry + run_ascent(l->ui, r) + 2,
  4172. w, 1}, r->color);
  4173. if (r->strike)
  4174. ngui_fill_rect(l->ui,
  4175. (struct ngui_rect){x,
  4176. ry + run_ascent(l->ui, r) -
  4177. (r->font_px > 3 ?
  4178. r->font_px / 3 : 1),
  4179. w, 1}, r->color);
  4180. if (r->overline)
  4181. ngui_fill_rect(l->ui,
  4182. (struct ngui_rect){x, ry,
  4183. w, 1}, r->color);
  4184. }
  4185. if (r->form || r->href) {
  4186. if (nhits < HIT_MAX) {
  4187. struct hit *h = &hits[nhits];
  4188. unsigned int target = r->form ?
  4189. r->form - 1 : r->href;
  4190. int hh = (r->form || r->img >= 0) ?
  4191. r->ih :
  4192. run_line_height(l->ui, r);
  4193. int merge = nhits > 0 &&
  4194. hits[nhits - 1].node == target &&
  4195. hits[nhits - 1].y == ry &&
  4196. hits[nhits - 1].h == hh &&
  4197. x <= hits[nhits - 1].x +
  4198. hits[nhits - 1].w + 2;
  4199. if (merge) {
  4200. struct hit *p = &hits[nhits - 1];
  4201. int end = x + w;
  4202. if (end > p->x + p->w)
  4203. p->w = end - p->x;
  4204. } else {
  4205. h->x = x;
  4206. h->y = ry;
  4207. h->w = w;
  4208. h->h = hh;
  4209. h->node = (unsigned short)target;
  4210. nhits++;
  4211. }
  4212. }
  4213. }
  4214. }
  4215. x += w;
  4216. }
  4217. l->y += l->line_h + 2;
  4218. if (l->float_active && l->y >= l->float_bottom)
  4219. l->float_active = 0;
  4220. l->nruns = 0;
  4221. l->line_x = l->left;
  4222. l->run_x = l->left;
  4223. l->line_left = l->left;
  4224. l->line_right = l->right;
  4225. l->line_h = 0;
  4226. l->space_pending = 0;
  4227. }
  4228. static void add_run(struct lay *l, unsigned short off, unsigned short len,
  4229. const struct br_style *st, unsigned short href,
  4230. const char *lit)
  4231. {
  4232. unsigned int n = lit ? s_len(lit) : len;
  4233. const char *tp = lit ? lit : doc.text + off;
  4234. int w = (int)face_text_width(l->ui, st, tp, n);
  4235. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  4236. flush_line(l);
  4237. if (l->nruns == 0) {
  4238. l->line_y = l->y;
  4239. l->line_h = 0;
  4240. start_line(l, st);
  4241. }
  4242. {
  4243. struct lay_run *r = &l->runs[l->nruns++];
  4244. int gap = l->line_x - l->run_x;
  4245. if (gap < 0)
  4246. gap = 0;
  4247. r->gap = (unsigned short)gap;
  4248. r->off = off;
  4249. r->len = len;
  4250. r->color = st->color;
  4251. r->href = href;
  4252. r->dy = 0;
  4253. r->has_lit = 0;
  4254. r->form = 0;
  4255. r->form_kind = 0;
  4256. r->form_disabled = 0;
  4257. r->lit[0] = '\0';
  4258. if (lit && lit[0]) {
  4259. unsigned int i;
  4260. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  4261. r->lit[i] = lit[i];
  4262. r->lit[i] = '\0';
  4263. r->has_lit = 1;
  4264. }
  4265. r->img = -1;
  4266. r->iw = r->ih = 0;
  4267. r->font_px = st->font_px;
  4268. r->bold = st->bold;
  4269. r->italic = st->italic;
  4270. r->mono = st->mono;
  4271. r->font_face = st->font_face;
  4272. /* A control with its own background is a button, not body copy;
  4273. * an inherited link underline would strike through the fill. */
  4274. r->underline = st->underline && !st->has_bg;
  4275. r->strike = st->strike && !st->has_bg;
  4276. r->overline = st->overline && !st->has_bg;
  4277. r->w = (unsigned short)w;
  4278. if (r->has_lit)
  4279. r->w = (unsigned short)run_text_width(
  4280. l->ui, r, r->lit, s_len(r->lit));
  4281. w = r->w;
  4282. }
  4283. l->line_x += w;
  4284. l->run_x = l->line_x;
  4285. {
  4286. int lh = face_line_height(l->ui, st);
  4287. if (st->line_h_px)
  4288. lh = st->line_h_px;
  4289. else if (st->line_h_pct)
  4290. lh = st->font_px * st->line_h_pct / 100;
  4291. if (lh < face_line_height(l->ui, st))
  4292. lh = face_line_height(l->ui, st);
  4293. if (l->line_h < lh)
  4294. l->line_h = lh;
  4295. }
  4296. }
  4297. static void add_image_run(struct lay *l, unsigned int node,
  4298. const struct br_style *st, unsigned short href)
  4299. {
  4300. struct br_image *bi = 0;
  4301. int idx = doc.nodes[node].img_index;
  4302. int dw, dh, maxw;
  4303. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  4304. bi = &images[idx];
  4305. if (l->nruns == 0)
  4306. start_line(l, st);
  4307. if (l->space_pending &&
  4308. (l->nruns > 0 || l->line_x > l->line_left)) {
  4309. int sp = (int)face_text_width(l->ui, st, " ", 1);
  4310. if (l->line_x + sp <= l->line_right)
  4311. l->line_x += sp;
  4312. }
  4313. l->space_pending = 0;
  4314. if (!bi) {
  4315. const char *alt = br_alt(&doc, node);
  4316. struct br_style gs = *st;
  4317. char tmp[96];
  4318. unsigned int n = 0;
  4319. int w;
  4320. gs.color = BR_GRAY;
  4321. gs.underline = 0;
  4322. s_append(tmp, &n, "[", sizeof(tmp));
  4323. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  4324. s_append(tmp, &n, "]", sizeof(tmp));
  4325. w = (int)face_text_width(l->ui, &gs, tmp, n);
  4326. if (l->line_x + w > l->line_right &&
  4327. (l->nruns > 0 || l->line_x > l->line_left))
  4328. flush_line(l);
  4329. add_run(l, 0, 0, &gs, href, tmp);
  4330. if (!l->draw) {
  4331. int t = l->line_y < 0 ? 0 : l->line_y;
  4332. int hh = face_line_height(l->ui, &gs);
  4333. if (t > 65535)
  4334. t = 65535;
  4335. if (hh > 65535)
  4336. hh = 65535;
  4337. img_top[node] = (unsigned short)t;
  4338. img_h[node] = (unsigned short)hh;
  4339. }
  4340. return;
  4341. }
  4342. maxw = l->line_right - l->line_left;
  4343. if (maxw < 8)
  4344. maxw = 8;
  4345. {
  4346. int iw = bi->native_w, ih = bi->native_h;
  4347. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  4348. if (iw <= 0 || ih <= 0) {
  4349. iw = (int)bi->img.w;
  4350. ih = (int)bi->img.h;
  4351. }
  4352. dw = iw;
  4353. dh = ih;
  4354. if (doc.nodes[node].width_attr) {
  4355. int want = doc.nodes[node].width_attr;
  4356. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  4357. have_w = 1;
  4358. }
  4359. if (doc.nodes[node].height_attr) {
  4360. int want = doc.nodes[node].height_attr;
  4361. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  4362. have_h = 1;
  4363. }
  4364. if (have_w && !have_h)
  4365. dh = ih ? ih * dw / iw : 0;
  4366. if (have_h && !have_w)
  4367. dw = iw ? iw * dh / ih : 0;
  4368. if (st->width_kind) {
  4369. css_w = 1;
  4370. if (st->width_kind == 3)
  4371. dw = maxw * st->width_calc_pct / 100 +
  4372. st->width_calc_px;
  4373. else
  4374. dw = st->width_kind == 2 ?
  4375. maxw * (int)st->width / 100 :
  4376. (int)st->width;
  4377. }
  4378. if (st->height_kind) {
  4379. css_h = 1;
  4380. if (st->height_kind == 3)
  4381. dh = maxw * st->height_calc_pct / 100 +
  4382. st->height_calc_px;
  4383. else
  4384. dh = st->height_kind == 2 ?
  4385. maxw * (int)st->height / 100 :
  4386. (int)st->height;
  4387. }
  4388. if (css_w && !css_h)
  4389. dh = ih ? ih * dw / iw : 0;
  4390. if (css_h && !css_w)
  4391. dw = iw ? iw * dh / ih : 0;
  4392. if (st->max_width_kind) {
  4393. int mw = st->max_width_kind == 3 ?
  4394. maxw * st->max_width_calc_pct / 100 +
  4395. st->max_width_calc_px :
  4396. st->max_width_kind == 2 ?
  4397. maxw * (int)st->max_width / 100 :
  4398. (int)st->max_width;
  4399. if (mw > 0 && dw > mw) {
  4400. dh = iw ? ih * mw / iw : 0;
  4401. dw = mw;
  4402. }
  4403. }
  4404. }
  4405. if (dw < 8)
  4406. dw = 8;
  4407. if (dh < 8)
  4408. dh = 8;
  4409. if (dw > maxw) {
  4410. dh = dw ? dh * maxw / dw : dh;
  4411. dw = maxw;
  4412. }
  4413. if (!l->draw) {
  4414. int t = l->line_y < 0 ? 0 : l->line_y;
  4415. if (t > 65535)
  4416. t = 65535;
  4417. if (dh > 65535)
  4418. dh = 65535;
  4419. img_top[node] = (unsigned short)t;
  4420. img_h[node] = (unsigned short)dh;
  4421. }
  4422. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  4423. l->line_x > l->line_left))
  4424. flush_line(l);
  4425. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  4426. flush_line(l);
  4427. if (l->nruns == 0) {
  4428. l->line_y = l->y;
  4429. l->line_h = 0;
  4430. start_line(l, st);
  4431. }
  4432. {
  4433. struct lay_run *r = &l->runs[l->nruns++];
  4434. int gap = l->line_x - l->run_x;
  4435. if (gap < 0)
  4436. gap = 0;
  4437. r->gap = (unsigned short)gap;
  4438. r->off = 0;
  4439. r->len = 0;
  4440. r->color = 0;
  4441. r->href = href;
  4442. r->form = 0;
  4443. r->form_kind = 0;
  4444. r->form_disabled = 0;
  4445. /* Inline replaced elements honour their vertical margins; this
  4446. * is how Bootstrap's negative logo margins centre the wordmark. */
  4447. {
  4448. int idy = mp_px(st, 0, l->right - l->left);
  4449. if (idy < -2048)
  4450. idy = -2048;
  4451. if (idy > 2048)
  4452. idy = 2048;
  4453. r->dy = (signed short)idy;
  4454. }
  4455. r->has_lit = 0;
  4456. r->lit[0] = '\0';
  4457. r->img = (short)idx;
  4458. r->iw = (unsigned short)dw;
  4459. r->ih = (unsigned short)dh;
  4460. r->w = (unsigned short)dw;
  4461. r->font_px = st->font_px;
  4462. r->bold = st->bold;
  4463. r->italic = st->italic;
  4464. r->mono = st->mono;
  4465. r->font_face = st->font_face;
  4466. r->transform_scale = st->transform_scale;
  4467. r->scale_x = st->scale_x;
  4468. r->scale_y = st->scale_y;
  4469. r->rotate_x100 = st->rotate_x100;
  4470. r->origin_x = st->origin_x;
  4471. r->origin_y = st->origin_y;
  4472. r->origin_x_kind = st->origin_x_kind;
  4473. r->origin_y_kind = st->origin_y_kind;
  4474. r->underline = 0;
  4475. }
  4476. if (node < BR_MAX_NODES) {
  4477. layout_boxes[node].x = l->line_x;
  4478. layout_boxes[node].y = l->line_y +
  4479. mp_px(st, 0, l->right - l->left);
  4480. layout_boxes[node].w = dw;
  4481. layout_boxes[node].h = dh;
  4482. layout_boxes[node].valid = 1;
  4483. }
  4484. l->line_x += dw;
  4485. l->run_x = l->line_x;
  4486. if (l->line_h < dh)
  4487. l->line_h = dh;
  4488. }
  4489. static int text_width(struct lay *l, const char *s, unsigned int n,
  4490. const struct br_style *st)
  4491. {
  4492. return (int)face_text_width(l->ui, st, s, n);
  4493. }
  4494. /* Longest prefix that fits in maxw, at least one byte. */
  4495. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  4496. const struct br_style *st, int maxw)
  4497. {
  4498. unsigned int take = 0;
  4499. while (take < n) {
  4500. if (text_width(l, s, take + 1, st) > maxw)
  4501. break;
  4502. take++;
  4503. }
  4504. return take ? take : 1;
  4505. }
  4506. static void emit_word(struct lay *l, const char *s, unsigned int start,
  4507. unsigned int n, unsigned int base,
  4508. const struct br_style *st, unsigned short href)
  4509. {
  4510. int avail;
  4511. int w = text_width(l, s + start, n, st);
  4512. unsigned int off = start;
  4513. if (l->nruns == 0)
  4514. start_line(l, st);
  4515. avail = l->line_right - l->line_left;
  4516. if (st->nowrap) {
  4517. if (n)
  4518. add_run(l, (unsigned short)(base + start),
  4519. (unsigned short)n, st, href, 0);
  4520. return;
  4521. }
  4522. /* A padded/bordered one-word button can be a few pixels wider than
  4523. * the content box; keep it on one line instead of splitting it. */
  4524. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  4525. add_run(l, (unsigned short)(base + start),
  4526. (unsigned short)n, st, href, 0);
  4527. return;
  4528. }
  4529. if (l->line_x + w > l->line_right &&
  4530. (l->nruns > 0 || l->line_x > l->line_left)) {
  4531. flush_line(l);
  4532. start_line(l, st);
  4533. avail = l->line_right - l->line_left;
  4534. }
  4535. if (w <= avail) {
  4536. if (n)
  4537. add_run(l, (unsigned short)(base + start),
  4538. (unsigned short)n, st, href, 0);
  4539. return;
  4540. }
  4541. while (n > 0) {
  4542. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  4543. add_run(l, (unsigned short)(base + off),
  4544. (unsigned short)take, st, href, 0);
  4545. off += take;
  4546. n -= take;
  4547. if (n) {
  4548. flush_line(l);
  4549. start_line(l, st);
  4550. avail = l->line_right - l->line_left;
  4551. }
  4552. }
  4553. }
  4554. static void emit_text(struct lay *l, const char *s, unsigned int len,
  4555. const struct br_style *st, unsigned short href, int pre)
  4556. {
  4557. unsigned int i = 0;
  4558. unsigned int base;
  4559. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  4560. if (!s || !len)
  4561. return;
  4562. if (space_w <= 0)
  4563. space_w = 8;
  4564. if (l->nruns == 0)
  4565. start_line(l, st);
  4566. base = (unsigned int)(s - doc.text);
  4567. if (st->uppercase) {
  4568. char *p = (char *)s;
  4569. unsigned int j;
  4570. for (j = 0; j < len; j++)
  4571. if (p[j] >= 'a' && p[j] <= 'z')
  4572. p[j] = (char)(p[j] - 'a' + 'A');
  4573. }
  4574. if (pre) {
  4575. while (i < len) {
  4576. unsigned int start;
  4577. if (s[i] == '\n') {
  4578. flush_line(l);
  4579. start_line(l, st);
  4580. i++;
  4581. continue;
  4582. }
  4583. if (s[i] == ' ') {
  4584. if (l->line_x + space_w > l->line_right &&
  4585. (l->nruns > 0 || l->line_x > l->line_left)) {
  4586. flush_line(l);
  4587. start_line(l, st);
  4588. } else {
  4589. l->line_x += space_w;
  4590. }
  4591. i++;
  4592. continue;
  4593. }
  4594. start = i;
  4595. while (i < len && s[i] != ' ' && s[i] != '\n')
  4596. i++;
  4597. emit_word(l, s, start, i - start, base, st, href);
  4598. }
  4599. return;
  4600. }
  4601. while (i < len) {
  4602. unsigned int start, n;
  4603. if (s[i] == ' ') {
  4604. l->space_pending = 1;
  4605. i++;
  4606. continue;
  4607. }
  4608. start = i;
  4609. while (i < len && s[i] != ' ')
  4610. i++;
  4611. n = i - start;
  4612. if (l->space_pending &&
  4613. (l->nruns > 0 || l->line_x > l->line_left)) {
  4614. if (st->nowrap ||
  4615. l->line_x + space_w <= l->line_right)
  4616. l->line_x += space_w;
  4617. }
  4618. l->space_pending = 0;
  4619. emit_word(l, s, start, n, base, st, href);
  4620. }
  4621. }
  4622. static int list_index(unsigned int parent, unsigned int node)
  4623. {
  4624. unsigned int n = 0, i;
  4625. for (i = doc.nodes[parent].first; i && i != node;
  4626. i = doc.nodes[i].next)
  4627. if (doc.nodes[i].tag == BR_TAG_LI)
  4628. n++;
  4629. return (int)n + 1;
  4630. }
  4631. static void list_roman(char *m, unsigned int *n, int v, int upper,
  4632. unsigned int cap)
  4633. {
  4634. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  4635. 50, 40, 10, 9, 5, 4, 1 };
  4636. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  4637. "l", "xl", "x", "ix", "v", "iv", "i" };
  4638. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  4639. "L", "XL", "X", "IX", "V", "IV", "I" };
  4640. unsigned int i;
  4641. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  4642. while (v >= val[i] && *n + 1 < cap) {
  4643. const char *s = upper ? up[i] : lo[i];
  4644. while (*s && *n + 1 < cap)
  4645. m[(*n)++] = *s++;
  4646. v -= val[i];
  4647. }
  4648. }
  4649. }
  4650. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  4651. {
  4652. unsigned int n = 0;
  4653. if (style == BR_LIST_DISC) {
  4654. m[n++] = '-';
  4655. } else if (style == BR_LIST_CIRCLE) {
  4656. m[n++] = 'o';
  4657. } else if (style == BR_LIST_SQUARE) {
  4658. m[n++] = '+';
  4659. } else if (style == BR_LIST_LOWER_ALPHA ||
  4660. style == BR_LIST_UPPER_ALPHA) {
  4661. if (idx >= 1 && idx <= 26)
  4662. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  4663. 'A' : 'a') + idx - 1);
  4664. else
  4665. m[n++] = '?';
  4666. m[n++] = '.';
  4667. } else if (style == BR_LIST_LOWER_ROMAN ||
  4668. style == BR_LIST_UPPER_ROMAN) {
  4669. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  4670. if (n + 1 < cap)
  4671. m[n++] = '.';
  4672. } else {
  4673. s_append_dec(m, &n, (unsigned int)idx, cap);
  4674. if (n + 1 < cap)
  4675. m[n++] = '.';
  4676. }
  4677. m[n] = '\0';
  4678. }
  4679. static void add_form_run(struct lay *l, unsigned int node,
  4680. const struct br_style *st, unsigned short href)
  4681. {
  4682. struct form_state *fs = form_get(node, 1);
  4683. char shown[FORM_VALUE_MAX + 1];
  4684. char opt[64];
  4685. const char *text = "";
  4686. struct lay_run *r;
  4687. int kind = form_kind_of(node);
  4688. int disabled = form_disabled(node);
  4689. int tw, w = 120, h = 20, i;
  4690. if (!fs)
  4691. return;
  4692. if (l->nruns == 0)
  4693. start_line(l, st);
  4694. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  4695. text = "";
  4696. w = 16;
  4697. h = 16;
  4698. } else if (kind == FORM_SELECT) {
  4699. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  4700. s_copy(opt, "Select", sizeof(opt));
  4701. text = opt;
  4702. w = 120;
  4703. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  4704. kind == FORM_RESET) {
  4705. if (fs->len)
  4706. text = fs->value;
  4707. else
  4708. text = kind == FORM_SUBMIT ? "Submit" :
  4709. kind == FORM_RESET ? "Reset" : "Button";
  4710. } else if (kind == FORM_PASSWORD) {
  4711. for (i = 0; i < fs->len; i++)
  4712. shown[i] = '*';
  4713. shown[fs->len] = '\0';
  4714. text = fs->len ? shown : br_placeholder(&doc, node);
  4715. } else {
  4716. if (fs->len)
  4717. text = fs->value;
  4718. else
  4719. text = br_placeholder(&doc, node);
  4720. if (kind == FORM_TEXTAREA) {
  4721. w = 180;
  4722. h = 40;
  4723. }
  4724. }
  4725. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  4726. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  4727. w = tw + 18;
  4728. if (w < 64)
  4729. w = 64;
  4730. h = 22;
  4731. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD) {
  4732. w = st->width_kind == 1 ? st->width : 120;
  4733. } else if (kind == FORM_SELECT) {
  4734. w = st->width_kind == 1 ? st->width : 120;
  4735. }
  4736. if (w > l->line_right - l->line_left)
  4737. w = l->line_right - l->line_left;
  4738. if (w < 8)
  4739. w = 8;
  4740. if (l->line_x + w > l->line_right &&
  4741. (l->nruns > 0 || l->line_x > l->line_left))
  4742. flush_line(l);
  4743. if (l->nruns >= 96)
  4744. return;
  4745. if (l->nruns == 0) {
  4746. l->line_y = l->y;
  4747. l->line_h = 0;
  4748. start_line(l, st);
  4749. }
  4750. r = &l->runs[l->nruns++];
  4751. r->gap = (unsigned short)(l->line_x - l->run_x);
  4752. r->off = r->len = 0;
  4753. r->color = st->color;
  4754. r->href = href;
  4755. r->dy = 0;
  4756. r->has_lit = 1;
  4757. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  4758. r->lit[i] = text[i];
  4759. r->lit[i] = '\0';
  4760. r->img = -2;
  4761. r->iw = (unsigned short)w;
  4762. r->ih = (unsigned short)h;
  4763. r->w = (unsigned short)w;
  4764. r->font_px = st->font_px;
  4765. r->bold = st->bold;
  4766. r->italic = st->italic;
  4767. r->mono = st->mono;
  4768. r->font_face = st->font_face;
  4769. r->underline = 0;
  4770. r->form = node + 1;
  4771. r->form_kind = (unsigned char)kind;
  4772. r->form_disabled = (unsigned char)disabled;
  4773. if (node < BR_MAX_NODES) {
  4774. layout_boxes[node].x = l->line_x;
  4775. layout_boxes[node].y = l->line_y;
  4776. layout_boxes[node].w = w;
  4777. layout_boxes[node].h = h;
  4778. layout_boxes[node].valid = 1;
  4779. }
  4780. l->line_x += w;
  4781. l->run_x = l->line_x;
  4782. if (l->line_h < h)
  4783. l->line_h = h;
  4784. }
  4785. /* A poster wrapper is absolutely positioned over the media slot; the
  4786. * measured height of its picture is normally added back to the flow. When a
  4787. * loading-skeleton sibling already reserves that slot, adding both doubles
  4788. * the media height and pushes the article text a full screen down. */
  4789. static int has_skeleton_sibling(unsigned int node)
  4790. {
  4791. unsigned int p = doc.nodes[node].parent, c;
  4792. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  4793. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  4794. continue;
  4795. if (doc.nodes[c].class_off &&
  4796. contains_ci(doc.attrs + doc.nodes[c].class_off,
  4797. "skeleton"))
  4798. return 1;
  4799. }
  4800. return 0;
  4801. }
  4802. static void layout_children(struct lay *l, unsigned int parent,
  4803. const struct br_style *pst, int depth,
  4804. unsigned short link);
  4805. static void layout_flex_children(struct lay *l, unsigned int parent,
  4806. const struct br_style *pst, int depth,
  4807. unsigned short link);
  4808. static void layout_grid_children(struct lay *l, unsigned int parent,
  4809. const struct br_style *pst, int depth,
  4810. unsigned short link);
  4811. static void layout_grid_auto(struct lay *l, unsigned int parent,
  4812. const struct br_style *pst, int depth,
  4813. unsigned short link);
  4814. static int flex_item_width(struct lay *l, unsigned int n,
  4815. const struct br_style *cs, int avail);
  4816. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  4817. const struct br_style *pst, int depth,
  4818. unsigned short link);
  4819. static void layout_table_row(struct lay *l, unsigned int row,
  4820. const struct br_style *pst, int depth,
  4821. unsigned short link);
  4822. static int table_has_rowspan(unsigned int table);
  4823. static void layout_table(struct lay *l, unsigned int table,
  4824. const struct br_style *st, int depth,
  4825. unsigned short link);
  4826. /* A flex container whose items are only inline spans is usually just a
  4827. * heading/icon pair. Our flex row positions such items without emitting
  4828. * their inline text in some deep page contexts; normal inline flow renders
  4829. * the same content correctly. */
  4830. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  4831. {
  4832. unsigned int c;
  4833. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  4834. struct br_node *nd = &doc.nodes[c];
  4835. struct br_style cs;
  4836. if (nd->type == BR_NODE_TEXT)
  4837. continue;
  4838. br_style_for(&doc, c, pst, &cs);
  4839. if (cs.display == BR_DISPLAY_NONE)
  4840. continue;
  4841. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  4842. cs.width_kind || cs.has_bg ||
  4843. cs.border_w[0] || cs.border_w[1] ||
  4844. cs.border_w[2] || cs.border_w[3] ||
  4845. nd->tag == BR_TAG_IMG)
  4846. return 1;
  4847. }
  4848. return 0;
  4849. }
  4850. static int css_radius(const struct br_style *st, int corner,
  4851. int w, int h)
  4852. {
  4853. int r = st->radius[corner];
  4854. if (r <= 0)
  4855. return 0;
  4856. if (r > w / 2)
  4857. r = w / 2;
  4858. if (r > h / 2)
  4859. r = h / 2;
  4860. return r;
  4861. }
  4862. static void svg_viewbox(unsigned node, int *vw, int *vh)
  4863. {
  4864. struct br_node *nd = &doc.nodes[node];
  4865. if (nd->width_attr && nd->height_attr) {
  4866. *vw = nd->width_attr;
  4867. *vh = nd->height_attr;
  4868. } else {
  4869. *vw = 300;
  4870. *vh = 150;
  4871. }
  4872. if (*vw < 1)
  4873. *vw = 1;
  4874. if (*vh < 1)
  4875. *vh = 1;
  4876. }
  4877. static int svg_num(const char **pp)
  4878. {
  4879. const char *p = *pp;
  4880. int neg = 0, v = 0, frac = 0, scale = 1;
  4881. while (*p == ' ' || *p == ',' || *p == '\t' ||
  4882. *p == '\n' || *p == '\r')
  4883. p++;
  4884. if (*p == '-') {
  4885. neg = 1;
  4886. p++;
  4887. } else if (*p == '+') {
  4888. p++;
  4889. }
  4890. while (*p >= '0' && *p <= '9') {
  4891. v = v * 10 + (*p - '0');
  4892. p++;
  4893. }
  4894. if (*p == '.') {
  4895. p++;
  4896. while (*p >= '0' && *p <= '9' && scale < 1000) {
  4897. frac = frac * 10 + (*p - '0');
  4898. scale *= 10;
  4899. p++;
  4900. }
  4901. }
  4902. v += frac / scale;
  4903. *pp = p;
  4904. return neg ? -v : v;
  4905. }
  4906. static void svg_path(struct ngui *ui, const char *d,
  4907. int ox, int oy, int dw, int dh, int vw, int vh,
  4908. unsigned short color)
  4909. {
  4910. int cx = 0, cy = 0, sx = 0, sy = 0;
  4911. char cmd = 0;
  4912. const char *p = d;
  4913. while (p && *p) {
  4914. int rel, nx, ny;
  4915. char c;
  4916. while (*p == ' ' || *p == ',' || *p == '\t' ||
  4917. *p == '\n' || *p == '\r')
  4918. p++;
  4919. if (!*p)
  4920. break;
  4921. if ((*p >= 'A' && *p <= 'Z') ||
  4922. (*p >= 'a' && *p <= 'z'))
  4923. cmd = *p++;
  4924. else if (!cmd) {
  4925. p++;
  4926. continue;
  4927. }
  4928. rel = cmd >= 'a' && cmd <= 'z';
  4929. c = rel ? (char)(cmd - 'a' + 'A') : cmd;
  4930. if (c == 'Z') {
  4931. ngui_line(ui, ox + cx * dw / vw, oy + cy * dh / vh,
  4932. ox + sx * dw / vw, oy + sy * dh / vh,
  4933. color);
  4934. cx = sx;
  4935. cy = sy;
  4936. cmd = 0;
  4937. continue;
  4938. }
  4939. if (c == 'H' || c == 'V') {
  4940. const char *save = p;
  4941. int a = svg_num(&p);
  4942. if (p == save) {
  4943. p++;
  4944. continue;
  4945. }
  4946. nx = cx;
  4947. ny = cy;
  4948. if (c == 'H')
  4949. nx = rel ? cx + a : a;
  4950. else
  4951. ny = rel ? cy + a : a;
  4952. } else {
  4953. const char *save = p;
  4954. int a = svg_num(&p);
  4955. int b = svg_num(&p);
  4956. if (p == save) {
  4957. p++;
  4958. continue;
  4959. }
  4960. if (c == 'M') {
  4961. nx = rel ? cx + a : a;
  4962. ny = rel ? cy + b : b;
  4963. cx = sx = nx;
  4964. cy = sy = ny;
  4965. cmd = rel ? 'l' : 'L';
  4966. continue;
  4967. }
  4968. if (c != 'L')
  4969. break;
  4970. nx = rel ? cx + a : a;
  4971. ny = rel ? cy + b : b;
  4972. }
  4973. ngui_line(ui, ox + cx * dw / vw, oy + cy * dh / vh,
  4974. ox + nx * dw / vw, oy + ny * dh / vh, color);
  4975. cx = nx;
  4976. cy = ny;
  4977. }
  4978. }
  4979. static void draw_svg(struct ngui *ui, unsigned node,
  4980. int ox, int oy, int dw, int dh, int vw, int vh,
  4981. const struct br_style *pst)
  4982. {
  4983. unsigned int c;
  4984. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  4985. struct br_node *nd = &doc.nodes[c];
  4986. struct br_style st;
  4987. const char *nm;
  4988. if (nd->type != BR_NODE_ELEM || !nd->name_off)
  4989. continue;
  4990. nm = doc.attrs + nd->name_off;
  4991. br_style_for(&doc, c, pst, &st);
  4992. if (s_eq(nm, "rect")) {
  4993. struct ngui_rect r;
  4994. int rx = (int)nd->svg_rx * dw / vw;
  4995. r.x = ox + (int)nd->svg_x * dw / vw;
  4996. r.y = oy + (int)nd->svg_y * dh / vh;
  4997. r.w = (int)nd->width_attr * dw / vw;
  4998. r.h = (int)nd->height_attr * dh / vh;
  4999. if (r.w < 1)
  5000. r.w = 1;
  5001. if (r.h < 1)
  5002. r.h = 1;
  5003. if (rx > r.w / 2)
  5004. rx = r.w / 2;
  5005. if (rx > r.h / 2)
  5006. rx = r.h / 2;
  5007. if (st.has_bg) {
  5008. if (rx)
  5009. ngui_fill_round_rect(ui, r, rx, rx,
  5010. rx, rx, st.bg);
  5011. else
  5012. ngui_fill_rect(ui, r, st.bg);
  5013. }
  5014. if (st.border_w[0]) {
  5015. if (rx)
  5016. ngui_frame_round(ui, r, rx, rx, rx, rx,
  5017. st.border_w[0],
  5018. st.border_c[0]);
  5019. else
  5020. draw_border_box(ui, r, &st);
  5021. }
  5022. } else if (s_eq(nm, "line")) {
  5023. if (st.border_w[0])
  5024. ngui_line(ui,
  5025. ox + (int)nd->svg_x * dw / vw,
  5026. oy + (int)nd->svg_y * dh / vh,
  5027. ox + (int)nd->width_attr * dw / vw,
  5028. oy + (int)nd->height_attr * dh / vh,
  5029. st.border_c[0]);
  5030. } else if (s_eq(nm, "path")) {
  5031. if (st.border_w[0] && nd->src_off)
  5032. svg_path(ui, doc.attrs + nd->src_off,
  5033. ox, oy, dw, dh, vw, vh,
  5034. st.border_c[0]);
  5035. } else if (s_eq(nm, "text")) {
  5036. unsigned int t = nd->first;
  5037. const char *s;
  5038. unsigned int n, tw;
  5039. int px = st.font_px ? st.font_px : 16;
  5040. int tx, ty, anchor;
  5041. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  5042. continue;
  5043. s = doc.text + doc.nodes[t].text_off;
  5044. n = doc.nodes[t].text_len;
  5045. tw = face_text_width(ui, &st, s, n);
  5046. tx = ox + (int)nd->svg_x * dw / vw;
  5047. ty = oy + (int)nd->svg_y * dh / vh -
  5048. ngui_text_ascent_face(ui, style_face(&st), px,
  5049. st.mono);
  5050. anchor = st.align;
  5051. if (nd->attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  5052. anchor = BR_ALIGN_CENTER;
  5053. else if (nd->attr_flags & BR_ATTR_ANCHOR_END)
  5054. anchor = BR_ALIGN_RIGHT;
  5055. if (anchor == BR_ALIGN_CENTER)
  5056. tx -= (int)tw / 2;
  5057. else if (anchor == BR_ALIGN_RIGHT)
  5058. tx -= (int)tw;
  5059. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  5060. st.color, px, st.bold, st.italic,
  5061. st.mono);
  5062. }
  5063. }
  5064. }
  5065. static void layout_block(struct lay *l, unsigned int node,
  5066. const struct br_style *st, int depth,
  5067. unsigned short link)
  5068. {
  5069. int old_left = l->left, old_right = l->right, old_align = l->align;
  5070. int saved_parent_top = l->parent_top;
  5071. int top, l0, r0;
  5072. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  5073. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  5074. int deco_w, deco_h, content_w, content_h, box_h;
  5075. int definite_w = 0;
  5076. int normal_top = 0;
  5077. int rel_dx = 0, rel_dy = 0;
  5078. int clip_pushed = 0;
  5079. struct ngui_rect clip_rect;
  5080. if (depth > 24 || st->display == BR_DISPLAY_NONE)
  5081. return;
  5082. flow_y = l->y;
  5083. flow_left = l->left;
  5084. flow_right = l->right;
  5085. positioned = st->pos == 1 || st->pos == 2;
  5086. relative = st->pos == 3;
  5087. sticky = st->pos == 4;
  5088. shifted = relative || sticky || st->transform_set;
  5089. if (positioned) {
  5090. int def_w = st->width_kind == 1 ? st->width : -1;
  5091. if (st->pos == 2) {
  5092. int avail_w = page_rect.w - 12;
  5093. if (st->right_set && def_w >= 0)
  5094. l->left = page_rect.x + avail_w - st->right -
  5095. def_w;
  5096. else
  5097. l->left = page_rect.x +
  5098. (st->left_set ? st->left : 0);
  5099. l->right = def_w >= 0 ? l->left + def_w :
  5100. page_rect.x + avail_w;
  5101. if (st->bottom_set && st->height_kind)
  5102. l->y = page_rect.y + page_rect.h -
  5103. st->bottom -
  5104. style_height_px(st, page_rect.w);
  5105. else
  5106. l->y = page_rect.y +
  5107. (st->top_set ? st->top : 0);
  5108. } else {
  5109. int left = flow_left + (st->left_set ? st->left : 0);
  5110. unsigned int parent = doc.nodes[node].parent;
  5111. if (st->right_set && def_w >= 0)
  5112. left = flow_right - st->right - def_w;
  5113. l->left = left;
  5114. l->right = def_w >= 0 ? left + def_w :
  5115. flow_right +
  5116. (st->left_set ? st->left : 0);
  5117. l->y = flow_y + (st->top_set ? st->top : 0);
  5118. if (st->bottom_set && st->height_kind &&
  5119. parent < BR_MAX_NODES && block_h[parent] > 0)
  5120. l->y = flow_y + block_h[parent] - st->bottom -
  5121. style_height_px(st, old_right - old_left);
  5122. }
  5123. old_left = l->left;
  5124. old_right = l->right;
  5125. } else if (relative) {
  5126. rel_dx = st->left_set ? st->left :
  5127. (st->right_set ? -st->right : 0);
  5128. rel_dy = st->top_set ? st->top :
  5129. (st->bottom_set ? -st->bottom : 0);
  5130. }
  5131. if (st->transform_set) {
  5132. rel_dx += st->tx;
  5133. rel_dy += st->ty;
  5134. }
  5135. if (doc.nodes[node].tag == BR_TAG_INPUT ||
  5136. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  5137. doc.nodes[node].tag == BR_TAG_SELECT ||
  5138. doc.nodes[node].tag == BR_TAG_BUTTON) {
  5139. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  5140. s_eq(br_type(&doc, node), "hidden"))
  5141. return;
  5142. add_form_run(l, node, st, link);
  5143. l->y += doc.nodes[node].tag == BR_TAG_TEXTAREA ? 40 :
  5144. doc.nodes[node].tag == BR_TAG_BUTTON ? 22 : 20;
  5145. return;
  5146. }
  5147. flush_line(l);
  5148. cbw = old_right - old_left;
  5149. if (cbw < 8)
  5150. cbw = 8;
  5151. l->y += mp_px(st, 0, cbw);
  5152. top = l->y;
  5153. ml = mp_px(st, 3, cbw);
  5154. mr = mp_px(st, 1, cbw);
  5155. bl = st->border_w[3];
  5156. br = st->border_w[1];
  5157. pl = mp_px(st, 7, cbw);
  5158. pr = mp_px(st, 5, cbw);
  5159. bt = st->border_w[0];
  5160. bb = st->border_w[2];
  5161. pt = mp_px(st, 4, cbw);
  5162. pb = mp_px(st, 6, cbw);
  5163. deco_w = bl + br + pl + pr;
  5164. deco_h = bt + bb + pt + pb;
  5165. if (st->width_kind) {
  5166. int w;
  5167. if (st->width_kind == 3)
  5168. w = cbw * st->width_calc_pct / 100 +
  5169. st->width_calc_px;
  5170. else
  5171. w = css_size(st->width_kind, st->width, cbw);
  5172. if (w < 0)
  5173. w = 0;
  5174. content_w = st->box_sizing ? w - deco_w : w;
  5175. definite_w = 1;
  5176. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  5177. doc.nodes[node].tag == BR_TAG_TD ||
  5178. doc.nodes[node].tag == BR_TAG_TH) &&
  5179. doc.nodes[node].width_attr) {
  5180. /* Legacy table/cell width attributes: percentages resolve
  5181. * against the containing block, bare numbers are pixels. */
  5182. int w = doc.nodes[node].width_pct ?
  5183. cbw * doc.nodes[node].width_attr / 100 :
  5184. doc.nodes[node].width_attr;
  5185. if (w < 0)
  5186. w = 0;
  5187. content_w = st->box_sizing ? w - deco_w : w;
  5188. definite_w = 1;
  5189. } else {
  5190. content_w = cbw - ml - mr - deco_w;
  5191. }
  5192. if (content_w < 0)
  5193. content_w = 0;
  5194. if (st->max_width_kind) {
  5195. int mw = st->max_width_kind == 3 ?
  5196. cbw * st->max_width_calc_pct / 100 +
  5197. st->max_width_calc_px :
  5198. css_size(st->max_width_kind, st->max_width, cbw);
  5199. int max_box = st->box_sizing ? mw : mw + deco_w;
  5200. if (content_w + deco_w > max_box)
  5201. content_w = max_box - deco_w;
  5202. }
  5203. if (st->min_width_kind) {
  5204. int mw = st->min_width_kind == 3 ?
  5205. cbw * st->min_width_calc_pct / 100 +
  5206. st->min_width_calc_px :
  5207. css_size(st->min_width_kind, st->min_width, cbw);
  5208. int min_box = st->box_sizing ? mw : mw + deco_w;
  5209. if (content_w + deco_w < min_box) {
  5210. content_w = min_box - deco_w;
  5211. definite_w = 1;
  5212. }
  5213. }
  5214. if (content_w < 8)
  5215. content_w = 8;
  5216. if (definite_w) {
  5217. int free_w = cbw - ml - mr - deco_w - content_w;
  5218. if (free_w < 0)
  5219. free_w = 0;
  5220. if (st->ml_auto && st->mr_auto) {
  5221. ml = free_w / 2;
  5222. mr = free_w - ml;
  5223. } else if (st->ml_auto) {
  5224. ml = free_w;
  5225. } else if (st->mr_auto) {
  5226. mr = free_w;
  5227. }
  5228. }
  5229. l0 = old_left + ml;
  5230. r0 = l0 + deco_w + content_w;
  5231. if (r0 < l0 + 8)
  5232. r0 = l0 + 8;
  5233. normal_top = top;
  5234. if (sticky) {
  5235. if (st->top_set) {
  5236. int stick = page_rect.y + 4 + st->top;
  5237. if (normal_top < stick)
  5238. rel_dy += stick - normal_top;
  5239. } else if (st->bottom_set && block_h[node]) {
  5240. int stick = page_rect.y + page_rect.h - st->bottom -
  5241. block_h[node];
  5242. if (normal_top > stick)
  5243. rel_dy += stick - normal_top;
  5244. }
  5245. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  5246. block_h[doc.nodes[node].parent]) {
  5247. unsigned int p = doc.nodes[node].parent;
  5248. int ptop = l->parent_top;
  5249. int pbottom = ptop + block_h[p];
  5250. int eh = block_h[node];
  5251. int moved_top = normal_top + rel_dy;
  5252. int moved_bottom = moved_top + eh;
  5253. if (moved_bottom > pbottom)
  5254. rel_dy -= moved_bottom - pbottom;
  5255. moved_top = normal_top + rel_dy;
  5256. if (moved_top < ptop)
  5257. rel_dy += ptop - moved_top;
  5258. }
  5259. }
  5260. if (shifted && l->draw) {
  5261. top += rel_dy;
  5262. l0 += rel_dx;
  5263. r0 += rel_dx;
  5264. }
  5265. l->parent_top = top;
  5266. if (l->draw && block_h[node] &&
  5267. top < page_rect.y + page_rect.h &&
  5268. top + block_h[node] > page_rect.y) {
  5269. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  5270. int rtl = css_radius(st, 0, box.w, box.h);
  5271. int rtr = css_radius(st, 1, box.w, box.h);
  5272. int rbr = css_radius(st, 2, box.w, box.h);
  5273. int rbl = css_radius(st, 3, box.w, box.h);
  5274. if (st->transform_scale) {
  5275. if (st->has_bg)
  5276. fill_transformed_rect(l->ui, box, st->bg, st);
  5277. } else if (rtl || rtr || rbr || rbl) {
  5278. if (st->has_bg) {
  5279. int bw = st->border_w[0];
  5280. if (bw > 0 && st->border_c[0] != st->bg &&
  5281. box.w > bw * 2 && box.h > bw * 2) {
  5282. struct ngui_rect inner = {
  5283. box.x + bw, box.y + bw,
  5284. box.w - bw * 2, box.h - bw * 2
  5285. };
  5286. int itl = rtl > bw ? rtl - bw : 0;
  5287. int itr = rtr > bw ? rtr - bw : 0;
  5288. int ibr = rbr > bw ? rbr - bw : 0;
  5289. int ibl = rbl > bw ? rbl - bw : 0;
  5290. ngui_fill_round_rect(l->ui, box, rtl,
  5291. rtr, rbr, rbl,
  5292. st->border_c[0]);
  5293. ngui_fill_round_rect(l->ui, inner,
  5294. itl, itr, ibr,
  5295. ibl, st->bg);
  5296. } else {
  5297. ngui_fill_round_rect(l->ui, box, rtl,
  5298. rtr, rbr, rbl,
  5299. st->bg);
  5300. }
  5301. } else if (st->border_w[0]) {
  5302. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  5303. rbl, st->border_w[0],
  5304. st->border_c[0]);
  5305. }
  5306. } else {
  5307. if (st->has_bg)
  5308. ngui_fill_rect(l->ui, box, st->bg);
  5309. if (st->bg_image)
  5310. draw_bg_image(l, box, node, st);
  5311. if (st->border_w[0] || st->border_w[1] ||
  5312. st->border_w[2] || st->border_w[3])
  5313. draw_border_box(l->ui, box, st);
  5314. }
  5315. }
  5316. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  5317. l->ui && l->ui->nclip < 4) {
  5318. clip_rect.x = l0 + bl;
  5319. clip_rect.y = top + bt;
  5320. clip_rect.w = (r0 - l0) - bl - br;
  5321. clip_rect.h = (int)block_h[node] - bt - bb;
  5322. if (clip_rect.w > 0 && clip_rect.h > 0) {
  5323. ngui_push_clip(l->ui, clip_rect);
  5324. clip_pushed = 1;
  5325. }
  5326. }
  5327. l->left = l0 + bl + pl;
  5328. l->right = l->left + content_w;
  5329. if (l->right < l->left + 8)
  5330. l->right = l->left + 8;
  5331. l->align = st->align;
  5332. l->line_left = l->left;
  5333. l->line_right = l->right;
  5334. l->y = top + bt + pt;
  5335. if (doc.nodes[node].tag == BR_TAG_HR) {
  5336. if (l->draw)
  5337. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  5338. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  5339. l->y += 8;
  5340. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  5341. int vw = l->right - l->left;
  5342. int vh;
  5343. if (doc.nodes[node].width_pct)
  5344. vw = vw * doc.nodes[node].width_attr / 100;
  5345. else if (doc.nodes[node].width_attr)
  5346. vw = doc.nodes[node].width_attr;
  5347. if (vw > l->right - l->left)
  5348. vw = l->right - l->left;
  5349. if (vw < 8)
  5350. vw = 8;
  5351. vh = vw * 9 / 16;
  5352. if (vh > 240)
  5353. vh = 240;
  5354. if (vh < 80)
  5355. vh = 80;
  5356. if (l->draw) {
  5357. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  5358. vw, vh}, 0xD69A);
  5359. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  5360. vw, vh}, 0x8410);
  5361. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  5362. 0x4208);
  5363. }
  5364. l->y += vh + 4;
  5365. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  5366. int vw, vh, dw = l->right - l->left;
  5367. int dh;
  5368. svg_viewbox(node, &vw, &vh);
  5369. if (dw < 8)
  5370. dw = 8;
  5371. dh = dw * vh / vw;
  5372. if (dh < 8)
  5373. dh = 8;
  5374. if (dh > 1400)
  5375. dh = 1400;
  5376. if (l->draw) {
  5377. struct ngui_rect clip = {l->left, l->y, dw, dh};
  5378. ngui_push_clip(l->ui, clip);
  5379. draw_svg(l->ui, node, l->left, l->y, dw, dh,
  5380. vw, vh, st);
  5381. ngui_pop_clip(l->ui);
  5382. }
  5383. l->y += dh;
  5384. } else {
  5385. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  5386. !st->no_bullet) {
  5387. char *m = li_marker[node];
  5388. if (!m[0]) {
  5389. unsigned int parent = doc.nodes[node].parent;
  5390. int style = st->list_style;
  5391. int idx = parent ? list_index(parent, node) : 1;
  5392. if (style == BR_LIST_AUTO)
  5393. style = (parent &&
  5394. doc.nodes[parent].tag ==
  5395. BR_TAG_OL) ?
  5396. BR_LIST_DECIMAL : BR_LIST_DISC;
  5397. list_marker_text(m, sizeof(li_marker[node]),
  5398. style, idx);
  5399. }
  5400. if (l->draw && m[0]) {
  5401. int mw = (int)ngui_text_width_ui(l->ui, m);
  5402. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  5403. st->color);
  5404. }
  5405. }
  5406. if (doc.nodes[node].tag == BR_TAG_TR)
  5407. layout_table_row(l, node, st, depth + 1, link);
  5408. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  5409. table_has_rowspan(node))
  5410. layout_table(l, node, st, depth + 1, link);
  5411. else if (st->grid_auto)
  5412. layout_grid_auto(l, node, st, depth + 1, link);
  5413. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  5414. st->grid_gap > 0)
  5415. layout_grid_children(l, node, st, depth + 1, link);
  5416. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  5417. flex_wants_row(node, st))
  5418. layout_flex_children(l, node, st, depth + 1, link);
  5419. else
  5420. layout_children(l, node, st, depth + 1, link);
  5421. }
  5422. flush_line(l);
  5423. if (clip_pushed)
  5424. ngui_pop_clip(l->ui);
  5425. if (l->float_active) {
  5426. if (l->y < l->float_bottom)
  5427. l->y = l->float_bottom;
  5428. l->float_active = 0;
  5429. }
  5430. if (st->height_kind &&
  5431. !((doc.nodes[node].tag == BR_TAG_HTML ||
  5432. doc.nodes[node].tag == BR_TAG_BODY) &&
  5433. st->height_kind == 2)) {
  5434. content_h = style_height_px(st, cbw);
  5435. if (st->box_sizing)
  5436. content_h -= deco_h;
  5437. } else {
  5438. /* Percentage heights on html/body resolve against the
  5439. * viewport, but their content still defines the document
  5440. * scroll height. Treating them as auto avoids collapsing
  5441. * the measured page to the containing block width. */
  5442. content_h = l->y - (top + bt + pt);
  5443. }
  5444. if (content_h < 0)
  5445. content_h = 0;
  5446. if (st->max_height_kind) {
  5447. int mh = st->max_height_kind == 3 ?
  5448. cbw * st->max_height_calc_pct / 100 +
  5449. st->max_height_calc_px :
  5450. css_size(st->max_height_kind, st->max_height, cbw);
  5451. int max_box = st->box_sizing ? mh : mh + deco_h;
  5452. if (content_h + deco_h > max_box)
  5453. content_h = max_box - deco_h;
  5454. }
  5455. if (st->min_height_kind &&
  5456. !((doc.nodes[node].tag == BR_TAG_HTML ||
  5457. doc.nodes[node].tag == BR_TAG_BODY) &&
  5458. st->min_height_kind == 2)) {
  5459. int mh = st->min_height_kind == 3 ?
  5460. cbw * st->min_height_calc_pct / 100 +
  5461. st->min_height_calc_px :
  5462. css_size(st->min_height_kind, st->min_height, cbw);
  5463. int min_box = st->box_sizing ? mh : mh + deco_h;
  5464. if (content_h + deco_h < min_box)
  5465. content_h = min_box - deco_h;
  5466. }
  5467. if (content_h < 0)
  5468. content_h = 0;
  5469. box_h = deco_h + content_h;
  5470. if (box_h < 0)
  5471. box_h = 0;
  5472. l->y = (shifted ? normal_top : top) + box_h;
  5473. if (node < BR_MAX_NODES) {
  5474. layout_boxes[node].x = l0;
  5475. layout_boxes[node].y = top;
  5476. layout_boxes[node].w = r0 - l0;
  5477. layout_boxes[node].h = box_h;
  5478. layout_boxes[node].valid = r0 > l0;
  5479. }
  5480. l->left = old_left;
  5481. l->right = old_right;
  5482. l->align = old_align;
  5483. l->y += mp_px(st, 2, cbw);
  5484. if (!l->draw) {
  5485. if (box_h > 65535)
  5486. box_h = 65535;
  5487. block_h[node] = (unsigned short)box_h;
  5488. }
  5489. if (positioned) {
  5490. l->y = flow_y;
  5491. l->left = flow_left;
  5492. l->right = flow_right;
  5493. }
  5494. l->parent_top = saved_parent_top;
  5495. }
  5496. static int text_node_blank(const struct br_node *nd)
  5497. {
  5498. const char *t = doc.text + nd->text_off;
  5499. unsigned int i;
  5500. for (i = 0; i < nd->text_len; i++)
  5501. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  5502. t[i] != '\r')
  5503. return 0;
  5504. return 1;
  5505. }
  5506. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  5507. * text/image widths in the subtree, plus padding and margins. This keeps
  5508. * Bootstrap's floated nav items on one line instead of giving each the whole
  5509. * row. */
  5510. static int text_space(char c)
  5511. {
  5512. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  5513. }
  5514. static int intrinsic_width(struct ngui *ui, unsigned int node,
  5515. const struct br_style *pst, int depth, int base)
  5516. {
  5517. unsigned int c;
  5518. int line_w = 0, max_w = 0;
  5519. if (depth > 12)
  5520. return 0;
  5521. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  5522. struct br_node *nd = &doc.nodes[c];
  5523. struct br_style cs;
  5524. if (nd->type == BR_NODE_TEXT) {
  5525. const char *t = doc.text + nd->text_off;
  5526. unsigned int tn = nd->text_len;
  5527. if (doc.nodes[node].tag == BR_TAG_PRE) {
  5528. line_w += (int)face_text_width(ui, pst, t, tn);
  5529. } else {
  5530. unsigned int ti = 0;
  5531. int first = 1;
  5532. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  5533. int sp = (int)face_text_width(ui, pst, " ", 1);
  5534. while (ti < tn) {
  5535. unsigned int ts;
  5536. while (ti < tn && text_space(t[ti]))
  5537. ti++;
  5538. ts = ti;
  5539. while (ti < tn && !text_space(t[ti]))
  5540. ti++;
  5541. if (ti == ts)
  5542. break;
  5543. if (!first || lead)
  5544. line_w += sp;
  5545. lead = 0;
  5546. line_w += (int)face_text_width(ui, pst,
  5547. t + ts, ti - ts);
  5548. first = 0;
  5549. }
  5550. }
  5551. continue;
  5552. }
  5553. br_style_for(&doc, c, pst, &cs);
  5554. if (cs.display == BR_DISPLAY_NONE)
  5555. continue;
  5556. if (nd->tag == BR_TAG_BR) {
  5557. if (line_w > max_w)
  5558. max_w = line_w;
  5559. line_w = 0;
  5560. continue;
  5561. }
  5562. if (nd->tag == BR_TAG_IMG) {
  5563. /* Measure the image as layout will draw it: a CSS or
  5564. * attribute height keeps the intrinsic aspect ratio, and
  5565. * a CSS width overrides the native pixel width. Bootstrap
  5566. * sizes the Cloudron logo with height:40px only. */
  5567. int idx = nd->img_index;
  5568. int iw = 0, ih = 0;
  5569. if (idx >= 0 && idx < image_count &&
  5570. images[idx].state == 1) {
  5571. iw = (int)images[idx].native_w;
  5572. ih = (int)images[idx].native_h;
  5573. if (iw <= 0 || ih <= 0) {
  5574. iw = (int)images[idx].img.w;
  5575. ih = (int)images[idx].img.h;
  5576. }
  5577. }
  5578. if (cs.width_kind) {
  5579. int ww = style_width_px(&cs, base);
  5580. line_w += ww > 0 ? ww : 64;
  5581. } else if (nd->width_attr) {
  5582. line_w += nd->width_attr;
  5583. } else if (nd->height_attr && iw && ih) {
  5584. line_w += iw * (int)nd->height_attr / ih;
  5585. } else if (cs.height_kind && iw && ih) {
  5586. int hh = style_height_px(&cs, base);
  5587. line_w += hh > 0 ? iw * hh / ih : iw;
  5588. } else if (iw) {
  5589. line_w += iw;
  5590. } else {
  5591. line_w += 64;
  5592. }
  5593. continue;
  5594. }
  5595. {
  5596. int cw = mp_px(&cs, 7, base) +
  5597. mp_px(&cs, 5, base) +
  5598. mp_px(&cs, 3, base) +
  5599. mp_px(&cs, 1, base) +
  5600. cs.border_w[1] + cs.border_w[3] +
  5601. intrinsic_width(ui, c, &cs, depth + 1, base);
  5602. if (cs.float_left || cs.display == BR_DISPLAY_INLINE ||
  5603. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  5604. line_w += cw;
  5605. } else {
  5606. if (line_w > max_w)
  5607. max_w = line_w;
  5608. line_w = 0;
  5609. if (cw > max_w)
  5610. max_w = cw;
  5611. }
  5612. }
  5613. if (line_w > 4096 || max_w > 4096)
  5614. break;
  5615. }
  5616. return line_w > max_w ? line_w : max_w;
  5617. }
  5618. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  5619. * the main user: .row > .col-md-* with float:left and a percentage width.
  5620. * Each column is laid out with its own left/right edge and the row advances
  5621. * to the tallest column. Returns the first child not consumed. */
  5622. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  5623. const struct br_style *pst, int depth,
  5624. unsigned short link)
  5625. {
  5626. unsigned int n = first;
  5627. int row_left = l->left, row_right = l->right;
  5628. int row_top, row_bottom, xl, xr, any = 0;
  5629. int fl_left = row_left, fl_right = row_right, fl_bottom;
  5630. flush_line(l);
  5631. row_top = l->y;
  5632. row_bottom = l->y;
  5633. fl_bottom = row_top;
  5634. xl = row_left;
  5635. xr = row_right;
  5636. while (n) {
  5637. struct br_node *nd = &doc.nodes[n];
  5638. struct br_style cs;
  5639. unsigned short lk = link;
  5640. int colw, right;
  5641. if (nd->type == BR_NODE_TEXT) {
  5642. if (text_node_blank(nd)) {
  5643. n = nd->next;
  5644. continue;
  5645. }
  5646. break;
  5647. }
  5648. br_style_for(&doc, n, pst, &cs);
  5649. if (cs.display == BR_DISPLAY_NONE) {
  5650. n = nd->next;
  5651. continue;
  5652. }
  5653. /* A float blockifies its box: Bootstrap floats inline
  5654. * anchors too (the navbar brand and its text links), and
  5655. * their padding must be honoured. */
  5656. if (!cs.float_left)
  5657. break;
  5658. if (nd->tag == BR_TAG_A && nd->href_off)
  5659. lk = (unsigned short)n;
  5660. right = cs.float_left == 2;
  5661. if (cs.width_kind == 2 || cs.width_kind == 3) {
  5662. colw = style_width_px(&cs, row_right - row_left);
  5663. } else if (cs.width_kind == 1) {
  5664. colw = (int)cs.width;
  5665. } else {
  5666. int base = row_right - row_left;
  5667. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  5668. mp_px(&cs, 7, base) +
  5669. mp_px(&cs, 5, base) +
  5670. mp_px(&cs, 3, base) +
  5671. mp_px(&cs, 1, base);
  5672. if (colw < 8)
  5673. colw = 8;
  5674. }
  5675. if (colw < 8)
  5676. colw = 8;
  5677. if (colw > row_right - row_left)
  5678. colw = row_right - row_left;
  5679. /* The float column width is already resolved. */
  5680. cs.width_kind = 0;
  5681. cs.max_width_kind = 0;
  5682. if (right) {
  5683. if (any && xr - colw < xl) {
  5684. row_top = row_bottom;
  5685. row_bottom = row_top;
  5686. xl = row_left;
  5687. xr = row_right;
  5688. }
  5689. if (xr - colw < xl)
  5690. colw = xr - xl;
  5691. if (colw < 8)
  5692. colw = 8;
  5693. l->left = xr - colw;
  5694. if (l->left < row_left)
  5695. l->left = row_left;
  5696. l->right = xr;
  5697. xr = l->left;
  5698. if (xr < fl_right)
  5699. fl_right = xr;
  5700. } else {
  5701. if (any && xl + colw > xr) {
  5702. row_top = row_bottom;
  5703. row_bottom = row_top;
  5704. xl = row_left;
  5705. xr = row_right;
  5706. }
  5707. l->left = xl;
  5708. l->right = xl + colw;
  5709. xl += colw;
  5710. if (xl > fl_left)
  5711. fl_left = xl;
  5712. }
  5713. if (l->right < l->left + 8)
  5714. l->right = l->left + 8;
  5715. l->y = row_top;
  5716. l->line_x = l->left;
  5717. l->run_x = l->left;
  5718. l->line_y = l->y;
  5719. l->line_h = 0;
  5720. l->nruns = 0;
  5721. l->space_pending = 0;
  5722. l->align = cs.align;
  5723. layout_block(l, n, &cs, depth + 1, lk);
  5724. if (l->y > row_bottom)
  5725. row_bottom = l->y;
  5726. if (l->y > fl_bottom)
  5727. fl_bottom = l->y;
  5728. any = 1;
  5729. n = nd->next;
  5730. }
  5731. l->left = row_left;
  5732. l->right = row_right;
  5733. if (n && any) {
  5734. struct br_node *nd = &doc.nodes[n];
  5735. int inline_next = 0;
  5736. if (nd->type == BR_NODE_TEXT) {
  5737. inline_next = 1;
  5738. } else if (nd->type == BR_NODE_ELEM) {
  5739. struct br_style cs;
  5740. br_style_for(&doc, n, pst, &cs);
  5741. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  5742. cs.display != BR_DISPLAY_NONE &&
  5743. !br_tag_is_block(nd->tag);
  5744. }
  5745. if (inline_next) {
  5746. if (l->float_active) {
  5747. if (l->float_left > fl_left)
  5748. fl_left = l->float_left;
  5749. if (l->float_right < fl_right)
  5750. fl_right = l->float_right;
  5751. if (l->float_bottom > fl_bottom)
  5752. fl_bottom = l->float_bottom;
  5753. }
  5754. l->float_active = 1;
  5755. l->float_left = fl_left;
  5756. l->float_right = fl_right;
  5757. l->float_bottom = fl_bottom;
  5758. l->y = row_top;
  5759. } else {
  5760. l->float_active = 0;
  5761. l->y = row_bottom;
  5762. }
  5763. } else {
  5764. l->float_active = 0;
  5765. l->y = row_bottom;
  5766. }
  5767. l->line_x = l->left;
  5768. l->run_x = l->left;
  5769. l->line_left = l->left;
  5770. l->line_right = l->right;
  5771. l->line_y = l->y;
  5772. l->line_h = 0;
  5773. l->nruns = 0;
  5774. l->space_pending = 0;
  5775. return n;
  5776. }
  5777. static int flex_item_width(struct lay *l, unsigned int n,
  5778. const struct br_style *cs, int avail)
  5779. {
  5780. struct br_node *nd = &doc.nodes[n];
  5781. (void)l;
  5782. int w;
  5783. if (cs->width_kind == 2 || cs->width_kind == 3)
  5784. w = style_width_px(cs, avail);
  5785. else if (cs->width_kind == 1)
  5786. w = (int)cs->width;
  5787. else if (nd->tag == BR_TAG_IMG) {
  5788. int idx = nd->img_index;
  5789. if (idx >= 0 && idx < image_count &&
  5790. images[idx].state == 1)
  5791. w = (int)images[idx].img.w;
  5792. else if (nd->width_attr)
  5793. w = (int)nd->width_attr;
  5794. else
  5795. w = 64;
  5796. } else {
  5797. w = intrinsic_width(l->ui, n, cs, 0, avail);
  5798. w += mp_px(cs, 7, avail);
  5799. w += mp_px(cs, 5, avail);
  5800. w += mp_px(cs, 3, avail);
  5801. w += mp_px(cs, 1, avail);
  5802. }
  5803. if (w < 24)
  5804. w = 24;
  5805. if (w > avail)
  5806. w = avail;
  5807. return w;
  5808. }
  5809. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  5810. * on one line, not one full-width block each. Place intrinsic widths from
  5811. * left to right and wrap when the row is full. */
  5812. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  5813. const struct br_style *pst, int depth,
  5814. unsigned short link)
  5815. {
  5816. unsigned int n = first;
  5817. int row_left = l->left, row_right = l->right;
  5818. int avail = row_right - row_left;
  5819. int x = row_left, y = l->y, row_h = 0, any = 0;
  5820. flush_line(l);
  5821. y = l->y;
  5822. while (n) {
  5823. struct br_node *nd = &doc.nodes[n];
  5824. struct br_style cs;
  5825. unsigned short lk = link;
  5826. int colw, h;
  5827. if (nd->type == BR_NODE_TEXT) {
  5828. if (!text_node_blank(nd))
  5829. break;
  5830. if (any)
  5831. x += 4;
  5832. n = nd->next;
  5833. continue;
  5834. }
  5835. br_style_for(&doc, n, pst, &cs);
  5836. if (cs.display == BR_DISPLAY_NONE) {
  5837. n = nd->next;
  5838. continue;
  5839. }
  5840. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  5841. break;
  5842. if (nd->tag == BR_TAG_A && nd->href_off)
  5843. lk = (unsigned short)n;
  5844. colw = flex_item_width(l, n, &cs, avail);
  5845. /* A few pixels of slack keep a single long token (boot.S)
  5846. * from wrapping at the exact content width. */
  5847. colw += 8;
  5848. if (colw > avail)
  5849. colw = avail;
  5850. cs.width_kind = 0;
  5851. cs.max_width_kind = 0;
  5852. if (any && x + colw > row_right) {
  5853. y += row_h + 2;
  5854. x = row_left;
  5855. row_h = 0;
  5856. any = 0;
  5857. }
  5858. if (any && x > row_left)
  5859. x += 4;
  5860. l->left = x;
  5861. l->right = x + colw;
  5862. if (l->right < l->left + 8)
  5863. l->right = l->left + 8;
  5864. l->y = y;
  5865. l->line_x = l->left;
  5866. l->run_x = l->left;
  5867. l->line_y = l->y;
  5868. l->line_h = 0;
  5869. l->nruns = 0;
  5870. l->space_pending = 0;
  5871. l->align = cs.align;
  5872. layout_block(l, n, &cs, depth + 1, lk);
  5873. h = l->y - y;
  5874. if (h > row_h)
  5875. row_h = h;
  5876. x += colw;
  5877. any = 1;
  5878. n = nd->next;
  5879. }
  5880. if (any)
  5881. y += row_h;
  5882. l->left = row_left;
  5883. l->right = row_right;
  5884. l->y = y;
  5885. l->line_x = l->left;
  5886. l->run_x = l->left;
  5887. l->line_y = l->y;
  5888. l->line_h = 0;
  5889. l->nruns = 0;
  5890. l->space_pending = 0;
  5891. return n;
  5892. }
  5893. struct flex_item {
  5894. unsigned int node;
  5895. unsigned short link;
  5896. int w;
  5897. };
  5898. static void layout_flex_children(struct lay *l, unsigned int parent,
  5899. const struct br_style *pst, int depth,
  5900. unsigned short link)
  5901. {
  5902. struct flex_item it[32];
  5903. unsigned int c;
  5904. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  5905. int row_left = l->left, row_right = l->right;
  5906. int avail = row_right - row_left;
  5907. int idx, row_top;
  5908. if (avail < 160 || depth > 24) {
  5909. layout_children(l, parent, pst, depth, link);
  5910. return;
  5911. }
  5912. /* If direct text is not just whitespace, normal block flow handles it
  5913. * better than pretending it is a flex item. */
  5914. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  5915. struct br_node *nd = &doc.nodes[c];
  5916. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  5917. layout_children(l, parent, pst, depth, link);
  5918. return;
  5919. }
  5920. }
  5921. for (c = doc.nodes[parent].first;
  5922. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  5923. c = doc.nodes[c].next) {
  5924. struct br_node *nd = &doc.nodes[c];
  5925. struct br_style cs;
  5926. if (nd->type == BR_NODE_TEXT)
  5927. continue;
  5928. br_style_for(&doc, c, pst, &cs);
  5929. if (cs.display == BR_DISPLAY_NONE)
  5930. continue;
  5931. it[nitem].node = c;
  5932. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  5933. (unsigned short)c : link;
  5934. it[nitem].w = 0;
  5935. if (cs.flex_grow && !cs.width_kind)
  5936. grow_count++;
  5937. else
  5938. fixed += flex_item_width(l, c, &cs, avail);
  5939. nitem++;
  5940. }
  5941. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  5942. if (grow_w < 96)
  5943. grow_w = 96;
  5944. for (idx = 0; idx < nitem; idx++) {
  5945. struct br_style cs;
  5946. br_style_for(&doc, it[idx].node, pst, &cs);
  5947. if (cs.flex_grow && !cs.width_kind)
  5948. it[idx].w = grow_w;
  5949. else
  5950. it[idx].w = flex_item_width(l, it[idx].node, &cs, avail);
  5951. if (it[idx].w > avail)
  5952. it[idx].w = avail;
  5953. if (it[idx].w < 8)
  5954. it[idx].w = 8;
  5955. }
  5956. row_top = l->y;
  5957. idx = 0;
  5958. while (idx < nitem) {
  5959. int start = idx, count = 0, row_w = 0;
  5960. int free_w, x, extra = 0, row_h = 0, k;
  5961. while (idx < nitem) {
  5962. int add = it[idx].w + (count ? gap : 0);
  5963. if (count && pst->flex_wrap != 2 &&
  5964. row_w + add > avail)
  5965. break;
  5966. row_w += add;
  5967. count++;
  5968. idx++;
  5969. }
  5970. if (!count) {
  5971. count = 1;
  5972. row_w = it[start].w;
  5973. idx = start + 1;
  5974. }
  5975. free_w = avail - row_w;
  5976. if (free_w < 0)
  5977. free_w = 0;
  5978. x = row_left;
  5979. if (pst->justify == 1) {
  5980. x += free_w / 2;
  5981. } else if (pst->justify == 2) {
  5982. x += free_w;
  5983. } else if (pst->justify == 3) {
  5984. extra = count > 1 ? free_w / (count - 1) : 0;
  5985. } else if (pst->justify == 4) {
  5986. extra = count ? free_w / count : 0;
  5987. x += extra / 2;
  5988. } else if (pst->justify == 5) {
  5989. extra = count ? free_w / (count + 1) : 0;
  5990. x += extra;
  5991. }
  5992. for (k = 0; k < count; k++) {
  5993. int node = (int)it[start + k].node;
  5994. int h = block_h[node];
  5995. if (h > row_h)
  5996. row_h = h;
  5997. }
  5998. if (pst->height_kind) {
  5999. int hh = style_height_px(pst, avail);
  6000. if (hh > row_h)
  6001. row_h = hh;
  6002. }
  6003. for (k = 0; k < count; k++) {
  6004. struct br_style cs;
  6005. int node = (int)it[start + k].node;
  6006. int yoff = 0;
  6007. br_style_for(&doc, node, pst, &cs);
  6008. cs.width_kind = 0;
  6009. cs.max_width_kind = 0;
  6010. if (l->draw && pst->align_items &&
  6011. row_h > block_h[node]) {
  6012. if (pst->align_items == 1)
  6013. yoff = (row_h - block_h[node]) / 2;
  6014. else if (pst->align_items == 2)
  6015. yoff = row_h - block_h[node];
  6016. }
  6017. l->left = x;
  6018. l->right = x + it[start + k].w;
  6019. if (l->right < l->left + 8)
  6020. l->right = l->left + 8;
  6021. l->y = row_top + yoff;
  6022. l->line_x = l->left;
  6023. l->run_x = l->left;
  6024. l->line_y = l->y;
  6025. l->line_h = 0;
  6026. l->nruns = 0;
  6027. l->space_pending = 0;
  6028. l->align = cs.align;
  6029. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  6030. if (!l->draw) {
  6031. int h = l->y - row_top;
  6032. if (h > row_h)
  6033. row_h = h;
  6034. }
  6035. x += it[start + k].w;
  6036. if (k + 1 < count)
  6037. x += gap + extra;
  6038. }
  6039. row_top += row_h;
  6040. }
  6041. l->left = row_left;
  6042. l->right = row_right;
  6043. l->y = row_top;
  6044. l->line_x = l->left;
  6045. l->run_x = l->left;
  6046. l->line_y = l->y;
  6047. l->line_h = 0;
  6048. l->nruns = 0;
  6049. l->space_pending = 0;
  6050. }
  6051. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  6052. * plus the grid-area hints used by site shells (site notice/footer full
  6053. * width, column-start left, page-content right). Anything more elaborate
  6054. * falls back to normal block flow. */
  6055. static int grid_track_width(unsigned char kind, unsigned short val,
  6056. int avail, int other)
  6057. {
  6058. if (kind == 2)
  6059. return avail * (int)val / 100;
  6060. if (kind == 1)
  6061. return val;
  6062. return other;
  6063. }
  6064. static void layout_grid_children(struct lay *l, unsigned int parent,
  6065. const struct br_style *pst, int depth,
  6066. unsigned short link)
  6067. {
  6068. unsigned int n;
  6069. int row_left = l->left, row_right = l->right;
  6070. int avail = row_right - row_left;
  6071. int gap = pst->grid_gap;
  6072. int track_total = avail - gap;
  6073. int col0, col1, x0, x1;
  6074. int row_y, row_bottom, have_left = 0, have_right = 0;
  6075. unsigned int c;
  6076. if (avail < 32 || depth > 24)
  6077. return;
  6078. if (track_total < 16)
  6079. track_total = 16;
  6080. col0 = grid_track_width((unsigned char)(pst->width_kind),
  6081. pst->width, track_total, 0);
  6082. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  6083. pst->max_width, track_total, 0);
  6084. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  6085. int w0 = pst->width ? pst->width : 1;
  6086. int w1 = pst->max_width ? pst->max_width : 1;
  6087. col0 = track_total * w0 / (w0 + w1);
  6088. col1 = track_total - col0;
  6089. } else if (pst->width_kind == 3) {
  6090. col0 = track_total - col1;
  6091. if (col0 < 24)
  6092. col0 = 24;
  6093. } else if (pst->max_width_kind == 3) {
  6094. col1 = track_total - col0;
  6095. if (col1 < 24)
  6096. col1 = 24;
  6097. }
  6098. if (col0 < 24)
  6099. col0 = 24;
  6100. if (col1 < 24)
  6101. col1 = 24;
  6102. if (col0 + col1 > track_total) {
  6103. col1 = track_total - col0;
  6104. if (col1 < 24)
  6105. col1 = 24;
  6106. }
  6107. x0 = row_left;
  6108. x1 = row_left + col0 + gap;
  6109. /* Direct text makes a grid ambiguous; use block flow instead. */
  6110. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  6111. struct br_node *nd = &doc.nodes[c];
  6112. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  6113. layout_children(l, parent, pst, depth, link);
  6114. return;
  6115. }
  6116. }
  6117. row_y = row_bottom = l->y;
  6118. n = doc.nodes[parent].first;
  6119. while (n) {
  6120. struct br_node *nd = &doc.nodes[n];
  6121. struct br_style cs;
  6122. unsigned short lk = link;
  6123. int slot, x, w;
  6124. if (nd->type == BR_NODE_TEXT) {
  6125. n = nd->next;
  6126. continue;
  6127. }
  6128. br_style_for(&doc, n, pst, &cs);
  6129. if (cs.display == BR_DISPLAY_NONE) {
  6130. n = nd->next;
  6131. continue;
  6132. }
  6133. if (nd->tag == BR_TAG_A && nd->href_off)
  6134. lk = (unsigned short)n;
  6135. slot = cs.grid_slot;
  6136. if (!slot) {
  6137. if (!have_left)
  6138. slot = 2;
  6139. else if (!have_right)
  6140. slot = 3;
  6141. else
  6142. slot = 2;
  6143. }
  6144. if (slot == 1) {
  6145. if (have_left || have_right) {
  6146. row_y = row_bottom;
  6147. have_left = have_right = 0;
  6148. }
  6149. x = row_left;
  6150. w = avail;
  6151. } else if (slot == 2) {
  6152. if (have_left) {
  6153. row_y = row_bottom;
  6154. have_left = have_right = 0;
  6155. }
  6156. x = x0;
  6157. w = col0;
  6158. have_left = 1;
  6159. } else {
  6160. if (have_right) {
  6161. row_y = row_bottom;
  6162. have_left = have_right = 0;
  6163. }
  6164. x = x1;
  6165. w = col1;
  6166. have_right = 1;
  6167. }
  6168. cs.width_kind = 0;
  6169. cs.max_width_kind = 0;
  6170. l->left = x;
  6171. l->right = x + w;
  6172. if (l->right < l->left + 8)
  6173. l->right = l->left + 8;
  6174. l->y = row_y;
  6175. l->line_x = l->left;
  6176. l->run_x = l->left;
  6177. l->line_y = l->y;
  6178. l->line_h = 0;
  6179. l->nruns = 0;
  6180. l->space_pending = 0;
  6181. l->align = cs.align;
  6182. layout_block(l, n, &cs, depth + 1, lk);
  6183. if (l->y > row_bottom)
  6184. row_bottom = l->y;
  6185. n = nd->next;
  6186. }
  6187. l->left = row_left;
  6188. l->right = row_right;
  6189. l->y = row_bottom;
  6190. l->line_x = l->left;
  6191. l->run_x = l->left;
  6192. l->line_y = l->y;
  6193. l->line_h = 0;
  6194. l->nruns = 0;
  6195. l->space_pending = 0;
  6196. }
  6197. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  6198. * capped at four. Used by the project docs' card grids. */
  6199. static void layout_grid_auto(struct lay *l, unsigned int parent,
  6200. const struct br_style *pst, int depth,
  6201. unsigned short link)
  6202. {
  6203. unsigned int n, c;
  6204. int row_left = l->left, row_right = l->right;
  6205. int avail = row_right - row_left;
  6206. int gap = pst->grid_gap;
  6207. int minw = pst->width_kind == 1 ? pst->width : 200;
  6208. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  6209. if (avail < 32 || depth > 24) {
  6210. layout_children(l, parent, pst, depth, link);
  6211. return;
  6212. }
  6213. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  6214. struct br_node *nd = &doc.nodes[c];
  6215. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  6216. layout_children(l, parent, pst, depth, link);
  6217. return;
  6218. }
  6219. }
  6220. if (minw < 80)
  6221. minw = 80;
  6222. ncols = (avail + gap) / (minw + gap);
  6223. if (ncols < 1)
  6224. ncols = 1;
  6225. if (ncols > 4)
  6226. ncols = 4;
  6227. colw = (avail - gap * (ncols - 1)) / ncols;
  6228. if (colw < 24)
  6229. colw = 24;
  6230. x = row_left;
  6231. n = doc.nodes[parent].first;
  6232. while (n) {
  6233. struct br_node *nd = &doc.nodes[n];
  6234. struct br_style cs;
  6235. unsigned short lk = link;
  6236. int h;
  6237. if (nd->type == BR_NODE_TEXT) {
  6238. n = nd->next;
  6239. continue;
  6240. }
  6241. br_style_for(&doc, n, pst, &cs);
  6242. if (cs.display == BR_DISPLAY_NONE) {
  6243. n = nd->next;
  6244. continue;
  6245. }
  6246. if (nd->tag == BR_TAG_A && nd->href_off)
  6247. lk = (unsigned short)n;
  6248. cs.width_kind = 0;
  6249. cs.max_width_kind = 0;
  6250. l->left = x;
  6251. l->right = x + colw;
  6252. if (l->right < l->left + 8)
  6253. l->right = l->left + 8;
  6254. l->y = y;
  6255. l->line_x = l->left;
  6256. l->run_x = l->left;
  6257. l->line_y = l->y;
  6258. l->line_h = 0;
  6259. l->nruns = 0;
  6260. l->space_pending = 0;
  6261. l->align = cs.align;
  6262. layout_block(l, n, &cs, depth + 1, lk);
  6263. h = l->y - y;
  6264. if (h > row_h)
  6265. row_h = h;
  6266. col++;
  6267. n = nd->next;
  6268. if (col == ncols) {
  6269. y += row_h + gap;
  6270. x = row_left;
  6271. row_h = 0;
  6272. col = 0;
  6273. } else {
  6274. x += colw + gap;
  6275. }
  6276. }
  6277. if (col)
  6278. y += row_h;
  6279. else if (y > start_y)
  6280. y -= gap;
  6281. l->left = row_left;
  6282. l->right = row_right;
  6283. l->y = y;
  6284. l->line_x = l->left;
  6285. l->run_x = l->left;
  6286. l->line_y = l->y;
  6287. l->line_h = 0;
  6288. l->nruns = 0;
  6289. l->space_pending = 0;
  6290. }
  6291. /* Column widths are the widest cell in each column across every row, so all
  6292. * rows line up. The table model is still deliberately basic: no colspan,
  6293. * border-collapse or percentage columns. */
  6294. static void table_columns(struct lay *l, unsigned int table,
  6295. const struct br_style *pst, int avail,
  6296. int *raw, int maxcols, int *out_cols,
  6297. int *out_total)
  6298. {
  6299. unsigned int r, c;
  6300. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  6301. int fixed[12];
  6302. for (c = 0; c < (unsigned int)maxcols; c++) {
  6303. raw[c] = 0;
  6304. fixed[c] = 0;
  6305. }
  6306. /* Intrinsic widths of single-column cells. */
  6307. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  6308. struct br_node *rn = &doc.nodes[r];
  6309. int col = 0;
  6310. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  6311. continue;
  6312. for (c = rn->first; c; c = doc.nodes[c].next) {
  6313. struct br_node *cn = &doc.nodes[c];
  6314. struct br_style cs;
  6315. int w, span;
  6316. if (cn->type != BR_NODE_ELEM ||
  6317. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  6318. continue;
  6319. span = cn->colspan ? cn->colspan : 1;
  6320. br_style_for(&doc, c, pst, &cs);
  6321. if (cs.display == BR_DISPLAY_NONE)
  6322. continue;
  6323. if (col + span > maxcols)
  6324. span = maxcols - col;
  6325. if (span < 1)
  6326. break;
  6327. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  6328. mp_px(&cs, 7, avail) +
  6329. mp_px(&cs, 5, avail) +
  6330. mp_px(&cs, 3, avail) +
  6331. mp_px(&cs, 1, avail) +
  6332. cs.border_w[0] + cs.border_w[1] +
  6333. cs.border_w[2] + cs.border_w[3];
  6334. if (w < 24)
  6335. w = 24;
  6336. if (span == 1) {
  6337. if (w > raw[col])
  6338. raw[col] = w;
  6339. }
  6340. if (col + span > cols)
  6341. cols = col + span;
  6342. col += span;
  6343. }
  6344. }
  6345. /* A colspan cell only has to be as wide as the sum of its columns. */
  6346. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  6347. struct br_node *rn = &doc.nodes[r];
  6348. int col = 0;
  6349. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  6350. continue;
  6351. for (c = rn->first; c; c = doc.nodes[c].next) {
  6352. struct br_node *cn = &doc.nodes[c];
  6353. struct br_style cs;
  6354. int span, w, sum, i;
  6355. if (cn->type != BR_NODE_ELEM ||
  6356. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  6357. continue;
  6358. span = cn->colspan ? cn->colspan : 1;
  6359. if (col + span > maxcols)
  6360. span = maxcols - col;
  6361. if (span < 1)
  6362. break;
  6363. if (span > 1) {
  6364. br_style_for(&doc, c, pst, &cs);
  6365. if (cs.display != BR_DISPLAY_NONE) {
  6366. w = intrinsic_width(l->ui, c, &cs,
  6367. 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. sum = 0;
  6375. for (i = 0; i < span; i++)
  6376. sum += raw[col + i];
  6377. if (w > sum)
  6378. raw[col + span - 1] += w - sum;
  6379. }
  6380. }
  6381. col += span;
  6382. }
  6383. }
  6384. /* Explicit and percentage widths override intrinsic widths. */
  6385. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  6386. struct br_node *rn = &doc.nodes[r];
  6387. int col = 0;
  6388. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  6389. continue;
  6390. for (c = rn->first; c; c = doc.nodes[c].next) {
  6391. struct br_node *cn = &doc.nodes[c];
  6392. struct br_style cs;
  6393. int span;
  6394. if (cn->type != BR_NODE_ELEM ||
  6395. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  6396. continue;
  6397. span = cn->colspan ? cn->colspan : 1;
  6398. if (col + span > maxcols)
  6399. span = maxcols - col;
  6400. if (span < 1)
  6401. break;
  6402. if (span == 1) {
  6403. br_style_for(&doc, c, pst, &cs);
  6404. if (cs.display != BR_DISPLAY_NONE) {
  6405. if (cs.width_kind == 1) {
  6406. raw[col] = cs.width;
  6407. fixed[col] = 1;
  6408. } else if (cs.width_kind == 2 ||
  6409. cs.width_kind == 3) {
  6410. raw[col] = style_width_px(&cs,
  6411. avail);
  6412. fixed[col] = 1;
  6413. }
  6414. }
  6415. }
  6416. col += span;
  6417. }
  6418. }
  6419. for (c = 0; c < (unsigned int)cols; c++) {
  6420. if (raw[c] < 8)
  6421. raw[c] = 8;
  6422. total += raw[c];
  6423. if (fixed[c])
  6424. fixed_sum += raw[c];
  6425. else {
  6426. free_raw += raw[c];
  6427. free_cols++;
  6428. }
  6429. }
  6430. if (fixed_sum > 0 && fixed_sum < avail) {
  6431. int free_avail = avail - fixed_sum;
  6432. int i;
  6433. if (free_raw > 0) {
  6434. for (i = 0; i < cols; i++)
  6435. if (!fixed[i])
  6436. raw[i] = free_avail * raw[i] /
  6437. free_raw;
  6438. } else if (free_cols > 0) {
  6439. for (i = 0; i < cols; i++)
  6440. if (!fixed[i])
  6441. raw[i] = free_avail / free_cols;
  6442. }
  6443. total = 0;
  6444. for (i = 0; i < cols; i++)
  6445. total += raw[i];
  6446. } else if (total < avail && total > 0) {
  6447. int i;
  6448. for (i = 0; i < cols; i++)
  6449. raw[i] = raw[i] * avail / total;
  6450. total = 0;
  6451. for (i = 0; i < cols; i++)
  6452. total += raw[i];
  6453. }
  6454. *out_cols = cols;
  6455. *out_total = total;
  6456. }
  6457. static void layout_table_row(struct lay *l, unsigned int row,
  6458. const struct br_style *pst, int depth,
  6459. unsigned short link)
  6460. {
  6461. unsigned int n, cell[12];
  6462. int raw[12], colstart[12], colspan[12];
  6463. int prefix[13];
  6464. int ncell = 0, total = 0, cols = 0, col = 0;
  6465. int row_left = l->left, row_right = l->right;
  6466. int avail = row_right - row_left;
  6467. int y = l->y, bottom = l->y;
  6468. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  6469. struct br_node *nd = &doc.nodes[n];
  6470. struct br_style cs;
  6471. int span;
  6472. if (nd->type == BR_NODE_TEXT) {
  6473. if (text_node_blank(nd))
  6474. continue;
  6475. layout_children(l, row, pst, depth, link);
  6476. return;
  6477. }
  6478. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  6479. layout_children(l, row, pst, depth, link);
  6480. return;
  6481. }
  6482. br_style_for(&doc, n, pst, &cs);
  6483. if (cs.display == BR_DISPLAY_NONE)
  6484. continue;
  6485. if (ncell >= 12) {
  6486. layout_children(l, row, pst, depth, link);
  6487. return;
  6488. }
  6489. span = nd->colspan ? nd->colspan : 1;
  6490. if (span > 12 - col)
  6491. span = 12 - col;
  6492. if (span < 1)
  6493. continue;
  6494. cell[ncell] = n;
  6495. colstart[ncell] = col;
  6496. colspan[ncell] = span;
  6497. col += span;
  6498. ncell++;
  6499. }
  6500. if (ncell < 1 || avail < 32) {
  6501. layout_children(l, row, pst, depth, link);
  6502. return;
  6503. }
  6504. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  6505. &total);
  6506. if (cols < 2 || total <= 0) {
  6507. int c;
  6508. total = 0;
  6509. for (c = 0; c < ncell; c++) {
  6510. struct br_style cs;
  6511. br_style_for(&doc, cell[c], pst, &cs);
  6512. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  6513. avail) +
  6514. mp_px(&cs, 7, avail) +
  6515. mp_px(&cs, 5, avail) +
  6516. mp_px(&cs, 3, avail) +
  6517. mp_px(&cs, 1, avail);
  6518. if (raw[c] < 24)
  6519. raw[c] = 24;
  6520. total += raw[c];
  6521. }
  6522. /* A one-column table still has to fill its own width; the
  6523. * intrinsic fallback above otherwise leaves the cell at its
  6524. * text width (HN's outer table and nested story table). */
  6525. if (total > 0 && total < avail) {
  6526. int c;
  6527. for (c = 0; c < ncell; c++)
  6528. raw[c] = raw[c] * avail / total;
  6529. total = avail;
  6530. }
  6531. }
  6532. prefix[0] = row_left;
  6533. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  6534. prefix[n + 1] = prefix[n] + raw[n];
  6535. for (n = 0; n < (unsigned int)ncell; n++) {
  6536. struct br_style cs;
  6537. int start = colstart[n];
  6538. int end = start + colspan[n];
  6539. int w;
  6540. if (end > cols)
  6541. end = cols;
  6542. if (start >= cols)
  6543. continue;
  6544. w = prefix[end] - prefix[start];
  6545. br_style_for(&doc, cell[n], pst, &cs);
  6546. /* The column width already reflects the cell's width property. */
  6547. cs.width_kind = 0;
  6548. cs.max_width_kind = 0;
  6549. if (w < 24)
  6550. w = 24;
  6551. if (w < 8)
  6552. w = 8;
  6553. l->left = prefix[start];
  6554. l->right = l->left + w;
  6555. l->y = y;
  6556. l->line_x = l->left;
  6557. l->run_x = l->left;
  6558. l->line_y = l->y;
  6559. l->line_h = 0;
  6560. l->nruns = 0;
  6561. l->space_pending = 0;
  6562. l->align = cs.align;
  6563. layout_block(l, cell[n], &cs, depth + 1, link);
  6564. if (l->y > bottom)
  6565. bottom = l->y;
  6566. }
  6567. l->left = row_left;
  6568. l->right = row_right;
  6569. l->y = bottom;
  6570. l->line_x = l->left;
  6571. l->run_x = l->left;
  6572. l->line_y = l->y;
  6573. l->line_h = 0;
  6574. l->nruns = 0;
  6575. l->space_pending = 0;
  6576. }
  6577. #define TBL_MAX_ROWS 32
  6578. #define TBL_MAX_COLS 12
  6579. #define TBL_MAX_CELLS 128
  6580. struct tbl_cell {
  6581. unsigned int node;
  6582. unsigned char row, col, rowspan, colspan;
  6583. int height;
  6584. };
  6585. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  6586. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  6587. static int table_active;
  6588. static int table_has_rowspan(unsigned int table)
  6589. {
  6590. unsigned int r, c;
  6591. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  6592. struct br_node *rn = &doc.nodes[r];
  6593. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  6594. continue;
  6595. for (c = rn->first; c; c = doc.nodes[c].next) {
  6596. struct br_node *cn = &doc.nodes[c];
  6597. if (cn->type == BR_NODE_ELEM &&
  6598. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  6599. cn->rowspan > 1)
  6600. return 1;
  6601. }
  6602. }
  6603. return 0;
  6604. }
  6605. static void table_cell_style(unsigned int row, unsigned int cell,
  6606. const struct br_style *st, struct br_style *out)
  6607. {
  6608. struct br_style trs;
  6609. br_style_for(&doc, row, st, &trs);
  6610. br_style_for(&doc, cell, &trs, out);
  6611. }
  6612. /* Tables that use rowspan need row heights before anything is painted. This
  6613. * path builds a small occupancy grid, measures the natural cell heights, then
  6614. * lays every cell out at its row/column position. Tables without rowspan
  6615. * keep the lighter per-row path in layout_table_row(). */
  6616. static void layout_table(struct lay *l, unsigned int table,
  6617. const struct br_style *st, int depth,
  6618. unsigned short link)
  6619. {
  6620. unsigned int rows[TBL_MAX_ROWS];
  6621. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  6622. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  6623. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  6624. int free_raw = 0, free_cols = 0;
  6625. int table_left = l->left, table_right = l->right;
  6626. int top = l->y, avail = table_right - table_left;
  6627. unsigned int r, c;
  6628. int i, rr, cc;
  6629. if (depth > 24 || table_active) {
  6630. layout_children(l, table, st, depth, link);
  6631. return;
  6632. }
  6633. table_active = 1;
  6634. for (r = doc.nodes[table].first;
  6635. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  6636. struct br_node *rn = &doc.nodes[r];
  6637. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  6638. rows[nrows++] = r;
  6639. }
  6640. if (!nrows) {
  6641. table_active = 0;
  6642. layout_children(l, table, st, depth, link);
  6643. return;
  6644. }
  6645. for (rr = 0; rr < nrows; rr++)
  6646. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  6647. tbl_at[rr][cc] = 0;
  6648. for (rr = 0; rr < nrows; rr++) {
  6649. int col = 0;
  6650. for (c = doc.nodes[rows[rr]].first; c;
  6651. c = doc.nodes[c].next) {
  6652. struct br_node *cn = &doc.nodes[c];
  6653. struct br_style cs;
  6654. int rs, csn;
  6655. if (cn->type != BR_NODE_ELEM ||
  6656. (cn->tag != BR_TAG_TD &&
  6657. cn->tag != BR_TAG_TH))
  6658. continue;
  6659. table_cell_style(rows[rr], c, st, &cs);
  6660. if (cs.display == BR_DISPLAY_NONE)
  6661. continue;
  6662. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  6663. col++;
  6664. if (col >= TBL_MAX_COLS)
  6665. break;
  6666. rs = cn->rowspan ? cn->rowspan : 1;
  6667. csn = cn->colspan ? cn->colspan : 1;
  6668. if (rr + rs > nrows)
  6669. rs = nrows - rr;
  6670. if (col + csn > TBL_MAX_COLS)
  6671. csn = TBL_MAX_COLS - col;
  6672. if (rs < 1 || csn < 1)
  6673. continue;
  6674. if (ncells >= TBL_MAX_CELLS)
  6675. break;
  6676. tbl_cells[ncells].node = c;
  6677. tbl_cells[ncells].row = (unsigned char)rr;
  6678. tbl_cells[ncells].col = (unsigned char)col;
  6679. tbl_cells[ncells].rowspan = (unsigned char)rs;
  6680. tbl_cells[ncells].colspan = (unsigned char)csn;
  6681. tbl_cells[ncells].height = 0;
  6682. for (i = rr; i < rr + rs; i++)
  6683. for (int j = col; j < col + csn; j++)
  6684. tbl_at[i][j] =
  6685. (unsigned short)(ncells + 1);
  6686. ncells++;
  6687. col += csn;
  6688. if (col > cols)
  6689. cols = col;
  6690. }
  6691. }
  6692. if (!ncells || cols < 1) {
  6693. table_active = 0;
  6694. layout_children(l, table, st, depth, link);
  6695. return;
  6696. }
  6697. for (i = 0; i < cols; i++) {
  6698. raw[i] = 0;
  6699. fixed[i] = 0;
  6700. }
  6701. /* Intrinsic widths of single-column cells. */
  6702. for (i = 0; i < ncells; i++) {
  6703. struct br_style cs;
  6704. int w;
  6705. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  6706. st, &cs);
  6707. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  6708. mp_px(&cs, 7, avail) +
  6709. mp_px(&cs, 5, avail) +
  6710. mp_px(&cs, 3, avail) +
  6711. mp_px(&cs, 1, avail) +
  6712. cs.border_w[0] + cs.border_w[1] +
  6713. cs.border_w[2] + cs.border_w[3];
  6714. if (w < 24)
  6715. w = 24;
  6716. if (tbl_cells[i].colspan == 1) {
  6717. int col = tbl_cells[i].col;
  6718. if (w > raw[col])
  6719. raw[col] = w;
  6720. }
  6721. }
  6722. /* A spanning cell only needs the sum of its columns to be large
  6723. * enough; put the deficit in the last column. */
  6724. for (i = 0; i < ncells; i++) {
  6725. struct br_style cs;
  6726. int w, sum, col, span;
  6727. if (tbl_cells[i].colspan < 2)
  6728. continue;
  6729. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  6730. st, &cs);
  6731. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  6732. mp_px(&cs, 7, avail) +
  6733. mp_px(&cs, 5, avail) +
  6734. mp_px(&cs, 3, avail) +
  6735. mp_px(&cs, 1, avail) +
  6736. cs.border_w[0] + cs.border_w[1] +
  6737. cs.border_w[2] + cs.border_w[3];
  6738. col = tbl_cells[i].col;
  6739. span = tbl_cells[i].colspan;
  6740. sum = 0;
  6741. for (int j = 0; j < span; j++)
  6742. sum += raw[col + j];
  6743. if (w > sum)
  6744. raw[col + span - 1] += w - sum;
  6745. }
  6746. /* Explicit/percentage widths, as in table_columns(). */
  6747. for (i = 0; i < ncells; i++) {
  6748. struct br_style cs;
  6749. int col;
  6750. if (tbl_cells[i].colspan != 1)
  6751. continue;
  6752. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  6753. st, &cs);
  6754. col = tbl_cells[i].col;
  6755. if (cs.width_kind == 1) {
  6756. raw[col] = cs.width;
  6757. fixed[col] = 1;
  6758. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  6759. raw[col] = style_width_px(&cs, avail);
  6760. fixed[col] = 1;
  6761. }
  6762. }
  6763. for (i = 0; i < cols; i++) {
  6764. if (raw[i] < 8)
  6765. raw[i] = 8;
  6766. total += raw[i];
  6767. if (fixed[i])
  6768. fixed_sum += raw[i];
  6769. else {
  6770. free_raw += raw[i];
  6771. free_cols++;
  6772. }
  6773. }
  6774. if (fixed_sum > 0 && fixed_sum < avail) {
  6775. int free_avail = avail - fixed_sum;
  6776. if (free_raw > 0) {
  6777. for (i = 0; i < cols; i++)
  6778. if (!fixed[i])
  6779. raw[i] = free_avail * raw[i] /
  6780. free_raw;
  6781. } else if (free_cols > 0) {
  6782. for (i = 0; i < cols; i++)
  6783. if (!fixed[i])
  6784. raw[i] = free_avail / free_cols;
  6785. }
  6786. } else if (total < avail && total > 0) {
  6787. for (i = 0; i < cols; i++)
  6788. raw[i] = raw[i] * avail / total;
  6789. }
  6790. prefix[0] = table_left;
  6791. for (i = 0; i < cols; i++)
  6792. prefix[i + 1] = prefix[i] + raw[i];
  6793. /* Measure natural cell heights with the column widths. */
  6794. for (i = 0; i < ncells; i++) {
  6795. struct br_style cs;
  6796. int col = tbl_cells[i].col;
  6797. int span = tbl_cells[i].colspan;
  6798. int w = prefix[col + span] - prefix[col];
  6799. int sl = l->left, sr = l->right, sy = l->y;
  6800. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  6801. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  6802. int sal = l->align, sdraw = l->draw;
  6803. struct ngui *sui = l->ui;
  6804. if (w < 8)
  6805. w = 8;
  6806. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  6807. st, &cs);
  6808. cs.width_kind = 0;
  6809. cs.max_width_kind = 0;
  6810. l->draw = 0;
  6811. l->ui = 0;
  6812. l->left = prefix[col];
  6813. l->right = l->left + w;
  6814. l->y = 0;
  6815. l->line_x = l->left;
  6816. l->run_x = l->left;
  6817. l->line_y = 0;
  6818. l->line_h = 0;
  6819. l->nruns = 0;
  6820. l->space_pending = 0;
  6821. l->align = cs.align;
  6822. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  6823. tbl_cells[i].height = block_h[tbl_cells[i].node];
  6824. l->left = sl;
  6825. l->right = sr;
  6826. l->y = sy;
  6827. l->line_x = slx;
  6828. l->run_x = srx;
  6829. l->line_y = sly;
  6830. l->line_h = slh;
  6831. l->nruns = snr;
  6832. l->space_pending = ssp;
  6833. l->align = sal;
  6834. l->draw = sdraw;
  6835. l->ui = sui;
  6836. }
  6837. for (i = 0; i < nrows; i++)
  6838. rowh[i] = 0;
  6839. for (i = 0; i < ncells; i++) {
  6840. int row = tbl_cells[i].row;
  6841. if (tbl_cells[i].rowspan == 1) {
  6842. if (tbl_cells[i].height > rowh[row])
  6843. rowh[row] = tbl_cells[i].height;
  6844. }
  6845. }
  6846. for (i = 0; i < ncells; i++) {
  6847. int row = tbl_cells[i].row;
  6848. int span = tbl_cells[i].rowspan;
  6849. int sum = 0;
  6850. if (span < 2)
  6851. continue;
  6852. for (int j = 0; j < span; j++)
  6853. sum += rowh[row + j];
  6854. if (sum < tbl_cells[i].height)
  6855. rowh[row + span - 1] +=
  6856. tbl_cells[i].height - sum;
  6857. }
  6858. for (i = 0; i < nrows; i++)
  6859. if (rowh[i] < 8)
  6860. rowh[i] = 8;
  6861. rowy[0] = top;
  6862. for (i = 1; i < nrows; i++)
  6863. rowy[i] = rowy[i - 1] + rowh[i - 1];
  6864. if (!l->draw) {
  6865. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  6866. table_active = 0;
  6867. return;
  6868. }
  6869. for (i = 0; i < ncells; i++) {
  6870. struct br_style cs;
  6871. int col = tbl_cells[i].col;
  6872. int span = tbl_cells[i].colspan;
  6873. int row = tbl_cells[i].row;
  6874. int rspan = tbl_cells[i].rowspan;
  6875. int w = prefix[col + span] - prefix[col];
  6876. int h = 0;
  6877. int sl = l->left, sr = l->right, sy = l->y;
  6878. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  6879. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  6880. int sal = l->align;
  6881. int deco;
  6882. for (int j = 0; j < rspan; j++)
  6883. h += rowh[row + j];
  6884. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  6885. cs.width_kind = 0;
  6886. cs.max_width_kind = 0;
  6887. cs.box_sizing = 0;
  6888. deco = mp_px(&cs, 4, avail) +
  6889. mp_px(&cs, 6, avail) +
  6890. cs.border_w[0] + cs.border_w[2];
  6891. cs.height_kind = 1;
  6892. cs.height = h > deco ? h - deco : 0;
  6893. /* The block painter reads block_h[] from the measure pass; make
  6894. * the table cell fill its row/rowspan, not just its content. */
  6895. if (h > 0 && h < 65536)
  6896. block_h[tbl_cells[i].node] = (unsigned short)h;
  6897. l->left = prefix[col];
  6898. l->right = l->left + w;
  6899. l->y = rowy[row];
  6900. l->line_x = l->left;
  6901. l->run_x = l->left;
  6902. l->line_y = l->y;
  6903. l->line_h = 0;
  6904. l->nruns = 0;
  6905. l->space_pending = 0;
  6906. l->align = cs.align;
  6907. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  6908. l->left = sl;
  6909. l->right = sr;
  6910. l->y = sy;
  6911. l->line_x = slx;
  6912. l->run_x = srx;
  6913. l->line_y = sly;
  6914. l->line_h = slh;
  6915. l->nruns = snr;
  6916. l->space_pending = ssp;
  6917. l->align = sal;
  6918. }
  6919. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  6920. table_active = 0;
  6921. }
  6922. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  6923. * flow so they sit above it, like CSS painting order. Their flow origin is
  6924. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  6925. struct br_deferred {
  6926. unsigned int node;
  6927. int flow_y, flow_left, flow_right;
  6928. unsigned short link;
  6929. signed short z_index;
  6930. unsigned char z_set;
  6931. unsigned int order;
  6932. };
  6933. static struct br_deferred deferred[16];
  6934. static int ndeferred;
  6935. static void layout_children(struct lay *l, unsigned int parent,
  6936. const struct br_style *pst, int depth,
  6937. unsigned short link)
  6938. {
  6939. unsigned int n;
  6940. if (depth > 24)
  6941. return;
  6942. n = doc.nodes[parent].first;
  6943. while (n) {
  6944. struct br_node *nd = &doc.nodes[n];
  6945. struct br_style cs;
  6946. unsigned short lk = link;
  6947. if (nd->type == BR_NODE_TEXT) {
  6948. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  6949. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  6950. n = nd->next;
  6951. continue;
  6952. }
  6953. br_style_for(&doc, n, pst, &cs);
  6954. if (cs.display == BR_DISPLAY_NONE) {
  6955. n = nd->next;
  6956. continue;
  6957. }
  6958. if (cs.clear && l->float_active) {
  6959. flush_line(l);
  6960. if (l->y < l->float_bottom)
  6961. l->y = l->float_bottom;
  6962. l->float_active = 0;
  6963. l->line_x = l->left;
  6964. l->run_x = l->left;
  6965. l->line_left = l->left;
  6966. l->line_right = l->right;
  6967. l->line_y = l->y;
  6968. l->line_h = 0;
  6969. l->nruns = 0;
  6970. l->space_pending = 0;
  6971. }
  6972. if (nd->tag == BR_TAG_A && nd->href_off)
  6973. lk = (unsigned short)n;
  6974. if (cs.pos == 1 || cs.pos == 2 ||
  6975. (cs.pos == 3 && cs.z_set)) {
  6976. if (cs.pos == 3 && l->draw && ndeferred < 16) {
  6977. /* Relative z-index: measure and advance the flow
  6978. * without painting, then paint it in the
  6979. * deferred (stacked) pass. */
  6980. int fy = l->y, fl = l->left, fr = l->right;
  6981. int save_draw = l->draw;
  6982. l->draw = 0;
  6983. layout_block(l, n, &cs, depth + 1, lk);
  6984. l->draw = save_draw;
  6985. deferred[ndeferred].node = n;
  6986. deferred[ndeferred].flow_y = fy;
  6987. deferred[ndeferred].flow_left = fl;
  6988. deferred[ndeferred].flow_right = fr;
  6989. deferred[ndeferred].link = lk;
  6990. deferred[ndeferred].z_index = cs.z_index;
  6991. deferred[ndeferred].z_set = cs.z_set;
  6992. deferred[ndeferred].order = (unsigned int)ndeferred;
  6993. ndeferred++;
  6994. } else if (l->draw && ndeferred < 16) {
  6995. deferred[ndeferred].node = n;
  6996. deferred[ndeferred].flow_y = l->y;
  6997. deferred[ndeferred].flow_left = l->left;
  6998. deferred[ndeferred].flow_right = l->right;
  6999. deferred[ndeferred].link = lk;
  7000. deferred[ndeferred].z_index = cs.z_index;
  7001. deferred[ndeferred].z_set = cs.z_set;
  7002. deferred[ndeferred].order = (unsigned int)ndeferred;
  7003. ndeferred++;
  7004. } else {
  7005. layout_block(l, n, &cs, depth + 1, lk);
  7006. }
  7007. if (cs.pos == 1 && block_h[n] &&
  7008. doc.nodes[n].class_off) {
  7009. const char *cl = doc.attrs +
  7010. doc.nodes[n].class_off;
  7011. if ((contains_ci(cl, "poster-wrapper") ||
  7012. contains_ci(cl, "ts-picture")) &&
  7013. !has_skeleton_sibling(n))
  7014. l->y += block_h[n];
  7015. }
  7016. n = nd->next;
  7017. continue;
  7018. }
  7019. if (nd->tag == BR_TAG_BR) {
  7020. flush_line(l);
  7021. n = nd->next;
  7022. continue;
  7023. }
  7024. if (nd->tag == BR_TAG_HR) {
  7025. flush_line(l);
  7026. if (l->draw)
  7027. ngui_fill_rect(l->ui,
  7028. (struct ngui_rect){l->left, l->y + 2,
  7029. l->right - l->left, 1}, BR_GRAY);
  7030. l->y += 8;
  7031. n = nd->next;
  7032. continue;
  7033. }
  7034. if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  7035. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) {
  7036. if (!(nd->tag == BR_TAG_INPUT &&
  7037. s_eq(br_type(&doc, n), "hidden")))
  7038. add_form_run(l, n, &cs, lk);
  7039. n = nd->next;
  7040. continue;
  7041. }
  7042. if (nd->tag == BR_TAG_IMG) {
  7043. add_image_run(l, n, &cs, lk);
  7044. n = nd->next;
  7045. continue;
  7046. }
  7047. if (nd->tag == BR_TAG_VIDEO) {
  7048. layout_block(l, n, &cs, depth + 1, lk);
  7049. n = nd->next;
  7050. continue;
  7051. }
  7052. if (cs.float_left) {
  7053. n = layout_float_group(l, n, pst, depth, lk);
  7054. continue;
  7055. }
  7056. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  7057. n = layout_inline_blocks(l, n, pst, depth, link);
  7058. continue;
  7059. }
  7060. if (cs.display == BR_DISPLAY_BLOCK || br_tag_is_block(nd->tag))
  7061. layout_block(l, n, &cs, depth + 1, lk);
  7062. else {
  7063. layout_children(l, n, &cs, depth + 1, lk);
  7064. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  7065. l->space_pending = 1;
  7066. }
  7067. n = nd->next;
  7068. }
  7069. }
  7070. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  7071. * runs and a recursive page can otherwise overflow the stack. */
  7072. static struct lay layout_state;
  7073. static int measure_page(int left, int right)
  7074. {
  7075. struct lay *l = &layout_state;
  7076. struct br_style base = base_style();
  7077. unsigned int i;
  7078. for (i = 0; i < BR_MAX_NODES; i++) {
  7079. block_h[i] = 0;
  7080. img_top[i] = 0;
  7081. img_h[i] = 0;
  7082. layout_boxes[i].valid = 0;
  7083. }
  7084. memset(li_marker, 0, sizeof(li_marker));
  7085. l->draw = 0;
  7086. l->ui = &ui;
  7087. l->left = left;
  7088. l->right = right;
  7089. l->y = 0;
  7090. l->line_x = left;
  7091. l->run_x = left;
  7092. l->line_left = left;
  7093. l->line_right = right;
  7094. l->line_y = 0;
  7095. l->line_h = 0;
  7096. l->align = BR_ALIGN_LEFT;
  7097. l->float_active = 0;
  7098. l->parent_top = 0;
  7099. l->depth = 0;
  7100. l->nruns = 0;
  7101. l->space_pending = 0;
  7102. layout_children(l, doc.root, &base, 0, 0);
  7103. return l->y + 8;
  7104. }
  7105. static int deferred_cmp(const struct br_deferred *a,
  7106. const struct br_deferred *b)
  7107. {
  7108. int az = a->z_set ? a->z_index : 0;
  7109. int bz = b->z_set ? b->z_index : 0;
  7110. if (az != bz)
  7111. return az < bz ? -1 : 1;
  7112. if (a->order != b->order)
  7113. return a->order < b->order ? -1 : 1;
  7114. return 0;
  7115. }
  7116. static void sort_deferred(void)
  7117. {
  7118. int i;
  7119. for (i = 1; i < ndeferred; i++) {
  7120. struct br_deferred key = deferred[i];
  7121. int j = i;
  7122. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  7123. deferred[j] = deferred[j - 1];
  7124. j--;
  7125. }
  7126. deferred[j] = key;
  7127. }
  7128. }
  7129. static void render_page(int left, int right, int y0)
  7130. {
  7131. struct lay *l = &layout_state;
  7132. struct br_style base = base_style();
  7133. l->draw = 1;
  7134. l->ui = &ui;
  7135. l->left = left;
  7136. l->right = right;
  7137. l->y = y0;
  7138. l->line_x = left;
  7139. l->run_x = left;
  7140. l->line_left = left;
  7141. l->line_right = right;
  7142. l->line_y = y0;
  7143. l->line_h = 0;
  7144. l->align = BR_ALIGN_LEFT;
  7145. l->float_active = 0;
  7146. l->parent_top = 0;
  7147. l->depth = 0;
  7148. l->nruns = 0;
  7149. l->space_pending = 0;
  7150. nhits = 0;
  7151. ndeferred = 0;
  7152. layout_children(l, doc.root, &base, 0, 0);
  7153. sort_deferred();
  7154. {
  7155. int i;
  7156. for (i = 0; i < ndeferred; i++) {
  7157. struct br_style st;
  7158. br_style_for(&doc, deferred[i].node, &base, &st);
  7159. if (st.display == BR_DISPLAY_NONE)
  7160. continue;
  7161. l->draw = 1;
  7162. l->left = deferred[i].flow_left;
  7163. l->right = deferred[i].flow_right;
  7164. l->y = deferred[i].flow_y;
  7165. l->line_x = l->left;
  7166. l->run_x = l->left;
  7167. l->line_y = l->y;
  7168. l->line_h = 0;
  7169. l->nruns = 0;
  7170. l->space_pending = 0;
  7171. l->align = st.align;
  7172. if (st.pos == 2 && block_h[deferred[i].node]) {
  7173. struct ngui_rect clip;
  7174. int ch = block_h[deferred[i].node] + 24;
  7175. clip.x = page_rect.x;
  7176. clip.y = page_rect.y;
  7177. clip.w = page_rect.w - 12;
  7178. if (ch > page_rect.h)
  7179. ch = page_rect.h;
  7180. clip.h = ch;
  7181. ngui_push_clip(&ui, clip);
  7182. if (st.has_bg)
  7183. ngui_fill_rect(&ui, clip, st.bg);
  7184. layout_block(l, deferred[i].node, &st, 0,
  7185. deferred[i].link);
  7186. ngui_pop_clip(&ui);
  7187. } else {
  7188. layout_block(l, deferred[i].node, &st, 0,
  7189. deferred[i].link);
  7190. }
  7191. }
  7192. }
  7193. }
  7194. /* ---- UI ---- */
  7195. static int find_hit(int x, int y)
  7196. {
  7197. int i;
  7198. for (i = nhits - 1; i >= 0; i--) {
  7199. struct hit *h = &hits[i];
  7200. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  7201. y < h->y + h->h)
  7202. return (int)h->node;
  7203. }
  7204. return 0;
  7205. }
  7206. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  7207. {
  7208. int x = r.x + 4, y = r.y + 4, h = 22;
  7209. int compact = r.w < 560;
  7210. int go_w = r.w < 420 ? 32 : 42;
  7211. int in_x, in_w, res;
  7212. ngui_fill_rect(&ui, r, ui.theme.panel);
  7213. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  7214. ui.theme.border);
  7215. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  7216. NGUI_ICON_CHEVRON_LEFT))
  7217. *action |= ACT_BACK;
  7218. x += 32;
  7219. if (!compact) {
  7220. if (ngui_icon_button(&ui, ID_FORWARD,
  7221. (struct ngui_rect){x, y, 28, h},
  7222. NGUI_ICON_CHEVRON_RIGHT))
  7223. *action |= ACT_FORWARD;
  7224. x += 32;
  7225. }
  7226. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  7227. NGUI_ICON_REFRESH))
  7228. *action |= ACT_RELOAD;
  7229. x += 32;
  7230. if (!compact) {
  7231. if (ngui_icon_button(&ui, ID_HOME,
  7232. (struct ngui_rect){x, y, 28, h},
  7233. NGUI_ICON_HOME))
  7234. *action |= ACT_HOME;
  7235. x += 32;
  7236. }
  7237. in_x = x + 2;
  7238. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  7239. if (in_w < 60)
  7240. in_w = 60;
  7241. res = ngui_text_input(&ui, ID_URL,
  7242. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  7243. if (res & NGUI_INPUT_SUBMIT)
  7244. *action |= ACT_NAV;
  7245. if (res & NGUI_INPUT_CANCEL)
  7246. ngui_set_focus(&ui, 0);
  7247. if (ngui_button(&ui, ID_GO,
  7248. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  7249. "Go"))
  7250. *action |= ACT_NAV;
  7251. }
  7252. static int page_hover_node(void)
  7253. {
  7254. if (!ui.inside)
  7255. return 0;
  7256. if (ui.mouse_x < page_rect.x ||
  7257. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  7258. ui.mouse_y < page_rect.y ||
  7259. ui.mouse_y >= page_rect.y + page_rect.h)
  7260. return 0;
  7261. return find_hit(ui.mouse_x, ui.mouse_y);
  7262. }
  7263. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  7264. {
  7265. int x, y, w = page.w, h = page.h;
  7266. if (!src || w <= 0 || h <= 0)
  7267. return;
  7268. for (y = 0; y < h; y++) {
  7269. unsigned short *s = src + (page.y + y) * sw + page.x;
  7270. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  7271. for (x = 0; x + 1 < w; x += 2) {
  7272. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  7273. }
  7274. if (x < w)
  7275. d[x] = s[x];
  7276. }
  7277. }
  7278. static void draw_page(struct ngui_rect page)
  7279. {
  7280. int left, right, ch;
  7281. int old_panel, old_dim;
  7282. unsigned short *saved_px;
  7283. unsigned short page_bg = ui.theme.bg;
  7284. int saved_w, saved_h, use_buf;
  7285. page_rect = page;
  7286. {
  7287. unsigned int root = doc.nnode > 1 ?
  7288. br_find_tag(&doc, BR_TAG_HTML) : 0;
  7289. unsigned int body = doc.nnode > 1 ?
  7290. br_find_tag(&doc, BR_TAG_BODY) : 0;
  7291. struct br_style bs;
  7292. if (root) {
  7293. style_for_node(root - 1, &bs);
  7294. if (bs.has_bg)
  7295. page_bg = bs.bg;
  7296. }
  7297. if (body) {
  7298. style_for_node(body - 1, &bs);
  7299. if (bs.has_bg)
  7300. page_bg = bs.bg;
  7301. }
  7302. }
  7303. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  7304. page_cache_valid && layout_valid &&
  7305. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  7306. !(ui.scroll_y &&
  7307. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  7308. page_scroll.offset == page_cache_scroll &&
  7309. page_cache_nnode == doc.nnode &&
  7310. page_cache_x == page.x && page_cache_y == page.y &&
  7311. page_cache_w == page.w && page_cache_h == page.h) {
  7312. blit_page(page, page_backbuf, pagebuf_w);
  7313. return;
  7314. }
  7315. ngui_fill_rect(&ui, page, page_bg);
  7316. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  7317. const char *s = page_loading ? "Loading..." : "No page";
  7318. int w = (int)ngui_text_width_ui(&ui, s);
  7319. ngui_text(&ui, page.x + (page.w - w) / 2,
  7320. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  7321. page_scroll.content_h = 0;
  7322. page_scroll.view_h = page.h;
  7323. page_cache_valid = 0;
  7324. return;
  7325. }
  7326. if (page.w < 40 || page.h < 40) {
  7327. page_cache_valid = 0;
  7328. return;
  7329. }
  7330. saved_px = ui.px;
  7331. saved_w = ui.w;
  7332. saved_h = ui.h;
  7333. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  7334. if (use_buf) {
  7335. ui.px = page_backbuf;
  7336. ui.w = pagebuf_w;
  7337. ui.h = pagebuf_h;
  7338. ngui_fill_rect(&ui, page, page_bg);
  7339. }
  7340. left = page.x + 8;
  7341. right = page.x + page.w - 16;
  7342. if (!layout_valid || left != layout_left || right != layout_right ||
  7343. layout_nnode != doc.nnode) {
  7344. layout_content_h = measure_page(left, right);
  7345. layout_valid = 1;
  7346. layout_left = left;
  7347. layout_right = right;
  7348. layout_nnode = doc.nnode;
  7349. }
  7350. ch = layout_content_h;
  7351. page_scroll.content_h = ch;
  7352. page_scroll.view_h = page.h;
  7353. ngui_scroll_begin(&ui, page, &page_scroll);
  7354. ngui_scroll_wheel(&ui, page, &page_scroll);
  7355. render_page(left, right, page.y + 4 - page_scroll.offset);
  7356. old_panel = ui.theme.panel_alt;
  7357. old_dim = ui.theme.text_dim;
  7358. ui.theme.panel_alt = 0xC618;
  7359. ui.theme.text_dim = 0x8410;
  7360. ngui_scroll_end(&ui, page, &page_scroll);
  7361. ui.theme.panel_alt = old_panel;
  7362. ui.theme.text_dim = old_dim;
  7363. if (use_buf) {
  7364. ui.px = saved_px;
  7365. ui.w = saved_w;
  7366. ui.h = saved_h;
  7367. blit_page(page, page_backbuf, pagebuf_w);
  7368. page_cache_valid = 1;
  7369. page_cache_scroll = page_scroll.offset;
  7370. page_cache_nnode = doc.nnode;
  7371. page_cache_x = page.x;
  7372. page_cache_y = page.y;
  7373. page_cache_w = page.w;
  7374. page_cache_h = page.h;
  7375. } else {
  7376. page_cache_valid = 0;
  7377. }
  7378. }
  7379. static void draw_status(struct ngui_rect r)
  7380. {
  7381. char msg[BR_URL_MAX + 32];
  7382. unsigned int n = 0;
  7383. int hover = page_hover_node();
  7384. unsigned short color;
  7385. const char *kind;
  7386. ngui_fill_rect(&ui, r, ui.theme.panel);
  7387. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  7388. ui.theme.border);
  7389. if (hover) {
  7390. const char *href = br_href(&doc, (unsigned int)hover);
  7391. char url[BR_URL_MAX];
  7392. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  7393. s_append(msg, &n, "Link: ", sizeof(msg));
  7394. s_append(msg, &n, url, sizeof(msg));
  7395. } else {
  7396. s_copy(msg, "Link", sizeof(msg));
  7397. }
  7398. color = ui.theme.accent;
  7399. } else if (status_text[0]) {
  7400. s_copy(msg, status_text, sizeof(msg));
  7401. color = status_error ? ui.theme.error : ui.theme.text;
  7402. } else if (page_title[0]) {
  7403. s_copy(msg, page_title, sizeof(msg));
  7404. color = ui.theme.text;
  7405. } else {
  7406. s_copy(msg, "Ready", sizeof(msg));
  7407. color = ui.theme.text_dim;
  7408. }
  7409. kind = s_eq(page_url, "about:home") ? "HOME" :
  7410. page_is_local ? "FILE" :
  7411. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  7412. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  7413. {
  7414. int kw = (int)ngui_text_width_ui(&ui, kind);
  7415. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  7416. ui.theme.text_dim);
  7417. }
  7418. }
  7419. static void draw(unsigned int *action)
  7420. {
  7421. struct ngui_rect r = {0, 0, ui.w, ui.h};
  7422. struct ngui_rect toolbar, status, page;
  7423. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  7424. status = ngui_cut_bottom(&r, BR_STATUS_H);
  7425. page = r;
  7426. draw_toolbar(toolbar, action);
  7427. draw_page(page);
  7428. draw_status(status);
  7429. }
  7430. static void redraw_now(void)
  7431. {
  7432. unsigned int action = 0;
  7433. ngui_begin(&ui);
  7434. draw(&action);
  7435. ngui_end(&ui);
  7436. }
  7437. static void handle_keys(unsigned int *action)
  7438. {
  7439. int k, scrolled = 0;
  7440. if (form_focus >= doc.nnode)
  7441. form_focus = 0;
  7442. if (form_focus && !ngui_focus(&ui)) {
  7443. while ((k = ngui_key(&ui)) != 0)
  7444. form_key(k);
  7445. return;
  7446. }
  7447. /* Batch queued page keys: a slow full-page render must not make a
  7448. * held Page Down advance only once every few frames. */
  7449. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  7450. scrolled++;
  7451. if (scrolled)
  7452. ngui_invalidate(&ui);
  7453. if (ngui_focus(&ui))
  7454. return;
  7455. while ((k = ngui_key(&ui)) != 0) {
  7456. switch (k) {
  7457. case NGUI_KEY_ESC:
  7458. *action |= ACT_CLOSE;
  7459. break;
  7460. case NGUI_KEY_TAB:
  7461. case 0x0C: /* Ctrl+L */
  7462. ngui_set_focus(&ui, ID_URL);
  7463. break;
  7464. case 0x12: /* Ctrl+R */
  7465. *action |= ACT_RELOAD;
  7466. break;
  7467. case NGUI_KEY_BACKSPACE:
  7468. *action |= ACT_BACK;
  7469. break;
  7470. case NGUI_KEY_UP:
  7471. ngui_scroll_to(&page_scroll,
  7472. page_scroll.offset - 24);
  7473. ngui_invalidate(&ui);
  7474. break;
  7475. case NGUI_KEY_DOWN:
  7476. ngui_scroll_to(&page_scroll,
  7477. page_scroll.offset + 24);
  7478. ngui_invalidate(&ui);
  7479. break;
  7480. case NGUI_KEY_HOME:
  7481. ngui_scroll_to(&page_scroll, 0);
  7482. ngui_invalidate(&ui);
  7483. break;
  7484. case NGUI_KEY_END:
  7485. ngui_scroll_to(&page_scroll,
  7486. page_scroll.content_h -
  7487. page_scroll.view_h);
  7488. ngui_invalidate(&ui);
  7489. break;
  7490. default:
  7491. break;
  7492. }
  7493. }
  7494. }
  7495. static unsigned int form_ancestor(unsigned int node)
  7496. {
  7497. unsigned int p = node;
  7498. while (p && p < doc.nnode) {
  7499. if (doc.nodes[p].tag == BR_TAG_FORM &&
  7500. doc.nodes[p].type == BR_NODE_ELEM)
  7501. return p;
  7502. p = doc.nodes[p].parent;
  7503. }
  7504. return 0;
  7505. }
  7506. static int form_descendant(unsigned int node, unsigned int form)
  7507. {
  7508. unsigned int p = node;
  7509. while (p && p < doc.nnode) {
  7510. if (p == form)
  7511. return 1;
  7512. p = doc.nodes[p].parent;
  7513. }
  7514. return 0;
  7515. }
  7516. static void form_reset_form(unsigned int form)
  7517. {
  7518. unsigned int i;
  7519. for (i = 0; i < FORM_MAX; i++)
  7520. if (form_states[i].used &&
  7521. form_descendant(form_states[i].node, form))
  7522. form_states[i].used = 0;
  7523. form_focus = 0;
  7524. }
  7525. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  7526. const char *s)
  7527. {
  7528. static const char hex[] = "0123456789ABCDEF";
  7529. while (s && *s && *n + 1 < cap) {
  7530. unsigned char c = (unsigned char)*s++;
  7531. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  7532. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  7533. c == '.' || c == '~') {
  7534. dst[(*n)++] = (char)c;
  7535. } else if (c == ' ') {
  7536. dst[(*n)++] = '+';
  7537. } else if (*n + 3 < cap) {
  7538. dst[(*n)++] = '%';
  7539. dst[(*n)++] = hex[c >> 4];
  7540. dst[(*n)++] = hex[c & 15];
  7541. }
  7542. }
  7543. dst[*n] = '\0';
  7544. }
  7545. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  7546. const char *name, const char *value, int *first)
  7547. {
  7548. if (!name || !name[0])
  7549. return;
  7550. if (!*first && *n + 1 < cap)
  7551. dst[(*n)++] = '&';
  7552. *first = 0;
  7553. form_url_append(dst, n, cap, name);
  7554. if (*n + 1 < cap)
  7555. dst[(*n)++] = '=';
  7556. form_url_append(dst, n, cap, value ? value : "");
  7557. dst[*n] = '\0';
  7558. }
  7559. static int form_submit_form(unsigned int node, int fire_event)
  7560. {
  7561. unsigned int form = form_ancestor(node);
  7562. char action[BR_URL_MAX], query[2048];
  7563. unsigned int qn = 0, i;
  7564. int first = 1, is_post = 0;
  7565. const char *a, *method;
  7566. if (!form)
  7567. return 0;
  7568. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  7569. return 0;
  7570. method = br_find_attr(&doc, form, "method");
  7571. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  7572. is_post = 1;
  7573. a = br_find_attr(&doc, form, "action");
  7574. if (a && a[0]) {
  7575. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  7576. return 0;
  7577. } else {
  7578. s_copy(action, page_url, sizeof(action));
  7579. }
  7580. query[0] = '\0';
  7581. for (i = 0; i < doc.nnode; i++) {
  7582. struct br_node *nd = &doc.nodes[i];
  7583. struct form_state *fs;
  7584. const char *name;
  7585. const char *value = "";
  7586. if (nd->type != BR_NODE_ELEM || i == form ||
  7587. !form_descendant(i, form))
  7588. continue;
  7589. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  7590. nd->tag != BR_TAG_SELECT)
  7591. continue;
  7592. if (form_disabled(i))
  7593. continue;
  7594. name = br_find_attr(&doc, i, "name");
  7595. if (!name || !name[0])
  7596. continue;
  7597. fs = form_get(i, 1);
  7598. if (!fs)
  7599. continue;
  7600. if (nd->tag == BR_TAG_SELECT) {
  7601. char opt[64];
  7602. if (!form_option_text(i, fs->selected, opt,
  7603. sizeof(opt)))
  7604. s_copy(opt, "", sizeof(opt));
  7605. value = opt;
  7606. {
  7607. unsigned int c, oi = 0;
  7608. for (c = nd->first; c;
  7609. c = doc.nodes[c].next) {
  7610. if (doc.nodes[c].type != BR_NODE_ELEM ||
  7611. doc.nodes[c].tag != BR_TAG_OPTION)
  7612. continue;
  7613. if (oi == fs->selected) {
  7614. const char *v =
  7615. br_value(&doc, c);
  7616. if (v && v[0])
  7617. value = v;
  7618. break;
  7619. }
  7620. oi++;
  7621. }
  7622. }
  7623. } else if (nd->tag == BR_TAG_INPUT) {
  7624. int kind = form_kind_of(i);
  7625. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  7626. if (!fs->checked)
  7627. continue;
  7628. value = br_value(&doc, i);
  7629. if (!value || !value[0])
  7630. value = "on";
  7631. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  7632. kind == FORM_BUTTON) {
  7633. if (i != node)
  7634. continue;
  7635. value = fs->value;
  7636. } else {
  7637. value = fs->value;
  7638. }
  7639. } else {
  7640. value = fs->value;
  7641. }
  7642. form_add_param(query, &qn, sizeof(query), name, value, &first);
  7643. }
  7644. if (is_post) {
  7645. if (action[0] == '/') {
  7646. set_status("POST forms need an HTTP action URL", 1, 4000);
  7647. ngui_invalidate(&ui);
  7648. return 0;
  7649. }
  7650. if (qn >= sizeof(pending_post))
  7651. qn = sizeof(pending_post) - 1;
  7652. if (qn)
  7653. memcpy(pending_post, query, qn);
  7654. pending_post[qn] = '\0';
  7655. pending_post_len = qn;
  7656. } else {
  7657. pending_post_len = 0;
  7658. if (qn) {
  7659. unsigned int an = s_len(action);
  7660. if (an + qn + 2 < sizeof(action)) {
  7661. action[an++] = strchr(action, '?') ? '&' : '?';
  7662. action[an] = '\0';
  7663. s_copy(action + an, query,
  7664. sizeof(action) - an);
  7665. }
  7666. }
  7667. }
  7668. s_copy(pending_url, action, sizeof(pending_url));
  7669. pending_action |= ACT_NAV;
  7670. cancel_fetch = 1;
  7671. ngui_invalidate(&ui);
  7672. return 1;
  7673. }
  7674. static void form_reset_event(unsigned int form)
  7675. {
  7676. if (form && !js_browser_event(form, "reset", 1, 1))
  7677. return;
  7678. if (form)
  7679. form_reset_form(form);
  7680. else
  7681. form_reset_state();
  7682. form_dirty = 0;
  7683. layout_valid = 0;
  7684. ngui_invalidate(&ui);
  7685. }
  7686. static void form_blur(void)
  7687. {
  7688. unsigned int node = form_focus;
  7689. form_focus = 0;
  7690. if (node && form_dirty) {
  7691. form_dirty = 0;
  7692. js_browser_event(node, "change", 1, 0);
  7693. }
  7694. }
  7695. static void form_click(unsigned int node)
  7696. {
  7697. struct form_state *fs;
  7698. int kind, changed = 0;
  7699. if (!form_is_control(node) || form_disabled(node))
  7700. return;
  7701. if (form_focus != node)
  7702. form_blur();
  7703. if (!js_browser_event(node, "click", 1, 1))
  7704. return;
  7705. fs = form_get(node, 1);
  7706. if (!fs)
  7707. return;
  7708. kind = form_kind_of(node);
  7709. form_focus = node;
  7710. form_dirty = 0;
  7711. if (kind == FORM_CHECKBOX) {
  7712. fs->checked = !fs->checked;
  7713. changed = 1;
  7714. } else if (kind == FORM_RADIO) {
  7715. const char *name = br_find_attr(&doc, node, "name");
  7716. unsigned int i;
  7717. fs->checked = 1;
  7718. changed = 1;
  7719. if (name) {
  7720. for (i = 0; i < FORM_MAX; i++) {
  7721. struct form_state *o = &form_states[i];
  7722. if (!o->used || o->node == node)
  7723. continue;
  7724. if (form_kind_of(o->node) == FORM_RADIO) {
  7725. const char *on = br_find_attr(&doc,
  7726. o->node,
  7727. "name");
  7728. if (on && s_eq(on, name))
  7729. o->checked = 0;
  7730. }
  7731. }
  7732. }
  7733. } else if (kind == FORM_SELECT) {
  7734. unsigned int n = form_option_count(node);
  7735. if (n) {
  7736. fs->selected = (unsigned char)
  7737. ((fs->selected + 1) % n);
  7738. changed = 1;
  7739. }
  7740. } else if (kind == FORM_SUBMIT) {
  7741. form_submit_form(node, 1);
  7742. return;
  7743. } else if (kind == FORM_RESET) {
  7744. form_reset_event(form_ancestor(node));
  7745. return;
  7746. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  7747. kind == FORM_TEXTAREA) {
  7748. fs->caret = fs->len;
  7749. }
  7750. if (changed) {
  7751. js_browser_event(node, "input", 1, 0);
  7752. js_browser_event(node, "change", 1, 0);
  7753. }
  7754. layout_valid = 0;
  7755. ngui_invalidate(&ui);
  7756. }
  7757. static void form_focus_next(void)
  7758. {
  7759. unsigned int start = form_focus ? form_focus + 1 : 0;
  7760. unsigned int i;
  7761. form_blur();
  7762. for (i = start; i < doc.nnode; i++) {
  7763. if (form_is_control(i) && !form_disabled(i) &&
  7764. !s_eq(br_type(&doc, i), "hidden")) {
  7765. form_focus = i;
  7766. layout_valid = 0;
  7767. ngui_invalidate(&ui);
  7768. return;
  7769. }
  7770. }
  7771. form_focus = 0;
  7772. layout_valid = 0;
  7773. ngui_invalidate(&ui);
  7774. }
  7775. static void form_key(int k)
  7776. {
  7777. struct form_state *fs;
  7778. int kind;
  7779. if (!form_focus || form_focus >= doc.nnode) {
  7780. form_focus = 0;
  7781. return;
  7782. }
  7783. fs = form_get(form_focus, 1);
  7784. if (!fs || form_disabled(form_focus))
  7785. return;
  7786. kind = form_kind_of(form_focus);
  7787. if (kind == FORM_SELECT) {
  7788. unsigned int n = form_option_count(form_focus);
  7789. int changed = 0;
  7790. if (k == NGUI_KEY_UP && n) {
  7791. fs->selected = (unsigned char)
  7792. ((fs->selected + n - 1) % n);
  7793. changed = 1;
  7794. } else if (k == NGUI_KEY_DOWN && n) {
  7795. fs->selected = (unsigned char)
  7796. ((fs->selected + 1) % n);
  7797. changed = 1;
  7798. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  7799. form_blur();
  7800. layout_valid = 0;
  7801. ngui_invalidate(&ui);
  7802. return;
  7803. } else {
  7804. return;
  7805. }
  7806. if (changed) {
  7807. js_browser_event(form_focus, "input", 1, 0);
  7808. js_browser_event(form_focus, "change", 1, 0);
  7809. }
  7810. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  7811. if (k == ' ') {
  7812. form_click(form_focus);
  7813. return;
  7814. }
  7815. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  7816. form_blur();
  7817. layout_valid = 0;
  7818. ngui_invalidate(&ui);
  7819. }
  7820. return;
  7821. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  7822. kind == FORM_RESET) {
  7823. if (k == NGUI_KEY_ESC) {
  7824. form_blur();
  7825. layout_valid = 0;
  7826. ngui_invalidate(&ui);
  7827. } else if (k == '\r' || k == '\n' || k == ' ') {
  7828. form_click(form_focus);
  7829. }
  7830. return;
  7831. } else if (k == NGUI_KEY_TAB) {
  7832. form_focus_next();
  7833. return;
  7834. } else if (k == NGUI_KEY_ESC) {
  7835. form_blur();
  7836. layout_valid = 0;
  7837. ngui_invalidate(&ui);
  7838. return;
  7839. } else if (k == '\r' || k == '\n') {
  7840. unsigned int node = form_focus;
  7841. form_blur();
  7842. if (form_ancestor(node))
  7843. form_submit_form(node, 1);
  7844. layout_valid = 0;
  7845. ngui_invalidate(&ui);
  7846. return;
  7847. } else if (k == NGUI_KEY_BACKSPACE) {
  7848. if (fs->caret) {
  7849. unsigned int i = --fs->caret;
  7850. for (; i < fs->len; i++)
  7851. fs->value[i] = fs->value[i + 1];
  7852. if (fs->len)
  7853. fs->len--;
  7854. form_dirty = 1;
  7855. js_browser_event(form_focus, "input", 1, 0);
  7856. }
  7857. } else if (k == NGUI_KEY_DELETE) {
  7858. if (fs->caret < fs->len) {
  7859. unsigned int i;
  7860. for (i = fs->caret; i < fs->len; i++)
  7861. fs->value[i] = fs->value[i + 1];
  7862. fs->len--;
  7863. form_dirty = 1;
  7864. js_browser_event(form_focus, "input", 1, 0);
  7865. }
  7866. } else if (k == NGUI_KEY_LEFT) {
  7867. if (fs->caret)
  7868. fs->caret--;
  7869. } else if (k == NGUI_KEY_RIGHT) {
  7870. if (fs->caret < fs->len)
  7871. fs->caret++;
  7872. } else if (k == NGUI_KEY_HOME) {
  7873. fs->caret = 0;
  7874. } else if (k == NGUI_KEY_END) {
  7875. fs->caret = fs->len;
  7876. } else if (k >= 32 && k < 127) {
  7877. if (fs->len < FORM_VALUE_MAX) {
  7878. unsigned int i;
  7879. for (i = fs->len; i > fs->caret; i--)
  7880. fs->value[i] = fs->value[i - 1];
  7881. fs->value[fs->caret++] = (char)k;
  7882. fs->len++;
  7883. form_dirty = 1;
  7884. js_browser_event(form_focus, "input", 1, 0);
  7885. }
  7886. } else {
  7887. return;
  7888. }
  7889. fs->value[fs->len] = '\0';
  7890. layout_valid = 0;
  7891. ngui_invalidate(&ui);
  7892. }
  7893. static void handle_page_click(unsigned int *action)
  7894. {
  7895. int node;
  7896. char url[BR_URL_MAX];
  7897. if (!ui.pressed)
  7898. return;
  7899. if (ui.press_x < page_rect.x ||
  7900. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  7901. ui.press_y < page_rect.y ||
  7902. ui.press_y >= page_rect.y + page_rect.h)
  7903. return;
  7904. node = find_hit(ui.press_x, ui.press_y);
  7905. if (!node)
  7906. return;
  7907. if (form_is_control((unsigned int)node)) {
  7908. form_click((unsigned int)node);
  7909. return;
  7910. }
  7911. form_blur();
  7912. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  7913. return;
  7914. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  7915. sizeof(url)) != 0)
  7916. return;
  7917. s_copy(click_url, url, sizeof(click_url));
  7918. *action |= ACT_NAV;
  7919. }
  7920. void _start(const char *arg)
  7921. {
  7922. struct win_info wi;
  7923. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  7924. u_win_create(960, 640, "Browser", &wi) != 0 &&
  7925. u_win_create(780, 540, "Browser", &wi) != 0) {
  7926. u_puts("browser: no graphics window\n");
  7927. u_exit(1);
  7928. }
  7929. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  7930. url_in.placeholder = "http://...";
  7931. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  7932. ui.theme.accent);
  7933. br_set_viewport(wi.width);
  7934. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  7935. s_copy(cwd, "/", sizeof(cwd));
  7936. heap_clear();
  7937. origin_cache_load();
  7938. css_cache_init();
  7939. script_cache_init();
  7940. page_scroll.offset = 0;
  7941. page_scroll.content_h = 0;
  7942. if (arg && arg[0]) {
  7943. navigate(arg, 1);
  7944. } else {
  7945. load_home(1);
  7946. /* Start ready to type: keep the home page, but leave the address
  7947. * bar empty instead of showing "about:home". */
  7948. ngui_input_set(&url_in, "");
  7949. ngui_set_focus(&ui, ID_URL);
  7950. }
  7951. for (;;) {
  7952. unsigned int action = 0;
  7953. unsigned int now;
  7954. click_url[0] = '\0';
  7955. if (pending_action) {
  7956. action |= pending_action & ACT_WAIT_NAV;
  7957. if (pending_url[0])
  7958. s_copy(click_url, pending_url, sizeof(click_url));
  7959. pending_action = 0;
  7960. pending_url[0] = '\0';
  7961. cancel_fetch = 0;
  7962. } else if (preload_active) {
  7963. if (preload_wait)
  7964. preload_wait = 0;
  7965. else
  7966. preload_step();
  7967. } else if (preload_pending &&
  7968. page_scroll.offset != preload_scroll) {
  7969. preload_scroll = page_scroll.offset;
  7970. preload_pending = 0;
  7971. preload_node = 0;
  7972. preload_active = 1;
  7973. }
  7974. js_browser_tick();
  7975. if (pending_action)
  7976. continue;
  7977. now = u_ticks_ms();
  7978. if (status_until && (int)(now - status_until) >= 0) {
  7979. status_text[0] = '\0';
  7980. status_until = 0;
  7981. status_error = 0;
  7982. ngui_invalidate(&ui);
  7983. }
  7984. if (!ngui_begin(&ui)) {
  7985. /* A queued navigation (e.g. Enter in the URL bar during
  7986. * a slow fetch) must be handled even when this frame
  7987. * needs no redraw. */
  7988. if (!action) {
  7989. fetch_workers_stop_if_unfocused();
  7990. u_sleep_ms(10);
  7991. continue;
  7992. }
  7993. } else {
  7994. draw(&action);
  7995. handle_keys(&action);
  7996. handle_page_click(&action);
  7997. ngui_end(&ui);
  7998. }
  7999. if (action & ACT_NAV) {
  8000. if (click_url[0]) {
  8001. navigate(click_url, 1);
  8002. click_url[0] = '\0';
  8003. } else {
  8004. navigate(url_in.text, 1);
  8005. }
  8006. }
  8007. if (action & ACT_BACK) {
  8008. if (hist_pos > 0) {
  8009. hist_pos--;
  8010. navigate(history[hist_pos], 0);
  8011. }
  8012. }
  8013. if (action & ACT_FORWARD) {
  8014. if (hist_pos + 1 < hist_len) {
  8015. hist_pos++;
  8016. navigate(history[hist_pos], 0);
  8017. }
  8018. }
  8019. if (action & ACT_RELOAD) {
  8020. if (s_eq(page_url, "about:home"))
  8021. load_home(0);
  8022. else
  8023. navigate(page_url, 0);
  8024. }
  8025. if (action & ACT_HOME)
  8026. load_home(1);
  8027. if (action & ACT_CLOSE)
  8028. quit = 1;
  8029. if (quit)
  8030. break;
  8031. if (pending_action)
  8032. continue;
  8033. fetch_workers_stop_if_unfocused();
  8034. u_sleep_ms(10);
  8035. }
  8036. fetch_workers_stop_all();
  8037. u_win_close();
  8038. u_exit(0);
  8039. }