browser.c 199 KB

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