browser.c 160 KB

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