browser.c 172 KB

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