browser.c 201 KB

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