browser.c 367 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799
  1. /* browser: a small HTML/CSS browser built on ngui, the image library and the
  2. * shared uhttp client.
  3. *
  4. * Page scripts run on the vendored QuickJS engine (modern ECMAScript) through
  5. * the DOM layer in js_browser.c; forms render and submit natively. External CSS is loaded over uhttp, and images are
  6. * decoded with img.c and drawn inline. Page-scoped buffers (page body,
  7. * rules and image bitmaps) come from the ring-3 libc heap; each image gets an
  8. * exact-size decode arena that is freed as soon as the scaled bitmap exists.
  9. * The DOM and the image/CSS I/O scratch use fixed static arenas.
  10. */
  11. #include <stdlib.h>
  12. #include <stdio.h>
  13. #include <string.h>
  14. #include <math.h>
  15. #include <ucmd_heap.h>
  16. #include "ucmd_lib.h"
  17. #include "ngui.h"
  18. #include "browser_html.h"
  19. #include "js_browser.h"
  20. #include "uhttp.h"
  21. #include "uhttp_cookie.h"
  22. #include "img.h"
  23. #include "inflate.h"
  24. #include "ufont.h"
  25. #include "svg_raster.h"
  26. static void svg_cache_clear(void);
  27. static unsigned char *decode_arena; /* see decode_arena_get() */
  28. static unsigned int decode_arena_size;
  29. /* Start wide enough for the desktop nav; smaller screens fall back to
  30. * 960x640 and 780x540, which still fit a 1024x768 panel. */
  31. #define BR_W 1100
  32. #define BR_H 700
  33. #define BR_TOOLBAR_H 30
  34. #define BR_STATUS_H 18
  35. #define BR_PAGE_MAX (2u * 1024u * 1024u)
  36. #define BR_IMG_FILE_MAX (1024u * 1024u)
  37. #define BR_IMG_PIX_MAX (8u * 1024u * 1024u)
  38. #define BR_MAX_IMAGES 256
  39. /* Decoded display bitmaps share the page heap: cap their total pixels
  40. * (RGB565 plus an optional alpha plane) instead of their count. */
  41. #define BR_IMG_PIXEL_BUDGET (4u * 1024u * 1024u)
  42. #define BR_IMG_DISP_BUDGET (6u * 1024u * 1024u)
  43. #define BR_IMG_ARENA_MAX (24u * 1024u * 1024u)
  44. #define BR_IMG_LAYOUT_W 1000
  45. /* Decode completed image jobs for at most this long per main-loop pass, then
  46. * return to input/painting. One image per pass plus a 10 ms sleep made a
  47. * page of small icons trickle in. */
  48. #define BR_IMG_DECODE_BUDGET_MS 40u
  49. /* Coalesce image-driven repaints: each decode invalidates the page, and a
  50. * full repaint per image made loading superlinear on image-heavy pages. */
  51. #define BR_IMG_REPAINT_MS 100u
  52. #define BR_IMG_STAT_LOG 3584
  53. /* An image job may hold a fetch helper this long. The page/script
  54. * deadline (UHTTP_TOTAL_TIMEOUT_MS) is minutes; one unreachable image host
  55. * must not starve the other images of all four helpers that long. */
  56. #define BR_IMG_JOB_TIMEOUT_MS 30000u
  57. #define BR_CSS_MAX (832u * 1024u)
  58. #define BR_CSS_COMP_MAX (192u * 1024u)
  59. /* Scripts and ES modules: Vite bundles reach ~1.7 MB (the Cloudron
  60. * dashboard's main chunk); the helper's FETCH_MAX is the same 2 MB. */
  61. #define BR_SCRIPT_MAX (2u * 1024u * 1024u)
  62. #define FETCH_ABORT (-2)
  63. /* Session cache for remote stylesheets (per launch; cleared at startup). */
  64. #define CSS_CACHE_MAX 16
  65. #define CSS_CACHE_FILE_MAX (256u * 1024u)
  66. #define CSS_CACHE_PREFIX "bcss-"
  67. #define SCRIPT_CACHE_MAX 24
  68. #define SCRIPT_CACHE_FILE_MAX BR_SCRIPT_MAX
  69. #define SCRIPT_CACHE_PREFIX "bjs-"
  70. /* Web fonts cached for the boot; /share holds 64 entries / 16 MB in all. */
  71. #define FONT_CACHE_MAX 8
  72. #define FONT_CACHE_PREFIX "bfont-"
  73. /* The ufont arena (built-in faces, @font-face files and glyph masks); the
  74. * 512 KB default holds the built-in set but not a page's web fonts. */
  75. #define BR_FONT_ARENA (3u * 1024u * 1024u)
  76. #define BR_MAX_SHEETS 6
  77. #define BR_HISTORY 16
  78. #define BR_URL_MAX 4096 /* = UHTTP_PATH_MAX: google.com's JS URL is ~3.7 KB */
  79. #define BR_STATUS_MAX 200
  80. #define BR_IMG_RGB565(r, g, b) \
  81. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  82. #define BR_GRAY 0x8410
  83. enum {
  84. ID_URL = 1,
  85. ID_GO,
  86. ID_BACK,
  87. ID_FORWARD,
  88. ID_RELOAD,
  89. ID_HOME
  90. };
  91. #define ACT_NAV (1u << 0)
  92. #define ACT_BACK (1u << 1)
  93. #define ACT_FORWARD (1u << 2)
  94. #define ACT_RELOAD (1u << 3)
  95. #define ACT_HOME (1u << 4)
  96. #define ACT_CLOSE (1u << 5)
  97. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  98. ACT_HOME | ACT_CLOSE)
  99. struct br_image {
  100. int state; /* 0 empty, 1 ready */
  101. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  102. int native_w, native_h;
  103. unsigned int url_hash; /* <img> source, 0 = not shareable */
  104. char err[32];
  105. /* Display-size cache: the box an image is actually painted in. The
  106. * source bitmap above is deliberately capped at BR_IMG_LAYOUT_W so a
  107. * window resize can re-scale it; the cached copy is exactly dw x dh,
  108. * so every repaint is a 1:1 blit instead of a per-pixel resample. */
  109. struct img_image disp;
  110. unsigned int disp_pixels;
  111. unsigned int disp_last;
  112. };
  113. static struct ngui ui;
  114. static struct ngui_input url_in;
  115. static struct ngui_scroll page_scroll;
  116. static struct br_doc doc;
  117. static struct br_image images[BR_MAX_IMAGES];
  118. static int image_count;
  119. static unsigned int image_pixels;
  120. static unsigned int image_disp_pixels;
  121. static unsigned int image_disp_clock;
  122. /* Per-image pipeline timing for the status line and /share/IMGSTAT. The
  123. * numbers are what decides whether the next work is network, decode or
  124. * display; keep them cheap (one tick read per phase). */
  125. static unsigned int img_stat_start;
  126. static unsigned int img_stat_wall;
  127. static unsigned int img_stat_net;
  128. static unsigned int img_stat_open;
  129. static unsigned int img_stat_first;
  130. static unsigned int img_stat_io;
  131. static unsigned int img_stat_dec;
  132. static unsigned int img_stat_scale;
  133. static unsigned int img_stat_paint;
  134. static unsigned int img_stat_reflow;
  135. static unsigned int img_stat_bytes;
  136. static int img_stat_n;
  137. static unsigned int img_last_dec_ms;
  138. static unsigned int img_last_scale_ms;
  139. static char img_stat_log[BR_IMG_STAT_LOG];
  140. static unsigned int img_stat_log_len;
  141. static unsigned int img_repaint_ms;
  142. static int img_repaint_pending;
  143. /* Painted border boxes, in page/screen coordinates (layout starts at
  144. * page_rect.y - scroll). getBoundingClientRect() subtracts page_rect. */
  145. struct br_layout_box {
  146. int x, y;
  147. int w, h;
  148. unsigned char valid;
  149. };
  150. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  151. /* Images are loaded one per main-loop iteration so the parsed page stays
  152. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  153. static int preload_active;
  154. static int preload_max_jobs;
  155. static int preload_pending;
  156. static int preload_wait;
  157. static unsigned int preload_node;
  158. static int preload_loaded;
  159. static int preload_scroll;
  160. static int preload_rescan;
  161. static char post_status_text[BR_STATUS_MAX];
  162. static int post_status_error;
  163. static unsigned int post_status_ttl;
  164. /* Content-relative position/height of each <img>, recorded by the measure
  165. * pass so image loading can be deferred until it is near the viewport. */
  166. static unsigned short img_top[BR_MAX_NODES];
  167. static unsigned short img_h[BR_MAX_NODES];
  168. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  169. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  170. * body. Decode arenas are allocated per image instead of living here. */
  171. static unsigned char *image_io_buf;
  172. static struct ufont_face *font_faces[BR_MAX_FACES];
  173. /* [family id - 1][bold * 2 + italic] -> 1-based face id, 0 = built-in. */
  174. static unsigned char font_pick[BR_MAX_FACES][4];
  175. #define image_file_buf (image_io_buf)
  176. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  177. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  178. static struct inflate image_inflate_ws;
  179. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  180. #error "CSS scratch must fit in image_io_buf"
  181. #endif
  182. static char page_url[BR_URL_MAX];
  183. static char page_title[BR_TITLE_MAX];
  184. static char cwd[64];
  185. static int page_is_local;
  186. static int page_loading;
  187. static char status_text[BR_STATUS_MAX];
  188. static unsigned int status_until;
  189. static int status_error;
  190. static char history[BR_HISTORY][BR_URL_MAX];
  191. static int hist_len, hist_pos;
  192. static char click_url[BR_URL_MAX];
  193. static char pending_url[BR_URL_MAX];
  194. #define BR_POST_MAX 4096
  195. static char pending_post[BR_POST_MAX];
  196. static unsigned int pending_post_len;
  197. /* The pending navigation is a POST even when its body is empty (a form
  198. * without fields, e.g. the OIDC consent auto-submit). */
  199. static int pending_post_is;
  200. /* window "resize" bookkeeping: the page width the last event was for. */
  201. static int resize_sent_w = -1;
  202. static int resize_pending;
  203. static unsigned int pending_action;
  204. static int cancel_fetch;
  205. static int quit;
  206. static struct ngui_rect page_rect;
  207. static unsigned short *page_backbuf;
  208. static int pagebuf_w, pagebuf_h;
  209. static int page_cache_valid;
  210. static int page_cache_scroll;
  211. static unsigned int page_cache_nnode;
  212. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  213. static int layout_valid, layout_left, layout_right;
  214. /* Height of the page viewport: what html/body height:100% resolves to. */
  215. static int layout_view_h;
  216. static unsigned int layout_nnode;
  217. static int layout_content_h;
  218. /* layout output */
  219. struct lay_run {
  220. unsigned int off;
  221. unsigned short len;
  222. unsigned short gap;
  223. unsigned short color;
  224. unsigned short href;
  225. char lit[28];
  226. short img;
  227. signed short dy; /* inline image vertical offset */
  228. unsigned short iw, ih;
  229. unsigned short w;
  230. unsigned char font_px, bold, italic, mono, underline, strike;
  231. unsigned char overline, font_face;
  232. unsigned char transform_scale;
  233. unsigned char origin_x_kind, origin_y_kind;
  234. signed short scale_x, scale_y, rotate_x100;
  235. signed short origin_x, origin_y;
  236. unsigned char has_lit;
  237. unsigned int form; /* node + 1, 0 = not a control */
  238. unsigned char form_kind;
  239. unsigned char form_disabled;
  240. /* RUN_PBOX: background colour, background image and its placement
  241. * inside the iw x ih box (relative offsets, drawn size). */
  242. unsigned char pb_has_bg;
  243. unsigned short pb_bg;
  244. short pb_img;
  245. short pb_x, pb_y, pb_w, pb_h;
  246. };
  247. struct lay {
  248. int draw;
  249. struct ngui *ui;
  250. int left, right;
  251. int y;
  252. int line_x, line_y, line_h;
  253. int line_left, line_right;
  254. int parent_top;
  255. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  256. int cb_h; /* definite content height of the containing block for
  257. * percentage heights; 0 = indefinite (auto) */
  258. int run_x;
  259. int align;
  260. int depth;
  261. int space_pending;
  262. unsigned char float_active;
  263. int float_left, float_right, float_bottom;
  264. struct lay_run runs[96];
  265. int nruns;
  266. };
  267. struct hit {
  268. int x, y, w, h;
  269. unsigned short node;
  270. };
  271. /* Live form state; the DOM attributes stay the initial/default value. */
  272. #define FORM_MAX 64
  273. #define FORM_VALUE_MAX 63
  274. enum {
  275. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  276. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  277. };
  278. struct form_state {
  279. unsigned int node;
  280. char value[FORM_VALUE_MAX + 1];
  281. unsigned char len, caret, checked, selected, used;
  282. };
  283. static struct form_state form_states[FORM_MAX];
  284. static unsigned int form_focus;
  285. static unsigned int form_dirty;
  286. static int form_descendant(unsigned int node, unsigned int form);
  287. static int form_submit_form(unsigned int node, int fire_event);
  288. static int link_fragment_nav(unsigned int node);
  289. static void history_push(const char *url);
  290. static void form_reset_event(unsigned int form);
  291. static unsigned int s_len(const char *s);
  292. static int s_eq(const char *a, const char *b);
  293. static void form_key(int k);
  294. static void form_click(unsigned int node);
  295. static void style_for_node(unsigned int node, struct br_style *out);
  296. static int form_author_styled(const struct br_style *st);
  297. static int css_radius(const struct br_style *st, int corner, int w, int h);
  298. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  299. const struct br_style *st, int focused);
  300. static int form_disabled(unsigned int node)
  301. {
  302. struct br_node *n = &doc.nodes[node];
  303. if (n->attr_flags & BR_ATTR_DISABLED)
  304. return 1;
  305. return br_find_attr(&doc, node, "disabled") != 0;
  306. }
  307. static int form_kind_of(unsigned int node)
  308. {
  309. const char *type = br_type(&doc, node);
  310. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  311. return FORM_TEXTAREA;
  312. if (doc.nodes[node].tag == BR_TAG_SELECT)
  313. return FORM_SELECT;
  314. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  315. if (s_eq(type, "reset"))
  316. return FORM_RESET;
  317. if (s_eq(type, "button"))
  318. return FORM_BUTTON;
  319. return FORM_SUBMIT;
  320. }
  321. if (s_eq(type, "password"))
  322. return FORM_PASSWORD;
  323. if (s_eq(type, "checkbox"))
  324. return FORM_CHECKBOX;
  325. if (s_eq(type, "radio"))
  326. return FORM_RADIO;
  327. if (s_eq(type, "submit"))
  328. return FORM_SUBMIT;
  329. if (s_eq(type, "reset"))
  330. return FORM_RESET;
  331. if (s_eq(type, "button"))
  332. return FORM_BUTTON;
  333. return FORM_TEXT;
  334. }
  335. static unsigned int form_option_count(unsigned int node)
  336. {
  337. unsigned int c, n = 0;
  338. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  339. if (doc.nodes[c].type == BR_NODE_ELEM &&
  340. doc.nodes[c].tag == BR_TAG_OPTION)
  341. n++;
  342. return n;
  343. }
  344. static unsigned int form_option_selected(unsigned int node)
  345. {
  346. unsigned int c, i = 0;
  347. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  348. if (doc.nodes[c].type != BR_NODE_ELEM ||
  349. doc.nodes[c].tag != BR_TAG_OPTION)
  350. continue;
  351. if (br_find_attr(&doc, c, "selected"))
  352. return i;
  353. i++;
  354. }
  355. return 0;
  356. }
  357. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  358. char *out, unsigned int cap)
  359. {
  360. unsigned int c, i = 0;
  361. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  362. if (doc.nodes[c].type != BR_NODE_ELEM ||
  363. doc.nodes[c].tag != BR_TAG_OPTION)
  364. continue;
  365. if (i == idx)
  366. return br_text_content(&doc, c, out, cap);
  367. i++;
  368. }
  369. return 0;
  370. }
  371. static int form_is_control(unsigned int node);
  372. static struct form_state *form_get(unsigned int node, int create)
  373. {
  374. struct form_state *slot = 0;
  375. unsigned int i;
  376. for (i = 0; i < FORM_MAX; i++) {
  377. if (form_states[i].used) {
  378. if (form_states[i].node == node)
  379. return &form_states[i];
  380. } else if (!slot) {
  381. slot = &form_states[i];
  382. }
  383. }
  384. if (create && !slot) {
  385. /* Full: a client-side router (Docusaurus' React Router)
  386. * replaces page content without a navigation, so slots of
  387. * controls that left the document pile up until no new
  388. * control can be drawn or focused.
  389. * Reuse those first, then slots of nodes that are no longer
  390. * controls. */
  391. for (i = 0; i < FORM_MAX && !slot; i++)
  392. if (form_states[i].node != form_focus &&
  393. br_node_detached(&doc, form_states[i].node))
  394. slot = &form_states[i];
  395. for (i = 0; i < FORM_MAX && !slot; i++)
  396. if (form_states[i].node != form_focus &&
  397. !form_is_control(form_states[i].node))
  398. slot = &form_states[i];
  399. }
  400. if (!create || !slot)
  401. return 0;
  402. slot->node = node;
  403. slot->len = 0;
  404. slot->caret = 0;
  405. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  406. slot->selected = form_option_selected(node);
  407. slot->used = 1;
  408. {
  409. unsigned int n = 0;
  410. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  411. n = br_text_content(&doc, node, slot->value,
  412. FORM_VALUE_MAX + 1);
  413. } else {
  414. const char *v = br_value(&doc, node);
  415. if (v) {
  416. n = s_len(v);
  417. if (n > FORM_VALUE_MAX)
  418. n = FORM_VALUE_MAX;
  419. for (unsigned int j = 0; j < n; j++)
  420. slot->value[j] = v[j];
  421. }
  422. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  423. n = br_text_content(&doc, node, slot->value,
  424. FORM_VALUE_MAX + 1);
  425. }
  426. if (n > FORM_VALUE_MAX)
  427. n = FORM_VALUE_MAX;
  428. slot->value[n] = '\0';
  429. slot->len = (unsigned char)n;
  430. slot->caret = (unsigned char)n;
  431. }
  432. return slot;
  433. }
  434. static void form_reset_state(void)
  435. {
  436. unsigned int i;
  437. for (i = 0; i < FORM_MAX; i++)
  438. form_states[i].used = 0;
  439. form_focus = 0;
  440. }
  441. /* A <button> with element content (an icon <svg>/<img>, a <span> label)
  442. * is laid out like a normal element so that content shows; only a text or
  443. * empty button is drawn as a native control. Clicks still reach it
  444. * through the box hit test. */
  445. static int button_has_elements(unsigned int node)
  446. {
  447. unsigned int c;
  448. if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
  449. return 0;
  450. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  451. if (doc.nodes[c].type == BR_NODE_ELEM)
  452. return 1;
  453. /* An empty button whose icon is a ::before/::after box (Docusaurus'
  454. * sidebar caret) is laid out as an element so the box is drawn. */
  455. if (!doc.nodes[node].first && doc.npe_rules) {
  456. struct br_style st, ps;
  457. char buf[8];
  458. int pe;
  459. style_for_node(node, &st);
  460. for (pe = 1; pe <= 2; pe++)
  461. if (!br_pseudo(&doc, node, pe, &st, &ps, buf,
  462. sizeof(buf)) &&
  463. ps.content == BR_CONTENT_EMPTY &&
  464. ps.display != BR_DISPLAY_NONE)
  465. return 1;
  466. }
  467. return 0;
  468. }
  469. static int form_is_control(unsigned int node)
  470. {
  471. unsigned int tag;
  472. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  473. return 0;
  474. tag = doc.nodes[node].tag;
  475. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  476. tag == BR_TAG_SELECT ||
  477. (tag == BR_TAG_BUTTON && !button_has_elements(node));
  478. }
  479. #define HIT_MAX 96
  480. static struct hit hits[HIT_MAX];
  481. static int nhits;
  482. static unsigned short block_h[BR_MAX_NODES];
  483. /* Border-box height a flex container stretches an item to (align-items:
  484. * stretch in a row with a taller line or a definite height), 0 = none.
  485. * Written by the measure pass, read by both. */
  486. static unsigned short flex_stretch_h[BR_MAX_NODES];
  487. /* Measure-pass top of each block, in the same document coordinates as
  488. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  489. * paint, so it cannot drive the lazy background loader). */
  490. static unsigned short block_top[BR_MAX_NODES];
  491. static char li_marker[BR_MAX_NODES][12];
  492. /* one connection object; the browser fetches one resource at a time */
  493. /* ---- tiny strings ---- */
  494. static unsigned int s_len(const char *s)
  495. {
  496. unsigned int n = 0;
  497. while (s && s[n])
  498. n++;
  499. return n;
  500. }
  501. static void s_copy(char *d, const char *s, unsigned int cap)
  502. {
  503. unsigned int i = 0;
  504. if (!cap)
  505. return;
  506. while (s && s[i] && i + 1 < cap) {
  507. d[i] = s[i];
  508. i++;
  509. }
  510. d[i] = '\0';
  511. }
  512. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  513. {
  514. while (s && *s && *n + 1 < cap)
  515. d[(*n)++] = *s++;
  516. d[*n] = '\0';
  517. }
  518. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  519. unsigned int cap)
  520. {
  521. char tmp[12];
  522. unsigned int i = 0, j;
  523. do {
  524. tmp[i++] = (char)('0' + v % 10);
  525. v /= 10;
  526. } while (v && i < sizeof(tmp));
  527. for (j = 0; j < i && *n + 1 < cap; j++)
  528. d[(*n)++] = tmp[i - 1 - j];
  529. d[*n] = '\0';
  530. }
  531. static int s_eq(const char *a, const char *b)
  532. {
  533. while (*a && *b) {
  534. if (*a != *b)
  535. return 0;
  536. a++;
  537. b++;
  538. }
  539. return *a == *b;
  540. }
  541. static int starts_with(const char *s, const char *p)
  542. {
  543. unsigned int i = 0;
  544. while (p[i]) {
  545. if (s[i] != p[i])
  546. return 0;
  547. i++;
  548. }
  549. return 1;
  550. }
  551. static int contains_ci(const char *s, const char *p)
  552. {
  553. unsigned int i, j;
  554. for (i = 0; s[i]; i++) {
  555. for (j = 0; p[j]; j++) {
  556. char a = s[i + j];
  557. if (a >= 'A' && a <= 'Z')
  558. a = (char)(a - 'A' + 'a');
  559. if (a != p[j])
  560. break;
  561. }
  562. if (!p[j])
  563. return 1;
  564. }
  565. return 0;
  566. }
  567. static char *trim(char *s)
  568. {
  569. unsigned int n;
  570. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  571. s++;
  572. n = s_len(s);
  573. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  574. s[n - 1] == '\r' || s[n - 1] == '\n'))
  575. s[--n] = '\0';
  576. return s;
  577. }
  578. /* ---- per-process heap ---- */
  579. static int heap_start(void)
  580. {
  581. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  582. if (!image_io_buf)
  583. return -1;
  584. page_backbuf = (unsigned short *)malloc(
  585. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  586. pagebuf_w = page_backbuf ? ui.w : 0;
  587. pagebuf_h = page_backbuf ? ui.h : 0;
  588. page_cache_valid = 0;
  589. return 0;
  590. }
  591. static void heap_clear(void)
  592. {
  593. memset(font_faces, 0, sizeof(font_faces));
  594. memset(font_pick, 0, sizeof(font_pick));
  595. ngui_font_detach(&ui);
  596. svg_cache_clear();
  597. decode_arena = 0; /* lives in the page heap too */
  598. decode_arena_size = 0;
  599. heap_reset();
  600. /* The document arenas live in that heap; drop the stale pointers so
  601. * the next br_parse_plain() allocates fresh ones. */
  602. doc.nodes = 0;
  603. doc.text = 0;
  604. doc.attrs = 0;
  605. image_io_buf = 0;
  606. page_backbuf = 0;
  607. pagebuf_w = pagebuf_h = 0;
  608. page_cache_valid = 0;
  609. }
  610. static void browser_rules_alloc(void)
  611. {
  612. struct br_rule *rules;
  613. rules = (struct br_rule *)malloc(
  614. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  615. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  616. }
  617. /* ---- status ---- */
  618. static void set_status(const char *s, int err, unsigned int ttl_ms)
  619. {
  620. s_copy(status_text, s, sizeof(status_text));
  621. status_error = err;
  622. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  623. ngui_invalidate(&ui);
  624. }
  625. /* Update the status text without forcing a frame; the throttled image
  626. * repaint picks it up. Starting one helper per image used to invalidate the
  627. * whole page before every decode. */
  628. static void set_status_quiet(const char *s)
  629. {
  630. s_copy(status_text, s, sizeof(status_text));
  631. status_error = 0;
  632. status_until = 0;
  633. }
  634. /* ---- JavaScript ---- */
  635. static int resolve_link(const char *base, const char *href, char *out,
  636. unsigned int cap);
  637. static char js_last_status[BR_STATUS_MAX];
  638. static int js_last_error;
  639. static void js_host_status(const char *msg, int error)
  640. {
  641. s_copy(js_last_status, msg, sizeof(js_last_status));
  642. js_last_error = error;
  643. set_status(msg, error, 6000);
  644. }
  645. static void js_host_report(const char *msg)
  646. {
  647. u_puts("[js] ");
  648. u_puts(msg);
  649. u_putc('\n');
  650. s_copy(js_last_status, msg, sizeof(js_last_status));
  651. js_last_error = 1;
  652. set_status(msg, 1, 8000);
  653. }
  654. static void js_host_navigate(const char *url)
  655. {
  656. char resolved[BR_URL_MAX];
  657. if (!url || !url[0])
  658. return;
  659. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  660. return;
  661. s_copy(pending_url, resolved, sizeof(pending_url));
  662. pending_action |= ACT_NAV;
  663. cancel_fetch = 1;
  664. }
  665. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  666. * back/forward between fragments): the page URL, address bar and history
  667. * follow, nothing is reloaded. `push` adds a history entry. */
  668. static int page_set_fragment(const char *url, int push)
  669. {
  670. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  671. return -1;
  672. s_copy(page_url, url, sizeof(page_url));
  673. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  674. url_in.len = s_len(url_in.text);
  675. url_in.cursor = url_in.len;
  676. url_in.scroll = 0;
  677. if (push)
  678. history_push(page_url);
  679. ngui_invalidate(&ui);
  680. return 0;
  681. }
  682. static int js_host_set_hash(const char *url)
  683. {
  684. return page_set_fragment(url, 1);
  685. }
  686. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  687. * the page, so a hash router can react). */
  688. static int same_doc_fragment(const char *url)
  689. {
  690. unsigned int a = 0, b = 0;
  691. if (!js_browser_active() || !url)
  692. return 0;
  693. while (url[a] && url[a] != '#')
  694. a++;
  695. while (page_url[b] && page_url[b] != '#')
  696. b++;
  697. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  698. !s_eq(url, page_url);
  699. }
  700. static void js_host_changed(void)
  701. {
  702. /* Class/style/attribute mutations change computed styles, not just the
  703. * text: drop the per-node style cache before the next layout. */
  704. br_reset_styles(&doc);
  705. layout_valid = 0;
  706. /* Script-built content (Angular's ng-repeat cards) brings new images
  707. * and inline background styles: rescan once the main loop is idle. */
  708. preload_rescan = 1;
  709. ngui_invalidate(&ui);
  710. }
  711. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  712. {
  713. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  714. return 0;
  715. *x = layout_boxes[node].x - page_rect.x;
  716. *y = layout_boxes[node].y - page_rect.y;
  717. *w = layout_boxes[node].w;
  718. *h = layout_boxes[node].h;
  719. return 1;
  720. }
  721. static void form_copy_out(const char *s, char *buf, int cap)
  722. {
  723. int i = 0;
  724. if (!buf || cap <= 0)
  725. return;
  726. while (s && s[i] && i + 1 < cap) {
  727. buf[i] = s[i];
  728. i++;
  729. }
  730. buf[i] = '\0';
  731. }
  732. static int js_host_form_value(unsigned int node, char *buf, int cap)
  733. {
  734. struct form_state *fs;
  735. int kind;
  736. if (!form_is_control(node))
  737. return 0;
  738. kind = form_kind_of(node);
  739. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  740. return 0;
  741. if (kind == FORM_SELECT) {
  742. char opt[64] = "";
  743. unsigned int c, i = 0;
  744. fs = form_get(node, 1);
  745. if (!fs)
  746. return 0;
  747. form_option_text(node, fs->selected, opt, sizeof(opt));
  748. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  749. if (doc.nodes[c].type != BR_NODE_ELEM ||
  750. doc.nodes[c].tag != BR_TAG_OPTION)
  751. continue;
  752. if (i == fs->selected) {
  753. const char *v = br_value(&doc, c);
  754. if (v && v[0])
  755. form_copy_out(v, buf, cap);
  756. else
  757. form_copy_out(opt, buf, cap);
  758. return 1;
  759. }
  760. i++;
  761. }
  762. form_copy_out(opt, buf, cap);
  763. return 1;
  764. }
  765. fs = form_get(node, 1);
  766. if (!fs)
  767. return 0;
  768. form_copy_out(fs->value, buf, cap);
  769. return 1;
  770. }
  771. static int js_host_form_checked(unsigned int node)
  772. {
  773. struct form_state *fs;
  774. int kind;
  775. if (!form_is_control(node))
  776. return -1;
  777. kind = form_kind_of(node);
  778. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  779. return -1;
  780. fs = form_get(node, 1);
  781. return fs ? fs->checked : 0;
  782. }
  783. static int js_host_form_selected(unsigned int node)
  784. {
  785. struct form_state *fs;
  786. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  787. return -1;
  788. fs = form_get(node, 1);
  789. return fs ? fs->selected : 0;
  790. }
  791. static int js_host_form_set_value(unsigned int node, const char *value)
  792. {
  793. struct form_state *fs;
  794. unsigned int n;
  795. if (!form_is_control(node))
  796. return 0;
  797. fs = form_get(node, 1);
  798. if (!fs)
  799. return 0;
  800. n = s_len(value ? value : "");
  801. if (n > FORM_VALUE_MAX)
  802. n = FORM_VALUE_MAX;
  803. for (unsigned int i = 0; i < n; i++)
  804. fs->value[i] = value[i];
  805. fs->value[n] = '\0';
  806. fs->len = (unsigned char)n;
  807. fs->caret = (unsigned char)n;
  808. layout_valid = 0;
  809. ngui_invalidate(&ui);
  810. return 1;
  811. }
  812. static int js_host_form_set_checked(unsigned int node, int checked)
  813. {
  814. struct form_state *fs;
  815. int kind;
  816. if (!form_is_control(node))
  817. return 0;
  818. kind = form_kind_of(node);
  819. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  820. return 0;
  821. fs = form_get(node, 1);
  822. if (!fs)
  823. return 0;
  824. fs->checked = (unsigned char)(checked != 0);
  825. layout_valid = 0;
  826. ngui_invalidate(&ui);
  827. return 1;
  828. }
  829. static int js_host_form_set_selected(unsigned int node, int index)
  830. {
  831. struct form_state *fs;
  832. unsigned int n;
  833. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  834. return 0;
  835. fs = form_get(node, 1);
  836. if (!fs)
  837. return 0;
  838. n = form_option_count(node);
  839. if (index < 0)
  840. index = 0;
  841. if (n && (unsigned int)index >= n)
  842. index = (int)n - 1;
  843. fs->selected = (unsigned char)index;
  844. layout_valid = 0;
  845. ngui_invalidate(&ui);
  846. return 1;
  847. }
  848. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  849. {
  850. unsigned int i;
  851. int n = 0;
  852. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  853. doc.nodes[form].tag != BR_TAG_FORM)
  854. return 0;
  855. for (i = 0; i < doc.nnode && n < cap; i++) {
  856. struct br_node *nd = &doc.nodes[i];
  857. if (i == form || nd->type != BR_NODE_ELEM)
  858. continue;
  859. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  860. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  861. continue;
  862. if (!form_descendant(i, form))
  863. continue;
  864. out[n++] = i;
  865. }
  866. return n;
  867. }
  868. static int js_host_form_submit(unsigned int form)
  869. {
  870. form_submit_form(form, 0);
  871. return 1;
  872. }
  873. static int js_host_form_reset(unsigned int form)
  874. {
  875. form_reset_event(form);
  876. return 1;
  877. }
  878. static void css_computed_name(const char *p, char *out, int cap)
  879. {
  880. int n = 0;
  881. for (; p && *p && n + 2 < cap; p++) {
  882. char c = *p;
  883. if (c >= 'A' && c <= 'Z') {
  884. out[n++] = '-';
  885. c = (char)(c - 'A' + 'a');
  886. } else if (c == '_') {
  887. c = '-';
  888. } else if (c >= 'a' && c <= 'z') {
  889. /* keep */
  890. }
  891. out[n++] = c;
  892. }
  893. out[n] = '\0';
  894. if (!strcmp(out, "css-float"))
  895. strcpy(out, "float");
  896. }
  897. static void css_rgb(unsigned short c, char *buf, int cap)
  898. {
  899. int r = ((c >> 11) & 31) * 255 / 31;
  900. int g = ((c >> 5) & 63) * 255 / 63;
  901. int b = (c & 31) * 255 / 31;
  902. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  903. }
  904. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  905. int font_px)
  906. {
  907. if (unit == 4) {
  908. snprintf(buf, cap, "auto");
  909. } else if (unit == 0) {
  910. snprintf(buf, cap, "%dpx", raw);
  911. } else if (unit == 1) {
  912. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  913. } else if (unit == 2) {
  914. /* Chrome's getComputedStyle() reports used pixel values. */
  915. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  916. } else if (unit == 3) {
  917. snprintf(buf, cap, "%dpx",
  918. (int)br_root_font_px() * raw / 100);
  919. } else {
  920. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  921. raw / 100, raw % 100, px);
  922. }
  923. }
  924. static int js_host_computed(unsigned int node, const char *property,
  925. char *buf, int cap)
  926. {
  927. struct br_style st;
  928. char name[40];
  929. /* Node 0 is a real element when the page starts with <html>. */
  930. if (!buf || cap <= 0 || node >= doc.nnode ||
  931. (node == 0 && doc.nodes[0].type != BR_NODE_ELEM))
  932. return 0;
  933. buf[0] = '\0';
  934. css_computed_name(property, name, sizeof(name));
  935. style_for_node(node, &st);
  936. if (!strcmp(name, "display")) {
  937. const char *v = "inline";
  938. if (st.display == BR_DISPLAY_BLOCK)
  939. v = "block";
  940. else if (st.display == BR_DISPLAY_NONE)
  941. v = "none";
  942. else if (st.display == BR_DISPLAY_FLEX)
  943. v = "flex";
  944. else if (st.display == BR_DISPLAY_GRID)
  945. v = "grid";
  946. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  947. v = "inline-block";
  948. snprintf(buf, cap, "%s", v);
  949. } else if (!strcmp(name, "position")) {
  950. static const char *pos[] = {
  951. "static", "absolute", "fixed", "relative", "sticky"
  952. };
  953. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  954. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  955. int is_w = name[0] == 'w';
  956. int kind = is_w ? st.width_kind : st.height_kind;
  957. int val = is_w ? st.width : st.height;
  958. if (kind == 3) {
  959. if (is_w)
  960. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  961. st.width_calc_pct / 100,
  962. st.width_calc_pct % 100,
  963. st.width_calc_px);
  964. else
  965. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  966. st.height_calc_pct / 100,
  967. st.height_calc_pct % 100,
  968. st.height_calc_px);
  969. } else if (kind == 1) {
  970. snprintf(buf, cap, "%dpx", val);
  971. } else if (kind == 2) {
  972. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  973. } else {
  974. snprintf(buf, cap, "auto");
  975. }
  976. } else if (!strcmp(name, "color") ||
  977. !strcmp(name, "background-color")) {
  978. if (!strcmp(name, "background-color") && !st.has_bg)
  979. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  980. else
  981. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  982. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  983. int is_fill = name[0] == 'f';
  984. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  985. if (mode == BR_PAINT_COLOR)
  986. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  987. else if (mode == BR_PAINT_CURRENT)
  988. css_rgb(st.color, buf, cap);
  989. else if (mode == BR_PAINT_UNSET && is_fill)
  990. snprintf(buf, cap, "rgb(0, 0, 0)");
  991. else if (mode == BR_PAINT_URL)
  992. snprintf(buf, cap, "url()");
  993. else
  994. snprintf(buf, cap, "none");
  995. } else if (!strcmp(name, "font-size")) {
  996. snprintf(buf, cap, "%dpx", st.font_px);
  997. } else if (!strcmp(name, "font-weight")) {
  998. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  999. } else if (!strcmp(name, "font-style")) {
  1000. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  1001. } else if (!strcmp(name, "font-family")) {
  1002. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  1003. br_font_face_family(st.font_face)[0])
  1004. snprintf(buf, cap, "%s",
  1005. br_font_face_family(st.font_face));
  1006. else
  1007. snprintf(buf, cap, "%s",
  1008. st.mono ? "monospace" : "sans-serif");
  1009. } else if (!strcmp(name, "text-align")) {
  1010. static const char *al[] = { "left", "center", "right", "justify" };
  1011. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  1012. } else if (!strcmp(name, "float")) {
  1013. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  1014. st.float_left == 2 ? "right" : "none");
  1015. } else if (!strcmp(name, "clear")) {
  1016. static const char *cl[] = { "none", "left", "right", "both" };
  1017. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  1018. } else if (!strcmp(name, "opacity")) {
  1019. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  1020. } else if (!strcmp(name, "visibility")) {
  1021. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  1022. } else if (!strcmp(name, "overflow")) {
  1023. snprintf(buf, cap, "%s",
  1024. st.overflow_hidden ? "hidden" : "visible");
  1025. } else if (!strcmp(name, "white-space")) {
  1026. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  1027. } else if (!strcmp(name, "text-transform")) {
  1028. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  1029. } else if (!strcmp(name, "box-sizing")) {
  1030. snprintf(buf, cap, "%s",
  1031. st.box_sizing ? "border-box" : "content-box");
  1032. } else if (!strcmp(name, "line-height")) {
  1033. if (st.line_h_px)
  1034. snprintf(buf, cap, "%dpx", st.line_h_px);
  1035. else if (st.line_h_pct)
  1036. snprintf(buf, cap, "%d%%", st.line_h_pct);
  1037. else
  1038. snprintf(buf, cap, "normal");
  1039. } else if (!strcmp(name, "z-index")) {
  1040. if (st.z_set)
  1041. snprintf(buf, cap, "%d", st.z_index);
  1042. else
  1043. snprintf(buf, cap, "auto");
  1044. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  1045. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  1046. int set = name[0] == 't' ? st.top_set :
  1047. name[0] == 'l' ? st.left_set :
  1048. name[0] == 'r' ? st.right_set : st.bottom_set;
  1049. int v = name[0] == 't' ? st.top :
  1050. name[0] == 'l' ? st.left :
  1051. name[0] == 'r' ? st.right : st.bottom;
  1052. if (set)
  1053. snprintf(buf, cap, "%dpx", v);
  1054. else
  1055. snprintf(buf, cap, "auto");
  1056. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  1057. !strcmp(name, "margin-bottom") ||
  1058. !strcmp(name, "margin-left") ||
  1059. !strcmp(name, "padding-top") ||
  1060. !strcmp(name, "padding-right") ||
  1061. !strcmp(name, "padding-bottom") ||
  1062. !strcmp(name, "padding-left")) {
  1063. int is_pad = name[0] == 'p';
  1064. int side = name[strlen(name) - 1] == 'p' ? 0 :
  1065. name[strlen(name) - 1] == 't' ? 1 :
  1066. name[strlen(name) - 1] == 'm' ? 2 : 3;
  1067. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  1068. if (!strcmp(name, "margin-right") ||
  1069. !strcmp(name, "padding-right"))
  1070. side = 1;
  1071. else if (!strcmp(name, "margin-bottom") ||
  1072. !strcmp(name, "padding-bottom"))
  1073. side = 2;
  1074. else if (!strcmp(name, "margin-left") ||
  1075. !strcmp(name, "padding-left"))
  1076. side = 3;
  1077. else
  1078. side = 0;
  1079. side += is_pad ? 4 : 0;
  1080. css_mp_value(buf, cap,
  1081. side == 0 ? st.mt : side == 1 ? st.mr :
  1082. side == 2 ? st.mb : side == 3 ? st.ml :
  1083. side == 4 ? st.pt : side == 5 ? st.pr :
  1084. side == 6 ? st.pb : st.pl,
  1085. st.mp_unit[side], st.mp_calc_px[side],
  1086. st.font_px);
  1087. } else if (!strcmp(name, "border-top-width") ||
  1088. !strcmp(name, "border-right-width") ||
  1089. !strcmp(name, "border-bottom-width") ||
  1090. !strcmp(name, "border-left-width")) {
  1091. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1092. name[7] == 'b' ? 2 : 3;
  1093. snprintf(buf, cap, "%dpx", st.border_w[side]);
  1094. } else if (!strcmp(name, "border-top-color") ||
  1095. !strcmp(name, "border-right-color") ||
  1096. !strcmp(name, "border-bottom-color") ||
  1097. !strcmp(name, "border-left-color")) {
  1098. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1099. name[7] == 'b' ? 2 : 3;
  1100. if (st.border_w[side] && !st.border_t[side])
  1101. css_rgb(st.border_c[side], buf, cap);
  1102. else
  1103. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1104. } else if (!strcmp(name, "background-image")) {
  1105. if (st.bg_image)
  1106. snprintf(buf, cap, "url(\"%s\")",
  1107. br_bg_image_url(st.bg_image - 1));
  1108. else
  1109. snprintf(buf, cap, "none");
  1110. } else if (!strcmp(name, "background-repeat")) {
  1111. static const char *rp[] = {
  1112. "repeat", "no-repeat", "repeat-x", "repeat-y"
  1113. };
  1114. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  1115. st.bg_repeat : 0]);
  1116. } else if (!strcmp(name, "background-position")) {
  1117. if (st.bg_pos_x_kind == 1)
  1118. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  1119. st.bg_pos_y);
  1120. else
  1121. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1122. st.bg_pos_y);
  1123. } else if (!strcmp(name, "background-size")) {
  1124. if (st.bg_size_kind == 3)
  1125. snprintf(buf, cap, "cover");
  1126. else if (st.bg_size_kind == 4)
  1127. snprintf(buf, cap, "contain");
  1128. else if (st.bg_size_kind == 1)
  1129. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1130. st.bg_size_h);
  1131. else if (st.bg_size_kind == 2)
  1132. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1133. st.bg_size_h);
  1134. else
  1135. snprintf(buf, cap, "auto");
  1136. } else if (!strcmp(name, "transform")) {
  1137. char tmp[128];
  1138. unsigned int n = 0;
  1139. if (!st.transform_set) {
  1140. snprintf(buf, cap, "none");
  1141. } else {
  1142. tmp[0] = '\0';
  1143. if (st.tx || st.ty) {
  1144. snprintf(tmp + n, sizeof(tmp) - n,
  1145. "translate(%dpx, %dpx)", st.tx, st.ty);
  1146. n = (unsigned int)strlen(tmp);
  1147. }
  1148. if (st.transform_scale) {
  1149. snprintf(tmp + n, sizeof(tmp) - n,
  1150. "%sscale(%d.%02d, %d.%02d)",
  1151. n ? " " : "", st.scale_x / 100,
  1152. st.scale_x % 100, st.scale_y / 100,
  1153. st.scale_y % 100);
  1154. n = (unsigned int)strlen(tmp);
  1155. if (st.rotate_x100) {
  1156. snprintf(tmp + n, sizeof(tmp) - n,
  1157. " rotate(%d.%02ddeg)",
  1158. st.rotate_x100 / 100,
  1159. st.rotate_x100 % 100);
  1160. }
  1161. } else if (st.rotate_x100) {
  1162. snprintf(tmp + n, sizeof(tmp) - n,
  1163. "%srotate(%d.%02ddeg)",
  1164. n ? " " : "", st.rotate_x100 / 100,
  1165. st.rotate_x100 % 100);
  1166. }
  1167. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1168. }
  1169. } else {
  1170. return 0;
  1171. }
  1172. return buf[0] != '\0';
  1173. }
  1174. static int js_host_click(unsigned int node)
  1175. {
  1176. char url[BR_URL_MAX];
  1177. const char *href;
  1178. if (node >= doc.nnode)
  1179. return 0;
  1180. if (form_is_control(node)) {
  1181. form_click(node); /* dispatches its own click event */
  1182. return 1;
  1183. }
  1184. /* element.click() fires a bubbling, cancelable click before the
  1185. * default action, like a real click (delegated list handlers). */
  1186. if (!js_browser_event(node, "click", 1, 1))
  1187. return 1;
  1188. if (link_fragment_nav(node))
  1189. return 1;
  1190. href = br_href(&doc, node);
  1191. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1192. return 0;
  1193. s_copy(pending_url, url, sizeof(pending_url));
  1194. pending_action |= ACT_NAV;
  1195. cancel_fetch = 1;
  1196. ngui_invalidate(&ui);
  1197. return 1;
  1198. }
  1199. static int fetch_script_text(const char *url, unsigned char **out,
  1200. unsigned int *outlen, char *err,
  1201. unsigned int errcap);
  1202. struct fetch_worker;
  1203. static struct fetch_worker *fetch_worker_alloc(void);
  1204. static void fetch_worker_release(struct fetch_worker *w);
  1205. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1206. unsigned int cap, const char *post,
  1207. unsigned int post_len, unsigned int node,
  1208. int bg, char *err, unsigned int errcap);
  1209. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1210. unsigned int errcap);
  1211. static int fetch_worker_read_body(struct fetch_worker *w,
  1212. unsigned char *plain,
  1213. unsigned int plaincap,
  1214. unsigned char *comp,
  1215. unsigned int compcap,
  1216. int *truncated, char *err,
  1217. unsigned int errcap);
  1218. static void fetch_workers_stop_all(void);
  1219. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1220. unsigned int cap, const char *method,
  1221. const char *ctype, const char *post,
  1222. unsigned int post_len, unsigned int node,
  1223. int bg, unsigned int dec_w,
  1224. unsigned int dec_h, char *err,
  1225. unsigned int errcap);
  1226. static int script_cache_has(const char *url);
  1227. static void script_cache_put(const char *url, const unsigned char *data,
  1228. unsigned int len);
  1229. static unsigned int script_cache_hash(const char *s);
  1230. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1231. unsigned int errcap);
  1232. static void fetch_workers_cancel_busy(void);
  1233. static void worker_wait_ui(void);
  1234. static int fetch_worker_status(const struct fetch_worker *w);
  1235. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1236. * module load: the wait must not pump input, or a click would dispatch DOM
  1237. * events into the middle of the running script. */
  1238. static int fetch_wait_passive;
  1239. static void script_error(const char *what, const char *url, const char *why)
  1240. {
  1241. char msg[192];
  1242. unsigned int n = 0;
  1243. s_append(msg, &n, what, sizeof(msg));
  1244. if (url && url[0]) {
  1245. s_append(msg, &n, " ", sizeof(msg));
  1246. s_append(msg, &n, url, sizeof(msg));
  1247. }
  1248. if (why && why[0]) {
  1249. s_append(msg, &n, ": ", sizeof(msg));
  1250. s_append(msg, &n, why, sizeof(msg));
  1251. }
  1252. js_host_report(msg);
  1253. }
  1254. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1255. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1256. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1257. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1258. #define JS_HTTP_POST_MAX (16u * 1024u)
  1259. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1260. static int js_worker_http(const char *method, const char *url,
  1261. const char *ctype, const char *body,
  1262. unsigned int body_len, struct js_http_resp *r,
  1263. char *err, int errcap);
  1264. static int js_host_http(const char *method, const char *url,
  1265. const char *ctype, const char *body,
  1266. unsigned int body_len, struct js_http_resp *r,
  1267. char *err, int errcap)
  1268. {
  1269. if (pending_action) {
  1270. s_copy(err, "page is navigating", (unsigned int)errcap);
  1271. return -1;
  1272. }
  1273. if (url[0] == '/') {
  1274. /* Local file: GET only. */
  1275. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1276. int rv;
  1277. if (!buf) {
  1278. s_copy(err, "out of memory", (unsigned int)errcap);
  1279. return -1;
  1280. }
  1281. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1282. (int)JS_HTTP_MAX);
  1283. r->status = rv < 0 ? 404 : 200;
  1284. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1285. buf[r->len] = '\0';
  1286. r->body = (char *)buf;
  1287. s_copy(r->url, url, sizeof(r->url));
  1288. if (contains_ci(url, ".json"))
  1289. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1290. return 0;
  1291. }
  1292. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1293. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1294. return -1;
  1295. }
  1296. if (body_len > JS_HTTP_POST_MAX) {
  1297. s_copy(err, "request body too large", (unsigned int)errcap);
  1298. return -1;
  1299. }
  1300. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1301. errcap);
  1302. }
  1303. /* Module source for the engine's loader: the boot script cache first, then
  1304. * one blocking fetch with input pumping disabled (the loader runs inside
  1305. * JavaScript). */
  1306. static char *js_host_load_script(const char *url, unsigned int *len)
  1307. {
  1308. unsigned char *data = 0;
  1309. char err[64];
  1310. int rv;
  1311. fetch_wait_passive++;
  1312. set_status("Loading module...", 0, 0);
  1313. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1314. fetch_wait_passive--;
  1315. if (rv != 0) {
  1316. script_error("Cannot load module", url,
  1317. rv == FETCH_ABORT ? "navigation" : err);
  1318. return 0;
  1319. }
  1320. return (char *)data;
  1321. }
  1322. /* Web Storage lives in /share, outside the page heap that every navigation
  1323. * resets: localStorage per origin for the boot, sessionStorage per origin
  1324. * and browser window. */
  1325. #define JS_ORIGIN_MAX 160
  1326. /* scheme://host[:port] of the page (a local page's whole path). */
  1327. static void js_page_origin(char *origin, unsigned int cap)
  1328. {
  1329. unsigned int i = 0, slashes = 0;
  1330. while (page_url[i] && i + 1 < cap) {
  1331. if (page_url[i] == '/' && ++slashes == 3)
  1332. break;
  1333. origin[i] = page_url[i];
  1334. i++;
  1335. }
  1336. origin[i] = '\0';
  1337. }
  1338. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1339. {
  1340. unsigned int n = 0;
  1341. s_append(out, &n, "/share/bls", cap);
  1342. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1343. }
  1344. static void js_storage_path(int kind, char *out, unsigned int cap)
  1345. {
  1346. char origin[JS_ORIGIN_MAX];
  1347. unsigned int n = 0;
  1348. js_page_origin(origin, sizeof(origin));
  1349. if (!kind) {
  1350. js_origin_path(origin, out, cap);
  1351. return;
  1352. }
  1353. s_append(out, &n, "/share/bss", cap);
  1354. if (kind) {
  1355. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1356. s_append(out, &n, "-", cap);
  1357. }
  1358. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1359. }
  1360. static void persist_mark_origin(const char *origin);
  1361. static int persist_store_lookup(const char *origin, char *out, int cap);
  1362. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1363. {
  1364. char path[48], origin[JS_ORIGIN_MAX];
  1365. int rv;
  1366. js_storage_path(kind, path, sizeof(path));
  1367. if (set) {
  1368. if (kind) {
  1369. if (!set[0] || !strcmp(set, "{}")) {
  1370. u_syscall1(SYS_UNLINK, (int)path);
  1371. return 0;
  1372. }
  1373. } else {
  1374. /* localStorage keeps an explicit "{}" rather than no
  1375. * file: a missing /share file means "not loaded from
  1376. * /data yet", and a cleared store must not come back
  1377. * from the disk copy before it is flushed. */
  1378. if (!set[0])
  1379. set = "{}";
  1380. js_page_origin(origin, sizeof(origin));
  1381. persist_mark_origin(origin);
  1382. }
  1383. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1384. (int)strlen(set)) < 0 ? -1 : 0;
  1385. }
  1386. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1387. if (rv < 0 && !kind) {
  1388. /* First use this boot: the persistent copy on /data. */
  1389. js_page_origin(origin, sizeof(origin));
  1390. rv = persist_store_lookup(origin, out, cap);
  1391. if (rv >= 0)
  1392. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1393. }
  1394. if (rv < 0)
  1395. return -1;
  1396. out[rv] = '\0';
  1397. return rv;
  1398. }
  1399. /* ---- persistence on /data ----
  1400. *
  1401. * /share is the working copy (RAM, shared by every helper and window); the
  1402. * installed disk's /data volume keeps the cookie jar and localStorage
  1403. * across reboots when it is mounted. The browser owns the disk copies: at
  1404. * start it restores the jar into /share, and its main loop writes back
  1405. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1406. * setItem updates costs one FAT write. The helpers only touch /share (they
  1407. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1408. * /data mount every disk access simply fails. Both files are plaintext
  1409. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1410. #define PERSIST_MS 3000u
  1411. #define SHARE_COOKIES "/share/bcookies"
  1412. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1413. #define DATA_STORE "/data/BSTORE.DAT"
  1414. #define DATA_STORE_MAGIC "NBLS1\n"
  1415. #define DATA_STORE_MAX (192u * 1024u)
  1416. #define PERSIST_DIRTY_MAX 8
  1417. static unsigned int persist_due;
  1418. static unsigned int cookie_sum_saved;
  1419. static int cookie_sum_valid;
  1420. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1421. static int persist_ndirty;
  1422. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1423. {
  1424. unsigned int h = 2166136261u, i;
  1425. for (i = 0; i < n; i++)
  1426. h = (h ^ p[i]) * 16777619u;
  1427. return h;
  1428. }
  1429. /* Called once at startup, before any helper runs. */
  1430. static void persist_restore(void)
  1431. {
  1432. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1433. int n;
  1434. if (!jar)
  1435. return;
  1436. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1437. (int)sizeof(struct uhttp_jar));
  1438. if (n != (int)sizeof(struct uhttp_jar)) {
  1439. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1440. (int)sizeof(struct uhttp_jar));
  1441. if (n == (int)sizeof(struct uhttp_jar)) {
  1442. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1443. (int)jar, n);
  1444. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1445. cookie_sum_valid = 1;
  1446. }
  1447. }
  1448. free(jar);
  1449. persist_due = u_ticks_ms() + PERSIST_MS;
  1450. }
  1451. static void persist_mark_origin(const char *origin)
  1452. {
  1453. int i;
  1454. for (i = 0; i < persist_ndirty; i++)
  1455. if (s_eq(persist_dirty[i], origin))
  1456. return;
  1457. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1458. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1459. }
  1460. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1461. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1462. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1463. unsigned int *o_off, unsigned int *o_len,
  1464. unsigned int *d_off, unsigned int *d_len,
  1465. unsigned int *rec_end)
  1466. {
  1467. unsigned int p = *pos, v = 0;
  1468. if (p >= len)
  1469. return 0;
  1470. *o_off = p;
  1471. while (p < len && buf[p] != '\n')
  1472. p++;
  1473. if (p >= len)
  1474. return 0;
  1475. *o_len = p - *o_off;
  1476. p++;
  1477. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1478. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1479. if (p >= len || buf[p] != '\n')
  1480. return 0;
  1481. p++;
  1482. if (v > len - p)
  1483. return 0;
  1484. *d_off = p;
  1485. *d_len = v;
  1486. p += v;
  1487. if (p < len && buf[p] == '\n')
  1488. p++;
  1489. *rec_end = p;
  1490. *pos = p;
  1491. return 1;
  1492. }
  1493. static int store_load(char **out)
  1494. {
  1495. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1496. int n;
  1497. *out = buf;
  1498. if (!buf)
  1499. return -1;
  1500. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1501. (int)DATA_STORE_MAX);
  1502. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1503. !starts_with(buf, DATA_STORE_MAGIC))
  1504. return 0;
  1505. return n;
  1506. }
  1507. static int persist_store_lookup(const char *origin, char *out, int cap)
  1508. {
  1509. char *buf;
  1510. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1511. unsigned int olen = s_len(origin);
  1512. int n = store_load(&buf), rv = -1;
  1513. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1514. &dl, &e)) {
  1515. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1516. if ((int)dl < cap) {
  1517. memcpy(out, buf + d, dl);
  1518. out[dl] = '\0';
  1519. rv = (int)dl;
  1520. }
  1521. break;
  1522. }
  1523. }
  1524. free(buf);
  1525. return rv;
  1526. }
  1527. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1528. static void persist_store_flush(void)
  1529. {
  1530. char *old, *nb, path[48];
  1531. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1532. int n = store_load(&old), i, w;
  1533. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1534. if (n < 0 || !nb) {
  1535. free(old);
  1536. free(nb);
  1537. return;
  1538. }
  1539. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1540. /* Untouched origins first, in their old order. */
  1541. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1542. &dl, &e)) {
  1543. int dirty = 0;
  1544. for (i = 0; i < persist_ndirty; i++)
  1545. if (s_len(persist_dirty[i]) == ol &&
  1546. !memcmp(persist_dirty[i], old + oo, ol))
  1547. dirty = 1;
  1548. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1549. continue;
  1550. memcpy(nb + nn, old + oo, e - oo);
  1551. nn += e - oo;
  1552. }
  1553. /* Then the changed ones (an emptied store is dropped). */
  1554. for (i = 0; i < persist_ndirty; i++) {
  1555. char num[12];
  1556. unsigned int k = 0;
  1557. js_origin_path(persist_dirty[i], path, sizeof(path));
  1558. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1559. (int)DATA_STORE_MAX);
  1560. if (w <= 2) /* missing or "{}" */
  1561. continue;
  1562. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1563. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1564. DATA_STORE_MAX) {
  1565. set_status("Saved site data is full; a site's "
  1566. "localStorage was not saved", 1, 6000);
  1567. continue;
  1568. }
  1569. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1570. nb[nn++] = '\n';
  1571. s_append(nb, &nn, num, DATA_STORE_MAX);
  1572. nb[nn++] = '\n';
  1573. memcpy(nb + nn, old, (unsigned int)w);
  1574. nn += (unsigned int)w;
  1575. nb[nn++] = '\n';
  1576. }
  1577. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1578. persist_ndirty = 0;
  1579. free(old);
  1580. free(nb);
  1581. }
  1582. static void persist_cookies_flush(void)
  1583. {
  1584. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1585. unsigned int sum;
  1586. int n;
  1587. if (!jar)
  1588. return;
  1589. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1590. (int)sizeof(struct uhttp_jar));
  1591. if (n == (int)sizeof(struct uhttp_jar)) {
  1592. sum = persist_sum(jar, (unsigned int)n);
  1593. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1594. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1595. (int)jar, n) >= 0) {
  1596. cookie_sum_saved = sum;
  1597. cookie_sum_valid = 1;
  1598. }
  1599. }
  1600. }
  1601. free(jar);
  1602. }
  1603. /* ---- visit history (URL-bar autocomplete) ----
  1604. *
  1605. * Every page that finishes loading is recorded with its title, a visit
  1606. * count and a stamp: a counter that only grows and travels with the file,
  1607. * so it orders visits across windows and boots without a wall clock. The
  1608. * table lives in BSS, because the page heap is reset on every navigation.
  1609. * The boot's browser windows share it through /share/bhist (rewritten on
  1610. * every visit) and it is persisted to /data/BHIST.DAT from persist_tick()
  1611. * at most every PERSIST_MS, like the cookie jar. A save re-reads
  1612. * /share/bhist and merges it first, so two windows add to one history
  1613. * instead of overwriting each other. File format: "NBHIST1\n", then
  1614. * "<visits> <stamp> <url>\t<title>\n" per entry. Plaintext, like the
  1615. * other browser state on /data. */
  1616. #define HIST_MAX 128
  1617. #define HIST_URL_MAX 512
  1618. #define HIST_FILE_MAX (HIST_MAX * (HIST_URL_MAX + BR_TITLE_MAX + 24) + 16)
  1619. #define HIST_MAGIC "NBHIST1\n"
  1620. #define SHARE_HIST "/share/bhist"
  1621. #define DATA_HIST "/data/BHIST.DAT"
  1622. #define HIST_FORGET_MAX 16
  1623. struct hist_ent {
  1624. unsigned int visits;
  1625. unsigned int stamp;
  1626. char url[HIST_URL_MAX];
  1627. char title[BR_TITLE_MAX];
  1628. };
  1629. static struct hist_ent hist_tab[HIST_MAX];
  1630. static int hist_n;
  1631. static int hist_share_dirty, hist_data_dirty;
  1632. /* URLs removed in this process: a merge must not bring them back. */
  1633. static unsigned int hist_forgot[HIST_FORGET_MAX];
  1634. static int hist_nforgot;
  1635. static unsigned int hist_hash(const char *s)
  1636. {
  1637. return persist_sum((const unsigned char *)s, s_len(s));
  1638. }
  1639. static int hist_is_forgotten(const char *url)
  1640. {
  1641. unsigned int h = hist_hash(url);
  1642. int i;
  1643. for (i = 0; i < hist_nforgot; i++)
  1644. if (hist_forgot[i] == h)
  1645. return 1;
  1646. return 0;
  1647. }
  1648. static int hist_find(const char *url)
  1649. {
  1650. int i;
  1651. for (i = 0; i < hist_n; i++)
  1652. if (s_eq(hist_tab[i].url, url))
  1653. return i;
  1654. return -1;
  1655. }
  1656. static unsigned int hist_next_stamp(void)
  1657. {
  1658. unsigned int m = 0;
  1659. int i;
  1660. for (i = 0; i < hist_n; i++)
  1661. if (hist_tab[i].stamp > m)
  1662. m = hist_tab[i].stamp;
  1663. return m + 1;
  1664. }
  1665. /* Copy a title, turning tabs/newlines (the file separators) into spaces. */
  1666. static void hist_copy_title(char *d, const char *s, unsigned int n)
  1667. {
  1668. unsigned int i;
  1669. for (i = 0; i + 1 < BR_TITLE_MAX && i < n && s[i]; i++)
  1670. d[i] = (unsigned char)s[i] < 0x20 ? ' ' : s[i];
  1671. d[i] = '\0';
  1672. }
  1673. /* Insert or update an entry; the newer stamp wins the title, the larger
  1674. * visit count is kept. A full table evicts the least recent entry, unless
  1675. * the new one is older still. Returns NULL when nothing was stored. */
  1676. static struct hist_ent *hist_put(const char *url, const char *title,
  1677. unsigned int visits, unsigned int stamp)
  1678. {
  1679. struct hist_ent *e;
  1680. int i = hist_find(url);
  1681. if (i < 0) {
  1682. if (hist_n < HIST_MAX) {
  1683. i = hist_n++;
  1684. } else {
  1685. int j;
  1686. i = 0;
  1687. for (j = 1; j < hist_n; j++)
  1688. if (hist_tab[j].stamp < hist_tab[i].stamp)
  1689. i = j;
  1690. if (hist_tab[i].stamp >= stamp)
  1691. return 0;
  1692. }
  1693. e = &hist_tab[i];
  1694. e->visits = 0;
  1695. e->stamp = 0;
  1696. e->title[0] = '\0';
  1697. s_copy(e->url, url, sizeof(e->url));
  1698. }
  1699. e = &hist_tab[i];
  1700. if (visits > e->visits)
  1701. e->visits = visits;
  1702. if (stamp >= e->stamp) {
  1703. e->stamp = stamp;
  1704. if (title && title[0])
  1705. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1706. } else if (!e->title[0] && title) {
  1707. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1708. }
  1709. return e;
  1710. }
  1711. static unsigned int hist_parse_dec(const char *b, int n, int *pos)
  1712. {
  1713. unsigned int v = 0;
  1714. while (*pos < n && b[*pos] >= '0' && b[*pos] <= '9')
  1715. v = v * 10 + (unsigned int)(b[(*pos)++] - '0');
  1716. return v;
  1717. }
  1718. static void hist_merge_buf(const char *b, int n)
  1719. {
  1720. int pos = (int)s_len(HIST_MAGIC);
  1721. char url[HIST_URL_MAX], title[BR_TITLE_MAX];
  1722. if (n < pos || memcmp(b, HIST_MAGIC, (unsigned int)pos))
  1723. return;
  1724. while (pos < n) {
  1725. unsigned int visits, stamp, ul = 0;
  1726. int t0, t1;
  1727. visits = hist_parse_dec(b, n, &pos);
  1728. if (pos < n && b[pos] == ' ')
  1729. pos++;
  1730. stamp = hist_parse_dec(b, n, &pos);
  1731. if (pos < n && b[pos] == ' ')
  1732. pos++;
  1733. while (pos < n && b[pos] != '\t' && b[pos] != '\n') {
  1734. if (ul + 1 < sizeof(url))
  1735. url[ul++] = b[pos];
  1736. pos++;
  1737. }
  1738. url[ul] = '\0';
  1739. t0 = t1 = pos < n && b[pos] == '\t' ? pos + 1 : pos;
  1740. while (t1 < n && b[t1] != '\n')
  1741. t1++;
  1742. pos = t1 + 1;
  1743. hist_copy_title(title, b + t0, (unsigned int)(t1 - t0));
  1744. if (ul && ul + 1 < sizeof(url) && !hist_is_forgotten(url))
  1745. hist_put(url, title, visits, stamp);
  1746. }
  1747. }
  1748. static int hist_serialize(char *b, unsigned int cap)
  1749. {
  1750. unsigned int n = 0;
  1751. int i;
  1752. s_append(b, &n, HIST_MAGIC, cap);
  1753. for (i = 0; i < hist_n; i++) {
  1754. struct hist_ent *e = &hist_tab[i];
  1755. if (n + s_len(e->url) + s_len(e->title) + 26 >= cap)
  1756. break;
  1757. s_append_dec(b, &n, e->visits, cap);
  1758. b[n++] = ' ';
  1759. s_append_dec(b, &n, e->stamp, cap);
  1760. b[n++] = ' ';
  1761. s_append(b, &n, e->url, cap);
  1762. b[n++] = '\t';
  1763. s_append(b, &n, e->title, cap);
  1764. b[n++] = '\n';
  1765. }
  1766. return (int)n;
  1767. }
  1768. /* Merge /share/bhist, then write it back (and /data when asked). */
  1769. static void hist_sync(int to_data)
  1770. {
  1771. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1772. int n;
  1773. if (!b)
  1774. return;
  1775. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1776. (int)HIST_FILE_MAX);
  1777. if (n > 0)
  1778. hist_merge_buf(b, n);
  1779. n = hist_serialize(b, HIST_FILE_MAX);
  1780. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1781. hist_share_dirty = 0;
  1782. if (to_data) {
  1783. /* No /data mount: the write fails, and there is nothing to
  1784. * retry until the next visit. */
  1785. u_syscall3(SYS_WRITE_FILE, (int)DATA_HIST, (int)b, n);
  1786. hist_data_dirty = 0;
  1787. }
  1788. free(b);
  1789. }
  1790. /* Startup: the boot's shared copy, else the saved one from /data. */
  1791. static void hist_load(void)
  1792. {
  1793. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1794. int n;
  1795. if (!b)
  1796. return;
  1797. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1798. (int)HIST_FILE_MAX);
  1799. if (n <= 0) {
  1800. n = u_syscall3(SYS_READ_FILE, (int)DATA_HIST, (int)b,
  1801. (int)HIST_FILE_MAX);
  1802. if (n > 0)
  1803. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1804. }
  1805. if (n > 0)
  1806. hist_merge_buf(b, n);
  1807. free(b);
  1808. }
  1809. static void hist_visit(const char *url, const char *title)
  1810. {
  1811. struct hist_ent *e;
  1812. unsigned int i;
  1813. if (!url[0] || starts_with(url, "about:") ||
  1814. s_len(url) >= HIST_URL_MAX)
  1815. return;
  1816. for (i = 0; url[i]; i++)
  1817. if ((unsigned char)url[i] < 0x20)
  1818. return;
  1819. e = hist_put(url, title, 0, hist_next_stamp());
  1820. if (!e)
  1821. return;
  1822. e->visits++;
  1823. hist_data_dirty = 1;
  1824. hist_sync(0);
  1825. }
  1826. static void hist_forget(int i)
  1827. {
  1828. if (i < 0 || i >= hist_n)
  1829. return;
  1830. if (hist_nforgot < HIST_FORGET_MAX)
  1831. hist_forgot[hist_nforgot++] = hist_hash(hist_tab[i].url);
  1832. hist_n--;
  1833. for (; i < hist_n; i++)
  1834. hist_tab[i] = hist_tab[i + 1];
  1835. hist_data_dirty = 1;
  1836. hist_sync(0);
  1837. }
  1838. static void hist_tick(void)
  1839. {
  1840. if (hist_share_dirty || hist_data_dirty)
  1841. hist_sync(hist_data_dirty);
  1842. }
  1843. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1844. static void persist_tick(void)
  1845. {
  1846. unsigned int now = u_ticks_ms();
  1847. if ((int)(now - persist_due) < 0)
  1848. return;
  1849. persist_due = now + PERSIST_MS;
  1850. persist_cookies_flush();
  1851. if (persist_ndirty)
  1852. persist_store_flush();
  1853. hist_tick();
  1854. }
  1855. /* <link rel="modulepreload">: download the page's module graph on all
  1856. * helpers at once into the boot script cache, before any script runs. The
  1857. * engine's module loader is sequential (one blocking fetch per import), so
  1858. * without this a Vite app with a dozen chunks pays every round trip in a
  1859. * row. Failures are ignored; the loader fetches what is missing. */
  1860. #define MODULE_PRELOAD_MAX 24
  1861. static void prefetch_module_preloads(void)
  1862. {
  1863. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1864. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1865. unsigned int count = 0, next = 0, done = 0, i;
  1866. char err[64];
  1867. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1868. struct br_node *nd = &doc.nodes[i];
  1869. const char *rel, *href;
  1870. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1871. continue;
  1872. rel = br_rel(&doc, i);
  1873. href = br_href(&doc, i);
  1874. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1875. continue;
  1876. if (resolve_link(page_url, href, urls[count],
  1877. sizeof(urls[count])) != 0 ||
  1878. urls[count][0] == '/' || script_cache_has(urls[count]))
  1879. continue;
  1880. slot[count++] = 0;
  1881. }
  1882. if (!count)
  1883. return;
  1884. set_status("Loading modules...", 0, 0);
  1885. while (done < count) {
  1886. struct fetch_worker *w;
  1887. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1888. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1889. 0, 0, 0, err,
  1890. sizeof(err)) != 0) {
  1891. fetch_worker_release(w);
  1892. done++;
  1893. } else {
  1894. slot[next] = w;
  1895. }
  1896. next++;
  1897. }
  1898. worker_wait_ui();
  1899. if (cancel_fetch || pending_action) {
  1900. fetch_workers_cancel_busy();
  1901. return;
  1902. }
  1903. for (i = 0; i < next; i++) {
  1904. unsigned char *body;
  1905. int rv, tr = 0;
  1906. if (!slot[i])
  1907. continue;
  1908. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1909. if (rv == 0)
  1910. continue;
  1911. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1912. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1913. if (body) {
  1914. rv = fetch_worker_read_body(slot[i], body,
  1915. BR_SCRIPT_MAX, image_io_buf,
  1916. BR_PAGE_COMP_MAX, &tr, err,
  1917. sizeof(err));
  1918. if (rv > 0 && !tr)
  1919. script_cache_put(urls[i], body,
  1920. (unsigned int)rv);
  1921. free(body);
  1922. }
  1923. fetch_worker_release(slot[i]);
  1924. slot[i] = 0;
  1925. done++;
  1926. }
  1927. u_sleep_ms(10);
  1928. }
  1929. }
  1930. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1931. * submitted to helper workers ahead of time, but scripts still execute in
  1932. * document order. */
  1933. #define SCRIPT_INLINE 0
  1934. #define SCRIPT_LOCAL 1
  1935. #define SCRIPT_REMOTE 2
  1936. #define SCRIPT_ERROR 3
  1937. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1938. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1939. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1940. static void script_submit_window(unsigned int *next, char *err,
  1941. unsigned int errcap)
  1942. {
  1943. while (*next < doc.nscripts) {
  1944. struct fetch_worker *w;
  1945. if (script_kind[*next] != SCRIPT_REMOTE) {
  1946. (*next)++;
  1947. continue;
  1948. }
  1949. w = fetch_worker_alloc();
  1950. if (!w)
  1951. return;
  1952. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1953. 0, 0, 0, 0, err, errcap) != 0) {
  1954. fetch_worker_release(w);
  1955. script_kind[*next] = SCRIPT_ERROR;
  1956. (*next)++;
  1957. continue;
  1958. }
  1959. script_slot[*next] = w;
  1960. (*next)++;
  1961. }
  1962. }
  1963. /* Run the page's scripts in document order. External bodies are prefetched
  1964. * in parallel so downloading script N+1 overlaps executing script N; inline
  1965. * bodies are copied because the engine needs NUL-terminated text. */
  1966. static void run_page_scripts(void)
  1967. {
  1968. struct js_browser_host host;
  1969. unsigned int i, next = 0;
  1970. char err[64], ferr[64];
  1971. if (!doc.nscripts)
  1972. return;
  1973. host.status = js_host_status;
  1974. host.report = js_host_report;
  1975. host.navigate = js_host_navigate;
  1976. host.changed = js_host_changed;
  1977. host.rect = js_host_rect;
  1978. host.form_value = js_host_form_value;
  1979. host.form_checked = js_host_form_checked;
  1980. host.form_selected = js_host_form_selected;
  1981. host.form_set_value = js_host_form_set_value;
  1982. host.form_set_checked = js_host_form_set_checked;
  1983. host.form_set_selected = js_host_form_set_selected;
  1984. host.form_elements = js_host_form_elements;
  1985. host.form_submit = js_host_form_submit;
  1986. host.form_reset = js_host_form_reset;
  1987. host.click = js_host_click;
  1988. host.computed = js_host_computed;
  1989. host.http = js_host_http;
  1990. host.load_script = js_host_load_script;
  1991. host.storage = js_host_storage;
  1992. host.set_hash = js_host_set_hash;
  1993. host.page_url = page_url;
  1994. host.width = ui.w;
  1995. host.height = ui.h;
  1996. if (js_browser_start(&doc, &host) != 0) {
  1997. js_host_status("JavaScript: out of memory", 1);
  1998. return;
  1999. }
  2000. resize_sent_w = -1;
  2001. resize_pending = 0;
  2002. prefetch_module_preloads();
  2003. for (i = 0; i < doc.nscripts; i++) {
  2004. struct br_script *script = &doc.scripts[i];
  2005. const char *src_attr = script->src_off ?
  2006. doc.attrs + script->src_off : "";
  2007. script_slot[i] = 0;
  2008. if (!script->src_off) {
  2009. script_kind[i] = SCRIPT_INLINE;
  2010. continue;
  2011. }
  2012. if (!src_attr[0] ||
  2013. resolve_link(page_url, src_attr, script_urls[i],
  2014. sizeof(script_urls[i])) != 0) {
  2015. script_urls[i][0] = '\0';
  2016. script_kind[i] = SCRIPT_ERROR;
  2017. continue;
  2018. }
  2019. if (script_urls[i][0] == '/' ||
  2020. script_cache_has(script_urls[i]))
  2021. script_kind[i] = SCRIPT_LOCAL;
  2022. else
  2023. script_kind[i] = SCRIPT_REMOTE;
  2024. }
  2025. script_submit_window(&next, ferr, sizeof(ferr));
  2026. for (i = 0; i < doc.nscripts; i++) {
  2027. struct br_script *script = &doc.scripts[i];
  2028. /* document.currentScript for classic scripts (null for modules) */
  2029. js_browser_set_current_script(script->module ? 0 : script->node);
  2030. if (script_kind[i] == SCRIPT_INLINE) {
  2031. unsigned int off = script->off;
  2032. unsigned int len = script->len;
  2033. unsigned int k;
  2034. char *src = (char *)malloc(len + 1);
  2035. if (!src) {
  2036. js_host_status("JavaScript: out of memory", 1);
  2037. break;
  2038. }
  2039. for (k = 0; k < len; k++)
  2040. src[k] = doc.script_src[off + k];
  2041. src[len] = '\0';
  2042. if (script->module) {
  2043. /* A distinct module name per inline module
  2044. * (QuickJS registers modules by name); the
  2045. * fragment keeps relative imports resolving
  2046. * against the page. */
  2047. char mname[BR_URL_MAX + 16];
  2048. unsigned int mn = 0;
  2049. s_append(mname, &mn, page_url, sizeof(mname));
  2050. s_append(mname, &mn, "#module", sizeof(mname));
  2051. s_append_dec(mname, &mn, i, sizeof(mname));
  2052. js_browser_run_module(src, mname);
  2053. } else {
  2054. js_browser_run(src, page_url);
  2055. }
  2056. free(src);
  2057. } else if (script->src_off) {
  2058. const char *src_attr = doc.attrs + script->src_off;
  2059. if (script_kind[i] == SCRIPT_ERROR) {
  2060. script_error("Cannot load script", src_attr,
  2061. script_urls[i][0] ?
  2062. "network busy" :
  2063. "unsupported URL");
  2064. continue;
  2065. }
  2066. if (script_kind[i] == SCRIPT_LOCAL) {
  2067. unsigned char *data = 0;
  2068. unsigned int len = 0;
  2069. int rv;
  2070. set_status("Loading script...", 0, 0);
  2071. rv = fetch_script_text(script_urls[i], &data,
  2072. &len, err, sizeof(err));
  2073. if (rv == FETCH_ABORT)
  2074. break;
  2075. if (rv != 0) {
  2076. script_error("Cannot load script",
  2077. script_urls[i], err);
  2078. continue;
  2079. }
  2080. if (script->module)
  2081. js_browser_run_module(
  2082. (const char *)data,
  2083. script_urls[i]);
  2084. else
  2085. js_browser_run((const char *)data,
  2086. script_urls[i]);
  2087. free(data);
  2088. } else {
  2089. struct fetch_worker *w = script_slot[i];
  2090. unsigned char *body = 0;
  2091. int tr = 0, rv;
  2092. if (!w) {
  2093. w = fetch_worker_alloc();
  2094. if (!w)
  2095. continue;
  2096. if (fetch_worker_submit(w,
  2097. script_urls[i],
  2098. BR_SCRIPT_MAX,
  2099. 0, 0, 0, 0, err,
  2100. sizeof(err)) != 0) {
  2101. fetch_worker_release(w);
  2102. script_kind[i] = SCRIPT_ERROR;
  2103. if (i == next)
  2104. next++;
  2105. continue;
  2106. }
  2107. script_slot[i] = w;
  2108. if (i == next)
  2109. next++;
  2110. }
  2111. set_status("Loading script...", 0, 0);
  2112. rv = fetch_worker_wait(w, err, sizeof(err));
  2113. if (rv == FETCH_ABORT) {
  2114. fetch_workers_stop_all();
  2115. break;
  2116. }
  2117. /* The body gets its own buffer (scripts are up
  2118. * to 2 MB); image_io_buf takes the gzip
  2119. * stream. */
  2120. body = rv == 0 ? (unsigned char *)malloc(
  2121. BR_SCRIPT_MAX + 1) : 0;
  2122. if (body)
  2123. rv = fetch_worker_read_body(w, body,
  2124. BR_SCRIPT_MAX, image_io_buf,
  2125. BR_PAGE_COMP_MAX, &tr, err,
  2126. sizeof(err));
  2127. else {
  2128. if (rv == 0)
  2129. s_copy(err, "out of memory",
  2130. sizeof(err));
  2131. rv = -1;
  2132. }
  2133. fetch_worker_release(w);
  2134. script_slot[i] = 0;
  2135. script_submit_window(&next, ferr, sizeof(ferr));
  2136. if (rv <= 0)
  2137. script_error("Cannot load script",
  2138. script_urls[i], err);
  2139. else if (tr || (unsigned int)rv >=
  2140. BR_SCRIPT_MAX)
  2141. script_error("Cannot load script",
  2142. script_urls[i],
  2143. "script is too large");
  2144. else {
  2145. body[rv] = '\0';
  2146. script_cache_put(script_urls[i], body,
  2147. (unsigned int)rv);
  2148. if (script->module)
  2149. js_browser_run_module(
  2150. (const char *)body,
  2151. script_urls[i]);
  2152. else
  2153. js_browser_run(
  2154. (const char *)body,
  2155. script_urls[i]);
  2156. }
  2157. free(body);
  2158. }
  2159. }
  2160. if (pending_action)
  2161. break;
  2162. }
  2163. js_browser_set_current_script(0);
  2164. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  2165. * load_home() stop it before the next navigation. */
  2166. if (doc.scripts_truncated && !js_last_error)
  2167. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  2168. 1);
  2169. }
  2170. /* ---- images ---- */
  2171. /* data: images that failed to decode (key = data_img_key()), so a layout
  2172. * pass does not retry them on every frame. */
  2173. #define DATA_IMG_FAIL_MAX 32
  2174. static unsigned int data_img_fail[DATA_IMG_FAIL_MAX];
  2175. static int data_img_nfail;
  2176. static void image_reset(void)
  2177. {
  2178. int i;
  2179. for (i = 0; i < BR_MAX_IMAGES; i++) {
  2180. images[i].state = 0;
  2181. images[i].native_w = images[i].native_h = 0;
  2182. images[i].err[0] = '\0';
  2183. /* heap_clear() ran before us, so these pointers are stale: drop
  2184. * them without calling free(). */
  2185. memset(&images[i].disp, 0, sizeof(images[i].disp));
  2186. images[i].disp_pixels = 0;
  2187. images[i].disp_last = 0;
  2188. }
  2189. image_count = 0;
  2190. data_img_nfail = 0;
  2191. image_pixels = 0;
  2192. image_disp_pixels = 0;
  2193. image_disp_clock = 0;
  2194. memset(img_stat_log, 0, sizeof(img_stat_log));
  2195. img_stat_log_len = 0;
  2196. img_stat_start = 0;
  2197. img_stat_wall = 0;
  2198. img_stat_net = img_stat_open = img_stat_first = 0;
  2199. img_stat_io = img_stat_dec = img_stat_scale = 0;
  2200. img_stat_paint = img_stat_reflow = 0;
  2201. img_stat_bytes = 0;
  2202. img_stat_n = 0;
  2203. img_last_dec_ms = img_last_scale_ms = 0;
  2204. img_repaint_ms = 0;
  2205. img_repaint_pending = 0;
  2206. preload_active = 0;
  2207. preload_pending = 0;
  2208. preload_wait = 0;
  2209. preload_node = 0;
  2210. preload_loaded = 0;
  2211. }
  2212. /* Ask for a repaint, but not more often than BR_IMG_REPAINT_MS while images
  2213. * are arriving. The main loop draws once per dirty frame; without this a
  2214. * page of N images did N full layout+paint passes. */
  2215. static void image_repaint(void)
  2216. {
  2217. unsigned int now = u_ticks_ms();
  2218. if (!img_repaint_ms || (now - img_repaint_ms) >= BR_IMG_REPAINT_MS) {
  2219. img_repaint_ms = now;
  2220. img_repaint_pending = 0;
  2221. ngui_invalidate(&ui);
  2222. } else {
  2223. img_repaint_pending = 1;
  2224. }
  2225. }
  2226. static void image_disp_drop(struct br_image *bi)
  2227. {
  2228. if (bi->disp.px)
  2229. free(bi->disp.px);
  2230. if (bi->disp.alpha)
  2231. free(bi->disp.alpha);
  2232. memset(&bi->disp, 0, sizeof(bi->disp));
  2233. if (bi->disp_pixels) {
  2234. if (image_disp_pixels >= bi->disp_pixels)
  2235. image_disp_pixels -= bi->disp_pixels;
  2236. bi->disp_pixels = 0;
  2237. }
  2238. }
  2239. /* Free the least recently used display caches until need pixels fit. The
  2240. * source bitmap (bi->img) is never evicted; a later draw rescales it again. */
  2241. static int image_disp_room(unsigned int need)
  2242. {
  2243. while (image_disp_pixels + need > BR_IMG_DISP_BUDGET) {
  2244. unsigned int oldest = ~0u;
  2245. int i, victim = -1;
  2246. for (i = 0; i < image_count; i++) {
  2247. if (!images[i].disp.px)
  2248. continue;
  2249. if (images[i].disp_last < oldest) {
  2250. oldest = images[i].disp_last;
  2251. victim = i;
  2252. }
  2253. }
  2254. if (victim < 0)
  2255. return -1;
  2256. image_disp_drop(&images[victim]);
  2257. }
  2258. return 0;
  2259. }
  2260. /* Return a bitmap at exactly dw x dh, building it once from the capped source
  2261. * bitmap. Callers then draw with scale 1 and img_draw's copy fast path. */
  2262. static struct img_image *image_display_get(struct br_image *bi, int dw, int dh)
  2263. {
  2264. struct img_blit b;
  2265. unsigned int px;
  2266. if (!bi || bi->state != 1 || !bi->img.px || dw < 1 || dh < 1)
  2267. return 0;
  2268. if (dw == (int)bi->img.w && dh == (int)bi->img.h)
  2269. return &bi->img;
  2270. if (dw > 4096 || dh > 4096)
  2271. return &bi->img;
  2272. if (bi->disp.px && bi->disp.w == (unsigned int)dw &&
  2273. bi->disp.h == (unsigned int)dh) {
  2274. bi->disp_last = ++image_disp_clock;
  2275. return &bi->disp;
  2276. }
  2277. px = (unsigned int)dw * (unsigned int)dh;
  2278. if (px > BR_IMG_DISP_BUDGET || image_disp_room(px) != 0)
  2279. return &bi->img;
  2280. image_disp_drop(bi);
  2281. bi->disp.px = (unsigned short *)malloc(px * 2u);
  2282. if (!bi->disp.px)
  2283. return &bi->img;
  2284. if (bi->img.alpha) {
  2285. bi->disp.alpha = (unsigned char *)malloc(px);
  2286. if (!bi->disp.alpha) {
  2287. free(bi->disp.px);
  2288. bi->disp.px = 0;
  2289. return &bi->img;
  2290. }
  2291. }
  2292. bi->disp.w = (unsigned int)dw;
  2293. bi->disp.h = (unsigned int)dh;
  2294. bi->disp.format = bi->img.format;
  2295. bi->disp.flags = 0;
  2296. memset(&b, 0, sizeof(b));
  2297. b.dst = bi->disp.px;
  2298. b.dst_w = dw;
  2299. b.dst_h = dh;
  2300. b.clip_w = dw;
  2301. b.clip_h = dh;
  2302. b.scale = ((unsigned int)dw << 16) / bi->img.w;
  2303. b.dst_a = bi->disp.alpha;
  2304. b.flags = bi->disp.alpha ? IMG_BLIT_SAVE_ALPHA : 0;
  2305. img_draw(&bi->img, &b);
  2306. bi->disp_pixels = px;
  2307. image_disp_pixels += px;
  2308. bi->disp_last = ++image_disp_clock;
  2309. return &bi->disp;
  2310. }
  2311. /* Decode into the shared arena, then copy/scale the result into a display
  2312. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  2313. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  2314. * pixels. Transparent edges are composited over white. */
  2315. /* One decode scratch arena per page, reused across images. Allocating and
  2316. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  2317. * each small display bitmap landed in the hole the previous arena left, so
  2318. * the next arena no longer fit and the heap ratcheted up until an app
  2319. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  2320. * still released right after their one image. */
  2321. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  2322. static unsigned char *decode_arena_get(unsigned int bytes)
  2323. {
  2324. if (decode_arena && decode_arena_size >= bytes)
  2325. return decode_arena;
  2326. free(decode_arena);
  2327. decode_arena = (unsigned char *)malloc(bytes);
  2328. decode_arena_size = decode_arena ? bytes : 0;
  2329. return decode_arena;
  2330. }
  2331. static void decode_arena_put(void)
  2332. {
  2333. if (decode_arena_size > DECODE_ARENA_KEEP) {
  2334. free(decode_arena);
  2335. decode_arena = 0;
  2336. decode_arena_size = 0;
  2337. }
  2338. }
  2339. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  2340. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  2341. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  2342. static int svg_text_sniff(const unsigned char *d, unsigned int len);
  2343. static int svg_decode_image(const unsigned char *data, unsigned int len,
  2344. struct br_image *bi, int box_w, int box_h);
  2345. static int decode_image_data(const unsigned char *data, unsigned int len,
  2346. struct br_image *bi, int box_w, int box_h,
  2347. int fit_w, int fit_h)
  2348. {
  2349. struct img_info info;
  2350. struct img_options opt;
  2351. struct img_mem mem;
  2352. struct img_image decoded;
  2353. unsigned char *arena;
  2354. unsigned int est, bytes, i;
  2355. unsigned int t0;
  2356. unsigned short *px;
  2357. unsigned char *alpha = 0;
  2358. int dw, dh, r;
  2359. bi->url_hash = 0;
  2360. img_last_dec_ms = 0;
  2361. img_last_scale_ms = 0;
  2362. if (img_sniff(data, len, &info) != 0) {
  2363. if (svg_text_sniff(data, len))
  2364. return svg_decode_image(data, len, bi,
  2365. box_w > 0 && box_h > 0 ? box_w : fit_w,
  2366. box_w > 0 && box_h > 0 ? box_h : fit_h);
  2367. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  2368. return -1;
  2369. }
  2370. est = img_estimate(&info);
  2371. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  2372. s_copy(bi->err, "image too large", sizeof(bi->err));
  2373. return -1;
  2374. }
  2375. arena = decode_arena_get(est);
  2376. if (!arena) {
  2377. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2378. return -1;
  2379. }
  2380. img_mem_init(&mem, arena, est);
  2381. opt.max_pixels = BR_IMG_PIX_MAX;
  2382. opt.max_w = fit_w > 0 ? (unsigned int)fit_w :
  2383. (box_w > 0 ? (unsigned int)box_w : 0);
  2384. opt.max_h = fit_h > 0 ? (unsigned int)fit_h :
  2385. (box_h > 0 ? (unsigned int)box_h : 0);
  2386. t0 = u_ticks_ms();
  2387. r = img_decode(data, len, &opt, &mem, &decoded);
  2388. img_last_dec_ms = u_ticks_ms() - t0;
  2389. if (r != 0) {
  2390. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  2391. goto fail;
  2392. }
  2393. if (decoded.w == 0 || decoded.h == 0) {
  2394. s_copy(bi->err, "empty image", sizeof(bi->err));
  2395. goto fail;
  2396. }
  2397. /* The JPEG decoder may have reduced the IDCT output; the layout still
  2398. * needs the intrinsic dimensions from the header. */
  2399. bi->native_w = info.width ? (int)info.width : (int)decoded.w;
  2400. bi->native_h = info.height ? (int)info.height : (int)decoded.h;
  2401. dw = (int)decoded.w;
  2402. dh = (int)decoded.h;
  2403. /* An <img> with a CSS/attribute box only ever needs a bitmap that big:
  2404. * decoding 1200x800 and then box-filtering it to 1000x666, only to
  2405. * paint it at 400x267, doubled the decode-time scaling work. cap both
  2406. * axes with one scale so the aspect ratio is preserved. */
  2407. if (fit_w > 0 || fit_h > 0) {
  2408. unsigned int scw = fit_w > 0 ?
  2409. ((unsigned int)fit_w << 16) / decoded.w : ~0u;
  2410. unsigned int sch = fit_h > 0 ?
  2411. ((unsigned int)fit_h << 16) / decoded.h : ~0u;
  2412. unsigned int sc = scw < sch ? scw : sch;
  2413. if (sc < 0x10000u) {
  2414. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2415. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2416. if (dw < 1)
  2417. dw = 1;
  2418. if (dh < 1)
  2419. dh = 1;
  2420. }
  2421. }
  2422. if (box_w > 0 && box_h > 0) {
  2423. /* cover: scale so both box sides are filled, never up */
  2424. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  2425. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  2426. unsigned int sc = sw > sh ? sw : sh;
  2427. if (sc < 0x10000u) {
  2428. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2429. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2430. }
  2431. }
  2432. if (dw > BR_IMG_LAYOUT_W) {
  2433. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  2434. dw = BR_IMG_LAYOUT_W;
  2435. }
  2436. if (dh < 1)
  2437. dh = 1;
  2438. if (dw < 1)
  2439. dw = 1;
  2440. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  2441. BR_IMG_PIXEL_BUDGET) {
  2442. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  2443. goto fail;
  2444. }
  2445. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  2446. px = (unsigned short *)malloc(bytes);
  2447. if (!px) {
  2448. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2449. goto fail;
  2450. }
  2451. /* Keep the alpha plane for the scaled image so transparent logos and
  2452. * icons composite over the page instead of the browser's dark theme
  2453. * background. Very large alpha images stay flattened to bound the
  2454. * heap use. */
  2455. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  2456. alpha = (unsigned char *)malloc((unsigned int)dw *
  2457. (unsigned int)dh);
  2458. if (alpha) {
  2459. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2460. alpha[i] = 255;
  2461. }
  2462. }
  2463. /* With an alpha plane the colour under transparent pixels only shows
  2464. * through partially covered edge pixels of the downscale: use white,
  2465. * as documented above, not the dark browser theme (which left a dark
  2466. * fringe around scaled app icons). */
  2467. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2468. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  2469. {
  2470. struct img_blit b;
  2471. b.dst = px;
  2472. b.dst_w = dw;
  2473. b.dst_h = dh;
  2474. b.clip_x = 0;
  2475. b.clip_y = 0;
  2476. b.clip_w = dw;
  2477. b.clip_h = dh;
  2478. b.x = 0;
  2479. b.y = 0;
  2480. b.scale = ((unsigned int)dw << 16) / decoded.w;
  2481. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  2482. b.bg2 = b.bg;
  2483. b.dst_a = alpha;
  2484. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  2485. t0 = u_ticks_ms();
  2486. img_draw(&decoded, &b);
  2487. img_last_scale_ms = u_ticks_ms() - t0;
  2488. }
  2489. bi->img.format = decoded.format;
  2490. bi->img.w = (unsigned int)dw;
  2491. bi->img.h = (unsigned int)dh;
  2492. bi->img.px = px;
  2493. bi->img.alpha = alpha;
  2494. bi->img.flags = 0;
  2495. bi->state = 1;
  2496. image_pixels += (unsigned int)dw * (unsigned int)dh;
  2497. decode_arena_put();
  2498. return 0;
  2499. fail:
  2500. decode_arena_put();
  2501. return -1;
  2502. }
  2503. /* ---- URL / local path handling ---- */
  2504. static int is_http(const char *s)
  2505. {
  2506. return starts_with(s, "http://") || starts_with(s, "https://");
  2507. }
  2508. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  2509. static int normalize_abs(const char *in, char *out, unsigned int cap)
  2510. {
  2511. char seg[64];
  2512. unsigned int i = 0, o = 1;
  2513. int depth = 0;
  2514. int trailing;
  2515. if (!in || in[0] != '/' || cap < 2)
  2516. return -1;
  2517. trailing = 0;
  2518. {
  2519. unsigned int n = s_len(in);
  2520. if (n > 1 && in[n - 1] == '/')
  2521. trailing = 1;
  2522. }
  2523. out[0] = '/';
  2524. while (in[i]) {
  2525. unsigned int n = 0;
  2526. while (in[i] == '/')
  2527. i++;
  2528. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  2529. if (n + 1 < sizeof(seg))
  2530. seg[n++] = in[i];
  2531. i++;
  2532. }
  2533. seg[n] = '\0';
  2534. if (n == 0)
  2535. break;
  2536. if (s_eq(seg, "."))
  2537. continue;
  2538. if (s_eq(seg, "..")) {
  2539. if (depth > 0) {
  2540. while (o > 1 && out[o - 1] != '/')
  2541. o--;
  2542. if (o > 1)
  2543. o--;
  2544. depth--;
  2545. }
  2546. continue;
  2547. }
  2548. if (o > 1) {
  2549. if (o + 1 >= cap)
  2550. return -1;
  2551. out[o++] = '/';
  2552. }
  2553. if (o + n + 1 >= cap)
  2554. return -1;
  2555. {
  2556. unsigned int j;
  2557. for (j = 0; j < n; j++)
  2558. out[o++] = seg[j];
  2559. }
  2560. depth++;
  2561. }
  2562. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2563. if (o + 1 >= cap)
  2564. return -1;
  2565. out[o++] = '/';
  2566. }
  2567. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2568. if (in[i] == '?' || in[i] == '#') {
  2569. while (in[i]) {
  2570. if (o + 1 >= cap)
  2571. return -1;
  2572. out[o++] = in[i++];
  2573. }
  2574. }
  2575. out[o] = '\0';
  2576. return 0;
  2577. }
  2578. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2579. {
  2580. char joined[BR_URL_MAX];
  2581. if (!in || !in[0]) {
  2582. s_copy(out, cwd[0] ? cwd : "/", cap);
  2583. return;
  2584. }
  2585. if (in[0] == '/') {
  2586. if (normalize_abs(in, out, cap) != 0)
  2587. s_copy(out, in, cap);
  2588. return;
  2589. }
  2590. {
  2591. unsigned int n = 0;
  2592. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2593. s_append(joined, &n, "/", sizeof(joined));
  2594. s_append(joined, &n, in, sizeof(joined));
  2595. }
  2596. if (normalize_abs(joined, out, cap) != 0)
  2597. s_copy(out, joined, cap);
  2598. }
  2599. /* ---- canonical origin cache ---- *
  2600. *
  2601. * Sites commonly redirect http://host to https://host and then to
  2602. * https://www.host. Remember the final scheme/host of the last navigation so
  2603. * a bare domain typed again goes straight there instead of paying for two
  2604. * more connections and TLS handshakes. Only default-port requests are
  2605. * rewritten; explicit ports are left alone. */
  2606. #define ORIGIN_CACHE_MAX 8
  2607. #define ORIGIN_FILE "/share/borigins"
  2608. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2609. UHTTP_HOST_MAX + 2))
  2610. struct origin_cache_entry {
  2611. char host[UHTTP_HOST_MAX];
  2612. char origin[UHTTP_HOST_MAX + 16];
  2613. };
  2614. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2615. static int origin_count;
  2616. static char origin_buf[ORIGIN_BUF_SIZE];
  2617. static int default_port(const struct uhttp_url *u)
  2618. {
  2619. return u->secure ? u->port == 443 : u->port == 80;
  2620. }
  2621. static void url_origin(const struct uhttp_url *u, char *out,
  2622. unsigned int cap)
  2623. {
  2624. unsigned int n = 0;
  2625. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2626. s_append(out, &n, u->host, cap);
  2627. if (!default_port(u)) {
  2628. s_append(out, &n, ":", cap);
  2629. s_append_dec(out, &n, u->port, cap);
  2630. }
  2631. }
  2632. static void origin_cache_apply(char *url, unsigned int cap)
  2633. {
  2634. struct uhttp_url u;
  2635. char out[BR_URL_MAX];
  2636. unsigned int n = 0;
  2637. int i;
  2638. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2639. return;
  2640. for (i = 0; i < origin_count; i++) {
  2641. if (!s_eq(u.host, origins[i].host))
  2642. continue;
  2643. s_append(out, &n, origins[i].origin, sizeof(out));
  2644. s_append(out, &n, u.path, sizeof(out));
  2645. s_copy(url, out, cap);
  2646. return;
  2647. }
  2648. }
  2649. static void origin_cache_save(void)
  2650. {
  2651. unsigned int n = 0;
  2652. int i;
  2653. for (i = 0; i < origin_count; i++) {
  2654. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2655. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2656. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2657. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2658. }
  2659. if (n)
  2660. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2661. (int)origin_buf, (int)n);
  2662. }
  2663. static void origin_cache_load(void)
  2664. {
  2665. char *p;
  2666. int rn;
  2667. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2668. (int)(sizeof(origin_buf) - 1));
  2669. if (rn <= 0)
  2670. return;
  2671. origin_buf[rn] = '\0';
  2672. p = origin_buf;
  2673. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2674. char *line = p, *origin;
  2675. while (*p && *p != '\n')
  2676. p++;
  2677. if (*p)
  2678. *p++ = '\0';
  2679. if (!line[0])
  2680. continue;
  2681. origin = line;
  2682. while (*origin && *origin != ' ')
  2683. origin++;
  2684. if (!*origin)
  2685. continue;
  2686. *origin++ = '\0';
  2687. if (!line[0] || !is_http(origin))
  2688. continue;
  2689. {
  2690. struct uhttp_url uo;
  2691. if (uhttp_parse_url(origin, &uo) != 0 ||
  2692. !s_eq(uo.path, "/"))
  2693. continue;
  2694. }
  2695. s_copy(origins[origin_count].host, line,
  2696. sizeof(origins[origin_count].host));
  2697. s_copy(origins[origin_count].origin, origin,
  2698. sizeof(origins[origin_count].origin));
  2699. origin_count++;
  2700. }
  2701. }
  2702. static int host_is_www_of(const char *host, const char *base)
  2703. {
  2704. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2705. host[3] == '.' && s_eq(host + 4, base);
  2706. }
  2707. static void origin_cache_learn(const char *requested, const char *final)
  2708. {
  2709. struct uhttp_url from, to;
  2710. char origin[UHTTP_HOST_MAX + 16];
  2711. int i;
  2712. if (!is_http(requested) || !is_http(final))
  2713. return;
  2714. if (uhttp_parse_url(requested, &from) != 0 ||
  2715. uhttp_parse_url(final, &to) != 0)
  2716. return;
  2717. if (!default_port(&from))
  2718. return;
  2719. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2720. from.port == to.port)
  2721. return;
  2722. /* Only remember origin-level canonicalisation: the same path, and
  2723. * either the same host or its www./apex sibling. A path- or
  2724. * host-specific redirect (a shortener, a login page) must not poison
  2725. * every request to the typed host. */
  2726. if (!s_eq(from.path, to.path))
  2727. return;
  2728. if (!s_eq(from.host, to.host) &&
  2729. !host_is_www_of(to.host, from.host) &&
  2730. !host_is_www_of(from.host, to.host))
  2731. return;
  2732. url_origin(&to, origin, sizeof(origin));
  2733. for (i = 0; i < origin_count; i++) {
  2734. if (s_eq(origins[i].host, from.host)) {
  2735. if (!s_eq(origins[i].origin, origin)) {
  2736. s_copy(origins[i].origin, origin,
  2737. sizeof(origins[i].origin));
  2738. origin_cache_save();
  2739. }
  2740. return;
  2741. }
  2742. }
  2743. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2744. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2745. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2746. origin_cache_save();
  2747. }
  2748. static int path_dir(const char *path, char *out, unsigned int cap)
  2749. {
  2750. unsigned int i, last = 0;
  2751. for (i = 0; path[i]; i++)
  2752. if (path[i] == '/')
  2753. last = i;
  2754. if (last == 0) {
  2755. if (cap < 2)
  2756. return -1;
  2757. out[0] = '/';
  2758. out[1] = '\0';
  2759. return 0;
  2760. }
  2761. if (last + 1 >= cap)
  2762. return -1;
  2763. {
  2764. unsigned int j;
  2765. for (j = 0; j < last; j++)
  2766. out[j] = path[j];
  2767. out[last] = '\0';
  2768. }
  2769. return 0;
  2770. }
  2771. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2772. static int resolve_link(const char *base, const char *href, char *out,
  2773. unsigned int cap)
  2774. {
  2775. static char joined[BR_URL_MAX]; /* leaf: off the stack */
  2776. if (!href || !href[0] || href[0] == '#')
  2777. return -1;
  2778. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2779. starts_with(href, "data:") || starts_with(href, "tel:"))
  2780. return -1;
  2781. if (starts_with(href, "about:")) {
  2782. s_copy(out, href, cap);
  2783. return 0;
  2784. }
  2785. if (is_http(href)) {
  2786. s_copy(out, href, cap);
  2787. return 0;
  2788. }
  2789. if (starts_with(href, "//")) {
  2790. if (is_http(base)) {
  2791. unsigned int n = 0;
  2792. s_append(out, &n, starts_with(base, "https:") ?
  2793. "https:" : "http:", cap);
  2794. s_append(out, &n, href, cap);
  2795. return 0;
  2796. }
  2797. return -1;
  2798. }
  2799. if (is_http(base)) {
  2800. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2801. }
  2802. /* local page */
  2803. if (href[0] == '/') {
  2804. if (normalize_abs(href, out, cap) != 0)
  2805. return -1;
  2806. return 0;
  2807. }
  2808. {
  2809. static char dir[BR_URL_MAX];
  2810. unsigned int n = 0;
  2811. if (s_eq(base, "about:home"))
  2812. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2813. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2814. s_copy(dir, "/", sizeof(dir));
  2815. s_append(joined, &n, dir, sizeof(joined));
  2816. if (n == 0 || joined[n - 1] != '/')
  2817. s_append(joined, &n, "/", sizeof(joined));
  2818. s_append(joined, &n, href, sizeof(joined));
  2819. }
  2820. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2821. }
  2822. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2823. * rest instead of failing when a page or stylesheet is larger than the
  2824. * buffer. The stream is still walked to the end, so a normal page is
  2825. * verified; a truncated compressed input still returns whatever was decoded
  2826. * so far. */
  2827. struct trunc_buf {
  2828. unsigned char *dst;
  2829. unsigned int cap, pos;
  2830. int full;
  2831. };
  2832. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2833. {
  2834. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2835. if (len > m->cap - m->pos) {
  2836. unsigned int room = m->cap - m->pos;
  2837. if (room) {
  2838. unsigned int i;
  2839. for (i = 0; i < room; i++)
  2840. m->dst[m->pos + i] = data[i];
  2841. m->pos += room;
  2842. }
  2843. m->full = 1;
  2844. return 0;
  2845. }
  2846. {
  2847. unsigned int i;
  2848. for (i = 0; i < len; i++)
  2849. m->dst[m->pos + i] = data[i];
  2850. }
  2851. m->pos += len;
  2852. return 0;
  2853. }
  2854. static void worker_wait_ui(void);
  2855. static void inflate_ui_pump(void *ctx)
  2856. {
  2857. static unsigned int last;
  2858. unsigned int now = u_ticks_ms();
  2859. (void)ctx;
  2860. if ((int)(now - last) >= 50) {
  2861. last = now;
  2862. worker_wait_ui();
  2863. }
  2864. }
  2865. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2866. unsigned char *dst, unsigned int cap,
  2867. unsigned int *outlen, int gzip, int *truncated)
  2868. {
  2869. struct inflate_src in;
  2870. struct inflate_sink sink;
  2871. struct trunc_buf m;
  2872. unsigned int got = 0;
  2873. int r;
  2874. in.p = src;
  2875. in.len = len;
  2876. in.more = 0;
  2877. in.ctx = 0;
  2878. m.dst = dst;
  2879. m.cap = cap;
  2880. m.pos = 0;
  2881. m.full = 0;
  2882. sink.write = trunc_write;
  2883. sink.ctx = &m;
  2884. inflate_init(&image_inflate_ws, &in, &sink);
  2885. image_inflate_ws.progress = inflate_ui_pump;
  2886. image_inflate_ws.progress_ctx = 0;
  2887. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2888. inflate_zlib(&image_inflate_ws, &got);
  2889. *outlen = m.pos;
  2890. *truncated = m.full || r != 0;
  2891. if (r != 0 && m.pos == 0)
  2892. return -1;
  2893. return 0;
  2894. }
  2895. /* ---- headless fetch workers ------------------------------------------ *
  2896. *
  2897. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2898. * writes the raw response, a small metadata file and a done marker under
  2899. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2900. * or a multi-megabyte body never freezes the UI and images download in
  2901. * parallel.
  2902. */
  2903. struct fetch_meta {
  2904. int status;
  2905. int error;
  2906. int trunc;
  2907. unsigned int len;
  2908. unsigned int open_ms;
  2909. unsigned int first_ms;
  2910. unsigned int total_ms;
  2911. /* Optional decoded bitmap produced by the helper (image jobs). */
  2912. unsigned int dw, dh, nw, nh;
  2913. unsigned int alpha;
  2914. unsigned int px_len;
  2915. unsigned int dec_ms;
  2916. int dec_err;
  2917. char encoding[16];
  2918. char ctype[64];
  2919. char final[BR_URL_MAX];
  2920. };
  2921. static void draw(unsigned int *action);
  2922. static void handle_keys(unsigned int *action);
  2923. static void handle_page_click(unsigned int *action);
  2924. #define FETCH_WORKERS 4
  2925. #define FETCH_PATH_MAX 32
  2926. /* One long-lived curl __serve helper per worker. Each worker has its own
  2927. * request/body/meta/done files under /share so several downloads can be in
  2928. * flight at once; the keep-alive connection stays in the helper process, so
  2929. * tls.c's per-process state remains valid. */
  2930. struct fetch_worker {
  2931. int pid;
  2932. int slot;
  2933. int busy;
  2934. int ready;
  2935. int image_job;
  2936. unsigned int seq;
  2937. unsigned int deadline;
  2938. int retried;
  2939. unsigned int dec_w, dec_h;
  2940. int dec_retried;
  2941. char req[FETCH_PATH_MAX];
  2942. char body[FETCH_PATH_MAX];
  2943. char meta[FETCH_PATH_MAX];
  2944. char done[FETCH_PATH_MAX];
  2945. char post[FETCH_PATH_MAX];
  2946. char px[FETCH_PATH_MAX];
  2947. /* Optional preload job attached to this worker. */
  2948. unsigned int node;
  2949. int bg;
  2950. char url[BR_URL_MAX];
  2951. struct fetch_meta m;
  2952. };
  2953. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2954. static int fetch_tty = -2;
  2955. static void fetch_tty_drain(void);
  2956. static unsigned int fetch_session;
  2957. static unsigned int fetch_seq;
  2958. static struct fetch_meta fetch_meta;
  2959. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2960. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2961. static int fetch_last_error;
  2962. static unsigned int meta_uint(char **pp)
  2963. {
  2964. char *p = *pp;
  2965. unsigned int v = 0;
  2966. while (*p >= '0' && *p <= '9') {
  2967. v = v * 10 + (unsigned int)(*p - '0');
  2968. p++;
  2969. }
  2970. while (*p && *p != '\n')
  2971. p++;
  2972. if (*p == '\n')
  2973. p++;
  2974. *pp = p;
  2975. return v;
  2976. }
  2977. static void meta_str(char **pp, char *out, unsigned int cap)
  2978. {
  2979. char *p = *pp;
  2980. unsigned int n = 0;
  2981. while (*p && *p != '\n' && n + 1 < cap)
  2982. out[n++] = *p++;
  2983. out[n] = '\0';
  2984. while (*p && *p != '\n')
  2985. p++;
  2986. if (*p == '\n')
  2987. p++;
  2988. *pp = p;
  2989. }
  2990. static void worker_wait_ui(void)
  2991. {
  2992. unsigned int action = 0;
  2993. if (!ngui_begin(&ui))
  2994. return;
  2995. draw(&action);
  2996. handle_keys(&action);
  2997. handle_page_click(&action);
  2998. if (action & ACT_WAIT_NAV) {
  2999. pending_action |= action & ACT_WAIT_NAV;
  3000. if ((action & ACT_NAV) && click_url[0])
  3001. s_copy(pending_url, click_url, sizeof(pending_url));
  3002. click_url[0] = '\0';
  3003. cancel_fetch = 1;
  3004. }
  3005. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  3006. ngui_invalidate(&ui);
  3007. ngui_end(&ui);
  3008. }
  3009. static void fetch_path(char *out, unsigned int cap, const char *kind,
  3010. unsigned int session, int slot)
  3011. {
  3012. unsigned int n = 0;
  3013. s_append(out, &n, "/share/bf", cap);
  3014. s_append_dec(out, &n, session, cap);
  3015. s_append(out, &n, "_", cap);
  3016. s_append_dec(out, &n, (unsigned int)slot, cap);
  3017. s_append(out, &n, kind, cap);
  3018. }
  3019. static void fetch_pool_init(void)
  3020. {
  3021. static int ready;
  3022. int i;
  3023. if (ready)
  3024. return;
  3025. ready = 1;
  3026. fetch_session = ((unsigned int)u_getpid() << 16) ^
  3027. (u_ticks_ms() & 0xFFFFu);
  3028. if (!fetch_session)
  3029. fetch_session = 1;
  3030. for (i = 0; i < FETCH_WORKERS; i++) {
  3031. struct fetch_worker *w = &fetch_workers[i];
  3032. w->pid = -1;
  3033. w->slot = i;
  3034. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  3035. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  3036. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  3037. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  3038. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  3039. fetch_path(w->px, sizeof(w->px), "px", fetch_session, i);
  3040. }
  3041. }
  3042. static void fetch_worker_stop(struct fetch_worker *w)
  3043. {
  3044. int i;
  3045. /* An abandoned image job leaves its node loadable again. */
  3046. if (w->busy && w->image_job && w->node < doc.nnode) {
  3047. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  3048. doc.nodes[w->node].bg_img_index = -1;
  3049. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  3050. doc.nodes[w->node].img_index = -1;
  3051. }
  3052. if (w->pid > 0) {
  3053. u_kill((unsigned int)w->pid);
  3054. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  3055. u_sleep_ms(5);
  3056. /* Let the reaper close the socket before we reuse the slot. */
  3057. u_sleep_ms(10);
  3058. }
  3059. w->pid = -1;
  3060. w->busy = 0;
  3061. w->ready = 0;
  3062. w->image_job = 0;
  3063. if (w->req[0]) {
  3064. u_syscall1(SYS_UNLINK, (int)w->done);
  3065. u_syscall1(SYS_UNLINK, (int)w->meta);
  3066. u_syscall1(SYS_UNLINK, (int)w->body);
  3067. u_syscall1(SYS_UNLINK, (int)w->post);
  3068. u_syscall1(SYS_UNLINK, (int)w->req);
  3069. }
  3070. }
  3071. static void fetch_workers_stop_all(void)
  3072. {
  3073. int i;
  3074. for (i = 0; i < FETCH_WORKERS; i++)
  3075. fetch_worker_stop(&fetch_workers[i]);
  3076. }
  3077. /* Abandon the transfers of the current page but keep idle helpers and their
  3078. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  3079. * because its response would otherwise land in a reused /share slot. */
  3080. static void fetch_workers_cancel_busy(void)
  3081. {
  3082. int i;
  3083. for (i = 0; i < FETCH_WORKERS; i++)
  3084. if (fetch_workers[i].busy)
  3085. fetch_worker_stop(&fetch_workers[i]);
  3086. }
  3087. static void fetch_workers_prepare_nav(const char *url)
  3088. {
  3089. int i;
  3090. (void)url;
  3091. for (i = 0; i < FETCH_WORKERS; i++) {
  3092. struct fetch_worker *w = &fetch_workers[i];
  3093. if (w->pid <= 0)
  3094. continue;
  3095. /* Only an in-flight transfer must be aborted. Idle helpers
  3096. * stay warm across origins: there are just FETCH_WORKERS of
  3097. * them, and uhttp_open drops the old connection when the
  3098. * next job is for another host. Killing and respawning all
  3099. * four on every navigation churned processes and sockets
  3100. * while images were still loading. */
  3101. if (w->busy)
  3102. fetch_worker_stop(w);
  3103. }
  3104. }
  3105. /* The browser is no longer the active window and no fetch is running: give
  3106. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  3107. static void fetch_workers_stop_if_unfocused(void)
  3108. {
  3109. int i;
  3110. fetch_tty_drain();
  3111. if (ui.focused || page_loading || preload_active)
  3112. return;
  3113. for (i = 0; i < FETCH_WORKERS; i++)
  3114. if (fetch_workers[i].pid > 0) {
  3115. fetch_workers_stop_all();
  3116. return;
  3117. }
  3118. }
  3119. /* The helpers (and this process, since u_tty_create() rebinds our own
  3120. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  3121. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  3122. * a dozen TLS connections every helper hung in its next log line, so the
  3123. * following cross-origin navigation sat at "Loading..." until it timed out.
  3124. * Drain and discard it from every wait/poll loop. */
  3125. static void fetch_tty_drain(void)
  3126. {
  3127. char sink[512];
  3128. int i;
  3129. if (fetch_tty <= 0)
  3130. return;
  3131. for (i = 0; i < 16; i++)
  3132. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  3133. break;
  3134. }
  3135. static int fetch_worker_start(struct fetch_worker *w, char *err,
  3136. unsigned int errcap)
  3137. {
  3138. char arg[40];
  3139. unsigned int n = 0;
  3140. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  3141. return 0;
  3142. w->pid = -1;
  3143. fetch_pool_init();
  3144. if (fetch_tty == -2) {
  3145. int t = u_tty_create();
  3146. fetch_tty = t > 0 ? t : 0;
  3147. }
  3148. s_append(arg, &n, "__serve ", sizeof(arg));
  3149. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  3150. s_append(arg, &n, " ", sizeof(arg));
  3151. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  3152. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  3153. if (w->pid <= 0) {
  3154. w->pid = -1;
  3155. s_copy(err, "cannot start network helper", errcap);
  3156. return -1;
  3157. }
  3158. return 0;
  3159. }
  3160. static struct fetch_worker *fetch_worker_alloc(void)
  3161. {
  3162. int i;
  3163. fetch_pool_init();
  3164. for (i = 0; i < FETCH_WORKERS; i++)
  3165. if (!fetch_workers[i].busy)
  3166. return &fetch_workers[i];
  3167. return 0;
  3168. }
  3169. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3170. unsigned int cap, const char *method,
  3171. const char *ctype, const char *post,
  3172. unsigned int post_len, unsigned int node,
  3173. int bg, unsigned int dec_w,
  3174. unsigned int dec_h, char *err,
  3175. unsigned int errcap);
  3176. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  3177. unsigned int cap, const char *post,
  3178. unsigned int post_len, unsigned int node,
  3179. int bg, char *err, unsigned int errcap)
  3180. {
  3181. /* A body pointer with no bytes is still a POST: the classic request
  3182. * line would turn it into a GET. */
  3183. if (post && !post_len)
  3184. return fetch_worker_submit_req(w, url, cap, "POST",
  3185. "application/x-www-form-urlencoded", post, 0, node,
  3186. bg, 0, 0, err, errcap);
  3187. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  3188. node, bg, 0, 0, err, errcap);
  3189. }
  3190. /* Image job: ask the helper to decode at these display bounds as well. */
  3191. static int fetch_worker_submit_image(struct fetch_worker *w, const char *url,
  3192. unsigned int cap, unsigned int node,
  3193. int bg, unsigned int dec_w,
  3194. unsigned int dec_h, char *err,
  3195. unsigned int errcap)
  3196. {
  3197. return fetch_worker_submit_req(w, url, cap, 0, 0, 0, 0, node, bg,
  3198. dec_w, dec_h, err, errcap);
  3199. }
  3200. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  3201. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  3202. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3203. unsigned int cap, const char *method,
  3204. const char *ctype, const char *post,
  3205. unsigned int post_len, unsigned int node,
  3206. int bg, unsigned int dec_w,
  3207. unsigned int dec_h, char *err,
  3208. unsigned int errcap)
  3209. {
  3210. static char req[BR_URL_MAX + 256];
  3211. unsigned int n = 0;
  3212. fetch_seq++;
  3213. if (!fetch_seq)
  3214. fetch_seq = 1;
  3215. w->seq = fetch_seq;
  3216. w->ready = 0;
  3217. w->image_job = 0;
  3218. w->retried = 0;
  3219. w->m.error = 0;
  3220. w->node = node;
  3221. w->bg = bg;
  3222. w->dec_w = dec_w;
  3223. w->dec_h = dec_h;
  3224. w->dec_retried = 0;
  3225. s_copy(w->url, url, sizeof(w->url));
  3226. s_append_dec(req, &n, w->seq, sizeof(req));
  3227. s_append(req, &n, " ", sizeof(req));
  3228. s_append_dec(req, &n, cap, sizeof(req));
  3229. s_append(req, &n, " ", sizeof(req));
  3230. if (dec_w || dec_h) {
  3231. s_append(req, &n, "D ", sizeof(req));
  3232. s_append_dec(req, &n, dec_w, sizeof(req));
  3233. s_append(req, &n, " ", sizeof(req));
  3234. s_append_dec(req, &n, dec_h, sizeof(req));
  3235. s_append(req, &n, " ", sizeof(req));
  3236. } else if (method) {
  3237. unsigned int k;
  3238. s_append(req, &n, "X ", sizeof(req));
  3239. s_append(req, &n, method, sizeof(req));
  3240. s_append(req, &n, " ", sizeof(req));
  3241. s_append_dec(req, &n, post_len, sizeof(req));
  3242. s_append(req, &n, " ", sizeof(req));
  3243. if (!ctype || !ctype[0])
  3244. s_append(req, &n, "-", sizeof(req));
  3245. /* One token on the request line: drop the spaces
  3246. * ("application/json; charset=utf-8" stays valid). */
  3247. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  3248. if (ctype[k] != ' ')
  3249. req[n++] = ctype[k];
  3250. req[n] = '\0';
  3251. s_append(req, &n, " ", sizeof(req));
  3252. } else if (post_len) {
  3253. s_append(req, &n, "POST ", sizeof(req));
  3254. s_append_dec(req, &n, post_len, sizeof(req));
  3255. s_append(req, &n, " ", sizeof(req));
  3256. }
  3257. s_append(req, &n, url, sizeof(req));
  3258. s_append(req, &n, "\n", sizeof(req));
  3259. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  3260. (int)post, (int)post_len) < 0) {
  3261. s_copy(err, "cannot queue form body", errcap);
  3262. return -1;
  3263. }
  3264. u_syscall1(SYS_UNLINK, (int)w->done);
  3265. u_syscall1(SYS_UNLINK, (int)w->meta);
  3266. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  3267. s_copy(err, "cannot queue network request", errcap);
  3268. return -1;
  3269. }
  3270. if (fetch_worker_start(w, err, errcap) != 0)
  3271. return -1;
  3272. w->busy = 1;
  3273. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  3274. return 0;
  3275. }
  3276. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  3277. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  3278. unsigned int errcap)
  3279. {
  3280. static char meta[BR_URL_MAX + 1024];
  3281. char *p;
  3282. int rn, mseq;
  3283. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  3284. (int)(sizeof(meta) - 1));
  3285. if (rn <= 0) {
  3286. s_copy(err, "network helper failed", errcap);
  3287. return -1;
  3288. }
  3289. meta[rn] = '\0';
  3290. p = meta;
  3291. mseq = (int)meta_uint(&p);
  3292. if (mseq != (int)w->seq) {
  3293. s_copy(err, "stale network response", errcap);
  3294. return -1;
  3295. }
  3296. w->m.status = (int)meta_uint(&p);
  3297. w->m.error = (int)meta_uint(&p);
  3298. w->m.trunc = (int)meta_uint(&p);
  3299. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  3300. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  3301. meta_str(&p, w->m.final, sizeof(w->m.final));
  3302. w->m.len = meta_uint(&p);
  3303. w->m.open_ms = 0;
  3304. w->m.first_ms = 0;
  3305. w->m.total_ms = 0;
  3306. if (*p) {
  3307. w->m.open_ms = meta_uint(&p);
  3308. w->m.first_ms = meta_uint(&p);
  3309. w->m.total_ms = meta_uint(&p);
  3310. }
  3311. w->m.dw = w->m.dh = w->m.nw = w->m.nh = 0;
  3312. w->m.alpha = w->m.px_len = w->m.dec_ms = 0;
  3313. w->m.dec_err = 0;
  3314. if (*p) {
  3315. w->m.dw = meta_uint(&p);
  3316. w->m.dh = meta_uint(&p);
  3317. w->m.nw = meta_uint(&p);
  3318. w->m.nh = meta_uint(&p);
  3319. w->m.alpha = meta_uint(&p);
  3320. w->m.px_len = meta_uint(&p);
  3321. w->m.dec_err = (int)meta_uint(&p);
  3322. w->m.dec_ms = meta_uint(&p);
  3323. }
  3324. if (w->m.error) {
  3325. s_copy(err, uhttp_error_string(w->m.error), errcap);
  3326. return -1;
  3327. }
  3328. w->ready = 1;
  3329. return 0;
  3330. }
  3331. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  3332. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  3333. unsigned int errcap)
  3334. {
  3335. static char done[24];
  3336. char *p;
  3337. int rn, mseq;
  3338. fetch_tty_drain();
  3339. if (!w->busy)
  3340. return -1;
  3341. if (w->ready)
  3342. return 1;
  3343. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  3344. (int)(sizeof(done) - 1));
  3345. if (rn > 0) {
  3346. done[rn] = '\0';
  3347. p = done;
  3348. mseq = (int)meta_uint(&p);
  3349. if (mseq == (int)w->seq) {
  3350. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  3351. fetch_worker_stop(w);
  3352. return -1;
  3353. }
  3354. return 1;
  3355. }
  3356. }
  3357. if (!u_alive((unsigned int)w->pid)) {
  3358. w->pid = -1;
  3359. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  3360. w->retried = 1;
  3361. return 0;
  3362. }
  3363. s_copy(err, "network helper stopped", errcap);
  3364. fetch_worker_stop(w);
  3365. return -1;
  3366. }
  3367. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  3368. s_copy(err, "network request timed out", errcap);
  3369. fetch_worker_stop(w);
  3370. return -1;
  3371. }
  3372. return 0;
  3373. }
  3374. /* Copy the completed body, inflating it if the server ignored our identity
  3375. * request. Mirrors the old fetch_remote body path. */
  3376. static int fetch_worker_read_body(struct fetch_worker *w,
  3377. unsigned char *plain,
  3378. unsigned int plaincap,
  3379. unsigned char *comp,
  3380. unsigned int compcap,
  3381. int *truncated, char *err,
  3382. unsigned int errcap)
  3383. {
  3384. int rv, zr, was_trunc;
  3385. if (contains_ci(w->m.encoding, "gzip") ||
  3386. contains_ci(w->m.encoding, "deflate")) {
  3387. unsigned int comp_len = 0, plen = 0;
  3388. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  3389. (int)compcap);
  3390. if (rv < 0) {
  3391. s_copy(err, "empty response", errcap);
  3392. return -1;
  3393. }
  3394. comp_len = (unsigned int)rv;
  3395. if (comp_len < w->m.len) {
  3396. s_copy(err, "compressed response is too large", errcap);
  3397. return -1;
  3398. }
  3399. if (contains_ci(w->m.encoding, "deflate"))
  3400. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3401. &plen, 0, &was_trunc);
  3402. else
  3403. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3404. &plen, 1, &was_trunc);
  3405. if (zr != 0) {
  3406. s_copy(err, "compressed response is corrupt", errcap);
  3407. return -1;
  3408. }
  3409. *truncated = w->m.trunc || was_trunc;
  3410. return (int)plen;
  3411. }
  3412. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  3413. if (rv < 0) {
  3414. s_copy(err, "empty response", errcap);
  3415. return -1;
  3416. }
  3417. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  3418. return rv;
  3419. }
  3420. static void fetch_worker_release(struct fetch_worker *w)
  3421. {
  3422. u_syscall1(SYS_UNLINK, (int)w->done);
  3423. u_syscall1(SYS_UNLINK, (int)w->meta);
  3424. u_syscall1(SYS_UNLINK, (int)w->body);
  3425. u_syscall1(SYS_UNLINK, (int)w->post);
  3426. u_syscall1(SYS_UNLINK, (int)w->px);
  3427. u_syscall1(SYS_UNLINK, (int)w->req);
  3428. w->busy = 0;
  3429. w->ready = 0;
  3430. w->image_job = 0;
  3431. w->dec_w = 0;
  3432. w->dec_h = 0;
  3433. w->dec_retried = 0;
  3434. }
  3435. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  3436. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  3437. unsigned int errcap)
  3438. {
  3439. for (;;) {
  3440. int rv;
  3441. if (!fetch_wait_passive)
  3442. worker_wait_ui();
  3443. if (cancel_fetch || pending_action) {
  3444. fetch_workers_cancel_busy();
  3445. return FETCH_ABORT;
  3446. }
  3447. rv = fetch_worker_poll(w, err, errcap);
  3448. if (rv != 0)
  3449. return rv == 1 ? 0 : -1;
  3450. u_sleep_ms(10);
  3451. }
  3452. }
  3453. static int fetch_remote(const char *url, unsigned int cap,
  3454. const char *post, unsigned int post_len,
  3455. unsigned char *plain, unsigned int plaincap,
  3456. unsigned char *comp, unsigned int compcap,
  3457. struct fetch_meta *m, int *truncated,
  3458. char *err, unsigned int errcap)
  3459. {
  3460. struct fetch_worker *w = fetch_worker_alloc();
  3461. int rv;
  3462. fetch_last_error = 0;
  3463. if (!w) {
  3464. s_copy(err, "network busy", errcap);
  3465. return -1;
  3466. }
  3467. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  3468. err, errcap) != 0) {
  3469. fetch_worker_release(w);
  3470. return -1;
  3471. }
  3472. rv = fetch_worker_wait(w, err, errcap);
  3473. if (rv == FETCH_ABORT) {
  3474. fetch_worker_release(w);
  3475. return FETCH_ABORT;
  3476. }
  3477. if (rv != 0) {
  3478. fetch_last_error = w->m.error;
  3479. fetch_worker_release(w);
  3480. return -1;
  3481. }
  3482. *m = w->m;
  3483. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  3484. truncated, err, errcap);
  3485. fetch_worker_release(w);
  3486. if (rv >= 0 && (cancel_fetch || pending_action))
  3487. return FETCH_ABORT;
  3488. return rv;
  3489. }
  3490. static int fetch_worker_status(const struct fetch_worker *w)
  3491. {
  3492. return w->m.status;
  3493. }
  3494. /* fetch()/XHR through a helper: one request, the status and body come back
  3495. * whatever the HTTP status (a 401 is an answer, not a network error). */
  3496. static int js_worker_http(const char *method, const char *url,
  3497. const char *ctype, const char *body,
  3498. unsigned int body_len, struct js_http_resp *r,
  3499. char *err, int errcap)
  3500. {
  3501. struct fetch_worker *w = fetch_worker_alloc();
  3502. unsigned char *plain;
  3503. int rv, tr = 0;
  3504. if (!w) {
  3505. s_copy(err, "network busy", (unsigned int)errcap);
  3506. return -1;
  3507. }
  3508. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  3509. body_len, 0, 0, 0, 0, err,
  3510. (unsigned int)errcap) != 0) {
  3511. fetch_worker_release(w);
  3512. return -1;
  3513. }
  3514. fetch_wait_passive++;
  3515. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  3516. fetch_wait_passive--;
  3517. if (rv != 0) {
  3518. if (rv == FETCH_ABORT)
  3519. s_copy(err, "page is navigating", (unsigned int)errcap);
  3520. fetch_worker_release(w);
  3521. return -1;
  3522. }
  3523. r->status = w->m.status;
  3524. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  3525. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  3526. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  3527. if (!plain) {
  3528. fetch_worker_release(w);
  3529. s_copy(err, "out of memory", (unsigned int)errcap);
  3530. return -1;
  3531. }
  3532. if (w->m.len == 0) {
  3533. rv = 0; /* 204, an empty 200: no body file */
  3534. } else {
  3535. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  3536. image_io_buf, BR_PAGE_COMP_MAX,
  3537. &tr, err, (unsigned int)errcap);
  3538. }
  3539. fetch_worker_release(w);
  3540. if (rv < 0) {
  3541. free(plain);
  3542. return -1;
  3543. }
  3544. plain[rv] = '\0';
  3545. r->body = (char *)plain;
  3546. r->len = (unsigned int)rv;
  3547. return 0;
  3548. }
  3549. /* ---- HTTP / file fetch ---- */
  3550. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  3551. unsigned int *outlen, int *is_local, char *ctype,
  3552. unsigned int ctcap, char *final, unsigned int finalcap,
  3553. char *err, unsigned int errcap, int *truncated,
  3554. const char *post, unsigned int post_len)
  3555. {
  3556. unsigned char *buf;
  3557. unsigned int len;
  3558. int tr = 0;
  3559. int rv;
  3560. *out = 0;
  3561. *outlen = 0;
  3562. *truncated = 0;
  3563. if (final && finalcap)
  3564. final[0] = '\0';
  3565. if (ctype && ctcap)
  3566. ctype[0] = '\0';
  3567. if (url[0] == '/') {
  3568. char pathbuf[BR_URL_MAX];
  3569. const char *open_url = url;
  3570. unsigned int i = 0;
  3571. /* A local form GET keeps ?query in the address bar but the
  3572. * file lookup uses the path alone, like a real browser. */
  3573. while (url[i] && url[i] != '?' && url[i] != '#')
  3574. i++;
  3575. if (url[i]) {
  3576. s_copy(pathbuf, url, i + 1);
  3577. open_url = pathbuf;
  3578. }
  3579. buf = (unsigned char *)malloc(cap);
  3580. if (!buf) {
  3581. s_copy(err, "out of memory", errcap);
  3582. return -1;
  3583. }
  3584. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  3585. if (rv < 0) {
  3586. free(buf);
  3587. s_copy(err, "file not found", errcap);
  3588. return -1;
  3589. }
  3590. *out = buf;
  3591. *outlen = (unsigned int)rv;
  3592. *is_local = 1;
  3593. if (ctype)
  3594. s_copy(ctype, "text/html", ctcap);
  3595. if (final)
  3596. s_copy(final, url, finalcap);
  3597. if ((unsigned int)rv == cap)
  3598. *truncated = 1;
  3599. return 0;
  3600. }
  3601. buf = (unsigned char *)malloc(cap);
  3602. if (!buf) {
  3603. s_copy(err, "out of memory", errcap);
  3604. return -1;
  3605. }
  3606. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3607. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3608. if (rv == FETCH_ABORT) {
  3609. free(buf);
  3610. return FETCH_ABORT;
  3611. }
  3612. if (rv < 0) {
  3613. free(buf);
  3614. return -1;
  3615. }
  3616. len = (unsigned int)rv;
  3617. if (len == 0) {
  3618. free(buf);
  3619. s_copy(err, "empty response", errcap);
  3620. return -1;
  3621. }
  3622. if (ctype)
  3623. s_copy(ctype, fetch_meta.ctype, ctcap);
  3624. if (final && fetch_meta.final[0])
  3625. s_copy(final, fetch_meta.final, finalcap);
  3626. *is_local = 0;
  3627. *out = buf;
  3628. *outlen = len;
  3629. *truncated = tr;
  3630. return 0;
  3631. }
  3632. static unsigned int css_cache_hash(const char *s);
  3633. /* Remote fonts are cached under /share for the current boot like the
  3634. * stylesheets, as the raw response (a WOFF stays compressed). */
  3635. static int font_cache_count;
  3636. static void font_cache_path(const char *url, char *out, unsigned int cap)
  3637. {
  3638. unsigned int n = 0;
  3639. s_append(out, &n, "/share/" FONT_CACHE_PREFIX, cap);
  3640. s_append_dec(out, &n, css_cache_hash(url), cap);
  3641. }
  3642. static void font_cache_init(void)
  3643. {
  3644. struct sys_dirent d;
  3645. int i;
  3646. font_cache_count = 0;
  3647. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3648. (int)&d) == 1; i++)
  3649. if (starts_with(d.name, FONT_CACHE_PREFIX))
  3650. font_cache_count++;
  3651. }
  3652. /* Read one font file (local path, boot cache or network) into a fresh
  3653. * malloc'ed buffer. Returns its length, or -1. */
  3654. static int font_fetch(const char *abs, unsigned char **out)
  3655. {
  3656. unsigned char *buf;
  3657. char path[96];
  3658. int rv;
  3659. *out = 0;
  3660. buf = (unsigned char *)malloc(UFONT_MAX_FILE + 512u);
  3661. if (!buf)
  3662. return -1;
  3663. if (abs[0] == '/') {
  3664. struct sys_stat st;
  3665. /* FAT reads may write past the length: the 512 bytes of
  3666. * slack above cover the final partial sector. */
  3667. if (u_stat(abs, &st) != 0 || st.is_dir || st.size == 0 ||
  3668. st.size > UFONT_MAX_FILE) {
  3669. free(buf);
  3670. return -1;
  3671. }
  3672. rv = u_syscall3(SYS_READ_FILE, (int)abs, (int)buf,
  3673. (int)st.size);
  3674. if (rv != (int)st.size) {
  3675. free(buf);
  3676. return -1;
  3677. }
  3678. *out = buf;
  3679. return rv;
  3680. }
  3681. if (!is_http(abs)) {
  3682. free(buf);
  3683. return -1;
  3684. }
  3685. font_cache_path(abs, path, sizeof(path));
  3686. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)buf,
  3687. (int)UFONT_MAX_FILE);
  3688. if (rv > 0 && (unsigned int)rv < UFONT_MAX_FILE) {
  3689. *out = buf;
  3690. return rv;
  3691. }
  3692. {
  3693. char err[64];
  3694. int tr = 0;
  3695. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3696. UFONT_MAX_FILE, image_io_buf,
  3697. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err,
  3698. sizeof(err));
  3699. /* An error page is not a font: never parse or cache it. */
  3700. if (rv > 0 && !tr && fetch_meta.status >= 300) {
  3701. snprintf(err, sizeof(err), "HTTP %d", fetch_meta.status);
  3702. rv = 0;
  3703. }
  3704. if (rv <= 0 || tr) {
  3705. u_puts("[font] failed: ");
  3706. u_puts(abs);
  3707. u_puts(rv <= 0 ? " " : " truncated ");
  3708. u_puts(rv <= 0 ? err : "");
  3709. u_putc('\n');
  3710. free(buf);
  3711. return -1;
  3712. }
  3713. }
  3714. if (font_cache_count < FONT_CACHE_MAX &&
  3715. u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, rv) >= 0)
  3716. font_cache_count++;
  3717. *out = buf;
  3718. return rv;
  3719. }
  3720. /* Open one @font-face entry: fetch, unwrap WOFF, parse into the ufont
  3721. * arena. A WOFF2 or CFF (OTTO) file is reported and left unloaded. */
  3722. static struct ufont_face *font_open_entry(int id)
  3723. {
  3724. const char *url = br_font_face_url(id);
  3725. const char *base = br_font_face_base(id);
  3726. char abs[BR_URL_MAX];
  3727. unsigned char *buf, *sfnt;
  3728. unsigned int slen = 0;
  3729. struct ufont_face *f = 0;
  3730. const char *why = 0;
  3731. int n;
  3732. if (!url || !url[0] ||
  3733. resolve_link(base && base[0] ? base : page_url, url, abs,
  3734. sizeof(abs)) != 0)
  3735. return 0;
  3736. n = font_fetch(abs, &buf);
  3737. if (n <= 0)
  3738. return 0;
  3739. sfnt = buf;
  3740. slen = (unsigned int)n;
  3741. if (ufont_is_woff2(buf, slen)) {
  3742. why = "WOFF2 not supported";
  3743. } else if (ufont_is_woff(buf, slen)) {
  3744. sfnt = ufont_woff_decode(buf, slen, &slen);
  3745. if (!sfnt)
  3746. why = "bad WOFF";
  3747. }
  3748. if (!why) {
  3749. f = ufont_face_open_mem(sfnt, slen);
  3750. if (!f)
  3751. why = (slen >= 4 && sfnt[0] == 'O' && sfnt[1] == 'T' &&
  3752. sfnt[2] == 'T' && sfnt[3] == 'O') ?
  3753. "CFF outlines not supported" :
  3754. "not a TrueType font or arena full";
  3755. }
  3756. if (sfnt && sfnt != buf)
  3757. free(sfnt);
  3758. free(buf);
  3759. u_puts(f ? "[font] loaded " : "[font] skipped ");
  3760. u_puts(br_font_face_family(id));
  3761. u_puts(": ");
  3762. u_puts(abs);
  3763. if (why) {
  3764. u_puts(" (");
  3765. u_puts(why);
  3766. u_putc(')');
  3767. }
  3768. u_putc('\n');
  3769. return f;
  3770. }
  3771. /* Distance of a face from the requested weight: 0 inside its range. A
  3772. * bold request prefers heavier faces and a normal one lighter faces, as
  3773. * the CSS font-matching steps do. */
  3774. static unsigned int font_weight_dist(const struct br_font_face_info *fi,
  3775. unsigned int want)
  3776. {
  3777. if (want >= fi->wmin && want <= fi->wmax)
  3778. return 0;
  3779. if (want > fi->wmax)
  3780. return (want - fi->wmax) * 2u + (want >= 500 ? 1u : 0u);
  3781. return (fi->wmin - want) * 2u + (want < 500 ? 1u : 0u);
  3782. }
  3783. /* Load the @font-face entries a font-family declaration named: per family
  3784. * the regular face first, then bold, italic and the rest, so a full arena
  3785. * drops the least common variants. Then precompute, for every family and
  3786. * (bold, italic) combination, the loaded face CSS font matching picks;
  3787. * layout reads only that table. A family with no loaded face keeps
  3788. * font_pick 0, and its text uses the built-in set. */
  3789. static void load_font_faces(void)
  3790. {
  3791. int n = br_font_face_count(), pass, id;
  3792. memset(font_faces, 0, sizeof(font_faces));
  3793. memset(font_pick, 0, sizeof(font_pick));
  3794. if (n > BR_MAX_FACES)
  3795. n = BR_MAX_FACES;
  3796. for (pass = 0; pass < 4; pass++) {
  3797. for (id = 1; id <= n; id++) {
  3798. struct br_font_face_info fi;
  3799. int cls;
  3800. if (br_font_face_info(id, &fi) != 0 || !fi.used)
  3801. continue;
  3802. if (!fi.italic && fi.wmin <= 400 && fi.wmax >= 400)
  3803. cls = 0;
  3804. else if (!fi.italic && fi.wmin <= 700 &&
  3805. fi.wmax >= 700)
  3806. cls = 1;
  3807. else if (fi.italic && fi.wmin <= 400 &&
  3808. fi.wmax >= 400)
  3809. cls = 2;
  3810. else
  3811. cls = 3;
  3812. if (cls == pass)
  3813. font_faces[id - 1] = font_open_entry(id);
  3814. }
  3815. }
  3816. for (id = 1; id <= n; id++) {
  3817. struct br_font_face_info fam;
  3818. int combo;
  3819. if (br_font_face_info(id, &fam) != 0 || fam.family_id != id)
  3820. continue;
  3821. for (combo = 0; combo < 4; combo++) {
  3822. unsigned int want = (combo & 2) ? 700u : 400u;
  3823. int italic = combo & 1, k, best = 0;
  3824. unsigned int best_score = 0;
  3825. for (k = 1; k <= n; k++) {
  3826. struct br_font_face_info fi;
  3827. unsigned int score;
  3828. if (!font_faces[k - 1] ||
  3829. br_font_face_info(k, &fi) != 0 ||
  3830. fi.family_id != id)
  3831. continue;
  3832. score = font_weight_dist(&fi, want) +
  3833. ((fi.italic != 0) != (italic != 0) ?
  3834. 100000u : 0u);
  3835. if (!best || score < best_score) {
  3836. best = k;
  3837. best_score = score;
  3838. }
  3839. }
  3840. font_pick[id - 1][combo] = (unsigned char)best;
  3841. }
  3842. }
  3843. }
  3844. /* Remote scripts are cached under /share for the current boot, like the
  3845. * stylesheet cache, so reloads and later visits skip the network. */
  3846. static int script_cache_count;
  3847. static unsigned int script_cache_hash(const char *s)
  3848. {
  3849. unsigned int h = 2166136261u;
  3850. while (*s) {
  3851. h ^= (unsigned char)*s++;
  3852. h *= 16777619u;
  3853. }
  3854. return h;
  3855. }
  3856. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3857. {
  3858. unsigned int n = 0;
  3859. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3860. s_append_dec(out, &n, script_cache_hash(url), cap);
  3861. }
  3862. static void script_cache_clear(void)
  3863. {
  3864. struct sys_dirent d;
  3865. char path[96];
  3866. for (;;) {
  3867. int i, found = 0;
  3868. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3869. (int)&d) == 1; i++) {
  3870. unsigned int n = 0;
  3871. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3872. continue;
  3873. s_append(path, &n, "/share/", sizeof(path));
  3874. s_append(path, &n, d.name, sizeof(path));
  3875. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3876. return;
  3877. found = 1;
  3878. break;
  3879. }
  3880. if (!found)
  3881. break;
  3882. }
  3883. script_cache_count = 0;
  3884. }
  3885. static void script_cache_init(void)
  3886. {
  3887. struct sys_dirent d;
  3888. int i, count = 0;
  3889. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3890. (int)&d) == 1; i++)
  3891. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3892. count++;
  3893. if (count >= SCRIPT_CACHE_MAX) {
  3894. script_cache_clear();
  3895. return;
  3896. }
  3897. script_cache_count = count;
  3898. }
  3899. static int script_cache_get(const char *url, unsigned char **out,
  3900. unsigned int *outlen)
  3901. {
  3902. char path[96];
  3903. struct sys_stat st;
  3904. unsigned char *buf;
  3905. int rn;
  3906. script_cache_path(url, path, sizeof(path));
  3907. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3908. st.size >= SCRIPT_CACHE_FILE_MAX)
  3909. return 0;
  3910. buf = (unsigned char *)malloc(st.size + 1);
  3911. if (!buf)
  3912. return 0;
  3913. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3914. if (rn != (int)st.size) {
  3915. free(buf);
  3916. return 0;
  3917. }
  3918. buf[st.size] = '\0';
  3919. *out = buf;
  3920. *outlen = st.size;
  3921. return 1;
  3922. }
  3923. static void script_cache_put(const char *url, const unsigned char *data,
  3924. unsigned int len)
  3925. {
  3926. char path[96];
  3927. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3928. len >= SCRIPT_CACHE_FILE_MAX)
  3929. return;
  3930. script_cache_path(url, path, sizeof(path));
  3931. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3932. (int)len) >= 0)
  3933. script_cache_count++;
  3934. }
  3935. static int script_cache_has(const char *url)
  3936. {
  3937. char path[96];
  3938. struct sys_stat st;
  3939. script_cache_path(url, path, sizeof(path));
  3940. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3941. st.size < SCRIPT_CACHE_FILE_MAX;
  3942. }
  3943. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3944. static int fetch_script_text(const char *url, unsigned char **out,
  3945. unsigned int *outlen, char *err,
  3946. unsigned int errcap)
  3947. {
  3948. unsigned char *buf;
  3949. unsigned int len;
  3950. int local, truncated = 0;
  3951. char ctype[64], final[BR_URL_MAX];
  3952. int rv;
  3953. *out = 0;
  3954. *outlen = 0;
  3955. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3956. return 0;
  3957. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3958. sizeof(ctype), final, sizeof(final), err, errcap,
  3959. &truncated, 0, 0);
  3960. if (rv != 0)
  3961. return rv;
  3962. if (truncated || len >= BR_SCRIPT_MAX) {
  3963. free(buf);
  3964. s_copy(err, "script is too large", errcap);
  3965. return -1;
  3966. }
  3967. buf[len] = '\0';
  3968. if (!local)
  3969. script_cache_put(url, buf, len);
  3970. *out = buf;
  3971. *outlen = len;
  3972. return 0;
  3973. }
  3974. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  3975. * the heap, so images must not allocate their file body from it as well. */
  3976. static int fetch_image(const char *url, unsigned int cap,
  3977. unsigned char **out, unsigned int *outlen,
  3978. char *err, unsigned int errcap)
  3979. {
  3980. unsigned int len;
  3981. int tr = 0;
  3982. int rv;
  3983. *out = 0;
  3984. *outlen = 0;
  3985. if (cap > BR_IMG_FILE_MAX)
  3986. cap = BR_IMG_FILE_MAX;
  3987. if (url[0] == '/') {
  3988. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  3989. (int)cap);
  3990. if (rv < 0) {
  3991. s_copy(err, "file not found", errcap);
  3992. return -1;
  3993. }
  3994. *out = image_file_buf;
  3995. *outlen = (unsigned int)rv;
  3996. return 0;
  3997. }
  3998. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  3999. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  4000. if (rv == FETCH_ABORT)
  4001. return FETCH_ABORT;
  4002. if (rv < 0)
  4003. return -1;
  4004. len = (unsigned int)rv;
  4005. if (len == 0) {
  4006. s_copy(err, "empty image", errcap);
  4007. return -1;
  4008. }
  4009. *out = image_file_buf;
  4010. *outlen = len;
  4011. return 0;
  4012. }
  4013. /* Remote stylesheets are immutable enough for the current boot: keep
  4014. * successful responses under /share so a reload, a second visit or a fresh
  4015. * browser launch does not fetch the same five sheets over the network again.
  4016. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  4017. static int css_cache_count;
  4018. static unsigned int css_cache_hash(const char *s)
  4019. {
  4020. unsigned int h = 2166136261u;
  4021. while (*s) {
  4022. h ^= (unsigned char)*s++;
  4023. h *= 16777619u;
  4024. }
  4025. return h;
  4026. }
  4027. static void css_cache_path(const char *url, char *out, unsigned int cap)
  4028. {
  4029. unsigned int n = 0;
  4030. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  4031. s_append_dec(out, &n, css_cache_hash(url), cap);
  4032. }
  4033. static void css_cache_clear(void)
  4034. {
  4035. struct sys_dirent d;
  4036. char path[96];
  4037. for (;;) {
  4038. int i, found = 0;
  4039. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4040. (int)&d) == 1; i++) {
  4041. unsigned int n = 0;
  4042. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  4043. continue;
  4044. s_append(path, &n, "/share/", sizeof(path));
  4045. s_append(path, &n, d.name, sizeof(path));
  4046. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  4047. return;
  4048. found = 1;
  4049. break;
  4050. }
  4051. if (!found)
  4052. break;
  4053. }
  4054. css_cache_count = 0;
  4055. }
  4056. static void css_cache_init(void)
  4057. {
  4058. struct sys_dirent d;
  4059. int i, count = 0;
  4060. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4061. (int)&d) == 1; i++)
  4062. if (starts_with(d.name, CSS_CACHE_PREFIX))
  4063. count++;
  4064. if (count >= CSS_CACHE_MAX) {
  4065. css_cache_clear();
  4066. return;
  4067. }
  4068. css_cache_count = count;
  4069. }
  4070. static int css_cache_get(const char *url, unsigned char **out,
  4071. unsigned int *outlen)
  4072. {
  4073. char path[96];
  4074. int rn;
  4075. css_cache_path(url, path, sizeof(path));
  4076. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  4077. (int)CSS_CACHE_FILE_MAX);
  4078. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  4079. return 0;
  4080. *out = image_io_buf;
  4081. *outlen = (unsigned int)rn;
  4082. return 1;
  4083. }
  4084. static void css_cache_put(const char *url, const unsigned char *data,
  4085. unsigned int len)
  4086. {
  4087. char path[96];
  4088. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  4089. len >= CSS_CACHE_FILE_MAX)
  4090. return;
  4091. css_cache_path(url, path, sizeof(path));
  4092. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  4093. (int)len) >= 0)
  4094. css_cache_count++;
  4095. }
  4096. static int css_cache_has(const char *url)
  4097. {
  4098. char path[96];
  4099. struct sys_stat st;
  4100. css_cache_path(url, path, sizeof(path));
  4101. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  4102. st.size < CSS_CACHE_FILE_MAX;
  4103. }
  4104. /* Read one stylesheet into the shared static buffer. CSS is parsed
  4105. * immediately, so it does not need the page heap; this leaves the heap for
  4106. * the 2 MB page body, the rules and the scaled image bitmaps. */
  4107. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  4108. char *err, unsigned int errcap)
  4109. {
  4110. unsigned int len;
  4111. int tr = 0;
  4112. int rv;
  4113. *out = 0;
  4114. *outlen = 0;
  4115. if (url[0] == '/') {
  4116. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  4117. (int)BR_CSS_MAX);
  4118. if (rv < 0) {
  4119. s_copy(err, "stylesheet not found", errcap);
  4120. return -1;
  4121. }
  4122. *out = image_io_buf;
  4123. *outlen = (unsigned int)rv;
  4124. return 0;
  4125. }
  4126. if (css_cache_get(url, out, outlen))
  4127. return 0;
  4128. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  4129. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  4130. &fetch_meta, &tr, err, errcap);
  4131. if (rv == FETCH_ABORT)
  4132. return FETCH_ABORT;
  4133. if (rv < 0)
  4134. return -1;
  4135. len = (unsigned int)rv;
  4136. if (len == 0) {
  4137. s_copy(err, "empty stylesheet", errcap);
  4138. return -1;
  4139. }
  4140. *out = image_io_buf;
  4141. *outlen = len;
  4142. css_cache_put(url, image_io_buf, len);
  4143. return 0;
  4144. }
  4145. static void redraw_now(void);
  4146. static char error_page[1024];
  4147. static void show_error(const char *title, const char *detail)
  4148. {
  4149. char *page = error_page;
  4150. unsigned int n = 0;
  4151. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  4152. s_append(page, &n, title, sizeof(error_page));
  4153. s_append(page, &n, "</h2><p>", sizeof(error_page));
  4154. {
  4155. const char *p = detail;
  4156. while (*p && n + 1 < sizeof(error_page)) {
  4157. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  4158. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  4159. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  4160. else page[n++] = *p;
  4161. p++;
  4162. }
  4163. }
  4164. page[n] = '\0';
  4165. s_append(page, &n, "</p><p>", sizeof(error_page));
  4166. s_append(page, &n, page_url, sizeof(error_page));
  4167. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  4168. sizeof(error_page));
  4169. br_parse(&doc, page, n);
  4170. layout_valid = 0;
  4171. preload_active = 0;
  4172. preload_pending = 0;
  4173. preload_wait = 0;
  4174. fetch_workers_cancel_busy();
  4175. s_copy(page_title, title, sizeof(page_title));
  4176. page_loading = 0;
  4177. set_status(title, 1, 0);
  4178. ngui_invalidate(&ui);
  4179. }
  4180. static int decode_direct_image(const unsigned char *data, unsigned int len,
  4181. unsigned int node)
  4182. {
  4183. if (image_count >= BR_MAX_IMAGES)
  4184. return -1;
  4185. if (decode_image_data(data, len, &images[0], 0, 0, 0, 0) != 0)
  4186. return -1;
  4187. doc.nodes[node].img_index = 0;
  4188. image_count = 1;
  4189. return 0;
  4190. }
  4191. static int ancestor_is(unsigned int node, unsigned int tag)
  4192. {
  4193. unsigned int p = doc.nodes[node].parent;
  4194. while (p) {
  4195. if (doc.nodes[p].tag == tag)
  4196. return 1;
  4197. p = doc.nodes[p].parent;
  4198. }
  4199. return 0;
  4200. }
  4201. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  4202. * parallel but parsed in document order, so the cascade is unchanged. */
  4203. static int load_stylesheets(void)
  4204. {
  4205. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  4206. static unsigned char remote[BR_MAX_SHEETS];
  4207. struct fetch_worker *slot[BR_MAX_SHEETS];
  4208. unsigned int i, n = 0, next = 0, k;
  4209. char err[64];
  4210. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  4211. struct br_node *nd = &doc.nodes[i];
  4212. const char *rel, *href;
  4213. char url[BR_URL_MAX];
  4214. int dup = 0;
  4215. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  4216. continue;
  4217. rel = br_rel(&doc, i);
  4218. if (!contains_ci(rel, "stylesheet"))
  4219. continue;
  4220. href = br_href(&doc, i);
  4221. if (!href[0])
  4222. continue;
  4223. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  4224. continue;
  4225. for (k = 0; k < n; k++)
  4226. if (s_eq(urls[k], url)) {
  4227. dup = 1;
  4228. break;
  4229. }
  4230. if (dup)
  4231. continue;
  4232. s_copy(urls[n], url, BR_URL_MAX);
  4233. remote[n] = url[0] != '/' && !css_cache_has(url);
  4234. n++;
  4235. }
  4236. for (i = 0; i < BR_MAX_SHEETS; i++)
  4237. slot[i] = 0;
  4238. /* Start as many remote sheets as there are free workers. */
  4239. for (; next < n; next++) {
  4240. struct fetch_worker *w;
  4241. if (!remote[next])
  4242. continue;
  4243. w = fetch_worker_alloc();
  4244. if (!w)
  4245. break;
  4246. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  4247. err, sizeof(err)) != 0) {
  4248. fetch_worker_release(w);
  4249. remote[next] = 0;
  4250. continue;
  4251. }
  4252. slot[next] = w;
  4253. }
  4254. for (i = 0; i < n; i++) {
  4255. unsigned char *data = 0;
  4256. unsigned int len = 0;
  4257. int rv;
  4258. if (!remote[i]) {
  4259. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  4260. if (rv == FETCH_ABORT) {
  4261. fetch_workers_stop_all();
  4262. return FETCH_ABORT;
  4263. }
  4264. if (rv != 0 || !len)
  4265. continue;
  4266. } else {
  4267. struct fetch_worker *w = slot[i];
  4268. int tr = 0;
  4269. if (!w) {
  4270. w = fetch_worker_alloc();
  4271. if (!w) {
  4272. rv = -1;
  4273. goto css_failed;
  4274. }
  4275. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  4276. 0, 0, 0, 0, err,
  4277. sizeof(err)) != 0) {
  4278. fetch_worker_release(w);
  4279. remote[i] = 0;
  4280. if (i == next)
  4281. next++;
  4282. continue;
  4283. }
  4284. slot[i] = w;
  4285. if (i == next)
  4286. next++;
  4287. }
  4288. rv = fetch_worker_wait(w, err, sizeof(err));
  4289. if (rv == FETCH_ABORT) {
  4290. fetch_workers_stop_all();
  4291. return FETCH_ABORT;
  4292. }
  4293. if (rv == 0)
  4294. rv = fetch_worker_read_body(w, image_io_buf,
  4295. BR_CSS_MAX,
  4296. image_io_buf + BR_CSS_MAX,
  4297. BR_CSS_COMP_MAX, &tr,
  4298. err, sizeof(err));
  4299. else
  4300. rv = -1;
  4301. fetch_worker_release(w);
  4302. slot[i] = 0;
  4303. /* Refill the worker window before parsing this sheet. */
  4304. for (; next < n; next++) {
  4305. struct fetch_worker *nw;
  4306. if (!remote[next])
  4307. continue;
  4308. nw = fetch_worker_alloc();
  4309. if (!nw)
  4310. break;
  4311. if (fetch_worker_submit(nw, urls[next],
  4312. BR_CSS_MAX, 0, 0, 0, 0,
  4313. err, sizeof(err)) != 0) {
  4314. fetch_worker_release(nw);
  4315. remote[next] = 0;
  4316. continue;
  4317. }
  4318. slot[next] = nw;
  4319. }
  4320. css_failed:
  4321. if (rv <= 0) {
  4322. /* One synchronous retry: a dropped sheet leaves the
  4323. * whole page unstyled (seen intermittently on
  4324. * arstechnica's CDN). */
  4325. u_puts("[css] retry ");
  4326. u_puts(urls[i]);
  4327. u_puts(": ");
  4328. u_puts(err[0] ? err : "no worker/empty body");
  4329. u_putc('\n');
  4330. err[0] = '\0';
  4331. rv = fetch_css(urls[i], &data, &len, err,
  4332. sizeof(err));
  4333. if (rv == FETCH_ABORT) {
  4334. fetch_workers_stop_all();
  4335. return FETCH_ABORT;
  4336. }
  4337. if (rv != 0 || !len) {
  4338. u_puts("[css] failed: ");
  4339. u_puts(err);
  4340. u_putc('\n');
  4341. continue;
  4342. }
  4343. } else {
  4344. len = (unsigned int)rv;
  4345. data = image_io_buf;
  4346. css_cache_put(urls[i], data, len);
  4347. }
  4348. }
  4349. if (len) {
  4350. br_set_font_base(urls[i]);
  4351. br_parse_css_text(&doc, (const char *)data, len);
  4352. }
  4353. }
  4354. br_set_font_base(page_url);
  4355. br_parse_inline_css(&doc);
  4356. load_font_faces();
  4357. br_reset_styles(&doc);
  4358. layout_valid = 0;
  4359. return 0;
  4360. }
  4361. static void preload_begin(void)
  4362. {
  4363. preload_active = 1;
  4364. preload_pending = 0;
  4365. preload_wait = 1;
  4366. preload_max_jobs = FETCH_WORKERS;
  4367. preload_node = 0;
  4368. preload_loaded = 0;
  4369. preload_scroll = 0;
  4370. img_stat_start = u_ticks_ms();
  4371. img_stat_wall = 0;
  4372. img_stat_net = img_stat_open = img_stat_first = 0;
  4373. img_stat_io = img_stat_dec = img_stat_scale = 0;
  4374. img_stat_paint = img_stat_reflow = 0;
  4375. img_stat_bytes = 0;
  4376. img_stat_n = 0;
  4377. img_stat_log_len = 0;
  4378. if (img_stat_log[0])
  4379. img_stat_log[0] = '\0';
  4380. img_repaint_ms = 0;
  4381. img_repaint_pending = 0;
  4382. }
  4383. /* Styles are computed top-down during layout, but images inside a hidden
  4384. * menu/carousel are never visited and keep img_top == 0. Without this check
  4385. * the preloader walks the DOM in node order and spends the whole image
  4386. * budget on logos and off-canvas thumbnails the reader cannot see. */
  4387. static struct br_style base_style(void);
  4388. static int node_hidden(unsigned int node)
  4389. {
  4390. unsigned int path[32], n = 0, p = node, i;
  4391. struct br_style st, parent;
  4392. while (p && n < sizeof(path) / sizeof(path[0])) {
  4393. path[n++] = p;
  4394. p = doc.nodes[p].parent;
  4395. }
  4396. /* Node 0 is the <html> element when the page starts with one: it
  4397. * is an ancestor too. Styles are cached per node, so the chain
  4398. * must start from the same base as style_for_node(); seeding it
  4399. * with a zeroed style left <body> cached with black text and no
  4400. * line-height once an image job ran (docs.cloudron.io). */
  4401. if (!p && n && n < sizeof(path) / sizeof(path[0]) &&
  4402. doc.nodes[0].type == BR_NODE_ELEM &&
  4403. doc.nodes[0].tag == BR_TAG_HTML &&
  4404. !(doc.nodes[path[n - 1]].flags & BR_NODE_DETACHED))
  4405. path[n++] = 0;
  4406. parent = base_style();
  4407. for (i = n; i > 0; i--) {
  4408. br_style_for(&doc, path[i - 1], &parent, &st);
  4409. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  4410. st.opacity_hidden)
  4411. return 1;
  4412. parent = st;
  4413. }
  4414. return 0;
  4415. }
  4416. static struct br_style base_style(void);
  4417. static int style_width_px(const struct br_style *st, int base);
  4418. static int style_height_px(const struct br_style *st, int base);
  4419. static void style_for_node(unsigned int node, struct br_style *out)
  4420. {
  4421. unsigned int p = doc.nodes[node].parent;
  4422. struct br_style parent;
  4423. /* Parent index 0 is ambiguous: it is the <html> element when the page
  4424. * starts with one (see root_style()), but also the parent field of a
  4425. * detached subtree root. */
  4426. if (p || (node != 0 && doc.nodes[0].type == BR_NODE_ELEM &&
  4427. doc.nodes[0].tag == BR_TAG_HTML &&
  4428. !(doc.nodes[node].flags & BR_NODE_DETACHED))) {
  4429. style_for_node(p, &parent);
  4430. br_style_for(&doc, node, &parent, out);
  4431. } else {
  4432. parent = base_style();
  4433. br_style_for(&doc, node, &parent, out);
  4434. }
  4435. }
  4436. /* ---- parallel image preloading ---- *
  4437. *
  4438. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  4439. * preload_step() only starts jobs and harvests completed ones; the browser
  4440. * main loop keeps drawing between calls, instead of blocking on one fetch.
  4441. */
  4442. static int preload_active_jobs(void)
  4443. {
  4444. int i, n = 0;
  4445. for (i = 0; i < FETCH_WORKERS; i++)
  4446. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  4447. n++;
  4448. return n;
  4449. }
  4450. static void preload_job_error(struct fetch_worker *w)
  4451. {
  4452. if (w->node < doc.nnode) {
  4453. if (w->bg)
  4454. doc.nodes[w->node].bg_img_index = -2;
  4455. else
  4456. doc.nodes[w->node].img_index = -2;
  4457. image_repaint();
  4458. }
  4459. }
  4460. /* Is the image's box anywhere near the visible page? A decode below the
  4461. * fold changes the layout (scroll extent) but not a single on-screen pixel,
  4462. * so it does not need a repaint. top/h come from the last layout; treat an
  4463. * unknown box as visible to stay safe. */
  4464. static int image_preload_visible(unsigned int node, int bg)
  4465. {
  4466. int top, h, scroll;
  4467. if (node >= BR_MAX_NODES || node >= doc.nnode || page_rect.h <= 0)
  4468. return 1;
  4469. if (bg) {
  4470. top = (int)block_top[node];
  4471. h = (int)block_h[node];
  4472. } else {
  4473. top = (int)img_top[node];
  4474. h = (int)img_h[node];
  4475. }
  4476. if (!top && !h)
  4477. return 1;
  4478. scroll = (int)page_scroll.offset;
  4479. if (top > scroll + page_rect.h + 160)
  4480. return 0;
  4481. if (top + h + 160 < scroll)
  4482. return 0;
  4483. return 1;
  4484. }
  4485. /* Upper bounds for the bitmap an <img> will paint. Zero means "unbounded";
  4486. * decode_image_data applies one scale to both axes so the aspect ratio is
  4487. * preserved. This is what keeps a 1200x800 photo that CSS paints at 400 px
  4488. * from being decoded and box-filtered to the 1000 px layout cap first. */
  4489. static void image_fit_size(unsigned int node, int *out_w, int *out_h)
  4490. {
  4491. struct br_style st;
  4492. struct br_node *nd;
  4493. unsigned int p;
  4494. int cw, w = 0, h = 0;
  4495. *out_w = *out_h = 0;
  4496. if (node >= doc.nnode)
  4497. return;
  4498. nd = &doc.nodes[node];
  4499. style_for_node(node, &st);
  4500. cw = page_rect.w > 24 ? page_rect.w - 24 : 0;
  4501. p = doc.nodes[node].parent;
  4502. if (p && p < BR_MAX_NODES && layout_boxes[p].valid &&
  4503. layout_boxes[p].w > 0 && layout_boxes[p].w < cw)
  4504. cw = layout_boxes[p].w;
  4505. if (st.width_kind)
  4506. w = style_width_px(&st, cw);
  4507. else if (nd->width_attr)
  4508. w = nd->width_pct ? cw * (int)nd->width_attr / 100 :
  4509. (int)nd->width_attr;
  4510. if (st.height_kind)
  4511. h = style_height_px(&st, cw);
  4512. else if (nd->height_attr)
  4513. h = nd->height_pct ? cw * (int)nd->height_attr / 100 :
  4514. (int)nd->height_attr;
  4515. if (st.max_width_kind) {
  4516. int mw = st.max_width_kind == 3 ?
  4517. cw * st.max_width_calc_pct / 100 +
  4518. st.max_width_calc_px :
  4519. st.max_width_kind == 2 ?
  4520. cw * (int)st.max_width / 100 :
  4521. (int)st.max_width;
  4522. if (mw > 0 && (w == 0 || w > mw))
  4523. w = mw;
  4524. }
  4525. if (st.max_height_kind) {
  4526. int mh = st.max_height_kind == 3 ?
  4527. cw * st.max_height_calc_pct / 100 +
  4528. st.max_height_calc_px :
  4529. st.max_height_kind == 2 ?
  4530. cw * (int)st.max_height / 100 :
  4531. (int)st.max_height;
  4532. if (mh > 0 && (h == 0 || h > mh))
  4533. h = mh;
  4534. }
  4535. if (w > BR_IMG_LAYOUT_W)
  4536. w = BR_IMG_LAYOUT_W;
  4537. if (h > 4096)
  4538. h = 4096;
  4539. if (w < 0)
  4540. w = 0;
  4541. if (h < 0)
  4542. h = 0;
  4543. *out_w = w;
  4544. *out_h = h;
  4545. }
  4546. static void preload_accept_image(unsigned int node, int bg, const char *url)
  4547. {
  4548. /* An <img> bitmap only depends on its URL, so the next <img> with the
  4549. * same source reuses it (heise repeats one comment icon 85 times).
  4550. * Backgrounds are scaled to their box and are not shared. */
  4551. images[image_count].url_hash =
  4552. !bg && url ? script_cache_hash(url) | 1u : 0;
  4553. if (bg)
  4554. doc.nodes[node].bg_img_index = (short)image_count;
  4555. else
  4556. doc.nodes[node].img_index = (short)image_count;
  4557. image_count++;
  4558. preload_loaded++;
  4559. /* A background bitmap never changes its box, so keep the (expensive)
  4560. * measured layout and only repaint the pixels. */
  4561. if (bg)
  4562. page_cache_valid = 0;
  4563. else
  4564. layout_valid = 0;
  4565. if (image_preload_visible(node, bg))
  4566. image_repaint();
  4567. }
  4568. /* Install a bitmap decoded by the fetch helper. The helper already applied
  4569. * the display bounds (and the JPEG reduced IDCT), so this is a read + copy
  4570. * on the UI thread instead of a decode. */
  4571. static int preload_store_helper(unsigned int node, int bg,
  4572. unsigned char *px, unsigned int pxlen,
  4573. unsigned int dw, unsigned int dh,
  4574. int alpha, unsigned int nw, unsigned int nh,
  4575. const char *url)
  4576. {
  4577. struct br_image *bi;
  4578. unsigned int npx;
  4579. if (image_count >= BR_MAX_IMAGES || !px || !dw || !dh ||
  4580. dw > 4096 || dh > 4096) {
  4581. free(px);
  4582. return -1;
  4583. }
  4584. npx = dw * dh;
  4585. if (image_pixels + npx > BR_IMG_PIXEL_BUDGET ||
  4586. pxlen < npx * 2u + (alpha ? npx : 0)) {
  4587. free(px);
  4588. return -1;
  4589. }
  4590. bi = &images[image_count];
  4591. bi->img.format = 0;
  4592. bi->img.w = dw;
  4593. bi->img.h = dh;
  4594. bi->img.px = (unsigned short *)px;
  4595. bi->img.alpha = alpha ? px + npx * 2u : 0;
  4596. bi->img.flags = 0;
  4597. bi->native_w = nw ? (int)nw : (int)dw;
  4598. bi->native_h = nh ? (int)nh : (int)dh;
  4599. bi->state = 1;
  4600. image_pixels += npx;
  4601. preload_accept_image(node, bg, url);
  4602. return 0;
  4603. }
  4604. static void preload_decode(unsigned int node, int bg,
  4605. const unsigned char *data, unsigned int len,
  4606. const char *url)
  4607. {
  4608. int fit_w = 0, fit_h = 0;
  4609. if (image_count >= BR_MAX_IMAGES) {
  4610. if (bg)
  4611. doc.nodes[node].bg_img_index = -2;
  4612. else
  4613. doc.nodes[node].img_index = -2;
  4614. return;
  4615. }
  4616. if (!bg)
  4617. image_fit_size(node, &fit_w, &fit_h);
  4618. if (decode_image_data(data, len, &images[image_count],
  4619. bg && node < BR_MAX_NODES &&
  4620. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  4621. bg && node < BR_MAX_NODES &&
  4622. layout_boxes[node].valid ? layout_boxes[node].h : 0,
  4623. fit_w, fit_h) == 0) {
  4624. preload_accept_image(node, bg, url);
  4625. } else {
  4626. if (bg)
  4627. doc.nodes[node].bg_img_index = -2;
  4628. else
  4629. doc.nodes[node].img_index = -2;
  4630. layout_valid = 0;
  4631. }
  4632. if (image_preload_visible(node, bg))
  4633. image_repaint();
  4634. }
  4635. /* ---- data: URLs ----
  4636. *
  4637. * `data:[<type>][;base64],<payload>` decoded to bytes from the page heap
  4638. * (the caller frees them). The payload is percent-decoded, then base64-
  4639. * decoded when the header says so. Infima's menu chevron and many icon
  4640. * fonts' fallbacks are inline SVGs written this way. */
  4641. static int b64_val(int c)
  4642. {
  4643. if (c >= 'A' && c <= 'Z') return c - 'A';
  4644. if (c >= 'a' && c <= 'z') return c - 'a' + 26;
  4645. if (c >= '0' && c <= '9') return c - '0' + 52;
  4646. if (c == '+' || c == '-') return 62;
  4647. if (c == '/' || c == '_') return 63;
  4648. return -1;
  4649. }
  4650. static int hex_val(int c)
  4651. {
  4652. if (c >= '0' && c <= '9') return c - '0';
  4653. c |= 32;
  4654. if (c >= 'a' && c <= 'f') return c - 'a' + 10;
  4655. return -1;
  4656. }
  4657. static int data_url_decode(const char *url, unsigned char **out,
  4658. unsigned int *out_len)
  4659. {
  4660. const char *comma, *p;
  4661. unsigned int n = 0, len, i;
  4662. unsigned char *buf;
  4663. int base64 = 0;
  4664. *out = 0;
  4665. *out_len = 0;
  4666. if (!starts_with(url, "data:"))
  4667. return -1;
  4668. comma = url + 5;
  4669. while (*comma && *comma != ',')
  4670. comma++;
  4671. if (!*comma)
  4672. return -1;
  4673. for (p = url + 5; p + 7 <= comma; p++)
  4674. if (!strncmp(p, ";base64", 7))
  4675. base64 = 1;
  4676. len = s_len(comma + 1);
  4677. buf = (unsigned char *)malloc(len + 1);
  4678. if (!buf)
  4679. return -1;
  4680. for (i = 0, p = comma + 1; i < len; i++) {
  4681. int c = (unsigned char)p[i];
  4682. if (c == '%' && i + 2 < len &&
  4683. hex_val(p[i + 1]) >= 0 && hex_val(p[i + 2]) >= 0) {
  4684. c = hex_val(p[i + 1]) * 16 + hex_val(p[i + 2]);
  4685. i += 2;
  4686. }
  4687. buf[n++] = (unsigned char)c;
  4688. }
  4689. if (base64) {
  4690. unsigned int acc = 0, o = 0;
  4691. int bits = 0;
  4692. for (i = 0; i < n; i++) {
  4693. int v = b64_val(buf[i]);
  4694. if (v < 0)
  4695. continue; /* padding, whitespace */
  4696. acc = (acc << 6) | (unsigned int)v;
  4697. bits += 6;
  4698. if (bits >= 8) {
  4699. bits -= 8;
  4700. buf[o++] = (unsigned char)(acc >> bits);
  4701. }
  4702. }
  4703. n = o;
  4704. }
  4705. buf[n] = 0;
  4706. *out = buf;
  4707. *out_len = n;
  4708. return 0;
  4709. }
  4710. static unsigned int data_img_key(const char *url, int w, int h)
  4711. {
  4712. return (script_cache_hash(url) ^ ((unsigned int)w * 2654435761u) ^
  4713. ((unsigned int)h * 40503u)) | 1u;
  4714. }
  4715. /* The image index of a data: URL decoded for a w x h box (an SVG is
  4716. * rasterized at that size), decoding it on first use; -1 on failure.
  4717. * Decoded bitmaps are found again through url_hash, which is distinct
  4718. * from the <img> sharing hash because it mixes in the size. */
  4719. static int data_url_image(const char *url, int w, int h)
  4720. {
  4721. unsigned int key, len;
  4722. unsigned char *data;
  4723. int i;
  4724. if (!starts_with(url, "data:") || w <= 0 || h <= 0)
  4725. return -1;
  4726. key = data_img_key(url, w, h);
  4727. for (i = 0; i < image_count; i++)
  4728. if (images[i].state == 1 && images[i].url_hash == key)
  4729. return i;
  4730. for (i = 0; i < data_img_nfail; i++)
  4731. if (data_img_fail[i] == key)
  4732. return -1;
  4733. if (image_count < BR_MAX_IMAGES &&
  4734. data_url_decode(url, &data, &len) == 0) {
  4735. int r = decode_image_data(data, len, &images[image_count],
  4736. w, h, w, h);
  4737. free(data);
  4738. if (r == 0) {
  4739. images[image_count].url_hash = key;
  4740. return image_count++;
  4741. }
  4742. }
  4743. if (data_img_nfail < DATA_IMG_FAIL_MAX)
  4744. data_img_fail[data_img_nfail++] = key;
  4745. return -1;
  4746. }
  4747. /* A local file image bypasses the helpers: count its decode so a page opened
  4748. * from /share or /data still produces the same timing breakdown. */
  4749. static void img_stat_local(int before, unsigned int bytes, unsigned int io_ms)
  4750. {
  4751. img_stat_n++;
  4752. img_stat_bytes += bytes;
  4753. img_stat_io += io_ms;
  4754. if (image_count > before) {
  4755. struct br_image *bi = &images[image_count - 1];
  4756. img_stat_dec += img_last_dec_ms;
  4757. img_stat_scale += img_last_scale_ms;
  4758. if (img_stat_log_len + 100 < sizeof(img_stat_log)) {
  4759. unsigned int n = img_stat_log_len;
  4760. s_append(img_stat_log, &n, "local ", sizeof(img_stat_log));
  4761. s_append_dec(img_stat_log, &n, bytes,
  4762. sizeof(img_stat_log));
  4763. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4764. s_append_dec(img_stat_log, &n, img_last_dec_ms,
  4765. sizeof(img_stat_log));
  4766. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4767. s_append_dec(img_stat_log, &n, img_last_scale_ms,
  4768. sizeof(img_stat_log));
  4769. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4770. s_append_dec(img_stat_log, &n,
  4771. (unsigned int)bi->native_w,
  4772. sizeof(img_stat_log));
  4773. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4774. s_append_dec(img_stat_log, &n,
  4775. (unsigned int)bi->native_h,
  4776. sizeof(img_stat_log));
  4777. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4778. s_append_dec(img_stat_log, &n, bi->img.w,
  4779. sizeof(img_stat_log));
  4780. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4781. s_append_dec(img_stat_log, &n, bi->img.h,
  4782. sizeof(img_stat_log));
  4783. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4784. s_append_dec(img_stat_log, &n,
  4785. bi->img.alpha ? 1u : 0u,
  4786. sizeof(img_stat_log));
  4787. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4788. img_stat_log_len = n;
  4789. }
  4790. }
  4791. }
  4792. /* Harvest one completed worker. Returns 1 when a job was finished. */
  4793. static int preload_finish_worker(struct fetch_worker *w)
  4794. {
  4795. char err[64];
  4796. int rv, tr = 0;
  4797. unsigned int t0, io_ms;
  4798. int before;
  4799. int used_px = 0;
  4800. rv = fetch_worker_poll(w, err, sizeof(err));
  4801. if (rv < 0) {
  4802. /* A helper from an older pack does not understand the image
  4803. * decode request; retry once without it and decode in-process. */
  4804. if (w->image_job && w->dec_w && !w->dec_retried &&
  4805. fetch_worker_submit_req(w, w->url, BR_IMG_FILE_MAX,
  4806. 0, 0, 0, 0, w->node, w->bg,
  4807. 0, 0, err, sizeof(err)) == 0) {
  4808. w->image_job = 1;
  4809. w->dec_retried = 1;
  4810. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4811. return 0;
  4812. }
  4813. preload_job_error(w);
  4814. if (img_stat_log_len + 64 < sizeof(img_stat_log)) {
  4815. unsigned int n = img_stat_log_len;
  4816. char u[48];
  4817. s_copy(u, w->url, sizeof(u));
  4818. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4819. s_append(img_stat_log, &n, " error\n",
  4820. sizeof(img_stat_log));
  4821. img_stat_log_len = n;
  4822. }
  4823. img_stat_n++;
  4824. fetch_worker_release(w);
  4825. return 1;
  4826. }
  4827. if (rv == 0)
  4828. return 0;
  4829. t0 = u_ticks_ms();
  4830. rv = -1;
  4831. before = image_count;
  4832. if (w->m.px_len && !w->m.dec_err && w->m.dw && w->m.dh &&
  4833. w->m.px_len <= 8u * 1024u * 1024u) {
  4834. unsigned char *px = (unsigned char *)malloc(w->m.px_len);
  4835. int pr = -1;
  4836. if (px)
  4837. pr = u_syscall3(SYS_READ_FILE, (int)w->px, (int)px,
  4838. (int)w->m.px_len);
  4839. if (pr == (int)w->m.px_len) {
  4840. if (preload_store_helper(w->node, w->bg, px,
  4841. w->m.px_len, w->m.dw,
  4842. w->m.dh, (int)w->m.alpha,
  4843. w->m.nw, w->m.nh,
  4844. w->url) == 0) {
  4845. rv = (int)w->m.len;
  4846. img_last_dec_ms = w->m.dec_ms;
  4847. img_last_scale_ms = 0;
  4848. used_px = 1;
  4849. } else {
  4850. px = 0; /* the helper freed it */
  4851. }
  4852. }
  4853. if (px && !(pr == (int)w->m.px_len))
  4854. free(px);
  4855. }
  4856. io_ms = u_ticks_ms() - t0;
  4857. if (rv < 0) {
  4858. t0 = u_ticks_ms();
  4859. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  4860. image_comp_buf, BR_IMG_FILE_MAX,
  4861. &tr, err, sizeof(err));
  4862. io_ms += u_ticks_ms() - t0;
  4863. before = image_count;
  4864. if (rv >= 0)
  4865. preload_decode(w->node, w->bg, image_file_buf,
  4866. (unsigned int)rv, w->url);
  4867. else
  4868. preload_job_error(w);
  4869. }
  4870. img_stat_n++;
  4871. img_stat_net += w->m.total_ms;
  4872. img_stat_open += w->m.open_ms;
  4873. img_stat_first += w->m.first_ms;
  4874. img_stat_io += io_ms;
  4875. img_stat_bytes += rv > 0 ? (unsigned int)rv : 0;
  4876. img_stat_dec += w->m.dec_ms;
  4877. if (rv >= 0 && !used_px) {
  4878. img_stat_dec += img_last_dec_ms;
  4879. img_stat_scale += img_last_scale_ms;
  4880. }
  4881. if (img_stat_log_len + 160 < sizeof(img_stat_log)) {
  4882. unsigned int n = img_stat_log_len;
  4883. char u[48];
  4884. s_copy(u, w->url, sizeof(u));
  4885. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4886. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4887. s_append_dec(img_stat_log, &n,
  4888. rv > 0 ? (unsigned int)rv : 0,
  4889. sizeof(img_stat_log));
  4890. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4891. s_append_dec(img_stat_log, &n, w->m.open_ms,
  4892. sizeof(img_stat_log));
  4893. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4894. s_append_dec(img_stat_log, &n, w->m.first_ms,
  4895. sizeof(img_stat_log));
  4896. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4897. s_append_dec(img_stat_log, &n, w->m.total_ms,
  4898. sizeof(img_stat_log));
  4899. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4900. s_append_dec(img_stat_log, &n, io_ms, sizeof(img_stat_log));
  4901. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4902. s_append_dec(img_stat_log, &n,
  4903. rv >= 0 ? img_last_dec_ms : 0,
  4904. sizeof(img_stat_log));
  4905. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4906. s_append_dec(img_stat_log, &n,
  4907. rv >= 0 ? img_last_scale_ms : 0,
  4908. sizeof(img_stat_log));
  4909. if (image_count > before) {
  4910. struct br_image *bi = &images[image_count - 1];
  4911. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4912. s_append_dec(img_stat_log, &n,
  4913. (unsigned int)bi->native_w,
  4914. sizeof(img_stat_log));
  4915. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4916. s_append_dec(img_stat_log, &n,
  4917. (unsigned int)bi->native_h,
  4918. sizeof(img_stat_log));
  4919. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4920. s_append_dec(img_stat_log, &n, bi->img.w,
  4921. sizeof(img_stat_log));
  4922. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4923. s_append_dec(img_stat_log, &n, bi->img.h,
  4924. sizeof(img_stat_log));
  4925. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4926. s_append_dec(img_stat_log, &n,
  4927. bi->img.alpha ? 1u : 0u,
  4928. sizeof(img_stat_log));
  4929. }
  4930. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4931. img_stat_log_len = n;
  4932. }
  4933. fetch_worker_release(w);
  4934. return 1;
  4935. }
  4936. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  4937. * the number of jobs started. */
  4938. static int preload_fill_jobs(void)
  4939. {
  4940. int started = 0;
  4941. char err[64];
  4942. while (preload_active && preload_node < doc.nnode) {
  4943. unsigned int i = preload_node;
  4944. struct br_node *nd = &doc.nodes[i];
  4945. const char *src;
  4946. char url[BR_URL_MAX];
  4947. struct fetch_worker *w;
  4948. if (preload_active_jobs() >= preload_max_jobs)
  4949. break;
  4950. if (nd->type != BR_NODE_ELEM) {
  4951. preload_node++;
  4952. continue;
  4953. }
  4954. if (nd->tag != BR_TAG_IMG) {
  4955. if (nd->bg_img_index == -1) {
  4956. struct br_style bs;
  4957. style_for_node(i, &bs);
  4958. if (bs.display != BR_DISPLAY_NONE &&
  4959. !bs.vis_hidden && bs.bg_image) {
  4960. const char *bsrc =
  4961. br_bg_image_url(bs.bg_image - 1);
  4962. /* Lazy like <img>: a background box
  4963. * below the viewport (or not laid
  4964. * out yet) waits for the next scan. */
  4965. if (bsrc[0] &&
  4966. (!layout_boxes[i].valid ||
  4967. block_top[i] >
  4968. (unsigned int)(page_scroll.offset +
  4969. page_rect.h + 160))) {
  4970. preload_pending = 1;
  4971. preload_node++;
  4972. continue;
  4973. }
  4974. if (starts_with(bsrc, "data:")) {
  4975. /* Inline image: decode now,
  4976. * no fetch helper. */
  4977. unsigned char *data;
  4978. unsigned int len;
  4979. preload_node = i + 1;
  4980. if (data_url_decode(bsrc, &data,
  4981. &len) == 0) {
  4982. preload_decode(i, 1, data,
  4983. len, 0);
  4984. free(data);
  4985. } else {
  4986. nd->bg_img_index = -2;
  4987. }
  4988. continue;
  4989. }
  4990. if (bsrc[0] &&
  4991. resolve_link(page_url, bsrc, url,
  4992. sizeof(url)) == 0) {
  4993. if (image_count +
  4994. preload_active_jobs() >=
  4995. BR_MAX_IMAGES) {
  4996. preload_node = doc.nnode;
  4997. break;
  4998. }
  4999. if (url[0] == '/') {
  5000. unsigned char *data = 0;
  5001. unsigned int len = 0;
  5002. unsigned int t0;
  5003. int before;
  5004. preload_node = i + 1;
  5005. before = image_count;
  5006. t0 = u_ticks_ms();
  5007. if (fetch_image(url,
  5008. BR_IMG_FILE_MAX,
  5009. &data, &len,
  5010. err,
  5011. sizeof(err)) == 0) {
  5012. preload_decode(i, 1, data, len, 0);
  5013. img_stat_local(before, len,
  5014. u_ticks_ms() - t0);
  5015. } else {
  5016. nd->bg_img_index = -2;
  5017. }
  5018. continue;
  5019. }
  5020. w = fetch_worker_alloc();
  5021. if (!w)
  5022. return started;
  5023. preload_node = i + 1;
  5024. if (fetch_worker_submit(w, url,
  5025. BR_IMG_FILE_MAX,
  5026. 0, 0, i, 1,
  5027. err,
  5028. sizeof(err)) != 0) {
  5029. nd->bg_img_index = -2;
  5030. fetch_worker_release(w);
  5031. continue;
  5032. }
  5033. w->image_job = 1;
  5034. w->deadline = u_ticks_ms() +
  5035. BR_IMG_JOB_TIMEOUT_MS;
  5036. /* in flight: rescans skip it */
  5037. nd->bg_img_index = -3;
  5038. started++;
  5039. continue;
  5040. }
  5041. }
  5042. nd->bg_img_index = -2;
  5043. }
  5044. preload_node++;
  5045. continue;
  5046. }
  5047. if (nd->img_index != -1) {
  5048. preload_node++;
  5049. continue;
  5050. }
  5051. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  5052. preload_node++;
  5053. continue;
  5054. }
  5055. src = br_src(&doc, i);
  5056. if (starts_with(src, "data:")) {
  5057. unsigned char *data;
  5058. unsigned int len;
  5059. preload_node = i + 1;
  5060. if (data_url_decode(src, &data, &len) == 0) {
  5061. preload_decode(i, 0, data, len, 0);
  5062. free(data);
  5063. } else {
  5064. doc.nodes[i].img_index = -2;
  5065. }
  5066. continue;
  5067. }
  5068. if (!src[0]) {
  5069. preload_node++;
  5070. continue;
  5071. }
  5072. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  5073. preload_node++;
  5074. continue;
  5075. }
  5076. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  5077. preload_node = doc.nnode;
  5078. break;
  5079. }
  5080. /* Do not stop at the first below-fold image: DOM order is
  5081. * not visual order, and a footer/ad image early in the DOM
  5082. * used to hide every later article image from the loader. */
  5083. if (img_top[i] >
  5084. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  5085. preload_pending = 1;
  5086. preload_node++;
  5087. continue;
  5088. }
  5089. {
  5090. unsigned int uh = script_cache_hash(url) | 1u;
  5091. int k;
  5092. for (k = 0; k < image_count; k++)
  5093. if (images[k].state == 1 &&
  5094. images[k].url_hash == uh)
  5095. break;
  5096. if (k < image_count) {
  5097. nd->img_index = (short)k;
  5098. layout_valid = 0;
  5099. preload_node = i + 1;
  5100. image_repaint();
  5101. continue;
  5102. }
  5103. }
  5104. if (url[0] == '/') {
  5105. unsigned char *data = 0;
  5106. unsigned int len = 0;
  5107. unsigned int t0;
  5108. int before;
  5109. preload_node = i + 1;
  5110. before = image_count;
  5111. t0 = u_ticks_ms();
  5112. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  5113. err, sizeof(err)) == 0) {
  5114. preload_decode(i, 0, data, len, url);
  5115. img_stat_local(before, len, u_ticks_ms() - t0);
  5116. } else {
  5117. nd->img_index = -2;
  5118. }
  5119. continue;
  5120. }
  5121. w = fetch_worker_alloc();
  5122. if (!w)
  5123. return started;
  5124. preload_node = i + 1;
  5125. {
  5126. char msg[64];
  5127. unsigned int n = 0;
  5128. s_append(msg, &n, "Loading images ", sizeof(msg));
  5129. s_append_dec(msg, &n,
  5130. (unsigned int)preload_loaded + 1,
  5131. sizeof(msg));
  5132. s_append(msg, &n, "...", sizeof(msg));
  5133. set_status_quiet(msg);
  5134. image_repaint();
  5135. }
  5136. {
  5137. int fit_w = 0, fit_h = 0;
  5138. image_fit_size(i, &fit_w, &fit_h);
  5139. if (!fit_w)
  5140. fit_w = BR_IMG_LAYOUT_W;
  5141. if (fetch_worker_submit_image(w, url, BR_IMG_FILE_MAX,
  5142. i, 0,
  5143. (unsigned int)fit_w,
  5144. (unsigned int)fit_h,
  5145. err, sizeof(err)) != 0) {
  5146. nd->img_index = -2;
  5147. fetch_worker_release(w);
  5148. continue;
  5149. }
  5150. }
  5151. w->image_job = 1;
  5152. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  5153. nd->img_index = -3; /* in flight: rescans skip it */
  5154. started++;
  5155. }
  5156. return started;
  5157. }
  5158. /* Report where the image batch spent its time: status bar for the headline,
  5159. * /share/IMGSTAT for the per-image breakdown (cat it from a terminal). */
  5160. static void img_stats_report(void)
  5161. {
  5162. char msg[80];
  5163. static char out[BR_IMG_STAT_LOG + 512];
  5164. unsigned int n = 0, o = 0;
  5165. if (!img_stat_n)
  5166. return;
  5167. img_stat_wall = img_stat_start ?
  5168. u_ticks_ms() - img_stat_start : 1;
  5169. if (!img_stat_wall)
  5170. img_stat_wall = 1;
  5171. /* Compact on-screen form; /share/IMGSTAT has the full breakdown. */
  5172. s_append(msg, &n, "img ", sizeof(msg));
  5173. s_append_dec(msg, &n, (unsigned int)img_stat_n, sizeof(msg));
  5174. s_append(msg, &n, " ", sizeof(msg));
  5175. s_append_dec(msg, &n, img_stat_wall, sizeof(msg));
  5176. s_append(msg, &n, "ms net ", sizeof(msg));
  5177. s_append_dec(msg, &n, img_stat_net, sizeof(msg));
  5178. s_append(msg, &n, " dec ", sizeof(msg));
  5179. s_append_dec(msg, &n, img_stat_dec, sizeof(msg));
  5180. s_append(msg, &n, " sc ", sizeof(msg));
  5181. s_append_dec(msg, &n, img_stat_scale, sizeof(msg));
  5182. s_append(msg, &n, " paint ", sizeof(msg));
  5183. s_append_dec(msg, &n, img_stat_paint, sizeof(msg));
  5184. /* Keep the page's phase breakdown and append the image summary when
  5185. * it fits; never hide a JS error or a truncation notice. */
  5186. if (!post_status_error && !contains_ci(post_status_text, "truncated")) {
  5187. unsigned int plen = s_len(post_status_text);
  5188. if (!plen) {
  5189. s_copy(post_status_text, msg, sizeof(post_status_text));
  5190. } else if (plen + s_len(msg) + 4 < sizeof(post_status_text)) {
  5191. unsigned int pn = plen;
  5192. s_append(post_status_text, &pn, " | ",
  5193. sizeof(post_status_text));
  5194. s_append(post_status_text, &pn, msg,
  5195. sizeof(post_status_text));
  5196. } else {
  5197. s_copy(post_status_text, msg, sizeof(post_status_text));
  5198. }
  5199. post_status_ttl = 12000;
  5200. }
  5201. s_append(out, &o, "browser image stats\n", sizeof(out));
  5202. s_append(out, &o, "n=", sizeof(out));
  5203. s_append_dec(out, &o, (unsigned int)img_stat_n, sizeof(out));
  5204. s_append(out, &o, " wall=", sizeof(out));
  5205. s_append_dec(out, &o, img_stat_wall, sizeof(out));
  5206. s_append(out, &o, " net=", sizeof(out));
  5207. s_append_dec(out, &o, img_stat_net, sizeof(out));
  5208. s_append(out, &o, " open=", sizeof(out));
  5209. s_append_dec(out, &o, img_stat_open, sizeof(out));
  5210. s_append(out, &o, " first=", sizeof(out));
  5211. s_append_dec(out, &o, img_stat_first, sizeof(out));
  5212. s_append(out, &o, " io=", sizeof(out));
  5213. s_append_dec(out, &o, img_stat_io, sizeof(out));
  5214. s_append(out, &o, " dec=", sizeof(out));
  5215. s_append_dec(out, &o, img_stat_dec, sizeof(out));
  5216. s_append(out, &o, " scale=", sizeof(out));
  5217. s_append_dec(out, &o, img_stat_scale, sizeof(out));
  5218. s_append(out, &o, " paint=", sizeof(out));
  5219. s_append_dec(out, &o, img_stat_paint, sizeof(out));
  5220. s_append(out, &o, " reflow=", sizeof(out));
  5221. s_append_dec(out, &o, img_stat_reflow, sizeof(out));
  5222. s_append(out, &o, " bytes=", sizeof(out));
  5223. s_append_dec(out, &o, img_stat_bytes, sizeof(out));
  5224. s_append(out, &o, "\nurl bytes open first total io dec scale native bitmap\n",
  5225. sizeof(out));
  5226. s_append(out, &o, img_stat_log, sizeof(out));
  5227. u_syscall3(SYS_WRITE_FILE, (int)"/share/IMGSTAT", (int)out,
  5228. (int)s_len(out));
  5229. }
  5230. static void preload_step(void)
  5231. {
  5232. int i;
  5233. unsigned int t0;
  5234. if (!preload_active)
  5235. return;
  5236. if (cancel_fetch || pending_action) {
  5237. preload_active = 0;
  5238. preload_pending = 0;
  5239. fetch_workers_cancel_busy();
  5240. return;
  5241. }
  5242. preload_fill_jobs();
  5243. /* Decode completed images in a short batch instead of one per pass.
  5244. * A pass used to decode one image and then sleep 10 ms, so a page of
  5245. * small icons trickled in at the decode rate. The budget keeps a
  5246. * single huge JPEG from monopolising the UI while small images
  5247. * finish together. */
  5248. t0 = u_ticks_ms();
  5249. for (i = 0; i < FETCH_WORKERS; i++) {
  5250. if (!fetch_workers[i].busy)
  5251. continue;
  5252. if (preload_finish_worker(&fetch_workers[i]) &&
  5253. u_ticks_ms() - t0 >= BR_IMG_DECODE_BUDGET_MS)
  5254. break;
  5255. }
  5256. if (preload_active && preload_node >= doc.nnode &&
  5257. preload_active_jobs() == 0) {
  5258. preload_active = 0;
  5259. if (preload_pending)
  5260. preload_scroll = page_scroll.offset;
  5261. else
  5262. preload_pending = 0;
  5263. /* Keep the now idle helpers and their connections; a later
  5264. * navigation reuses them. They exit after ten idle seconds,
  5265. * and losing window focus stops them at once. */
  5266. if (img_repaint_pending) {
  5267. img_repaint_pending = 0;
  5268. ngui_invalidate(&ui);
  5269. }
  5270. img_stats_report();
  5271. set_status(post_status_text, post_status_error, post_status_ttl);
  5272. ngui_invalidate(&ui);
  5273. }
  5274. }
  5275. /* Set by navigate() when it turned a typed bare host into https://; the next
  5276. * load_page() consumes it and may retry over http. */
  5277. static int nav_https_upgraded;
  5278. /* Errors that mean "https is not served here" rather than "the site is
  5279. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  5280. static int https_fallback_error(int e)
  5281. {
  5282. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  5283. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  5284. e == UHTTP_ERR_RESET;
  5285. }
  5286. static void history_push(const char *url)
  5287. {
  5288. if (!url || !url[0])
  5289. return;
  5290. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  5291. s_eq(history[hist_pos], url))
  5292. return;
  5293. if (hist_len > 0 && hist_pos + 1 < hist_len)
  5294. hist_len = hist_pos + 1;
  5295. if (hist_len < BR_HISTORY) {
  5296. s_copy(history[hist_len], url, BR_URL_MAX);
  5297. hist_pos = hist_len;
  5298. hist_len++;
  5299. } else {
  5300. int i;
  5301. for (i = 1; i < BR_HISTORY; i++)
  5302. s_copy(history[i - 1], history[i], BR_URL_MAX);
  5303. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  5304. hist_pos = BR_HISTORY - 1;
  5305. }
  5306. }
  5307. static void load_page(const char *url, int local, int push)
  5308. {
  5309. unsigned char *body = 0;
  5310. unsigned int len = 0;
  5311. int truncated = 0;
  5312. struct img_info image_info;
  5313. char ctype[64];
  5314. char final[BR_URL_MAX];
  5315. char err[80];
  5316. const char *detail = 0;
  5317. const char *post = pending_post_is ? pending_post : 0;
  5318. unsigned int post_len = pending_post_len;
  5319. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  5320. /* Phase timings for the status line: where a slow load spends it. */
  5321. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  5322. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  5323. int upgraded = nav_https_upgraded;
  5324. int retried = 0;
  5325. int rv;
  5326. nav_https_upgraded = 0;
  5327. final[0] = '\0';
  5328. pending_post_len = 0;
  5329. pending_post_is = 0;
  5330. cancel_fetch = 0;
  5331. preload_active = 0;
  5332. preload_pending = 0;
  5333. fetch_workers_prepare_nav(url);
  5334. js_browser_stop();
  5335. js_last_status[0] = '\0';
  5336. js_last_error = 0;
  5337. heap_clear();
  5338. image_reset();
  5339. form_reset_state();
  5340. layout_valid = 0;
  5341. page_scroll.offset = 0;
  5342. page_scroll.dragging = 0;
  5343. page_title[0] = '\0';
  5344. page_loading = 1;
  5345. page_is_local = local;
  5346. s_copy(page_url, url, sizeof(page_url));
  5347. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5348. url_in.len = s_len(url_in.text);
  5349. url_in.cursor = url_in.len;
  5350. url_in.scroll = 0;
  5351. ngui_set_focus(&ui, 0);
  5352. if (final[0])
  5353. final[0] = '\0';
  5354. if (push)
  5355. history_push(url);
  5356. set_status("Loading...", 0, 0);
  5357. ngui_invalidate(&ui);
  5358. /* heap_clear() detaches the fonts, so attach them again before the
  5359. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  5360. if (heap_start() != 0) {
  5361. show_error("Out of memory", "Cannot allocate the page buffer");
  5362. return;
  5363. }
  5364. br_parse_plain(&doc, "", 0); /* blank while loading */
  5365. ngui_font_attach(&ui);
  5366. redraw_now();
  5367. browser_rules_alloc();
  5368. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5369. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  5370. &truncated, post, post_len);
  5371. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  5372. fetch_last_error == UHTTP_ERR_DNS) {
  5373. /* A busy previous page can leave the receiver ring full just
  5374. * long enough to lose a DNS reply. Tear the old helpers down
  5375. * and try once more before giving up. */
  5376. retried = 1;
  5377. fetch_workers_stop_all();
  5378. u_sleep_ms(500);
  5379. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5380. sizeof(ctype), final, sizeof(final), err,
  5381. sizeof(err), &truncated, post, post_len);
  5382. }
  5383. if (rv == FETCH_ABORT)
  5384. return;
  5385. t_fetch = u_ticks_ms() - t_start;
  5386. /* Capture the page timing before CSS/script/image fetches overwrite the
  5387. * shared fetch_meta block. */
  5388. if (rv == 0 && !local) {
  5389. page_open_ms = fetch_meta.open_ms;
  5390. page_first_ms = fetch_meta.first_ms;
  5391. page_total_ms = fetch_meta.total_ms;
  5392. }
  5393. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  5394. https_fallback_error(fetch_last_error)) {
  5395. char http_url[BR_URL_MAX];
  5396. unsigned int n = 0;
  5397. s_append(http_url, &n, "http://", sizeof(http_url));
  5398. s_append(http_url, &n, url + 8, sizeof(http_url));
  5399. /* Replace the https entry instead of adding a second one. */
  5400. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  5401. s_eq(history[hist_pos], url))
  5402. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  5403. load_page(http_url, 0, 0);
  5404. return;
  5405. }
  5406. if (rv != 0) {
  5407. detail = err;
  5408. show_error("Cannot load this page", detail);
  5409. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5410. url_in.len = s_len(url_in.text);
  5411. url_in.cursor = url_in.len;
  5412. url_in.scroll = 0;
  5413. return;
  5414. }
  5415. if (!local)
  5416. origin_cache_learn(url, final[0] ? final : url);
  5417. page_is_local = local;
  5418. if (final[0]) {
  5419. s_copy(page_url, final, sizeof(page_url));
  5420. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5421. url_in.len = s_len(url_in.text);
  5422. url_in.cursor = url_in.len;
  5423. url_in.scroll = 0;
  5424. }
  5425. if (contains_ci(ctype, "text/plain")) {
  5426. br_parse_plain(&doc, (const char *)body, len);
  5427. } else if (contains_ci(ctype, "image/") ||
  5428. (!contains_ci(ctype, "text/html") &&
  5429. img_sniff(body, len, &image_info) == 0)) {
  5430. unsigned int node = br_parse_image_doc(&doc, page_url);
  5431. if (node)
  5432. decode_direct_image(body, len, node);
  5433. s_copy(page_title, "Image", sizeof(page_title));
  5434. } else {
  5435. br_set_viewport(ui.w);
  5436. t_mark = u_ticks_ms();
  5437. br_parse(&doc, (const char *)body, len);
  5438. t_parse = u_ticks_ms() - t_mark;
  5439. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  5440. sizeof(page_title));
  5441. t_mark = u_ticks_ms();
  5442. if (load_stylesheets() == FETCH_ABORT)
  5443. return;
  5444. t_css = u_ticks_ms() - t_mark;
  5445. if (pending_action)
  5446. return;
  5447. }
  5448. preload_begin();
  5449. page_loading = 0;
  5450. hist_visit(page_url, page_title);
  5451. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5452. url_in.len = s_len(url_in.text);
  5453. url_in.cursor = url_in.len;
  5454. url_in.scroll = 0;
  5455. ngui_set_focus(&ui, 0);
  5456. /* Paint the parsed page before fetching/running scripts. A slow
  5457. * remote <script src> then does not hide the page behind the loading
  5458. * screen; the fetch helper pumps this UI while it waits. */
  5459. set_status("Loading scripts...", 0, 0);
  5460. t_mark = u_ticks_ms();
  5461. redraw_now();
  5462. t_paint = u_ticks_ms() - t_mark;
  5463. /* Start one image download before the scripts. The other workers
  5464. * fetch the external script bodies in parallel, and the remaining
  5465. * images start as soon as the script phase ends. */
  5466. preload_max_jobs = 1;
  5467. preload_fill_jobs();
  5468. preload_wait = 0;
  5469. t_mark = u_ticks_ms();
  5470. run_page_scripts();
  5471. t_js = u_ticks_ms() - t_mark;
  5472. preload_max_jobs = FETCH_WORKERS;
  5473. if (pending_action)
  5474. return;
  5475. post_status_text[0] = '\0';
  5476. post_status_error = 0;
  5477. post_status_ttl = 0;
  5478. if (js_last_status[0]) {
  5479. s_copy(post_status_text, js_last_status,
  5480. sizeof(post_status_text));
  5481. post_status_error = js_last_error;
  5482. post_status_ttl = 8000;
  5483. } else if (truncated) {
  5484. s_copy(post_status_text, "Page truncated at the buffer limit",
  5485. sizeof(post_status_text));
  5486. post_status_ttl = 6000;
  5487. } else if (doc.truncated) {
  5488. s_copy(post_status_text, "Page truncated by the parser",
  5489. sizeof(post_status_text));
  5490. post_status_ttl = 6000;
  5491. } else if (page_total_ms) {
  5492. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  5493. * paint 220, js 1750" -- the phases of this load. */
  5494. unsigned int n = 0;
  5495. static const char *const names[] = {
  5496. ", parse ", ", css ", ", paint ", ", js "
  5497. };
  5498. unsigned int vals[4];
  5499. int k;
  5500. vals[0] = t_parse;
  5501. vals[1] = t_css;
  5502. vals[2] = t_paint;
  5503. vals[3] = t_js;
  5504. (void)page_first_ms;
  5505. if (starts_with(page_url, "https://"))
  5506. s_append(post_status_text, &n,
  5507. "HTTPS (not verified), ",
  5508. sizeof(post_status_text));
  5509. s_append(post_status_text, &n, "Loaded in ",
  5510. sizeof(post_status_text));
  5511. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  5512. sizeof(post_status_text));
  5513. s_append(post_status_text, &n, " ms: page ",
  5514. sizeof(post_status_text));
  5515. s_append_dec(post_status_text, &n, t_fetch,
  5516. sizeof(post_status_text));
  5517. s_append(post_status_text, &n, " (headers ",
  5518. sizeof(post_status_text));
  5519. s_append_dec(post_status_text, &n, page_open_ms,
  5520. sizeof(post_status_text));
  5521. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  5522. for (k = 0; k < 4; k++) {
  5523. s_append(post_status_text, &n, names[k],
  5524. sizeof(post_status_text));
  5525. s_append_dec(post_status_text, &n, vals[k],
  5526. sizeof(post_status_text));
  5527. }
  5528. post_status_ttl = 12000;
  5529. } else if (starts_with(page_url, "https://")) {
  5530. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  5531. sizeof(post_status_text));
  5532. post_status_ttl = 6000;
  5533. }
  5534. set_status(post_status_text, post_status_error, post_status_ttl);
  5535. ngui_invalidate(&ui);
  5536. }
  5537. static void load_home(int push)
  5538. {
  5539. pending_post_len = 0;
  5540. pending_post_is = 0;
  5541. cancel_fetch = 0;
  5542. preload_active = 0;
  5543. preload_pending = 0;
  5544. js_browser_stop();
  5545. js_last_status[0] = '\0';
  5546. js_last_error = 0;
  5547. heap_clear();
  5548. image_reset();
  5549. form_reset_state();
  5550. layout_valid = 0;
  5551. page_scroll.offset = 0;
  5552. page_scroll.dragging = 0;
  5553. page_loading = 1;
  5554. page_is_local = 0;
  5555. s_copy(page_url, "about:home", sizeof(page_url));
  5556. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5557. url_in.len = s_len(url_in.text);
  5558. url_in.cursor = url_in.len;
  5559. url_in.scroll = 0;
  5560. ngui_set_focus(&ui, 0);
  5561. if (push)
  5562. history_push(page_url);
  5563. ngui_invalidate(&ui);
  5564. /* See load_page(): reattach the fonts before the first redraw. */
  5565. if (heap_start() != 0) {
  5566. show_error("Out of memory", "Cannot allocate the browser heap");
  5567. return;
  5568. }
  5569. br_parse_plain(&doc, "", 0);
  5570. ngui_font_attach(&ui);
  5571. redraw_now();
  5572. browser_rules_alloc();
  5573. {
  5574. static const char home[] =
  5575. "<html><head><title>NebOS Browser</title><style>"
  5576. "body { margin: 10px; color: #e4e6f0; }"
  5577. "h1 { color: #7fb0ff; }"
  5578. ".box { background-color: #262b3a; margin: 12px; "
  5579. "padding: 10px; }"
  5580. "a { color: #7fb0ff; }"
  5581. "pre { background-color: #32384a; }"
  5582. "</style></head><body>"
  5583. "<h1>NebOS Browser</h1>"
  5584. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  5585. "shared HTTP client and the image library.</p>"
  5586. "<div class=\"box\"><b>Try:</b>"
  5587. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  5588. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  5589. "<li><a href=\"/floppy1/JS.HTM\">/"
  5590. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  5591. "<li><a href=\"http://10.0.2.2:8000/\">"
  5592. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  5593. "<li><a href=\"https://example.com/\">"
  5594. "https://example.com/</a> (TLS, not verified)</li>"
  5595. "</ul></div>"
  5596. "<p>Type a URL in the bar above. Esc closes the "
  5597. "window, Ctrl+L focuses the address bar.</p>"
  5598. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  5599. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  5600. "</body></html>";
  5601. br_set_viewport(ui.w);
  5602. br_parse(&doc, home, sizeof(home) - 1);
  5603. br_parse_inline_css(&doc);
  5604. br_reset_styles(&doc);
  5605. s_copy(page_title, doc.title, sizeof(page_title));
  5606. }
  5607. post_status_text[0] = '\0';
  5608. post_status_error = 0;
  5609. post_status_ttl = 0;
  5610. page_loading = 0;
  5611. set_status("", 0, 0);
  5612. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5613. url_in.len = s_len(url_in.text);
  5614. url_in.cursor = url_in.len;
  5615. url_in.scroll = 0;
  5616. ngui_set_focus(&ui, 0);
  5617. ngui_invalidate(&ui);
  5618. }
  5619. /* Extensions the browser opens from the local filesystem. A dotted input
  5620. * with one of these still resolves relative to the cwd. */
  5621. static int local_file_ext(const char *s)
  5622. {
  5623. static const char *const exts[] = {
  5624. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  5625. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  5626. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  5627. "cfg", "conf", 0
  5628. };
  5629. unsigned int i = 0, start = 0, len = 0, e;
  5630. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  5631. s[i] != '#') {
  5632. if (s[i] == '.') {
  5633. start = i + 1;
  5634. len = 0;
  5635. } else if (start) {
  5636. len++;
  5637. }
  5638. i++;
  5639. }
  5640. if (!len)
  5641. return 0;
  5642. for (e = 0; exts[e]; e++) {
  5643. const char *x = exts[e];
  5644. unsigned int xn = s_len(x), k;
  5645. if (xn != len)
  5646. continue;
  5647. for (k = 0; k < len; k++) {
  5648. char a = s[start + k];
  5649. if (a >= 'A' && a <= 'Z')
  5650. a = (char)(a - 'A' + 'a');
  5651. if (a != x[k])
  5652. break;
  5653. }
  5654. if (k == len)
  5655. return 1;
  5656. }
  5657. return 0;
  5658. }
  5659. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  5660. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  5661. * Enter to the first network request. */
  5662. static int looks_like_host(const char *s)
  5663. {
  5664. unsigned int i = 0;
  5665. int dot = 0;
  5666. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  5667. s[i] != ':') {
  5668. char c = s[i];
  5669. if (c == '.') {
  5670. dot = 1;
  5671. } else if (!((c >= 'a' && c <= 'z') ||
  5672. (c >= 'A' && c <= 'Z') ||
  5673. (c >= '0' && c <= '9') ||
  5674. c == '-' || c == '_')) {
  5675. return 0;
  5676. }
  5677. i++;
  5678. }
  5679. return dot && i > 0 && !local_file_ext(s);
  5680. }
  5681. static void load_remote(const char *url, int push)
  5682. {
  5683. char canon[BR_URL_MAX];
  5684. s_copy(canon, url, sizeof(canon));
  5685. origin_cache_apply(canon, sizeof(canon));
  5686. load_page(canon, 0, push);
  5687. }
  5688. static void navigate(const char *input, int push)
  5689. {
  5690. char target[BR_URL_MAX];
  5691. char *t;
  5692. if (!input)
  5693. return;
  5694. s_copy(target, input, sizeof(target));
  5695. t = trim(target);
  5696. if (!t[0])
  5697. return;
  5698. if (s_eq(t, "about:home")) {
  5699. load_home(push);
  5700. return;
  5701. }
  5702. if (starts_with(t, "file://")) {
  5703. make_abs_local(t + 7, target, sizeof(target));
  5704. load_page(target, 1, push);
  5705. return;
  5706. }
  5707. if (is_http(t)) {
  5708. load_remote(t, push);
  5709. return;
  5710. }
  5711. if (t[0] == '/') {
  5712. make_abs_local(t, target, sizeof(target));
  5713. load_page(target, 1, push);
  5714. return;
  5715. }
  5716. if (!looks_like_host(t)) {
  5717. struct sys_stat st;
  5718. if (u_stat(t, &st) == 0 && !st.is_dir) {
  5719. make_abs_local(t, target, sizeof(target));
  5720. load_page(target, 1, push);
  5721. return;
  5722. }
  5723. }
  5724. {
  5725. /* A typed bare host tries https first: nearly every site
  5726. * redirects http -> https anyway, and that hop costs a whole
  5727. * extra connection. load_page() falls back to http when the
  5728. * https connection itself fails. */
  5729. char with_scheme[BR_URL_MAX];
  5730. unsigned int n = 0;
  5731. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  5732. s_append(with_scheme, &n, t, sizeof(with_scheme));
  5733. nav_https_upgraded = 1;
  5734. load_remote(with_scheme, push);
  5735. }
  5736. }
  5737. /* ---- layout ---- */
  5738. static struct ufont_face *face_for(unsigned int family, int bold, int italic)
  5739. {
  5740. unsigned int id;
  5741. if (!family || family > BR_MAX_FACES)
  5742. return 0;
  5743. id = font_pick[family - 1][(bold ? 2 : 0) | (italic ? 1 : 0)];
  5744. return id ? font_faces[id - 1] : 0;
  5745. }
  5746. static struct ufont_face *style_face(const struct br_style *st)
  5747. {
  5748. return st ? face_for(st->font_face, st->bold, st->italic) : 0;
  5749. }
  5750. static struct ufont_face *run_face(const struct lay_run *r)
  5751. {
  5752. return face_for(r->font_face, r->bold, r->italic);
  5753. }
  5754. static unsigned int face_text_width(struct ngui *gui,
  5755. const struct br_style *st,
  5756. const char *s, unsigned int n)
  5757. {
  5758. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  5759. st->bold, st->italic, st->mono);
  5760. }
  5761. static int face_line_height(struct ngui *gui, const struct br_style *st)
  5762. {
  5763. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  5764. st->mono);
  5765. }
  5766. static unsigned int run_text_width(struct ngui *gui,
  5767. const struct lay_run *r,
  5768. const char *s, unsigned int n)
  5769. {
  5770. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  5771. r->bold, r->italic, r->mono);
  5772. }
  5773. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  5774. {
  5775. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  5776. r->mono);
  5777. }
  5778. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  5779. {
  5780. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  5781. }
  5782. static struct br_style base_style(void)
  5783. {
  5784. struct br_style s = { 0 };
  5785. s.color = ui.theme.text;
  5786. s.bg = ui.theme.bg;
  5787. s.has_bg = 0;
  5788. for (int i = 0; i < 4; i++) {
  5789. s.border_c[i] = 0;
  5790. s.border_w[i] = 0;
  5791. s.border_s[i] = BR_BORDER_SOLID;
  5792. }
  5793. s.font_px = 16;
  5794. s.bold = 0;
  5795. s.italic = 0;
  5796. s.mono = 0;
  5797. s.underline = 0;
  5798. s.strike = 0;
  5799. s.overline = 0;
  5800. s.align = BR_ALIGN_LEFT;
  5801. s.display = BR_DISPLAY_BLOCK;
  5802. s.no_bullet = 0;
  5803. s.list_style = BR_LIST_AUTO;
  5804. s.uppercase = 0;
  5805. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  5806. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  5807. s.width = s.max_width = s.min_width = 0;
  5808. s.height = s.min_height = s.max_height = 0;
  5809. s.box_sizing = 0;
  5810. s.ml_auto = s.mr_auto = 0;
  5811. s.line_h_pct = 0;
  5812. s.line_h_px = 0;
  5813. s.mt = s.mb = s.ml = s.mr = 0;
  5814. s.pt = s.pb = s.pl = s.pr = 0;
  5815. return s;
  5816. }
  5817. /* The style node 0's children inherit. Node 0 is the first parsed node:
  5818. * a minified page that starts `<!doctype html><html ...>` makes it the
  5819. * <html> element itself, and the layout walks only its children, so its
  5820. * own cascade (html { color; font } -- Docusaurus/Infima put the page
  5821. * colour and font there) used to be skipped and the theme defaults showed
  5822. * through. Only inherited properties are taken: the root's box (margins,
  5823. * display, background) is not a container style for its children here. */
  5824. static struct br_style root_style(void)
  5825. {
  5826. struct br_style base = base_style(), st;
  5827. if (!doc.nnode || doc.nodes[doc.root].type != BR_NODE_ELEM ||
  5828. doc.nodes[doc.root].tag != BR_TAG_HTML)
  5829. return base;
  5830. br_style_for(&doc, doc.root, &base, &st);
  5831. base.color = st.color;
  5832. base.font_px = st.font_px;
  5833. base.bold = st.bold;
  5834. base.italic = st.italic;
  5835. base.mono = st.mono;
  5836. base.font_face = st.font_face;
  5837. base.align = st.align;
  5838. base.line_h_pct = st.line_h_pct;
  5839. base.line_h_px = st.line_h_px;
  5840. base.nowrap = st.nowrap;
  5841. base.uppercase = st.uppercase;
  5842. base.cursor = st.cursor;
  5843. base.vis_hidden = st.vis_hidden;
  5844. base.fill_mode = st.fill_mode;
  5845. base.fill = st.fill;
  5846. base.stroke_mode = st.stroke_mode;
  5847. base.stroke = st.stroke;
  5848. base.stroke_w = st.stroke_w;
  5849. base.fill_evenodd = st.fill_evenodd;
  5850. return base;
  5851. }
  5852. /* Resolve a margin/padding raw value. Percentages use the containing
  5853. * block width for all four sides, as CSS specifies. */
  5854. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  5855. {
  5856. if (unit == 1)
  5857. return base * v / 10000;
  5858. if (unit == 2)
  5859. return st->font_px * v / 100;
  5860. if (unit == 3)
  5861. return (int)br_root_font_px() * v / 100;
  5862. if (unit == 4)
  5863. return 0;
  5864. return v;
  5865. }
  5866. static int mp_px(const struct br_style *st, int side, int base)
  5867. {
  5868. int raw;
  5869. switch (side) {
  5870. case 0: raw = st->mt; break;
  5871. case 1: raw = st->mr; break;
  5872. case 2: raw = st->mb; break;
  5873. case 3: raw = st->ml; break;
  5874. case 4: raw = st->pt; break;
  5875. case 5: raw = st->pr; break;
  5876. case 6: raw = st->pb; break;
  5877. default: raw = st->pl; break;
  5878. }
  5879. if (st->mp_unit[side] == 5)
  5880. return base * raw / 100 + st->mp_calc_px[side];
  5881. return css_mp_px(st, raw, st->mp_unit[side], base);
  5882. }
  5883. static int style_width_px(const struct br_style *st, int base)
  5884. {
  5885. if (st->width_kind == 1)
  5886. return st->width;
  5887. if (st->width_kind == 2)
  5888. return base * (int)st->width / 100;
  5889. if (st->width_kind == 3)
  5890. return base * st->width_calc_pct / 100 + st->width_calc_px;
  5891. return 0;
  5892. }
  5893. static int style_height_px(const struct br_style *st, int base)
  5894. {
  5895. if (st->height_kind == 1)
  5896. return st->height;
  5897. if (st->height_kind == 2)
  5898. return base * (int)st->height / 100;
  5899. if (st->height_kind == 3)
  5900. return base * st->height_calc_pct / 100 + st->height_calc_px;
  5901. return 0;
  5902. }
  5903. static int css_size(unsigned char kind, int val, int base)
  5904. {
  5905. if (kind == 1)
  5906. return val;
  5907. if (kind == 2)
  5908. return base * val / 100;
  5909. return -1;
  5910. }
  5911. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  5912. int thick, int horizontal, unsigned short color,
  5913. unsigned char style)
  5914. {
  5915. int pos;
  5916. if (len <= 0 || thick <= 0)
  5917. return;
  5918. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  5919. if (horizontal)
  5920. ngui_fill_rect(ui, (struct ngui_rect){
  5921. x, y, len, thick}, color);
  5922. else
  5923. ngui_fill_rect(ui, (struct ngui_rect){
  5924. x, y, thick, len}, color);
  5925. return;
  5926. }
  5927. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  5928. int seg = len - pos;
  5929. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  5930. seg = style == BR_BORDER_DASHED ? 4 : 2;
  5931. if (horizontal)
  5932. ngui_fill_rect(ui, (struct ngui_rect){
  5933. x + pos, y, seg, thick}, color);
  5934. else
  5935. ngui_fill_rect(ui, (struct ngui_rect){
  5936. x, y + pos, thick, seg}, color);
  5937. }
  5938. }
  5939. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  5940. const struct br_style *st)
  5941. {
  5942. int top = st->border_w[0], right = st->border_w[1];
  5943. int bottom = st->border_w[2], left = st->border_w[3];
  5944. if (r.w <= 0 || r.h <= 0)
  5945. return;
  5946. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  5947. int i;
  5948. for (i = 0; i < 4; i++)
  5949. if (st->border_w[i] && !st->border_t[i]) {
  5950. ngui_fill_rect(ui, r, st->border_c[i]);
  5951. break;
  5952. }
  5953. return;
  5954. }
  5955. if (top && !st->border_t[0])
  5956. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  5957. st->border_c[0], st->border_s[0]);
  5958. if (bottom && !st->border_t[2])
  5959. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  5960. st->border_c[2], st->border_s[2]);
  5961. if (left && !st->border_t[3])
  5962. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  5963. left, 0, st->border_c[3], st->border_s[3]);
  5964. if (right && !st->border_t[1])
  5965. draw_border_side(ui, r.x + r.w - right, r.y + top,
  5966. r.h - top - bottom, right, 0,
  5967. st->border_c[1], st->border_s[1]);
  5968. }
  5969. static void transform_origin(const struct br_style *st, int w, int h,
  5970. int *ox, int *oy)
  5971. {
  5972. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  5973. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  5974. }
  5975. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  5976. unsigned int a)
  5977. {
  5978. unsigned int dr, dg, db, sr, sg, sb;
  5979. if (a >= 255)
  5980. return s;
  5981. dr = (d >> 11) & 31;
  5982. dg = (d >> 5) & 63;
  5983. db = d & 31;
  5984. sr = (s >> 11) & 31;
  5985. sg = (s >> 5) & 63;
  5986. sb = s & 31;
  5987. dr = (dr * (255 - a) + sr * a) / 255;
  5988. dg = (dg * (255 - a) + sg * a) / 255;
  5989. db = (db * (255 - a) + sb * a) / 255;
  5990. return (unsigned short)((dr << 11) | (dg << 5) | db);
  5991. }
  5992. /* Paint a solid box through scale()/rotate() around transform-origin. This
  5993. * transforms the element's own background box; text and descendants keep
  5994. * their layout (documented approximation). */
  5995. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  5996. unsigned short color,
  5997. const struct br_style *st)
  5998. {
  5999. double sx = st->scale_x / 100.0;
  6000. double sy = st->scale_y / 100.0;
  6001. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  6002. double c = cos(th), sn = sin(th);
  6003. int ox, oy, minx, miny, maxx, maxy, x, y;
  6004. double ax, ay;
  6005. double px[4], py[4];
  6006. int cx1, cy1, cx2, cy2, i;
  6007. if (sx == 0)
  6008. sx = 0.01;
  6009. if (sy == 0)
  6010. sy = 0.01;
  6011. transform_origin(st, box.w, box.h, &ox, &oy);
  6012. ax = box.x + ox;
  6013. ay = box.y + oy;
  6014. px[0] = -ox; py[0] = -oy;
  6015. px[1] = box.w - ox; py[1] = -oy;
  6016. px[2] = box.w - ox; py[2] = box.h - oy;
  6017. px[3] = -ox; py[3] = box.h - oy;
  6018. minx = miny = 1000000;
  6019. maxx = maxy = -1000000;
  6020. for (i = 0; i < 4; i++) {
  6021. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  6022. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  6023. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  6024. if (dx < minx) minx = dx;
  6025. if (dx > maxx) maxx = dx;
  6026. if (dy < miny) miny = dy;
  6027. if (dy > maxy) maxy = dy;
  6028. }
  6029. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  6030. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  6031. cx2 = page_rect.x + page_rect.w - 12;
  6032. cy2 = page_rect.y + page_rect.h;
  6033. if (cx2 > gui->w) cx2 = gui->w;
  6034. if (cy2 > gui->h) cy2 = gui->h;
  6035. if (minx < cx1) minx = cx1;
  6036. if (miny < cy1) miny = cy1;
  6037. if (maxx > cx2 - 1) maxx = cx2 - 1;
  6038. if (maxy > cy2 - 1) maxy = cy2 - 1;
  6039. for (y = miny; y <= maxy; y++) {
  6040. for (x = minx; x <= maxx; x++) {
  6041. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  6042. double rx = dx * c + dy * sn;
  6043. double ry = -dx * sn + dy * c;
  6044. double bx = rx / sx + ox;
  6045. double by = ry / sy + oy;
  6046. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  6047. gui->px[y * gui->w + x] = color;
  6048. }
  6049. }
  6050. }
  6051. static void draw_image_transformed(struct ngui *gui,
  6052. const struct img_image *im,
  6053. int x, int y, int w, int h,
  6054. int sx100, int sy100, int rot100,
  6055. int origin_x, int origin_y,
  6056. int origin_x_kind, int origin_y_kind)
  6057. {
  6058. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  6059. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  6060. double c = cos(th), sn = sin(th);
  6061. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  6062. double ax, ay;
  6063. double bx[4], by[4];
  6064. int cx1, cy1, cx2, cy2;
  6065. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  6066. return;
  6067. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  6068. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  6069. ax = x + ox;
  6070. ay = y + oy;
  6071. bx[0] = -ox; by[0] = -oy;
  6072. bx[1] = w - ox; by[1] = -oy;
  6073. bx[2] = w - ox; by[2] = h - oy;
  6074. bx[3] = -ox; by[3] = h - oy;
  6075. minx = miny = 1000000;
  6076. maxx = maxy = -1000000;
  6077. for (i = 0; i < 4; i++) {
  6078. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  6079. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  6080. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  6081. if (dx < minx) minx = dx;
  6082. if (dx > maxx) maxx = dx;
  6083. if (dy < miny) miny = dy;
  6084. if (dy > maxy) maxy = dy;
  6085. }
  6086. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  6087. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  6088. cx2 = page_rect.x + page_rect.w - 12;
  6089. cy2 = page_rect.y + page_rect.h;
  6090. if (cx2 > gui->w) cx2 = gui->w;
  6091. if (cy2 > gui->h) cy2 = gui->h;
  6092. if (minx < cx1) minx = cx1;
  6093. if (miny < cy1) miny = cy1;
  6094. if (maxx > cx2 - 1) maxx = cx2 - 1;
  6095. if (maxy > cy2 - 1) maxy = cy2 - 1;
  6096. for (py = miny; py <= maxy; py++) {
  6097. for (px = minx; px <= maxx; px++) {
  6098. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  6099. double rx = dx * c + dy * sn;
  6100. double ry = -dx * sn + dy * c;
  6101. double fx = rx / sx + ox;
  6102. double fy = ry / sy + oy;
  6103. int ix, iy;
  6104. unsigned int si, a;
  6105. unsigned short src;
  6106. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  6107. continue;
  6108. ix = (int)(fx * (double)im->w / w);
  6109. iy = (int)(fy * (double)im->h / h);
  6110. if (ix < 0 || ix >= (int)im->w ||
  6111. iy < 0 || iy >= (int)im->h)
  6112. continue;
  6113. si = (unsigned int)iy * im->w + (unsigned int)ix;
  6114. src = im->px[si];
  6115. a = im->alpha ? im->alpha[si] : 255;
  6116. gui->px[py * gui->w + px] =
  6117. a >= 255 ? src :
  6118. blend_rgb565(gui->px[py * gui->w + px],
  6119. src, a);
  6120. }
  6121. }
  6122. }
  6123. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  6124. unsigned int node, const struct br_style *st);
  6125. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  6126. * first and every pixel outside a corner's arc is restored afterwards. */
  6127. #define BG_ROUND_MAX 64
  6128. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  6129. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  6130. unsigned int node, const struct br_style *st,
  6131. int rtl, int rtr, int rbr, int rbl)
  6132. {
  6133. struct ngui *ui = l->ui;
  6134. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  6135. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  6136. if (ui->nclip > 0)
  6137. clip = ui->clip[ui->nclip - 1];
  6138. for (c = 0; c < 4; c++) {
  6139. if (r[c] > BG_ROUND_MAX)
  6140. r[c] = BG_ROUND_MAX;
  6141. if (r[c] > box.w / 2)
  6142. r[c] = box.w / 2;
  6143. if (r[c] > box.h / 2)
  6144. r[c] = box.h / 2;
  6145. }
  6146. for (c = 0; c < 4; c++) {
  6147. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  6148. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  6149. for (dy = 0; dy < r[c]; dy++)
  6150. for (dx = 0; dx < r[c]; dx++) {
  6151. int px = ox + dx, py = oy + dy;
  6152. if (px >= clip.x && py >= clip.y &&
  6153. px < clip.x + clip.w && py < clip.y + clip.h)
  6154. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  6155. ui->px[py * ui->w + px];
  6156. }
  6157. }
  6158. draw_bg_image(l, box, node, st);
  6159. for (c = 0; c < 4; c++) {
  6160. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  6161. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  6162. /* arc centre, in corner-square coordinates */
  6163. int cx = (c == 1 || c == 2) ? 0 : r[c];
  6164. int cy = (c >= 2) ? 0 : r[c];
  6165. for (dy = 0; dy < r[c]; dy++)
  6166. for (dx = 0; dx < r[c]; dx++) {
  6167. int px = ox + dx, py = oy + dy;
  6168. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  6169. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  6170. continue;
  6171. if (px >= clip.x && py >= clip.y &&
  6172. px < clip.x + clip.w && py < clip.y + clip.h)
  6173. ui->px[py * ui->w + px] =
  6174. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  6175. }
  6176. }
  6177. }
  6178. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  6179. unsigned int node, const struct br_style *st)
  6180. {
  6181. struct br_image *bi;
  6182. struct img_blit b;
  6183. int tw, th, x, y, rep_x, rep_y, posx, posy;
  6184. unsigned int scale = 65536;
  6185. int legacy, tiles = 0, rows = 0;
  6186. int cx1, cy1, cx2, cy2;
  6187. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  6188. return;
  6189. if (doc.nodes[node].bg_img_index < 0 ||
  6190. doc.nodes[node].bg_img_index >= image_count)
  6191. return;
  6192. bi = &images[doc.nodes[node].bg_img_index];
  6193. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  6194. return;
  6195. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  6196. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  6197. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  6198. if (legacy) {
  6199. scale = ((unsigned int)box.w << 16) / bi->img.w;
  6200. tw = box.w;
  6201. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6202. x = box.x;
  6203. y = box.y;
  6204. rep_x = rep_y = 0;
  6205. } else {
  6206. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  6207. unsigned int sx = ((unsigned int)box.w << 16) /
  6208. bi->img.w;
  6209. unsigned int sy = ((unsigned int)box.h << 16) /
  6210. bi->img.h;
  6211. scale = st->bg_size_kind == 3 ?
  6212. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  6213. } else if (st->bg_size_kind == 1 ||
  6214. st->bg_size_kind == 2) {
  6215. int w = st->bg_size_w;
  6216. int h = st->bg_size_h;
  6217. if (st->bg_size_kind == 2) {
  6218. if (w)
  6219. w = box.w * w / 100;
  6220. if (h)
  6221. h = box.h * h / 100;
  6222. }
  6223. if (w)
  6224. scale = ((unsigned int)w << 16) / bi->img.w;
  6225. else if (h)
  6226. scale = ((unsigned int)h << 16) / bi->img.h;
  6227. }
  6228. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  6229. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6230. if (tw < 1)
  6231. tw = 1;
  6232. if (th < 1)
  6233. th = 1;
  6234. posx = st->bg_pos_x_kind == 1 ?
  6235. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  6236. posy = st->bg_pos_y_kind == 1 ?
  6237. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  6238. x = box.x + posx;
  6239. y = box.y + posy;
  6240. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  6241. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  6242. if (rep_x) {
  6243. int m = (x - box.x) % tw;
  6244. if (m > 0)
  6245. m -= tw;
  6246. x = box.x + m;
  6247. }
  6248. if (rep_y) {
  6249. int m = (y - box.y) % th;
  6250. if (m > 0)
  6251. m -= th;
  6252. y = box.y + m;
  6253. }
  6254. }
  6255. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  6256. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  6257. cx2 = box.x + box.w;
  6258. cy2 = box.y + box.h;
  6259. if (cx2 > page_rect.x + page_rect.w - 12)
  6260. cx2 = page_rect.x + page_rect.w - 12;
  6261. if (cy2 > page_rect.y + page_rect.h)
  6262. cy2 = page_rect.y + page_rect.h;
  6263. if (cx1 >= cx2 || cy1 >= cy2)
  6264. return;
  6265. b.dst = l->ui->px;
  6266. b.dst_w = l->ui->w;
  6267. b.dst_h = l->ui->h;
  6268. b.clip_x = cx1;
  6269. b.clip_y = cy1;
  6270. b.clip_w = cx2 - cx1;
  6271. b.clip_h = cy2 - cy1;
  6272. b.bg = ui.theme.bg;
  6273. b.bg2 = ui.theme.bg;
  6274. b.dst_a = 0;
  6275. {
  6276. struct img_image *src = image_display_get(bi, tw, th);
  6277. int row_x;
  6278. if (!src)
  6279. src = &bi->img;
  6280. b.scale = ((unsigned int)tw << 16) / src->w;
  6281. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  6282. row_x = x;
  6283. for (;;) {
  6284. for (;;) {
  6285. b.x = x;
  6286. b.y = y;
  6287. img_draw(src, &b);
  6288. if (!rep_x || ++tiles > 512)
  6289. break;
  6290. x += tw;
  6291. if (x >= box.x + box.w)
  6292. break;
  6293. }
  6294. if (!rep_y || ++rows > 64)
  6295. break;
  6296. y += th;
  6297. if (y >= box.y + box.h)
  6298. break;
  6299. x = row_x;
  6300. }
  6301. }
  6302. }
  6303. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  6304. int *out_w, int *out_h);
  6305. static void svg_paint_box(struct ngui *ui, unsigned int node,
  6306. const struct br_style *st, int x, int y, int w,
  6307. int h);
  6308. /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
  6309. * RUN_SVG an inline <svg> icon (its node in off), RUN_PBOX an empty
  6310. * ::before/::after box with a background (Infima's menu chevrons). */
  6311. #define RUN_SVG (-3)
  6312. #define RUN_PBOX (-4)
  6313. static int run_width(const struct lay_run *r)
  6314. {
  6315. if (r->img >= 0)
  6316. return r->iw;
  6317. if (r->img == -2 || r->img == RUN_SVG || r->img == RUN_PBOX)
  6318. return r->iw;
  6319. return (int)r->w;
  6320. }
  6321. static void start_line(struct lay *l, const struct br_style *st)
  6322. {
  6323. (void)st;
  6324. if (l->nruns == 0) {
  6325. l->line_y = l->y;
  6326. l->line_h = 0;
  6327. }
  6328. l->line_left = l->left;
  6329. l->line_right = l->right;
  6330. if (l->float_active && l->line_y < l->float_bottom) {
  6331. if (l->float_left > l->line_left)
  6332. l->line_left = l->float_left;
  6333. if (l->float_right < l->line_right)
  6334. l->line_right = l->float_right;
  6335. }
  6336. if (l->line_right < l->line_left + 8)
  6337. l->line_right = l->line_left + 8;
  6338. l->line_x = l->line_left;
  6339. l->run_x = l->line_left;
  6340. }
  6341. static void flush_line(struct lay *l)
  6342. {
  6343. int total, x, i, vis;
  6344. if (!l->nruns && l->line_x == l->line_left) {
  6345. l->line_h = 0;
  6346. return;
  6347. }
  6348. total = l->line_x - l->line_left;
  6349. x = l->line_left;
  6350. vis = 1;
  6351. if (l->draw) {
  6352. int lh = l->line_h ? l->line_h : 16;
  6353. vis = l->line_y + lh >= page_rect.y &&
  6354. l->line_y <= page_rect.y + page_rect.h;
  6355. }
  6356. if (l->align == BR_ALIGN_CENTER)
  6357. x += (l->line_right - l->line_left - total) / 2;
  6358. else if (l->align == BR_ALIGN_RIGHT)
  6359. x = l->line_right - total;
  6360. if (x < l->line_left)
  6361. x = l->line_left;
  6362. for (i = 0; i < l->nruns; i++) {
  6363. struct lay_run *r = &l->runs[i];
  6364. int w = run_width(r);
  6365. int ry = l->line_y + r->dy;
  6366. x += r->gap;
  6367. if (l->draw && vis) {
  6368. if (r->form) {
  6369. unsigned int node = r->form - 1;
  6370. struct form_state *fs = form_get(node, 1);
  6371. int hh = r->ih ? r->ih : 20;
  6372. int focused = form_focus == node;
  6373. int disabled = r->form_disabled;
  6374. unsigned short bg = l->ui->theme.panel_alt;
  6375. unsigned short fg = disabled ? 0x8410 : r->color;
  6376. struct ngui_rect box = {x, ry, w, hh};
  6377. if (r->form_kind == FORM_CHECKBOX ||
  6378. r->form_kind == FORM_RADIO) {
  6379. ngui_fill_rect(l->ui, box, bg);
  6380. ngui_frame(l->ui, box,
  6381. focused ? l->ui->theme.accent :
  6382. l->ui->theme.border);
  6383. if (fs && fs->checked) {
  6384. struct ngui_rect dot = {
  6385. x + 4, ry + 4,
  6386. w > 8 ? w - 8 : 1,
  6387. hh > 8 ? hh - 8 : 1
  6388. };
  6389. if (r->form_kind == FORM_RADIO)
  6390. ngui_fill_round_rect(
  6391. l->ui, dot, 4,
  6392. 4, 4, 4,
  6393. l->ui->theme.accent);
  6394. else
  6395. ngui_fill_rect(l->ui,
  6396. dot,
  6397. l->ui->theme.accent);
  6398. }
  6399. } else {
  6400. int editable =
  6401. r->form_kind == FORM_TEXT ||
  6402. r->form_kind == FORM_PASSWORD ||
  6403. r->form_kind == FORM_TEXTAREA;
  6404. int scroll = 0;
  6405. /* Editable fields draw the live value
  6406. * (r->lit is a short copy). */
  6407. static char shown[FORM_VALUE_MAX + 1];
  6408. const char *txt = r->lit;
  6409. unsigned int tl = s_len(r->lit);
  6410. if (editable && fs && fs->len) {
  6411. unsigned int k;
  6412. if (r->form_kind == FORM_PASSWORD) {
  6413. for (k = 0; k < fs->len; k++)
  6414. shown[k] = '*';
  6415. shown[k] = '\0';
  6416. txt = shown;
  6417. } else {
  6418. txt = fs->value;
  6419. }
  6420. tl = fs->len;
  6421. }
  6422. struct br_style fst;
  6423. int author, tx = x + 6, pr = 6;
  6424. style_for_node(node, &fst);
  6425. author = form_author_styled(&fst);
  6426. if (author) {
  6427. /* The page styled the control:
  6428. * its background, border, radius
  6429. * and text colour. */
  6430. form_paint_author(l->ui, box, &fst,
  6431. focused);
  6432. tx = x + fst.border_w[3] +
  6433. mp_px(&fst, 7, w);
  6434. pr = fst.border_w[1] +
  6435. mp_px(&fst, 5, w);
  6436. if (tx < x + 2 && !editable)
  6437. tx = x + 2;
  6438. if (!disabled)
  6439. fg = editable && fs &&
  6440. !fs->len ?
  6441. 0x8410 : fst.color;
  6442. if (!editable) {
  6443. int tw0 = (int)
  6444. run_text_width(l->ui,
  6445. r, txt, tl);
  6446. tx = x + (w - tw0) / 2;
  6447. }
  6448. } else {
  6449. /* The box is drawn in theme colours, so
  6450. * the text is too: the page's CSS colour
  6451. * (dark on a light page) would vanish on
  6452. * the dark field. */
  6453. if (!disabled)
  6454. fg = editable && fs && !fs->len ?
  6455. l->ui->theme.text_dim :
  6456. l->ui->theme.text;
  6457. ngui_fill_rect(l->ui, box, bg);
  6458. ngui_frame(l->ui, box,
  6459. focused ? l->ui->theme.accent :
  6460. l->ui->theme.border);
  6461. }
  6462. /* A value wider than the field shows its
  6463. * tail (where typing happens). */
  6464. if (editable && fs && fs->len &&
  6465. w > (tx - x) + pr) {
  6466. int tw = (int)run_text_width(l->ui,
  6467. r, txt, tl);
  6468. int room = w - (tx - x) - pr;
  6469. if (tw > room)
  6470. scroll = tw - room;
  6471. }
  6472. ngui_push_clip(l->ui, (struct ngui_rect){
  6473. x + 1, ry + 1,
  6474. w > 2 ? w - 2 : 1,
  6475. hh > 2 ? hh - 2 : 1 });
  6476. ngui_text_px_face(l->ui, run_face(r),
  6477. tx - scroll,
  6478. ry + (hh - r->font_px) / 2 - 1,
  6479. txt, tl, fg, r->font_px,
  6480. r->bold, r->italic, r->mono);
  6481. if (focused && fs && editable) {
  6482. int cw = 0;
  6483. if (fs->len && fs->caret)
  6484. cw = (int)run_text_width(
  6485. l->ui, r, txt,
  6486. fs->caret < fs->len ?
  6487. fs->caret : fs->len);
  6488. ngui_fill_rect(l->ui,
  6489. (struct ngui_rect){
  6490. tx + cw - scroll,
  6491. ry + 4, 1,
  6492. hh > 8 ? hh - 8 : 1
  6493. },
  6494. l->ui->theme.accent);
  6495. }
  6496. ngui_pop_clip(l->ui);
  6497. if (r->form_kind == FORM_SELECT) {
  6498. ngui_text_px(l->ui, x + w - 12,
  6499. ry + 2, "v", 1, fg,
  6500. r->font_px, 0, 0, 0);
  6501. }
  6502. }
  6503. } else if (r->img == RUN_PBOX) {
  6504. struct ngui_rect bx = { x, ry, w, r->ih };
  6505. ngui_push_clip(l->ui, bx);
  6506. if (r->pb_has_bg)
  6507. ngui_fill_rect(l->ui, bx, r->pb_bg);
  6508. if (r->pb_img >= 0 && r->pb_img < image_count &&
  6509. images[r->pb_img].state == 1) {
  6510. /* Rotate about the box centre: the
  6511. * image is centred in it here. */
  6512. draw_image_transformed(l->ui,
  6513. &images[r->pb_img].img,
  6514. x + r->pb_x, ry + r->pb_y,
  6515. r->pb_w, r->pb_h,
  6516. r->transform_scale ?
  6517. r->scale_x : 100,
  6518. r->transform_scale ?
  6519. r->scale_y : 100,
  6520. r->transform_scale ?
  6521. r->rotate_x100 : 0,
  6522. 50, 50, 1, 1);
  6523. }
  6524. ngui_pop_clip(l->ui);
  6525. } else if (r->img == RUN_SVG) {
  6526. struct br_style sst;
  6527. style_for_node(r->off, &sst);
  6528. svg_paint_box(l->ui, r->off, &sst, x, ry, w,
  6529. r->ih);
  6530. } else if (r->img == -2) {
  6531. int hh = r->ih ? r->ih : 20;
  6532. ngui_fill_rect(l->ui,
  6533. (struct ngui_rect){x, ry, w, hh},
  6534. l->ui->theme.panel_alt);
  6535. ngui_frame(l->ui,
  6536. (struct ngui_rect){x, ry, w, hh},
  6537. l->ui->theme.border);
  6538. ngui_text_px_face(l->ui, run_face(r),
  6539. x + 6, ry + 2, r->lit,
  6540. s_len(r->lit), r->color,
  6541. r->font_px, r->bold, r->italic,
  6542. r->mono);
  6543. } else if (r->img >= 0) {
  6544. struct br_image *bi = &images[r->img];
  6545. if (bi->state == 1 && r->transform_scale) {
  6546. draw_image_transformed(l->ui, &bi->img,
  6547. x, ry, r->iw, r->ih,
  6548. r->scale_x, r->scale_y,
  6549. r->rotate_x100, r->origin_x,
  6550. r->origin_y, r->origin_x_kind,
  6551. r->origin_y_kind);
  6552. } else if (bi->state == 1) {
  6553. struct img_image *src =
  6554. image_display_get(bi, r->iw, r->ih);
  6555. struct img_blit b;
  6556. if (!src)
  6557. src = &bi->img;
  6558. b.dst = l->ui->px;
  6559. b.dst_w = l->ui->w;
  6560. b.dst_h = l->ui->h;
  6561. b.clip_x = page_rect.x;
  6562. b.clip_y = page_rect.y;
  6563. b.clip_w = page_rect.w - 12;
  6564. b.clip_h = page_rect.h;
  6565. b.x = x;
  6566. b.y = ry;
  6567. b.scale = ((unsigned int)r->iw << 16) /
  6568. src->w;
  6569. b.bg = ui.theme.bg;
  6570. b.bg2 = ui.theme.bg;
  6571. b.dst_a = 0;
  6572. b.flags = src->alpha ?
  6573. IMG_BLIT_OVER_DST : 0;
  6574. img_draw(src, &b);
  6575. }
  6576. } else {
  6577. const char *s = r->has_lit ? r->lit :
  6578. doc.text + r->off;
  6579. unsigned int n = r->has_lit ? s_len(r->lit) :
  6580. r->len;
  6581. ngui_text_px_face(l->ui, run_face(r), x, ry,
  6582. s, n, r->color, r->font_px,
  6583. r->bold, r->italic, r->mono);
  6584. if (r->underline)
  6585. ngui_fill_rect(l->ui,
  6586. (struct ngui_rect){x,
  6587. ry + run_ascent(l->ui, r) + 2,
  6588. w, 1}, r->color);
  6589. if (r->strike)
  6590. ngui_fill_rect(l->ui,
  6591. (struct ngui_rect){x,
  6592. ry + run_ascent(l->ui, r) -
  6593. (r->font_px > 3 ?
  6594. r->font_px / 3 : 1),
  6595. w, 1}, r->color);
  6596. if (r->overline)
  6597. ngui_fill_rect(l->ui,
  6598. (struct ngui_rect){x, ry,
  6599. w, 1}, r->color);
  6600. }
  6601. if (r->form || r->href) {
  6602. if (nhits < HIT_MAX) {
  6603. struct hit *h = &hits[nhits];
  6604. unsigned int target = r->form ?
  6605. r->form - 1 : r->href;
  6606. int hh = (r->form || r->img >= 0 ||
  6607. r->img == RUN_SVG) ?
  6608. r->ih :
  6609. run_line_height(l->ui, r);
  6610. int merge = nhits > 0 &&
  6611. hits[nhits - 1].node == target &&
  6612. hits[nhits - 1].y == ry &&
  6613. hits[nhits - 1].h == hh &&
  6614. x <= hits[nhits - 1].x +
  6615. hits[nhits - 1].w + 2;
  6616. if (merge) {
  6617. struct hit *p = &hits[nhits - 1];
  6618. int end = x + w;
  6619. if (end > p->x + p->w)
  6620. p->w = end - p->x;
  6621. } else {
  6622. h->x = x;
  6623. h->y = ry;
  6624. h->w = w;
  6625. h->h = hh;
  6626. h->node = (unsigned short)target;
  6627. nhits++;
  6628. }
  6629. }
  6630. }
  6631. }
  6632. x += w;
  6633. }
  6634. l->y += l->line_h + 2;
  6635. if (l->float_active && l->y >= l->float_bottom)
  6636. l->float_active = 0;
  6637. l->nruns = 0;
  6638. l->line_x = l->left;
  6639. l->run_x = l->left;
  6640. l->line_left = l->left;
  6641. l->line_right = l->right;
  6642. l->line_h = 0;
  6643. l->space_pending = 0;
  6644. }
  6645. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  6646. const struct br_style *st, unsigned short href,
  6647. const char *lit)
  6648. {
  6649. unsigned int n = lit ? s_len(lit) : len;
  6650. const char *tp = lit ? lit : doc.text + off;
  6651. int w = (int)face_text_width(l->ui, st, tp, n);
  6652. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6653. flush_line(l);
  6654. if (l->nruns == 0) {
  6655. l->line_y = l->y;
  6656. l->line_h = 0;
  6657. start_line(l, st);
  6658. }
  6659. {
  6660. struct lay_run *r = &l->runs[l->nruns++];
  6661. int gap = l->line_x - l->run_x;
  6662. if (gap < 0)
  6663. gap = 0;
  6664. r->gap = (unsigned short)gap;
  6665. r->off = off;
  6666. r->len = len;
  6667. r->color = st->color;
  6668. r->href = href;
  6669. r->dy = 0;
  6670. r->has_lit = 0;
  6671. r->form = 0;
  6672. r->form_kind = 0;
  6673. r->form_disabled = 0;
  6674. r->lit[0] = '\0';
  6675. if (lit && lit[0]) {
  6676. unsigned int i;
  6677. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  6678. r->lit[i] = lit[i];
  6679. r->lit[i] = '\0';
  6680. r->has_lit = 1;
  6681. }
  6682. r->img = -1;
  6683. r->iw = r->ih = 0;
  6684. r->font_px = st->font_px;
  6685. r->bold = st->bold;
  6686. r->italic = st->italic;
  6687. r->mono = st->mono;
  6688. r->font_face = st->font_face;
  6689. /* A control with its own background is a button, not body copy;
  6690. * an inherited link underline would strike through the fill. */
  6691. r->underline = st->underline && !st->has_bg;
  6692. r->strike = st->strike && !st->has_bg;
  6693. r->overline = st->overline && !st->has_bg;
  6694. r->w = (unsigned short)w;
  6695. if (r->has_lit)
  6696. r->w = (unsigned short)run_text_width(
  6697. l->ui, r, r->lit, s_len(r->lit));
  6698. w = r->w;
  6699. }
  6700. l->line_x += w;
  6701. l->run_x = l->line_x;
  6702. {
  6703. int lh = face_line_height(l->ui, st);
  6704. if (st->line_h_px)
  6705. lh = st->line_h_px;
  6706. else if (st->line_h_pct)
  6707. lh = st->font_px * st->line_h_pct / 100;
  6708. if (lh < face_line_height(l->ui, st))
  6709. lh = face_line_height(l->ui, st);
  6710. if (l->line_h < lh)
  6711. l->line_h = lh;
  6712. }
  6713. }
  6714. static void add_image_run(struct lay *l, unsigned int node,
  6715. const struct br_style *st, unsigned short href)
  6716. {
  6717. struct br_image *bi = 0;
  6718. int idx = doc.nodes[node].img_index;
  6719. int dw, dh, maxw;
  6720. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  6721. bi = &images[idx];
  6722. if (l->nruns == 0)
  6723. start_line(l, st);
  6724. if (l->space_pending &&
  6725. (l->nruns > 0 || l->line_x > l->line_left)) {
  6726. int sp = (int)face_text_width(l->ui, st, " ", 1);
  6727. if (l->line_x + sp <= l->line_right)
  6728. l->line_x += sp;
  6729. }
  6730. l->space_pending = 0;
  6731. if (!bi) {
  6732. const char *alt = br_alt(&doc, node);
  6733. struct br_style gs = *st;
  6734. char tmp[96];
  6735. unsigned int n = 0;
  6736. int w;
  6737. gs.color = BR_GRAY;
  6738. gs.underline = 0;
  6739. s_append(tmp, &n, "[", sizeof(tmp));
  6740. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  6741. s_append(tmp, &n, "]", sizeof(tmp));
  6742. w = (int)face_text_width(l->ui, &gs, tmp, n);
  6743. if (l->line_x + w > l->line_right &&
  6744. (l->nruns > 0 || l->line_x > l->line_left))
  6745. flush_line(l);
  6746. add_run(l, 0, 0, &gs, href, tmp);
  6747. if (!l->draw) {
  6748. int t = l->line_y < 0 ? 0 : l->line_y;
  6749. int hh = face_line_height(l->ui, &gs);
  6750. if (t > 65535)
  6751. t = 65535;
  6752. if (hh > 65535)
  6753. hh = 65535;
  6754. img_top[node] = (unsigned short)t;
  6755. img_h[node] = (unsigned short)hh;
  6756. }
  6757. return;
  6758. }
  6759. maxw = l->line_right - l->line_left;
  6760. if (maxw < 8)
  6761. maxw = 8;
  6762. {
  6763. int iw = bi->native_w, ih = bi->native_h;
  6764. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  6765. if (iw <= 0 || ih <= 0) {
  6766. iw = (int)bi->img.w;
  6767. ih = (int)bi->img.h;
  6768. }
  6769. dw = iw;
  6770. dh = ih;
  6771. if (doc.nodes[node].width_attr) {
  6772. int want = doc.nodes[node].width_attr;
  6773. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  6774. have_w = 1;
  6775. }
  6776. if (doc.nodes[node].height_attr) {
  6777. int want = doc.nodes[node].height_attr;
  6778. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  6779. have_h = 1;
  6780. }
  6781. if (have_w && !have_h)
  6782. dh = ih ? ih * dw / iw : 0;
  6783. if (have_h && !have_w)
  6784. dw = iw ? iw * dh / ih : 0;
  6785. if (st->width_kind) {
  6786. css_w = 1;
  6787. if (st->width_kind == 3)
  6788. dw = maxw * st->width_calc_pct / 100 +
  6789. st->width_calc_px;
  6790. else
  6791. dw = st->width_kind == 2 ?
  6792. maxw * (int)st->width / 100 :
  6793. (int)st->width;
  6794. }
  6795. /* Percentage heights resolve against the containing block's
  6796. * definite height (Docusaurus' logo: `.navbar__logo { height:
  6797. * 2rem }` holding an `img { height: 100% }`), and are auto
  6798. * when it has none; they used to use the width. */
  6799. if (st->height_kind == 1 ||
  6800. ((st->height_kind == 2 || st->height_kind == 3) &&
  6801. l->cb_h > 0)) {
  6802. css_h = 1;
  6803. if (st->height_kind == 3)
  6804. dh = l->cb_h * st->height_calc_pct / 100 +
  6805. st->height_calc_px;
  6806. else
  6807. dh = st->height_kind == 2 ?
  6808. l->cb_h * (int)st->height / 100 :
  6809. (int)st->height;
  6810. }
  6811. if (css_w && !css_h)
  6812. dh = ih ? ih * dw / iw : 0;
  6813. if (css_h && !css_w)
  6814. dw = iw ? iw * dh / ih : 0;
  6815. if (st->max_width_kind) {
  6816. int mw = st->max_width_kind == 3 ?
  6817. maxw * st->max_width_calc_pct / 100 +
  6818. st->max_width_calc_px :
  6819. st->max_width_kind == 2 ?
  6820. maxw * (int)st->max_width / 100 :
  6821. (int)st->max_width;
  6822. if (mw > 0 && dw > mw) {
  6823. dh = iw ? ih * mw / iw : 0;
  6824. dw = mw;
  6825. }
  6826. }
  6827. }
  6828. if (dw < 8)
  6829. dw = 8;
  6830. if (dh < 8)
  6831. dh = 8;
  6832. if (dw > maxw) {
  6833. dh = dw ? dh * maxw / dw : dh;
  6834. dw = maxw;
  6835. }
  6836. if (!l->draw) {
  6837. int t = l->line_y < 0 ? 0 : l->line_y;
  6838. if (t > 65535)
  6839. t = 65535;
  6840. if (dh > 65535)
  6841. dh = 65535;
  6842. img_top[node] = (unsigned short)t;
  6843. img_h[node] = (unsigned short)dh;
  6844. }
  6845. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  6846. l->line_x > l->line_left))
  6847. flush_line(l);
  6848. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6849. flush_line(l);
  6850. if (l->nruns == 0) {
  6851. l->line_y = l->y;
  6852. l->line_h = 0;
  6853. start_line(l, st);
  6854. }
  6855. {
  6856. struct lay_run *r = &l->runs[l->nruns++];
  6857. int gap = l->line_x - l->run_x;
  6858. if (gap < 0)
  6859. gap = 0;
  6860. r->gap = (unsigned short)gap;
  6861. r->off = 0;
  6862. r->len = 0;
  6863. r->color = 0;
  6864. r->href = href;
  6865. r->form = 0;
  6866. r->form_kind = 0;
  6867. r->form_disabled = 0;
  6868. /* Inline replaced elements honour their vertical margins; this
  6869. * is how Bootstrap's negative logo margins centre the wordmark. */
  6870. {
  6871. int idy = mp_px(st, 0, l->right - l->left);
  6872. if (idy < -2048)
  6873. idy = -2048;
  6874. if (idy > 2048)
  6875. idy = 2048;
  6876. r->dy = (signed short)idy;
  6877. }
  6878. r->has_lit = 0;
  6879. r->lit[0] = '\0';
  6880. r->img = (short)idx;
  6881. r->iw = (unsigned short)dw;
  6882. r->ih = (unsigned short)dh;
  6883. r->w = (unsigned short)dw;
  6884. r->font_px = st->font_px;
  6885. r->bold = st->bold;
  6886. r->italic = st->italic;
  6887. r->mono = st->mono;
  6888. r->font_face = st->font_face;
  6889. r->transform_scale = st->transform_scale;
  6890. r->scale_x = st->scale_x;
  6891. r->scale_y = st->scale_y;
  6892. r->rotate_x100 = st->rotate_x100;
  6893. r->origin_x = st->origin_x;
  6894. r->origin_y = st->origin_y;
  6895. r->origin_x_kind = st->origin_x_kind;
  6896. r->origin_y_kind = st->origin_y_kind;
  6897. r->underline = 0;
  6898. }
  6899. if (node < BR_MAX_NODES) {
  6900. layout_boxes[node].x = l->line_x;
  6901. layout_boxes[node].y = l->line_y +
  6902. mp_px(st, 0, l->right - l->left);
  6903. layout_boxes[node].w = dw;
  6904. layout_boxes[node].h = dh;
  6905. layout_boxes[node].valid = 1;
  6906. }
  6907. l->line_x += dw;
  6908. l->run_x = l->line_x;
  6909. if (l->line_h < dh)
  6910. l->line_h = dh;
  6911. }
  6912. /* An inline (or inline-block) <svg> is a replaced element in the text
  6913. * line, like an <img>: comment bubbles and arrows sit next to their label
  6914. * instead of starting a block of their own. */
  6915. static void add_svg_run(struct lay *l, unsigned int node,
  6916. const struct br_style *st, unsigned short href)
  6917. {
  6918. struct lay_run *r;
  6919. int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
  6920. if (lw < 8)
  6921. lw = 8;
  6922. cw = st->width_kind ? style_width_px(st, lw) : lw;
  6923. if (cw < 1)
  6924. cw = 1;
  6925. svg_size(node, st, cw, &dw, &dh);
  6926. if (dw > lw)
  6927. dw = lw;
  6928. ml = mp_px(st, 3, lw);
  6929. mr = mp_px(st, 1, lw);
  6930. if (ml < 0)
  6931. ml = 0;
  6932. if (mr < 0)
  6933. mr = 0;
  6934. if (l->line_x + ml + dw > l->line_right &&
  6935. (l->nruns > 0 || l->line_x > l->line_left))
  6936. flush_line(l);
  6937. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6938. flush_line(l);
  6939. if (l->nruns == 0) {
  6940. l->line_y = l->y;
  6941. l->line_h = 0;
  6942. start_line(l, st);
  6943. }
  6944. l->line_x += ml;
  6945. r = &l->runs[l->nruns++];
  6946. memset(r, 0, sizeof(*r));
  6947. r->gap = (unsigned short)(l->line_x > l->run_x ?
  6948. l->line_x - l->run_x : 0);
  6949. r->off = node;
  6950. r->color = st->color;
  6951. r->href = href;
  6952. r->img = RUN_SVG;
  6953. r->iw = (unsigned short)dw;
  6954. r->ih = (unsigned short)dh;
  6955. r->w = (unsigned short)dw;
  6956. r->font_px = st->font_px;
  6957. if (node < BR_MAX_NODES) {
  6958. layout_boxes[node].x = l->line_x;
  6959. layout_boxes[node].y = l->line_y;
  6960. layout_boxes[node].w = dw;
  6961. layout_boxes[node].h = dh;
  6962. layout_boxes[node].valid = 1;
  6963. }
  6964. l->line_x += dw + mr;
  6965. l->run_x = l->line_x;
  6966. if (l->line_h < dh)
  6967. l->line_h = dh;
  6968. }
  6969. static int text_width(struct lay *l, const char *s, unsigned int n,
  6970. const struct br_style *st)
  6971. {
  6972. return (int)face_text_width(l->ui, st, s, n);
  6973. }
  6974. /* Longest prefix that fits in maxw, at least one byte. */
  6975. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  6976. const struct br_style *st, int maxw)
  6977. {
  6978. unsigned int take = 0;
  6979. while (take < n) {
  6980. if (text_width(l, s, take + 1, st) > maxw)
  6981. break;
  6982. take++;
  6983. }
  6984. return take ? take : 1;
  6985. }
  6986. static void emit_word(struct lay *l, const char *s, unsigned int start,
  6987. unsigned int n, unsigned int base,
  6988. const struct br_style *st, unsigned short href)
  6989. {
  6990. int avail;
  6991. int w = text_width(l, s + start, n, st);
  6992. unsigned int off = start;
  6993. if (l->nruns == 0)
  6994. start_line(l, st);
  6995. avail = l->line_right - l->line_left;
  6996. if (st->nowrap) {
  6997. if (n)
  6998. add_run(l, base + start,
  6999. (unsigned short)n, st, href, 0);
  7000. return;
  7001. }
  7002. /* A padded/bordered one-word button can be a few pixels wider than
  7003. * the content box; keep it on one line instead of splitting it. */
  7004. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  7005. add_run(l, base + start,
  7006. (unsigned short)n, st, href, 0);
  7007. return;
  7008. }
  7009. if (l->line_x + w > l->line_right &&
  7010. (l->nruns > 0 || l->line_x > l->line_left)) {
  7011. flush_line(l);
  7012. start_line(l, st);
  7013. avail = l->line_right - l->line_left;
  7014. }
  7015. if (w <= avail) {
  7016. if (n)
  7017. add_run(l, base + start,
  7018. (unsigned short)n, st, href, 0);
  7019. return;
  7020. }
  7021. while (n > 0) {
  7022. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  7023. add_run(l, base + off,
  7024. (unsigned short)take, st, href, 0);
  7025. off += take;
  7026. n -= take;
  7027. if (n) {
  7028. flush_line(l);
  7029. start_line(l, st);
  7030. avail = l->line_right - l->line_left;
  7031. }
  7032. }
  7033. }
  7034. static void emit_text(struct lay *l, const char *s, unsigned int len,
  7035. const struct br_style *st, unsigned short href, int pre)
  7036. {
  7037. unsigned int i = 0;
  7038. unsigned int base;
  7039. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  7040. if (!s || !len)
  7041. return;
  7042. if (space_w <= 0)
  7043. space_w = 8;
  7044. if (l->nruns == 0)
  7045. start_line(l, st);
  7046. base = (unsigned int)(s - doc.text);
  7047. if (st->uppercase) {
  7048. char *p = (char *)s;
  7049. unsigned int j;
  7050. for (j = 0; j < len; j++)
  7051. if (p[j] >= 'a' && p[j] <= 'z')
  7052. p[j] = (char)(p[j] - 'a' + 'A');
  7053. }
  7054. if (pre) {
  7055. while (i < len) {
  7056. unsigned int start;
  7057. if (s[i] == '\n') {
  7058. flush_line(l);
  7059. start_line(l, st);
  7060. i++;
  7061. continue;
  7062. }
  7063. if (s[i] == ' ') {
  7064. if (l->line_x + space_w > l->line_right &&
  7065. (l->nruns > 0 || l->line_x > l->line_left)) {
  7066. flush_line(l);
  7067. start_line(l, st);
  7068. } else {
  7069. l->line_x += space_w;
  7070. }
  7071. i++;
  7072. continue;
  7073. }
  7074. start = i;
  7075. while (i < len && s[i] != ' ' && s[i] != '\n')
  7076. i++;
  7077. emit_word(l, s, start, i - start, base, st, href);
  7078. }
  7079. return;
  7080. }
  7081. while (i < len) {
  7082. unsigned int start, n;
  7083. if (s[i] == ' ') {
  7084. l->space_pending = 1;
  7085. i++;
  7086. continue;
  7087. }
  7088. start = i;
  7089. while (i < len && s[i] != ' ')
  7090. i++;
  7091. n = i - start;
  7092. if (l->space_pending &&
  7093. (l->nruns > 0 || l->line_x > l->line_left)) {
  7094. if (st->nowrap ||
  7095. l->line_x + space_w <= l->line_right)
  7096. l->line_x += space_w;
  7097. }
  7098. l->space_pending = 0;
  7099. emit_word(l, s, start, n, base, st, href);
  7100. }
  7101. }
  7102. static int list_index(unsigned int parent, unsigned int node)
  7103. {
  7104. unsigned int n = 0, i;
  7105. for (i = doc.nodes[parent].first; i && i != node;
  7106. i = doc.nodes[i].next)
  7107. if (doc.nodes[i].tag == BR_TAG_LI)
  7108. n++;
  7109. return (int)n + 1;
  7110. }
  7111. static void list_roman(char *m, unsigned int *n, int v, int upper,
  7112. unsigned int cap)
  7113. {
  7114. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  7115. 50, 40, 10, 9, 5, 4, 1 };
  7116. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  7117. "l", "xl", "x", "ix", "v", "iv", "i" };
  7118. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  7119. "L", "XL", "X", "IX", "V", "IV", "I" };
  7120. unsigned int i;
  7121. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  7122. while (v >= val[i] && *n + 1 < cap) {
  7123. const char *s = upper ? up[i] : lo[i];
  7124. while (*s && *n + 1 < cap)
  7125. m[(*n)++] = *s++;
  7126. v -= val[i];
  7127. }
  7128. }
  7129. }
  7130. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  7131. {
  7132. unsigned int n = 0;
  7133. if (style == BR_LIST_DISC) {
  7134. m[n++] = '-';
  7135. } else if (style == BR_LIST_CIRCLE) {
  7136. m[n++] = 'o';
  7137. } else if (style == BR_LIST_SQUARE) {
  7138. m[n++] = '+';
  7139. } else if (style == BR_LIST_LOWER_ALPHA ||
  7140. style == BR_LIST_UPPER_ALPHA) {
  7141. if (idx >= 1 && idx <= 26)
  7142. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  7143. 'A' : 'a') + idx - 1);
  7144. else
  7145. m[n++] = '?';
  7146. m[n++] = '.';
  7147. } else if (style == BR_LIST_LOWER_ROMAN ||
  7148. style == BR_LIST_UPPER_ROMAN) {
  7149. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  7150. if (n + 1 < cap)
  7151. m[n++] = '.';
  7152. } else {
  7153. s_append_dec(m, &n, (unsigned int)idx, cap);
  7154. if (n + 1 < cap)
  7155. m[n++] = '.';
  7156. }
  7157. m[n] = '\0';
  7158. }
  7159. /* A control the page styled itself (background, border or radius in author
  7160. * CSS -- `background:transparent;border:none` counts) is painted with that
  7161. * style, sized from its padding/height and keeps the page's text colour.
  7162. * Unstyled controls keep the ngui theme look. */
  7163. static int form_author_styled(const struct br_style *st)
  7164. {
  7165. int i;
  7166. if (st->bg_set)
  7167. return 1;
  7168. for (i = 0; i < 4; i++)
  7169. if (st->border_w[i] || st->radius[i])
  7170. return 1;
  7171. return 0;
  7172. }
  7173. /* Set by the layout when the control is stretched to its line: a flex item
  7174. * (its box width was assigned by the flex row) or a child of a flex column,
  7175. * whose default align-items: stretch makes inputs full width. */
  7176. static int form_fill_line;
  7177. static void add_form_run(struct lay *l, unsigned int node,
  7178. const struct br_style *st, unsigned short href)
  7179. {
  7180. struct form_state *fs = form_get(node, 1);
  7181. char shown[FORM_VALUE_MAX + 1];
  7182. char opt[64];
  7183. const char *text = "";
  7184. struct lay_run *r;
  7185. int kind = form_kind_of(node);
  7186. int disabled = form_disabled(node);
  7187. int author = form_author_styled(st);
  7188. int tw, w = 120, h = 20, i, line_w, pad_x, pad_y;
  7189. int ml = 0, mr = 0, mt = 0, mb = 0;
  7190. if (!fs)
  7191. return;
  7192. if (l->nruns == 0)
  7193. start_line(l, st);
  7194. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  7195. text = "";
  7196. w = 16;
  7197. h = 16;
  7198. } else if (kind == FORM_SELECT) {
  7199. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  7200. s_copy(opt, "Select", sizeof(opt));
  7201. text = opt;
  7202. w = 120;
  7203. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  7204. kind == FORM_RESET) {
  7205. if (fs->len)
  7206. text = fs->value;
  7207. else if (doc.nodes[node].tag == BR_TAG_BUTTON)
  7208. /* A <button>'s label is its content: an empty one
  7209. * (Docusaurus' sidebar caret, drawn by a CSS
  7210. * ::before icon) shows none. Only <input> buttons
  7211. * get the UA's default label. */
  7212. text = "";
  7213. else
  7214. text = kind == FORM_SUBMIT ? "Submit" :
  7215. kind == FORM_RESET ? "Reset" : "Button";
  7216. } else if (kind == FORM_PASSWORD) {
  7217. for (i = 0; i < fs->len; i++)
  7218. shown[i] = '*';
  7219. shown[fs->len] = '\0';
  7220. text = fs->len ? shown : br_placeholder(&doc, node);
  7221. } else {
  7222. if (fs->len)
  7223. text = fs->value;
  7224. else
  7225. text = br_placeholder(&doc, node);
  7226. if (kind == FORM_TEXTAREA) {
  7227. w = 180;
  7228. h = 40;
  7229. }
  7230. }
  7231. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  7232. line_w = l->line_right - l->line_left;
  7233. pad_x = mp_px(st, 7, line_w) + mp_px(st, 5, line_w) +
  7234. st->border_w[1] + st->border_w[3];
  7235. pad_y = mp_px(st, 4, line_w) + mp_px(st, 6, line_w) +
  7236. st->border_w[0] + st->border_w[2];
  7237. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  7238. /* Buttons are border-box in every UA stylesheet: an
  7239. * explicit width/height is the whole box. */
  7240. if (author || pad_x) {
  7241. w = tw + pad_x;
  7242. } else {
  7243. w = tw + 18;
  7244. if (w < 64)
  7245. w = 64;
  7246. }
  7247. if (st->width_kind)
  7248. w = style_width_px(st, line_w);
  7249. if (st->min_width_kind == 1 && w < (int)st->min_width)
  7250. w = st->min_width;
  7251. if (st->height_kind == 1)
  7252. h = st->height;
  7253. else if (author)
  7254. h = st->font_px + 6 + pad_y;
  7255. else
  7256. h = 22;
  7257. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  7258. kind == FORM_TEXTAREA) {
  7259. int fill = form_fill_line || st->display == BR_DISPLAY_BLOCK ||
  7260. st->display == BR_DISPLAY_FLEX;
  7261. int boxed = st->box_sizing ? 0 : pad_x;
  7262. if (st->width_kind)
  7263. w = style_width_px(st, line_w) + boxed;
  7264. else if (fill)
  7265. w = line_w - (l->line_x - l->line_left);
  7266. else
  7267. w = kind == FORM_TEXTAREA ? 180 : 120;
  7268. if (kind == FORM_TEXTAREA) {
  7269. const char *ra = br_find_attr(&doc, node, "rows");
  7270. int rows = 0;
  7271. int lh = st->line_h_px ? st->line_h_px :
  7272. st->font_px * 5 / 4;
  7273. while (ra && *ra >= '0' && *ra <= '9')
  7274. rows = rows * 10 + (*ra++ - '0');
  7275. if (rows < 1 || rows > 40)
  7276. rows = 2;
  7277. h = author ? rows * lh + pad_y : 40;
  7278. } else if (author) {
  7279. h = st->font_px + 8 + pad_y;
  7280. } else if (st->font_px + 8 > h) {
  7281. /* Taller fields for large text (min-height/padding
  7282. * on login pages): keep the box around the glyphs. */
  7283. h = st->font_px + 8;
  7284. }
  7285. if (st->height_kind == 1)
  7286. h = st->height + (st->box_sizing ? 0 : pad_y);
  7287. if (st->min_height_kind == 1 && h < (int)st->min_height)
  7288. h = st->min_height;
  7289. } else if (kind == FORM_SELECT) {
  7290. w = st->width_kind == 1 ? st->width : 120;
  7291. }
  7292. if (author) {
  7293. /* Inline margins (Google's `margin:11px 4px` between its
  7294. * two submit buttons). */
  7295. ml = mp_px(st, 3, line_w);
  7296. mr = mp_px(st, 1, line_w);
  7297. mt = mp_px(st, 0, line_w);
  7298. mb = mp_px(st, 2, line_w);
  7299. if (ml < 0 || ml > 64) ml = 0;
  7300. if (mr < 0 || mr > 64) mr = 0;
  7301. if (mt < 0 || mt > 64) mt = 0;
  7302. if (mb < 0 || mb > 64) mb = 0;
  7303. }
  7304. if (w > line_w - ml - mr)
  7305. w = line_w - ml - mr;
  7306. if (w < 8)
  7307. w = 8;
  7308. if (h > 400)
  7309. h = 400;
  7310. if (l->line_x + ml + w > l->line_right &&
  7311. (l->nruns > 0 || l->line_x > l->line_left))
  7312. flush_line(l);
  7313. if (l->nruns >= 96)
  7314. return;
  7315. if (l->nruns == 0) {
  7316. l->line_y = l->y;
  7317. l->line_h = 0;
  7318. start_line(l, st);
  7319. }
  7320. l->line_x += ml;
  7321. r = &l->runs[l->nruns++];
  7322. r->gap = (unsigned short)(l->line_x - l->run_x);
  7323. r->off = r->len = 0;
  7324. r->color = st->color;
  7325. r->href = href;
  7326. r->dy = (signed short)mt;
  7327. r->has_lit = 1;
  7328. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  7329. r->lit[i] = text[i];
  7330. r->lit[i] = '\0';
  7331. r->img = -2;
  7332. r->iw = (unsigned short)w;
  7333. r->ih = (unsigned short)h;
  7334. r->w = (unsigned short)w;
  7335. r->font_px = st->font_px;
  7336. r->bold = st->bold;
  7337. r->italic = st->italic;
  7338. r->mono = st->mono;
  7339. r->font_face = st->font_face;
  7340. r->underline = 0;
  7341. r->form = node + 1;
  7342. r->form_kind = (unsigned char)kind;
  7343. r->form_disabled = (unsigned char)disabled;
  7344. if (node < BR_MAX_NODES) {
  7345. layout_boxes[node].x = l->line_x;
  7346. layout_boxes[node].y = l->line_y + mt;
  7347. layout_boxes[node].w = w;
  7348. layout_boxes[node].h = h;
  7349. layout_boxes[node].valid = 1;
  7350. }
  7351. l->line_x += w;
  7352. l->run_x = l->line_x;
  7353. l->line_x += mr;
  7354. if (l->line_h < h + mt + mb)
  7355. l->line_h = h + mt + mb;
  7356. }
  7357. /* Background, border and corner radius of an author-styled control, the
  7358. * same decoration rules as a block box. */
  7359. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  7360. const struct br_style *st, int focused)
  7361. {
  7362. int rtl = css_radius(st, 0, box.w, box.h);
  7363. int rtr = css_radius(st, 1, box.w, box.h);
  7364. int rbr = css_radius(st, 2, box.w, box.h);
  7365. int rbl = css_radius(st, 3, box.w, box.h);
  7366. int bw = st->border_t[0] ? 0 : st->border_w[0];
  7367. (void)focused;
  7368. if (box.w <= 0 || box.h <= 0)
  7369. return;
  7370. if (rtl || rtr || rbr || rbl) {
  7371. if (bw > 0 && st->has_bg && st->border_c[0] != st->bg &&
  7372. box.w > bw * 2 && box.h > bw * 2) {
  7373. struct ngui_rect in = { box.x + bw, box.y + bw,
  7374. box.w - bw * 2,
  7375. box.h - bw * 2 };
  7376. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  7377. st->border_c[0]);
  7378. ngui_fill_round_rect(ui, in,
  7379. rtl > bw ? rtl - bw : 0,
  7380. rtr > bw ? rtr - bw : 0,
  7381. rbr > bw ? rbr - bw : 0,
  7382. rbl > bw ? rbl - bw : 0, st->bg);
  7383. } else if (st->has_bg) {
  7384. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  7385. st->bg);
  7386. } else if (bw > 0) {
  7387. ngui_frame_round(ui, box, rtl, rtr, rbr, rbl, bw,
  7388. st->border_c[0]);
  7389. }
  7390. return;
  7391. }
  7392. if (st->has_bg)
  7393. ngui_fill_rect(ui, box, st->bg);
  7394. if (st->border_w[0] || st->border_w[1] || st->border_w[2] ||
  7395. st->border_w[3])
  7396. draw_border_box(ui, box, st);
  7397. }
  7398. /* A poster wrapper is absolutely positioned over the media slot; the
  7399. * measured height of its picture is normally added back to the flow. When a
  7400. * loading-skeleton sibling already reserves that slot, adding both doubles
  7401. * the media height and pushes the article text a full screen down. */
  7402. static int has_skeleton_sibling(unsigned int node)
  7403. {
  7404. unsigned int p = doc.nodes[node].parent, c;
  7405. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  7406. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  7407. continue;
  7408. if (doc.nodes[c].class_off &&
  7409. contains_ci(doc.attrs + doc.nodes[c].class_off,
  7410. "skeleton"))
  7411. return 1;
  7412. }
  7413. return 0;
  7414. }
  7415. static void layout_children(struct lay *l, unsigned int parent,
  7416. const struct br_style *pst, int depth,
  7417. unsigned short link);
  7418. static void layout_flex_children(struct lay *l, unsigned int parent,
  7419. const struct br_style *pst, int depth,
  7420. unsigned short link);
  7421. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  7422. struct br_style *ps, int base);
  7423. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  7424. const struct br_style *ps, unsigned short link);
  7425. static void layout_grid_children(struct lay *l, unsigned int parent,
  7426. const struct br_style *pst, int depth,
  7427. unsigned short link);
  7428. static void layout_grid_auto(struct lay *l, unsigned int parent,
  7429. const struct br_style *pst, int depth,
  7430. unsigned short link);
  7431. static int flex_item_width(struct lay *l, unsigned int n,
  7432. const struct br_style *cs, int avail);
  7433. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  7434. const struct br_style *pst, int depth,
  7435. unsigned short link);
  7436. static void layout_table_row(struct lay *l, unsigned int row,
  7437. const struct br_style *pst, int depth,
  7438. unsigned short link);
  7439. static int table_has_rowspan(unsigned int table);
  7440. static void layout_table(struct lay *l, unsigned int table,
  7441. const struct br_style *st, int depth,
  7442. unsigned short link);
  7443. /* A flex container whose items are only inline spans is usually just a
  7444. * heading/icon pair. Our flex row positions such items without emitting
  7445. * their inline text in some deep page contexts; normal inline flow renders
  7446. * the same content correctly. */
  7447. static int layout_out_of_flow(struct lay *l, unsigned int n,
  7448. const struct br_style *cs, int depth,
  7449. unsigned short lk);
  7450. static void layout_flex_column(struct lay *l, unsigned int parent,
  7451. const struct br_style *pst, int depth,
  7452. unsigned short link);
  7453. static void emit_pseudo(struct lay *l, unsigned int node,
  7454. const struct br_style *st, int pe, unsigned short link);
  7455. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  7456. {
  7457. unsigned int c;
  7458. int items = 0;
  7459. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7460. struct br_node *nd = &doc.nodes[c];
  7461. struct br_style cs;
  7462. if (nd->type == BR_NODE_TEXT)
  7463. continue;
  7464. br_style_for(&doc, c, pst, &cs);
  7465. if (cs.display == BR_DISPLAY_NONE)
  7466. continue;
  7467. /* `justify-content: space-between` spreads even two plain
  7468. * inline items (a "Password ... Reset password" label row)
  7469. * across the line; inline flow would set them side by side. */
  7470. if (++items >= 2 && pst->justify >= 3)
  7471. return 1;
  7472. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  7473. cs.width_kind || cs.has_bg ||
  7474. cs.border_w[0] || cs.border_w[1] ||
  7475. cs.border_w[2] || cs.border_w[3] ||
  7476. nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG)
  7477. return 1;
  7478. }
  7479. return 0;
  7480. }
  7481. static int css_radius(const struct br_style *st, int corner,
  7482. int w, int h)
  7483. {
  7484. int r = st->radius[corner];
  7485. if (r <= 0)
  7486. return 0;
  7487. if (r > w / 2)
  7488. r = w / 2;
  7489. if (r > h / 2)
  7490. r = h / 2;
  7491. return r;
  7492. }
  7493. /* ---- inline SVG ----
  7494. *
  7495. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  7496. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  7497. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  7498. * opacity and solid paint; a gradient paints the average of its stops) and
  7499. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  7500. #define SVG_CACHE_MAX 48
  7501. #define SVG_CACHE_PIXELS (640 * 1024)
  7502. #define SVG_MAX_POINTS 24576
  7503. struct svg_cache_ent {
  7504. unsigned int node;
  7505. int w, h;
  7506. unsigned short *px;
  7507. unsigned char *a;
  7508. unsigned int stamp;
  7509. };
  7510. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  7511. static unsigned int svg_cache_pixels, svg_cache_clock;
  7512. static struct svgr svg_geom;
  7513. static void *svg_geom_buf;
  7514. /* Current viewport in user units: percentage lengths resolve against it
  7515. * (the viewBox size, not the device pixels). */
  7516. static double svg_vp_w = 300, svg_vp_h = 150;
  7517. /* The layers live in the page heap: forget them before heap_reset(). */
  7518. static void svg_cache_clear(void)
  7519. {
  7520. memset(svg_cache, 0, sizeof(svg_cache));
  7521. svg_cache_pixels = 0;
  7522. svg_geom_buf = 0;
  7523. }
  7524. static int svg_name_is(const char *a, const char *b)
  7525. {
  7526. while (*a && *b) {
  7527. char x = *a, y = *b;
  7528. if (x >= 'A' && x <= 'Z')
  7529. x = (char)(x - 'A' + 'a');
  7530. if (x != y)
  7531. return 0;
  7532. a++;
  7533. b++;
  7534. }
  7535. return *a == *b;
  7536. }
  7537. static const char *svg_elem_name(unsigned int node)
  7538. {
  7539. const struct br_node *nd = &doc.nodes[node];
  7540. if (nd->name_off)
  7541. return doc.attrs + nd->name_off;
  7542. return br_tag_name(nd->tag);
  7543. }
  7544. /* A numeric attribute; a percentage resolves against `base`. */
  7545. static double svg_attr_num(unsigned int node, const char *name, double def,
  7546. double base)
  7547. {
  7548. const char *v = br_find_attr(&doc, node, name);
  7549. const char *p = v;
  7550. int ok = 0;
  7551. double x;
  7552. if (!v)
  7553. return def;
  7554. x = svgr_num(&p, &ok);
  7555. if (!ok)
  7556. return def;
  7557. if (*p == '%')
  7558. x = x * base / 100.0;
  7559. return x;
  7560. }
  7561. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  7562. static int svg_viewbox4(unsigned int node, double vb[4])
  7563. {
  7564. const char *v = br_find_attr(&doc, node, "viewbox");
  7565. const char *p = v;
  7566. int i, ok = 1;
  7567. if (!v)
  7568. return 0;
  7569. for (i = 0; i < 4 && ok; i++)
  7570. vb[i] = svgr_num(&p, &ok);
  7571. return ok && vb[2] > 0 && vb[3] > 0;
  7572. }
  7573. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  7574. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  7575. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  7576. double w, double h, double m[6])
  7577. {
  7578. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  7579. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  7580. int ax = 1, ay = 1;
  7581. if (par && contains_ci(par, "none")) {
  7582. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  7583. m[4] = -vb[0] * sx;
  7584. m[5] = -vb[1] * sy;
  7585. return;
  7586. }
  7587. if (par) {
  7588. if (contains_ci(par, "xmin"))
  7589. ax = 0;
  7590. else if (contains_ci(par, "xmax"))
  7591. ax = 2;
  7592. if (contains_ci(par, "ymin"))
  7593. ay = 0;
  7594. else if (contains_ci(par, "ymax"))
  7595. ay = 2;
  7596. }
  7597. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  7598. (sx < sy ? sx : sy);
  7599. tx = (w - vb[2] * s) * ax / 2.0;
  7600. ty = (h - vb[3] * s) * ay / 2.0;
  7601. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  7602. m[4] = tx - vb[0] * s;
  7603. m[5] = ty - vb[1] * s;
  7604. }
  7605. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  7606. * the paint attribute, then average the gradient's stops. */
  7607. static int svg_url_paint(unsigned int node, const char *attr,
  7608. unsigned short *color, unsigned int *alpha)
  7609. {
  7610. const char *v = 0, *h;
  7611. char id[64];
  7612. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  7613. for (k = 0; node && k < 32 && !v; k++) {
  7614. v = br_find_attr(&doc, node, attr);
  7615. if (!v) {
  7616. const char *style = br_find_attr(&doc, node, "style");
  7617. if (style && contains_ci(style, "url(#"))
  7618. v = strstr(style, "url(#");
  7619. }
  7620. if (v && !contains_ci(v, "url("))
  7621. v = 0;
  7622. node = doc.nodes[node].parent;
  7623. }
  7624. if (!v || !(h = strstr(v, "#")))
  7625. return 0;
  7626. h++;
  7627. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  7628. id[n++] = *h++;
  7629. id[n] = '\0';
  7630. g = br_find_id(&doc, id);
  7631. /* Follow href chains (a gradient that only references another one's
  7632. * stops), at most a few hops. */
  7633. for (k = 0; g && k < 4; k++) {
  7634. unsigned int gi = g - 1;
  7635. const char *ref;
  7636. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  7637. const char *nm, *sc, *so;
  7638. unsigned short col = 0;
  7639. double op = 1;
  7640. if (doc.nodes[c].type != BR_NODE_ELEM)
  7641. continue;
  7642. nm = svg_elem_name(c);
  7643. if (!svg_name_is(nm, "stop"))
  7644. continue;
  7645. sc = br_find_attr(&doc, c, "stop-color");
  7646. so = br_find_attr(&doc, c, "stop-opacity");
  7647. {
  7648. const char *st = br_find_attr(&doc, c, "style");
  7649. const char *q;
  7650. if (st && (q = strstr(st, "stop-color:")) != 0)
  7651. sc = q + 11;
  7652. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  7653. so = q + 13;
  7654. }
  7655. if (sc) {
  7656. unsigned int L = 0;
  7657. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  7658. L++;
  7659. if (!br_parse_color(sc, L, &col))
  7660. col = 0;
  7661. }
  7662. if (so) {
  7663. const char *p = so;
  7664. int ok = 0;
  7665. double x = svgr_num(&p, &ok);
  7666. if (ok)
  7667. op = x < 0 ? 0 : x > 1 ? 1 : x;
  7668. }
  7669. sr += (col >> 11) & 31;
  7670. sg += (col >> 5) & 63;
  7671. sb += col & 31;
  7672. sa += (unsigned int)(op * 255);
  7673. cnt++;
  7674. }
  7675. if (cnt)
  7676. break;
  7677. ref = br_find_attr(&doc, gi, "href");
  7678. if (!ref)
  7679. ref = br_find_attr(&doc, gi, "xlink:href");
  7680. if (!ref || ref[0] != '#')
  7681. break;
  7682. g = br_find_id(&doc, ref + 1);
  7683. }
  7684. if (!cnt)
  7685. return 0;
  7686. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  7687. (sb / cnt));
  7688. *alpha = sa / cnt;
  7689. return 1;
  7690. }
  7691. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  7692. unsigned short *color, unsigned int *alpha)
  7693. {
  7694. int mode = fill ? st->fill_mode : st->stroke_mode;
  7695. const char *op = br_find_attr(&doc, node,
  7696. fill ? "fill-opacity" : "stroke-opacity");
  7697. *alpha = 255;
  7698. switch (mode) {
  7699. case BR_PAINT_UNSET:
  7700. if (!fill)
  7701. return 0;
  7702. *color = 0;
  7703. break;
  7704. case BR_PAINT_COLOR:
  7705. *color = fill ? st->fill : st->stroke;
  7706. break;
  7707. case BR_PAINT_CURRENT:
  7708. *color = st->color;
  7709. break;
  7710. case BR_PAINT_URL:
  7711. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  7712. alpha))
  7713. return 0;
  7714. break;
  7715. default:
  7716. return 0;
  7717. }
  7718. if (op) {
  7719. const char *p = op;
  7720. int ok = 0;
  7721. double x = svgr_num(&p, &ok);
  7722. if (ok)
  7723. *alpha = (unsigned int)(*alpha *
  7724. (x < 0 ? 0 : x > 1 ? 1 : x));
  7725. }
  7726. return *alpha > 0;
  7727. }
  7728. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7729. const double m[6], const struct br_style *pst,
  7730. unsigned int alpha, int depth);
  7731. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  7732. const double m[6], const struct br_style *st,
  7733. unsigned int alpha, int depth)
  7734. {
  7735. unsigned int c;
  7736. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  7737. if (doc.nodes[c].type == BR_NODE_ELEM)
  7738. svg_draw_node(L, c, m, st, alpha, depth + 1);
  7739. }
  7740. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7741. const double pm[6], const struct br_style *pst,
  7742. unsigned int alpha, int depth)
  7743. {
  7744. struct br_style st;
  7745. const char *nm = svg_elem_name(node);
  7746. const char *tf;
  7747. double m[6];
  7748. unsigned short color;
  7749. unsigned int pa;
  7750. int shape = 0, fillable = 1;
  7751. if (depth > 24 || !nm)
  7752. return;
  7753. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  7754. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  7755. svg_name_is(nm, "lineargradient") ||
  7756. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  7757. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  7758. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  7759. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  7760. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  7761. svg_name_is(nm, "foreignobject"))
  7762. return;
  7763. br_style_for(&doc, node, pst, &st);
  7764. if (st.display == BR_DISPLAY_NONE)
  7765. return;
  7766. memcpy(m, pm, sizeof(m));
  7767. tf = br_find_attr(&doc, node, "transform");
  7768. if (tf)
  7769. svgr_transform(m, tf);
  7770. {
  7771. const char *op = br_find_attr(&doc, node, "opacity");
  7772. if (op) {
  7773. const char *p = op;
  7774. int ok = 0;
  7775. double x = svgr_num(&p, &ok);
  7776. if (ok)
  7777. alpha = (unsigned int)(alpha *
  7778. (x < 0 ? 0 :
  7779. x > 1 ? 1 : x));
  7780. }
  7781. }
  7782. if (!alpha)
  7783. return;
  7784. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  7785. svg_name_is(nm, "switch")) {
  7786. svg_draw_children(L, node, m, &st, alpha, depth);
  7787. return;
  7788. }
  7789. if (svg_name_is(nm, "svg")) {
  7790. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  7791. y = svg_attr_num(node, "y", 0, 0);
  7792. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7793. t[4] = x;
  7794. t[5] = y;
  7795. svgr_mat_mul(m, m, t);
  7796. double ow = svg_vp_w, oh = svg_vp_h;
  7797. if (svg_viewbox4(node, vb)) {
  7798. double w = svg_attr_num(node, "width", vb[2], ow);
  7799. double h = svg_attr_num(node, "height", vb[3], oh);
  7800. double vm[6];
  7801. svg_viewport_matrix(node, vb, w, h, vm);
  7802. svgr_mat_mul(m, m, vm);
  7803. svg_vp_w = vb[2];
  7804. svg_vp_h = vb[3];
  7805. }
  7806. svg_draw_children(L, node, m, &st, alpha, depth);
  7807. svg_vp_w = ow;
  7808. svg_vp_h = oh;
  7809. return;
  7810. }
  7811. if (svg_name_is(nm, "use")) {
  7812. const char *ref = br_find_attr(&doc, node, "href");
  7813. unsigned int tgt;
  7814. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7815. if (!ref)
  7816. ref = br_find_attr(&doc, node, "xlink:href");
  7817. if (!ref || ref[0] != '#')
  7818. return;
  7819. tgt = br_find_id(&doc, ref + 1);
  7820. if (!tgt || tgt - 1 == node)
  7821. return;
  7822. tgt--;
  7823. t[4] = svg_attr_num(node, "x", 0, 0);
  7824. t[5] = svg_attr_num(node, "y", 0, 0);
  7825. svgr_mat_mul(m, m, t);
  7826. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  7827. double vb[4];
  7828. double ow = svg_vp_w, oh = svg_vp_h;
  7829. if (svg_viewbox4(tgt, vb)) {
  7830. /* A <use> without width/height sizes the
  7831. * symbol to 100% of the viewport: Docusaurus'
  7832. * 13.5px external-link icon references a
  7833. * 24-unit symbol and showed only its corner. */
  7834. double w = svg_attr_num(node, "width",
  7835. ow > 0 ? ow : vb[2], ow);
  7836. double h = svg_attr_num(node, "height",
  7837. oh > 0 ? oh : vb[3], oh);
  7838. double vm[6];
  7839. svg_viewport_matrix(tgt, vb, w, h, vm);
  7840. svgr_mat_mul(m, m, vm);
  7841. svg_vp_w = vb[2];
  7842. svg_vp_h = vb[3];
  7843. }
  7844. svg_draw_children(L, tgt, m, &st, alpha, depth);
  7845. svg_vp_w = ow;
  7846. svg_vp_h = oh;
  7847. } else {
  7848. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  7849. }
  7850. return;
  7851. }
  7852. svgr_reset(&svg_geom, m);
  7853. if (svg_name_is(nm, "path")) {
  7854. const char *d = br_find_attr(&doc, node, "d");
  7855. if (d) {
  7856. svgr_path(&svg_geom, d);
  7857. shape = 1;
  7858. }
  7859. } else if (svg_name_is(nm, "rect")) {
  7860. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  7861. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  7862. double rx = svg_attr_num(node, "rx", -1, w);
  7863. double ry = svg_attr_num(node, "ry", -1, h);
  7864. if (rx < 0)
  7865. rx = ry < 0 ? 0 : ry;
  7866. if (ry < 0)
  7867. ry = rx;
  7868. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  7869. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  7870. shape = 1;
  7871. } else if (svg_name_is(nm, "circle")) {
  7872. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  7873. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7874. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  7875. shape = 1;
  7876. } else if (svg_name_is(nm, "ellipse")) {
  7877. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7878. svg_attr_num(node, "cy", 0, svg_vp_h),
  7879. svg_attr_num(node, "rx", 0, svg_vp_w),
  7880. svg_attr_num(node, "ry", 0, svg_vp_h));
  7881. shape = 1;
  7882. } else if (svg_name_is(nm, "line")) {
  7883. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  7884. svg_attr_num(node, "y1", 0, svg_vp_h));
  7885. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  7886. svg_attr_num(node, "y2", 0, svg_vp_h));
  7887. shape = 1;
  7888. fillable = 0;
  7889. } else if (svg_name_is(nm, "polyline") ||
  7890. svg_name_is(nm, "polygon")) {
  7891. const char *pts = br_find_attr(&doc, node, "points");
  7892. if (pts) {
  7893. svgr_points(&svg_geom, pts,
  7894. svg_name_is(nm, "polygon"));
  7895. shape = 1;
  7896. }
  7897. }
  7898. if (!shape)
  7899. return;
  7900. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  7901. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  7902. st.fill_evenodd);
  7903. if (svg_paint(node, &st, 0, &color, &pa)) {
  7904. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  7905. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7906. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  7907. }
  7908. }
  7909. /* <text> elements: drawn straight onto the page every frame (the glyph
  7910. * renderer targets the ngui canvas, not a layer). x/y map through the
  7911. * accumulated transform; the font size scales with it. */
  7912. static void svg_draw_text(struct ngui *ui, unsigned int node,
  7913. const double pm[6], const struct br_style *pst,
  7914. int ox, int oy, int depth)
  7915. {
  7916. unsigned int c;
  7917. if (depth > 24)
  7918. return;
  7919. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7920. struct br_style st;
  7921. const char *nm, *tf;
  7922. double m[6];
  7923. if (doc.nodes[c].type != BR_NODE_ELEM)
  7924. continue;
  7925. nm = svg_elem_name(c);
  7926. if (!nm || svg_name_is(nm, "defs") ||
  7927. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  7928. svg_name_is(nm, "clippath"))
  7929. continue;
  7930. br_style_for(&doc, c, pst, &st);
  7931. if (st.display == BR_DISPLAY_NONE)
  7932. continue;
  7933. memcpy(m, pm, sizeof(m));
  7934. tf = br_find_attr(&doc, c, "transform");
  7935. if (tf)
  7936. svgr_transform(m, tf);
  7937. if (svg_name_is(nm, "text")) {
  7938. unsigned int t = doc.nodes[c].first;
  7939. const char *s;
  7940. unsigned int n, tw;
  7941. double x = svg_attr_num(c, "x", 0, 0),
  7942. y = svg_attr_num(c, "y", 0, 0);
  7943. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7944. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  7945. int tx, ty, anchor;
  7946. unsigned short col;
  7947. unsigned int pa;
  7948. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  7949. continue;
  7950. if (px < 6)
  7951. px = 6;
  7952. if (px > 72)
  7953. px = 72;
  7954. if (!svg_paint(c, &st, 1, &col, &pa))
  7955. continue;
  7956. s = doc.text + doc.nodes[t].text_off;
  7957. n = doc.nodes[t].text_len;
  7958. st.font_px = (unsigned char)px;
  7959. tw = face_text_width(ui, &st, s, n);
  7960. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  7961. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  7962. ngui_text_ascent_face(ui, style_face(&st), px,
  7963. st.mono);
  7964. anchor = st.align;
  7965. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  7966. anchor = BR_ALIGN_CENTER;
  7967. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  7968. anchor = BR_ALIGN_RIGHT;
  7969. if (anchor == BR_ALIGN_CENTER)
  7970. tx -= (int)tw / 2;
  7971. else if (anchor == BR_ALIGN_RIGHT)
  7972. tx -= (int)tw;
  7973. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  7974. col, px, st.bold, st.italic,
  7975. st.mono);
  7976. } else {
  7977. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  7978. }
  7979. }
  7980. }
  7981. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  7982. {
  7983. double vb[4];
  7984. if (svg_viewbox4(node, vb)) {
  7985. svg_viewport_matrix(node, vb, w, h, m);
  7986. } else {
  7987. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  7988. }
  7989. }
  7990. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  7991. const struct br_style *st)
  7992. {
  7993. struct svg_cache_ent *e = 0;
  7994. struct svgr_layer L;
  7995. double m[6];
  7996. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  7997. svg_cache_clock++;
  7998. for (i = 0; i < SVG_CACHE_MAX; i++)
  7999. if (svg_cache[i].px && svg_cache[i].node == node &&
  8000. svg_cache[i].w == w && svg_cache[i].h == h) {
  8001. svg_cache[i].stamp = svg_cache_clock;
  8002. return &svg_cache[i];
  8003. }
  8004. if (need > SVG_CACHE_PIXELS)
  8005. return 0;
  8006. /* Evict least recently used layers until this one fits. */
  8007. for (;;) {
  8008. struct svg_cache_ent *lru = 0, *free_slot = 0;
  8009. for (i = 0; i < SVG_CACHE_MAX; i++) {
  8010. if (!svg_cache[i].px) {
  8011. if (!free_slot)
  8012. free_slot = &svg_cache[i];
  8013. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  8014. lru = &svg_cache[i];
  8015. }
  8016. }
  8017. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  8018. e = free_slot;
  8019. break;
  8020. }
  8021. if (!lru)
  8022. return 0;
  8023. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  8024. free(lru->px);
  8025. free(lru->a);
  8026. memset(lru, 0, sizeof(*lru));
  8027. }
  8028. if (!svg_geom_buf) {
  8029. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  8030. if (!svg_geom_buf)
  8031. return 0;
  8032. }
  8033. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  8034. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  8035. e->a = (unsigned char *)calloc(need, 1);
  8036. if (!e->px || !e->a) {
  8037. free(e->px);
  8038. free(e->a);
  8039. memset(e, 0, sizeof(*e));
  8040. return 0;
  8041. }
  8042. e->node = node;
  8043. e->w = w;
  8044. e->h = h;
  8045. e->stamp = svg_cache_clock;
  8046. svg_cache_pixels += need;
  8047. L.px = e->px;
  8048. L.a = e->a;
  8049. L.w = w;
  8050. L.h = h;
  8051. svg_root_matrix(node, w, h, m);
  8052. {
  8053. double vb[4];
  8054. if (svg_viewbox4(node, vb)) {
  8055. svg_vp_w = vb[2];
  8056. svg_vp_h = vb[3];
  8057. } else {
  8058. svg_vp_w = w;
  8059. svg_vp_h = h;
  8060. }
  8061. }
  8062. svg_draw_children(&L, node, m, st, 255, 0);
  8063. return e;
  8064. }
  8065. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  8066. *
  8067. * The markup is parsed into a detached subtree of the page document and
  8068. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  8069. * bitmap, which then behaves like any decoded image. currentColor is
  8070. * black (an image has no inherited text colour); <text> is not drawn. */
  8071. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  8072. {
  8073. unsigned int i = 0;
  8074. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  8075. i = 3;
  8076. while (i < len) {
  8077. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  8078. d[i] == '\r' || d[i] == '\n'))
  8079. i++;
  8080. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  8081. return 1;
  8082. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  8083. i += 4;
  8084. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  8085. i++;
  8086. i += 3;
  8087. continue;
  8088. }
  8089. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  8090. while (i < len && d[i] != '>')
  8091. i++;
  8092. i++;
  8093. continue;
  8094. }
  8095. return 0;
  8096. }
  8097. return 0;
  8098. }
  8099. static int svg_len_attr(unsigned int node, const char *name)
  8100. {
  8101. const char *v = br_find_attr(&doc, node, name);
  8102. int n = 0, any = 0;
  8103. if (!v)
  8104. return 0;
  8105. while (*v == ' ')
  8106. v++;
  8107. while (*v >= '0' && *v <= '9') {
  8108. n = n * 10 + (*v++ - '0');
  8109. any = 1;
  8110. }
  8111. if (*v == '.')
  8112. while (*++v >= '0' && *v <= '9')
  8113. ;
  8114. if (!any || *v == '%')
  8115. return 0;
  8116. return n;
  8117. }
  8118. static int svg_decode_image(const unsigned char *data, unsigned int len,
  8119. struct br_image *bi, int box_w, int box_h)
  8120. {
  8121. unsigned int holder, svg = 0, c, need, i;
  8122. struct br_style base = base_style(), st;
  8123. struct svgr_layer L;
  8124. double vb[4], m[6];
  8125. int w, h, have_vb, nat_w, nat_h;
  8126. holder = br_create_element(&doc, "div", 3);
  8127. if (!holder) {
  8128. s_copy(bi->err, "page is full", sizeof(bi->err));
  8129. return -1;
  8130. }
  8131. holder--;
  8132. br_set_inner_html(&doc, holder, (const char *)data, len);
  8133. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  8134. if (doc.nodes[c].type == BR_NODE_ELEM &&
  8135. doc.nodes[c].tag == BR_TAG_SVG) {
  8136. svg = c;
  8137. break;
  8138. }
  8139. if (!svg) {
  8140. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  8141. return -1;
  8142. }
  8143. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  8144. w = svg_len_attr(svg, "width");
  8145. h = svg_len_attr(svg, "height");
  8146. if (box_w > 0 && box_h > 0) {
  8147. w = box_w;
  8148. h = box_h;
  8149. } else if (!w && !h) {
  8150. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  8151. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  8152. } else if (!w) {
  8153. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  8154. } else if (!h) {
  8155. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  8156. }
  8157. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  8158. * so CSS scaling stays crisp. */
  8159. nat_w = w;
  8160. nat_h = h;
  8161. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  8162. w *= 2;
  8163. h *= 2;
  8164. }
  8165. if (w > BR_IMG_LAYOUT_W) {
  8166. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  8167. w = BR_IMG_LAYOUT_W;
  8168. }
  8169. if (h > 2048)
  8170. h = 2048;
  8171. if (w < 1)
  8172. w = 1;
  8173. if (h < 1)
  8174. h = 1;
  8175. need = (unsigned int)w * (unsigned int)h;
  8176. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  8177. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  8178. return -1;
  8179. }
  8180. if (!svg_geom_buf) {
  8181. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  8182. if (!svg_geom_buf) {
  8183. s_copy(bi->err, "out of memory", sizeof(bi->err));
  8184. return -1;
  8185. }
  8186. }
  8187. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  8188. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  8189. L.a = (unsigned char *)calloc(need, 1);
  8190. if (!L.px || !L.a) {
  8191. free(L.px);
  8192. free(L.a);
  8193. s_copy(bi->err, "out of memory", sizeof(bi->err));
  8194. return -1;
  8195. }
  8196. for (i = 0; i < need; i++)
  8197. L.px[i] = 0xFFFF;
  8198. L.w = w;
  8199. L.h = h;
  8200. base.color = 0x0000;
  8201. br_style_for(&doc, svg, &base, &st);
  8202. svg_root_matrix(svg, w, h, m);
  8203. if (!have_vb && nat_w > 0 && nat_h > 0) {
  8204. /* No viewBox: user units are CSS pixels of the natural size,
  8205. * so the up-to-4x raster (and a box size) must scale them.
  8206. * A 40x20 icon used to fill only the top-left quarter of its
  8207. * 160x80 bitmap and was drawn at a quarter of its size. */
  8208. m[0] = (double)w / nat_w;
  8209. m[3] = (double)h / nat_h;
  8210. }
  8211. svg_vp_w = have_vb ? vb[2] : nat_w;
  8212. svg_vp_h = have_vb ? vb[3] : nat_h;
  8213. svg_draw_children(&L, svg, m, &st, 255, 0);
  8214. bi->native_w = nat_w;
  8215. bi->native_h = nat_h;
  8216. bi->img.format = 0;
  8217. bi->img.w = (unsigned int)w;
  8218. bi->img.h = (unsigned int)h;
  8219. bi->img.px = L.px;
  8220. bi->img.alpha = L.a;
  8221. bi->img.flags = 0;
  8222. bi->state = 1;
  8223. image_pixels += need;
  8224. return 0;
  8225. }
  8226. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  8227. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  8228. int *out_w, int *out_h)
  8229. {
  8230. double vb[4];
  8231. int has_vb = svg_viewbox4(node, vb);
  8232. double aw = svg_attr_num(node, "width", -1, cw);
  8233. double ah = svg_attr_num(node, "height", -1, 0);
  8234. int w, h;
  8235. if (st->width_kind)
  8236. w = cw;
  8237. else if (aw > 0)
  8238. w = (int)(aw + 0.5);
  8239. else if (st->height_kind == 1 && has_vb)
  8240. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  8241. else if (ah > 0 && has_vb)
  8242. w = (int)(ah * vb[2] / vb[3] + 0.5);
  8243. else if (has_vb)
  8244. w = cw;
  8245. else
  8246. w = 300;
  8247. if (st->max_width_kind == 1 && w > st->max_width)
  8248. w = st->max_width;
  8249. if (w > cw && cw > 0 && !(aw > 0))
  8250. w = cw;
  8251. if (w < 1)
  8252. w = 1;
  8253. if (w > 2000)
  8254. w = 2000;
  8255. if (st->height_kind == 1)
  8256. h = st->height;
  8257. else if (ah > 0)
  8258. h = (int)(ah + 0.5);
  8259. else if (has_vb)
  8260. h = (int)(w * vb[3] / vb[2] + 0.5);
  8261. else
  8262. h = 150;
  8263. if (h < 1)
  8264. h = 1;
  8265. if (h > 1400)
  8266. h = 1400;
  8267. *out_w = w;
  8268. *out_h = h;
  8269. }
  8270. static void svg_paint_box(struct ngui *ui, unsigned int node,
  8271. const struct br_style *st, int x, int y, int w, int h)
  8272. {
  8273. struct svg_cache_ent *e;
  8274. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  8275. int cx0, cy0, cx1, cy1, px, py;
  8276. double m[6];
  8277. if (ui->nclip > 0)
  8278. clip = ui->clip[ui->nclip - 1];
  8279. cx0 = r.x > clip.x ? r.x : clip.x;
  8280. cy0 = r.y > clip.y ? r.y : clip.y;
  8281. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  8282. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  8283. if (cx0 >= cx1 || cy0 >= cy1)
  8284. return;
  8285. e = svg_layer(node, w, h, st);
  8286. if (e) {
  8287. for (py = cy0; py < cy1; py++) {
  8288. unsigned int srow = (unsigned int)(py - y) *
  8289. (unsigned int)w;
  8290. unsigned short *dst = ui->px + py * ui->w;
  8291. for (px = cx0; px < cx1; px++) {
  8292. unsigned int si = srow + (unsigned int)(px - x);
  8293. unsigned int a = e->a[si];
  8294. if (!a)
  8295. continue;
  8296. dst[px] = a >= 255 ? e->px[si] :
  8297. blend_rgb565(dst[px], e->px[si], a);
  8298. }
  8299. }
  8300. }
  8301. svg_root_matrix(node, w, h, m);
  8302. ngui_push_clip(ui, r);
  8303. svg_draw_text(ui, node, m, st, x, y, 0);
  8304. ngui_pop_clip(ui);
  8305. }
  8306. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  8307. * keep using add_image_run(); this covers the CSS `position:absolute;
  8308. * width:100%` poster pattern used by news sites. */
  8309. static void image_block_size(unsigned int node, const struct br_style *st,
  8310. int cbw, int *out_w, int *out_h)
  8311. {
  8312. struct br_node *nd = &doc.nodes[node];
  8313. int idx = nd->img_index;
  8314. int iw = 0, ih = 0, w, h, aw, ah;
  8315. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  8316. iw = (int)images[idx].img.w;
  8317. ih = (int)images[idx].img.h;
  8318. if (iw <= 0 || ih <= 0) {
  8319. iw = (int)images[idx].native_w;
  8320. ih = (int)images[idx].native_h;
  8321. }
  8322. }
  8323. if (st->width_kind)
  8324. w = style_width_px(st, cbw);
  8325. else if (nd->width_attr)
  8326. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  8327. (int)nd->width_attr;
  8328. else if (nd->height_attr && !nd->height_pct && iw && ih)
  8329. w = iw * (int)nd->height_attr / ih;
  8330. else if (iw)
  8331. w = iw;
  8332. else
  8333. w = 64;
  8334. /* max-width/min-width against the containing block: Tailwind's
  8335. * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
  8336. * 300x300 thumbnail to its 75 px avatar box. */
  8337. if (st->max_width_kind) {
  8338. int mw = st->max_width_kind == 3 ?
  8339. cbw * st->max_width_calc_pct / 100 +
  8340. st->max_width_calc_px :
  8341. st->max_width_kind == 2 ?
  8342. cbw * (int)st->max_width / 100 : (int)st->max_width;
  8343. if (mw > 0 && w > mw)
  8344. w = mw;
  8345. }
  8346. if (st->min_width_kind) {
  8347. int mn = st->min_width_kind == 3 ?
  8348. cbw * st->min_width_calc_pct / 100 +
  8349. st->min_width_calc_px :
  8350. st->min_width_kind == 2 ?
  8351. cbw * (int)st->min_width / 100 : (int)st->min_width;
  8352. if (mn > w)
  8353. w = mn;
  8354. }
  8355. if (w < 8)
  8356. w = 8;
  8357. if (cbw > 0 && w > cbw)
  8358. w = cbw;
  8359. /* Without a CSS height the attributes (or the bitmap) only give the
  8360. * aspect ratio: a width clamped by max-width scales the height too,
  8361. * instead of letterboxing the image into its attribute height. */
  8362. aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
  8363. ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
  8364. if (st->height_kind)
  8365. h = style_height_px(st, cbw);
  8366. else if (aw > 0 && ah > 0)
  8367. h = w * ah / aw;
  8368. else if (nd->height_attr)
  8369. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  8370. (int)nd->height_attr;
  8371. else
  8372. h = 64;
  8373. if (h < 8)
  8374. h = 8;
  8375. *out_w = w;
  8376. *out_h = h;
  8377. }
  8378. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  8379. int dw, int dh)
  8380. {
  8381. int idx = doc.nodes[node].img_index;
  8382. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  8383. struct img_image *src = image_display_get(&images[idx], dw, dh);
  8384. struct img_blit b;
  8385. if (!src)
  8386. src = &images[idx].img;
  8387. b.dst = l->ui->px;
  8388. b.dst_w = l->ui->w;
  8389. b.dst_h = l->ui->h;
  8390. b.clip_x = page_rect.x;
  8391. b.clip_y = page_rect.y;
  8392. b.clip_w = page_rect.w - 12;
  8393. b.clip_h = page_rect.h;
  8394. b.x = x;
  8395. b.y = y;
  8396. b.scale = ((unsigned int)dw << 16) / src->w;
  8397. b.bg = ui.theme.bg;
  8398. b.bg2 = ui.theme.bg;
  8399. b.dst_a = 0;
  8400. /* OVER_DST is only needed for an alpha source; an opaque one can
  8401. * take img_draw's 1:1 copy path. */
  8402. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  8403. img_draw(src, &b);
  8404. } else if (l->draw) {
  8405. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  8406. 0xD69A);
  8407. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  8408. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  8409. }
  8410. }
  8411. static void layout_block(struct lay *l, unsigned int node,
  8412. const struct br_style *st, int depth,
  8413. unsigned short link)
  8414. {
  8415. int old_left = l->left, old_right = l->right, old_align = l->align;
  8416. int parent_cb_h = l->cb_h;
  8417. int saved_parent_top = l->parent_top;
  8418. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  8419. int saved_cb_top = l->cb_top;
  8420. int top, l0, r0;
  8421. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  8422. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  8423. int deco_w, deco_h, content_w, content_h, box_h;
  8424. int img_dh = 0;
  8425. int definite_w = 0;
  8426. int normal_top = 0;
  8427. int rel_dx = 0, rel_dy = 0;
  8428. int clip_pushed = 0;
  8429. struct ngui_rect clip_rect;
  8430. /* A DOM level costs about two depth units (layout_block ->
  8431. * layout_children), so 48 covers a ~24-level page. Real news pages
  8432. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  8433. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  8434. return;
  8435. flow_y = l->y;
  8436. flow_left = l->left;
  8437. flow_right = l->right;
  8438. positioned = st->pos == 1 || st->pos == 2;
  8439. relative = st->pos == 3;
  8440. sticky = st->pos == 4;
  8441. shifted = relative || sticky || st->transform_set;
  8442. if (positioned) {
  8443. int def_w = st->width_kind == 1 ? st->width : -1;
  8444. if (st->pos == 2) {
  8445. int avail_w = page_rect.w - 12;
  8446. if (st->right_set && def_w >= 0)
  8447. l->left = page_rect.x + avail_w - st->right -
  8448. def_w;
  8449. else if (!st->left_set && !st->right_set)
  8450. l->left = flow_left; /* static position */
  8451. else
  8452. l->left = page_rect.x +
  8453. (st->left_set ? st->left : 0);
  8454. l->right = def_w >= 0 ? l->left + def_w :
  8455. st->width_kind == 2 ?
  8456. l->left + avail_w * (int)st->width / 100 :
  8457. page_rect.x + avail_w;
  8458. /* Placed by `bottom` (a page footer): an auto
  8459. * height is the measured one. */
  8460. if (st->bottom_set && st->height_kind)
  8461. l->y = page_rect.y + page_rect.h -
  8462. st->bottom -
  8463. style_height_px(st, page_rect.w);
  8464. else if (st->bottom_set && !st->top_set &&
  8465. block_h[node])
  8466. l->y = page_rect.y + page_rect.h -
  8467. st->bottom - (int)block_h[node] -
  8468. mp_px(st, 0, avail_w) -
  8469. mp_px(st, 2, avail_w);
  8470. else
  8471. l->y = page_rect.y +
  8472. (st->top_set ? st->top : 0);
  8473. } else {
  8474. int left = flow_left + (st->left_set ? st->left : 0);
  8475. unsigned int parent = doc.nodes[node].parent;
  8476. if (st->right_set && def_w >= 0)
  8477. left = flow_right - st->right - def_w;
  8478. l->left = left;
  8479. l->right = def_w >= 0 ? left + def_w :
  8480. flow_right +
  8481. (st->left_set ? st->left : 0);
  8482. l->y = flow_y + (st->top_set ? st->top : 0);
  8483. if (st->bottom_set && st->height_kind &&
  8484. parent < BR_MAX_NODES && block_h[parent] > 0)
  8485. l->y = flow_y + block_h[parent] - st->bottom -
  8486. style_height_px(st, old_right - old_left);
  8487. else if (st->bottom_set && !st->top_set &&
  8488. parent < BR_MAX_NODES && block_h[parent] > 0 &&
  8489. block_h[node] > 0)
  8490. l->y = flow_y + block_h[parent] - st->bottom -
  8491. (int)block_h[node] -
  8492. mp_px(st, 0, old_right - old_left) -
  8493. mp_px(st, 2, old_right - old_left);
  8494. }
  8495. /* `left: 100%` parks a box (Docusaurus' "Skip to main
  8496. * content" link) past the containing block's right edge
  8497. * until it is focused. An auto width then has no room: it
  8498. * used to collapse to 8 px and wrap one word per line into a
  8499. * tall column painted over the page. Lay it out at the
  8500. * containing block's width so it stays one line and
  8501. * overflows (off-screen) like in a real browser. */
  8502. if (def_w < 0 && l->right - l->left < 8) {
  8503. int avail = st->pos == 2 ? page_rect.w - 12 :
  8504. flow_right - flow_left;
  8505. l->right = l->left + (avail > 8 ? avail : 8);
  8506. }
  8507. old_left = l->left;
  8508. old_right = l->right;
  8509. } else if (relative) {
  8510. rel_dx = st->left_set ? st->left :
  8511. (st->right_set ? -st->right : 0);
  8512. rel_dy = st->top_set ? st->top :
  8513. (st->bottom_set ? -st->bottom : 0);
  8514. }
  8515. if (st->transform_set) {
  8516. rel_dx += st->tx;
  8517. rel_dy += st->ty;
  8518. }
  8519. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  8520. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  8521. doc.nodes[node].tag == BR_TAG_SELECT ||
  8522. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  8523. !button_has_elements(node)) {
  8524. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  8525. s_eq(br_type(&doc, node), "hidden"))
  8526. return;
  8527. /* Reached as a block-level box (a flex item): the control
  8528. * fills the box the caller assigned, and its line is flushed
  8529. * here; flex layout resets the run list for the next item, so
  8530. * a queued run would never be drawn. */
  8531. form_fill_line = 1;
  8532. add_form_run(l, node, st, link);
  8533. form_fill_line = 0;
  8534. flush_line(l);
  8535. return;
  8536. }
  8537. flush_line(l);
  8538. cbw = old_right - old_left;
  8539. if (cbw < 8)
  8540. cbw = 8;
  8541. l->y += mp_px(st, 0, cbw);
  8542. top = l->y;
  8543. ml = mp_px(st, 3, cbw);
  8544. mr = mp_px(st, 1, cbw);
  8545. bl = st->border_w[3];
  8546. br = st->border_w[1];
  8547. pl = mp_px(st, 7, cbw);
  8548. pr = mp_px(st, 5, cbw);
  8549. bt = st->border_w[0];
  8550. bb = st->border_w[2];
  8551. pt = mp_px(st, 4, cbw);
  8552. pb = mp_px(st, 6, cbw);
  8553. deco_w = bl + br + pl + pr;
  8554. deco_h = bt + bb + pt + pb;
  8555. if (st->width_kind) {
  8556. int w;
  8557. if (st->width_kind == 3)
  8558. w = cbw * st->width_calc_pct / 100 +
  8559. st->width_calc_px;
  8560. else
  8561. w = css_size(st->width_kind, st->width, cbw);
  8562. if (w < 0)
  8563. w = 0;
  8564. content_w = st->box_sizing ? w - deco_w : w;
  8565. definite_w = 1;
  8566. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  8567. doc.nodes[node].tag == BR_TAG_TD ||
  8568. doc.nodes[node].tag == BR_TAG_TH) &&
  8569. doc.nodes[node].width_attr) {
  8570. /* Legacy table/cell width attributes: percentages resolve
  8571. * against the containing block, bare numbers are pixels. */
  8572. int w = doc.nodes[node].width_pct ?
  8573. cbw * doc.nodes[node].width_attr / 100 :
  8574. doc.nodes[node].width_attr;
  8575. if (w < 0)
  8576. w = 0;
  8577. content_w = st->box_sizing ? w - deco_w : w;
  8578. definite_w = 1;
  8579. } else {
  8580. content_w = cbw - ml - mr - deco_w;
  8581. }
  8582. if (content_w < 0)
  8583. content_w = 0;
  8584. if (st->max_width_kind) {
  8585. int mw = st->max_width_kind == 3 ?
  8586. cbw * st->max_width_calc_pct / 100 +
  8587. st->max_width_calc_px :
  8588. css_size(st->max_width_kind, st->max_width, cbw);
  8589. int max_box = st->box_sizing ? mw : mw + deco_w;
  8590. /* A clamped auto width is used as the width, so auto
  8591. * margins share the rest (Google's 688 px search box). */
  8592. if (content_w + deco_w > max_box) {
  8593. content_w = max_box - deco_w;
  8594. definite_w = 1;
  8595. }
  8596. }
  8597. if (st->min_width_kind) {
  8598. int mw = st->min_width_kind == 3 ?
  8599. cbw * st->min_width_calc_pct / 100 +
  8600. st->min_width_calc_px :
  8601. css_size(st->min_width_kind, st->min_width, cbw);
  8602. int min_box = st->box_sizing ? mw : mw + deco_w;
  8603. if (content_w + deco_w < min_box) {
  8604. content_w = min_box - deco_w;
  8605. definite_w = 1;
  8606. }
  8607. }
  8608. if (content_w < 8)
  8609. content_w = 8;
  8610. if (definite_w) {
  8611. int free_w = cbw - ml - mr - deco_w - content_w;
  8612. if (free_w < 0)
  8613. free_w = 0;
  8614. if (st->ml_auto && st->mr_auto) {
  8615. ml = free_w / 2;
  8616. mr = free_w - ml;
  8617. } else if (st->ml_auto) {
  8618. ml = free_w;
  8619. } else if (st->mr_auto) {
  8620. mr = free_w;
  8621. }
  8622. }
  8623. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8624. int iw, ih;
  8625. image_block_size(node, st, cbw, &iw, &ih);
  8626. content_w = iw;
  8627. img_dh = ih;
  8628. }
  8629. l0 = old_left + ml;
  8630. r0 = l0 + deco_w + content_w;
  8631. if (r0 < l0 + 8)
  8632. r0 = l0 + 8;
  8633. normal_top = top;
  8634. if (sticky) {
  8635. if (st->top_set) {
  8636. int stick = page_rect.y + st->top;
  8637. if (normal_top < stick)
  8638. rel_dy += stick - normal_top;
  8639. } else if (st->bottom_set && block_h[node]) {
  8640. int stick = page_rect.y + page_rect.h - st->bottom -
  8641. block_h[node];
  8642. if (normal_top > stick)
  8643. rel_dy += stick - normal_top;
  8644. }
  8645. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  8646. block_h[doc.nodes[node].parent]) {
  8647. unsigned int p = doc.nodes[node].parent;
  8648. int ptop = l->parent_top;
  8649. int pbottom = ptop + block_h[p];
  8650. int eh = block_h[node];
  8651. int moved_top = normal_top + rel_dy;
  8652. int moved_bottom = moved_top + eh;
  8653. if (moved_bottom > pbottom)
  8654. rel_dy -= moved_bottom - pbottom;
  8655. moved_top = normal_top + rel_dy;
  8656. if (moved_top < ptop)
  8657. rel_dy += ptop - moved_top;
  8658. }
  8659. }
  8660. if (shifted && l->draw) {
  8661. top += rel_dy;
  8662. l0 += rel_dx;
  8663. r0 += rel_dx;
  8664. }
  8665. l->parent_top = top;
  8666. if (st->pos != 0) {
  8667. /* Positioned boxes establish the containing block for their
  8668. * absolutely positioned descendants. */
  8669. l->cb_left = l0;
  8670. l->cb_right = r0;
  8671. l->cb_top = top;
  8672. }
  8673. if (l->draw && block_h[node] &&
  8674. top < page_rect.y + page_rect.h &&
  8675. top + block_h[node] > page_rect.y) {
  8676. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  8677. int rtl = css_radius(st, 0, box.w, box.h);
  8678. int rtr = css_radius(st, 1, box.w, box.h);
  8679. int rbr = css_radius(st, 2, box.w, box.h);
  8680. int rbl = css_radius(st, 3, box.w, box.h);
  8681. if (st->transform_scale) {
  8682. if (st->has_bg)
  8683. fill_transformed_rect(l->ui, box, st->bg, st);
  8684. } else if (rtl || rtr || rbr || rbl) {
  8685. if (st->has_bg) {
  8686. int bw = st->border_w[0];
  8687. if (bw > 0 && !st->border_t[0] &&
  8688. st->border_c[0] != st->bg &&
  8689. box.w > bw * 2 && box.h > bw * 2) {
  8690. struct ngui_rect inner = {
  8691. box.x + bw, box.y + bw,
  8692. box.w - bw * 2, box.h - bw * 2
  8693. };
  8694. int itl = rtl > bw ? rtl - bw : 0;
  8695. int itr = rtr > bw ? rtr - bw : 0;
  8696. int ibr = rbr > bw ? rbr - bw : 0;
  8697. int ibl = rbl > bw ? rbl - bw : 0;
  8698. ngui_fill_round_rect(l->ui, box, rtl,
  8699. rtr, rbr, rbl,
  8700. st->border_c[0]);
  8701. ngui_fill_round_rect(l->ui, inner,
  8702. itl, itr, ibr,
  8703. ibl, st->bg);
  8704. } else {
  8705. ngui_fill_round_rect(l->ui, box, rtl,
  8706. rtr, rbr, rbl,
  8707. st->bg);
  8708. }
  8709. } else if (st->border_w[0] && !st->border_t[0]) {
  8710. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  8711. rbl, st->border_w[0],
  8712. st->border_c[0]);
  8713. }
  8714. /* Rounded boxes paint their background image too
  8715. * (app icons are rounded squares), kept inside the
  8716. * corner arcs. */
  8717. if (st->bg_image)
  8718. draw_bg_image_round(l, box, node, st, rtl, rtr,
  8719. rbr, rbl);
  8720. } else {
  8721. if (st->has_bg)
  8722. ngui_fill_rect(l->ui, box, st->bg);
  8723. if (st->bg_image)
  8724. draw_bg_image(l, box, node, st);
  8725. if (st->border_w[0] || st->border_w[1] ||
  8726. st->border_w[2] || st->border_w[3])
  8727. draw_border_box(l->ui, box, st);
  8728. }
  8729. }
  8730. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  8731. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  8732. content_w, img_dh);
  8733. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  8734. l->ui && l->ui->nclip < 4) {
  8735. clip_rect.x = l0 + bl;
  8736. clip_rect.y = top + bt;
  8737. clip_rect.w = (r0 - l0) - bl - br;
  8738. clip_rect.h = (int)block_h[node] - bt - bb;
  8739. if (clip_rect.w > 0 && clip_rect.h > 0) {
  8740. ngui_push_clip(l->ui, clip_rect);
  8741. clip_pushed = 1;
  8742. }
  8743. }
  8744. l->left = l0 + bl + pl;
  8745. l->right = l->left + content_w;
  8746. if (l->right < l->left + 8)
  8747. l->right = l->left + 8;
  8748. l->align = st->align;
  8749. l->line_left = l->left;
  8750. l->line_right = l->right;
  8751. l->y = top + bt + pt;
  8752. if (doc.nodes[node].tag == BR_TAG_HR) {
  8753. if (l->draw)
  8754. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  8755. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  8756. l->y += 8;
  8757. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  8758. int vw = l->right - l->left;
  8759. int vh;
  8760. if (doc.nodes[node].width_pct)
  8761. vw = vw * doc.nodes[node].width_attr / 100;
  8762. else if (doc.nodes[node].width_attr)
  8763. vw = doc.nodes[node].width_attr;
  8764. if (vw > l->right - l->left)
  8765. vw = l->right - l->left;
  8766. if (vw < 8)
  8767. vw = 8;
  8768. vh = vw * 9 / 16;
  8769. if (vh > 240)
  8770. vh = 240;
  8771. if (vh < 80)
  8772. vh = 80;
  8773. if (l->draw) {
  8774. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  8775. vw, vh}, 0xD69A);
  8776. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  8777. vw, vh}, 0x8410);
  8778. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  8779. 0x4208);
  8780. }
  8781. l->y += vh + 4;
  8782. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  8783. int dw, dh, cw = l->right - l->left;
  8784. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  8785. if (l->draw && l->y < page_rect.y + page_rect.h &&
  8786. l->y + dh > page_rect.y)
  8787. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  8788. l->y += dh;
  8789. } else {
  8790. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  8791. !st->no_bullet) {
  8792. char *m = li_marker[node];
  8793. if (!m[0]) {
  8794. unsigned int parent = doc.nodes[node].parent;
  8795. int style = st->list_style;
  8796. int idx = parent ? list_index(parent, node) : 1;
  8797. if (style == BR_LIST_AUTO)
  8798. style = (parent &&
  8799. doc.nodes[parent].tag ==
  8800. BR_TAG_OL) ?
  8801. BR_LIST_DECIMAL : BR_LIST_DISC;
  8802. list_marker_text(m, sizeof(li_marker[node]),
  8803. style, idx);
  8804. }
  8805. if (l->draw && m[0]) {
  8806. int mw = (int)ngui_text_width_ui(l->ui, m);
  8807. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  8808. st->color);
  8809. }
  8810. }
  8811. /* This box's definite content height, for its children's
  8812. * percentage heights. */
  8813. if (doc.nodes[node].tag == BR_TAG_HTML ||
  8814. doc.nodes[node].tag == BR_TAG_BODY)
  8815. l->cb_h = layout_view_h;
  8816. else if (st->height_kind == 1)
  8817. l->cb_h = (int)st->height -
  8818. (st->box_sizing ? deco_h : 0);
  8819. else if (st->height_kind == 2 && parent_cb_h > 0)
  8820. l->cb_h = parent_cb_h * (int)st->height / 100 -
  8821. (st->box_sizing ? deco_h : 0);
  8822. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  8823. l->cb_h = content_w * (int)st->aspect_h /
  8824. (int)st->aspect_w;
  8825. else if (!st->height_kind && node < BR_MAX_NODES &&
  8826. flex_stretch_h[node] > deco_h)
  8827. l->cb_h = flex_stretch_h[node] - deco_h;
  8828. else
  8829. l->cb_h = 0;
  8830. if (l->cb_h < 0)
  8831. l->cb_h = 0;
  8832. if (doc.nodes[node].tag == BR_TAG_TR)
  8833. layout_table_row(l, node, st, depth + 1, link);
  8834. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  8835. table_has_rowspan(node))
  8836. layout_table(l, node, st, depth + 1, link);
  8837. else if (st->grid_auto)
  8838. layout_grid_auto(l, node, st, depth + 1, link);
  8839. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  8840. st->grid_gap > 0)
  8841. layout_grid_children(l, node, st, depth + 1, link);
  8842. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  8843. flex_wants_row(node, st))
  8844. layout_flex_children(l, node, st, depth + 1, link);
  8845. else if (st->display == BR_DISPLAY_FLEX && st->flex_col)
  8846. layout_flex_column(l, node, st, depth + 1, link);
  8847. else
  8848. layout_children(l, node, st, depth + 1, link);
  8849. l->cb_h = parent_cb_h;
  8850. }
  8851. flush_line(l);
  8852. if (clip_pushed)
  8853. ngui_pop_clip(l->ui);
  8854. if (l->float_active) {
  8855. if (l->y < l->float_bottom)
  8856. l->y = l->float_bottom;
  8857. l->float_active = 0;
  8858. }
  8859. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8860. content_h = img_dh;
  8861. } else if (st->height_kind == 2 &&
  8862. doc.nodes[node].tag != BR_TAG_HTML &&
  8863. doc.nodes[node].tag != BR_TAG_BODY) {
  8864. /* A percentage of the containing block's definite height, or
  8865. * auto when it has none (it used to resolve against the
  8866. * width). The result is a minimum: without scrollable inner
  8867. * boxes, an app shell's height:100%; overflow:hidden column
  8868. * would otherwise clip everything past the first screen. */
  8869. int auto_h = l->y - (top + bt + pt);
  8870. content_h = parent_cb_h > 0 ?
  8871. parent_cb_h * (int)st->height / 100 -
  8872. (st->box_sizing ? deco_h : 0) : 0;
  8873. if (content_h < auto_h)
  8874. content_h = auto_h;
  8875. } else if (st->height_kind &&
  8876. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8877. doc.nodes[node].tag == BR_TAG_BODY) &&
  8878. st->height_kind == 2)) {
  8879. content_h = style_height_px(st, cbw);
  8880. if (st->box_sizing)
  8881. content_h -= deco_h;
  8882. } else {
  8883. /* Percentage heights on html/body resolve against the
  8884. * viewport, but their content still defines the document
  8885. * scroll height. Treating them as auto avoids collapsing
  8886. * the measured page to the containing block width. */
  8887. content_h = l->y - (top + bt + pt);
  8888. /* aspect-ratio: the preferred height of an auto-height box
  8889. * (Tailwind aspect-video image frames); content can still
  8890. * make it taller, as with min-height: auto. */
  8891. if (st->aspect_w && st->aspect_h && content_w > 0) {
  8892. int ah = content_w * (int)st->aspect_h /
  8893. (int)st->aspect_w;
  8894. if (content_h < ah)
  8895. content_h = ah;
  8896. }
  8897. }
  8898. if (content_h < 0)
  8899. content_h = 0;
  8900. if (!st->height_kind && node < BR_MAX_NODES &&
  8901. content_h + deco_h < flex_stretch_h[node])
  8902. content_h = flex_stretch_h[node] - deco_h;
  8903. if (st->max_height_kind) {
  8904. int mh = st->max_height_kind == 3 ?
  8905. cbw * st->max_height_calc_pct / 100 +
  8906. st->max_height_calc_px :
  8907. css_size(st->max_height_kind, st->max_height, cbw);
  8908. int max_box = st->box_sizing ? mh : mh + deco_h;
  8909. if (content_h + deco_h > max_box)
  8910. content_h = max_box - deco_h;
  8911. }
  8912. if (st->min_height_kind &&
  8913. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8914. doc.nodes[node].tag == BR_TAG_BODY) &&
  8915. st->min_height_kind == 2)) {
  8916. int mh = st->min_height_kind == 3 ?
  8917. cbw * st->min_height_calc_pct / 100 +
  8918. st->min_height_calc_px :
  8919. css_size(st->min_height_kind, st->min_height, cbw);
  8920. int min_box = st->box_sizing ? mh : mh + deco_h;
  8921. if (content_h + deco_h < min_box)
  8922. content_h = min_box - deco_h;
  8923. }
  8924. if (content_h < 0)
  8925. content_h = 0;
  8926. box_h = deco_h + content_h;
  8927. if (box_h < 0)
  8928. box_h = 0;
  8929. l->y = (shifted ? normal_top : top) + box_h;
  8930. if (node < BR_MAX_NODES) {
  8931. layout_boxes[node].x = l0;
  8932. layout_boxes[node].y = top;
  8933. layout_boxes[node].w = r0 - l0;
  8934. layout_boxes[node].h = box_h;
  8935. layout_boxes[node].valid = r0 > l0;
  8936. }
  8937. l->left = old_left;
  8938. l->right = old_right;
  8939. l->align = old_align;
  8940. l->y += mp_px(st, 2, cbw);
  8941. if (!l->draw) {
  8942. if (box_h > 65535)
  8943. box_h = 65535;
  8944. block_h[node] = (unsigned short)box_h;
  8945. block_top[node] = (unsigned short)(top < 0 ? 0 :
  8946. top > 65535 ? 65535 : top);
  8947. }
  8948. if (positioned) {
  8949. l->y = flow_y;
  8950. l->left = flow_left;
  8951. l->right = flow_right;
  8952. }
  8953. l->parent_top = saved_parent_top;
  8954. l->cb_left = saved_cb_left;
  8955. l->cb_right = saved_cb_right;
  8956. l->cb_top = saved_cb_top;
  8957. }
  8958. static int text_node_blank(const struct br_node *nd)
  8959. {
  8960. const char *t = doc.text + nd->text_off;
  8961. unsigned int i;
  8962. for (i = 0; i < nd->text_len; i++)
  8963. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  8964. t[i] != '\r')
  8965. return 0;
  8966. return 1;
  8967. }
  8968. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  8969. * text/image widths in the subtree, plus padding and margins. This keeps
  8970. * Bootstrap's floated nav items on one line instead of giving each the whole
  8971. * row. */
  8972. static int text_space(char c)
  8973. {
  8974. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  8975. }
  8976. static int intrinsic_width(struct ngui *ui, unsigned int node,
  8977. const struct br_style *pst, int depth, int base)
  8978. {
  8979. unsigned int c;
  8980. int line_w = 0, max_w = 0;
  8981. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  8982. if (depth > 32)
  8983. return 0;
  8984. if (doc.npe_rules) {
  8985. struct br_style ps;
  8986. /* Icon boxes (::before/::after with a size) are inline
  8987. * content of the element. */
  8988. line_w += pseudo_box_w(node, pst, 1, &ps, base) +
  8989. pseudo_box_w(node, pst, 2, &ps, base);
  8990. }
  8991. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8992. struct br_node *nd = &doc.nodes[c];
  8993. struct br_style cs;
  8994. if (nd->type == BR_NODE_TEXT) {
  8995. const char *t = doc.text + nd->text_off;
  8996. unsigned int tn = nd->text_len;
  8997. if (doc.nodes[node].tag == BR_TAG_PRE) {
  8998. line_w += (int)face_text_width(ui, pst, t, tn);
  8999. } else {
  9000. unsigned int ti = 0;
  9001. int first = 1;
  9002. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  9003. int sp = (int)face_text_width(ui, pst, " ", 1);
  9004. while (ti < tn) {
  9005. unsigned int ts;
  9006. while (ti < tn && text_space(t[ti]))
  9007. ti++;
  9008. ts = ti;
  9009. while (ti < tn && !text_space(t[ti]))
  9010. ti++;
  9011. if (ti == ts)
  9012. break;
  9013. if (!first || lead)
  9014. line_w += sp;
  9015. lead = 0;
  9016. line_w += (int)face_text_width(ui, pst,
  9017. t + ts, ti - ts);
  9018. first = 0;
  9019. }
  9020. }
  9021. continue;
  9022. }
  9023. br_style_for(&doc, c, pst, &cs);
  9024. if (cs.display == BR_DISPLAY_NONE)
  9025. continue;
  9026. if (nd->tag == BR_TAG_BR) {
  9027. if (line_w > max_w)
  9028. max_w = line_w;
  9029. line_w = 0;
  9030. continue;
  9031. }
  9032. if (nd->tag == BR_TAG_IMG) {
  9033. /* Measure the image as layout will draw it: a CSS or
  9034. * attribute height keeps the intrinsic aspect ratio, and
  9035. * a CSS width overrides the native pixel width. Bootstrap
  9036. * sizes the Cloudron logo with height:40px only. */
  9037. int idx = nd->img_index;
  9038. int iw = 0, ih = 0;
  9039. if (idx >= 0 && idx < image_count &&
  9040. images[idx].state == 1) {
  9041. iw = (int)images[idx].native_w;
  9042. ih = (int)images[idx].native_h;
  9043. if (iw <= 0 || ih <= 0) {
  9044. iw = (int)images[idx].img.w;
  9045. ih = (int)images[idx].img.h;
  9046. }
  9047. }
  9048. if (cs.width_kind) {
  9049. int ww = style_width_px(&cs, base);
  9050. line_w += ww > 0 ? ww : 64;
  9051. } else if (nd->width_attr) {
  9052. line_w += nd->width_attr;
  9053. } else if (nd->height_attr && iw && ih) {
  9054. line_w += iw * (int)nd->height_attr / ih;
  9055. } else if (cs.height_kind && iw && ih) {
  9056. /* A percentage height needs the parent's
  9057. * definite height (the logo's 2rem box), as in
  9058. * add_image_run(); otherwise it is auto. */
  9059. int hh = cs.height_kind == 1 ?
  9060. style_height_px(&cs, base) :
  9061. cs.height_kind == 2 &&
  9062. pst->height_kind == 1 ?
  9063. (int)pst->height * (int)cs.height / 100 :
  9064. 0;
  9065. line_w += hh > 0 ? iw * hh / ih : iw;
  9066. } else if (iw) {
  9067. line_w += iw;
  9068. } else {
  9069. line_w += 64;
  9070. }
  9071. continue;
  9072. }
  9073. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  9074. nd->tag == BR_TAG_TEXTAREA) &&
  9075. !s_eq(br_type(&doc, c), "hidden")) {
  9076. /* Form controls are replaced: CSS width applies even
  9077. * when they are inline (add_form_run's sizes). */
  9078. int fw = cs.width_kind ? style_width_px(&cs, base) :
  9079. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  9080. if (s_eq(br_type(&doc, c), "checkbox") ||
  9081. s_eq(br_type(&doc, c), "radio"))
  9082. fw = 16;
  9083. line_w += (fw > 0 ? fw : 120) +
  9084. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  9085. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  9086. continue;
  9087. }
  9088. if (nd->tag == BR_TAG_SVG) {
  9089. /* A replaced element: its own size, like add_svg_run()
  9090. * (its path children have no width). */
  9091. int sw, sh, sb = cs.width_kind ?
  9092. style_width_px(&cs, base) : base;
  9093. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  9094. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  9095. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  9096. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  9097. line_w += sw;
  9098. } else {
  9099. if (line_w > max_w)
  9100. max_w = line_w;
  9101. line_w = 0;
  9102. if (sw > max_w)
  9103. max_w = sw;
  9104. }
  9105. continue;
  9106. }
  9107. {
  9108. int cw = mp_px(&cs, 7, base) +
  9109. mp_px(&cs, 5, base) +
  9110. mp_px(&cs, 3, base) +
  9111. mp_px(&cs, 1, base) +
  9112. cs.border_w[1] + cs.border_w[3];
  9113. /* width/height do not apply to non-replaced inline
  9114. * boxes. The tagesschau home label is an inline span
  9115. * with width:1px for the mobile icon-only header; using
  9116. * that width made the whole subnav collapse to a
  9117. * one-character column. */
  9118. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  9119. cw += cs.width_kind == 1 ? cs.width :
  9120. style_width_px(&cs, base);
  9121. else
  9122. cw += intrinsic_width(ui, c, &cs, depth + 1,
  9123. base);
  9124. if (flex_row || cs.float_left ||
  9125. cs.display == BR_DISPLAY_INLINE ||
  9126. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  9127. line_w += cw;
  9128. } else {
  9129. if (line_w > max_w)
  9130. max_w = line_w;
  9131. line_w = 0;
  9132. if (cw > max_w)
  9133. max_w = cw;
  9134. }
  9135. }
  9136. if (line_w > 4096 || max_w > 4096)
  9137. break;
  9138. }
  9139. return line_w > max_w ? line_w : max_w;
  9140. }
  9141. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  9142. * the main user: .row > .col-md-* with float:left and a percentage width.
  9143. * Each column is laid out with its own left/right edge and the row advances
  9144. * to the tallest column. Returns the first child not consumed. */
  9145. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  9146. const struct br_style *pst, int depth,
  9147. unsigned short link)
  9148. {
  9149. unsigned int n = first;
  9150. int row_left = l->left, row_right = l->right;
  9151. int row_top, row_bottom, xl, xr, any = 0;
  9152. int fl_left = row_left, fl_right = row_right, fl_bottom;
  9153. flush_line(l);
  9154. row_top = l->y;
  9155. row_bottom = l->y;
  9156. fl_bottom = row_top;
  9157. xl = row_left;
  9158. xr = row_right;
  9159. while (n) {
  9160. struct br_node *nd = &doc.nodes[n];
  9161. struct br_style cs;
  9162. unsigned short lk = link;
  9163. int colw, right;
  9164. if (nd->type == BR_NODE_TEXT) {
  9165. if (text_node_blank(nd)) {
  9166. n = nd->next;
  9167. continue;
  9168. }
  9169. break;
  9170. }
  9171. br_style_for(&doc, n, pst, &cs);
  9172. if (cs.display == BR_DISPLAY_NONE) {
  9173. n = nd->next;
  9174. continue;
  9175. }
  9176. /* A float blockifies its box: Bootstrap floats inline
  9177. * anchors too (the navbar brand and its text links), and
  9178. * their padding must be honoured. */
  9179. if (!cs.float_left)
  9180. break;
  9181. if (nd->tag == BR_TAG_A && nd->href_off)
  9182. lk = (unsigned short)n;
  9183. right = cs.float_left == 2;
  9184. if (cs.width_kind == 1 || cs.width_kind == 2 ||
  9185. cs.width_kind == 3) {
  9186. /* The column is the margin box: `width` is the
  9187. * content (or, with border-box, the border) box,
  9188. * and layout_block() takes margins, padding and
  9189. * borders back out of the column. A 200px float
  9190. * with margin-right:20px used to get 180px of
  9191. * content. */
  9192. int base = row_right - row_left;
  9193. colw = cs.width_kind == 1 ? (int)cs.width :
  9194. style_width_px(&cs, base);
  9195. colw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  9196. if (!cs.box_sizing)
  9197. colw += mp_px(&cs, 7, base) +
  9198. mp_px(&cs, 5, base) +
  9199. cs.border_w[1] + cs.border_w[3];
  9200. } else {
  9201. int base = row_right - row_left;
  9202. /* Shrink-to-fit outer width: borders too (Google's
  9203. * 1px-bordered "Anmelden" pill wrapped otherwise). */
  9204. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  9205. mp_px(&cs, 7, base) +
  9206. mp_px(&cs, 5, base) +
  9207. mp_px(&cs, 3, base) +
  9208. mp_px(&cs, 1, base) +
  9209. cs.border_w[1] + cs.border_w[3];
  9210. if (colw < 8)
  9211. colw = 8;
  9212. }
  9213. if (colw < 8)
  9214. colw = 8;
  9215. if (colw > row_right - row_left)
  9216. colw = row_right - row_left;
  9217. /* The float column width is already resolved. */
  9218. cs.width_kind = 0;
  9219. cs.max_width_kind = 0;
  9220. if (right) {
  9221. if (any && xr - colw < xl) {
  9222. row_top = row_bottom;
  9223. row_bottom = row_top;
  9224. xl = row_left;
  9225. xr = row_right;
  9226. }
  9227. if (xr - colw < xl)
  9228. colw = xr - xl;
  9229. if (colw < 8)
  9230. colw = 8;
  9231. l->left = xr - colw;
  9232. if (l->left < row_left)
  9233. l->left = row_left;
  9234. l->right = xr;
  9235. xr = l->left;
  9236. if (xr < fl_right)
  9237. fl_right = xr;
  9238. } else {
  9239. if (any && xl + colw > xr) {
  9240. row_top = row_bottom;
  9241. row_bottom = row_top;
  9242. xl = row_left;
  9243. xr = row_right;
  9244. }
  9245. l->left = xl;
  9246. l->right = xl + colw;
  9247. xl += colw;
  9248. if (xl > fl_left)
  9249. fl_left = xl;
  9250. }
  9251. if (l->right < l->left + 8)
  9252. l->right = l->left + 8;
  9253. l->y = row_top;
  9254. l->line_left = l->line_x = l->left;
  9255. l->run_x = l->left;
  9256. l->line_y = l->y;
  9257. l->line_h = 0;
  9258. l->nruns = 0;
  9259. l->space_pending = 0;
  9260. l->align = cs.align;
  9261. layout_block(l, n, &cs, depth + 1, lk);
  9262. if (l->y > row_bottom)
  9263. row_bottom = l->y;
  9264. if (l->y > fl_bottom)
  9265. fl_bottom = l->y;
  9266. any = 1;
  9267. n = nd->next;
  9268. }
  9269. l->left = row_left;
  9270. l->right = row_right;
  9271. if (n && any) {
  9272. struct br_node *nd = &doc.nodes[n];
  9273. int inline_next = 0;
  9274. if (nd->type == BR_NODE_TEXT) {
  9275. inline_next = 1;
  9276. } else if (nd->type == BR_NODE_ELEM) {
  9277. struct br_style cs;
  9278. br_style_for(&doc, n, pst, &cs);
  9279. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  9280. cs.display != BR_DISPLAY_NONE &&
  9281. !br_tag_is_block(nd->tag);
  9282. }
  9283. if (inline_next) {
  9284. if (l->float_active) {
  9285. if (l->float_left > fl_left)
  9286. fl_left = l->float_left;
  9287. if (l->float_right < fl_right)
  9288. fl_right = l->float_right;
  9289. if (l->float_bottom > fl_bottom)
  9290. fl_bottom = l->float_bottom;
  9291. }
  9292. l->float_active = 1;
  9293. l->float_left = fl_left;
  9294. l->float_right = fl_right;
  9295. l->float_bottom = fl_bottom;
  9296. l->y = row_top;
  9297. } else {
  9298. l->float_active = 0;
  9299. l->y = row_bottom;
  9300. }
  9301. } else {
  9302. l->float_active = 0;
  9303. l->y = row_bottom;
  9304. }
  9305. l->line_x = l->left;
  9306. l->run_x = l->left;
  9307. l->line_left = l->left;
  9308. l->line_right = l->right;
  9309. l->line_y = l->y;
  9310. l->line_h = 0;
  9311. l->nruns = 0;
  9312. l->space_pending = 0;
  9313. return n;
  9314. }
  9315. static int flex_item_width(struct lay *l, unsigned int n,
  9316. const struct br_style *cs, int avail)
  9317. {
  9318. struct br_node *nd = &doc.nodes[n];
  9319. (void)l;
  9320. int w;
  9321. if (cs->width_kind == 2 || cs->width_kind == 3)
  9322. w = style_width_px(cs, avail);
  9323. else if (cs->width_kind == 1)
  9324. w = (int)cs->width;
  9325. else if (nd->tag == BR_TAG_IMG) {
  9326. int idx = nd->img_index;
  9327. if (idx >= 0 && idx < image_count &&
  9328. images[idx].state == 1)
  9329. w = (int)images[idx].img.w;
  9330. else if (nd->width_attr)
  9331. w = (int)nd->width_attr;
  9332. else
  9333. w = 64;
  9334. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  9335. nd->tag == BR_TAG_TEXTAREA) {
  9336. /* A control has no content to measure: its default size
  9337. * (a search field in a filter bar). */
  9338. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  9339. } else {
  9340. w = intrinsic_width(l->ui, n, cs, 0, avail);
  9341. }
  9342. /* Explicit widths are content-box sizes; the flex item's outer width
  9343. * must include padding, borders and margins. */
  9344. w += mp_px(cs, 7, avail);
  9345. w += mp_px(cs, 5, avail);
  9346. w += mp_px(cs, 3, avail);
  9347. w += mp_px(cs, 1, avail);
  9348. w += cs->border_w[1] + cs->border_w[3];
  9349. if (w < 24)
  9350. w = 24;
  9351. if (w > avail)
  9352. w = avail;
  9353. return w;
  9354. }
  9355. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  9356. int depth);
  9357. /* An inline child of a text-only inline-block: the same test minus the
  9358. * display check (an inline <span> may have padding/background in CSS, but
  9359. * the inline path paints those for spans anyway). */
  9360. static int inline_block_flows_inline(unsigned int node,
  9361. const struct br_style *cs, int depth)
  9362. {
  9363. unsigned int c;
  9364. if (depth > 3 || cs->pos)
  9365. return 0;
  9366. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9367. const struct br_node *nd = &doc.nodes[c];
  9368. struct br_style ch;
  9369. if (nd->type != BR_NODE_ELEM)
  9370. continue;
  9371. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  9372. br_tag_is_block(nd->tag))
  9373. return 0;
  9374. br_style_for(&doc, c, cs, &ch);
  9375. if (ch.display == BR_DISPLAY_NONE)
  9376. continue;
  9377. if (ch.display != BR_DISPLAY_INLINE ||
  9378. !inline_block_flows_inline(c, &ch, depth + 1))
  9379. return 0;
  9380. }
  9381. return 1;
  9382. }
  9383. /* An inline-block that is only text in a line (a <time> in a byline, a
  9384. * label) with no box of its own -- no size, background, border or padding
  9385. * -- lays out exactly like an inline element, so it stays in the text line
  9386. * instead of ending it. Boxes with any of those keep the row path. */
  9387. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  9388. int depth)
  9389. {
  9390. unsigned int c;
  9391. int i;
  9392. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  9393. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  9394. cs->pos || depth > 3)
  9395. return 0;
  9396. for (i = 0; i < 4; i++)
  9397. if (cs->border_w[i])
  9398. return 0;
  9399. for (i = 4; i < 8; i++)
  9400. if (mp_px(cs, i, 0) > 0)
  9401. return 0;
  9402. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9403. const struct br_node *nd = &doc.nodes[c];
  9404. struct br_style ch;
  9405. if (nd->type != BR_NODE_ELEM)
  9406. continue;
  9407. if (nd->tag == BR_TAG_SVG) {
  9408. /* An icon box (Docusaurus' admonition heading:
  9409. * `<span inline-block><svg/></span>Note`): the SVG
  9410. * is an inline replaced run, so the box can stay in
  9411. * the text line. */
  9412. br_style_for(&doc, c, cs, &ch);
  9413. if (ch.display == BR_DISPLAY_NONE ||
  9414. ch.display == BR_DISPLAY_INLINE ||
  9415. ch.display == BR_DISPLAY_INLINE_BLOCK)
  9416. continue;
  9417. return 0;
  9418. }
  9419. if (nd->tag == BR_TAG_IMG || br_tag_is_block(nd->tag))
  9420. return 0;
  9421. br_style_for(&doc, c, cs, &ch);
  9422. if (ch.display == BR_DISPLAY_NONE)
  9423. continue;
  9424. if (ch.display != BR_DISPLAY_INLINE ||
  9425. !inline_block_flows_inline(c, &ch, depth + 1))
  9426. return 0;
  9427. }
  9428. return 1;
  9429. }
  9430. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  9431. * on one line, not one full-width block each. Place intrinsic widths from
  9432. * left to right and wrap when the row is full. */
  9433. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  9434. const struct br_style *pst, int depth,
  9435. unsigned short link)
  9436. {
  9437. unsigned int n = first;
  9438. int row_left = l->left, row_right = l->right;
  9439. int avail = row_right - row_left;
  9440. int x = row_left, y = l->y, row_h = 0, any = 0;
  9441. /* Each box sets l->align from its own style; the text after the row
  9442. * must keep the container's (a centred .fa-fw icon centred the menu
  9443. * label that followed it). */
  9444. unsigned char row_align = l->align;
  9445. flush_line(l);
  9446. y = l->y;
  9447. while (n) {
  9448. struct br_node *nd = &doc.nodes[n];
  9449. struct br_style cs;
  9450. unsigned short lk = link;
  9451. int colw, h;
  9452. if (nd->type == BR_NODE_TEXT) {
  9453. if (!text_node_blank(nd))
  9454. break;
  9455. if (any)
  9456. x += 4;
  9457. n = nd->next;
  9458. continue;
  9459. }
  9460. br_style_for(&doc, n, pst, &cs);
  9461. if (cs.display == BR_DISPLAY_NONE) {
  9462. n = nd->next;
  9463. continue;
  9464. }
  9465. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  9466. break;
  9467. if (nd->tag == BR_TAG_A && nd->href_off)
  9468. lk = (unsigned short)n;
  9469. colw = flex_item_width(l, n, &cs, avail);
  9470. /* A few pixels of slack keep a single long token (boot.S)
  9471. * from wrapping at the exact content width. */
  9472. colw += 8;
  9473. if (colw > avail)
  9474. colw = avail;
  9475. cs.width_kind = 0;
  9476. cs.max_width_kind = 0;
  9477. if (any && x + colw > row_right) {
  9478. y += row_h + 2;
  9479. x = row_left;
  9480. row_h = 0;
  9481. any = 0;
  9482. }
  9483. if (any && x > row_left)
  9484. x += 4;
  9485. l->left = x;
  9486. l->right = x + colw;
  9487. if (l->right < l->left + 8)
  9488. l->right = l->left + 8;
  9489. l->y = y;
  9490. l->line_left = l->line_x = l->left;
  9491. l->run_x = l->left;
  9492. l->line_y = l->y;
  9493. l->line_h = 0;
  9494. l->nruns = 0;
  9495. l->space_pending = 0;
  9496. l->align = cs.align;
  9497. layout_block(l, n, &cs, depth + 1, lk);
  9498. h = l->y - y;
  9499. if (h > row_h)
  9500. row_h = h;
  9501. x += colw;
  9502. any = 1;
  9503. n = nd->next;
  9504. }
  9505. if (any)
  9506. y += row_h;
  9507. l->left = row_left;
  9508. l->right = row_right;
  9509. l->align = row_align;
  9510. l->y = y;
  9511. l->line_left = l->line_x = l->left;
  9512. l->run_x = l->left;
  9513. l->line_y = l->y;
  9514. l->line_h = 0;
  9515. l->nruns = 0;
  9516. l->space_pending = 0;
  9517. return n;
  9518. }
  9519. struct flex_item {
  9520. unsigned int node;
  9521. unsigned short link;
  9522. int w;
  9523. };
  9524. /* An item's min-width/max-width as outer (margin-box) widths in the flex
  9525. * row, or -1 when unset. Percentages and calc() resolve against the
  9526. * container width. */
  9527. static int flex_limit_w(const struct br_style *cs, int which_max, int avail)
  9528. {
  9529. unsigned char kind = which_max ? cs->max_width_kind :
  9530. cs->min_width_kind;
  9531. int w;
  9532. if (kind == 3)
  9533. w = which_max ?
  9534. avail * cs->max_width_calc_pct / 100 +
  9535. cs->max_width_calc_px :
  9536. avail * cs->min_width_calc_pct / 100 +
  9537. cs->min_width_calc_px;
  9538. else
  9539. w = css_size(kind, which_max ? cs->max_width : cs->min_width,
  9540. avail);
  9541. if (w < 0)
  9542. return -1;
  9543. if (!cs->box_sizing)
  9544. w += mp_px(cs, 7, avail) + mp_px(cs, 5, avail) +
  9545. cs->border_w[1] + cs->border_w[3];
  9546. return w + mp_px(cs, 3, avail) + mp_px(cs, 1, avail);
  9547. }
  9548. static int flex_clamp_w(const struct br_style *cs, int w, int avail)
  9549. {
  9550. int mx = flex_limit_w(cs, 1, avail), mn = flex_limit_w(cs, 0, avail);
  9551. if (mx >= 0 && w > mx)
  9552. w = mx;
  9553. if (mn >= 0 && w < mn)
  9554. w = mn;
  9555. return w;
  9556. }
  9557. /* Does a flex row stretch this item to the line height? Only items with
  9558. * no height of their own and align-self/align-items stretch; replaced
  9559. * content (images, icons) keeps its aspect ratio. */
  9560. static int flex_item_stretches(unsigned int node, const struct br_style *cs,
  9561. const struct br_style *pst)
  9562. {
  9563. int ai = cs->align_self ? cs->align_self - 1 : pst->align_items;
  9564. unsigned char tag = doc.nodes[node].tag;
  9565. return ai == 0 && !cs->height_kind && !cs->max_height_kind &&
  9566. tag != BR_TAG_IMG && tag != BR_TAG_SVG && tag != BR_TAG_INPUT &&
  9567. tag != BR_TAG_SELECT && tag != BR_TAG_TEXTAREA &&
  9568. tag != BR_TAG_BUTTON;
  9569. }
  9570. static void flex_set_stretch(unsigned int node, const struct br_style *cs,
  9571. int line_h, int cbw)
  9572. {
  9573. int h = line_h - mp_px(cs, 0, cbw) - mp_px(cs, 2, cbw);
  9574. if (node >= BR_MAX_NODES || h <= 0)
  9575. return;
  9576. if (h > 65535)
  9577. h = 65535;
  9578. flex_stretch_h[node] = (unsigned short)h;
  9579. if (block_h[node] < h)
  9580. block_h[node] = (unsigned short)h;
  9581. }
  9582. static void layout_flex_children(struct lay *l, unsigned int parent,
  9583. const struct br_style *pst, int depth,
  9584. unsigned short link)
  9585. {
  9586. struct flex_item it[32];
  9587. unsigned int c;
  9588. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  9589. int grow_need = 0; /* growing items at their content width */
  9590. int row_left = l->left, row_right = l->right;
  9591. int avail = row_right - row_left;
  9592. int idx, row_top;
  9593. unsigned char row_align = l->align;
  9594. int box_left = l->left, box_right = l->right, row_top0 = l->y;
  9595. int bw = 0, aw = 0, first_h = -1;
  9596. int cont_h = l->cb_h; /* the container's definite content height */
  9597. struct br_style bps, aps;
  9598. if (avail < 8 || depth > 48) {
  9599. layout_children(l, parent, pst, depth, link);
  9600. return;
  9601. }
  9602. /* If direct text is not just whitespace, normal block flow handles it
  9603. * better than pretending it is a flex item. */
  9604. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9605. struct br_node *nd = &doc.nodes[c];
  9606. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9607. layout_children(l, parent, pst, depth, link);
  9608. return;
  9609. }
  9610. }
  9611. /* ::before/::after icon boxes are the row's first and last items
  9612. * (Docusaurus' sidebar chevron): reserve their columns. */
  9613. if (doc.npe_rules) {
  9614. bw = pseudo_box_w(parent, pst, 1, &bps, avail);
  9615. aw = pseudo_box_w(parent, pst, 2, &aps, avail);
  9616. if (bw + aw > avail - 8) {
  9617. bw = 0;
  9618. aw = 0;
  9619. }
  9620. row_left += bw;
  9621. row_right -= aw;
  9622. avail = row_right - row_left;
  9623. }
  9624. for (c = doc.nodes[parent].first;
  9625. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  9626. c = doc.nodes[c].next) {
  9627. struct br_node *nd = &doc.nodes[c];
  9628. struct br_style cs;
  9629. if (nd->type == BR_NODE_TEXT)
  9630. continue;
  9631. br_style_for(&doc, c, pst, &cs);
  9632. if (cs.display == BR_DISPLAY_NONE)
  9633. continue;
  9634. if ((cs.pos == 1 || cs.pos == 2) &&
  9635. layout_out_of_flow(l, c, &cs, depth,
  9636. (nd->tag == BR_TAG_A && nd->href_off) ?
  9637. (unsigned short)c : link))
  9638. continue; /* absolutely positioned: not an item */
  9639. it[nitem].node = c;
  9640. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  9641. (unsigned short)c : link;
  9642. it[nitem].w = 0;
  9643. if (cs.flex_grow && !cs.width_kind) {
  9644. grow_count++;
  9645. grow_need += flex_item_width(l, c, &cs, avail);
  9646. } else
  9647. fixed += flex_clamp_w(&cs,
  9648. flex_item_width(l, c, &cs, avail),
  9649. avail);
  9650. nitem++;
  9651. }
  9652. /* A narrow container (an icon row sized to its content, Google's
  9653. * mic + lens buttons) is still a row when its items fit; only a
  9654. * narrow one that would overflow or squeeze growing items falls
  9655. * back to block flow. */
  9656. if (avail < 160 && fixed + grow_need > avail) {
  9657. layout_children(l, parent, pst, depth, link);
  9658. return;
  9659. }
  9660. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  9661. /* A growing item capped by max-width (Docusaurus' doc column,
  9662. * `max-width: 75%`; its main container, `calc(100% - 300px)`)
  9663. * keeps its cap and leaves the rest of the free space to the other
  9664. * growing items. */
  9665. if (grow_count) {
  9666. int pass, capped[32] = { 0 };
  9667. for (pass = 0; pass < nitem; pass++) {
  9668. int changed = 0;
  9669. for (idx = 0; idx < nitem; idx++) {
  9670. struct br_style cs;
  9671. int lim;
  9672. if (capped[idx])
  9673. continue;
  9674. br_style_for(&doc, it[idx].node, pst, &cs);
  9675. if (!cs.flex_grow || cs.width_kind)
  9676. continue;
  9677. lim = flex_clamp_w(&cs, grow_w, avail);
  9678. if (lim == grow_w)
  9679. continue;
  9680. capped[idx] = lim + 1;
  9681. fixed += lim;
  9682. grow_count--;
  9683. changed = 1;
  9684. }
  9685. if (!changed || !grow_count)
  9686. break;
  9687. grow_w = (avail - fixed) / grow_count;
  9688. }
  9689. for (idx = 0; idx < nitem; idx++)
  9690. it[idx].w = capped[idx] ? capped[idx] - 1 : 0;
  9691. }
  9692. if (grow_w < 96 && avail >= 160)
  9693. grow_w = 96;
  9694. for (idx = 0; idx < nitem; idx++) {
  9695. struct br_style cs;
  9696. if (it[idx].w)
  9697. continue; /* capped growing item */
  9698. br_style_for(&doc, it[idx].node, pst, &cs);
  9699. if (cs.flex_grow && !cs.width_kind)
  9700. it[idx].w = grow_w;
  9701. else
  9702. it[idx].w = flex_clamp_w(&cs,
  9703. flex_item_width(l,
  9704. it[idx].node,
  9705. &cs, avail),
  9706. avail);
  9707. if (it[idx].w > avail)
  9708. it[idx].w = avail;
  9709. if (it[idx].w < 8)
  9710. it[idx].w = 8;
  9711. }
  9712. row_top = l->y;
  9713. idx = 0;
  9714. while (idx < nitem) {
  9715. int start = idx, count = 0, row_w = 0;
  9716. int free_w, x, extra = 0, row_h = 0, k;
  9717. while (idx < nitem) {
  9718. int add = it[idx].w + (count ? gap : 0);
  9719. /* CSS default is nowrap; only flex-wrap: wrap (1)
  9720. * starts a new row. */
  9721. if (count && pst->flex_wrap == 1 &&
  9722. row_w + add > avail)
  9723. break;
  9724. row_w += add;
  9725. count++;
  9726. idx++;
  9727. }
  9728. if (!count) {
  9729. count = 1;
  9730. row_w = it[start].w;
  9731. idx = start + 1;
  9732. }
  9733. free_w = avail - row_w;
  9734. if (free_w < 0)
  9735. free_w = 0;
  9736. x = row_left;
  9737. if (pst->justify == 1) {
  9738. x += free_w / 2;
  9739. } else if (pst->justify == 2) {
  9740. x += free_w;
  9741. } else if (pst->justify == 3) {
  9742. extra = count > 1 ? free_w / (count - 1) : 0;
  9743. } else if (pst->justify == 4) {
  9744. extra = count ? free_w / count : 0;
  9745. x += extra / 2;
  9746. } else if (pst->justify == 5) {
  9747. extra = count ? free_w / (count + 1) : 0;
  9748. x += extra;
  9749. }
  9750. for (k = 0; k < count; k++) {
  9751. int node = (int)it[start + k].node;
  9752. int h = block_h[node];
  9753. if (h > row_h)
  9754. row_h = h;
  9755. }
  9756. /* A single line fills a definite container height (an app
  9757. * shell's `height: 100%` sidebar + content row). */
  9758. if (pst->flex_wrap != 1 && cont_h > row_h)
  9759. row_h = cont_h;
  9760. else if (pst->height_kind == 1 && (int)pst->height > row_h)
  9761. row_h = pst->height;
  9762. for (k = 0; k < count; k++) {
  9763. struct br_style cs;
  9764. int node = (int)it[start + k].node;
  9765. int yoff = 0;
  9766. br_style_for(&doc, node, pst, &cs);
  9767. cs.width_kind = 0;
  9768. cs.max_width_kind = 0;
  9769. /* align-items: stretch. With a definite line height
  9770. * the item is laid out at it, so its own children see
  9771. * a definite height; otherwise the measure pass
  9772. * stretches it once the line is known (below). */
  9773. if (!l->draw && row_h > 0 && flex_item_stretches(node,
  9774. &cs, pst))
  9775. flex_set_stretch(node, &cs, row_h, avail);
  9776. {
  9777. int ai = cs.align_self ? cs.align_self - 1 :
  9778. pst->align_items;
  9779. if (l->draw && ai && row_h > block_h[node]) {
  9780. if (ai == 1)
  9781. yoff = (row_h -
  9782. block_h[node]) / 2;
  9783. else if (ai == 2)
  9784. yoff = row_h - block_h[node];
  9785. }
  9786. }
  9787. l->left = x;
  9788. l->right = x + it[start + k].w;
  9789. if (l->right < l->left + 8)
  9790. l->right = l->left + 8;
  9791. l->y = row_top + yoff;
  9792. /* line_left too: a stale one from the previous item
  9793. * made flush_line() see a non-empty line and push
  9794. * every later item down by an empty line's height. */
  9795. l->line_left = l->line_x = l->run_x = l->left;
  9796. l->line_right = l->right;
  9797. l->line_y = l->y;
  9798. l->line_h = 0;
  9799. l->nruns = 0;
  9800. l->space_pending = 0;
  9801. l->align = cs.align;
  9802. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  9803. {
  9804. /* Both passes: a form control item has no
  9805. * block_h of its own, so the draw pass would
  9806. * otherwise end a row of only an <input> at
  9807. * height 0 and pull the content below up. */
  9808. int h = l->y - row_top;
  9809. if (h > row_h)
  9810. row_h = h;
  9811. }
  9812. x += it[start + k].w;
  9813. if (k + 1 < count)
  9814. x += gap + extra;
  9815. }
  9816. if (!l->draw) {
  9817. for (k = 0; k < count; k++) {
  9818. struct br_style cs;
  9819. int node = (int)it[start + k].node;
  9820. br_style_for(&doc, node, pst, &cs);
  9821. if (!flex_item_stretches(node, &cs, pst))
  9822. continue;
  9823. /* To the line's bottom edge from where the
  9824. * item really starts (its top margin, or a
  9825. * line box above it). */
  9826. if (layout_boxes[node].valid)
  9827. flex_set_stretch(node, &cs,
  9828. row_top + row_h -
  9829. layout_boxes[node].y +
  9830. mp_px(&cs, 0, avail), avail);
  9831. else
  9832. flex_set_stretch(node, &cs, row_h, avail);
  9833. }
  9834. }
  9835. if (first_h < 0)
  9836. first_h = row_h;
  9837. row_top += row_h;
  9838. }
  9839. if (bw || aw) {
  9840. int pass;
  9841. for (pass = 0; pass < 2; pass++) {
  9842. const struct br_style *ps = pass ? &aps : &bps;
  9843. int a = pass ? row_right : box_left;
  9844. int b = pass ? box_right : row_left;
  9845. int h = ps->height_kind ?
  9846. style_height_px(ps, box_right - box_left) : 0;
  9847. if (!(pass ? aw : bw))
  9848. continue;
  9849. l->left = l->line_left = l->line_x = l->run_x = a;
  9850. l->right = l->line_right = b;
  9851. l->y = row_top0;
  9852. if (pst->align_items == 1 && first_h > h)
  9853. l->y += (first_h - h) / 2;
  9854. l->line_y = l->y;
  9855. l->line_h = 0;
  9856. l->nruns = 0;
  9857. l->space_pending = 0;
  9858. emit_pseudo_box(l, pst, ps, link);
  9859. flush_line(l);
  9860. /* The box sits inside the first row; it only makes
  9861. * the row taller when it is taller itself. */
  9862. if (row_top0 + h > row_top)
  9863. row_top = row_top0 + h;
  9864. }
  9865. }
  9866. l->left = box_left;
  9867. l->right = box_right;
  9868. l->align = row_align;
  9869. l->y = row_top;
  9870. l->line_left = l->line_x = l->run_x = l->left;
  9871. l->line_right = l->right;
  9872. l->line_y = l->y;
  9873. l->line_h = 0;
  9874. l->nruns = 0;
  9875. l->space_pending = 0;
  9876. }
  9877. /* flex-direction: column. Items stack in order with the gap and never
  9878. * collapse margins. In the draw pass justify-content shares out the free
  9879. * height of the container's measured box (a definite or min-height, or a
  9880. * row stretch), and align-items places each item: stretch (the default)
  9881. * fills the line, start/center/end shrink an item to its content width
  9882. * (a login form's "Log in" button, a centred logo and name). */
  9883. static void layout_flex_column(struct lay *l, unsigned int parent,
  9884. const struct br_style *pst, int depth,
  9885. unsigned short link)
  9886. {
  9887. unsigned int c;
  9888. int box_left = l->left, box_right = l->right;
  9889. int avail = box_right - box_left;
  9890. int gap = pst->grid_gap, y0 = l->y;
  9891. int n = 0, k = 0, total = 0, lead = 0, extra = 0;
  9892. unsigned char row_align = l->align;
  9893. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9894. struct br_node *nd = &doc.nodes[c];
  9895. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd))
  9896. break;
  9897. }
  9898. if (c || avail < 8 || depth > 48) {
  9899. /* Loose text: block flow, with centred lines standing in
  9900. * for align-items: center. */
  9901. struct br_style cst = *pst;
  9902. if (pst->align_items == 1) {
  9903. cst.align = BR_ALIGN_CENTER;
  9904. l->align = BR_ALIGN_CENTER;
  9905. }
  9906. layout_children(l, parent, &cst, depth, link);
  9907. return;
  9908. }
  9909. emit_pseudo(l, parent, pst, 1, link);
  9910. flush_line(l);
  9911. y0 = l->y;
  9912. if (l->draw && parent < BR_MAX_NODES && block_h[parent]) {
  9913. int inner = (int)block_h[parent] - pst->border_w[0] -
  9914. pst->border_w[2] - mp_px(pst, 4, avail) -
  9915. mp_px(pst, 6, avail) - (y0 - l->parent_top -
  9916. pst->border_w[0] - mp_px(pst, 4, avail));
  9917. int free_h;
  9918. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9919. struct br_style cs;
  9920. if (doc.nodes[c].type != BR_NODE_ELEM)
  9921. continue;
  9922. br_style_for(&doc, c, pst, &cs);
  9923. if (cs.display == BR_DISPLAY_NONE || cs.pos == 1 ||
  9924. cs.pos == 2)
  9925. continue;
  9926. total += block_h[c] + mp_px(&cs, 0, avail) +
  9927. mp_px(&cs, 2, avail);
  9928. n++;
  9929. }
  9930. if (n > 1)
  9931. total += gap * (n - 1);
  9932. free_h = inner - total;
  9933. if (n && free_h > 0) {
  9934. if (pst->justify == 1) {
  9935. lead = free_h / 2;
  9936. } else if (pst->justify == 2) {
  9937. lead = free_h;
  9938. } else if (pst->justify == 3) {
  9939. extra = n > 1 ? free_h / (n - 1) : 0;
  9940. } else if (pst->justify == 4) {
  9941. extra = free_h / n;
  9942. lead = extra / 2;
  9943. } else if (pst->justify == 5) {
  9944. extra = free_h / (n + 1);
  9945. lead = extra;
  9946. }
  9947. }
  9948. }
  9949. l->y = y0 + lead;
  9950. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9951. struct br_node *nd = &doc.nodes[c];
  9952. unsigned short lk = (nd->tag == BR_TAG_A && nd->href_off) ?
  9953. (unsigned short)c : link;
  9954. struct br_style cs;
  9955. int ai, left = box_left, right = box_right;
  9956. if (nd->type != BR_NODE_ELEM)
  9957. continue;
  9958. br_style_for(&doc, c, pst, &cs);
  9959. if (cs.display == BR_DISPLAY_NONE)
  9960. continue;
  9961. if ((cs.pos == 1 || cs.pos == 2) &&
  9962. layout_out_of_flow(l, c, &cs, depth, lk))
  9963. continue;
  9964. if (k++)
  9965. l->y += gap + extra;
  9966. ai = cs.align_self ? cs.align_self - 1 : pst->align_items;
  9967. if (ai) {
  9968. int w = flex_clamp_w(&cs, flex_item_width(l, c, &cs,
  9969. avail),
  9970. avail);
  9971. if (ai == 1)
  9972. left += (avail - w) / 2;
  9973. else if (ai == 2)
  9974. left += avail - w;
  9975. right = left + w;
  9976. cs.width_kind = 0;
  9977. cs.max_width_kind = 0;
  9978. }
  9979. l->left = l->line_left = l->line_x = l->run_x = left;
  9980. l->right = l->line_right = right;
  9981. l->line_y = l->y;
  9982. l->line_h = 0;
  9983. l->nruns = 0;
  9984. l->space_pending = 0;
  9985. l->align = cs.align;
  9986. layout_block(l, c, &cs, depth + 1, lk);
  9987. }
  9988. l->left = l->line_left = l->line_x = l->run_x = box_left;
  9989. l->right = l->line_right = box_right;
  9990. l->align = row_align;
  9991. l->line_y = l->y;
  9992. l->line_h = 0;
  9993. l->nruns = 0;
  9994. l->space_pending = 0;
  9995. emit_pseudo(l, parent, pst, 2, link);
  9996. }
  9997. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  9998. * plus the grid-area hints used by site shells (site notice/footer full
  9999. * width, column-start left, page-content right). Anything more elaborate
  10000. * falls back to normal block flow. */
  10001. static int grid_track_width(unsigned char kind, unsigned short val,
  10002. int avail, int other)
  10003. {
  10004. if (kind == 2)
  10005. return avail * (int)val / 100;
  10006. if (kind == 1)
  10007. return val;
  10008. return other;
  10009. }
  10010. static void layout_grid_children(struct lay *l, unsigned int parent,
  10011. const struct br_style *pst, int depth,
  10012. unsigned short link)
  10013. {
  10014. unsigned int n;
  10015. int row_left = l->left, row_right = l->right;
  10016. int avail = row_right - row_left;
  10017. int gap = pst->grid_gap;
  10018. int track_total = avail - gap;
  10019. int col0, col1, x0, x1;
  10020. int row_y, row_bottom, have_left = 0, have_right = 0;
  10021. unsigned int c;
  10022. if (avail < 32 || depth > 48)
  10023. return;
  10024. if (track_total < 16)
  10025. track_total = 16;
  10026. col0 = grid_track_width((unsigned char)(pst->width_kind),
  10027. pst->width, track_total, 0);
  10028. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  10029. pst->max_width, track_total, 0);
  10030. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  10031. int w0 = pst->width ? pst->width : 1;
  10032. int w1 = pst->max_width ? pst->max_width : 1;
  10033. col0 = track_total * w0 / (w0 + w1);
  10034. col1 = track_total - col0;
  10035. } else if (pst->width_kind == 3) {
  10036. col0 = track_total - col1;
  10037. if (col0 < 24)
  10038. col0 = 24;
  10039. } else if (pst->max_width_kind == 3) {
  10040. col1 = track_total - col0;
  10041. if (col1 < 24)
  10042. col1 = 24;
  10043. }
  10044. if (col0 < 24)
  10045. col0 = 24;
  10046. if (col1 < 24)
  10047. col1 = 24;
  10048. if (col0 + col1 > track_total) {
  10049. col1 = track_total - col0;
  10050. if (col1 < 24)
  10051. col1 = 24;
  10052. }
  10053. x0 = row_left;
  10054. x1 = row_left + col0 + gap;
  10055. /* Direct text makes a grid ambiguous; use block flow instead. */
  10056. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10057. struct br_node *nd = &doc.nodes[c];
  10058. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  10059. layout_children(l, parent, pst, depth, link);
  10060. return;
  10061. }
  10062. }
  10063. row_y = row_bottom = l->y;
  10064. n = doc.nodes[parent].first;
  10065. while (n) {
  10066. struct br_node *nd = &doc.nodes[n];
  10067. struct br_style cs;
  10068. unsigned short lk = link;
  10069. int slot, x, w;
  10070. if (nd->type == BR_NODE_TEXT) {
  10071. n = nd->next;
  10072. continue;
  10073. }
  10074. br_style_for(&doc, n, pst, &cs);
  10075. if (cs.display == BR_DISPLAY_NONE) {
  10076. n = nd->next;
  10077. continue;
  10078. }
  10079. if (nd->tag == BR_TAG_A && nd->href_off)
  10080. lk = (unsigned short)n;
  10081. slot = cs.grid_slot;
  10082. if (!slot) {
  10083. if (!have_left)
  10084. slot = 2;
  10085. else if (!have_right)
  10086. slot = 3;
  10087. else
  10088. slot = 2;
  10089. }
  10090. if (slot == 1) {
  10091. if (have_left || have_right) {
  10092. row_y = row_bottom;
  10093. have_left = have_right = 0;
  10094. }
  10095. x = row_left;
  10096. w = avail;
  10097. } else if (slot == 2) {
  10098. if (have_left) {
  10099. row_y = row_bottom;
  10100. have_left = have_right = 0;
  10101. }
  10102. x = x0;
  10103. w = col0;
  10104. have_left = 1;
  10105. } else {
  10106. if (have_right) {
  10107. row_y = row_bottom;
  10108. have_left = have_right = 0;
  10109. }
  10110. x = x1;
  10111. w = col1;
  10112. have_right = 1;
  10113. }
  10114. cs.width_kind = 0;
  10115. cs.max_width_kind = 0;
  10116. l->left = x;
  10117. l->right = x + w;
  10118. if (l->right < l->left + 8)
  10119. l->right = l->left + 8;
  10120. l->y = row_y;
  10121. l->line_left = l->line_x = l->left;
  10122. l->run_x = l->left;
  10123. l->line_y = l->y;
  10124. l->line_h = 0;
  10125. l->nruns = 0;
  10126. l->space_pending = 0;
  10127. l->align = cs.align;
  10128. layout_block(l, n, &cs, depth + 1, lk);
  10129. if (l->y > row_bottom)
  10130. row_bottom = l->y;
  10131. n = nd->next;
  10132. }
  10133. l->left = row_left;
  10134. l->right = row_right;
  10135. l->y = row_bottom;
  10136. l->line_left = l->line_x = l->left;
  10137. l->run_x = l->left;
  10138. l->line_y = l->y;
  10139. l->line_h = 0;
  10140. l->nruns = 0;
  10141. l->space_pending = 0;
  10142. }
  10143. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  10144. * capped at four. Used by the project docs' card grids. A fixed
  10145. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  10146. static void layout_grid_auto(struct lay *l, unsigned int parent,
  10147. const struct br_style *pst, int depth,
  10148. unsigned short link)
  10149. {
  10150. unsigned int n, c;
  10151. int row_left = l->left, row_right = l->right;
  10152. int avail = row_right - row_left;
  10153. int gap = pst->grid_gap;
  10154. int minw = pst->width_kind == 1 ? pst->width : 200;
  10155. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  10156. if (avail < 32 || depth > 48) {
  10157. layout_children(l, parent, pst, depth, link);
  10158. return;
  10159. }
  10160. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10161. struct br_node *nd = &doc.nodes[c];
  10162. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  10163. layout_children(l, parent, pst, depth, link);
  10164. return;
  10165. }
  10166. }
  10167. if (minw < 80)
  10168. minw = 80;
  10169. ncols = (avail + gap) / (minw + gap);
  10170. if (ncols < 1)
  10171. ncols = 1;
  10172. if (ncols > 4)
  10173. ncols = 4;
  10174. if (pst->grid_auto > BR_GRID_FIXED) {
  10175. /* grid-template-columns: repeat(N, 1fr) */
  10176. ncols = pst->grid_auto - BR_GRID_FIXED;
  10177. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  10178. ncols--;
  10179. }
  10180. colw = (avail - gap * (ncols - 1)) / ncols;
  10181. if (colw < 24)
  10182. colw = 24;
  10183. x = row_left;
  10184. n = doc.nodes[parent].first;
  10185. while (n) {
  10186. struct br_node *nd = &doc.nodes[n];
  10187. struct br_style cs;
  10188. unsigned short lk = link;
  10189. int h;
  10190. if (nd->type == BR_NODE_TEXT) {
  10191. n = nd->next;
  10192. continue;
  10193. }
  10194. br_style_for(&doc, n, pst, &cs);
  10195. if (cs.display == BR_DISPLAY_NONE) {
  10196. n = nd->next;
  10197. continue;
  10198. }
  10199. if (nd->tag == BR_TAG_A && nd->href_off)
  10200. lk = (unsigned short)n;
  10201. cs.width_kind = 0;
  10202. cs.max_width_kind = 0;
  10203. l->left = x;
  10204. l->right = x + colw;
  10205. if (l->right < l->left + 8)
  10206. l->right = l->left + 8;
  10207. l->y = y;
  10208. l->line_left = l->line_x = l->left;
  10209. l->run_x = l->left;
  10210. l->line_y = l->y;
  10211. l->line_h = 0;
  10212. l->nruns = 0;
  10213. l->space_pending = 0;
  10214. l->align = cs.align;
  10215. layout_block(l, n, &cs, depth + 1, lk);
  10216. h = l->y - y;
  10217. if (h > row_h)
  10218. row_h = h;
  10219. col++;
  10220. n = nd->next;
  10221. if (col == ncols) {
  10222. y += row_h + gap;
  10223. x = row_left;
  10224. row_h = 0;
  10225. col = 0;
  10226. } else {
  10227. x += colw + gap;
  10228. }
  10229. }
  10230. if (col)
  10231. y += row_h;
  10232. else if (y > start_y)
  10233. y -= gap;
  10234. l->left = row_left;
  10235. l->right = row_right;
  10236. l->y = y;
  10237. l->line_left = l->line_x = l->left;
  10238. l->run_x = l->left;
  10239. l->line_y = l->y;
  10240. l->line_h = 0;
  10241. l->nruns = 0;
  10242. l->space_pending = 0;
  10243. }
  10244. /* Column widths are the widest cell in each column across every row, so all
  10245. * rows line up. The table model is still deliberately basic: no colspan,
  10246. * border-collapse or percentage columns. */
  10247. static void table_columns(struct lay *l, unsigned int table,
  10248. const struct br_style *pst, int avail,
  10249. int *raw, int maxcols, int *out_cols,
  10250. int *out_total)
  10251. {
  10252. unsigned int r, c;
  10253. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  10254. int fixed[12];
  10255. for (c = 0; c < (unsigned int)maxcols; c++) {
  10256. raw[c] = 0;
  10257. fixed[c] = 0;
  10258. }
  10259. /* Intrinsic widths of single-column cells. */
  10260. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10261. struct br_node *rn = &doc.nodes[r];
  10262. int col = 0;
  10263. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10264. continue;
  10265. for (c = rn->first; c; c = doc.nodes[c].next) {
  10266. struct br_node *cn = &doc.nodes[c];
  10267. struct br_style cs;
  10268. int w, span;
  10269. if (cn->type != BR_NODE_ELEM ||
  10270. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10271. continue;
  10272. span = cn->colspan ? cn->colspan : 1;
  10273. br_style_for(&doc, c, pst, &cs);
  10274. if (cs.display == BR_DISPLAY_NONE)
  10275. continue;
  10276. if (col + span > maxcols)
  10277. span = maxcols - col;
  10278. if (span < 1)
  10279. break;
  10280. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  10281. mp_px(&cs, 7, avail) +
  10282. mp_px(&cs, 5, avail) +
  10283. mp_px(&cs, 3, avail) +
  10284. mp_px(&cs, 1, avail) +
  10285. cs.border_w[0] + cs.border_w[1] +
  10286. cs.border_w[2] + cs.border_w[3];
  10287. if (w < 24)
  10288. w = 24;
  10289. if (span == 1) {
  10290. if (w > raw[col])
  10291. raw[col] = w;
  10292. }
  10293. if (col + span > cols)
  10294. cols = col + span;
  10295. col += span;
  10296. }
  10297. }
  10298. /* A colspan cell only has to be as wide as the sum of its columns. */
  10299. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10300. struct br_node *rn = &doc.nodes[r];
  10301. int col = 0;
  10302. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10303. continue;
  10304. for (c = rn->first; c; c = doc.nodes[c].next) {
  10305. struct br_node *cn = &doc.nodes[c];
  10306. struct br_style cs;
  10307. int span, w, sum, i;
  10308. if (cn->type != BR_NODE_ELEM ||
  10309. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10310. continue;
  10311. span = cn->colspan ? cn->colspan : 1;
  10312. if (col + span > maxcols)
  10313. span = maxcols - col;
  10314. if (span < 1)
  10315. break;
  10316. if (span > 1) {
  10317. br_style_for(&doc, c, pst, &cs);
  10318. if (cs.display != BR_DISPLAY_NONE) {
  10319. w = intrinsic_width(l->ui, c, &cs,
  10320. 0, avail) +
  10321. mp_px(&cs, 7, avail) +
  10322. mp_px(&cs, 5, avail) +
  10323. mp_px(&cs, 3, avail) +
  10324. mp_px(&cs, 1, avail) +
  10325. cs.border_w[0] + cs.border_w[1] +
  10326. cs.border_w[2] + cs.border_w[3];
  10327. sum = 0;
  10328. for (i = 0; i < span; i++)
  10329. sum += raw[col + i];
  10330. if (w > sum)
  10331. raw[col + span - 1] += w - sum;
  10332. }
  10333. }
  10334. col += span;
  10335. }
  10336. }
  10337. /* Explicit and percentage widths override intrinsic widths. */
  10338. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10339. struct br_node *rn = &doc.nodes[r];
  10340. int col = 0;
  10341. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10342. continue;
  10343. for (c = rn->first; c; c = doc.nodes[c].next) {
  10344. struct br_node *cn = &doc.nodes[c];
  10345. struct br_style cs;
  10346. int span;
  10347. if (cn->type != BR_NODE_ELEM ||
  10348. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10349. continue;
  10350. span = cn->colspan ? cn->colspan : 1;
  10351. if (col + span > maxcols)
  10352. span = maxcols - col;
  10353. if (span < 1)
  10354. break;
  10355. if (span == 1) {
  10356. br_style_for(&doc, c, pst, &cs);
  10357. if (cs.display != BR_DISPLAY_NONE) {
  10358. if (cs.width_kind == 1) {
  10359. raw[col] = cs.width;
  10360. fixed[col] = 1;
  10361. } else if (cs.width_kind == 2 ||
  10362. cs.width_kind == 3) {
  10363. raw[col] = style_width_px(&cs,
  10364. avail);
  10365. fixed[col] = 1;
  10366. }
  10367. }
  10368. }
  10369. col += span;
  10370. }
  10371. }
  10372. for (c = 0; c < (unsigned int)cols; c++) {
  10373. if (raw[c] < 8)
  10374. raw[c] = 8;
  10375. total += raw[c];
  10376. if (fixed[c])
  10377. fixed_sum += raw[c];
  10378. else {
  10379. free_raw += raw[c];
  10380. free_cols++;
  10381. }
  10382. }
  10383. if (fixed_sum > 0 && fixed_sum < avail) {
  10384. int free_avail = avail - fixed_sum;
  10385. int i;
  10386. if (free_raw > 0) {
  10387. for (i = 0; i < cols; i++)
  10388. if (!fixed[i])
  10389. raw[i] = free_avail * raw[i] /
  10390. free_raw;
  10391. } else if (free_cols > 0) {
  10392. for (i = 0; i < cols; i++)
  10393. if (!fixed[i])
  10394. raw[i] = free_avail / free_cols;
  10395. }
  10396. total = 0;
  10397. for (i = 0; i < cols; i++)
  10398. total += raw[i];
  10399. } else if (total < avail && total > 0) {
  10400. int i;
  10401. for (i = 0; i < cols; i++)
  10402. raw[i] = raw[i] * avail / total;
  10403. total = 0;
  10404. for (i = 0; i < cols; i++)
  10405. total += raw[i];
  10406. }
  10407. *out_cols = cols;
  10408. *out_total = total;
  10409. }
  10410. static void layout_table_row(struct lay *l, unsigned int row,
  10411. const struct br_style *pst, int depth,
  10412. unsigned short link)
  10413. {
  10414. unsigned int n, cell[12];
  10415. int raw[12], colstart[12], colspan[12];
  10416. int prefix[13];
  10417. int ncell = 0, total = 0, cols = 0, col = 0;
  10418. int row_left = l->left, row_right = l->right;
  10419. int avail = row_right - row_left;
  10420. int y = l->y, bottom = l->y;
  10421. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  10422. struct br_node *nd = &doc.nodes[n];
  10423. struct br_style cs;
  10424. int span;
  10425. if (nd->type == BR_NODE_TEXT) {
  10426. if (text_node_blank(nd))
  10427. continue;
  10428. layout_children(l, row, pst, depth, link);
  10429. return;
  10430. }
  10431. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  10432. layout_children(l, row, pst, depth, link);
  10433. return;
  10434. }
  10435. br_style_for(&doc, n, pst, &cs);
  10436. if (cs.display == BR_DISPLAY_NONE)
  10437. continue;
  10438. if (ncell >= 12) {
  10439. layout_children(l, row, pst, depth, link);
  10440. return;
  10441. }
  10442. span = nd->colspan ? nd->colspan : 1;
  10443. if (span > 12 - col)
  10444. span = 12 - col;
  10445. if (span < 1)
  10446. continue;
  10447. cell[ncell] = n;
  10448. colstart[ncell] = col;
  10449. colspan[ncell] = span;
  10450. col += span;
  10451. ncell++;
  10452. }
  10453. if (ncell < 1 || avail < 32) {
  10454. layout_children(l, row, pst, depth, link);
  10455. return;
  10456. }
  10457. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  10458. &total);
  10459. if (cols < 2 || total <= 0) {
  10460. int c;
  10461. total = 0;
  10462. for (c = 0; c < ncell; c++) {
  10463. struct br_style cs;
  10464. br_style_for(&doc, cell[c], pst, &cs);
  10465. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  10466. avail) +
  10467. mp_px(&cs, 7, avail) +
  10468. mp_px(&cs, 5, avail) +
  10469. mp_px(&cs, 3, avail) +
  10470. mp_px(&cs, 1, avail);
  10471. if (raw[c] < 24)
  10472. raw[c] = 24;
  10473. total += raw[c];
  10474. }
  10475. /* A one-column table still has to fill its own width; the
  10476. * intrinsic fallback above otherwise leaves the cell at its
  10477. * text width (HN's outer table and nested story table). */
  10478. if (total > 0 && total < avail) {
  10479. int c;
  10480. for (c = 0; c < ncell; c++)
  10481. raw[c] = raw[c] * avail / total;
  10482. total = avail;
  10483. }
  10484. }
  10485. prefix[0] = row_left;
  10486. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  10487. prefix[n + 1] = prefix[n] + raw[n];
  10488. for (n = 0; n < (unsigned int)ncell; n++) {
  10489. struct br_style cs;
  10490. int start = colstart[n];
  10491. int end = start + colspan[n];
  10492. int w;
  10493. if (end > cols)
  10494. end = cols;
  10495. if (start >= cols)
  10496. continue;
  10497. w = prefix[end] - prefix[start];
  10498. br_style_for(&doc, cell[n], pst, &cs);
  10499. /* The column width already reflects the cell's width property. */
  10500. cs.width_kind = 0;
  10501. cs.max_width_kind = 0;
  10502. if (w < 24)
  10503. w = 24;
  10504. if (w < 8)
  10505. w = 8;
  10506. l->left = prefix[start];
  10507. l->right = l->left + w;
  10508. l->y = y;
  10509. l->line_left = l->line_x = l->left;
  10510. l->run_x = l->left;
  10511. l->line_y = l->y;
  10512. l->line_h = 0;
  10513. l->nruns = 0;
  10514. l->space_pending = 0;
  10515. l->align = cs.align;
  10516. layout_block(l, cell[n], &cs, depth + 1, link);
  10517. if (l->y > bottom)
  10518. bottom = l->y;
  10519. }
  10520. l->left = row_left;
  10521. l->right = row_right;
  10522. l->y = bottom;
  10523. l->line_left = l->line_x = l->left;
  10524. l->run_x = l->left;
  10525. l->line_y = l->y;
  10526. l->line_h = 0;
  10527. l->nruns = 0;
  10528. l->space_pending = 0;
  10529. }
  10530. #define TBL_MAX_ROWS 32
  10531. #define TBL_MAX_COLS 12
  10532. #define TBL_MAX_CELLS 128
  10533. struct tbl_cell {
  10534. unsigned int node;
  10535. unsigned char row, col, rowspan, colspan;
  10536. int height;
  10537. };
  10538. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  10539. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  10540. static int table_active;
  10541. static int table_has_rowspan(unsigned int table)
  10542. {
  10543. unsigned int r, c;
  10544. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10545. struct br_node *rn = &doc.nodes[r];
  10546. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10547. continue;
  10548. for (c = rn->first; c; c = doc.nodes[c].next) {
  10549. struct br_node *cn = &doc.nodes[c];
  10550. if (cn->type == BR_NODE_ELEM &&
  10551. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  10552. cn->rowspan > 1)
  10553. return 1;
  10554. }
  10555. }
  10556. return 0;
  10557. }
  10558. static void table_cell_style(unsigned int row, unsigned int cell,
  10559. const struct br_style *st, struct br_style *out)
  10560. {
  10561. struct br_style trs;
  10562. br_style_for(&doc, row, st, &trs);
  10563. br_style_for(&doc, cell, &trs, out);
  10564. }
  10565. /* Tables that use rowspan need row heights before anything is painted. This
  10566. * path builds a small occupancy grid, measures the natural cell heights, then
  10567. * lays every cell out at its row/column position. Tables without rowspan
  10568. * keep the lighter per-row path in layout_table_row(). */
  10569. static void layout_table(struct lay *l, unsigned int table,
  10570. const struct br_style *st, int depth,
  10571. unsigned short link)
  10572. {
  10573. unsigned int rows[TBL_MAX_ROWS];
  10574. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  10575. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  10576. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  10577. int free_raw = 0, free_cols = 0;
  10578. int table_left = l->left, table_right = l->right;
  10579. int top = l->y, avail = table_right - table_left;
  10580. unsigned int r, c;
  10581. int i, rr, cc;
  10582. if (depth > 48 || table_active) {
  10583. layout_children(l, table, st, depth, link);
  10584. return;
  10585. }
  10586. table_active = 1;
  10587. for (r = doc.nodes[table].first;
  10588. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  10589. struct br_node *rn = &doc.nodes[r];
  10590. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  10591. rows[nrows++] = r;
  10592. }
  10593. if (!nrows) {
  10594. table_active = 0;
  10595. layout_children(l, table, st, depth, link);
  10596. return;
  10597. }
  10598. for (rr = 0; rr < nrows; rr++)
  10599. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  10600. tbl_at[rr][cc] = 0;
  10601. for (rr = 0; rr < nrows; rr++) {
  10602. int col = 0;
  10603. for (c = doc.nodes[rows[rr]].first; c;
  10604. c = doc.nodes[c].next) {
  10605. struct br_node *cn = &doc.nodes[c];
  10606. struct br_style cs;
  10607. int rs, csn;
  10608. if (cn->type != BR_NODE_ELEM ||
  10609. (cn->tag != BR_TAG_TD &&
  10610. cn->tag != BR_TAG_TH))
  10611. continue;
  10612. table_cell_style(rows[rr], c, st, &cs);
  10613. if (cs.display == BR_DISPLAY_NONE)
  10614. continue;
  10615. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  10616. col++;
  10617. if (col >= TBL_MAX_COLS)
  10618. break;
  10619. rs = cn->rowspan ? cn->rowspan : 1;
  10620. csn = cn->colspan ? cn->colspan : 1;
  10621. if (rr + rs > nrows)
  10622. rs = nrows - rr;
  10623. if (col + csn > TBL_MAX_COLS)
  10624. csn = TBL_MAX_COLS - col;
  10625. if (rs < 1 || csn < 1)
  10626. continue;
  10627. if (ncells >= TBL_MAX_CELLS)
  10628. break;
  10629. tbl_cells[ncells].node = c;
  10630. tbl_cells[ncells].row = (unsigned char)rr;
  10631. tbl_cells[ncells].col = (unsigned char)col;
  10632. tbl_cells[ncells].rowspan = (unsigned char)rs;
  10633. tbl_cells[ncells].colspan = (unsigned char)csn;
  10634. tbl_cells[ncells].height = 0;
  10635. for (i = rr; i < rr + rs; i++)
  10636. for (int j = col; j < col + csn; j++)
  10637. tbl_at[i][j] =
  10638. (unsigned short)(ncells + 1);
  10639. ncells++;
  10640. col += csn;
  10641. if (col > cols)
  10642. cols = col;
  10643. }
  10644. }
  10645. if (!ncells || cols < 1) {
  10646. table_active = 0;
  10647. layout_children(l, table, st, depth, link);
  10648. return;
  10649. }
  10650. for (i = 0; i < cols; i++) {
  10651. raw[i] = 0;
  10652. fixed[i] = 0;
  10653. }
  10654. /* Intrinsic widths of single-column cells. */
  10655. for (i = 0; i < ncells; i++) {
  10656. struct br_style cs;
  10657. int w;
  10658. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10659. st, &cs);
  10660. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10661. mp_px(&cs, 7, avail) +
  10662. mp_px(&cs, 5, avail) +
  10663. mp_px(&cs, 3, avail) +
  10664. mp_px(&cs, 1, avail) +
  10665. cs.border_w[0] + cs.border_w[1] +
  10666. cs.border_w[2] + cs.border_w[3];
  10667. if (w < 24)
  10668. w = 24;
  10669. if (tbl_cells[i].colspan == 1) {
  10670. int col = tbl_cells[i].col;
  10671. if (w > raw[col])
  10672. raw[col] = w;
  10673. }
  10674. }
  10675. /* A spanning cell only needs the sum of its columns to be large
  10676. * enough; put the deficit in the last column. */
  10677. for (i = 0; i < ncells; i++) {
  10678. struct br_style cs;
  10679. int w, sum, col, span;
  10680. if (tbl_cells[i].colspan < 2)
  10681. continue;
  10682. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10683. st, &cs);
  10684. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10685. mp_px(&cs, 7, avail) +
  10686. mp_px(&cs, 5, avail) +
  10687. mp_px(&cs, 3, avail) +
  10688. mp_px(&cs, 1, avail) +
  10689. cs.border_w[0] + cs.border_w[1] +
  10690. cs.border_w[2] + cs.border_w[3];
  10691. col = tbl_cells[i].col;
  10692. span = tbl_cells[i].colspan;
  10693. sum = 0;
  10694. for (int j = 0; j < span; j++)
  10695. sum += raw[col + j];
  10696. if (w > sum)
  10697. raw[col + span - 1] += w - sum;
  10698. }
  10699. /* Explicit/percentage widths, as in table_columns(). */
  10700. for (i = 0; i < ncells; i++) {
  10701. struct br_style cs;
  10702. int col;
  10703. if (tbl_cells[i].colspan != 1)
  10704. continue;
  10705. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10706. st, &cs);
  10707. col = tbl_cells[i].col;
  10708. if (cs.width_kind == 1) {
  10709. raw[col] = cs.width;
  10710. fixed[col] = 1;
  10711. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  10712. raw[col] = style_width_px(&cs, avail);
  10713. fixed[col] = 1;
  10714. }
  10715. }
  10716. for (i = 0; i < cols; i++) {
  10717. if (raw[i] < 8)
  10718. raw[i] = 8;
  10719. total += raw[i];
  10720. if (fixed[i])
  10721. fixed_sum += raw[i];
  10722. else {
  10723. free_raw += raw[i];
  10724. free_cols++;
  10725. }
  10726. }
  10727. if (fixed_sum > 0 && fixed_sum < avail) {
  10728. int free_avail = avail - fixed_sum;
  10729. if (free_raw > 0) {
  10730. for (i = 0; i < cols; i++)
  10731. if (!fixed[i])
  10732. raw[i] = free_avail * raw[i] /
  10733. free_raw;
  10734. } else if (free_cols > 0) {
  10735. for (i = 0; i < cols; i++)
  10736. if (!fixed[i])
  10737. raw[i] = free_avail / free_cols;
  10738. }
  10739. } else if (total < avail && total > 0) {
  10740. for (i = 0; i < cols; i++)
  10741. raw[i] = raw[i] * avail / total;
  10742. }
  10743. prefix[0] = table_left;
  10744. for (i = 0; i < cols; i++)
  10745. prefix[i + 1] = prefix[i] + raw[i];
  10746. /* Measure natural cell heights with the column widths. */
  10747. for (i = 0; i < ncells; i++) {
  10748. struct br_style cs;
  10749. int col = tbl_cells[i].col;
  10750. int span = tbl_cells[i].colspan;
  10751. int w = prefix[col + span] - prefix[col];
  10752. int sl = l->left, sr = l->right, sy = l->y;
  10753. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10754. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10755. int sal = l->align, sdraw = l->draw;
  10756. struct ngui *sui = l->ui;
  10757. if (w < 8)
  10758. w = 8;
  10759. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10760. st, &cs);
  10761. cs.width_kind = 0;
  10762. cs.max_width_kind = 0;
  10763. l->draw = 0;
  10764. l->ui = 0;
  10765. l->left = prefix[col];
  10766. l->right = l->left + w;
  10767. l->y = 0;
  10768. l->line_left = l->line_x = l->left;
  10769. l->run_x = l->left;
  10770. l->line_y = 0;
  10771. l->line_h = 0;
  10772. l->nruns = 0;
  10773. l->space_pending = 0;
  10774. l->align = cs.align;
  10775. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10776. tbl_cells[i].height = block_h[tbl_cells[i].node];
  10777. l->left = sl;
  10778. l->right = sr;
  10779. l->y = sy;
  10780. l->line_x = slx;
  10781. l->run_x = srx;
  10782. l->line_y = sly;
  10783. l->line_h = slh;
  10784. l->nruns = snr;
  10785. l->space_pending = ssp;
  10786. l->align = sal;
  10787. l->draw = sdraw;
  10788. l->ui = sui;
  10789. }
  10790. for (i = 0; i < nrows; i++)
  10791. rowh[i] = 0;
  10792. for (i = 0; i < ncells; i++) {
  10793. int row = tbl_cells[i].row;
  10794. if (tbl_cells[i].rowspan == 1) {
  10795. if (tbl_cells[i].height > rowh[row])
  10796. rowh[row] = tbl_cells[i].height;
  10797. }
  10798. }
  10799. for (i = 0; i < ncells; i++) {
  10800. int row = tbl_cells[i].row;
  10801. int span = tbl_cells[i].rowspan;
  10802. int sum = 0;
  10803. if (span < 2)
  10804. continue;
  10805. for (int j = 0; j < span; j++)
  10806. sum += rowh[row + j];
  10807. if (sum < tbl_cells[i].height)
  10808. rowh[row + span - 1] +=
  10809. tbl_cells[i].height - sum;
  10810. }
  10811. for (i = 0; i < nrows; i++)
  10812. if (rowh[i] < 8)
  10813. rowh[i] = 8;
  10814. rowy[0] = top;
  10815. for (i = 1; i < nrows; i++)
  10816. rowy[i] = rowy[i - 1] + rowh[i - 1];
  10817. if (!l->draw) {
  10818. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10819. table_active = 0;
  10820. return;
  10821. }
  10822. for (i = 0; i < ncells; i++) {
  10823. struct br_style cs;
  10824. int col = tbl_cells[i].col;
  10825. int span = tbl_cells[i].colspan;
  10826. int row = tbl_cells[i].row;
  10827. int rspan = tbl_cells[i].rowspan;
  10828. int w = prefix[col + span] - prefix[col];
  10829. int h = 0;
  10830. int sl = l->left, sr = l->right, sy = l->y;
  10831. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10832. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10833. int sal = l->align;
  10834. int deco;
  10835. for (int j = 0; j < rspan; j++)
  10836. h += rowh[row + j];
  10837. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  10838. cs.width_kind = 0;
  10839. cs.max_width_kind = 0;
  10840. cs.box_sizing = 0;
  10841. deco = mp_px(&cs, 4, avail) +
  10842. mp_px(&cs, 6, avail) +
  10843. cs.border_w[0] + cs.border_w[2];
  10844. cs.height_kind = 1;
  10845. cs.height = h > deco ? h - deco : 0;
  10846. /* The block painter reads block_h[] from the measure pass; make
  10847. * the table cell fill its row/rowspan, not just its content. */
  10848. if (h > 0 && h < 65536)
  10849. block_h[tbl_cells[i].node] = (unsigned short)h;
  10850. l->left = prefix[col];
  10851. l->right = l->left + w;
  10852. l->y = rowy[row];
  10853. l->line_left = l->line_x = l->left;
  10854. l->run_x = l->left;
  10855. l->line_y = l->y;
  10856. l->line_h = 0;
  10857. l->nruns = 0;
  10858. l->space_pending = 0;
  10859. l->align = cs.align;
  10860. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10861. l->left = sl;
  10862. l->right = sr;
  10863. l->y = sy;
  10864. l->line_x = slx;
  10865. l->run_x = srx;
  10866. l->line_y = sly;
  10867. l->line_h = slh;
  10868. l->nruns = snr;
  10869. l->space_pending = ssp;
  10870. l->align = sal;
  10871. }
  10872. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10873. table_active = 0;
  10874. }
  10875. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  10876. * flow so they sit above it, like CSS painting order. Their flow origin is
  10877. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  10878. struct br_deferred {
  10879. unsigned int node;
  10880. int flow_y, flow_left, flow_right;
  10881. int parent_top; /* the parent box top, for sticky clamping */
  10882. unsigned short link;
  10883. signed short z_index;
  10884. unsigned char z_set;
  10885. unsigned int order;
  10886. };
  10887. /* Positioned boxes painted after the flow. News front pages have one or two
  10888. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  10889. * old 16 entries the rest fell back into the flow, so a hero image landed
  10890. * below its padding-top aspect box instead of on top of it. */
  10891. #define BR_MAX_DEFERRED 256
  10892. static struct br_deferred deferred[BR_MAX_DEFERRED];
  10893. static int ndeferred;
  10894. /* Outer width of an element's empty ::before (pe 1) / ::after (pe 2) icon
  10895. * box, 0 when it has none; *ps receives the pseudo-element's style. */
  10896. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  10897. struct br_style *ps, int base)
  10898. {
  10899. char buf[8];
  10900. int w, h;
  10901. if (!doc.npe_rules ||
  10902. br_pseudo(&doc, node, pe, st, ps, buf, sizeof(buf)) ||
  10903. ps->content != BR_CONTENT_EMPTY || ps->display == BR_DISPLAY_NONE)
  10904. return 0;
  10905. w = ps->width_kind ? style_width_px(ps, base) : 0;
  10906. h = ps->height_kind ? style_height_px(ps, base) : 0;
  10907. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  10908. w = (int)ps->min_width;
  10909. if (w <= 0)
  10910. w = h;
  10911. if (w <= 0 || w > 512)
  10912. return 0;
  10913. return w + (ps->ml_auto ? 0 : mp_px(ps, 3, base)) + mp_px(ps, 1, base);
  10914. }
  10915. /* An empty ::before/::after with a size and a background: one run the
  10916. * size of the box. Only data: background images are drawn (decoded at
  10917. * the background-size); `margin-left: auto` inside a flex parent pushes
  10918. * the box to the line's right edge like the flex row would. */
  10919. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  10920. const struct br_style *ps, unsigned short link)
  10921. {
  10922. struct lay_run *r;
  10923. int lw = l->line_right - l->line_left, w, h, ml, mr, tw, th;
  10924. const char *url = ps->bg_image ? br_bg_image_url(ps->bg_image - 1) : "";
  10925. if (lw < 8)
  10926. lw = 8;
  10927. w = ps->width_kind ? style_width_px(ps, lw) : 0;
  10928. h = ps->height_kind ? style_height_px(ps, lw) : 0;
  10929. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  10930. w = (int)ps->min_width;
  10931. if (w <= 0)
  10932. w = h;
  10933. if (h <= 0)
  10934. h = w;
  10935. if (w <= 0 || w > 512 || h > 512)
  10936. return;
  10937. ml = ps->ml_auto ? 0 : mp_px(ps, 3, lw);
  10938. mr = mp_px(ps, 1, lw);
  10939. if (ml < 0)
  10940. ml = 0;
  10941. if (mr < 0)
  10942. mr = 0;
  10943. if (l->line_x + ml + w > l->line_right &&
  10944. (l->nruns > 0 || l->line_x > l->line_left))
  10945. flush_line(l);
  10946. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  10947. flush_line(l);
  10948. if (l->nruns == 0) {
  10949. l->line_y = l->y;
  10950. l->line_h = 0;
  10951. start_line(l, ps);
  10952. }
  10953. if (ps->ml_auto && parent->display == BR_DISPLAY_FLEX &&
  10954. l->line_right - w - mr > l->line_x)
  10955. l->line_x = l->line_right - w - mr;
  10956. else
  10957. l->line_x += ml;
  10958. r = &l->runs[l->nruns++];
  10959. memset(r, 0, sizeof(*r));
  10960. r->gap = (unsigned short)(l->line_x > l->run_x ?
  10961. l->line_x - l->run_x : 0);
  10962. r->img = RUN_PBOX;
  10963. r->href = link;
  10964. r->iw = (unsigned short)w;
  10965. r->ih = (unsigned short)h;
  10966. r->w = (unsigned short)w;
  10967. r->font_px = ps->font_px;
  10968. r->pb_has_bg = ps->has_bg;
  10969. r->pb_bg = ps->bg;
  10970. r->pb_img = -1;
  10971. if (ps->transform_set) {
  10972. r->transform_scale = 1;
  10973. r->scale_x = ps->scale_x;
  10974. r->scale_y = ps->scale_y;
  10975. r->rotate_x100 = ps->rotate_x100;
  10976. }
  10977. /* Background size and position, as draw_bg_image() resolves them. */
  10978. tw = w;
  10979. th = h;
  10980. if (ps->bg_size_kind == 1 || ps->bg_size_kind == 2) {
  10981. int bw = ps->bg_size_w, bh = ps->bg_size_h;
  10982. if (ps->bg_size_kind == 2) {
  10983. bw = bw ? w * bw / 100 : 0;
  10984. bh = bh ? h * bh / 100 : 0;
  10985. }
  10986. tw = bw ? bw : (bh ? bh : w);
  10987. th = bh ? bh : tw;
  10988. }
  10989. if (tw > 0 && th > 0 && tw <= 512 && th <= 512 && url[0])
  10990. r->pb_img = (short)data_url_image(url, tw, th);
  10991. r->pb_w = (short)tw;
  10992. r->pb_h = (short)th;
  10993. r->pb_x = (short)(ps->bg_pos_x_kind == 1 ?
  10994. (w - tw) * ps->bg_pos_x / 100 : ps->bg_pos_x);
  10995. r->pb_y = (short)(ps->bg_pos_y_kind == 1 ?
  10996. (h - th) * ps->bg_pos_y / 100 : ps->bg_pos_y);
  10997. l->line_x += w + mr;
  10998. l->run_x = l->line_x;
  10999. if (l->line_h < h)
  11000. l->line_h = h;
  11001. }
  11002. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  11003. * element's line. A block-level pseudo-element gets its own line; its box
  11004. * (margins, padding, background) is not drawn. */
  11005. static void emit_pseudo(struct lay *l, unsigned int node,
  11006. const struct br_style *st, int pe, unsigned short link)
  11007. {
  11008. char buf[160];
  11009. struct br_style ps;
  11010. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  11011. unsigned int i = 0;
  11012. int block, space_w;
  11013. if (!n && ps.content == BR_CONTENT_EMPTY &&
  11014. ps.display != BR_DISPLAY_NONE) {
  11015. emit_pseudo_box(l, st, &ps, link);
  11016. return;
  11017. }
  11018. if (!n)
  11019. return;
  11020. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  11021. if (block)
  11022. flush_line(l);
  11023. if (ps.uppercase)
  11024. for (i = 0; i < n; i++)
  11025. if (buf[i] >= 'a' && buf[i] <= 'z')
  11026. buf[i] = (char)(buf[i] - 'a' + 'A');
  11027. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  11028. if (space_w <= 0)
  11029. space_w = 8;
  11030. i = 0;
  11031. while (i < n) {
  11032. char word[28];
  11033. unsigned int k = 0;
  11034. int w;
  11035. if (buf[i] == ' ') {
  11036. l->space_pending = 1;
  11037. i++;
  11038. continue;
  11039. }
  11040. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  11041. word[k++] = buf[i++];
  11042. word[k] = '\0';
  11043. if (l->space_pending &&
  11044. (l->nruns > 0 || l->line_x > l->line_left) &&
  11045. l->line_x + space_w <= l->line_right)
  11046. l->line_x += space_w;
  11047. l->space_pending = 0;
  11048. w = (int)face_text_width(l->ui, &ps, word, k);
  11049. if (l->line_x + w > l->line_right &&
  11050. (l->nruns > 0 || l->line_x > l->line_left))
  11051. flush_line(l);
  11052. add_run(l, 0, 0, &ps, link, word);
  11053. }
  11054. if (block)
  11055. flush_line(l);
  11056. }
  11057. /* An out-of-flow child (absolute/fixed, or a relative/sticky box with a
  11058. * z-index): measured in place, painted from the deferred stacked pass
  11059. * against its containing block. Shared by block and flex layout, so an
  11060. * absolute icon inside a flex row (a password field's reveal button) is
  11061. * not laid out as one of the row's items. Returns 1 when it handled n. */
  11062. static int layout_out_of_flow(struct lay *l, unsigned int n,
  11063. const struct br_style *cs, int depth,
  11064. unsigned short lk)
  11065. {
  11066. if (!(cs->pos == 1 || cs->pos == 2 ||
  11067. ((cs->pos == 3 || cs->pos == 4) && cs->z_set)))
  11068. return 0;
  11069. if ((cs->pos == 3 || cs->pos == 4) && l->draw &&
  11070. ndeferred < BR_MAX_DEFERRED) {
  11071. /* Relative or sticky z-index (a sticky site
  11072. * header): measure and advance the flow without
  11073. * painting, then paint it in the deferred
  11074. * (stacked) pass, above the content after it. */
  11075. int fy = l->y, fl = l->left, fr = l->right;
  11076. int save_draw = l->draw;
  11077. l->draw = 0;
  11078. layout_block(l, n, cs, depth + 1, lk);
  11079. l->draw = save_draw;
  11080. deferred[ndeferred].node = n;
  11081. deferred[ndeferred].parent_top = l->parent_top;
  11082. deferred[ndeferred].flow_y = fy;
  11083. deferred[ndeferred].flow_left = fl;
  11084. deferred[ndeferred].flow_right = fr;
  11085. deferred[ndeferred].link = lk;
  11086. deferred[ndeferred].z_index = cs->z_index;
  11087. deferred[ndeferred].z_set = cs->z_set;
  11088. deferred[ndeferred].order = (unsigned int)ndeferred;
  11089. ndeferred++;
  11090. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  11091. deferred[ndeferred].node = n;
  11092. deferred[ndeferred].parent_top = l->parent_top;
  11093. deferred[ndeferred].flow_y =
  11094. cs->pos == 1 ? l->cb_top : l->y;
  11095. deferred[ndeferred].flow_left =
  11096. cs->pos == 1 ? l->cb_left : l->left;
  11097. deferred[ndeferred].flow_right =
  11098. cs->pos == 1 ? l->cb_right : l->right;
  11099. deferred[ndeferred].link = lk;
  11100. deferred[ndeferred].z_index = cs->z_index;
  11101. deferred[ndeferred].z_set = cs->z_set;
  11102. deferred[ndeferred].order = (unsigned int)ndeferred;
  11103. ndeferred++;
  11104. } else if (l->draw && cs->pos == 1) {
  11105. /* Deferred list full: paint in place, but still
  11106. * against the containing block, not the flow. */
  11107. int fy = l->y, fl = l->left, fr = l->right;
  11108. l->y = l->cb_top;
  11109. l->left = l->cb_left;
  11110. l->right = l->cb_right;
  11111. layout_block(l, n, cs, depth + 1, lk);
  11112. l->y = fy;
  11113. l->left = fl;
  11114. l->right = fr;
  11115. } else {
  11116. layout_block(l, n, cs, depth + 1, lk);
  11117. }
  11118. if (cs->pos == 1 && block_h[n] &&
  11119. doc.nodes[n].class_off) {
  11120. const char *cl = doc.attrs +
  11121. doc.nodes[n].class_off;
  11122. if ((contains_ci(cl, "poster-wrapper") ||
  11123. contains_ci(cl, "ts-picture")) &&
  11124. !has_skeleton_sibling(n))
  11125. l->y += block_h[n];
  11126. }
  11127. return 1;
  11128. }
  11129. static void layout_children(struct lay *l, unsigned int parent,
  11130. const struct br_style *pst, int depth,
  11131. unsigned short link)
  11132. {
  11133. unsigned int n;
  11134. if (depth > 48)
  11135. return;
  11136. emit_pseudo(l, parent, pst, 1, link);
  11137. n = doc.nodes[parent].first;
  11138. while (n) {
  11139. struct br_node *nd = &doc.nodes[n];
  11140. struct br_style cs;
  11141. unsigned short lk = link;
  11142. if (nd->type == BR_NODE_TEXT) {
  11143. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  11144. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  11145. n = nd->next;
  11146. continue;
  11147. }
  11148. br_style_for(&doc, n, pst, &cs);
  11149. if (cs.display == BR_DISPLAY_NONE) {
  11150. n = nd->next;
  11151. continue;
  11152. }
  11153. if (cs.clear && l->float_active) {
  11154. flush_line(l);
  11155. if (l->y < l->float_bottom)
  11156. l->y = l->float_bottom;
  11157. l->float_active = 0;
  11158. l->line_x = l->left;
  11159. l->run_x = l->left;
  11160. l->line_left = l->left;
  11161. l->line_right = l->right;
  11162. l->line_y = l->y;
  11163. l->line_h = 0;
  11164. l->nruns = 0;
  11165. l->space_pending = 0;
  11166. }
  11167. if (nd->tag == BR_TAG_A && nd->href_off)
  11168. lk = (unsigned short)n;
  11169. if (layout_out_of_flow(l, n, &cs, depth, lk)) {
  11170. n = nd->next;
  11171. continue;
  11172. }
  11173. if (nd->tag == BR_TAG_BR) {
  11174. flush_line(l);
  11175. n = nd->next;
  11176. continue;
  11177. }
  11178. if (nd->tag == BR_TAG_HR) {
  11179. flush_line(l);
  11180. if (l->draw)
  11181. ngui_fill_rect(l->ui,
  11182. (struct ngui_rect){l->left, l->y + 2,
  11183. l->right - l->left, 1}, BR_GRAY);
  11184. l->y += 8;
  11185. n = nd->next;
  11186. continue;
  11187. }
  11188. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  11189. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  11190. !button_has_elements(n)) {
  11191. if (!(nd->tag == BR_TAG_INPUT &&
  11192. s_eq(br_type(&doc, n), "hidden"))) {
  11193. form_fill_line = pst->display ==
  11194. BR_DISPLAY_FLEX &&
  11195. pst->flex_col;
  11196. add_form_run(l, n, &cs, lk);
  11197. form_fill_line = 0;
  11198. }
  11199. n = nd->next;
  11200. continue;
  11201. }
  11202. if (nd->tag == BR_TAG_IMG) {
  11203. add_image_run(l, n, &cs, lk);
  11204. n = nd->next;
  11205. continue;
  11206. }
  11207. if (nd->tag == BR_TAG_SVG &&
  11208. (cs.display == BR_DISPLAY_INLINE ||
  11209. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  11210. !cs.float_left) {
  11211. add_svg_run(l, n, &cs, lk);
  11212. n = nd->next;
  11213. continue;
  11214. }
  11215. if (nd->tag == BR_TAG_VIDEO) {
  11216. layout_block(l, n, &cs, depth + 1, lk);
  11217. n = nd->next;
  11218. continue;
  11219. }
  11220. if (cs.float_left) {
  11221. n = layout_float_group(l, n, pst, depth, lk);
  11222. continue;
  11223. }
  11224. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  11225. inline_block_flows(n, &cs, 0)) {
  11226. layout_children(l, n, &cs, depth + 1, lk);
  11227. n = nd->next;
  11228. continue;
  11229. }
  11230. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  11231. n = layout_inline_blocks(l, n, pst, depth, link);
  11232. continue;
  11233. }
  11234. /* A flex container is block-level like any block box even when
  11235. * the element is an inline tag such as <a> (a link card with
  11236. * display:flex is common on news sites). Without the block box
  11237. * its children were laid out in the parent flow with a 0x0 box
  11238. * of their own. */
  11239. /* inline-flex around inline content only ("| mehr" link
  11240. * tails, icon+label pills) stays in the text line. */
  11241. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  11242. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  11243. !flex_wants_row(n, &cs)) {
  11244. layout_children(l, n, &cs, depth + 1, lk);
  11245. } else if (cs.display == BR_DISPLAY_BLOCK ||
  11246. cs.display == BR_DISPLAY_FLEX ||
  11247. br_tag_is_block(nd->tag))
  11248. layout_block(l, n, &cs, depth + 1, lk);
  11249. else {
  11250. layout_children(l, n, &cs, depth + 1, lk);
  11251. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  11252. l->space_pending = 1;
  11253. }
  11254. n = nd->next;
  11255. }
  11256. emit_pseudo(l, parent, pst, 2, link);
  11257. }
  11258. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  11259. * runs and a recursive page can otherwise overflow the stack. */
  11260. static struct lay layout_state;
  11261. static int measure_page(int left, int right)
  11262. {
  11263. struct lay *l = &layout_state;
  11264. struct br_style base = base_style();
  11265. unsigned int i;
  11266. for (i = 0; i < BR_MAX_NODES; i++) {
  11267. block_h[i] = 0;
  11268. flex_stretch_h[i] = 0;
  11269. img_top[i] = 0;
  11270. block_top[i] = 0;
  11271. img_h[i] = 0;
  11272. layout_boxes[i].valid = 0;
  11273. }
  11274. memset(li_marker, 0, sizeof(li_marker));
  11275. l->draw = 0;
  11276. l->ui = &ui;
  11277. l->left = left;
  11278. l->right = right;
  11279. l->y = 0;
  11280. l->line_x = left;
  11281. l->run_x = left;
  11282. l->line_left = left;
  11283. l->line_right = right;
  11284. l->line_y = 0;
  11285. l->line_h = 0;
  11286. l->align = BR_ALIGN_LEFT;
  11287. l->cb_h = layout_view_h;
  11288. l->float_active = 0;
  11289. l->parent_top = 0;
  11290. l->cb_left = left;
  11291. l->cb_right = right;
  11292. l->cb_top = 0;
  11293. l->depth = 0;
  11294. l->nruns = 0;
  11295. l->space_pending = 0;
  11296. base = root_style();
  11297. layout_children(l, doc.root, &base, 0, 0);
  11298. return l->y + 8;
  11299. }
  11300. static int deferred_cmp(const struct br_deferred *a,
  11301. const struct br_deferred *b)
  11302. {
  11303. int az = a->z_set ? a->z_index : 0;
  11304. int bz = b->z_set ? b->z_index : 0;
  11305. if (az != bz)
  11306. return az < bz ? -1 : 1;
  11307. if (a->order != b->order)
  11308. return a->order < b->order ? -1 : 1;
  11309. return 0;
  11310. }
  11311. static void sort_deferred(void)
  11312. {
  11313. int i;
  11314. for (i = 1; i < ndeferred; i++) {
  11315. struct br_deferred key = deferred[i];
  11316. int j = i;
  11317. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  11318. deferred[j] = deferred[j - 1];
  11319. j--;
  11320. }
  11321. deferred[j] = key;
  11322. }
  11323. }
  11324. static void render_page(int left, int right, int y0)
  11325. {
  11326. struct lay *l = &layout_state;
  11327. struct br_style base = base_style();
  11328. l->draw = 1;
  11329. l->ui = &ui;
  11330. l->left = left;
  11331. l->right = right;
  11332. l->y = y0;
  11333. l->line_x = left;
  11334. l->run_x = left;
  11335. l->line_left = left;
  11336. l->line_right = right;
  11337. l->line_y = y0;
  11338. l->line_h = 0;
  11339. l->align = BR_ALIGN_LEFT;
  11340. l->cb_h = layout_view_h;
  11341. l->float_active = 0;
  11342. l->parent_top = 0;
  11343. l->cb_left = left;
  11344. l->cb_right = right;
  11345. l->cb_top = y0;
  11346. l->depth = 0;
  11347. l->nruns = 0;
  11348. l->space_pending = 0;
  11349. nhits = 0;
  11350. ndeferred = 0;
  11351. base = root_style();
  11352. layout_children(l, doc.root, &base, 0, 0);
  11353. sort_deferred();
  11354. {
  11355. int i;
  11356. for (i = 0; i < ndeferred; i++) {
  11357. struct br_style st;
  11358. br_style_for(&doc, deferred[i].node, &base, &st);
  11359. if (st.display == BR_DISPLAY_NONE)
  11360. continue;
  11361. l->draw = 1;
  11362. l->left = deferred[i].flow_left;
  11363. l->right = deferred[i].flow_right;
  11364. l->y = deferred[i].flow_y;
  11365. l->parent_top = deferred[i].parent_top;
  11366. l->line_left = l->line_x = l->left;
  11367. l->run_x = l->left;
  11368. l->line_y = l->y;
  11369. l->line_h = 0;
  11370. l->nruns = 0;
  11371. l->space_pending = 0;
  11372. l->align = st.align;
  11373. if (st.pos == 2 && block_h[deferred[i].node]) {
  11374. struct ngui_rect clip;
  11375. int ch = block_h[deferred[i].node] + 24;
  11376. int pr = page_rect.x + page_rect.w - 12;
  11377. int x0 = page_rect.x, x1 = pr;
  11378. int y0 = page_rect.y;
  11379. /* A box placed by `bottom` (a page footer) is
  11380. * clipped and filled where layout_block puts
  11381. * it, against the bottom edge. */
  11382. if (st.bottom_set && !st.top_set) {
  11383. ch = block_h[deferred[i].node] +
  11384. mp_px(&st, 0, pr - page_rect.x) +
  11385. mp_px(&st, 2, pr - page_rect.x);
  11386. y0 = page_rect.y + page_rect.h -
  11387. st.bottom - ch;
  11388. }
  11389. /* The background pre-fill spans the box's own
  11390. * columns, not the whole page: Docusaurus parks
  11391. * a white "Skip to main content" link at
  11392. * `left: 100%` with a z-index above the navbar,
  11393. * and a full-width fill painted over the bar. */
  11394. if (st.left_set)
  11395. x0 = page_rect.x + st.left;
  11396. else if (!st.right_set)
  11397. x0 = deferred[i].flow_left;
  11398. if (st.width_kind == 1) {
  11399. if (st.right_set && !st.left_set)
  11400. x0 = pr - st.right - st.width;
  11401. x1 = x0 + st.width;
  11402. } else if (st.right_set) {
  11403. x1 = pr - st.right;
  11404. }
  11405. if (x0 >= pr || x1 <= page_rect.x)
  11406. continue; /* entirely off-screen */
  11407. if (x0 < page_rect.x)
  11408. x0 = page_rect.x;
  11409. if (x1 > pr)
  11410. x1 = pr;
  11411. if (y0 < page_rect.y) {
  11412. ch -= page_rect.y - y0;
  11413. y0 = page_rect.y;
  11414. }
  11415. clip.x = x0;
  11416. clip.y = y0;
  11417. clip.w = x1 - x0;
  11418. if (ch > page_rect.h)
  11419. ch = page_rect.h;
  11420. if (ch <= 0)
  11421. continue;
  11422. clip.h = ch;
  11423. ngui_push_clip(&ui, clip);
  11424. if (st.has_bg)
  11425. ngui_fill_rect(&ui, clip, st.bg);
  11426. layout_block(l, deferred[i].node, &st, 0,
  11427. deferred[i].link);
  11428. ngui_pop_clip(&ui);
  11429. } else {
  11430. layout_block(l, deferred[i].node, &st, 0,
  11431. deferred[i].link);
  11432. }
  11433. }
  11434. }
  11435. }
  11436. /* ---- UI ---- */
  11437. static int find_hit(int x, int y)
  11438. {
  11439. int i;
  11440. for (i = nhits - 1; i >= 0; i--) {
  11441. struct hit *h = &hits[i];
  11442. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  11443. y < h->y + h->h)
  11444. return (int)h->node;
  11445. }
  11446. return 0;
  11447. }
  11448. /* ---- URL-bar autocomplete ----
  11449. *
  11450. * While the address bar has the focus a dropdown lists up to SUG_MAX
  11451. * history entries. An empty bar (a fresh focus, Ctrl+L) shows the most
  11452. * visited/recent sites; typing ranks prefix matches of the URL (with or
  11453. * without the scheme and "www.") above substring matches of the URL, then
  11454. * of the title, and adds visit count and recency. Typing at the end of the
  11455. * text also completes inline to the next '/' of the best prefix match
  11456. * ("clo" -> "cloudron.io/"), with the added part selected so the next
  11457. * keystroke replaces it; Enter on that text opens the history URL it came
  11458. * from (scheme included). Up/Down preview a row in the bar, Delete on a
  11459. * highlighted row forgets it, Esc closes the list (a second Esc leaves the
  11460. * bar), and a click on a row opens it. */
  11461. #define SUG_MAX 6
  11462. #define SUG_ROW_H 36
  11463. static int sug_idx[SUG_MAX];
  11464. static int sug_n, sug_sel = -1, sug_open;
  11465. static char sug_typed[NGUI_INPUT_MAX]; /* what the user typed */
  11466. static char sug_restore[NGUI_INPUT_MAX]; /* bar text before a preview */
  11467. static char ac_text[NGUI_INPUT_MAX]; /* bar text of the inline completion */
  11468. static char ac_url[HIST_URL_MAX]; /* the history URL it stands for */
  11469. static struct ngui_rect url_rect, sug_rect;
  11470. static int url_had_focus;
  11471. static char lc(char c)
  11472. {
  11473. return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
  11474. }
  11475. static int prefix_ci(const char *s, const char *p) /* p is lower case */
  11476. {
  11477. for (; *p; s++, p++)
  11478. if (lc(*s) != *p)
  11479. return 0;
  11480. return 1;
  11481. }
  11482. static unsigned int url_scheme_len(const char *url)
  11483. {
  11484. if (starts_with(url, "https://"))
  11485. return 8;
  11486. if (starts_with(url, "http://"))
  11487. return 7;
  11488. return 0;
  11489. }
  11490. /* Offset in `url` where the lower-case text `t` matches as a prefix: the
  11491. * whole URL, the URL without its scheme, or without scheme and "www.". */
  11492. static int hist_prefix_at(const char *url, const char *t)
  11493. {
  11494. unsigned int s = url_scheme_len(url);
  11495. if (prefix_ci(url, t))
  11496. return 0;
  11497. if (s && prefix_ci(url + s, t))
  11498. return (int)s;
  11499. if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
  11500. return (int)s + 4;
  11501. return -1;
  11502. }
  11503. static int hist_score(const struct hist_ent *e, const char *t,
  11504. unsigned int next)
  11505. {
  11506. unsigned int age = next - e->stamp;
  11507. int sc, at;
  11508. if (!t[0]) {
  11509. sc = 0;
  11510. } else if ((at = hist_prefix_at(e->url, t)) >= 0) {
  11511. /* Shorter rests first: "cloudron.io/" before its subpages. */
  11512. int rest = (int)s_len(e->url + at);
  11513. sc = 4000 - (rest > 400 ? 400 : rest);
  11514. } else if (contains_ci(e->url, t)) {
  11515. sc = 1000;
  11516. } else if (contains_ci(e->title, t)) {
  11517. sc = 600;
  11518. } else {
  11519. return -1;
  11520. }
  11521. sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
  11522. sc += age >= 500 ? 0 : (int)(500 - age);
  11523. return sc;
  11524. }
  11525. static void sug_lower(char *t, unsigned int cap)
  11526. {
  11527. unsigned int k;
  11528. for (k = 0; sug_typed[k] && k + 1 < cap; k++)
  11529. t[k] = lc(sug_typed[k]);
  11530. t[k] = '\0';
  11531. }
  11532. static void sug_refresh(void)
  11533. {
  11534. char t[NGUI_INPUT_MAX];
  11535. int sc[SUG_MAX], i, j;
  11536. unsigned int next = hist_next_stamp();
  11537. sug_lower(t, sizeof(t));
  11538. sug_n = 0;
  11539. for (i = 0; i < hist_n; i++) {
  11540. int s = hist_score(&hist_tab[i], t, next);
  11541. if (s < 0)
  11542. continue;
  11543. j = sug_n;
  11544. if (j == SUG_MAX) {
  11545. if (sc[SUG_MAX - 1] >= s)
  11546. continue;
  11547. j = SUG_MAX - 1;
  11548. }
  11549. while (j > 0 && sc[j - 1] < s) {
  11550. sc[j] = sc[j - 1];
  11551. sug_idx[j] = sug_idx[j - 1];
  11552. j--;
  11553. }
  11554. sc[j] = s;
  11555. sug_idx[j] = i;
  11556. if (sug_n < SUG_MAX)
  11557. sug_n++;
  11558. }
  11559. if (sug_sel >= sug_n)
  11560. sug_sel = -1;
  11561. }
  11562. /* Complete the typed text inline to the next '/' of the best prefix match. */
  11563. static void sug_inline(void)
  11564. {
  11565. char t[NGUI_INPUT_MAX];
  11566. const char *url, *rest;
  11567. unsigned int L, start, end, hs, tn, n = 0;
  11568. unsigned int next = hist_next_stamp();
  11569. int i, best = -1, best_sc = -1, at = 0;
  11570. sug_lower(t, sizeof(t));
  11571. L = s_len(t);
  11572. if (!L)
  11573. return;
  11574. for (i = 0; i < hist_n; i++) {
  11575. int a = hist_prefix_at(hist_tab[i].url, t), s;
  11576. if (a < 0)
  11577. continue;
  11578. s = hist_score(&hist_tab[i], t, next);
  11579. if (s > best_sc) {
  11580. best_sc = s;
  11581. best = i;
  11582. at = a;
  11583. }
  11584. }
  11585. if (best < 0)
  11586. return;
  11587. url = hist_tab[best].url;
  11588. rest = url + at;
  11589. /* Typing the scheme ("htt") completes past "https://", not to it. */
  11590. hs = at == 0 ? url_scheme_len(url) : 0;
  11591. start = L > hs ? L : hs;
  11592. end = start;
  11593. while (rest[end] && rest[end] != '/')
  11594. end++;
  11595. if (rest[end] == '/')
  11596. end++;
  11597. tn = s_len(sug_typed);
  11598. if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
  11599. return;
  11600. s_append(ac_text, &n, sug_typed, sizeof(ac_text));
  11601. for (; L < end && n + 1 < sizeof(ac_text); L++)
  11602. ac_text[n++] = rest[L];
  11603. ac_text[n] = '\0';
  11604. s_copy(ac_url, url, (unsigned int)at + end + 1);
  11605. ngui_input_set(&url_in, ac_text);
  11606. url_in.anchor = tn; /* select the completed part */
  11607. }
  11608. static void sug_close(void)
  11609. {
  11610. sug_open = 0;
  11611. sug_sel = -1;
  11612. ac_text[0] = '\0';
  11613. }
  11614. static int sug_visible(void)
  11615. {
  11616. return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
  11617. }
  11618. /* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
  11619. * start page) lists the top sites until something is typed. */
  11620. static int sug_focus_check(void)
  11621. {
  11622. int focused = ngui_focus(&ui) == ID_URL;
  11623. if (focused && !url_had_focus) {
  11624. sug_typed[0] = '\0';
  11625. sug_close();
  11626. sug_open = 1;
  11627. sug_refresh();
  11628. }
  11629. url_had_focus = focused;
  11630. return focused;
  11631. }
  11632. static void url_submit(unsigned int *action)
  11633. {
  11634. if (ac_text[0] && s_eq(url_in.text, ac_text))
  11635. s_copy(click_url, ac_url, sizeof(click_url));
  11636. *action |= ACT_NAV;
  11637. sug_close();
  11638. }
  11639. /* The bar text changed through typing or editing. */
  11640. static void sug_changed(void)
  11641. {
  11642. unsigned int pl = s_len(sug_typed);
  11643. int grew = url_in.len > pl && url_in.cursor == url_in.len &&
  11644. !memcmp(url_in.text, sug_typed, pl);
  11645. s_copy(sug_typed, url_in.text, sizeof(sug_typed));
  11646. ac_text[0] = '\0';
  11647. sug_sel = -1;
  11648. sug_open = 1;
  11649. sug_refresh();
  11650. if (grew)
  11651. sug_inline();
  11652. }
  11653. /* Keys for the list, taken off the queue before the text field sees them.
  11654. * Only a leading run is handled; the rest goes to the field. */
  11655. static void sug_keys(void)
  11656. {
  11657. int k;
  11658. while ((k = ngui_key_peek(&ui)) != 0) {
  11659. if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
  11660. ngui_key(&ui);
  11661. if (!sug_open) {
  11662. sug_open = 1;
  11663. continue;
  11664. }
  11665. if (sug_sel < 0)
  11666. s_copy(sug_restore, url_in.text,
  11667. sizeof(sug_restore));
  11668. if (k == NGUI_KEY_DOWN)
  11669. sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
  11670. else
  11671. sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
  11672. ngui_input_set(&url_in, sug_sel >= 0 ?
  11673. hist_tab[sug_idx[sug_sel]].url :
  11674. sug_restore);
  11675. } else if (k == NGUI_KEY_ESC && sug_visible()) {
  11676. ngui_key(&ui);
  11677. if (sug_sel >= 0)
  11678. ngui_input_set(&url_in, sug_restore);
  11679. else if (ac_text[0] && s_eq(url_in.text, ac_text))
  11680. ngui_input_set(&url_in, sug_typed);
  11681. sug_close();
  11682. } else if (k == NGUI_KEY_DELETE && sug_visible() &&
  11683. sug_sel >= 0) {
  11684. ngui_key(&ui);
  11685. hist_forget(sug_idx[sug_sel]);
  11686. ngui_input_set(&url_in, sug_restore);
  11687. sug_sel = -1;
  11688. sug_refresh();
  11689. } else {
  11690. break;
  11691. }
  11692. }
  11693. }
  11694. /* A press on a row of last frame's list opens it; any press on the list is
  11695. * swallowed so the page underneath does not see it. */
  11696. static void sug_click(unsigned int *action)
  11697. {
  11698. int row;
  11699. if (!(ui.pressed & 1) || !sug_rect.w ||
  11700. !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
  11701. return;
  11702. row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
  11703. if (row >= 0 && row < sug_n) {
  11704. s_copy(click_url, hist_tab[sug_idx[row]].url,
  11705. sizeof(click_url));
  11706. *action |= ACT_NAV;
  11707. sug_close();
  11708. }
  11709. ui.pressed = 0;
  11710. }
  11711. static void draw_suggest(struct ngui_rect page)
  11712. {
  11713. struct ngui_rect r;
  11714. int i, rows = sug_n, hover = -1;
  11715. r.x = url_rect.x;
  11716. r.y = url_rect.y + url_rect.h + 1;
  11717. r.w = url_rect.w < 320 ? 320 : url_rect.w;
  11718. if (r.x + r.w > ui.w - 2)
  11719. r.w = ui.w - 2 - r.x;
  11720. while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
  11721. rows--;
  11722. if (rows <= 0 || r.w < 60) {
  11723. sug_rect.w = 0;
  11724. return;
  11725. }
  11726. r.h = rows * SUG_ROW_H + 2;
  11727. sug_rect = r;
  11728. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  11729. hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
  11730. ngui_set_cursor(&ui, CURSOR_POINTER);
  11731. }
  11732. ngui_fill_rect(&ui, r, ui.theme.border);
  11733. for (i = 0; i < rows; i++) {
  11734. const struct hist_ent *e = &hist_tab[sug_idx[i]];
  11735. struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
  11736. r.w - 2, SUG_ROW_H};
  11737. struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
  11738. unsigned short bg = i == sug_sel ? ui.theme.selection :
  11739. i == hover ? ui.theme.panel_alt :
  11740. ui.theme.panel;
  11741. ngui_fill_rect(&ui, rr, bg);
  11742. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
  11743. e->title[0] ? e->title : e->url,
  11744. ui.theme.text);
  11745. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
  11746. i == sug_sel ? ui.theme.text :
  11747. ui.theme.text_dim);
  11748. }
  11749. }
  11750. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  11751. {
  11752. int x = r.x + 4, y = r.y + 4, h = 22;
  11753. int compact = r.w < 560;
  11754. int go_w = r.w < 420 ? 32 : 42;
  11755. int in_x, in_w, res;
  11756. ngui_fill_rect(&ui, r, ui.theme.panel);
  11757. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  11758. ui.theme.border);
  11759. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  11760. NGUI_ICON_CHEVRON_LEFT))
  11761. *action |= ACT_BACK;
  11762. x += 32;
  11763. if (!compact) {
  11764. if (ngui_icon_button(&ui, ID_FORWARD,
  11765. (struct ngui_rect){x, y, 28, h},
  11766. NGUI_ICON_CHEVRON_RIGHT))
  11767. *action |= ACT_FORWARD;
  11768. x += 32;
  11769. }
  11770. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  11771. NGUI_ICON_REFRESH))
  11772. *action |= ACT_RELOAD;
  11773. x += 32;
  11774. if (!compact) {
  11775. if (ngui_icon_button(&ui, ID_HOME,
  11776. (struct ngui_rect){x, y, 28, h},
  11777. NGUI_ICON_HOME))
  11778. *action |= ACT_HOME;
  11779. x += 32;
  11780. }
  11781. in_x = x + 2;
  11782. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  11783. if (in_w < 60)
  11784. in_w = 60;
  11785. url_rect = (struct ngui_rect){in_x, y, in_w, h};
  11786. if (sug_focus_check())
  11787. sug_keys();
  11788. res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
  11789. sug_focus_check(); /* a click into the bar focuses it here */
  11790. if (res & NGUI_INPUT_CHANGED)
  11791. sug_changed();
  11792. if (res & NGUI_INPUT_SUBMIT)
  11793. url_submit(action);
  11794. if (res & NGUI_INPUT_CANCEL)
  11795. ngui_set_focus(&ui, 0);
  11796. if (ngui_button(&ui, ID_GO,
  11797. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  11798. "Go"))
  11799. url_submit(action);
  11800. if (!sug_focus_check())
  11801. sug_close();
  11802. }
  11803. static int page_hover_node(void)
  11804. {
  11805. if (!ui.inside)
  11806. return 0;
  11807. if (ui.mouse_x < page_rect.x ||
  11808. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  11809. ui.mouse_y < page_rect.y ||
  11810. ui.mouse_y >= page_rect.y + page_rect.h)
  11811. return 0;
  11812. return find_hit(ui.mouse_x, ui.mouse_y);
  11813. }
  11814. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  11815. {
  11816. int x, y, w = page.w, h = page.h;
  11817. if (!src || w <= 0 || h <= 0)
  11818. return;
  11819. for (y = 0; y < h; y++) {
  11820. unsigned short *s = src + (page.y + y) * sw + page.x;
  11821. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  11822. for (x = 0; x + 1 < w; x += 2) {
  11823. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  11824. }
  11825. if (x < w)
  11826. d[x] = s[x];
  11827. }
  11828. }
  11829. static void draw_page(struct ngui_rect page)
  11830. {
  11831. int left, right, ch;
  11832. int old_panel, old_dim;
  11833. unsigned short *saved_px;
  11834. unsigned short page_bg = ui.theme.bg;
  11835. int saved_w, saved_h, use_buf;
  11836. unsigned int t0 = u_ticks_ms();
  11837. page_rect = page;
  11838. {
  11839. unsigned int root = doc.nnode > 1 ?
  11840. br_find_tag(&doc, BR_TAG_HTML) : 0;
  11841. unsigned int body = doc.nnode > 1 ?
  11842. br_find_tag(&doc, BR_TAG_BODY) : 0;
  11843. struct br_style bs;
  11844. int bg_found = 0;
  11845. if (root) {
  11846. style_for_node(root - 1, &bs);
  11847. if (bs.has_bg) {
  11848. page_bg = bs.bg;
  11849. bg_found = 1;
  11850. }
  11851. }
  11852. if (body) {
  11853. style_for_node(body - 1, &bs);
  11854. if (bs.has_bg) {
  11855. page_bg = bs.bg;
  11856. bg_found = 1;
  11857. }
  11858. }
  11859. /* No canvas colour, but the author made the text dark
  11860. * (Infima's light theme: `--ifm-background-color:
  11861. * transparent` on html, #1c1e21 text): the page expects the
  11862. * white canvas of a normal browser, and dark text on the
  11863. * dark default canvas is unreadable. */
  11864. if (!bg_found && (body || root) && bs.color != ui.theme.text) {
  11865. unsigned int c = bs.color;
  11866. unsigned int lum = ((c >> 11) & 31) * 8 * 299 +
  11867. ((c >> 5) & 63) * 4 * 587 +
  11868. (c & 31) * 8 * 114;
  11869. if (lum < 100 * 1000)
  11870. page_bg = 0xFFFF;
  11871. }
  11872. }
  11873. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  11874. page_cache_valid && layout_valid &&
  11875. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  11876. !(ui.scroll_y &&
  11877. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  11878. page_scroll.offset == page_cache_scroll &&
  11879. page_cache_nnode == doc.nnode &&
  11880. page_cache_x == page.x && page_cache_y == page.y &&
  11881. page_cache_w == page.w && page_cache_h == page.h) {
  11882. blit_page(page, page_backbuf, pagebuf_w);
  11883. if (img_stat_n)
  11884. img_stat_paint += u_ticks_ms() - t0;
  11885. return;
  11886. }
  11887. ngui_fill_rect(&ui, page, page_bg);
  11888. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  11889. const char *s = page_loading ? "Loading..." : "No page";
  11890. int w = (int)ngui_text_width_ui(&ui, s);
  11891. ngui_text(&ui, page.x + (page.w - w) / 2,
  11892. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  11893. page_scroll.content_h = 0;
  11894. page_scroll.view_h = page.h;
  11895. page_cache_valid = 0;
  11896. return;
  11897. }
  11898. if (page.w < 40 || page.h < 40) {
  11899. page_cache_valid = 0;
  11900. return;
  11901. }
  11902. saved_px = ui.px;
  11903. saved_w = ui.w;
  11904. saved_h = ui.h;
  11905. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  11906. if (use_buf) {
  11907. ui.px = page_backbuf;
  11908. ui.w = pagebuf_w;
  11909. ui.h = pagebuf_h;
  11910. ngui_fill_rect(&ui, page, page_bg);
  11911. }
  11912. /* No gutter of our own: the body's UA margin provides it. The
  11913. * right 12 px stay clear for the scrollbar, like every viewport
  11914. * width below (page_rect.w - 12). */
  11915. left = page.x;
  11916. right = page.x + page.w - 12;
  11917. if (!layout_valid || left != layout_left || right != layout_right ||
  11918. layout_nnode != doc.nnode) {
  11919. unsigned int tm = u_ticks_ms();
  11920. layout_view_h = page.h;
  11921. layout_content_h = measure_page(left, right);
  11922. if (img_stat_n)
  11923. img_stat_reflow += u_ticks_ms() - tm;
  11924. layout_valid = 1;
  11925. layout_left = left;
  11926. layout_right = right;
  11927. layout_nnode = doc.nnode;
  11928. /* Scripts that measured before any layout (offsetWidth on
  11929. * mount) get a resize event once real boxes exist, and again
  11930. * whenever the page width changes. */
  11931. if (js_browser_active() && right - left != resize_sent_w)
  11932. resize_pending = 1;
  11933. }
  11934. ch = layout_content_h;
  11935. page_scroll.content_h = ch;
  11936. page_scroll.view_h = page.h;
  11937. t0 = u_ticks_ms();
  11938. ngui_scroll_begin(&ui, page, &page_scroll);
  11939. ngui_scroll_wheel(&ui, page, &page_scroll);
  11940. render_page(left, right, page.y - page_scroll.offset);
  11941. old_panel = ui.theme.panel_alt;
  11942. old_dim = ui.theme.text_dim;
  11943. ui.theme.panel_alt = 0xC618;
  11944. ui.theme.text_dim = 0x8410;
  11945. ngui_scroll_end(&ui, page, &page_scroll);
  11946. ui.theme.panel_alt = old_panel;
  11947. ui.theme.text_dim = old_dim;
  11948. if (use_buf) {
  11949. ui.px = saved_px;
  11950. ui.w = saved_w;
  11951. ui.h = saved_h;
  11952. blit_page(page, page_backbuf, pagebuf_w);
  11953. page_cache_valid = 1;
  11954. page_cache_scroll = page_scroll.offset;
  11955. page_cache_nnode = doc.nnode;
  11956. page_cache_x = page.x;
  11957. page_cache_y = page.y;
  11958. page_cache_w = page.w;
  11959. page_cache_h = page.h;
  11960. } else {
  11961. page_cache_valid = 0;
  11962. }
  11963. if (img_stat_n)
  11964. img_stat_paint += u_ticks_ms() - t0;
  11965. }
  11966. static void draw_status(struct ngui_rect r)
  11967. {
  11968. static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
  11969. unsigned int n = 0;
  11970. int hover = page_hover_node();
  11971. unsigned short color;
  11972. const char *kind;
  11973. ngui_fill_rect(&ui, r, ui.theme.panel);
  11974. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  11975. ui.theme.border);
  11976. /* Only a real link target is shown: a form control, or an element
  11977. * that is merely clickable through a script listener (google.com's
  11978. * jsaction wrapper around its search field), is not a link. */
  11979. if (hover && !br_href(&doc, (unsigned int)hover))
  11980. hover = 0;
  11981. if (hover) {
  11982. const char *href = br_href(&doc, (unsigned int)hover);
  11983. char url[BR_URL_MAX];
  11984. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  11985. s_append(msg, &n, "Link: ", sizeof(msg));
  11986. s_append(msg, &n, url, sizeof(msg));
  11987. } else {
  11988. s_copy(msg, "Link", sizeof(msg));
  11989. }
  11990. color = ui.theme.accent;
  11991. } else if (status_text[0]) {
  11992. s_copy(msg, status_text, sizeof(msg));
  11993. color = status_error ? ui.theme.error : ui.theme.text;
  11994. } else if (page_title[0]) {
  11995. s_copy(msg, page_title, sizeof(msg));
  11996. color = ui.theme.text;
  11997. } else {
  11998. s_copy(msg, "Ready", sizeof(msg));
  11999. color = ui.theme.text_dim;
  12000. }
  12001. kind = s_eq(page_url, "about:home") ? "HOME" :
  12002. page_is_local ? "FILE" :
  12003. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  12004. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  12005. {
  12006. int kw = (int)ngui_text_width_ui(&ui, kind);
  12007. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  12008. ui.theme.text_dim);
  12009. }
  12010. }
  12011. /* Mouse cursor over the page: the hovered node's CSS `cursor` (inherited);
  12012. * for `auto`, a hand over links, the I-beam over text fields, and the
  12013. * progress arrow anywhere on the page while it is still loading. The
  12014. * toolbar's URL field sets its own I-beam through ngui. */
  12015. static void page_cursor(void)
  12016. {
  12017. int hover = page_hover_node();
  12018. struct br_style st;
  12019. if (!hover) {
  12020. if (page_loading && ui.inside &&
  12021. ngui_rect_contains(&page_rect, ui.mouse_x, ui.mouse_y))
  12022. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  12023. return;
  12024. }
  12025. style_for_node((unsigned int)hover, &st);
  12026. if (st.cursor != BR_CURSOR_AUTO) {
  12027. ngui_set_cursor(&ui, (int)st.cursor - 1);
  12028. return;
  12029. }
  12030. if (br_href(&doc, (unsigned int)hover)) {
  12031. ngui_set_cursor(&ui, CURSOR_POINTER);
  12032. return;
  12033. }
  12034. if (form_is_control((unsigned int)hover)) {
  12035. int k = form_kind_of((unsigned int)hover);
  12036. if (form_disabled((unsigned int)hover))
  12037. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  12038. else if (k == FORM_TEXT || k == FORM_PASSWORD ||
  12039. k == FORM_TEXTAREA)
  12040. ngui_set_cursor(&ui, CURSOR_TEXT);
  12041. return;
  12042. }
  12043. if (page_loading)
  12044. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  12045. }
  12046. static void draw(unsigned int *action)
  12047. {
  12048. struct ngui_rect r = {0, 0, ui.w, ui.h};
  12049. struct ngui_rect toolbar, status, page;
  12050. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  12051. status = ngui_cut_bottom(&r, BR_STATUS_H);
  12052. page = r;
  12053. if (sug_visible())
  12054. sug_click(action);
  12055. draw_toolbar(toolbar, action);
  12056. draw_page(page);
  12057. draw_status(status);
  12058. page_cursor();
  12059. if (sug_visible())
  12060. draw_suggest(page);
  12061. else
  12062. sug_rect.w = 0;
  12063. }
  12064. static void redraw_now(void)
  12065. {
  12066. unsigned int action = 0;
  12067. ngui_begin(&ui);
  12068. draw(&action);
  12069. ngui_end(&ui);
  12070. }
  12071. static void handle_keys(unsigned int *action)
  12072. {
  12073. int k, scrolled = 0;
  12074. if (form_focus >= doc.nnode)
  12075. form_focus = 0;
  12076. if (form_focus && !ngui_focus(&ui)) {
  12077. while ((k = ngui_key(&ui)) != 0)
  12078. form_key(k);
  12079. return;
  12080. }
  12081. /* Batch queued page keys: a slow full-page render must not make a
  12082. * held Page Down advance only once every few frames. */
  12083. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  12084. scrolled++;
  12085. if (scrolled)
  12086. ngui_invalidate(&ui);
  12087. if (ngui_focus(&ui))
  12088. return;
  12089. while ((k = ngui_key(&ui)) != 0) {
  12090. switch (k) {
  12091. case NGUI_KEY_ESC:
  12092. *action |= ACT_CLOSE;
  12093. break;
  12094. case NGUI_KEY_TAB:
  12095. case 0x0C: /* Ctrl+L */
  12096. ngui_set_focus(&ui, ID_URL);
  12097. break;
  12098. case 0x12: /* Ctrl+R */
  12099. *action |= ACT_RELOAD;
  12100. break;
  12101. case NGUI_KEY_BACKSPACE:
  12102. *action |= ACT_BACK;
  12103. break;
  12104. case NGUI_KEY_UP:
  12105. ngui_scroll_to(&page_scroll,
  12106. page_scroll.offset - 24);
  12107. ngui_invalidate(&ui);
  12108. break;
  12109. case NGUI_KEY_DOWN:
  12110. ngui_scroll_to(&page_scroll,
  12111. page_scroll.offset + 24);
  12112. ngui_invalidate(&ui);
  12113. break;
  12114. case NGUI_KEY_HOME:
  12115. ngui_scroll_to(&page_scroll, 0);
  12116. ngui_invalidate(&ui);
  12117. break;
  12118. case NGUI_KEY_END:
  12119. ngui_scroll_to(&page_scroll,
  12120. page_scroll.content_h -
  12121. page_scroll.view_h);
  12122. ngui_invalidate(&ui);
  12123. break;
  12124. default:
  12125. break;
  12126. }
  12127. }
  12128. }
  12129. static unsigned int form_ancestor(unsigned int node)
  12130. {
  12131. unsigned int p = node;
  12132. while (p && p < doc.nnode) {
  12133. if (doc.nodes[p].tag == BR_TAG_FORM &&
  12134. doc.nodes[p].type == BR_NODE_ELEM)
  12135. return p;
  12136. p = doc.nodes[p].parent;
  12137. }
  12138. return 0;
  12139. }
  12140. static int form_descendant(unsigned int node, unsigned int form)
  12141. {
  12142. unsigned int p = node;
  12143. while (p && p < doc.nnode) {
  12144. if (p == form)
  12145. return 1;
  12146. p = doc.nodes[p].parent;
  12147. }
  12148. return 0;
  12149. }
  12150. static void form_reset_form(unsigned int form)
  12151. {
  12152. unsigned int i;
  12153. for (i = 0; i < FORM_MAX; i++)
  12154. if (form_states[i].used &&
  12155. form_descendant(form_states[i].node, form))
  12156. form_states[i].used = 0;
  12157. form_focus = 0;
  12158. }
  12159. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  12160. const char *s)
  12161. {
  12162. static const char hex[] = "0123456789ABCDEF";
  12163. while (s && *s && *n + 1 < cap) {
  12164. unsigned char c = (unsigned char)*s++;
  12165. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  12166. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  12167. c == '.' || c == '~') {
  12168. dst[(*n)++] = (char)c;
  12169. } else if (c == ' ') {
  12170. dst[(*n)++] = '+';
  12171. } else if (*n + 3 < cap) {
  12172. dst[(*n)++] = '%';
  12173. dst[(*n)++] = hex[c >> 4];
  12174. dst[(*n)++] = hex[c & 15];
  12175. }
  12176. }
  12177. dst[*n] = '\0';
  12178. }
  12179. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  12180. const char *name, const char *value, int *first)
  12181. {
  12182. if (!name || !name[0])
  12183. return;
  12184. if (!*first && *n + 1 < cap)
  12185. dst[(*n)++] = '&';
  12186. *first = 0;
  12187. form_url_append(dst, n, cap, name);
  12188. if (*n + 1 < cap)
  12189. dst[(*n)++] = '=';
  12190. form_url_append(dst, n, cap, value ? value : "");
  12191. dst[*n] = '\0';
  12192. }
  12193. static int form_submit_form(unsigned int node, int fire_event)
  12194. {
  12195. unsigned int form = form_ancestor(node);
  12196. char action[BR_URL_MAX], query[2048];
  12197. unsigned int qn = 0, i;
  12198. int first = 1, is_post = 0;
  12199. const char *a, *method;
  12200. if (!form)
  12201. return 0;
  12202. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  12203. return 0;
  12204. method = br_find_attr(&doc, form, "method");
  12205. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  12206. is_post = 1;
  12207. a = br_find_attr(&doc, form, "action");
  12208. if (a && a[0]) {
  12209. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  12210. return 0;
  12211. } else {
  12212. s_copy(action, page_url, sizeof(action));
  12213. }
  12214. query[0] = '\0';
  12215. for (i = 0; i < doc.nnode; i++) {
  12216. struct br_node *nd = &doc.nodes[i];
  12217. struct form_state *fs;
  12218. const char *name;
  12219. const char *value = "";
  12220. if (nd->type != BR_NODE_ELEM || i == form ||
  12221. !form_descendant(i, form))
  12222. continue;
  12223. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  12224. nd->tag != BR_TAG_SELECT)
  12225. continue;
  12226. if (form_disabled(i))
  12227. continue;
  12228. name = br_find_attr(&doc, i, "name");
  12229. if (!name || !name[0])
  12230. continue;
  12231. fs = form_get(i, 1);
  12232. if (!fs)
  12233. continue;
  12234. if (nd->tag == BR_TAG_SELECT) {
  12235. char opt[64];
  12236. if (!form_option_text(i, fs->selected, opt,
  12237. sizeof(opt)))
  12238. s_copy(opt, "", sizeof(opt));
  12239. value = opt;
  12240. {
  12241. unsigned int c, oi = 0;
  12242. for (c = nd->first; c;
  12243. c = doc.nodes[c].next) {
  12244. if (doc.nodes[c].type != BR_NODE_ELEM ||
  12245. doc.nodes[c].tag != BR_TAG_OPTION)
  12246. continue;
  12247. if (oi == fs->selected) {
  12248. const char *v =
  12249. br_value(&doc, c);
  12250. if (v && v[0])
  12251. value = v;
  12252. break;
  12253. }
  12254. oi++;
  12255. }
  12256. }
  12257. } else if (nd->tag == BR_TAG_INPUT) {
  12258. int kind = form_kind_of(i);
  12259. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  12260. if (!fs->checked)
  12261. continue;
  12262. value = br_value(&doc, i);
  12263. if (!value || !value[0])
  12264. value = "on";
  12265. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  12266. kind == FORM_BUTTON) {
  12267. if (i != node)
  12268. continue;
  12269. value = fs->value;
  12270. } else {
  12271. value = fs->value;
  12272. }
  12273. } else {
  12274. value = fs->value;
  12275. }
  12276. form_add_param(query, &qn, sizeof(query), name, value, &first);
  12277. }
  12278. if (is_post) {
  12279. if (action[0] == '/') {
  12280. set_status("POST forms need an HTTP action URL", 1, 4000);
  12281. ngui_invalidate(&ui);
  12282. return 0;
  12283. }
  12284. if (qn >= sizeof(pending_post))
  12285. qn = sizeof(pending_post) - 1;
  12286. if (qn)
  12287. memcpy(pending_post, query, qn);
  12288. pending_post[qn] = '\0';
  12289. pending_post_len = qn;
  12290. pending_post_is = 1;
  12291. } else {
  12292. pending_post_len = 0;
  12293. pending_post_is = 0;
  12294. if (qn) {
  12295. unsigned int an = s_len(action);
  12296. if (an + qn + 2 < sizeof(action)) {
  12297. action[an++] = strchr(action, '?') ? '&' : '?';
  12298. action[an] = '\0';
  12299. s_copy(action + an, query,
  12300. sizeof(action) - an);
  12301. }
  12302. }
  12303. }
  12304. s_copy(pending_url, action, sizeof(pending_url));
  12305. pending_action |= ACT_NAV;
  12306. cancel_fetch = 1;
  12307. ngui_invalidate(&ui);
  12308. return 1;
  12309. }
  12310. static void form_reset_event(unsigned int form)
  12311. {
  12312. if (form && !js_browser_event(form, "reset", 1, 1))
  12313. return;
  12314. if (form)
  12315. form_reset_form(form);
  12316. else
  12317. form_reset_state();
  12318. form_dirty = 0;
  12319. layout_valid = 0;
  12320. ngui_invalidate(&ui);
  12321. }
  12322. static void form_blur(void)
  12323. {
  12324. unsigned int node = form_focus;
  12325. form_focus = 0;
  12326. if (node && form_dirty) {
  12327. form_dirty = 0;
  12328. js_browser_event(node, "change", 1, 0);
  12329. }
  12330. }
  12331. static void form_click(unsigned int node)
  12332. {
  12333. struct form_state *fs;
  12334. int kind, changed = 0;
  12335. if (!form_is_control(node) || form_disabled(node))
  12336. return;
  12337. if (form_focus != node)
  12338. form_blur();
  12339. fs = form_get(node, 1);
  12340. if (!fs)
  12341. return;
  12342. kind = form_kind_of(node);
  12343. /* Focus moves on the press, before `click` is dispatched: a page
  12344. * that cancels the click (a framework's root listener) suppresses
  12345. * the activation behaviour below, never the focus (as in other
  12346. * browsers, where focus follows mousedown). */
  12347. form_focus = node;
  12348. form_dirty = 0;
  12349. if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  12350. kind == FORM_TEXTAREA)
  12351. fs->caret = fs->len;
  12352. layout_valid = 0;
  12353. ngui_invalidate(&ui);
  12354. if (!js_browser_event(node, "click", 1, 1))
  12355. return;
  12356. fs = form_get(node, 0); /* the handler may have changed the DOM */
  12357. if (!fs)
  12358. return;
  12359. if (kind == FORM_CHECKBOX) {
  12360. fs->checked = !fs->checked;
  12361. changed = 1;
  12362. } else if (kind == FORM_RADIO) {
  12363. const char *name = br_find_attr(&doc, node, "name");
  12364. unsigned int i;
  12365. fs->checked = 1;
  12366. changed = 1;
  12367. if (name) {
  12368. for (i = 0; i < FORM_MAX; i++) {
  12369. struct form_state *o = &form_states[i];
  12370. if (!o->used || o->node == node)
  12371. continue;
  12372. if (form_kind_of(o->node) == FORM_RADIO) {
  12373. const char *on = br_find_attr(&doc,
  12374. o->node,
  12375. "name");
  12376. if (on && s_eq(on, name))
  12377. o->checked = 0;
  12378. }
  12379. }
  12380. }
  12381. } else if (kind == FORM_SELECT) {
  12382. unsigned int n = form_option_count(node);
  12383. if (n) {
  12384. fs->selected = (unsigned char)
  12385. ((fs->selected + 1) % n);
  12386. changed = 1;
  12387. }
  12388. } else if (kind == FORM_SUBMIT) {
  12389. form_submit_form(node, 1);
  12390. return;
  12391. } else if (kind == FORM_RESET) {
  12392. form_reset_event(form_ancestor(node));
  12393. return;
  12394. }
  12395. if (changed) {
  12396. js_browser_event(node, "input", 1, 0);
  12397. js_browser_event(node, "change", 1, 0);
  12398. }
  12399. layout_valid = 0;
  12400. ngui_invalidate(&ui);
  12401. }
  12402. static void form_focus_next(void)
  12403. {
  12404. unsigned int start = form_focus ? form_focus + 1 : 0;
  12405. unsigned int i;
  12406. form_blur();
  12407. for (i = start; i < doc.nnode; i++) {
  12408. if (form_is_control(i) && !form_disabled(i) &&
  12409. !s_eq(br_type(&doc, i), "hidden")) {
  12410. form_focus = i;
  12411. layout_valid = 0;
  12412. ngui_invalidate(&ui);
  12413. return;
  12414. }
  12415. }
  12416. form_focus = 0;
  12417. layout_valid = 0;
  12418. ngui_invalidate(&ui);
  12419. }
  12420. static void form_key(int k)
  12421. {
  12422. struct form_state *fs;
  12423. int kind;
  12424. if (!form_focus || form_focus >= doc.nnode) {
  12425. form_focus = 0;
  12426. return;
  12427. }
  12428. fs = form_get(form_focus, 1);
  12429. if (!fs || form_disabled(form_focus))
  12430. return;
  12431. kind = form_kind_of(form_focus);
  12432. if (kind == FORM_SELECT) {
  12433. unsigned int n = form_option_count(form_focus);
  12434. int changed = 0;
  12435. if (k == NGUI_KEY_UP && n) {
  12436. fs->selected = (unsigned char)
  12437. ((fs->selected + n - 1) % n);
  12438. changed = 1;
  12439. } else if (k == NGUI_KEY_DOWN && n) {
  12440. fs->selected = (unsigned char)
  12441. ((fs->selected + 1) % n);
  12442. changed = 1;
  12443. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  12444. form_blur();
  12445. layout_valid = 0;
  12446. ngui_invalidate(&ui);
  12447. return;
  12448. } else {
  12449. return;
  12450. }
  12451. if (changed) {
  12452. js_browser_event(form_focus, "input", 1, 0);
  12453. js_browser_event(form_focus, "change", 1, 0);
  12454. }
  12455. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  12456. if (k == ' ') {
  12457. form_click(form_focus);
  12458. return;
  12459. }
  12460. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  12461. form_blur();
  12462. layout_valid = 0;
  12463. ngui_invalidate(&ui);
  12464. }
  12465. return;
  12466. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  12467. kind == FORM_RESET) {
  12468. if (k == NGUI_KEY_ESC) {
  12469. form_blur();
  12470. layout_valid = 0;
  12471. ngui_invalidate(&ui);
  12472. } else if (k == '\r' || k == '\n' || k == ' ') {
  12473. form_click(form_focus);
  12474. }
  12475. return;
  12476. } else if (k == NGUI_KEY_TAB) {
  12477. form_focus_next();
  12478. return;
  12479. } else if (k == NGUI_KEY_ESC) {
  12480. form_blur();
  12481. layout_valid = 0;
  12482. ngui_invalidate(&ui);
  12483. return;
  12484. } else if (k == '\r' || k == '\n') {
  12485. unsigned int node = form_focus;
  12486. form_blur();
  12487. if (form_ancestor(node))
  12488. form_submit_form(node, 1);
  12489. layout_valid = 0;
  12490. ngui_invalidate(&ui);
  12491. return;
  12492. } else if (k == NGUI_KEY_BACKSPACE) {
  12493. if (fs->caret) {
  12494. unsigned int i = --fs->caret;
  12495. for (; i < fs->len; i++)
  12496. fs->value[i] = fs->value[i + 1];
  12497. if (fs->len)
  12498. fs->len--;
  12499. form_dirty = 1;
  12500. js_browser_event(form_focus, "input", 1, 0);
  12501. }
  12502. } else if (k == NGUI_KEY_DELETE) {
  12503. if (fs->caret < fs->len) {
  12504. unsigned int i;
  12505. for (i = fs->caret; i < fs->len; i++)
  12506. fs->value[i] = fs->value[i + 1];
  12507. fs->len--;
  12508. form_dirty = 1;
  12509. js_browser_event(form_focus, "input", 1, 0);
  12510. }
  12511. } else if (k == NGUI_KEY_LEFT) {
  12512. if (fs->caret)
  12513. fs->caret--;
  12514. } else if (k == NGUI_KEY_RIGHT) {
  12515. if (fs->caret < fs->len)
  12516. fs->caret++;
  12517. } else if (k == NGUI_KEY_HOME) {
  12518. fs->caret = 0;
  12519. } else if (k == NGUI_KEY_END) {
  12520. fs->caret = fs->len;
  12521. } else if (k >= 32 && k < 127) {
  12522. if (fs->len < FORM_VALUE_MAX) {
  12523. unsigned int i;
  12524. for (i = fs->len; i > fs->caret; i--)
  12525. fs->value[i] = fs->value[i - 1];
  12526. fs->value[fs->caret++] = (char)k;
  12527. fs->len++;
  12528. form_dirty = 1;
  12529. js_browser_event(form_focus, "input", 1, 0);
  12530. }
  12531. } else {
  12532. return;
  12533. }
  12534. fs->value[fs->len] = '\0';
  12535. layout_valid = 0;
  12536. ngui_invalidate(&ui);
  12537. }
  12538. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  12539. * a same-document navigation: update the URL and fire hashchange. Returns
  12540. * 1 when handled. */
  12541. static int link_fragment_nav(unsigned int node)
  12542. {
  12543. const char *href = br_href(&doc, node);
  12544. char url[BR_URL_MAX];
  12545. unsigned int n = 0;
  12546. if (!href || !href[0] || !js_browser_active())
  12547. return 0;
  12548. if (href[0] == '#') {
  12549. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  12550. url[n] = page_url[n];
  12551. n++;
  12552. }
  12553. url[n] = '\0';
  12554. s_append(url, &n, href, sizeof(url));
  12555. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  12556. return 0;
  12557. }
  12558. if (!same_doc_fragment(url))
  12559. return href[0] == '#';
  12560. page_set_fragment(url, 1);
  12561. js_browser_hashchange();
  12562. return 1;
  12563. }
  12564. /* The innermost laid-out box under a screen point: the smallest valid box
  12565. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  12566. * Used to deliver clicks to elements that are neither links nor controls
  12567. * (a Vue <div role="button">, a card with a click listener). */
  12568. static unsigned int find_box_hit(int x, int y)
  12569. {
  12570. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  12571. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  12572. const struct br_layout_box *b = &layout_boxes[i];
  12573. unsigned int area;
  12574. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  12575. x < b->x || y < b->y || x >= b->x + b->w ||
  12576. y >= b->y + b->h)
  12577. continue;
  12578. area = (unsigned int)b->w * (unsigned int)b->h;
  12579. if (area <= best_area) {
  12580. best = i;
  12581. best_area = area;
  12582. }
  12583. }
  12584. return best;
  12585. }
  12586. static void handle_page_click(unsigned int *action)
  12587. {
  12588. int node;
  12589. char url[BR_URL_MAX];
  12590. if (!ui.pressed)
  12591. return;
  12592. if (ui.press_x < page_rect.x ||
  12593. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  12594. ui.press_y < page_rect.y ||
  12595. ui.press_y >= page_rect.y + page_rect.h)
  12596. return;
  12597. node = find_hit(ui.press_x, ui.press_y);
  12598. if (!node) {
  12599. unsigned int box;
  12600. if (!js_browser_active())
  12601. return;
  12602. box = find_box_hit(ui.press_x, ui.press_y);
  12603. if (box) {
  12604. form_blur();
  12605. js_browser_event(box, "click", 1, 1);
  12606. }
  12607. return;
  12608. }
  12609. if (form_is_control((unsigned int)node)) {
  12610. form_click((unsigned int)node);
  12611. return;
  12612. }
  12613. form_blur();
  12614. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  12615. return;
  12616. if (link_fragment_nav((unsigned int)node))
  12617. return;
  12618. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  12619. sizeof(url)) != 0)
  12620. return;
  12621. s_copy(click_url, url, sizeof(click_url));
  12622. *action |= ACT_NAV;
  12623. }
  12624. void _start(const char *arg)
  12625. {
  12626. struct win_info wi;
  12627. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  12628. u_win_create(960, 640, "Browser", &wi) != 0 &&
  12629. u_win_create(780, 540, "Browser", &wi) != 0) {
  12630. u_puts("browser: no graphics window\n");
  12631. u_exit(1);
  12632. }
  12633. ufont_set_arena_bytes(BR_FONT_ARENA);
  12634. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  12635. url_in.placeholder = "http://...";
  12636. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  12637. ui.theme.accent);
  12638. br_set_viewport(wi.width);
  12639. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  12640. s_copy(cwd, "/", sizeof(cwd));
  12641. heap_clear();
  12642. origin_cache_load();
  12643. css_cache_init();
  12644. script_cache_init();
  12645. font_cache_init();
  12646. persist_restore();
  12647. hist_load();
  12648. page_scroll.offset = 0;
  12649. page_scroll.content_h = 0;
  12650. if (arg && arg[0]) {
  12651. navigate(arg, 1);
  12652. } else {
  12653. load_home(1);
  12654. /* Start ready to type: keep the home page, but leave the address
  12655. * bar empty instead of showing "about:home". */
  12656. ngui_input_set(&url_in, "");
  12657. ngui_set_focus(&ui, ID_URL);
  12658. }
  12659. for (;;) {
  12660. unsigned int action = 0;
  12661. unsigned int now;
  12662. click_url[0] = '\0';
  12663. if (pending_action) {
  12664. action |= pending_action & ACT_WAIT_NAV;
  12665. if (pending_url[0])
  12666. s_copy(click_url, pending_url, sizeof(click_url));
  12667. pending_action = 0;
  12668. pending_url[0] = '\0';
  12669. cancel_fetch = 0;
  12670. } else if (preload_active) {
  12671. if (preload_wait)
  12672. preload_wait = 0;
  12673. else
  12674. preload_step();
  12675. } else if ((preload_pending &&
  12676. page_scroll.offset != preload_scroll) ||
  12677. (preload_rescan && layout_valid)) {
  12678. preload_scroll = page_scroll.offset;
  12679. preload_rescan = 0;
  12680. preload_pending = 0;
  12681. preload_node = 0;
  12682. preload_active = 1;
  12683. }
  12684. js_browser_tick();
  12685. if (resize_pending && !pending_action) {
  12686. resize_pending = 0;
  12687. resize_sent_w = layout_right - layout_left;
  12688. js_browser_window_event("resize");
  12689. }
  12690. persist_tick();
  12691. if (pending_action)
  12692. continue;
  12693. now = u_ticks_ms();
  12694. if (status_until && (int)(now - status_until) >= 0) {
  12695. status_text[0] = '\0';
  12696. status_until = 0;
  12697. status_error = 0;
  12698. ngui_invalidate(&ui);
  12699. }
  12700. if (!ngui_begin(&ui)) {
  12701. /* A queued navigation (e.g. Enter in the URL bar during
  12702. * a slow fetch) must be handled even when this frame
  12703. * needs no redraw. */
  12704. if (!action) {
  12705. fetch_workers_stop_if_unfocused();
  12706. u_sleep_ms(10);
  12707. continue;
  12708. }
  12709. } else {
  12710. draw(&action);
  12711. handle_keys(&action);
  12712. handle_page_click(&action);
  12713. ngui_end(&ui);
  12714. }
  12715. if (action & ACT_NAV) {
  12716. if (click_url[0]) {
  12717. navigate(click_url, 1);
  12718. click_url[0] = '\0';
  12719. } else {
  12720. navigate(url_in.text, 1);
  12721. }
  12722. }
  12723. if (action & ACT_BACK) {
  12724. if (hist_pos > 0) {
  12725. hist_pos--;
  12726. if (same_doc_fragment(history[hist_pos])) {
  12727. page_set_fragment(history[hist_pos], 0);
  12728. js_browser_hashchange();
  12729. } else {
  12730. navigate(history[hist_pos], 0);
  12731. }
  12732. }
  12733. }
  12734. if (action & ACT_FORWARD) {
  12735. if (hist_pos + 1 < hist_len) {
  12736. hist_pos++;
  12737. if (same_doc_fragment(history[hist_pos])) {
  12738. page_set_fragment(history[hist_pos], 0);
  12739. js_browser_hashchange();
  12740. } else {
  12741. navigate(history[hist_pos], 0);
  12742. }
  12743. }
  12744. }
  12745. if (action & ACT_RELOAD) {
  12746. if (s_eq(page_url, "about:home"))
  12747. load_home(0);
  12748. else
  12749. navigate(page_url, 0);
  12750. }
  12751. if (action & ACT_HOME)
  12752. load_home(1);
  12753. if (action & ACT_CLOSE)
  12754. quit = 1;
  12755. if (quit)
  12756. break;
  12757. if (pending_action)
  12758. continue;
  12759. fetch_workers_stop_if_unfocused();
  12760. u_sleep_ms(10);
  12761. }
  12762. fetch_workers_stop_all();
  12763. u_win_close();
  12764. u_exit(0);
  12765. }