browser.c 203 KB

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