browser.c 221 KB

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