browser.c 361 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592
  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. #define BR_MAX_SHEETS 6
  71. #define BR_HISTORY 16
  72. #define BR_URL_MAX 4096 /* = UHTTP_PATH_MAX: google.com's JS URL is ~3.7 KB */
  73. #define BR_STATUS_MAX 200
  74. #define BR_IMG_RGB565(r, g, b) \
  75. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  76. #define BR_GRAY 0x8410
  77. enum {
  78. ID_URL = 1,
  79. ID_GO,
  80. ID_BACK,
  81. ID_FORWARD,
  82. ID_RELOAD,
  83. ID_HOME
  84. };
  85. #define ACT_NAV (1u << 0)
  86. #define ACT_BACK (1u << 1)
  87. #define ACT_FORWARD (1u << 2)
  88. #define ACT_RELOAD (1u << 3)
  89. #define ACT_HOME (1u << 4)
  90. #define ACT_CLOSE (1u << 5)
  91. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  92. ACT_HOME | ACT_CLOSE)
  93. struct br_image {
  94. int state; /* 0 empty, 1 ready */
  95. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  96. int native_w, native_h;
  97. unsigned int url_hash; /* <img> source, 0 = not shareable */
  98. char err[32];
  99. /* Display-size cache: the box an image is actually painted in. The
  100. * source bitmap above is deliberately capped at BR_IMG_LAYOUT_W so a
  101. * window resize can re-scale it; the cached copy is exactly dw x dh,
  102. * so every repaint is a 1:1 blit instead of a per-pixel resample. */
  103. struct img_image disp;
  104. unsigned int disp_pixels;
  105. unsigned int disp_last;
  106. };
  107. static struct ngui ui;
  108. static struct ngui_input url_in;
  109. static struct ngui_scroll page_scroll;
  110. static struct br_doc doc;
  111. static struct br_image images[BR_MAX_IMAGES];
  112. static int image_count;
  113. static unsigned int image_pixels;
  114. static unsigned int image_disp_pixels;
  115. static unsigned int image_disp_clock;
  116. /* Per-image pipeline timing for the status line and /share/IMGSTAT. The
  117. * numbers are what decides whether the next work is network, decode or
  118. * display; keep them cheap (one tick read per phase). */
  119. static unsigned int img_stat_start;
  120. static unsigned int img_stat_wall;
  121. static unsigned int img_stat_net;
  122. static unsigned int img_stat_open;
  123. static unsigned int img_stat_first;
  124. static unsigned int img_stat_io;
  125. static unsigned int img_stat_dec;
  126. static unsigned int img_stat_scale;
  127. static unsigned int img_stat_paint;
  128. static unsigned int img_stat_reflow;
  129. static unsigned int img_stat_bytes;
  130. static int img_stat_n;
  131. static unsigned int img_last_dec_ms;
  132. static unsigned int img_last_scale_ms;
  133. static char img_stat_log[BR_IMG_STAT_LOG];
  134. static unsigned int img_stat_log_len;
  135. static unsigned int img_repaint_ms;
  136. static int img_repaint_pending;
  137. /* Painted border boxes, in page/screen coordinates (layout starts at
  138. * page_rect.y - scroll). getBoundingClientRect() subtracts page_rect. */
  139. struct br_layout_box {
  140. int x, y;
  141. int w, h;
  142. unsigned char valid;
  143. };
  144. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  145. /* Images are loaded one per main-loop iteration so the parsed page stays
  146. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  147. static int preload_active;
  148. static int preload_max_jobs;
  149. static int preload_pending;
  150. static int preload_wait;
  151. static unsigned int preload_node;
  152. static int preload_loaded;
  153. static int preload_scroll;
  154. static int preload_rescan;
  155. static char post_status_text[BR_STATUS_MAX];
  156. static int post_status_error;
  157. static unsigned int post_status_ttl;
  158. /* Content-relative position/height of each <img>, recorded by the measure
  159. * pass so image loading can be deferred until it is near the viewport. */
  160. static unsigned short img_top[BR_MAX_NODES];
  161. static unsigned short img_h[BR_MAX_NODES];
  162. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  163. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  164. * body. Decode arenas are allocated per image instead of living here. */
  165. static unsigned char *image_io_buf;
  166. static struct ufont_face *font_faces[BR_MAX_FACES];
  167. #define image_file_buf (image_io_buf)
  168. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  169. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  170. static struct inflate image_inflate_ws;
  171. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  172. #error "CSS scratch must fit in image_io_buf"
  173. #endif
  174. static char page_url[BR_URL_MAX];
  175. static char page_title[BR_TITLE_MAX];
  176. static char cwd[64];
  177. static int page_is_local;
  178. static int page_loading;
  179. static char status_text[BR_STATUS_MAX];
  180. static unsigned int status_until;
  181. static int status_error;
  182. static char history[BR_HISTORY][BR_URL_MAX];
  183. static int hist_len, hist_pos;
  184. static char click_url[BR_URL_MAX];
  185. static char pending_url[BR_URL_MAX];
  186. #define BR_POST_MAX 4096
  187. static char pending_post[BR_POST_MAX];
  188. static unsigned int pending_post_len;
  189. /* The pending navigation is a POST even when its body is empty (a form
  190. * without fields, e.g. the OIDC consent auto-submit). */
  191. static int pending_post_is;
  192. /* window "resize" bookkeeping: the page width the last event was for. */
  193. static int resize_sent_w = -1;
  194. static int resize_pending;
  195. static unsigned int pending_action;
  196. static int cancel_fetch;
  197. static int quit;
  198. static struct ngui_rect page_rect;
  199. static unsigned short *page_backbuf;
  200. static int pagebuf_w, pagebuf_h;
  201. static int page_cache_valid;
  202. static int page_cache_scroll;
  203. static unsigned int page_cache_nnode;
  204. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  205. static int layout_valid, layout_left, layout_right;
  206. /* Height of the page viewport: what html/body height:100% resolves to. */
  207. static int layout_view_h;
  208. static unsigned int layout_nnode;
  209. static int layout_content_h;
  210. /* layout output */
  211. struct lay_run {
  212. unsigned int off;
  213. unsigned short len;
  214. unsigned short gap;
  215. unsigned short color;
  216. unsigned short href;
  217. char lit[28];
  218. short img;
  219. signed short dy; /* inline image vertical offset */
  220. unsigned short iw, ih;
  221. unsigned short w;
  222. unsigned char font_px, bold, italic, mono, underline, strike;
  223. unsigned char overline, font_face;
  224. unsigned char transform_scale;
  225. unsigned char origin_x_kind, origin_y_kind;
  226. signed short scale_x, scale_y, rotate_x100;
  227. signed short origin_x, origin_y;
  228. unsigned char has_lit;
  229. unsigned int form; /* node + 1, 0 = not a control */
  230. unsigned char form_kind;
  231. unsigned char form_disabled;
  232. /* RUN_PBOX: background colour, background image and its placement
  233. * inside the iw x ih box (relative offsets, drawn size). */
  234. unsigned char pb_has_bg;
  235. unsigned short pb_bg;
  236. short pb_img;
  237. short pb_x, pb_y, pb_w, pb_h;
  238. };
  239. struct lay {
  240. int draw;
  241. struct ngui *ui;
  242. int left, right;
  243. int y;
  244. int line_x, line_y, line_h;
  245. int line_left, line_right;
  246. int parent_top;
  247. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  248. int cb_h; /* definite content height of the containing block for
  249. * percentage heights; 0 = indefinite (auto) */
  250. int run_x;
  251. int align;
  252. int depth;
  253. int space_pending;
  254. unsigned char float_active;
  255. int float_left, float_right, float_bottom;
  256. struct lay_run runs[96];
  257. int nruns;
  258. };
  259. struct hit {
  260. int x, y, w, h;
  261. unsigned short node;
  262. };
  263. /* Live form state; the DOM attributes stay the initial/default value. */
  264. #define FORM_MAX 64
  265. #define FORM_VALUE_MAX 63
  266. enum {
  267. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  268. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  269. };
  270. struct form_state {
  271. unsigned int node;
  272. char value[FORM_VALUE_MAX + 1];
  273. unsigned char len, caret, checked, selected, used;
  274. };
  275. static struct form_state form_states[FORM_MAX];
  276. static unsigned int form_focus;
  277. static unsigned int form_dirty;
  278. static int form_descendant(unsigned int node, unsigned int form);
  279. static int form_submit_form(unsigned int node, int fire_event);
  280. static int link_fragment_nav(unsigned int node);
  281. static void history_push(const char *url);
  282. static void form_reset_event(unsigned int form);
  283. static unsigned int s_len(const char *s);
  284. static int s_eq(const char *a, const char *b);
  285. static void form_key(int k);
  286. static void form_click(unsigned int node);
  287. static void style_for_node(unsigned int node, struct br_style *out);
  288. static int form_author_styled(const struct br_style *st);
  289. static int css_radius(const struct br_style *st, int corner, int w, int h);
  290. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  291. const struct br_style *st, int focused);
  292. static int form_disabled(unsigned int node)
  293. {
  294. struct br_node *n = &doc.nodes[node];
  295. if (n->attr_flags & BR_ATTR_DISABLED)
  296. return 1;
  297. return br_find_attr(&doc, node, "disabled") != 0;
  298. }
  299. static int form_kind_of(unsigned int node)
  300. {
  301. const char *type = br_type(&doc, node);
  302. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  303. return FORM_TEXTAREA;
  304. if (doc.nodes[node].tag == BR_TAG_SELECT)
  305. return FORM_SELECT;
  306. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  307. if (s_eq(type, "reset"))
  308. return FORM_RESET;
  309. if (s_eq(type, "button"))
  310. return FORM_BUTTON;
  311. return FORM_SUBMIT;
  312. }
  313. if (s_eq(type, "password"))
  314. return FORM_PASSWORD;
  315. if (s_eq(type, "checkbox"))
  316. return FORM_CHECKBOX;
  317. if (s_eq(type, "radio"))
  318. return FORM_RADIO;
  319. if (s_eq(type, "submit"))
  320. return FORM_SUBMIT;
  321. if (s_eq(type, "reset"))
  322. return FORM_RESET;
  323. if (s_eq(type, "button"))
  324. return FORM_BUTTON;
  325. return FORM_TEXT;
  326. }
  327. static unsigned int form_option_count(unsigned int node)
  328. {
  329. unsigned int c, n = 0;
  330. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  331. if (doc.nodes[c].type == BR_NODE_ELEM &&
  332. doc.nodes[c].tag == BR_TAG_OPTION)
  333. n++;
  334. return n;
  335. }
  336. static unsigned int form_option_selected(unsigned int node)
  337. {
  338. unsigned int c, i = 0;
  339. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  340. if (doc.nodes[c].type != BR_NODE_ELEM ||
  341. doc.nodes[c].tag != BR_TAG_OPTION)
  342. continue;
  343. if (br_find_attr(&doc, c, "selected"))
  344. return i;
  345. i++;
  346. }
  347. return 0;
  348. }
  349. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  350. char *out, unsigned int cap)
  351. {
  352. unsigned int c, i = 0;
  353. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  354. if (doc.nodes[c].type != BR_NODE_ELEM ||
  355. doc.nodes[c].tag != BR_TAG_OPTION)
  356. continue;
  357. if (i == idx)
  358. return br_text_content(&doc, c, out, cap);
  359. i++;
  360. }
  361. return 0;
  362. }
  363. static int form_is_control(unsigned int node);
  364. static struct form_state *form_get(unsigned int node, int create)
  365. {
  366. struct form_state *slot = 0;
  367. unsigned int i;
  368. for (i = 0; i < FORM_MAX; i++) {
  369. if (form_states[i].used) {
  370. if (form_states[i].node == node)
  371. return &form_states[i];
  372. } else if (!slot) {
  373. slot = &form_states[i];
  374. }
  375. }
  376. if (create && !slot) {
  377. /* Full: a client-side router (Docusaurus' React Router)
  378. * replaces page content without a navigation, so slots of
  379. * controls that left the document pile up until no new
  380. * control can be drawn or focused.
  381. * Reuse those first, then slots of nodes that are no longer
  382. * controls. */
  383. for (i = 0; i < FORM_MAX && !slot; i++)
  384. if (form_states[i].node != form_focus &&
  385. br_node_detached(&doc, form_states[i].node))
  386. slot = &form_states[i];
  387. for (i = 0; i < FORM_MAX && !slot; i++)
  388. if (form_states[i].node != form_focus &&
  389. !form_is_control(form_states[i].node))
  390. slot = &form_states[i];
  391. }
  392. if (!create || !slot)
  393. return 0;
  394. slot->node = node;
  395. slot->len = 0;
  396. slot->caret = 0;
  397. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  398. slot->selected = form_option_selected(node);
  399. slot->used = 1;
  400. {
  401. unsigned int n = 0;
  402. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  403. n = br_text_content(&doc, node, slot->value,
  404. FORM_VALUE_MAX + 1);
  405. } else {
  406. const char *v = br_value(&doc, node);
  407. if (v) {
  408. n = s_len(v);
  409. if (n > FORM_VALUE_MAX)
  410. n = FORM_VALUE_MAX;
  411. for (unsigned int j = 0; j < n; j++)
  412. slot->value[j] = v[j];
  413. }
  414. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  415. n = br_text_content(&doc, node, slot->value,
  416. FORM_VALUE_MAX + 1);
  417. }
  418. if (n > FORM_VALUE_MAX)
  419. n = FORM_VALUE_MAX;
  420. slot->value[n] = '\0';
  421. slot->len = (unsigned char)n;
  422. slot->caret = (unsigned char)n;
  423. }
  424. return slot;
  425. }
  426. static void form_reset_state(void)
  427. {
  428. unsigned int i;
  429. for (i = 0; i < FORM_MAX; i++)
  430. form_states[i].used = 0;
  431. form_focus = 0;
  432. }
  433. /* A <button> with element content (an icon <svg>/<img>, a <span> label)
  434. * is laid out like a normal element so that content shows; only a text or
  435. * empty button is drawn as a native control. Clicks still reach it
  436. * through the box hit test. */
  437. static int button_has_elements(unsigned int node)
  438. {
  439. unsigned int c;
  440. if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
  441. return 0;
  442. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  443. if (doc.nodes[c].type == BR_NODE_ELEM)
  444. return 1;
  445. /* An empty button whose icon is a ::before/::after box (Docusaurus'
  446. * sidebar caret) is laid out as an element so the box is drawn. */
  447. if (!doc.nodes[node].first && doc.npe_rules) {
  448. struct br_style st, ps;
  449. char buf[8];
  450. int pe;
  451. style_for_node(node, &st);
  452. for (pe = 1; pe <= 2; pe++)
  453. if (!br_pseudo(&doc, node, pe, &st, &ps, buf,
  454. sizeof(buf)) &&
  455. ps.content == BR_CONTENT_EMPTY &&
  456. ps.display != BR_DISPLAY_NONE)
  457. return 1;
  458. }
  459. return 0;
  460. }
  461. static int form_is_control(unsigned int node)
  462. {
  463. unsigned int tag;
  464. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  465. return 0;
  466. tag = doc.nodes[node].tag;
  467. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  468. tag == BR_TAG_SELECT ||
  469. (tag == BR_TAG_BUTTON && !button_has_elements(node));
  470. }
  471. #define HIT_MAX 96
  472. static struct hit hits[HIT_MAX];
  473. static int nhits;
  474. static unsigned short block_h[BR_MAX_NODES];
  475. /* Border-box height a flex container stretches an item to (align-items:
  476. * stretch in a row with a taller line or a definite height), 0 = none.
  477. * Written by the measure pass, read by both. */
  478. static unsigned short flex_stretch_h[BR_MAX_NODES];
  479. /* Measure-pass top of each block, in the same document coordinates as
  480. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  481. * paint, so it cannot drive the lazy background loader). */
  482. static unsigned short block_top[BR_MAX_NODES];
  483. static char li_marker[BR_MAX_NODES][12];
  484. /* one connection object; the browser fetches one resource at a time */
  485. /* ---- tiny strings ---- */
  486. static unsigned int s_len(const char *s)
  487. {
  488. unsigned int n = 0;
  489. while (s && s[n])
  490. n++;
  491. return n;
  492. }
  493. static void s_copy(char *d, const char *s, unsigned int cap)
  494. {
  495. unsigned int i = 0;
  496. if (!cap)
  497. return;
  498. while (s && s[i] && i + 1 < cap) {
  499. d[i] = s[i];
  500. i++;
  501. }
  502. d[i] = '\0';
  503. }
  504. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  505. {
  506. while (s && *s && *n + 1 < cap)
  507. d[(*n)++] = *s++;
  508. d[*n] = '\0';
  509. }
  510. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  511. unsigned int cap)
  512. {
  513. char tmp[12];
  514. unsigned int i = 0, j;
  515. do {
  516. tmp[i++] = (char)('0' + v % 10);
  517. v /= 10;
  518. } while (v && i < sizeof(tmp));
  519. for (j = 0; j < i && *n + 1 < cap; j++)
  520. d[(*n)++] = tmp[i - 1 - j];
  521. d[*n] = '\0';
  522. }
  523. static int s_eq(const char *a, const char *b)
  524. {
  525. while (*a && *b) {
  526. if (*a != *b)
  527. return 0;
  528. a++;
  529. b++;
  530. }
  531. return *a == *b;
  532. }
  533. static int starts_with(const char *s, const char *p)
  534. {
  535. unsigned int i = 0;
  536. while (p[i]) {
  537. if (s[i] != p[i])
  538. return 0;
  539. i++;
  540. }
  541. return 1;
  542. }
  543. static int contains_ci(const char *s, const char *p)
  544. {
  545. unsigned int i, j;
  546. for (i = 0; s[i]; i++) {
  547. for (j = 0; p[j]; j++) {
  548. char a = s[i + j];
  549. if (a >= 'A' && a <= 'Z')
  550. a = (char)(a - 'A' + 'a');
  551. if (a != p[j])
  552. break;
  553. }
  554. if (!p[j])
  555. return 1;
  556. }
  557. return 0;
  558. }
  559. static char *trim(char *s)
  560. {
  561. unsigned int n;
  562. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  563. s++;
  564. n = s_len(s);
  565. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  566. s[n - 1] == '\r' || s[n - 1] == '\n'))
  567. s[--n] = '\0';
  568. return s;
  569. }
  570. /* ---- per-process heap ---- */
  571. static int heap_start(void)
  572. {
  573. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  574. if (!image_io_buf)
  575. return -1;
  576. page_backbuf = (unsigned short *)malloc(
  577. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  578. pagebuf_w = page_backbuf ? ui.w : 0;
  579. pagebuf_h = page_backbuf ? ui.h : 0;
  580. page_cache_valid = 0;
  581. return 0;
  582. }
  583. static void heap_clear(void)
  584. {
  585. memset(font_faces, 0, sizeof(font_faces));
  586. ngui_font_detach(&ui);
  587. svg_cache_clear();
  588. decode_arena = 0; /* lives in the page heap too */
  589. decode_arena_size = 0;
  590. heap_reset();
  591. /* The document arenas live in that heap; drop the stale pointers so
  592. * the next br_parse_plain() allocates fresh ones. */
  593. doc.nodes = 0;
  594. doc.text = 0;
  595. doc.attrs = 0;
  596. image_io_buf = 0;
  597. page_backbuf = 0;
  598. pagebuf_w = pagebuf_h = 0;
  599. page_cache_valid = 0;
  600. }
  601. static void browser_rules_alloc(void)
  602. {
  603. struct br_rule *rules;
  604. rules = (struct br_rule *)malloc(
  605. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  606. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  607. }
  608. /* ---- status ---- */
  609. static void set_status(const char *s, int err, unsigned int ttl_ms)
  610. {
  611. s_copy(status_text, s, sizeof(status_text));
  612. status_error = err;
  613. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  614. ngui_invalidate(&ui);
  615. }
  616. /* Update the status text without forcing a frame; the throttled image
  617. * repaint picks it up. Starting one helper per image used to invalidate the
  618. * whole page before every decode. */
  619. static void set_status_quiet(const char *s)
  620. {
  621. s_copy(status_text, s, sizeof(status_text));
  622. status_error = 0;
  623. status_until = 0;
  624. }
  625. /* ---- JavaScript ---- */
  626. static int resolve_link(const char *base, const char *href, char *out,
  627. unsigned int cap);
  628. static char js_last_status[BR_STATUS_MAX];
  629. static int js_last_error;
  630. static void js_host_status(const char *msg, int error)
  631. {
  632. s_copy(js_last_status, msg, sizeof(js_last_status));
  633. js_last_error = error;
  634. set_status(msg, error, 6000);
  635. }
  636. static void js_host_report(const char *msg)
  637. {
  638. u_puts("[js] ");
  639. u_puts(msg);
  640. u_putc('\n');
  641. s_copy(js_last_status, msg, sizeof(js_last_status));
  642. js_last_error = 1;
  643. set_status(msg, 1, 8000);
  644. }
  645. static void js_host_navigate(const char *url)
  646. {
  647. char resolved[BR_URL_MAX];
  648. if (!url || !url[0])
  649. return;
  650. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  651. return;
  652. s_copy(pending_url, resolved, sizeof(pending_url));
  653. pending_action |= ACT_NAV;
  654. cancel_fetch = 1;
  655. }
  656. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  657. * back/forward between fragments): the page URL, address bar and history
  658. * follow, nothing is reloaded. `push` adds a history entry. */
  659. static int page_set_fragment(const char *url, int push)
  660. {
  661. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  662. return -1;
  663. s_copy(page_url, url, sizeof(page_url));
  664. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  665. url_in.len = s_len(url_in.text);
  666. url_in.cursor = url_in.len;
  667. url_in.scroll = 0;
  668. if (push)
  669. history_push(page_url);
  670. ngui_invalidate(&ui);
  671. return 0;
  672. }
  673. static int js_host_set_hash(const char *url)
  674. {
  675. return page_set_fragment(url, 1);
  676. }
  677. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  678. * the page, so a hash router can react). */
  679. static int same_doc_fragment(const char *url)
  680. {
  681. unsigned int a = 0, b = 0;
  682. if (!js_browser_active() || !url)
  683. return 0;
  684. while (url[a] && url[a] != '#')
  685. a++;
  686. while (page_url[b] && page_url[b] != '#')
  687. b++;
  688. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  689. !s_eq(url, page_url);
  690. }
  691. static void js_host_changed(void)
  692. {
  693. /* Class/style/attribute mutations change computed styles, not just the
  694. * text: drop the per-node style cache before the next layout. */
  695. br_reset_styles(&doc);
  696. layout_valid = 0;
  697. /* Script-built content (Angular's ng-repeat cards) brings new images
  698. * and inline background styles: rescan once the main loop is idle. */
  699. preload_rescan = 1;
  700. ngui_invalidate(&ui);
  701. }
  702. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  703. {
  704. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  705. return 0;
  706. *x = layout_boxes[node].x - page_rect.x;
  707. *y = layout_boxes[node].y - page_rect.y;
  708. *w = layout_boxes[node].w;
  709. *h = layout_boxes[node].h;
  710. return 1;
  711. }
  712. static void form_copy_out(const char *s, char *buf, int cap)
  713. {
  714. int i = 0;
  715. if (!buf || cap <= 0)
  716. return;
  717. while (s && s[i] && i + 1 < cap) {
  718. buf[i] = s[i];
  719. i++;
  720. }
  721. buf[i] = '\0';
  722. }
  723. static int js_host_form_value(unsigned int node, char *buf, int cap)
  724. {
  725. struct form_state *fs;
  726. int kind;
  727. if (!form_is_control(node))
  728. return 0;
  729. kind = form_kind_of(node);
  730. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  731. return 0;
  732. if (kind == FORM_SELECT) {
  733. char opt[64] = "";
  734. unsigned int c, i = 0;
  735. fs = form_get(node, 1);
  736. if (!fs)
  737. return 0;
  738. form_option_text(node, fs->selected, opt, sizeof(opt));
  739. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  740. if (doc.nodes[c].type != BR_NODE_ELEM ||
  741. doc.nodes[c].tag != BR_TAG_OPTION)
  742. continue;
  743. if (i == fs->selected) {
  744. const char *v = br_value(&doc, c);
  745. if (v && v[0])
  746. form_copy_out(v, buf, cap);
  747. else
  748. form_copy_out(opt, buf, cap);
  749. return 1;
  750. }
  751. i++;
  752. }
  753. form_copy_out(opt, buf, cap);
  754. return 1;
  755. }
  756. fs = form_get(node, 1);
  757. if (!fs)
  758. return 0;
  759. form_copy_out(fs->value, buf, cap);
  760. return 1;
  761. }
  762. static int js_host_form_checked(unsigned int node)
  763. {
  764. struct form_state *fs;
  765. int kind;
  766. if (!form_is_control(node))
  767. return -1;
  768. kind = form_kind_of(node);
  769. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  770. return -1;
  771. fs = form_get(node, 1);
  772. return fs ? fs->checked : 0;
  773. }
  774. static int js_host_form_selected(unsigned int node)
  775. {
  776. struct form_state *fs;
  777. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  778. return -1;
  779. fs = form_get(node, 1);
  780. return fs ? fs->selected : 0;
  781. }
  782. static int js_host_form_set_value(unsigned int node, const char *value)
  783. {
  784. struct form_state *fs;
  785. unsigned int n;
  786. if (!form_is_control(node))
  787. return 0;
  788. fs = form_get(node, 1);
  789. if (!fs)
  790. return 0;
  791. n = s_len(value ? value : "");
  792. if (n > FORM_VALUE_MAX)
  793. n = FORM_VALUE_MAX;
  794. for (unsigned int i = 0; i < n; i++)
  795. fs->value[i] = value[i];
  796. fs->value[n] = '\0';
  797. fs->len = (unsigned char)n;
  798. fs->caret = (unsigned char)n;
  799. layout_valid = 0;
  800. ngui_invalidate(&ui);
  801. return 1;
  802. }
  803. static int js_host_form_set_checked(unsigned int node, int checked)
  804. {
  805. struct form_state *fs;
  806. int kind;
  807. if (!form_is_control(node))
  808. return 0;
  809. kind = form_kind_of(node);
  810. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  811. return 0;
  812. fs = form_get(node, 1);
  813. if (!fs)
  814. return 0;
  815. fs->checked = (unsigned char)(checked != 0);
  816. layout_valid = 0;
  817. ngui_invalidate(&ui);
  818. return 1;
  819. }
  820. static int js_host_form_set_selected(unsigned int node, int index)
  821. {
  822. struct form_state *fs;
  823. unsigned int n;
  824. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  825. return 0;
  826. fs = form_get(node, 1);
  827. if (!fs)
  828. return 0;
  829. n = form_option_count(node);
  830. if (index < 0)
  831. index = 0;
  832. if (n && (unsigned int)index >= n)
  833. index = (int)n - 1;
  834. fs->selected = (unsigned char)index;
  835. layout_valid = 0;
  836. ngui_invalidate(&ui);
  837. return 1;
  838. }
  839. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  840. {
  841. unsigned int i;
  842. int n = 0;
  843. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  844. doc.nodes[form].tag != BR_TAG_FORM)
  845. return 0;
  846. for (i = 0; i < doc.nnode && n < cap; i++) {
  847. struct br_node *nd = &doc.nodes[i];
  848. if (i == form || nd->type != BR_NODE_ELEM)
  849. continue;
  850. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  851. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  852. continue;
  853. if (!form_descendant(i, form))
  854. continue;
  855. out[n++] = i;
  856. }
  857. return n;
  858. }
  859. static int js_host_form_submit(unsigned int form)
  860. {
  861. form_submit_form(form, 0);
  862. return 1;
  863. }
  864. static int js_host_form_reset(unsigned int form)
  865. {
  866. form_reset_event(form);
  867. return 1;
  868. }
  869. static void css_computed_name(const char *p, char *out, int cap)
  870. {
  871. int n = 0;
  872. for (; p && *p && n + 2 < cap; p++) {
  873. char c = *p;
  874. if (c >= 'A' && c <= 'Z') {
  875. out[n++] = '-';
  876. c = (char)(c - 'A' + 'a');
  877. } else if (c == '_') {
  878. c = '-';
  879. } else if (c >= 'a' && c <= 'z') {
  880. /* keep */
  881. }
  882. out[n++] = c;
  883. }
  884. out[n] = '\0';
  885. if (!strcmp(out, "css-float"))
  886. strcpy(out, "float");
  887. }
  888. static void css_rgb(unsigned short c, char *buf, int cap)
  889. {
  890. int r = ((c >> 11) & 31) * 255 / 31;
  891. int g = ((c >> 5) & 63) * 255 / 63;
  892. int b = (c & 31) * 255 / 31;
  893. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  894. }
  895. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  896. int font_px)
  897. {
  898. if (unit == 4) {
  899. snprintf(buf, cap, "auto");
  900. } else if (unit == 0) {
  901. snprintf(buf, cap, "%dpx", raw);
  902. } else if (unit == 1) {
  903. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  904. } else if (unit == 2) {
  905. /* Chrome's getComputedStyle() reports used pixel values. */
  906. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  907. } else if (unit == 3) {
  908. snprintf(buf, cap, "%dpx",
  909. (int)br_root_font_px() * raw / 100);
  910. } else {
  911. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  912. raw / 100, raw % 100, px);
  913. }
  914. }
  915. static int js_host_computed(unsigned int node, const char *property,
  916. char *buf, int cap)
  917. {
  918. struct br_style st;
  919. char name[40];
  920. /* Node 0 is a real element when the page starts with <html>. */
  921. if (!buf || cap <= 0 || node >= doc.nnode ||
  922. (node == 0 && doc.nodes[0].type != BR_NODE_ELEM))
  923. return 0;
  924. buf[0] = '\0';
  925. css_computed_name(property, name, sizeof(name));
  926. style_for_node(node, &st);
  927. if (!strcmp(name, "display")) {
  928. const char *v = "inline";
  929. if (st.display == BR_DISPLAY_BLOCK)
  930. v = "block";
  931. else if (st.display == BR_DISPLAY_NONE)
  932. v = "none";
  933. else if (st.display == BR_DISPLAY_FLEX)
  934. v = "flex";
  935. else if (st.display == BR_DISPLAY_GRID)
  936. v = "grid";
  937. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  938. v = "inline-block";
  939. snprintf(buf, cap, "%s", v);
  940. } else if (!strcmp(name, "position")) {
  941. static const char *pos[] = {
  942. "static", "absolute", "fixed", "relative", "sticky"
  943. };
  944. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  945. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  946. int is_w = name[0] == 'w';
  947. int kind = is_w ? st.width_kind : st.height_kind;
  948. int val = is_w ? st.width : st.height;
  949. if (kind == 3) {
  950. if (is_w)
  951. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  952. st.width_calc_pct / 100,
  953. st.width_calc_pct % 100,
  954. st.width_calc_px);
  955. else
  956. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  957. st.height_calc_pct / 100,
  958. st.height_calc_pct % 100,
  959. st.height_calc_px);
  960. } else if (kind == 1) {
  961. snprintf(buf, cap, "%dpx", val);
  962. } else if (kind == 2) {
  963. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  964. } else {
  965. snprintf(buf, cap, "auto");
  966. }
  967. } else if (!strcmp(name, "color") ||
  968. !strcmp(name, "background-color")) {
  969. if (!strcmp(name, "background-color") && !st.has_bg)
  970. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  971. else
  972. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  973. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  974. int is_fill = name[0] == 'f';
  975. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  976. if (mode == BR_PAINT_COLOR)
  977. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  978. else if (mode == BR_PAINT_CURRENT)
  979. css_rgb(st.color, buf, cap);
  980. else if (mode == BR_PAINT_UNSET && is_fill)
  981. snprintf(buf, cap, "rgb(0, 0, 0)");
  982. else if (mode == BR_PAINT_URL)
  983. snprintf(buf, cap, "url()");
  984. else
  985. snprintf(buf, cap, "none");
  986. } else if (!strcmp(name, "font-size")) {
  987. snprintf(buf, cap, "%dpx", st.font_px);
  988. } else if (!strcmp(name, "font-weight")) {
  989. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  990. } else if (!strcmp(name, "font-style")) {
  991. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  992. } else if (!strcmp(name, "font-family")) {
  993. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  994. br_font_face_family(st.font_face)[0])
  995. snprintf(buf, cap, "%s",
  996. br_font_face_family(st.font_face));
  997. else
  998. snprintf(buf, cap, "%s",
  999. st.mono ? "monospace" : "sans-serif");
  1000. } else if (!strcmp(name, "text-align")) {
  1001. static const char *al[] = { "left", "center", "right", "justify" };
  1002. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  1003. } else if (!strcmp(name, "float")) {
  1004. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  1005. st.float_left == 2 ? "right" : "none");
  1006. } else if (!strcmp(name, "clear")) {
  1007. static const char *cl[] = { "none", "left", "right", "both" };
  1008. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  1009. } else if (!strcmp(name, "opacity")) {
  1010. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  1011. } else if (!strcmp(name, "visibility")) {
  1012. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  1013. } else if (!strcmp(name, "overflow")) {
  1014. snprintf(buf, cap, "%s",
  1015. st.overflow_hidden ? "hidden" : "visible");
  1016. } else if (!strcmp(name, "white-space")) {
  1017. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  1018. } else if (!strcmp(name, "text-transform")) {
  1019. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  1020. } else if (!strcmp(name, "box-sizing")) {
  1021. snprintf(buf, cap, "%s",
  1022. st.box_sizing ? "border-box" : "content-box");
  1023. } else if (!strcmp(name, "line-height")) {
  1024. if (st.line_h_px)
  1025. snprintf(buf, cap, "%dpx", st.line_h_px);
  1026. else if (st.line_h_pct)
  1027. snprintf(buf, cap, "%d%%", st.line_h_pct);
  1028. else
  1029. snprintf(buf, cap, "normal");
  1030. } else if (!strcmp(name, "z-index")) {
  1031. if (st.z_set)
  1032. snprintf(buf, cap, "%d", st.z_index);
  1033. else
  1034. snprintf(buf, cap, "auto");
  1035. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  1036. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  1037. int set = name[0] == 't' ? st.top_set :
  1038. name[0] == 'l' ? st.left_set :
  1039. name[0] == 'r' ? st.right_set : st.bottom_set;
  1040. int v = name[0] == 't' ? st.top :
  1041. name[0] == 'l' ? st.left :
  1042. name[0] == 'r' ? st.right : st.bottom;
  1043. if (set)
  1044. snprintf(buf, cap, "%dpx", v);
  1045. else
  1046. snprintf(buf, cap, "auto");
  1047. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  1048. !strcmp(name, "margin-bottom") ||
  1049. !strcmp(name, "margin-left") ||
  1050. !strcmp(name, "padding-top") ||
  1051. !strcmp(name, "padding-right") ||
  1052. !strcmp(name, "padding-bottom") ||
  1053. !strcmp(name, "padding-left")) {
  1054. int is_pad = name[0] == 'p';
  1055. int side = name[strlen(name) - 1] == 'p' ? 0 :
  1056. name[strlen(name) - 1] == 't' ? 1 :
  1057. name[strlen(name) - 1] == 'm' ? 2 : 3;
  1058. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  1059. if (!strcmp(name, "margin-right") ||
  1060. !strcmp(name, "padding-right"))
  1061. side = 1;
  1062. else if (!strcmp(name, "margin-bottom") ||
  1063. !strcmp(name, "padding-bottom"))
  1064. side = 2;
  1065. else if (!strcmp(name, "margin-left") ||
  1066. !strcmp(name, "padding-left"))
  1067. side = 3;
  1068. else
  1069. side = 0;
  1070. side += is_pad ? 4 : 0;
  1071. css_mp_value(buf, cap,
  1072. side == 0 ? st.mt : side == 1 ? st.mr :
  1073. side == 2 ? st.mb : side == 3 ? st.ml :
  1074. side == 4 ? st.pt : side == 5 ? st.pr :
  1075. side == 6 ? st.pb : st.pl,
  1076. st.mp_unit[side], st.mp_calc_px[side],
  1077. st.font_px);
  1078. } else if (!strcmp(name, "border-top-width") ||
  1079. !strcmp(name, "border-right-width") ||
  1080. !strcmp(name, "border-bottom-width") ||
  1081. !strcmp(name, "border-left-width")) {
  1082. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1083. name[7] == 'b' ? 2 : 3;
  1084. snprintf(buf, cap, "%dpx", st.border_w[side]);
  1085. } else if (!strcmp(name, "border-top-color") ||
  1086. !strcmp(name, "border-right-color") ||
  1087. !strcmp(name, "border-bottom-color") ||
  1088. !strcmp(name, "border-left-color")) {
  1089. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1090. name[7] == 'b' ? 2 : 3;
  1091. if (st.border_w[side] && !st.border_t[side])
  1092. css_rgb(st.border_c[side], buf, cap);
  1093. else
  1094. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1095. } else if (!strcmp(name, "background-image")) {
  1096. if (st.bg_image)
  1097. snprintf(buf, cap, "url(\"%s\")",
  1098. br_bg_image_url(st.bg_image - 1));
  1099. else
  1100. snprintf(buf, cap, "none");
  1101. } else if (!strcmp(name, "background-repeat")) {
  1102. static const char *rp[] = {
  1103. "repeat", "no-repeat", "repeat-x", "repeat-y"
  1104. };
  1105. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  1106. st.bg_repeat : 0]);
  1107. } else if (!strcmp(name, "background-position")) {
  1108. if (st.bg_pos_x_kind == 1)
  1109. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  1110. st.bg_pos_y);
  1111. else
  1112. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1113. st.bg_pos_y);
  1114. } else if (!strcmp(name, "background-size")) {
  1115. if (st.bg_size_kind == 3)
  1116. snprintf(buf, cap, "cover");
  1117. else if (st.bg_size_kind == 4)
  1118. snprintf(buf, cap, "contain");
  1119. else if (st.bg_size_kind == 1)
  1120. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1121. st.bg_size_h);
  1122. else if (st.bg_size_kind == 2)
  1123. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1124. st.bg_size_h);
  1125. else
  1126. snprintf(buf, cap, "auto");
  1127. } else if (!strcmp(name, "transform")) {
  1128. char tmp[128];
  1129. unsigned int n = 0;
  1130. if (!st.transform_set) {
  1131. snprintf(buf, cap, "none");
  1132. } else {
  1133. tmp[0] = '\0';
  1134. if (st.tx || st.ty) {
  1135. snprintf(tmp + n, sizeof(tmp) - n,
  1136. "translate(%dpx, %dpx)", st.tx, st.ty);
  1137. n = (unsigned int)strlen(tmp);
  1138. }
  1139. if (st.transform_scale) {
  1140. snprintf(tmp + n, sizeof(tmp) - n,
  1141. "%sscale(%d.%02d, %d.%02d)",
  1142. n ? " " : "", st.scale_x / 100,
  1143. st.scale_x % 100, st.scale_y / 100,
  1144. st.scale_y % 100);
  1145. n = (unsigned int)strlen(tmp);
  1146. if (st.rotate_x100) {
  1147. snprintf(tmp + n, sizeof(tmp) - n,
  1148. " rotate(%d.%02ddeg)",
  1149. st.rotate_x100 / 100,
  1150. st.rotate_x100 % 100);
  1151. }
  1152. } else if (st.rotate_x100) {
  1153. snprintf(tmp + n, sizeof(tmp) - n,
  1154. "%srotate(%d.%02ddeg)",
  1155. n ? " " : "", st.rotate_x100 / 100,
  1156. st.rotate_x100 % 100);
  1157. }
  1158. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1159. }
  1160. } else {
  1161. return 0;
  1162. }
  1163. return buf[0] != '\0';
  1164. }
  1165. static int js_host_click(unsigned int node)
  1166. {
  1167. char url[BR_URL_MAX];
  1168. const char *href;
  1169. if (node >= doc.nnode)
  1170. return 0;
  1171. if (form_is_control(node)) {
  1172. form_click(node); /* dispatches its own click event */
  1173. return 1;
  1174. }
  1175. /* element.click() fires a bubbling, cancelable click before the
  1176. * default action, like a real click (delegated list handlers). */
  1177. if (!js_browser_event(node, "click", 1, 1))
  1178. return 1;
  1179. if (link_fragment_nav(node))
  1180. return 1;
  1181. href = br_href(&doc, node);
  1182. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1183. return 0;
  1184. s_copy(pending_url, url, sizeof(pending_url));
  1185. pending_action |= ACT_NAV;
  1186. cancel_fetch = 1;
  1187. ngui_invalidate(&ui);
  1188. return 1;
  1189. }
  1190. static int fetch_script_text(const char *url, unsigned char **out,
  1191. unsigned int *outlen, char *err,
  1192. unsigned int errcap);
  1193. struct fetch_worker;
  1194. static struct fetch_worker *fetch_worker_alloc(void);
  1195. static void fetch_worker_release(struct fetch_worker *w);
  1196. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1197. unsigned int cap, const char *post,
  1198. unsigned int post_len, unsigned int node,
  1199. int bg, char *err, unsigned int errcap);
  1200. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1201. unsigned int errcap);
  1202. static int fetch_worker_read_body(struct fetch_worker *w,
  1203. unsigned char *plain,
  1204. unsigned int plaincap,
  1205. unsigned char *comp,
  1206. unsigned int compcap,
  1207. int *truncated, char *err,
  1208. unsigned int errcap);
  1209. static void fetch_workers_stop_all(void);
  1210. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1211. unsigned int cap, const char *method,
  1212. const char *ctype, const char *post,
  1213. unsigned int post_len, unsigned int node,
  1214. int bg, unsigned int dec_w,
  1215. unsigned int dec_h, char *err,
  1216. unsigned int errcap);
  1217. static int script_cache_has(const char *url);
  1218. static void script_cache_put(const char *url, const unsigned char *data,
  1219. unsigned int len);
  1220. static unsigned int script_cache_hash(const char *s);
  1221. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1222. unsigned int errcap);
  1223. static void fetch_workers_cancel_busy(void);
  1224. static void worker_wait_ui(void);
  1225. static int fetch_worker_status(const struct fetch_worker *w);
  1226. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1227. * module load: the wait must not pump input, or a click would dispatch DOM
  1228. * events into the middle of the running script. */
  1229. static int fetch_wait_passive;
  1230. static void script_error(const char *what, const char *url, const char *why)
  1231. {
  1232. char msg[192];
  1233. unsigned int n = 0;
  1234. s_append(msg, &n, what, sizeof(msg));
  1235. if (url && url[0]) {
  1236. s_append(msg, &n, " ", sizeof(msg));
  1237. s_append(msg, &n, url, sizeof(msg));
  1238. }
  1239. if (why && why[0]) {
  1240. s_append(msg, &n, ": ", sizeof(msg));
  1241. s_append(msg, &n, why, sizeof(msg));
  1242. }
  1243. js_host_report(msg);
  1244. }
  1245. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1246. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1247. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1248. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1249. #define JS_HTTP_POST_MAX (16u * 1024u)
  1250. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1251. static int js_worker_http(const char *method, const char *url,
  1252. const char *ctype, const char *body,
  1253. unsigned int body_len, struct js_http_resp *r,
  1254. char *err, int errcap);
  1255. static int js_host_http(const char *method, const char *url,
  1256. const char *ctype, const char *body,
  1257. unsigned int body_len, struct js_http_resp *r,
  1258. char *err, int errcap)
  1259. {
  1260. if (pending_action) {
  1261. s_copy(err, "page is navigating", (unsigned int)errcap);
  1262. return -1;
  1263. }
  1264. if (url[0] == '/') {
  1265. /* Local file: GET only. */
  1266. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1267. int rv;
  1268. if (!buf) {
  1269. s_copy(err, "out of memory", (unsigned int)errcap);
  1270. return -1;
  1271. }
  1272. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1273. (int)JS_HTTP_MAX);
  1274. r->status = rv < 0 ? 404 : 200;
  1275. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1276. buf[r->len] = '\0';
  1277. r->body = (char *)buf;
  1278. s_copy(r->url, url, sizeof(r->url));
  1279. if (contains_ci(url, ".json"))
  1280. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1281. return 0;
  1282. }
  1283. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1284. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1285. return -1;
  1286. }
  1287. if (body_len > JS_HTTP_POST_MAX) {
  1288. s_copy(err, "request body too large", (unsigned int)errcap);
  1289. return -1;
  1290. }
  1291. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1292. errcap);
  1293. }
  1294. /* Module source for the engine's loader: the boot script cache first, then
  1295. * one blocking fetch with input pumping disabled (the loader runs inside
  1296. * JavaScript). */
  1297. static char *js_host_load_script(const char *url, unsigned int *len)
  1298. {
  1299. unsigned char *data = 0;
  1300. char err[64];
  1301. int rv;
  1302. fetch_wait_passive++;
  1303. set_status("Loading module...", 0, 0);
  1304. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1305. fetch_wait_passive--;
  1306. if (rv != 0) {
  1307. script_error("Cannot load module", url,
  1308. rv == FETCH_ABORT ? "navigation" : err);
  1309. return 0;
  1310. }
  1311. return (char *)data;
  1312. }
  1313. /* Web Storage lives in /share, outside the page heap that every navigation
  1314. * resets: localStorage per origin for the boot, sessionStorage per origin
  1315. * and browser window. */
  1316. #define JS_ORIGIN_MAX 160
  1317. /* scheme://host[:port] of the page (a local page's whole path). */
  1318. static void js_page_origin(char *origin, unsigned int cap)
  1319. {
  1320. unsigned int i = 0, slashes = 0;
  1321. while (page_url[i] && i + 1 < cap) {
  1322. if (page_url[i] == '/' && ++slashes == 3)
  1323. break;
  1324. origin[i] = page_url[i];
  1325. i++;
  1326. }
  1327. origin[i] = '\0';
  1328. }
  1329. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1330. {
  1331. unsigned int n = 0;
  1332. s_append(out, &n, "/share/bls", cap);
  1333. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1334. }
  1335. static void js_storage_path(int kind, char *out, unsigned int cap)
  1336. {
  1337. char origin[JS_ORIGIN_MAX];
  1338. unsigned int n = 0;
  1339. js_page_origin(origin, sizeof(origin));
  1340. if (!kind) {
  1341. js_origin_path(origin, out, cap);
  1342. return;
  1343. }
  1344. s_append(out, &n, "/share/bss", cap);
  1345. if (kind) {
  1346. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1347. s_append(out, &n, "-", cap);
  1348. }
  1349. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1350. }
  1351. static void persist_mark_origin(const char *origin);
  1352. static int persist_store_lookup(const char *origin, char *out, int cap);
  1353. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1354. {
  1355. char path[48], origin[JS_ORIGIN_MAX];
  1356. int rv;
  1357. js_storage_path(kind, path, sizeof(path));
  1358. if (set) {
  1359. if (kind) {
  1360. if (!set[0] || !strcmp(set, "{}")) {
  1361. u_syscall1(SYS_UNLINK, (int)path);
  1362. return 0;
  1363. }
  1364. } else {
  1365. /* localStorage keeps an explicit "{}" rather than no
  1366. * file: a missing /share file means "not loaded from
  1367. * /data yet", and a cleared store must not come back
  1368. * from the disk copy before it is flushed. */
  1369. if (!set[0])
  1370. set = "{}";
  1371. js_page_origin(origin, sizeof(origin));
  1372. persist_mark_origin(origin);
  1373. }
  1374. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1375. (int)strlen(set)) < 0 ? -1 : 0;
  1376. }
  1377. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1378. if (rv < 0 && !kind) {
  1379. /* First use this boot: the persistent copy on /data. */
  1380. js_page_origin(origin, sizeof(origin));
  1381. rv = persist_store_lookup(origin, out, cap);
  1382. if (rv >= 0)
  1383. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1384. }
  1385. if (rv < 0)
  1386. return -1;
  1387. out[rv] = '\0';
  1388. return rv;
  1389. }
  1390. /* ---- persistence on /data ----
  1391. *
  1392. * /share is the working copy (RAM, shared by every helper and window); the
  1393. * installed disk's /data volume keeps the cookie jar and localStorage
  1394. * across reboots when it is mounted. The browser owns the disk copies: at
  1395. * start it restores the jar into /share, and its main loop writes back
  1396. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1397. * setItem updates costs one FAT write. The helpers only touch /share (they
  1398. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1399. * /data mount every disk access simply fails. Both files are plaintext
  1400. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1401. #define PERSIST_MS 3000u
  1402. #define SHARE_COOKIES "/share/bcookies"
  1403. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1404. #define DATA_STORE "/data/BSTORE.DAT"
  1405. #define DATA_STORE_MAGIC "NBLS1\n"
  1406. #define DATA_STORE_MAX (192u * 1024u)
  1407. #define PERSIST_DIRTY_MAX 8
  1408. static unsigned int persist_due;
  1409. static unsigned int cookie_sum_saved;
  1410. static int cookie_sum_valid;
  1411. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1412. static int persist_ndirty;
  1413. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1414. {
  1415. unsigned int h = 2166136261u, i;
  1416. for (i = 0; i < n; i++)
  1417. h = (h ^ p[i]) * 16777619u;
  1418. return h;
  1419. }
  1420. /* Called once at startup, before any helper runs. */
  1421. static void persist_restore(void)
  1422. {
  1423. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1424. int n;
  1425. if (!jar)
  1426. return;
  1427. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1428. (int)sizeof(struct uhttp_jar));
  1429. if (n != (int)sizeof(struct uhttp_jar)) {
  1430. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1431. (int)sizeof(struct uhttp_jar));
  1432. if (n == (int)sizeof(struct uhttp_jar)) {
  1433. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1434. (int)jar, n);
  1435. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1436. cookie_sum_valid = 1;
  1437. }
  1438. }
  1439. free(jar);
  1440. persist_due = u_ticks_ms() + PERSIST_MS;
  1441. }
  1442. static void persist_mark_origin(const char *origin)
  1443. {
  1444. int i;
  1445. for (i = 0; i < persist_ndirty; i++)
  1446. if (s_eq(persist_dirty[i], origin))
  1447. return;
  1448. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1449. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1450. }
  1451. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1452. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1453. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1454. unsigned int *o_off, unsigned int *o_len,
  1455. unsigned int *d_off, unsigned int *d_len,
  1456. unsigned int *rec_end)
  1457. {
  1458. unsigned int p = *pos, v = 0;
  1459. if (p >= len)
  1460. return 0;
  1461. *o_off = p;
  1462. while (p < len && buf[p] != '\n')
  1463. p++;
  1464. if (p >= len)
  1465. return 0;
  1466. *o_len = p - *o_off;
  1467. p++;
  1468. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1469. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1470. if (p >= len || buf[p] != '\n')
  1471. return 0;
  1472. p++;
  1473. if (v > len - p)
  1474. return 0;
  1475. *d_off = p;
  1476. *d_len = v;
  1477. p += v;
  1478. if (p < len && buf[p] == '\n')
  1479. p++;
  1480. *rec_end = p;
  1481. *pos = p;
  1482. return 1;
  1483. }
  1484. static int store_load(char **out)
  1485. {
  1486. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1487. int n;
  1488. *out = buf;
  1489. if (!buf)
  1490. return -1;
  1491. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1492. (int)DATA_STORE_MAX);
  1493. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1494. !starts_with(buf, DATA_STORE_MAGIC))
  1495. return 0;
  1496. return n;
  1497. }
  1498. static int persist_store_lookup(const char *origin, char *out, int cap)
  1499. {
  1500. char *buf;
  1501. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1502. unsigned int olen = s_len(origin);
  1503. int n = store_load(&buf), rv = -1;
  1504. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1505. &dl, &e)) {
  1506. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1507. if ((int)dl < cap) {
  1508. memcpy(out, buf + d, dl);
  1509. out[dl] = '\0';
  1510. rv = (int)dl;
  1511. }
  1512. break;
  1513. }
  1514. }
  1515. free(buf);
  1516. return rv;
  1517. }
  1518. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1519. static void persist_store_flush(void)
  1520. {
  1521. char *old, *nb, path[48];
  1522. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1523. int n = store_load(&old), i, w;
  1524. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1525. if (n < 0 || !nb) {
  1526. free(old);
  1527. free(nb);
  1528. return;
  1529. }
  1530. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1531. /* Untouched origins first, in their old order. */
  1532. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1533. &dl, &e)) {
  1534. int dirty = 0;
  1535. for (i = 0; i < persist_ndirty; i++)
  1536. if (s_len(persist_dirty[i]) == ol &&
  1537. !memcmp(persist_dirty[i], old + oo, ol))
  1538. dirty = 1;
  1539. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1540. continue;
  1541. memcpy(nb + nn, old + oo, e - oo);
  1542. nn += e - oo;
  1543. }
  1544. /* Then the changed ones (an emptied store is dropped). */
  1545. for (i = 0; i < persist_ndirty; i++) {
  1546. char num[12];
  1547. unsigned int k = 0;
  1548. js_origin_path(persist_dirty[i], path, sizeof(path));
  1549. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1550. (int)DATA_STORE_MAX);
  1551. if (w <= 2) /* missing or "{}" */
  1552. continue;
  1553. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1554. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1555. DATA_STORE_MAX) {
  1556. set_status("Saved site data is full; a site's "
  1557. "localStorage was not saved", 1, 6000);
  1558. continue;
  1559. }
  1560. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1561. nb[nn++] = '\n';
  1562. s_append(nb, &nn, num, DATA_STORE_MAX);
  1563. nb[nn++] = '\n';
  1564. memcpy(nb + nn, old, (unsigned int)w);
  1565. nn += (unsigned int)w;
  1566. nb[nn++] = '\n';
  1567. }
  1568. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1569. persist_ndirty = 0;
  1570. free(old);
  1571. free(nb);
  1572. }
  1573. static void persist_cookies_flush(void)
  1574. {
  1575. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1576. unsigned int sum;
  1577. int n;
  1578. if (!jar)
  1579. return;
  1580. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1581. (int)sizeof(struct uhttp_jar));
  1582. if (n == (int)sizeof(struct uhttp_jar)) {
  1583. sum = persist_sum(jar, (unsigned int)n);
  1584. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1585. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1586. (int)jar, n) >= 0) {
  1587. cookie_sum_saved = sum;
  1588. cookie_sum_valid = 1;
  1589. }
  1590. }
  1591. }
  1592. free(jar);
  1593. }
  1594. /* ---- visit history (URL-bar autocomplete) ----
  1595. *
  1596. * Every page that finishes loading is recorded with its title, a visit
  1597. * count and a stamp: a counter that only grows and travels with the file,
  1598. * so it orders visits across windows and boots without a wall clock. The
  1599. * table lives in BSS, because the page heap is reset on every navigation.
  1600. * The boot's browser windows share it through /share/bhist (rewritten on
  1601. * every visit) and it is persisted to /data/BHIST.DAT from persist_tick()
  1602. * at most every PERSIST_MS, like the cookie jar. A save re-reads
  1603. * /share/bhist and merges it first, so two windows add to one history
  1604. * instead of overwriting each other. File format: "NBHIST1\n", then
  1605. * "<visits> <stamp> <url>\t<title>\n" per entry. Plaintext, like the
  1606. * other browser state on /data. */
  1607. #define HIST_MAX 128
  1608. #define HIST_URL_MAX 512
  1609. #define HIST_FILE_MAX (HIST_MAX * (HIST_URL_MAX + BR_TITLE_MAX + 24) + 16)
  1610. #define HIST_MAGIC "NBHIST1\n"
  1611. #define SHARE_HIST "/share/bhist"
  1612. #define DATA_HIST "/data/BHIST.DAT"
  1613. #define HIST_FORGET_MAX 16
  1614. struct hist_ent {
  1615. unsigned int visits;
  1616. unsigned int stamp;
  1617. char url[HIST_URL_MAX];
  1618. char title[BR_TITLE_MAX];
  1619. };
  1620. static struct hist_ent hist_tab[HIST_MAX];
  1621. static int hist_n;
  1622. static int hist_share_dirty, hist_data_dirty;
  1623. /* URLs removed in this process: a merge must not bring them back. */
  1624. static unsigned int hist_forgot[HIST_FORGET_MAX];
  1625. static int hist_nforgot;
  1626. static unsigned int hist_hash(const char *s)
  1627. {
  1628. return persist_sum((const unsigned char *)s, s_len(s));
  1629. }
  1630. static int hist_is_forgotten(const char *url)
  1631. {
  1632. unsigned int h = hist_hash(url);
  1633. int i;
  1634. for (i = 0; i < hist_nforgot; i++)
  1635. if (hist_forgot[i] == h)
  1636. return 1;
  1637. return 0;
  1638. }
  1639. static int hist_find(const char *url)
  1640. {
  1641. int i;
  1642. for (i = 0; i < hist_n; i++)
  1643. if (s_eq(hist_tab[i].url, url))
  1644. return i;
  1645. return -1;
  1646. }
  1647. static unsigned int hist_next_stamp(void)
  1648. {
  1649. unsigned int m = 0;
  1650. int i;
  1651. for (i = 0; i < hist_n; i++)
  1652. if (hist_tab[i].stamp > m)
  1653. m = hist_tab[i].stamp;
  1654. return m + 1;
  1655. }
  1656. /* Copy a title, turning tabs/newlines (the file separators) into spaces. */
  1657. static void hist_copy_title(char *d, const char *s, unsigned int n)
  1658. {
  1659. unsigned int i;
  1660. for (i = 0; i + 1 < BR_TITLE_MAX && i < n && s[i]; i++)
  1661. d[i] = (unsigned char)s[i] < 0x20 ? ' ' : s[i];
  1662. d[i] = '\0';
  1663. }
  1664. /* Insert or update an entry; the newer stamp wins the title, the larger
  1665. * visit count is kept. A full table evicts the least recent entry, unless
  1666. * the new one is older still. Returns NULL when nothing was stored. */
  1667. static struct hist_ent *hist_put(const char *url, const char *title,
  1668. unsigned int visits, unsigned int stamp)
  1669. {
  1670. struct hist_ent *e;
  1671. int i = hist_find(url);
  1672. if (i < 0) {
  1673. if (hist_n < HIST_MAX) {
  1674. i = hist_n++;
  1675. } else {
  1676. int j;
  1677. i = 0;
  1678. for (j = 1; j < hist_n; j++)
  1679. if (hist_tab[j].stamp < hist_tab[i].stamp)
  1680. i = j;
  1681. if (hist_tab[i].stamp >= stamp)
  1682. return 0;
  1683. }
  1684. e = &hist_tab[i];
  1685. e->visits = 0;
  1686. e->stamp = 0;
  1687. e->title[0] = '\0';
  1688. s_copy(e->url, url, sizeof(e->url));
  1689. }
  1690. e = &hist_tab[i];
  1691. if (visits > e->visits)
  1692. e->visits = visits;
  1693. if (stamp >= e->stamp) {
  1694. e->stamp = stamp;
  1695. if (title && title[0])
  1696. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1697. } else if (!e->title[0] && title) {
  1698. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1699. }
  1700. return e;
  1701. }
  1702. static unsigned int hist_parse_dec(const char *b, int n, int *pos)
  1703. {
  1704. unsigned int v = 0;
  1705. while (*pos < n && b[*pos] >= '0' && b[*pos] <= '9')
  1706. v = v * 10 + (unsigned int)(b[(*pos)++] - '0');
  1707. return v;
  1708. }
  1709. static void hist_merge_buf(const char *b, int n)
  1710. {
  1711. int pos = (int)s_len(HIST_MAGIC);
  1712. char url[HIST_URL_MAX], title[BR_TITLE_MAX];
  1713. if (n < pos || memcmp(b, HIST_MAGIC, (unsigned int)pos))
  1714. return;
  1715. while (pos < n) {
  1716. unsigned int visits, stamp, ul = 0;
  1717. int t0, t1;
  1718. visits = hist_parse_dec(b, n, &pos);
  1719. if (pos < n && b[pos] == ' ')
  1720. pos++;
  1721. stamp = hist_parse_dec(b, n, &pos);
  1722. if (pos < n && b[pos] == ' ')
  1723. pos++;
  1724. while (pos < n && b[pos] != '\t' && b[pos] != '\n') {
  1725. if (ul + 1 < sizeof(url))
  1726. url[ul++] = b[pos];
  1727. pos++;
  1728. }
  1729. url[ul] = '\0';
  1730. t0 = t1 = pos < n && b[pos] == '\t' ? pos + 1 : pos;
  1731. while (t1 < n && b[t1] != '\n')
  1732. t1++;
  1733. pos = t1 + 1;
  1734. hist_copy_title(title, b + t0, (unsigned int)(t1 - t0));
  1735. if (ul && ul + 1 < sizeof(url) && !hist_is_forgotten(url))
  1736. hist_put(url, title, visits, stamp);
  1737. }
  1738. }
  1739. static int hist_serialize(char *b, unsigned int cap)
  1740. {
  1741. unsigned int n = 0;
  1742. int i;
  1743. s_append(b, &n, HIST_MAGIC, cap);
  1744. for (i = 0; i < hist_n; i++) {
  1745. struct hist_ent *e = &hist_tab[i];
  1746. if (n + s_len(e->url) + s_len(e->title) + 26 >= cap)
  1747. break;
  1748. s_append_dec(b, &n, e->visits, cap);
  1749. b[n++] = ' ';
  1750. s_append_dec(b, &n, e->stamp, cap);
  1751. b[n++] = ' ';
  1752. s_append(b, &n, e->url, cap);
  1753. b[n++] = '\t';
  1754. s_append(b, &n, e->title, cap);
  1755. b[n++] = '\n';
  1756. }
  1757. return (int)n;
  1758. }
  1759. /* Merge /share/bhist, then write it back (and /data when asked). */
  1760. static void hist_sync(int to_data)
  1761. {
  1762. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1763. int n;
  1764. if (!b)
  1765. return;
  1766. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1767. (int)HIST_FILE_MAX);
  1768. if (n > 0)
  1769. hist_merge_buf(b, n);
  1770. n = hist_serialize(b, HIST_FILE_MAX);
  1771. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1772. hist_share_dirty = 0;
  1773. if (to_data) {
  1774. /* No /data mount: the write fails, and there is nothing to
  1775. * retry until the next visit. */
  1776. u_syscall3(SYS_WRITE_FILE, (int)DATA_HIST, (int)b, n);
  1777. hist_data_dirty = 0;
  1778. }
  1779. free(b);
  1780. }
  1781. /* Startup: the boot's shared copy, else the saved one from /data. */
  1782. static void hist_load(void)
  1783. {
  1784. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1785. int n;
  1786. if (!b)
  1787. return;
  1788. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1789. (int)HIST_FILE_MAX);
  1790. if (n <= 0) {
  1791. n = u_syscall3(SYS_READ_FILE, (int)DATA_HIST, (int)b,
  1792. (int)HIST_FILE_MAX);
  1793. if (n > 0)
  1794. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1795. }
  1796. if (n > 0)
  1797. hist_merge_buf(b, n);
  1798. free(b);
  1799. }
  1800. static void hist_visit(const char *url, const char *title)
  1801. {
  1802. struct hist_ent *e;
  1803. unsigned int i;
  1804. if (!url[0] || starts_with(url, "about:") ||
  1805. s_len(url) >= HIST_URL_MAX)
  1806. return;
  1807. for (i = 0; url[i]; i++)
  1808. if ((unsigned char)url[i] < 0x20)
  1809. return;
  1810. e = hist_put(url, title, 0, hist_next_stamp());
  1811. if (!e)
  1812. return;
  1813. e->visits++;
  1814. hist_data_dirty = 1;
  1815. hist_sync(0);
  1816. }
  1817. static void hist_forget(int i)
  1818. {
  1819. if (i < 0 || i >= hist_n)
  1820. return;
  1821. if (hist_nforgot < HIST_FORGET_MAX)
  1822. hist_forgot[hist_nforgot++] = hist_hash(hist_tab[i].url);
  1823. hist_n--;
  1824. for (; i < hist_n; i++)
  1825. hist_tab[i] = hist_tab[i + 1];
  1826. hist_data_dirty = 1;
  1827. hist_sync(0);
  1828. }
  1829. static void hist_tick(void)
  1830. {
  1831. if (hist_share_dirty || hist_data_dirty)
  1832. hist_sync(hist_data_dirty);
  1833. }
  1834. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1835. static void persist_tick(void)
  1836. {
  1837. unsigned int now = u_ticks_ms();
  1838. if ((int)(now - persist_due) < 0)
  1839. return;
  1840. persist_due = now + PERSIST_MS;
  1841. persist_cookies_flush();
  1842. if (persist_ndirty)
  1843. persist_store_flush();
  1844. hist_tick();
  1845. }
  1846. /* <link rel="modulepreload">: download the page's module graph on all
  1847. * helpers at once into the boot script cache, before any script runs. The
  1848. * engine's module loader is sequential (one blocking fetch per import), so
  1849. * without this a Vite app with a dozen chunks pays every round trip in a
  1850. * row. Failures are ignored; the loader fetches what is missing. */
  1851. #define MODULE_PRELOAD_MAX 24
  1852. static void prefetch_module_preloads(void)
  1853. {
  1854. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1855. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1856. unsigned int count = 0, next = 0, done = 0, i;
  1857. char err[64];
  1858. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1859. struct br_node *nd = &doc.nodes[i];
  1860. const char *rel, *href;
  1861. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1862. continue;
  1863. rel = br_rel(&doc, i);
  1864. href = br_href(&doc, i);
  1865. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1866. continue;
  1867. if (resolve_link(page_url, href, urls[count],
  1868. sizeof(urls[count])) != 0 ||
  1869. urls[count][0] == '/' || script_cache_has(urls[count]))
  1870. continue;
  1871. slot[count++] = 0;
  1872. }
  1873. if (!count)
  1874. return;
  1875. set_status("Loading modules...", 0, 0);
  1876. while (done < count) {
  1877. struct fetch_worker *w;
  1878. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1879. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1880. 0, 0, 0, err,
  1881. sizeof(err)) != 0) {
  1882. fetch_worker_release(w);
  1883. done++;
  1884. } else {
  1885. slot[next] = w;
  1886. }
  1887. next++;
  1888. }
  1889. worker_wait_ui();
  1890. if (cancel_fetch || pending_action) {
  1891. fetch_workers_cancel_busy();
  1892. return;
  1893. }
  1894. for (i = 0; i < next; i++) {
  1895. unsigned char *body;
  1896. int rv, tr = 0;
  1897. if (!slot[i])
  1898. continue;
  1899. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1900. if (rv == 0)
  1901. continue;
  1902. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1903. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1904. if (body) {
  1905. rv = fetch_worker_read_body(slot[i], body,
  1906. BR_SCRIPT_MAX, image_io_buf,
  1907. BR_PAGE_COMP_MAX, &tr, err,
  1908. sizeof(err));
  1909. if (rv > 0 && !tr)
  1910. script_cache_put(urls[i], body,
  1911. (unsigned int)rv);
  1912. free(body);
  1913. }
  1914. fetch_worker_release(slot[i]);
  1915. slot[i] = 0;
  1916. done++;
  1917. }
  1918. u_sleep_ms(10);
  1919. }
  1920. }
  1921. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1922. * submitted to helper workers ahead of time, but scripts still execute in
  1923. * document order. */
  1924. #define SCRIPT_INLINE 0
  1925. #define SCRIPT_LOCAL 1
  1926. #define SCRIPT_REMOTE 2
  1927. #define SCRIPT_ERROR 3
  1928. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1929. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1930. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1931. static void script_submit_window(unsigned int *next, char *err,
  1932. unsigned int errcap)
  1933. {
  1934. while (*next < doc.nscripts) {
  1935. struct fetch_worker *w;
  1936. if (script_kind[*next] != SCRIPT_REMOTE) {
  1937. (*next)++;
  1938. continue;
  1939. }
  1940. w = fetch_worker_alloc();
  1941. if (!w)
  1942. return;
  1943. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1944. 0, 0, 0, 0, err, errcap) != 0) {
  1945. fetch_worker_release(w);
  1946. script_kind[*next] = SCRIPT_ERROR;
  1947. (*next)++;
  1948. continue;
  1949. }
  1950. script_slot[*next] = w;
  1951. (*next)++;
  1952. }
  1953. }
  1954. /* Run the page's scripts in document order. External bodies are prefetched
  1955. * in parallel so downloading script N+1 overlaps executing script N; inline
  1956. * bodies are copied because the engine needs NUL-terminated text. */
  1957. static void run_page_scripts(void)
  1958. {
  1959. struct js_browser_host host;
  1960. unsigned int i, next = 0;
  1961. char err[64], ferr[64];
  1962. if (!doc.nscripts)
  1963. return;
  1964. host.status = js_host_status;
  1965. host.report = js_host_report;
  1966. host.navigate = js_host_navigate;
  1967. host.changed = js_host_changed;
  1968. host.rect = js_host_rect;
  1969. host.form_value = js_host_form_value;
  1970. host.form_checked = js_host_form_checked;
  1971. host.form_selected = js_host_form_selected;
  1972. host.form_set_value = js_host_form_set_value;
  1973. host.form_set_checked = js_host_form_set_checked;
  1974. host.form_set_selected = js_host_form_set_selected;
  1975. host.form_elements = js_host_form_elements;
  1976. host.form_submit = js_host_form_submit;
  1977. host.form_reset = js_host_form_reset;
  1978. host.click = js_host_click;
  1979. host.computed = js_host_computed;
  1980. host.http = js_host_http;
  1981. host.load_script = js_host_load_script;
  1982. host.storage = js_host_storage;
  1983. host.set_hash = js_host_set_hash;
  1984. host.page_url = page_url;
  1985. host.width = ui.w;
  1986. host.height = ui.h;
  1987. if (js_browser_start(&doc, &host) != 0) {
  1988. js_host_status("JavaScript: out of memory", 1);
  1989. return;
  1990. }
  1991. resize_sent_w = -1;
  1992. resize_pending = 0;
  1993. prefetch_module_preloads();
  1994. for (i = 0; i < doc.nscripts; i++) {
  1995. struct br_script *script = &doc.scripts[i];
  1996. const char *src_attr = script->src_off ?
  1997. doc.attrs + script->src_off : "";
  1998. script_slot[i] = 0;
  1999. if (!script->src_off) {
  2000. script_kind[i] = SCRIPT_INLINE;
  2001. continue;
  2002. }
  2003. if (!src_attr[0] ||
  2004. resolve_link(page_url, src_attr, script_urls[i],
  2005. sizeof(script_urls[i])) != 0) {
  2006. script_urls[i][0] = '\0';
  2007. script_kind[i] = SCRIPT_ERROR;
  2008. continue;
  2009. }
  2010. if (script_urls[i][0] == '/' ||
  2011. script_cache_has(script_urls[i]))
  2012. script_kind[i] = SCRIPT_LOCAL;
  2013. else
  2014. script_kind[i] = SCRIPT_REMOTE;
  2015. }
  2016. script_submit_window(&next, ferr, sizeof(ferr));
  2017. for (i = 0; i < doc.nscripts; i++) {
  2018. struct br_script *script = &doc.scripts[i];
  2019. /* document.currentScript for classic scripts (null for modules) */
  2020. js_browser_set_current_script(script->module ? 0 : script->node);
  2021. if (script_kind[i] == SCRIPT_INLINE) {
  2022. unsigned int off = script->off;
  2023. unsigned int len = script->len;
  2024. unsigned int k;
  2025. char *src = (char *)malloc(len + 1);
  2026. if (!src) {
  2027. js_host_status("JavaScript: out of memory", 1);
  2028. break;
  2029. }
  2030. for (k = 0; k < len; k++)
  2031. src[k] = doc.script_src[off + k];
  2032. src[len] = '\0';
  2033. if (script->module) {
  2034. /* A distinct module name per inline module
  2035. * (QuickJS registers modules by name); the
  2036. * fragment keeps relative imports resolving
  2037. * against the page. */
  2038. char mname[BR_URL_MAX + 16];
  2039. unsigned int mn = 0;
  2040. s_append(mname, &mn, page_url, sizeof(mname));
  2041. s_append(mname, &mn, "#module", sizeof(mname));
  2042. s_append_dec(mname, &mn, i, sizeof(mname));
  2043. js_browser_run_module(src, mname);
  2044. } else {
  2045. js_browser_run(src, page_url);
  2046. }
  2047. free(src);
  2048. } else if (script->src_off) {
  2049. const char *src_attr = doc.attrs + script->src_off;
  2050. if (script_kind[i] == SCRIPT_ERROR) {
  2051. script_error("Cannot load script", src_attr,
  2052. script_urls[i][0] ?
  2053. "network busy" :
  2054. "unsupported URL");
  2055. continue;
  2056. }
  2057. if (script_kind[i] == SCRIPT_LOCAL) {
  2058. unsigned char *data = 0;
  2059. unsigned int len = 0;
  2060. int rv;
  2061. set_status("Loading script...", 0, 0);
  2062. rv = fetch_script_text(script_urls[i], &data,
  2063. &len, err, sizeof(err));
  2064. if (rv == FETCH_ABORT)
  2065. break;
  2066. if (rv != 0) {
  2067. script_error("Cannot load script",
  2068. script_urls[i], err);
  2069. continue;
  2070. }
  2071. if (script->module)
  2072. js_browser_run_module(
  2073. (const char *)data,
  2074. script_urls[i]);
  2075. else
  2076. js_browser_run((const char *)data,
  2077. script_urls[i]);
  2078. free(data);
  2079. } else {
  2080. struct fetch_worker *w = script_slot[i];
  2081. unsigned char *body = 0;
  2082. int tr = 0, rv;
  2083. if (!w) {
  2084. w = fetch_worker_alloc();
  2085. if (!w)
  2086. continue;
  2087. if (fetch_worker_submit(w,
  2088. script_urls[i],
  2089. BR_SCRIPT_MAX,
  2090. 0, 0, 0, 0, err,
  2091. sizeof(err)) != 0) {
  2092. fetch_worker_release(w);
  2093. script_kind[i] = SCRIPT_ERROR;
  2094. if (i == next)
  2095. next++;
  2096. continue;
  2097. }
  2098. script_slot[i] = w;
  2099. if (i == next)
  2100. next++;
  2101. }
  2102. set_status("Loading script...", 0, 0);
  2103. rv = fetch_worker_wait(w, err, sizeof(err));
  2104. if (rv == FETCH_ABORT) {
  2105. fetch_workers_stop_all();
  2106. break;
  2107. }
  2108. /* The body gets its own buffer (scripts are up
  2109. * to 2 MB); image_io_buf takes the gzip
  2110. * stream. */
  2111. body = rv == 0 ? (unsigned char *)malloc(
  2112. BR_SCRIPT_MAX + 1) : 0;
  2113. if (body)
  2114. rv = fetch_worker_read_body(w, body,
  2115. BR_SCRIPT_MAX, image_io_buf,
  2116. BR_PAGE_COMP_MAX, &tr, err,
  2117. sizeof(err));
  2118. else {
  2119. if (rv == 0)
  2120. s_copy(err, "out of memory",
  2121. sizeof(err));
  2122. rv = -1;
  2123. }
  2124. fetch_worker_release(w);
  2125. script_slot[i] = 0;
  2126. script_submit_window(&next, ferr, sizeof(ferr));
  2127. if (rv <= 0)
  2128. script_error("Cannot load script",
  2129. script_urls[i], err);
  2130. else if (tr || (unsigned int)rv >=
  2131. BR_SCRIPT_MAX)
  2132. script_error("Cannot load script",
  2133. script_urls[i],
  2134. "script is too large");
  2135. else {
  2136. body[rv] = '\0';
  2137. script_cache_put(script_urls[i], body,
  2138. (unsigned int)rv);
  2139. if (script->module)
  2140. js_browser_run_module(
  2141. (const char *)body,
  2142. script_urls[i]);
  2143. else
  2144. js_browser_run(
  2145. (const char *)body,
  2146. script_urls[i]);
  2147. }
  2148. free(body);
  2149. }
  2150. }
  2151. if (pending_action)
  2152. break;
  2153. }
  2154. js_browser_set_current_script(0);
  2155. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  2156. * load_home() stop it before the next navigation. */
  2157. if (doc.scripts_truncated && !js_last_error)
  2158. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  2159. 1);
  2160. }
  2161. /* ---- images ---- */
  2162. /* data: images that failed to decode (key = data_img_key()), so a layout
  2163. * pass does not retry them on every frame. */
  2164. #define DATA_IMG_FAIL_MAX 32
  2165. static unsigned int data_img_fail[DATA_IMG_FAIL_MAX];
  2166. static int data_img_nfail;
  2167. static void image_reset(void)
  2168. {
  2169. int i;
  2170. for (i = 0; i < BR_MAX_IMAGES; i++) {
  2171. images[i].state = 0;
  2172. images[i].native_w = images[i].native_h = 0;
  2173. images[i].err[0] = '\0';
  2174. /* heap_clear() ran before us, so these pointers are stale: drop
  2175. * them without calling free(). */
  2176. memset(&images[i].disp, 0, sizeof(images[i].disp));
  2177. images[i].disp_pixels = 0;
  2178. images[i].disp_last = 0;
  2179. }
  2180. image_count = 0;
  2181. data_img_nfail = 0;
  2182. image_pixels = 0;
  2183. image_disp_pixels = 0;
  2184. image_disp_clock = 0;
  2185. memset(img_stat_log, 0, sizeof(img_stat_log));
  2186. img_stat_log_len = 0;
  2187. img_stat_start = 0;
  2188. img_stat_wall = 0;
  2189. img_stat_net = img_stat_open = img_stat_first = 0;
  2190. img_stat_io = img_stat_dec = img_stat_scale = 0;
  2191. img_stat_paint = img_stat_reflow = 0;
  2192. img_stat_bytes = 0;
  2193. img_stat_n = 0;
  2194. img_last_dec_ms = img_last_scale_ms = 0;
  2195. img_repaint_ms = 0;
  2196. img_repaint_pending = 0;
  2197. preload_active = 0;
  2198. preload_pending = 0;
  2199. preload_wait = 0;
  2200. preload_node = 0;
  2201. preload_loaded = 0;
  2202. }
  2203. /* Ask for a repaint, but not more often than BR_IMG_REPAINT_MS while images
  2204. * are arriving. The main loop draws once per dirty frame; without this a
  2205. * page of N images did N full layout+paint passes. */
  2206. static void image_repaint(void)
  2207. {
  2208. unsigned int now = u_ticks_ms();
  2209. if (!img_repaint_ms || (now - img_repaint_ms) >= BR_IMG_REPAINT_MS) {
  2210. img_repaint_ms = now;
  2211. img_repaint_pending = 0;
  2212. ngui_invalidate(&ui);
  2213. } else {
  2214. img_repaint_pending = 1;
  2215. }
  2216. }
  2217. static void image_disp_drop(struct br_image *bi)
  2218. {
  2219. if (bi->disp.px)
  2220. free(bi->disp.px);
  2221. if (bi->disp.alpha)
  2222. free(bi->disp.alpha);
  2223. memset(&bi->disp, 0, sizeof(bi->disp));
  2224. if (bi->disp_pixels) {
  2225. if (image_disp_pixels >= bi->disp_pixels)
  2226. image_disp_pixels -= bi->disp_pixels;
  2227. bi->disp_pixels = 0;
  2228. }
  2229. }
  2230. /* Free the least recently used display caches until need pixels fit. The
  2231. * source bitmap (bi->img) is never evicted; a later draw rescales it again. */
  2232. static int image_disp_room(unsigned int need)
  2233. {
  2234. while (image_disp_pixels + need > BR_IMG_DISP_BUDGET) {
  2235. unsigned int oldest = ~0u;
  2236. int i, victim = -1;
  2237. for (i = 0; i < image_count; i++) {
  2238. if (!images[i].disp.px)
  2239. continue;
  2240. if (images[i].disp_last < oldest) {
  2241. oldest = images[i].disp_last;
  2242. victim = i;
  2243. }
  2244. }
  2245. if (victim < 0)
  2246. return -1;
  2247. image_disp_drop(&images[victim]);
  2248. }
  2249. return 0;
  2250. }
  2251. /* Return a bitmap at exactly dw x dh, building it once from the capped source
  2252. * bitmap. Callers then draw with scale 1 and img_draw's copy fast path. */
  2253. static struct img_image *image_display_get(struct br_image *bi, int dw, int dh)
  2254. {
  2255. struct img_blit b;
  2256. unsigned int px;
  2257. if (!bi || bi->state != 1 || !bi->img.px || dw < 1 || dh < 1)
  2258. return 0;
  2259. if (dw == (int)bi->img.w && dh == (int)bi->img.h)
  2260. return &bi->img;
  2261. if (dw > 4096 || dh > 4096)
  2262. return &bi->img;
  2263. if (bi->disp.px && bi->disp.w == (unsigned int)dw &&
  2264. bi->disp.h == (unsigned int)dh) {
  2265. bi->disp_last = ++image_disp_clock;
  2266. return &bi->disp;
  2267. }
  2268. px = (unsigned int)dw * (unsigned int)dh;
  2269. if (px > BR_IMG_DISP_BUDGET || image_disp_room(px) != 0)
  2270. return &bi->img;
  2271. image_disp_drop(bi);
  2272. bi->disp.px = (unsigned short *)malloc(px * 2u);
  2273. if (!bi->disp.px)
  2274. return &bi->img;
  2275. if (bi->img.alpha) {
  2276. bi->disp.alpha = (unsigned char *)malloc(px);
  2277. if (!bi->disp.alpha) {
  2278. free(bi->disp.px);
  2279. bi->disp.px = 0;
  2280. return &bi->img;
  2281. }
  2282. }
  2283. bi->disp.w = (unsigned int)dw;
  2284. bi->disp.h = (unsigned int)dh;
  2285. bi->disp.format = bi->img.format;
  2286. bi->disp.flags = 0;
  2287. memset(&b, 0, sizeof(b));
  2288. b.dst = bi->disp.px;
  2289. b.dst_w = dw;
  2290. b.dst_h = dh;
  2291. b.clip_w = dw;
  2292. b.clip_h = dh;
  2293. b.scale = ((unsigned int)dw << 16) / bi->img.w;
  2294. b.dst_a = bi->disp.alpha;
  2295. b.flags = bi->disp.alpha ? IMG_BLIT_SAVE_ALPHA : 0;
  2296. img_draw(&bi->img, &b);
  2297. bi->disp_pixels = px;
  2298. image_disp_pixels += px;
  2299. bi->disp_last = ++image_disp_clock;
  2300. return &bi->disp;
  2301. }
  2302. /* Decode into the shared arena, then copy/scale the result into a display
  2303. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  2304. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  2305. * pixels. Transparent edges are composited over white. */
  2306. /* One decode scratch arena per page, reused across images. Allocating and
  2307. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  2308. * each small display bitmap landed in the hole the previous arena left, so
  2309. * the next arena no longer fit and the heap ratcheted up until an app
  2310. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  2311. * still released right after their one image. */
  2312. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  2313. static unsigned char *decode_arena_get(unsigned int bytes)
  2314. {
  2315. if (decode_arena && decode_arena_size >= bytes)
  2316. return decode_arena;
  2317. free(decode_arena);
  2318. decode_arena = (unsigned char *)malloc(bytes);
  2319. decode_arena_size = decode_arena ? bytes : 0;
  2320. return decode_arena;
  2321. }
  2322. static void decode_arena_put(void)
  2323. {
  2324. if (decode_arena_size > DECODE_ARENA_KEEP) {
  2325. free(decode_arena);
  2326. decode_arena = 0;
  2327. decode_arena_size = 0;
  2328. }
  2329. }
  2330. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  2331. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  2332. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  2333. static int svg_text_sniff(const unsigned char *d, unsigned int len);
  2334. static int svg_decode_image(const unsigned char *data, unsigned int len,
  2335. struct br_image *bi, int box_w, int box_h);
  2336. static int decode_image_data(const unsigned char *data, unsigned int len,
  2337. struct br_image *bi, int box_w, int box_h,
  2338. int fit_w, int fit_h)
  2339. {
  2340. struct img_info info;
  2341. struct img_options opt;
  2342. struct img_mem mem;
  2343. struct img_image decoded;
  2344. unsigned char *arena;
  2345. unsigned int est, bytes, i;
  2346. unsigned int t0;
  2347. unsigned short *px;
  2348. unsigned char *alpha = 0;
  2349. int dw, dh, r;
  2350. bi->url_hash = 0;
  2351. img_last_dec_ms = 0;
  2352. img_last_scale_ms = 0;
  2353. if (img_sniff(data, len, &info) != 0) {
  2354. if (svg_text_sniff(data, len))
  2355. return svg_decode_image(data, len, bi,
  2356. box_w > 0 && box_h > 0 ? box_w : fit_w,
  2357. box_w > 0 && box_h > 0 ? box_h : fit_h);
  2358. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  2359. return -1;
  2360. }
  2361. est = img_estimate(&info);
  2362. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  2363. s_copy(bi->err, "image too large", sizeof(bi->err));
  2364. return -1;
  2365. }
  2366. arena = decode_arena_get(est);
  2367. if (!arena) {
  2368. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2369. return -1;
  2370. }
  2371. img_mem_init(&mem, arena, est);
  2372. opt.max_pixels = BR_IMG_PIX_MAX;
  2373. opt.max_w = fit_w > 0 ? (unsigned int)fit_w :
  2374. (box_w > 0 ? (unsigned int)box_w : 0);
  2375. opt.max_h = fit_h > 0 ? (unsigned int)fit_h :
  2376. (box_h > 0 ? (unsigned int)box_h : 0);
  2377. t0 = u_ticks_ms();
  2378. r = img_decode(data, len, &opt, &mem, &decoded);
  2379. img_last_dec_ms = u_ticks_ms() - t0;
  2380. if (r != 0) {
  2381. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  2382. goto fail;
  2383. }
  2384. if (decoded.w == 0 || decoded.h == 0) {
  2385. s_copy(bi->err, "empty image", sizeof(bi->err));
  2386. goto fail;
  2387. }
  2388. /* The JPEG decoder may have reduced the IDCT output; the layout still
  2389. * needs the intrinsic dimensions from the header. */
  2390. bi->native_w = info.width ? (int)info.width : (int)decoded.w;
  2391. bi->native_h = info.height ? (int)info.height : (int)decoded.h;
  2392. dw = (int)decoded.w;
  2393. dh = (int)decoded.h;
  2394. /* An <img> with a CSS/attribute box only ever needs a bitmap that big:
  2395. * decoding 1200x800 and then box-filtering it to 1000x666, only to
  2396. * paint it at 400x267, doubled the decode-time scaling work. cap both
  2397. * axes with one scale so the aspect ratio is preserved. */
  2398. if (fit_w > 0 || fit_h > 0) {
  2399. unsigned int scw = fit_w > 0 ?
  2400. ((unsigned int)fit_w << 16) / decoded.w : ~0u;
  2401. unsigned int sch = fit_h > 0 ?
  2402. ((unsigned int)fit_h << 16) / decoded.h : ~0u;
  2403. unsigned int sc = scw < sch ? scw : sch;
  2404. if (sc < 0x10000u) {
  2405. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2406. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2407. if (dw < 1)
  2408. dw = 1;
  2409. if (dh < 1)
  2410. dh = 1;
  2411. }
  2412. }
  2413. if (box_w > 0 && box_h > 0) {
  2414. /* cover: scale so both box sides are filled, never up */
  2415. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  2416. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  2417. unsigned int sc = sw > sh ? sw : sh;
  2418. if (sc < 0x10000u) {
  2419. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2420. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2421. }
  2422. }
  2423. if (dw > BR_IMG_LAYOUT_W) {
  2424. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  2425. dw = BR_IMG_LAYOUT_W;
  2426. }
  2427. if (dh < 1)
  2428. dh = 1;
  2429. if (dw < 1)
  2430. dw = 1;
  2431. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  2432. BR_IMG_PIXEL_BUDGET) {
  2433. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  2434. goto fail;
  2435. }
  2436. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  2437. px = (unsigned short *)malloc(bytes);
  2438. if (!px) {
  2439. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2440. goto fail;
  2441. }
  2442. /* Keep the alpha plane for the scaled image so transparent logos and
  2443. * icons composite over the page instead of the browser's dark theme
  2444. * background. Very large alpha images stay flattened to bound the
  2445. * heap use. */
  2446. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  2447. alpha = (unsigned char *)malloc((unsigned int)dw *
  2448. (unsigned int)dh);
  2449. if (alpha) {
  2450. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2451. alpha[i] = 255;
  2452. }
  2453. }
  2454. /* With an alpha plane the colour under transparent pixels only shows
  2455. * through partially covered edge pixels of the downscale: use white,
  2456. * as documented above, not the dark browser theme (which left a dark
  2457. * fringe around scaled app icons). */
  2458. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2459. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  2460. {
  2461. struct img_blit b;
  2462. b.dst = px;
  2463. b.dst_w = dw;
  2464. b.dst_h = dh;
  2465. b.clip_x = 0;
  2466. b.clip_y = 0;
  2467. b.clip_w = dw;
  2468. b.clip_h = dh;
  2469. b.x = 0;
  2470. b.y = 0;
  2471. b.scale = ((unsigned int)dw << 16) / decoded.w;
  2472. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  2473. b.bg2 = b.bg;
  2474. b.dst_a = alpha;
  2475. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  2476. t0 = u_ticks_ms();
  2477. img_draw(&decoded, &b);
  2478. img_last_scale_ms = u_ticks_ms() - t0;
  2479. }
  2480. bi->img.format = decoded.format;
  2481. bi->img.w = (unsigned int)dw;
  2482. bi->img.h = (unsigned int)dh;
  2483. bi->img.px = px;
  2484. bi->img.alpha = alpha;
  2485. bi->img.flags = 0;
  2486. bi->state = 1;
  2487. image_pixels += (unsigned int)dw * (unsigned int)dh;
  2488. decode_arena_put();
  2489. return 0;
  2490. fail:
  2491. decode_arena_put();
  2492. return -1;
  2493. }
  2494. /* ---- URL / local path handling ---- */
  2495. static int is_http(const char *s)
  2496. {
  2497. return starts_with(s, "http://") || starts_with(s, "https://");
  2498. }
  2499. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  2500. static int normalize_abs(const char *in, char *out, unsigned int cap)
  2501. {
  2502. char seg[64];
  2503. unsigned int i = 0, o = 1;
  2504. int depth = 0;
  2505. int trailing;
  2506. if (!in || in[0] != '/' || cap < 2)
  2507. return -1;
  2508. trailing = 0;
  2509. {
  2510. unsigned int n = s_len(in);
  2511. if (n > 1 && in[n - 1] == '/')
  2512. trailing = 1;
  2513. }
  2514. out[0] = '/';
  2515. while (in[i]) {
  2516. unsigned int n = 0;
  2517. while (in[i] == '/')
  2518. i++;
  2519. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  2520. if (n + 1 < sizeof(seg))
  2521. seg[n++] = in[i];
  2522. i++;
  2523. }
  2524. seg[n] = '\0';
  2525. if (n == 0)
  2526. break;
  2527. if (s_eq(seg, "."))
  2528. continue;
  2529. if (s_eq(seg, "..")) {
  2530. if (depth > 0) {
  2531. while (o > 1 && out[o - 1] != '/')
  2532. o--;
  2533. if (o > 1)
  2534. o--;
  2535. depth--;
  2536. }
  2537. continue;
  2538. }
  2539. if (o > 1) {
  2540. if (o + 1 >= cap)
  2541. return -1;
  2542. out[o++] = '/';
  2543. }
  2544. if (o + n + 1 >= cap)
  2545. return -1;
  2546. {
  2547. unsigned int j;
  2548. for (j = 0; j < n; j++)
  2549. out[o++] = seg[j];
  2550. }
  2551. depth++;
  2552. }
  2553. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2554. if (o + 1 >= cap)
  2555. return -1;
  2556. out[o++] = '/';
  2557. }
  2558. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2559. if (in[i] == '?' || in[i] == '#') {
  2560. while (in[i]) {
  2561. if (o + 1 >= cap)
  2562. return -1;
  2563. out[o++] = in[i++];
  2564. }
  2565. }
  2566. out[o] = '\0';
  2567. return 0;
  2568. }
  2569. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2570. {
  2571. char joined[BR_URL_MAX];
  2572. if (!in || !in[0]) {
  2573. s_copy(out, cwd[0] ? cwd : "/", cap);
  2574. return;
  2575. }
  2576. if (in[0] == '/') {
  2577. if (normalize_abs(in, out, cap) != 0)
  2578. s_copy(out, in, cap);
  2579. return;
  2580. }
  2581. {
  2582. unsigned int n = 0;
  2583. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2584. s_append(joined, &n, "/", sizeof(joined));
  2585. s_append(joined, &n, in, sizeof(joined));
  2586. }
  2587. if (normalize_abs(joined, out, cap) != 0)
  2588. s_copy(out, joined, cap);
  2589. }
  2590. /* ---- canonical origin cache ---- *
  2591. *
  2592. * Sites commonly redirect http://host to https://host and then to
  2593. * https://www.host. Remember the final scheme/host of the last navigation so
  2594. * a bare domain typed again goes straight there instead of paying for two
  2595. * more connections and TLS handshakes. Only default-port requests are
  2596. * rewritten; explicit ports are left alone. */
  2597. #define ORIGIN_CACHE_MAX 8
  2598. #define ORIGIN_FILE "/share/borigins"
  2599. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2600. UHTTP_HOST_MAX + 2))
  2601. struct origin_cache_entry {
  2602. char host[UHTTP_HOST_MAX];
  2603. char origin[UHTTP_HOST_MAX + 16];
  2604. };
  2605. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2606. static int origin_count;
  2607. static char origin_buf[ORIGIN_BUF_SIZE];
  2608. static int default_port(const struct uhttp_url *u)
  2609. {
  2610. return u->secure ? u->port == 443 : u->port == 80;
  2611. }
  2612. static void url_origin(const struct uhttp_url *u, char *out,
  2613. unsigned int cap)
  2614. {
  2615. unsigned int n = 0;
  2616. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2617. s_append(out, &n, u->host, cap);
  2618. if (!default_port(u)) {
  2619. s_append(out, &n, ":", cap);
  2620. s_append_dec(out, &n, u->port, cap);
  2621. }
  2622. }
  2623. static void origin_cache_apply(char *url, unsigned int cap)
  2624. {
  2625. struct uhttp_url u;
  2626. char out[BR_URL_MAX];
  2627. unsigned int n = 0;
  2628. int i;
  2629. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2630. return;
  2631. for (i = 0; i < origin_count; i++) {
  2632. if (!s_eq(u.host, origins[i].host))
  2633. continue;
  2634. s_append(out, &n, origins[i].origin, sizeof(out));
  2635. s_append(out, &n, u.path, sizeof(out));
  2636. s_copy(url, out, cap);
  2637. return;
  2638. }
  2639. }
  2640. static void origin_cache_save(void)
  2641. {
  2642. unsigned int n = 0;
  2643. int i;
  2644. for (i = 0; i < origin_count; i++) {
  2645. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2646. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2647. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2648. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2649. }
  2650. if (n)
  2651. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2652. (int)origin_buf, (int)n);
  2653. }
  2654. static void origin_cache_load(void)
  2655. {
  2656. char *p;
  2657. int rn;
  2658. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2659. (int)(sizeof(origin_buf) - 1));
  2660. if (rn <= 0)
  2661. return;
  2662. origin_buf[rn] = '\0';
  2663. p = origin_buf;
  2664. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2665. char *line = p, *origin;
  2666. while (*p && *p != '\n')
  2667. p++;
  2668. if (*p)
  2669. *p++ = '\0';
  2670. if (!line[0])
  2671. continue;
  2672. origin = line;
  2673. while (*origin && *origin != ' ')
  2674. origin++;
  2675. if (!*origin)
  2676. continue;
  2677. *origin++ = '\0';
  2678. if (!line[0] || !is_http(origin))
  2679. continue;
  2680. {
  2681. struct uhttp_url uo;
  2682. if (uhttp_parse_url(origin, &uo) != 0 ||
  2683. !s_eq(uo.path, "/"))
  2684. continue;
  2685. }
  2686. s_copy(origins[origin_count].host, line,
  2687. sizeof(origins[origin_count].host));
  2688. s_copy(origins[origin_count].origin, origin,
  2689. sizeof(origins[origin_count].origin));
  2690. origin_count++;
  2691. }
  2692. }
  2693. static int host_is_www_of(const char *host, const char *base)
  2694. {
  2695. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2696. host[3] == '.' && s_eq(host + 4, base);
  2697. }
  2698. static void origin_cache_learn(const char *requested, const char *final)
  2699. {
  2700. struct uhttp_url from, to;
  2701. char origin[UHTTP_HOST_MAX + 16];
  2702. int i;
  2703. if (!is_http(requested) || !is_http(final))
  2704. return;
  2705. if (uhttp_parse_url(requested, &from) != 0 ||
  2706. uhttp_parse_url(final, &to) != 0)
  2707. return;
  2708. if (!default_port(&from))
  2709. return;
  2710. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2711. from.port == to.port)
  2712. return;
  2713. /* Only remember origin-level canonicalisation: the same path, and
  2714. * either the same host or its www./apex sibling. A path- or
  2715. * host-specific redirect (a shortener, a login page) must not poison
  2716. * every request to the typed host. */
  2717. if (!s_eq(from.path, to.path))
  2718. return;
  2719. if (!s_eq(from.host, to.host) &&
  2720. !host_is_www_of(to.host, from.host) &&
  2721. !host_is_www_of(from.host, to.host))
  2722. return;
  2723. url_origin(&to, origin, sizeof(origin));
  2724. for (i = 0; i < origin_count; i++) {
  2725. if (s_eq(origins[i].host, from.host)) {
  2726. if (!s_eq(origins[i].origin, origin)) {
  2727. s_copy(origins[i].origin, origin,
  2728. sizeof(origins[i].origin));
  2729. origin_cache_save();
  2730. }
  2731. return;
  2732. }
  2733. }
  2734. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2735. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2736. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2737. origin_cache_save();
  2738. }
  2739. static int path_dir(const char *path, char *out, unsigned int cap)
  2740. {
  2741. unsigned int i, last = 0;
  2742. for (i = 0; path[i]; i++)
  2743. if (path[i] == '/')
  2744. last = i;
  2745. if (last == 0) {
  2746. if (cap < 2)
  2747. return -1;
  2748. out[0] = '/';
  2749. out[1] = '\0';
  2750. return 0;
  2751. }
  2752. if (last + 1 >= cap)
  2753. return -1;
  2754. {
  2755. unsigned int j;
  2756. for (j = 0; j < last; j++)
  2757. out[j] = path[j];
  2758. out[last] = '\0';
  2759. }
  2760. return 0;
  2761. }
  2762. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2763. static int resolve_link(const char *base, const char *href, char *out,
  2764. unsigned int cap)
  2765. {
  2766. static char joined[BR_URL_MAX]; /* leaf: off the stack */
  2767. if (!href || !href[0] || href[0] == '#')
  2768. return -1;
  2769. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2770. starts_with(href, "data:") || starts_with(href, "tel:"))
  2771. return -1;
  2772. if (starts_with(href, "about:")) {
  2773. s_copy(out, href, cap);
  2774. return 0;
  2775. }
  2776. if (is_http(href)) {
  2777. s_copy(out, href, cap);
  2778. return 0;
  2779. }
  2780. if (starts_with(href, "//")) {
  2781. if (is_http(base)) {
  2782. unsigned int n = 0;
  2783. s_append(out, &n, starts_with(base, "https:") ?
  2784. "https:" : "http:", cap);
  2785. s_append(out, &n, href, cap);
  2786. return 0;
  2787. }
  2788. return -1;
  2789. }
  2790. if (is_http(base)) {
  2791. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2792. }
  2793. /* local page */
  2794. if (href[0] == '/') {
  2795. if (normalize_abs(href, out, cap) != 0)
  2796. return -1;
  2797. return 0;
  2798. }
  2799. {
  2800. static char dir[BR_URL_MAX];
  2801. unsigned int n = 0;
  2802. if (s_eq(base, "about:home"))
  2803. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2804. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2805. s_copy(dir, "/", sizeof(dir));
  2806. s_append(joined, &n, dir, sizeof(joined));
  2807. if (n == 0 || joined[n - 1] != '/')
  2808. s_append(joined, &n, "/", sizeof(joined));
  2809. s_append(joined, &n, href, sizeof(joined));
  2810. }
  2811. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2812. }
  2813. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2814. * rest instead of failing when a page or stylesheet is larger than the
  2815. * buffer. The stream is still walked to the end, so a normal page is
  2816. * verified; a truncated compressed input still returns whatever was decoded
  2817. * so far. */
  2818. struct trunc_buf {
  2819. unsigned char *dst;
  2820. unsigned int cap, pos;
  2821. int full;
  2822. };
  2823. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2824. {
  2825. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2826. if (len > m->cap - m->pos) {
  2827. unsigned int room = m->cap - m->pos;
  2828. if (room) {
  2829. unsigned int i;
  2830. for (i = 0; i < room; i++)
  2831. m->dst[m->pos + i] = data[i];
  2832. m->pos += room;
  2833. }
  2834. m->full = 1;
  2835. return 0;
  2836. }
  2837. {
  2838. unsigned int i;
  2839. for (i = 0; i < len; i++)
  2840. m->dst[m->pos + i] = data[i];
  2841. }
  2842. m->pos += len;
  2843. return 0;
  2844. }
  2845. static void worker_wait_ui(void);
  2846. static void inflate_ui_pump(void *ctx)
  2847. {
  2848. static unsigned int last;
  2849. unsigned int now = u_ticks_ms();
  2850. (void)ctx;
  2851. if ((int)(now - last) >= 50) {
  2852. last = now;
  2853. worker_wait_ui();
  2854. }
  2855. }
  2856. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2857. unsigned char *dst, unsigned int cap,
  2858. unsigned int *outlen, int gzip, int *truncated)
  2859. {
  2860. struct inflate_src in;
  2861. struct inflate_sink sink;
  2862. struct trunc_buf m;
  2863. unsigned int got = 0;
  2864. int r;
  2865. in.p = src;
  2866. in.len = len;
  2867. in.more = 0;
  2868. in.ctx = 0;
  2869. m.dst = dst;
  2870. m.cap = cap;
  2871. m.pos = 0;
  2872. m.full = 0;
  2873. sink.write = trunc_write;
  2874. sink.ctx = &m;
  2875. inflate_init(&image_inflate_ws, &in, &sink);
  2876. image_inflate_ws.progress = inflate_ui_pump;
  2877. image_inflate_ws.progress_ctx = 0;
  2878. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2879. inflate_zlib(&image_inflate_ws, &got);
  2880. *outlen = m.pos;
  2881. *truncated = m.full || r != 0;
  2882. if (r != 0 && m.pos == 0)
  2883. return -1;
  2884. return 0;
  2885. }
  2886. /* ---- headless fetch workers ------------------------------------------ *
  2887. *
  2888. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2889. * writes the raw response, a small metadata file and a done marker under
  2890. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2891. * or a multi-megabyte body never freezes the UI and images download in
  2892. * parallel.
  2893. */
  2894. struct fetch_meta {
  2895. int status;
  2896. int error;
  2897. int trunc;
  2898. unsigned int len;
  2899. unsigned int open_ms;
  2900. unsigned int first_ms;
  2901. unsigned int total_ms;
  2902. /* Optional decoded bitmap produced by the helper (image jobs). */
  2903. unsigned int dw, dh, nw, nh;
  2904. unsigned int alpha;
  2905. unsigned int px_len;
  2906. unsigned int dec_ms;
  2907. int dec_err;
  2908. char encoding[16];
  2909. char ctype[64];
  2910. char final[BR_URL_MAX];
  2911. };
  2912. static void draw(unsigned int *action);
  2913. static void handle_keys(unsigned int *action);
  2914. static void handle_page_click(unsigned int *action);
  2915. #define FETCH_WORKERS 4
  2916. #define FETCH_PATH_MAX 32
  2917. /* One long-lived curl __serve helper per worker. Each worker has its own
  2918. * request/body/meta/done files under /share so several downloads can be in
  2919. * flight at once; the keep-alive connection stays in the helper process, so
  2920. * tls.c's per-process state remains valid. */
  2921. struct fetch_worker {
  2922. int pid;
  2923. int slot;
  2924. int busy;
  2925. int ready;
  2926. int image_job;
  2927. unsigned int seq;
  2928. unsigned int deadline;
  2929. int retried;
  2930. unsigned int dec_w, dec_h;
  2931. int dec_retried;
  2932. char req[FETCH_PATH_MAX];
  2933. char body[FETCH_PATH_MAX];
  2934. char meta[FETCH_PATH_MAX];
  2935. char done[FETCH_PATH_MAX];
  2936. char post[FETCH_PATH_MAX];
  2937. char px[FETCH_PATH_MAX];
  2938. /* Optional preload job attached to this worker. */
  2939. unsigned int node;
  2940. int bg;
  2941. char url[BR_URL_MAX];
  2942. struct fetch_meta m;
  2943. };
  2944. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2945. static int fetch_tty = -2;
  2946. static void fetch_tty_drain(void);
  2947. static unsigned int fetch_session;
  2948. static unsigned int fetch_seq;
  2949. static struct fetch_meta fetch_meta;
  2950. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2951. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2952. static int fetch_last_error;
  2953. static unsigned int meta_uint(char **pp)
  2954. {
  2955. char *p = *pp;
  2956. unsigned int v = 0;
  2957. while (*p >= '0' && *p <= '9') {
  2958. v = v * 10 + (unsigned int)(*p - '0');
  2959. p++;
  2960. }
  2961. while (*p && *p != '\n')
  2962. p++;
  2963. if (*p == '\n')
  2964. p++;
  2965. *pp = p;
  2966. return v;
  2967. }
  2968. static void meta_str(char **pp, char *out, unsigned int cap)
  2969. {
  2970. char *p = *pp;
  2971. unsigned int n = 0;
  2972. while (*p && *p != '\n' && n + 1 < cap)
  2973. out[n++] = *p++;
  2974. out[n] = '\0';
  2975. while (*p && *p != '\n')
  2976. p++;
  2977. if (*p == '\n')
  2978. p++;
  2979. *pp = p;
  2980. }
  2981. static void worker_wait_ui(void)
  2982. {
  2983. unsigned int action = 0;
  2984. if (!ngui_begin(&ui))
  2985. return;
  2986. draw(&action);
  2987. handle_keys(&action);
  2988. handle_page_click(&action);
  2989. if (action & ACT_WAIT_NAV) {
  2990. pending_action |= action & ACT_WAIT_NAV;
  2991. if ((action & ACT_NAV) && click_url[0])
  2992. s_copy(pending_url, click_url, sizeof(pending_url));
  2993. click_url[0] = '\0';
  2994. cancel_fetch = 1;
  2995. }
  2996. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  2997. ngui_invalidate(&ui);
  2998. ngui_end(&ui);
  2999. }
  3000. static void fetch_path(char *out, unsigned int cap, const char *kind,
  3001. unsigned int session, int slot)
  3002. {
  3003. unsigned int n = 0;
  3004. s_append(out, &n, "/share/bf", cap);
  3005. s_append_dec(out, &n, session, cap);
  3006. s_append(out, &n, "_", cap);
  3007. s_append_dec(out, &n, (unsigned int)slot, cap);
  3008. s_append(out, &n, kind, cap);
  3009. }
  3010. static void fetch_pool_init(void)
  3011. {
  3012. static int ready;
  3013. int i;
  3014. if (ready)
  3015. return;
  3016. ready = 1;
  3017. fetch_session = ((unsigned int)u_getpid() << 16) ^
  3018. (u_ticks_ms() & 0xFFFFu);
  3019. if (!fetch_session)
  3020. fetch_session = 1;
  3021. for (i = 0; i < FETCH_WORKERS; i++) {
  3022. struct fetch_worker *w = &fetch_workers[i];
  3023. w->pid = -1;
  3024. w->slot = i;
  3025. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  3026. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  3027. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  3028. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  3029. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  3030. fetch_path(w->px, sizeof(w->px), "px", fetch_session, i);
  3031. }
  3032. }
  3033. static void fetch_worker_stop(struct fetch_worker *w)
  3034. {
  3035. int i;
  3036. /* An abandoned image job leaves its node loadable again. */
  3037. if (w->busy && w->image_job && w->node < doc.nnode) {
  3038. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  3039. doc.nodes[w->node].bg_img_index = -1;
  3040. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  3041. doc.nodes[w->node].img_index = -1;
  3042. }
  3043. if (w->pid > 0) {
  3044. u_kill((unsigned int)w->pid);
  3045. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  3046. u_sleep_ms(5);
  3047. /* Let the reaper close the socket before we reuse the slot. */
  3048. u_sleep_ms(10);
  3049. }
  3050. w->pid = -1;
  3051. w->busy = 0;
  3052. w->ready = 0;
  3053. w->image_job = 0;
  3054. if (w->req[0]) {
  3055. u_syscall1(SYS_UNLINK, (int)w->done);
  3056. u_syscall1(SYS_UNLINK, (int)w->meta);
  3057. u_syscall1(SYS_UNLINK, (int)w->body);
  3058. u_syscall1(SYS_UNLINK, (int)w->post);
  3059. u_syscall1(SYS_UNLINK, (int)w->req);
  3060. }
  3061. }
  3062. static void fetch_workers_stop_all(void)
  3063. {
  3064. int i;
  3065. for (i = 0; i < FETCH_WORKERS; i++)
  3066. fetch_worker_stop(&fetch_workers[i]);
  3067. }
  3068. /* Abandon the transfers of the current page but keep idle helpers and their
  3069. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  3070. * because its response would otherwise land in a reused /share slot. */
  3071. static void fetch_workers_cancel_busy(void)
  3072. {
  3073. int i;
  3074. for (i = 0; i < FETCH_WORKERS; i++)
  3075. if (fetch_workers[i].busy)
  3076. fetch_worker_stop(&fetch_workers[i]);
  3077. }
  3078. static void fetch_workers_prepare_nav(const char *url)
  3079. {
  3080. int i;
  3081. (void)url;
  3082. for (i = 0; i < FETCH_WORKERS; i++) {
  3083. struct fetch_worker *w = &fetch_workers[i];
  3084. if (w->pid <= 0)
  3085. continue;
  3086. /* Only an in-flight transfer must be aborted. Idle helpers
  3087. * stay warm across origins: there are just FETCH_WORKERS of
  3088. * them, and uhttp_open drops the old connection when the
  3089. * next job is for another host. Killing and respawning all
  3090. * four on every navigation churned processes and sockets
  3091. * while images were still loading. */
  3092. if (w->busy)
  3093. fetch_worker_stop(w);
  3094. }
  3095. }
  3096. /* The browser is no longer the active window and no fetch is running: give
  3097. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  3098. static void fetch_workers_stop_if_unfocused(void)
  3099. {
  3100. int i;
  3101. fetch_tty_drain();
  3102. if (ui.focused || page_loading || preload_active)
  3103. return;
  3104. for (i = 0; i < FETCH_WORKERS; i++)
  3105. if (fetch_workers[i].pid > 0) {
  3106. fetch_workers_stop_all();
  3107. return;
  3108. }
  3109. }
  3110. /* The helpers (and this process, since u_tty_create() rebinds our own
  3111. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  3112. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  3113. * a dozen TLS connections every helper hung in its next log line, so the
  3114. * following cross-origin navigation sat at "Loading..." until it timed out.
  3115. * Drain and discard it from every wait/poll loop. */
  3116. static void fetch_tty_drain(void)
  3117. {
  3118. char sink[512];
  3119. int i;
  3120. if (fetch_tty <= 0)
  3121. return;
  3122. for (i = 0; i < 16; i++)
  3123. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  3124. break;
  3125. }
  3126. static int fetch_worker_start(struct fetch_worker *w, char *err,
  3127. unsigned int errcap)
  3128. {
  3129. char arg[40];
  3130. unsigned int n = 0;
  3131. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  3132. return 0;
  3133. w->pid = -1;
  3134. fetch_pool_init();
  3135. if (fetch_tty == -2) {
  3136. int t = u_tty_create();
  3137. fetch_tty = t > 0 ? t : 0;
  3138. }
  3139. s_append(arg, &n, "__serve ", sizeof(arg));
  3140. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  3141. s_append(arg, &n, " ", sizeof(arg));
  3142. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  3143. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  3144. if (w->pid <= 0) {
  3145. w->pid = -1;
  3146. s_copy(err, "cannot start network helper", errcap);
  3147. return -1;
  3148. }
  3149. return 0;
  3150. }
  3151. static struct fetch_worker *fetch_worker_alloc(void)
  3152. {
  3153. int i;
  3154. fetch_pool_init();
  3155. for (i = 0; i < FETCH_WORKERS; i++)
  3156. if (!fetch_workers[i].busy)
  3157. return &fetch_workers[i];
  3158. return 0;
  3159. }
  3160. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3161. unsigned int cap, const char *method,
  3162. const char *ctype, const char *post,
  3163. unsigned int post_len, unsigned int node,
  3164. int bg, unsigned int dec_w,
  3165. unsigned int dec_h, char *err,
  3166. unsigned int errcap);
  3167. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  3168. unsigned int cap, const char *post,
  3169. unsigned int post_len, unsigned int node,
  3170. int bg, char *err, unsigned int errcap)
  3171. {
  3172. /* A body pointer with no bytes is still a POST: the classic request
  3173. * line would turn it into a GET. */
  3174. if (post && !post_len)
  3175. return fetch_worker_submit_req(w, url, cap, "POST",
  3176. "application/x-www-form-urlencoded", post, 0, node,
  3177. bg, 0, 0, err, errcap);
  3178. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  3179. node, bg, 0, 0, err, errcap);
  3180. }
  3181. /* Image job: ask the helper to decode at these display bounds as well. */
  3182. static int fetch_worker_submit_image(struct fetch_worker *w, const char *url,
  3183. unsigned int cap, unsigned int node,
  3184. int bg, unsigned int dec_w,
  3185. unsigned int dec_h, char *err,
  3186. unsigned int errcap)
  3187. {
  3188. return fetch_worker_submit_req(w, url, cap, 0, 0, 0, 0, node, bg,
  3189. dec_w, dec_h, err, errcap);
  3190. }
  3191. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  3192. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  3193. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3194. unsigned int cap, const char *method,
  3195. const char *ctype, const char *post,
  3196. unsigned int post_len, unsigned int node,
  3197. int bg, unsigned int dec_w,
  3198. unsigned int dec_h, char *err,
  3199. unsigned int errcap)
  3200. {
  3201. static char req[BR_URL_MAX + 256];
  3202. unsigned int n = 0;
  3203. fetch_seq++;
  3204. if (!fetch_seq)
  3205. fetch_seq = 1;
  3206. w->seq = fetch_seq;
  3207. w->ready = 0;
  3208. w->image_job = 0;
  3209. w->retried = 0;
  3210. w->m.error = 0;
  3211. w->node = node;
  3212. w->bg = bg;
  3213. w->dec_w = dec_w;
  3214. w->dec_h = dec_h;
  3215. w->dec_retried = 0;
  3216. s_copy(w->url, url, sizeof(w->url));
  3217. s_append_dec(req, &n, w->seq, sizeof(req));
  3218. s_append(req, &n, " ", sizeof(req));
  3219. s_append_dec(req, &n, cap, sizeof(req));
  3220. s_append(req, &n, " ", sizeof(req));
  3221. if (dec_w || dec_h) {
  3222. s_append(req, &n, "D ", sizeof(req));
  3223. s_append_dec(req, &n, dec_w, sizeof(req));
  3224. s_append(req, &n, " ", sizeof(req));
  3225. s_append_dec(req, &n, dec_h, sizeof(req));
  3226. s_append(req, &n, " ", sizeof(req));
  3227. } else if (method) {
  3228. unsigned int k;
  3229. s_append(req, &n, "X ", sizeof(req));
  3230. s_append(req, &n, method, sizeof(req));
  3231. s_append(req, &n, " ", sizeof(req));
  3232. s_append_dec(req, &n, post_len, sizeof(req));
  3233. s_append(req, &n, " ", sizeof(req));
  3234. if (!ctype || !ctype[0])
  3235. s_append(req, &n, "-", sizeof(req));
  3236. /* One token on the request line: drop the spaces
  3237. * ("application/json; charset=utf-8" stays valid). */
  3238. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  3239. if (ctype[k] != ' ')
  3240. req[n++] = ctype[k];
  3241. req[n] = '\0';
  3242. s_append(req, &n, " ", sizeof(req));
  3243. } else if (post_len) {
  3244. s_append(req, &n, "POST ", sizeof(req));
  3245. s_append_dec(req, &n, post_len, sizeof(req));
  3246. s_append(req, &n, " ", sizeof(req));
  3247. }
  3248. s_append(req, &n, url, sizeof(req));
  3249. s_append(req, &n, "\n", sizeof(req));
  3250. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  3251. (int)post, (int)post_len) < 0) {
  3252. s_copy(err, "cannot queue form body", errcap);
  3253. return -1;
  3254. }
  3255. u_syscall1(SYS_UNLINK, (int)w->done);
  3256. u_syscall1(SYS_UNLINK, (int)w->meta);
  3257. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  3258. s_copy(err, "cannot queue network request", errcap);
  3259. return -1;
  3260. }
  3261. if (fetch_worker_start(w, err, errcap) != 0)
  3262. return -1;
  3263. w->busy = 1;
  3264. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  3265. return 0;
  3266. }
  3267. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  3268. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  3269. unsigned int errcap)
  3270. {
  3271. static char meta[BR_URL_MAX + 1024];
  3272. char *p;
  3273. int rn, mseq;
  3274. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  3275. (int)(sizeof(meta) - 1));
  3276. if (rn <= 0) {
  3277. s_copy(err, "network helper failed", errcap);
  3278. return -1;
  3279. }
  3280. meta[rn] = '\0';
  3281. p = meta;
  3282. mseq = (int)meta_uint(&p);
  3283. if (mseq != (int)w->seq) {
  3284. s_copy(err, "stale network response", errcap);
  3285. return -1;
  3286. }
  3287. w->m.status = (int)meta_uint(&p);
  3288. w->m.error = (int)meta_uint(&p);
  3289. w->m.trunc = (int)meta_uint(&p);
  3290. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  3291. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  3292. meta_str(&p, w->m.final, sizeof(w->m.final));
  3293. w->m.len = meta_uint(&p);
  3294. w->m.open_ms = 0;
  3295. w->m.first_ms = 0;
  3296. w->m.total_ms = 0;
  3297. if (*p) {
  3298. w->m.open_ms = meta_uint(&p);
  3299. w->m.first_ms = meta_uint(&p);
  3300. w->m.total_ms = meta_uint(&p);
  3301. }
  3302. w->m.dw = w->m.dh = w->m.nw = w->m.nh = 0;
  3303. w->m.alpha = w->m.px_len = w->m.dec_ms = 0;
  3304. w->m.dec_err = 0;
  3305. if (*p) {
  3306. w->m.dw = meta_uint(&p);
  3307. w->m.dh = meta_uint(&p);
  3308. w->m.nw = meta_uint(&p);
  3309. w->m.nh = meta_uint(&p);
  3310. w->m.alpha = meta_uint(&p);
  3311. w->m.px_len = meta_uint(&p);
  3312. w->m.dec_err = (int)meta_uint(&p);
  3313. w->m.dec_ms = meta_uint(&p);
  3314. }
  3315. if (w->m.error) {
  3316. s_copy(err, uhttp_error_string(w->m.error), errcap);
  3317. return -1;
  3318. }
  3319. w->ready = 1;
  3320. return 0;
  3321. }
  3322. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  3323. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  3324. unsigned int errcap)
  3325. {
  3326. static char done[24];
  3327. char *p;
  3328. int rn, mseq;
  3329. fetch_tty_drain();
  3330. if (!w->busy)
  3331. return -1;
  3332. if (w->ready)
  3333. return 1;
  3334. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  3335. (int)(sizeof(done) - 1));
  3336. if (rn > 0) {
  3337. done[rn] = '\0';
  3338. p = done;
  3339. mseq = (int)meta_uint(&p);
  3340. if (mseq == (int)w->seq) {
  3341. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  3342. fetch_worker_stop(w);
  3343. return -1;
  3344. }
  3345. return 1;
  3346. }
  3347. }
  3348. if (!u_alive((unsigned int)w->pid)) {
  3349. w->pid = -1;
  3350. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  3351. w->retried = 1;
  3352. return 0;
  3353. }
  3354. s_copy(err, "network helper stopped", errcap);
  3355. fetch_worker_stop(w);
  3356. return -1;
  3357. }
  3358. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  3359. s_copy(err, "network request timed out", errcap);
  3360. fetch_worker_stop(w);
  3361. return -1;
  3362. }
  3363. return 0;
  3364. }
  3365. /* Copy the completed body, inflating it if the server ignored our identity
  3366. * request. Mirrors the old fetch_remote body path. */
  3367. static int fetch_worker_read_body(struct fetch_worker *w,
  3368. unsigned char *plain,
  3369. unsigned int plaincap,
  3370. unsigned char *comp,
  3371. unsigned int compcap,
  3372. int *truncated, char *err,
  3373. unsigned int errcap)
  3374. {
  3375. int rv, zr, was_trunc;
  3376. if (contains_ci(w->m.encoding, "gzip") ||
  3377. contains_ci(w->m.encoding, "deflate")) {
  3378. unsigned int comp_len = 0, plen = 0;
  3379. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  3380. (int)compcap);
  3381. if (rv < 0) {
  3382. s_copy(err, "empty response", errcap);
  3383. return -1;
  3384. }
  3385. comp_len = (unsigned int)rv;
  3386. if (comp_len < w->m.len) {
  3387. s_copy(err, "compressed response is too large", errcap);
  3388. return -1;
  3389. }
  3390. if (contains_ci(w->m.encoding, "deflate"))
  3391. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3392. &plen, 0, &was_trunc);
  3393. else
  3394. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3395. &plen, 1, &was_trunc);
  3396. if (zr != 0) {
  3397. s_copy(err, "compressed response is corrupt", errcap);
  3398. return -1;
  3399. }
  3400. *truncated = w->m.trunc || was_trunc;
  3401. return (int)plen;
  3402. }
  3403. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  3404. if (rv < 0) {
  3405. s_copy(err, "empty response", errcap);
  3406. return -1;
  3407. }
  3408. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  3409. return rv;
  3410. }
  3411. static void fetch_worker_release(struct fetch_worker *w)
  3412. {
  3413. u_syscall1(SYS_UNLINK, (int)w->done);
  3414. u_syscall1(SYS_UNLINK, (int)w->meta);
  3415. u_syscall1(SYS_UNLINK, (int)w->body);
  3416. u_syscall1(SYS_UNLINK, (int)w->post);
  3417. u_syscall1(SYS_UNLINK, (int)w->px);
  3418. u_syscall1(SYS_UNLINK, (int)w->req);
  3419. w->busy = 0;
  3420. w->ready = 0;
  3421. w->image_job = 0;
  3422. w->dec_w = 0;
  3423. w->dec_h = 0;
  3424. w->dec_retried = 0;
  3425. }
  3426. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  3427. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  3428. unsigned int errcap)
  3429. {
  3430. for (;;) {
  3431. int rv;
  3432. if (!fetch_wait_passive)
  3433. worker_wait_ui();
  3434. if (cancel_fetch || pending_action) {
  3435. fetch_workers_cancel_busy();
  3436. return FETCH_ABORT;
  3437. }
  3438. rv = fetch_worker_poll(w, err, errcap);
  3439. if (rv != 0)
  3440. return rv == 1 ? 0 : -1;
  3441. u_sleep_ms(10);
  3442. }
  3443. }
  3444. static int fetch_remote(const char *url, unsigned int cap,
  3445. const char *post, unsigned int post_len,
  3446. unsigned char *plain, unsigned int plaincap,
  3447. unsigned char *comp, unsigned int compcap,
  3448. struct fetch_meta *m, int *truncated,
  3449. char *err, unsigned int errcap)
  3450. {
  3451. struct fetch_worker *w = fetch_worker_alloc();
  3452. int rv;
  3453. fetch_last_error = 0;
  3454. if (!w) {
  3455. s_copy(err, "network busy", errcap);
  3456. return -1;
  3457. }
  3458. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  3459. err, errcap) != 0) {
  3460. fetch_worker_release(w);
  3461. return -1;
  3462. }
  3463. rv = fetch_worker_wait(w, err, errcap);
  3464. if (rv == FETCH_ABORT) {
  3465. fetch_worker_release(w);
  3466. return FETCH_ABORT;
  3467. }
  3468. if (rv != 0) {
  3469. fetch_last_error = w->m.error;
  3470. fetch_worker_release(w);
  3471. return -1;
  3472. }
  3473. *m = w->m;
  3474. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  3475. truncated, err, errcap);
  3476. fetch_worker_release(w);
  3477. if (rv >= 0 && (cancel_fetch || pending_action))
  3478. return FETCH_ABORT;
  3479. return rv;
  3480. }
  3481. static int fetch_worker_status(const struct fetch_worker *w)
  3482. {
  3483. return w->m.status;
  3484. }
  3485. /* fetch()/XHR through a helper: one request, the status and body come back
  3486. * whatever the HTTP status (a 401 is an answer, not a network error). */
  3487. static int js_worker_http(const char *method, const char *url,
  3488. const char *ctype, const char *body,
  3489. unsigned int body_len, struct js_http_resp *r,
  3490. char *err, int errcap)
  3491. {
  3492. struct fetch_worker *w = fetch_worker_alloc();
  3493. unsigned char *plain;
  3494. int rv, tr = 0;
  3495. if (!w) {
  3496. s_copy(err, "network busy", (unsigned int)errcap);
  3497. return -1;
  3498. }
  3499. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  3500. body_len, 0, 0, 0, 0, err,
  3501. (unsigned int)errcap) != 0) {
  3502. fetch_worker_release(w);
  3503. return -1;
  3504. }
  3505. fetch_wait_passive++;
  3506. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  3507. fetch_wait_passive--;
  3508. if (rv != 0) {
  3509. if (rv == FETCH_ABORT)
  3510. s_copy(err, "page is navigating", (unsigned int)errcap);
  3511. fetch_worker_release(w);
  3512. return -1;
  3513. }
  3514. r->status = w->m.status;
  3515. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  3516. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  3517. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  3518. if (!plain) {
  3519. fetch_worker_release(w);
  3520. s_copy(err, "out of memory", (unsigned int)errcap);
  3521. return -1;
  3522. }
  3523. if (w->m.len == 0) {
  3524. rv = 0; /* 204, an empty 200: no body file */
  3525. } else {
  3526. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  3527. image_io_buf, BR_PAGE_COMP_MAX,
  3528. &tr, err, (unsigned int)errcap);
  3529. }
  3530. fetch_worker_release(w);
  3531. if (rv < 0) {
  3532. free(plain);
  3533. return -1;
  3534. }
  3535. plain[rv] = '\0';
  3536. r->body = (char *)plain;
  3537. r->len = (unsigned int)rv;
  3538. return 0;
  3539. }
  3540. /* ---- HTTP / file fetch ---- */
  3541. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  3542. unsigned int *outlen, int *is_local, char *ctype,
  3543. unsigned int ctcap, char *final, unsigned int finalcap,
  3544. char *err, unsigned int errcap, int *truncated,
  3545. const char *post, unsigned int post_len)
  3546. {
  3547. unsigned char *buf;
  3548. unsigned int len;
  3549. int tr = 0;
  3550. int rv;
  3551. *out = 0;
  3552. *outlen = 0;
  3553. *truncated = 0;
  3554. if (final && finalcap)
  3555. final[0] = '\0';
  3556. if (ctype && ctcap)
  3557. ctype[0] = '\0';
  3558. if (url[0] == '/') {
  3559. char pathbuf[BR_URL_MAX];
  3560. const char *open_url = url;
  3561. unsigned int i = 0;
  3562. /* A local form GET keeps ?query in the address bar but the
  3563. * file lookup uses the path alone, like a real browser. */
  3564. while (url[i] && url[i] != '?' && url[i] != '#')
  3565. i++;
  3566. if (url[i]) {
  3567. s_copy(pathbuf, url, i + 1);
  3568. open_url = pathbuf;
  3569. }
  3570. buf = (unsigned char *)malloc(cap);
  3571. if (!buf) {
  3572. s_copy(err, "out of memory", errcap);
  3573. return -1;
  3574. }
  3575. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  3576. if (rv < 0) {
  3577. free(buf);
  3578. s_copy(err, "file not found", errcap);
  3579. return -1;
  3580. }
  3581. *out = buf;
  3582. *outlen = (unsigned int)rv;
  3583. *is_local = 1;
  3584. if (ctype)
  3585. s_copy(ctype, "text/html", ctcap);
  3586. if (final)
  3587. s_copy(final, url, finalcap);
  3588. if ((unsigned int)rv == cap)
  3589. *truncated = 1;
  3590. return 0;
  3591. }
  3592. buf = (unsigned char *)malloc(cap);
  3593. if (!buf) {
  3594. s_copy(err, "out of memory", errcap);
  3595. return -1;
  3596. }
  3597. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3598. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3599. if (rv == FETCH_ABORT) {
  3600. free(buf);
  3601. return FETCH_ABORT;
  3602. }
  3603. if (rv < 0) {
  3604. free(buf);
  3605. return -1;
  3606. }
  3607. len = (unsigned int)rv;
  3608. if (len == 0) {
  3609. free(buf);
  3610. s_copy(err, "empty response", errcap);
  3611. return -1;
  3612. }
  3613. if (ctype)
  3614. s_copy(ctype, fetch_meta.ctype, ctcap);
  3615. if (final && fetch_meta.final[0])
  3616. s_copy(final, fetch_meta.final, finalcap);
  3617. *is_local = 0;
  3618. *out = buf;
  3619. *outlen = len;
  3620. *truncated = tr;
  3621. return 0;
  3622. }
  3623. /* Load every @font-face the parser registered. Local files go through
  3624. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  3625. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  3626. * to the built-in regular/bold/italic/mono set. */
  3627. static void load_font_faces(void)
  3628. {
  3629. unsigned int i;
  3630. memset(font_faces, 0, sizeof(font_faces));
  3631. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  3632. i <= BR_MAX_FACES; i++) {
  3633. const char *url = br_font_face_url((int)i);
  3634. const char *base = br_font_face_base((int)i);
  3635. char abs[BR_URL_MAX];
  3636. if (!url || !url[0])
  3637. continue;
  3638. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  3639. sizeof(abs)) != 0)
  3640. continue;
  3641. if (abs[0] == '/') {
  3642. font_faces[i - 1] = ufont_face_open_path(abs);
  3643. } else if (is_http(abs)) {
  3644. unsigned char *buf;
  3645. char err[64];
  3646. int rv, tr = 0;
  3647. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  3648. if (!buf)
  3649. continue;
  3650. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3651. UFONT_MAX_FILE, image_io_buf,
  3652. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  3653. err, sizeof(err));
  3654. if (rv > 0)
  3655. font_faces[i - 1] = ufont_face_open_mem(buf,
  3656. rv);
  3657. free(buf);
  3658. }
  3659. }
  3660. }
  3661. /* Remote scripts are cached under /share for the current boot, like the
  3662. * stylesheet cache, so reloads and later visits skip the network. */
  3663. static int script_cache_count;
  3664. static unsigned int script_cache_hash(const char *s)
  3665. {
  3666. unsigned int h = 2166136261u;
  3667. while (*s) {
  3668. h ^= (unsigned char)*s++;
  3669. h *= 16777619u;
  3670. }
  3671. return h;
  3672. }
  3673. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3674. {
  3675. unsigned int n = 0;
  3676. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3677. s_append_dec(out, &n, script_cache_hash(url), cap);
  3678. }
  3679. static void script_cache_clear(void)
  3680. {
  3681. struct sys_dirent d;
  3682. char path[96];
  3683. for (;;) {
  3684. int i, found = 0;
  3685. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3686. (int)&d) == 1; i++) {
  3687. unsigned int n = 0;
  3688. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3689. continue;
  3690. s_append(path, &n, "/share/", sizeof(path));
  3691. s_append(path, &n, d.name, sizeof(path));
  3692. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3693. return;
  3694. found = 1;
  3695. break;
  3696. }
  3697. if (!found)
  3698. break;
  3699. }
  3700. script_cache_count = 0;
  3701. }
  3702. static void script_cache_init(void)
  3703. {
  3704. struct sys_dirent d;
  3705. int i, count = 0;
  3706. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3707. (int)&d) == 1; i++)
  3708. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3709. count++;
  3710. if (count >= SCRIPT_CACHE_MAX) {
  3711. script_cache_clear();
  3712. return;
  3713. }
  3714. script_cache_count = count;
  3715. }
  3716. static int script_cache_get(const char *url, unsigned char **out,
  3717. unsigned int *outlen)
  3718. {
  3719. char path[96];
  3720. struct sys_stat st;
  3721. unsigned char *buf;
  3722. int rn;
  3723. script_cache_path(url, path, sizeof(path));
  3724. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3725. st.size >= SCRIPT_CACHE_FILE_MAX)
  3726. return 0;
  3727. buf = (unsigned char *)malloc(st.size + 1);
  3728. if (!buf)
  3729. return 0;
  3730. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3731. if (rn != (int)st.size) {
  3732. free(buf);
  3733. return 0;
  3734. }
  3735. buf[st.size] = '\0';
  3736. *out = buf;
  3737. *outlen = st.size;
  3738. return 1;
  3739. }
  3740. static void script_cache_put(const char *url, const unsigned char *data,
  3741. unsigned int len)
  3742. {
  3743. char path[96];
  3744. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3745. len >= SCRIPT_CACHE_FILE_MAX)
  3746. return;
  3747. script_cache_path(url, path, sizeof(path));
  3748. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3749. (int)len) >= 0)
  3750. script_cache_count++;
  3751. }
  3752. static int script_cache_has(const char *url)
  3753. {
  3754. char path[96];
  3755. struct sys_stat st;
  3756. script_cache_path(url, path, sizeof(path));
  3757. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3758. st.size < SCRIPT_CACHE_FILE_MAX;
  3759. }
  3760. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3761. static int fetch_script_text(const char *url, unsigned char **out,
  3762. unsigned int *outlen, char *err,
  3763. unsigned int errcap)
  3764. {
  3765. unsigned char *buf;
  3766. unsigned int len;
  3767. int local, truncated = 0;
  3768. char ctype[64], final[BR_URL_MAX];
  3769. int rv;
  3770. *out = 0;
  3771. *outlen = 0;
  3772. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3773. return 0;
  3774. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3775. sizeof(ctype), final, sizeof(final), err, errcap,
  3776. &truncated, 0, 0);
  3777. if (rv != 0)
  3778. return rv;
  3779. if (truncated || len >= BR_SCRIPT_MAX) {
  3780. free(buf);
  3781. s_copy(err, "script is too large", errcap);
  3782. return -1;
  3783. }
  3784. buf[len] = '\0';
  3785. if (!local)
  3786. script_cache_put(url, buf, len);
  3787. *out = buf;
  3788. *outlen = len;
  3789. return 0;
  3790. }
  3791. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  3792. * the heap, so images must not allocate their file body from it as well. */
  3793. static int fetch_image(const char *url, unsigned int cap,
  3794. unsigned char **out, unsigned int *outlen,
  3795. char *err, unsigned int errcap)
  3796. {
  3797. unsigned int len;
  3798. int tr = 0;
  3799. int rv;
  3800. *out = 0;
  3801. *outlen = 0;
  3802. if (cap > BR_IMG_FILE_MAX)
  3803. cap = BR_IMG_FILE_MAX;
  3804. if (url[0] == '/') {
  3805. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  3806. (int)cap);
  3807. if (rv < 0) {
  3808. s_copy(err, "file not found", errcap);
  3809. return -1;
  3810. }
  3811. *out = image_file_buf;
  3812. *outlen = (unsigned int)rv;
  3813. return 0;
  3814. }
  3815. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  3816. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  3817. if (rv == FETCH_ABORT)
  3818. return FETCH_ABORT;
  3819. if (rv < 0)
  3820. return -1;
  3821. len = (unsigned int)rv;
  3822. if (len == 0) {
  3823. s_copy(err, "empty image", errcap);
  3824. return -1;
  3825. }
  3826. *out = image_file_buf;
  3827. *outlen = len;
  3828. return 0;
  3829. }
  3830. /* Remote stylesheets are immutable enough for the current boot: keep
  3831. * successful responses under /share so a reload, a second visit or a fresh
  3832. * browser launch does not fetch the same five sheets over the network again.
  3833. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  3834. static int css_cache_count;
  3835. static unsigned int css_cache_hash(const char *s)
  3836. {
  3837. unsigned int h = 2166136261u;
  3838. while (*s) {
  3839. h ^= (unsigned char)*s++;
  3840. h *= 16777619u;
  3841. }
  3842. return h;
  3843. }
  3844. static void css_cache_path(const char *url, char *out, unsigned int cap)
  3845. {
  3846. unsigned int n = 0;
  3847. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  3848. s_append_dec(out, &n, css_cache_hash(url), cap);
  3849. }
  3850. static void css_cache_clear(void)
  3851. {
  3852. struct sys_dirent d;
  3853. char path[96];
  3854. for (;;) {
  3855. int i, found = 0;
  3856. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3857. (int)&d) == 1; i++) {
  3858. unsigned int n = 0;
  3859. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  3860. continue;
  3861. s_append(path, &n, "/share/", sizeof(path));
  3862. s_append(path, &n, d.name, sizeof(path));
  3863. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3864. return;
  3865. found = 1;
  3866. break;
  3867. }
  3868. if (!found)
  3869. break;
  3870. }
  3871. css_cache_count = 0;
  3872. }
  3873. static void css_cache_init(void)
  3874. {
  3875. struct sys_dirent d;
  3876. int i, count = 0;
  3877. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3878. (int)&d) == 1; i++)
  3879. if (starts_with(d.name, CSS_CACHE_PREFIX))
  3880. count++;
  3881. if (count >= CSS_CACHE_MAX) {
  3882. css_cache_clear();
  3883. return;
  3884. }
  3885. css_cache_count = count;
  3886. }
  3887. static int css_cache_get(const char *url, unsigned char **out,
  3888. unsigned int *outlen)
  3889. {
  3890. char path[96];
  3891. int rn;
  3892. css_cache_path(url, path, sizeof(path));
  3893. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  3894. (int)CSS_CACHE_FILE_MAX);
  3895. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  3896. return 0;
  3897. *out = image_io_buf;
  3898. *outlen = (unsigned int)rn;
  3899. return 1;
  3900. }
  3901. static void css_cache_put(const char *url, const unsigned char *data,
  3902. unsigned int len)
  3903. {
  3904. char path[96];
  3905. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  3906. len >= CSS_CACHE_FILE_MAX)
  3907. return;
  3908. css_cache_path(url, path, sizeof(path));
  3909. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3910. (int)len) >= 0)
  3911. css_cache_count++;
  3912. }
  3913. static int css_cache_has(const char *url)
  3914. {
  3915. char path[96];
  3916. struct sys_stat st;
  3917. css_cache_path(url, path, sizeof(path));
  3918. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3919. st.size < CSS_CACHE_FILE_MAX;
  3920. }
  3921. /* Read one stylesheet into the shared static buffer. CSS is parsed
  3922. * immediately, so it does not need the page heap; this leaves the heap for
  3923. * the 2 MB page body, the rules and the scaled image bitmaps. */
  3924. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  3925. char *err, unsigned int errcap)
  3926. {
  3927. unsigned int len;
  3928. int tr = 0;
  3929. int rv;
  3930. *out = 0;
  3931. *outlen = 0;
  3932. if (url[0] == '/') {
  3933. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  3934. (int)BR_CSS_MAX);
  3935. if (rv < 0) {
  3936. s_copy(err, "stylesheet not found", errcap);
  3937. return -1;
  3938. }
  3939. *out = image_io_buf;
  3940. *outlen = (unsigned int)rv;
  3941. return 0;
  3942. }
  3943. if (css_cache_get(url, out, outlen))
  3944. return 0;
  3945. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  3946. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  3947. &fetch_meta, &tr, err, errcap);
  3948. if (rv == FETCH_ABORT)
  3949. return FETCH_ABORT;
  3950. if (rv < 0)
  3951. return -1;
  3952. len = (unsigned int)rv;
  3953. if (len == 0) {
  3954. s_copy(err, "empty stylesheet", errcap);
  3955. return -1;
  3956. }
  3957. *out = image_io_buf;
  3958. *outlen = len;
  3959. css_cache_put(url, image_io_buf, len);
  3960. return 0;
  3961. }
  3962. static void redraw_now(void);
  3963. static char error_page[1024];
  3964. static void show_error(const char *title, const char *detail)
  3965. {
  3966. char *page = error_page;
  3967. unsigned int n = 0;
  3968. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  3969. s_append(page, &n, title, sizeof(error_page));
  3970. s_append(page, &n, "</h2><p>", sizeof(error_page));
  3971. {
  3972. const char *p = detail;
  3973. while (*p && n + 1 < sizeof(error_page)) {
  3974. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  3975. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  3976. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  3977. else page[n++] = *p;
  3978. p++;
  3979. }
  3980. }
  3981. page[n] = '\0';
  3982. s_append(page, &n, "</p><p>", sizeof(error_page));
  3983. s_append(page, &n, page_url, sizeof(error_page));
  3984. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  3985. sizeof(error_page));
  3986. br_parse(&doc, page, n);
  3987. layout_valid = 0;
  3988. preload_active = 0;
  3989. preload_pending = 0;
  3990. preload_wait = 0;
  3991. fetch_workers_cancel_busy();
  3992. s_copy(page_title, title, sizeof(page_title));
  3993. page_loading = 0;
  3994. set_status(title, 1, 0);
  3995. ngui_invalidate(&ui);
  3996. }
  3997. static int decode_direct_image(const unsigned char *data, unsigned int len,
  3998. unsigned int node)
  3999. {
  4000. if (image_count >= BR_MAX_IMAGES)
  4001. return -1;
  4002. if (decode_image_data(data, len, &images[0], 0, 0, 0, 0) != 0)
  4003. return -1;
  4004. doc.nodes[node].img_index = 0;
  4005. image_count = 1;
  4006. return 0;
  4007. }
  4008. static int ancestor_is(unsigned int node, unsigned int tag)
  4009. {
  4010. unsigned int p = doc.nodes[node].parent;
  4011. while (p) {
  4012. if (doc.nodes[p].tag == tag)
  4013. return 1;
  4014. p = doc.nodes[p].parent;
  4015. }
  4016. return 0;
  4017. }
  4018. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  4019. * parallel but parsed in document order, so the cascade is unchanged. */
  4020. static int load_stylesheets(void)
  4021. {
  4022. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  4023. static unsigned char remote[BR_MAX_SHEETS];
  4024. struct fetch_worker *slot[BR_MAX_SHEETS];
  4025. unsigned int i, n = 0, next = 0, k;
  4026. char err[64];
  4027. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  4028. struct br_node *nd = &doc.nodes[i];
  4029. const char *rel, *href;
  4030. char url[BR_URL_MAX];
  4031. int dup = 0;
  4032. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  4033. continue;
  4034. rel = br_rel(&doc, i);
  4035. if (!contains_ci(rel, "stylesheet"))
  4036. continue;
  4037. href = br_href(&doc, i);
  4038. if (!href[0])
  4039. continue;
  4040. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  4041. continue;
  4042. for (k = 0; k < n; k++)
  4043. if (s_eq(urls[k], url)) {
  4044. dup = 1;
  4045. break;
  4046. }
  4047. if (dup)
  4048. continue;
  4049. s_copy(urls[n], url, BR_URL_MAX);
  4050. remote[n] = url[0] != '/' && !css_cache_has(url);
  4051. n++;
  4052. }
  4053. for (i = 0; i < BR_MAX_SHEETS; i++)
  4054. slot[i] = 0;
  4055. /* Start as many remote sheets as there are free workers. */
  4056. for (; next < n; next++) {
  4057. struct fetch_worker *w;
  4058. if (!remote[next])
  4059. continue;
  4060. w = fetch_worker_alloc();
  4061. if (!w)
  4062. break;
  4063. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  4064. err, sizeof(err)) != 0) {
  4065. fetch_worker_release(w);
  4066. remote[next] = 0;
  4067. continue;
  4068. }
  4069. slot[next] = w;
  4070. }
  4071. for (i = 0; i < n; i++) {
  4072. unsigned char *data = 0;
  4073. unsigned int len = 0;
  4074. int rv;
  4075. if (!remote[i]) {
  4076. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  4077. if (rv == FETCH_ABORT) {
  4078. fetch_workers_stop_all();
  4079. return FETCH_ABORT;
  4080. }
  4081. if (rv != 0 || !len)
  4082. continue;
  4083. } else {
  4084. struct fetch_worker *w = slot[i];
  4085. int tr = 0;
  4086. if (!w) {
  4087. w = fetch_worker_alloc();
  4088. if (!w) {
  4089. rv = -1;
  4090. goto css_failed;
  4091. }
  4092. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  4093. 0, 0, 0, 0, err,
  4094. sizeof(err)) != 0) {
  4095. fetch_worker_release(w);
  4096. remote[i] = 0;
  4097. if (i == next)
  4098. next++;
  4099. continue;
  4100. }
  4101. slot[i] = w;
  4102. if (i == next)
  4103. next++;
  4104. }
  4105. rv = fetch_worker_wait(w, err, sizeof(err));
  4106. if (rv == FETCH_ABORT) {
  4107. fetch_workers_stop_all();
  4108. return FETCH_ABORT;
  4109. }
  4110. if (rv == 0)
  4111. rv = fetch_worker_read_body(w, image_io_buf,
  4112. BR_CSS_MAX,
  4113. image_io_buf + BR_CSS_MAX,
  4114. BR_CSS_COMP_MAX, &tr,
  4115. err, sizeof(err));
  4116. else
  4117. rv = -1;
  4118. fetch_worker_release(w);
  4119. slot[i] = 0;
  4120. /* Refill the worker window before parsing this sheet. */
  4121. for (; next < n; next++) {
  4122. struct fetch_worker *nw;
  4123. if (!remote[next])
  4124. continue;
  4125. nw = fetch_worker_alloc();
  4126. if (!nw)
  4127. break;
  4128. if (fetch_worker_submit(nw, urls[next],
  4129. BR_CSS_MAX, 0, 0, 0, 0,
  4130. err, sizeof(err)) != 0) {
  4131. fetch_worker_release(nw);
  4132. remote[next] = 0;
  4133. continue;
  4134. }
  4135. slot[next] = nw;
  4136. }
  4137. css_failed:
  4138. if (rv <= 0) {
  4139. /* One synchronous retry: a dropped sheet leaves the
  4140. * whole page unstyled (seen intermittently on
  4141. * arstechnica's CDN). */
  4142. u_puts("[css] retry ");
  4143. u_puts(urls[i]);
  4144. u_puts(": ");
  4145. u_puts(err[0] ? err : "no worker/empty body");
  4146. u_putc('\n');
  4147. err[0] = '\0';
  4148. rv = fetch_css(urls[i], &data, &len, err,
  4149. sizeof(err));
  4150. if (rv == FETCH_ABORT) {
  4151. fetch_workers_stop_all();
  4152. return FETCH_ABORT;
  4153. }
  4154. if (rv != 0 || !len) {
  4155. u_puts("[css] failed: ");
  4156. u_puts(err);
  4157. u_putc('\n');
  4158. continue;
  4159. }
  4160. } else {
  4161. len = (unsigned int)rv;
  4162. data = image_io_buf;
  4163. css_cache_put(urls[i], data, len);
  4164. }
  4165. }
  4166. if (len) {
  4167. br_set_font_base(urls[i]);
  4168. br_parse_css_text(&doc, (const char *)data, len);
  4169. }
  4170. }
  4171. br_set_font_base(page_url);
  4172. br_parse_inline_css(&doc);
  4173. load_font_faces();
  4174. br_reset_styles(&doc);
  4175. layout_valid = 0;
  4176. return 0;
  4177. }
  4178. static void preload_begin(void)
  4179. {
  4180. preload_active = 1;
  4181. preload_pending = 0;
  4182. preload_wait = 1;
  4183. preload_max_jobs = FETCH_WORKERS;
  4184. preload_node = 0;
  4185. preload_loaded = 0;
  4186. preload_scroll = 0;
  4187. img_stat_start = u_ticks_ms();
  4188. img_stat_wall = 0;
  4189. img_stat_net = img_stat_open = img_stat_first = 0;
  4190. img_stat_io = img_stat_dec = img_stat_scale = 0;
  4191. img_stat_paint = img_stat_reflow = 0;
  4192. img_stat_bytes = 0;
  4193. img_stat_n = 0;
  4194. img_stat_log_len = 0;
  4195. if (img_stat_log[0])
  4196. img_stat_log[0] = '\0';
  4197. img_repaint_ms = 0;
  4198. img_repaint_pending = 0;
  4199. }
  4200. /* Styles are computed top-down during layout, but images inside a hidden
  4201. * menu/carousel are never visited and keep img_top == 0. Without this check
  4202. * the preloader walks the DOM in node order and spends the whole image
  4203. * budget on logos and off-canvas thumbnails the reader cannot see. */
  4204. static struct br_style base_style(void);
  4205. static int node_hidden(unsigned int node)
  4206. {
  4207. unsigned int path[32], n = 0, p = node, i;
  4208. struct br_style st, parent;
  4209. while (p && n < sizeof(path) / sizeof(path[0])) {
  4210. path[n++] = p;
  4211. p = doc.nodes[p].parent;
  4212. }
  4213. /* Node 0 is the <html> element when the page starts with one: it
  4214. * is an ancestor too. Styles are cached per node, so the chain
  4215. * must start from the same base as style_for_node(); seeding it
  4216. * with a zeroed style left <body> cached with black text and no
  4217. * line-height once an image job ran (docs.cloudron.io). */
  4218. if (!p && n && n < sizeof(path) / sizeof(path[0]) &&
  4219. doc.nodes[0].type == BR_NODE_ELEM &&
  4220. doc.nodes[0].tag == BR_TAG_HTML &&
  4221. !(doc.nodes[path[n - 1]].flags & BR_NODE_DETACHED))
  4222. path[n++] = 0;
  4223. parent = base_style();
  4224. for (i = n; i > 0; i--) {
  4225. br_style_for(&doc, path[i - 1], &parent, &st);
  4226. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  4227. st.opacity_hidden)
  4228. return 1;
  4229. parent = st;
  4230. }
  4231. return 0;
  4232. }
  4233. static struct br_style base_style(void);
  4234. static int style_width_px(const struct br_style *st, int base);
  4235. static int style_height_px(const struct br_style *st, int base);
  4236. static void style_for_node(unsigned int node, struct br_style *out)
  4237. {
  4238. unsigned int p = doc.nodes[node].parent;
  4239. struct br_style parent;
  4240. /* Parent index 0 is ambiguous: it is the <html> element when the page
  4241. * starts with one (see root_style()), but also the parent field of a
  4242. * detached subtree root. */
  4243. if (p || (node != 0 && doc.nodes[0].type == BR_NODE_ELEM &&
  4244. doc.nodes[0].tag == BR_TAG_HTML &&
  4245. !(doc.nodes[node].flags & BR_NODE_DETACHED))) {
  4246. style_for_node(p, &parent);
  4247. br_style_for(&doc, node, &parent, out);
  4248. } else {
  4249. parent = base_style();
  4250. br_style_for(&doc, node, &parent, out);
  4251. }
  4252. }
  4253. /* ---- parallel image preloading ---- *
  4254. *
  4255. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  4256. * preload_step() only starts jobs and harvests completed ones; the browser
  4257. * main loop keeps drawing between calls, instead of blocking on one fetch.
  4258. */
  4259. static int preload_active_jobs(void)
  4260. {
  4261. int i, n = 0;
  4262. for (i = 0; i < FETCH_WORKERS; i++)
  4263. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  4264. n++;
  4265. return n;
  4266. }
  4267. static void preload_job_error(struct fetch_worker *w)
  4268. {
  4269. if (w->node < doc.nnode) {
  4270. if (w->bg)
  4271. doc.nodes[w->node].bg_img_index = -2;
  4272. else
  4273. doc.nodes[w->node].img_index = -2;
  4274. image_repaint();
  4275. }
  4276. }
  4277. /* Is the image's box anywhere near the visible page? A decode below the
  4278. * fold changes the layout (scroll extent) but not a single on-screen pixel,
  4279. * so it does not need a repaint. top/h come from the last layout; treat an
  4280. * unknown box as visible to stay safe. */
  4281. static int image_preload_visible(unsigned int node, int bg)
  4282. {
  4283. int top, h, scroll;
  4284. if (node >= BR_MAX_NODES || node >= doc.nnode || page_rect.h <= 0)
  4285. return 1;
  4286. if (bg) {
  4287. top = (int)block_top[node];
  4288. h = (int)block_h[node];
  4289. } else {
  4290. top = (int)img_top[node];
  4291. h = (int)img_h[node];
  4292. }
  4293. if (!top && !h)
  4294. return 1;
  4295. scroll = (int)page_scroll.offset;
  4296. if (top > scroll + page_rect.h + 160)
  4297. return 0;
  4298. if (top + h + 160 < scroll)
  4299. return 0;
  4300. return 1;
  4301. }
  4302. /* Upper bounds for the bitmap an <img> will paint. Zero means "unbounded";
  4303. * decode_image_data applies one scale to both axes so the aspect ratio is
  4304. * preserved. This is what keeps a 1200x800 photo that CSS paints at 400 px
  4305. * from being decoded and box-filtered to the 1000 px layout cap first. */
  4306. static void image_fit_size(unsigned int node, int *out_w, int *out_h)
  4307. {
  4308. struct br_style st;
  4309. struct br_node *nd;
  4310. unsigned int p;
  4311. int cw, w = 0, h = 0;
  4312. *out_w = *out_h = 0;
  4313. if (node >= doc.nnode)
  4314. return;
  4315. nd = &doc.nodes[node];
  4316. style_for_node(node, &st);
  4317. cw = page_rect.w > 24 ? page_rect.w - 24 : 0;
  4318. p = doc.nodes[node].parent;
  4319. if (p && p < BR_MAX_NODES && layout_boxes[p].valid &&
  4320. layout_boxes[p].w > 0 && layout_boxes[p].w < cw)
  4321. cw = layout_boxes[p].w;
  4322. if (st.width_kind)
  4323. w = style_width_px(&st, cw);
  4324. else if (nd->width_attr)
  4325. w = nd->width_pct ? cw * (int)nd->width_attr / 100 :
  4326. (int)nd->width_attr;
  4327. if (st.height_kind)
  4328. h = style_height_px(&st, cw);
  4329. else if (nd->height_attr)
  4330. h = nd->height_pct ? cw * (int)nd->height_attr / 100 :
  4331. (int)nd->height_attr;
  4332. if (st.max_width_kind) {
  4333. int mw = st.max_width_kind == 3 ?
  4334. cw * st.max_width_calc_pct / 100 +
  4335. st.max_width_calc_px :
  4336. st.max_width_kind == 2 ?
  4337. cw * (int)st.max_width / 100 :
  4338. (int)st.max_width;
  4339. if (mw > 0 && (w == 0 || w > mw))
  4340. w = mw;
  4341. }
  4342. if (st.max_height_kind) {
  4343. int mh = st.max_height_kind == 3 ?
  4344. cw * st.max_height_calc_pct / 100 +
  4345. st.max_height_calc_px :
  4346. st.max_height_kind == 2 ?
  4347. cw * (int)st.max_height / 100 :
  4348. (int)st.max_height;
  4349. if (mh > 0 && (h == 0 || h > mh))
  4350. h = mh;
  4351. }
  4352. if (w > BR_IMG_LAYOUT_W)
  4353. w = BR_IMG_LAYOUT_W;
  4354. if (h > 4096)
  4355. h = 4096;
  4356. if (w < 0)
  4357. w = 0;
  4358. if (h < 0)
  4359. h = 0;
  4360. *out_w = w;
  4361. *out_h = h;
  4362. }
  4363. static void preload_accept_image(unsigned int node, int bg, const char *url)
  4364. {
  4365. /* An <img> bitmap only depends on its URL, so the next <img> with the
  4366. * same source reuses it (heise repeats one comment icon 85 times).
  4367. * Backgrounds are scaled to their box and are not shared. */
  4368. images[image_count].url_hash =
  4369. !bg && url ? script_cache_hash(url) | 1u : 0;
  4370. if (bg)
  4371. doc.nodes[node].bg_img_index = (short)image_count;
  4372. else
  4373. doc.nodes[node].img_index = (short)image_count;
  4374. image_count++;
  4375. preload_loaded++;
  4376. /* A background bitmap never changes its box, so keep the (expensive)
  4377. * measured layout and only repaint the pixels. */
  4378. if (bg)
  4379. page_cache_valid = 0;
  4380. else
  4381. layout_valid = 0;
  4382. if (image_preload_visible(node, bg))
  4383. image_repaint();
  4384. }
  4385. /* Install a bitmap decoded by the fetch helper. The helper already applied
  4386. * the display bounds (and the JPEG reduced IDCT), so this is a read + copy
  4387. * on the UI thread instead of a decode. */
  4388. static int preload_store_helper(unsigned int node, int bg,
  4389. unsigned char *px, unsigned int pxlen,
  4390. unsigned int dw, unsigned int dh,
  4391. int alpha, unsigned int nw, unsigned int nh,
  4392. const char *url)
  4393. {
  4394. struct br_image *bi;
  4395. unsigned int npx;
  4396. if (image_count >= BR_MAX_IMAGES || !px || !dw || !dh ||
  4397. dw > 4096 || dh > 4096) {
  4398. free(px);
  4399. return -1;
  4400. }
  4401. npx = dw * dh;
  4402. if (image_pixels + npx > BR_IMG_PIXEL_BUDGET ||
  4403. pxlen < npx * 2u + (alpha ? npx : 0)) {
  4404. free(px);
  4405. return -1;
  4406. }
  4407. bi = &images[image_count];
  4408. bi->img.format = 0;
  4409. bi->img.w = dw;
  4410. bi->img.h = dh;
  4411. bi->img.px = (unsigned short *)px;
  4412. bi->img.alpha = alpha ? px + npx * 2u : 0;
  4413. bi->img.flags = 0;
  4414. bi->native_w = nw ? (int)nw : (int)dw;
  4415. bi->native_h = nh ? (int)nh : (int)dh;
  4416. bi->state = 1;
  4417. image_pixels += npx;
  4418. preload_accept_image(node, bg, url);
  4419. return 0;
  4420. }
  4421. static void preload_decode(unsigned int node, int bg,
  4422. const unsigned char *data, unsigned int len,
  4423. const char *url)
  4424. {
  4425. int fit_w = 0, fit_h = 0;
  4426. if (image_count >= BR_MAX_IMAGES) {
  4427. if (bg)
  4428. doc.nodes[node].bg_img_index = -2;
  4429. else
  4430. doc.nodes[node].img_index = -2;
  4431. return;
  4432. }
  4433. if (!bg)
  4434. image_fit_size(node, &fit_w, &fit_h);
  4435. if (decode_image_data(data, len, &images[image_count],
  4436. bg && node < BR_MAX_NODES &&
  4437. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  4438. bg && node < BR_MAX_NODES &&
  4439. layout_boxes[node].valid ? layout_boxes[node].h : 0,
  4440. fit_w, fit_h) == 0) {
  4441. preload_accept_image(node, bg, url);
  4442. } else {
  4443. if (bg)
  4444. doc.nodes[node].bg_img_index = -2;
  4445. else
  4446. doc.nodes[node].img_index = -2;
  4447. layout_valid = 0;
  4448. }
  4449. if (image_preload_visible(node, bg))
  4450. image_repaint();
  4451. }
  4452. /* ---- data: URLs ----
  4453. *
  4454. * `data:[<type>][;base64],<payload>` decoded to bytes from the page heap
  4455. * (the caller frees them). The payload is percent-decoded, then base64-
  4456. * decoded when the header says so. Infima's menu chevron and many icon
  4457. * fonts' fallbacks are inline SVGs written this way. */
  4458. static int b64_val(int c)
  4459. {
  4460. if (c >= 'A' && c <= 'Z') return c - 'A';
  4461. if (c >= 'a' && c <= 'z') return c - 'a' + 26;
  4462. if (c >= '0' && c <= '9') return c - '0' + 52;
  4463. if (c == '+' || c == '-') return 62;
  4464. if (c == '/' || c == '_') return 63;
  4465. return -1;
  4466. }
  4467. static int hex_val(int c)
  4468. {
  4469. if (c >= '0' && c <= '9') return c - '0';
  4470. c |= 32;
  4471. if (c >= 'a' && c <= 'f') return c - 'a' + 10;
  4472. return -1;
  4473. }
  4474. static int data_url_decode(const char *url, unsigned char **out,
  4475. unsigned int *out_len)
  4476. {
  4477. const char *comma, *p;
  4478. unsigned int n = 0, len, i;
  4479. unsigned char *buf;
  4480. int base64 = 0;
  4481. *out = 0;
  4482. *out_len = 0;
  4483. if (!starts_with(url, "data:"))
  4484. return -1;
  4485. comma = url + 5;
  4486. while (*comma && *comma != ',')
  4487. comma++;
  4488. if (!*comma)
  4489. return -1;
  4490. for (p = url + 5; p + 7 <= comma; p++)
  4491. if (!strncmp(p, ";base64", 7))
  4492. base64 = 1;
  4493. len = s_len(comma + 1);
  4494. buf = (unsigned char *)malloc(len + 1);
  4495. if (!buf)
  4496. return -1;
  4497. for (i = 0, p = comma + 1; i < len; i++) {
  4498. int c = (unsigned char)p[i];
  4499. if (c == '%' && i + 2 < len &&
  4500. hex_val(p[i + 1]) >= 0 && hex_val(p[i + 2]) >= 0) {
  4501. c = hex_val(p[i + 1]) * 16 + hex_val(p[i + 2]);
  4502. i += 2;
  4503. }
  4504. buf[n++] = (unsigned char)c;
  4505. }
  4506. if (base64) {
  4507. unsigned int acc = 0, o = 0;
  4508. int bits = 0;
  4509. for (i = 0; i < n; i++) {
  4510. int v = b64_val(buf[i]);
  4511. if (v < 0)
  4512. continue; /* padding, whitespace */
  4513. acc = (acc << 6) | (unsigned int)v;
  4514. bits += 6;
  4515. if (bits >= 8) {
  4516. bits -= 8;
  4517. buf[o++] = (unsigned char)(acc >> bits);
  4518. }
  4519. }
  4520. n = o;
  4521. }
  4522. buf[n] = 0;
  4523. *out = buf;
  4524. *out_len = n;
  4525. return 0;
  4526. }
  4527. static unsigned int data_img_key(const char *url, int w, int h)
  4528. {
  4529. return (script_cache_hash(url) ^ ((unsigned int)w * 2654435761u) ^
  4530. ((unsigned int)h * 40503u)) | 1u;
  4531. }
  4532. /* The image index of a data: URL decoded for a w x h box (an SVG is
  4533. * rasterized at that size), decoding it on first use; -1 on failure.
  4534. * Decoded bitmaps are found again through url_hash, which is distinct
  4535. * from the <img> sharing hash because it mixes in the size. */
  4536. static int data_url_image(const char *url, int w, int h)
  4537. {
  4538. unsigned int key, len;
  4539. unsigned char *data;
  4540. int i;
  4541. if (!starts_with(url, "data:") || w <= 0 || h <= 0)
  4542. return -1;
  4543. key = data_img_key(url, w, h);
  4544. for (i = 0; i < image_count; i++)
  4545. if (images[i].state == 1 && images[i].url_hash == key)
  4546. return i;
  4547. for (i = 0; i < data_img_nfail; i++)
  4548. if (data_img_fail[i] == key)
  4549. return -1;
  4550. if (image_count < BR_MAX_IMAGES &&
  4551. data_url_decode(url, &data, &len) == 0) {
  4552. int r = decode_image_data(data, len, &images[image_count],
  4553. w, h, w, h);
  4554. free(data);
  4555. if (r == 0) {
  4556. images[image_count].url_hash = key;
  4557. return image_count++;
  4558. }
  4559. }
  4560. if (data_img_nfail < DATA_IMG_FAIL_MAX)
  4561. data_img_fail[data_img_nfail++] = key;
  4562. return -1;
  4563. }
  4564. /* A local file image bypasses the helpers: count its decode so a page opened
  4565. * from /share or /data still produces the same timing breakdown. */
  4566. static void img_stat_local(int before, unsigned int bytes, unsigned int io_ms)
  4567. {
  4568. img_stat_n++;
  4569. img_stat_bytes += bytes;
  4570. img_stat_io += io_ms;
  4571. if (image_count > before) {
  4572. struct br_image *bi = &images[image_count - 1];
  4573. img_stat_dec += img_last_dec_ms;
  4574. img_stat_scale += img_last_scale_ms;
  4575. if (img_stat_log_len + 100 < sizeof(img_stat_log)) {
  4576. unsigned int n = img_stat_log_len;
  4577. s_append(img_stat_log, &n, "local ", sizeof(img_stat_log));
  4578. s_append_dec(img_stat_log, &n, bytes,
  4579. sizeof(img_stat_log));
  4580. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4581. s_append_dec(img_stat_log, &n, img_last_dec_ms,
  4582. sizeof(img_stat_log));
  4583. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4584. s_append_dec(img_stat_log, &n, img_last_scale_ms,
  4585. sizeof(img_stat_log));
  4586. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4587. s_append_dec(img_stat_log, &n,
  4588. (unsigned int)bi->native_w,
  4589. sizeof(img_stat_log));
  4590. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4591. s_append_dec(img_stat_log, &n,
  4592. (unsigned int)bi->native_h,
  4593. sizeof(img_stat_log));
  4594. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4595. s_append_dec(img_stat_log, &n, bi->img.w,
  4596. sizeof(img_stat_log));
  4597. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4598. s_append_dec(img_stat_log, &n, bi->img.h,
  4599. sizeof(img_stat_log));
  4600. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4601. s_append_dec(img_stat_log, &n,
  4602. bi->img.alpha ? 1u : 0u,
  4603. sizeof(img_stat_log));
  4604. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4605. img_stat_log_len = n;
  4606. }
  4607. }
  4608. }
  4609. /* Harvest one completed worker. Returns 1 when a job was finished. */
  4610. static int preload_finish_worker(struct fetch_worker *w)
  4611. {
  4612. char err[64];
  4613. int rv, tr = 0;
  4614. unsigned int t0, io_ms;
  4615. int before;
  4616. int used_px = 0;
  4617. rv = fetch_worker_poll(w, err, sizeof(err));
  4618. if (rv < 0) {
  4619. /* A helper from an older pack does not understand the image
  4620. * decode request; retry once without it and decode in-process. */
  4621. if (w->image_job && w->dec_w && !w->dec_retried &&
  4622. fetch_worker_submit_req(w, w->url, BR_IMG_FILE_MAX,
  4623. 0, 0, 0, 0, w->node, w->bg,
  4624. 0, 0, err, sizeof(err)) == 0) {
  4625. w->image_job = 1;
  4626. w->dec_retried = 1;
  4627. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4628. return 0;
  4629. }
  4630. preload_job_error(w);
  4631. if (img_stat_log_len + 64 < sizeof(img_stat_log)) {
  4632. unsigned int n = img_stat_log_len;
  4633. char u[48];
  4634. s_copy(u, w->url, sizeof(u));
  4635. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4636. s_append(img_stat_log, &n, " error\n",
  4637. sizeof(img_stat_log));
  4638. img_stat_log_len = n;
  4639. }
  4640. img_stat_n++;
  4641. fetch_worker_release(w);
  4642. return 1;
  4643. }
  4644. if (rv == 0)
  4645. return 0;
  4646. t0 = u_ticks_ms();
  4647. rv = -1;
  4648. before = image_count;
  4649. if (w->m.px_len && !w->m.dec_err && w->m.dw && w->m.dh &&
  4650. w->m.px_len <= 8u * 1024u * 1024u) {
  4651. unsigned char *px = (unsigned char *)malloc(w->m.px_len);
  4652. int pr = -1;
  4653. if (px)
  4654. pr = u_syscall3(SYS_READ_FILE, (int)w->px, (int)px,
  4655. (int)w->m.px_len);
  4656. if (pr == (int)w->m.px_len) {
  4657. if (preload_store_helper(w->node, w->bg, px,
  4658. w->m.px_len, w->m.dw,
  4659. w->m.dh, (int)w->m.alpha,
  4660. w->m.nw, w->m.nh,
  4661. w->url) == 0) {
  4662. rv = (int)w->m.len;
  4663. img_last_dec_ms = w->m.dec_ms;
  4664. img_last_scale_ms = 0;
  4665. used_px = 1;
  4666. } else {
  4667. px = 0; /* the helper freed it */
  4668. }
  4669. }
  4670. if (px && !(pr == (int)w->m.px_len))
  4671. free(px);
  4672. }
  4673. io_ms = u_ticks_ms() - t0;
  4674. if (rv < 0) {
  4675. t0 = u_ticks_ms();
  4676. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  4677. image_comp_buf, BR_IMG_FILE_MAX,
  4678. &tr, err, sizeof(err));
  4679. io_ms += u_ticks_ms() - t0;
  4680. before = image_count;
  4681. if (rv >= 0)
  4682. preload_decode(w->node, w->bg, image_file_buf,
  4683. (unsigned int)rv, w->url);
  4684. else
  4685. preload_job_error(w);
  4686. }
  4687. img_stat_n++;
  4688. img_stat_net += w->m.total_ms;
  4689. img_stat_open += w->m.open_ms;
  4690. img_stat_first += w->m.first_ms;
  4691. img_stat_io += io_ms;
  4692. img_stat_bytes += rv > 0 ? (unsigned int)rv : 0;
  4693. img_stat_dec += w->m.dec_ms;
  4694. if (rv >= 0 && !used_px) {
  4695. img_stat_dec += img_last_dec_ms;
  4696. img_stat_scale += img_last_scale_ms;
  4697. }
  4698. if (img_stat_log_len + 160 < sizeof(img_stat_log)) {
  4699. unsigned int n = img_stat_log_len;
  4700. char u[48];
  4701. s_copy(u, w->url, sizeof(u));
  4702. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4703. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4704. s_append_dec(img_stat_log, &n,
  4705. rv > 0 ? (unsigned int)rv : 0,
  4706. sizeof(img_stat_log));
  4707. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4708. s_append_dec(img_stat_log, &n, w->m.open_ms,
  4709. sizeof(img_stat_log));
  4710. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4711. s_append_dec(img_stat_log, &n, w->m.first_ms,
  4712. sizeof(img_stat_log));
  4713. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4714. s_append_dec(img_stat_log, &n, w->m.total_ms,
  4715. sizeof(img_stat_log));
  4716. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4717. s_append_dec(img_stat_log, &n, io_ms, sizeof(img_stat_log));
  4718. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4719. s_append_dec(img_stat_log, &n,
  4720. rv >= 0 ? img_last_dec_ms : 0,
  4721. sizeof(img_stat_log));
  4722. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4723. s_append_dec(img_stat_log, &n,
  4724. rv >= 0 ? img_last_scale_ms : 0,
  4725. sizeof(img_stat_log));
  4726. if (image_count > before) {
  4727. struct br_image *bi = &images[image_count - 1];
  4728. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4729. s_append_dec(img_stat_log, &n,
  4730. (unsigned int)bi->native_w,
  4731. sizeof(img_stat_log));
  4732. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4733. s_append_dec(img_stat_log, &n,
  4734. (unsigned int)bi->native_h,
  4735. sizeof(img_stat_log));
  4736. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4737. s_append_dec(img_stat_log, &n, bi->img.w,
  4738. sizeof(img_stat_log));
  4739. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4740. s_append_dec(img_stat_log, &n, bi->img.h,
  4741. sizeof(img_stat_log));
  4742. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4743. s_append_dec(img_stat_log, &n,
  4744. bi->img.alpha ? 1u : 0u,
  4745. sizeof(img_stat_log));
  4746. }
  4747. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4748. img_stat_log_len = n;
  4749. }
  4750. fetch_worker_release(w);
  4751. return 1;
  4752. }
  4753. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  4754. * the number of jobs started. */
  4755. static int preload_fill_jobs(void)
  4756. {
  4757. int started = 0;
  4758. char err[64];
  4759. while (preload_active && preload_node < doc.nnode) {
  4760. unsigned int i = preload_node;
  4761. struct br_node *nd = &doc.nodes[i];
  4762. const char *src;
  4763. char url[BR_URL_MAX];
  4764. struct fetch_worker *w;
  4765. if (preload_active_jobs() >= preload_max_jobs)
  4766. break;
  4767. if (nd->type != BR_NODE_ELEM) {
  4768. preload_node++;
  4769. continue;
  4770. }
  4771. if (nd->tag != BR_TAG_IMG) {
  4772. if (nd->bg_img_index == -1) {
  4773. struct br_style bs;
  4774. style_for_node(i, &bs);
  4775. if (bs.display != BR_DISPLAY_NONE &&
  4776. !bs.vis_hidden && bs.bg_image) {
  4777. const char *bsrc =
  4778. br_bg_image_url(bs.bg_image - 1);
  4779. /* Lazy like <img>: a background box
  4780. * below the viewport (or not laid
  4781. * out yet) waits for the next scan. */
  4782. if (bsrc[0] &&
  4783. (!layout_boxes[i].valid ||
  4784. block_top[i] >
  4785. (unsigned int)(page_scroll.offset +
  4786. page_rect.h + 160))) {
  4787. preload_pending = 1;
  4788. preload_node++;
  4789. continue;
  4790. }
  4791. if (starts_with(bsrc, "data:")) {
  4792. /* Inline image: decode now,
  4793. * no fetch helper. */
  4794. unsigned char *data;
  4795. unsigned int len;
  4796. preload_node = i + 1;
  4797. if (data_url_decode(bsrc, &data,
  4798. &len) == 0) {
  4799. preload_decode(i, 1, data,
  4800. len, 0);
  4801. free(data);
  4802. } else {
  4803. nd->bg_img_index = -2;
  4804. }
  4805. continue;
  4806. }
  4807. if (bsrc[0] &&
  4808. resolve_link(page_url, bsrc, url,
  4809. sizeof(url)) == 0) {
  4810. if (image_count +
  4811. preload_active_jobs() >=
  4812. BR_MAX_IMAGES) {
  4813. preload_node = doc.nnode;
  4814. break;
  4815. }
  4816. if (url[0] == '/') {
  4817. unsigned char *data = 0;
  4818. unsigned int len = 0;
  4819. unsigned int t0;
  4820. int before;
  4821. preload_node = i + 1;
  4822. before = image_count;
  4823. t0 = u_ticks_ms();
  4824. if (fetch_image(url,
  4825. BR_IMG_FILE_MAX,
  4826. &data, &len,
  4827. err,
  4828. sizeof(err)) == 0) {
  4829. preload_decode(i, 1, data, len, 0);
  4830. img_stat_local(before, len,
  4831. u_ticks_ms() - t0);
  4832. } else {
  4833. nd->bg_img_index = -2;
  4834. }
  4835. continue;
  4836. }
  4837. w = fetch_worker_alloc();
  4838. if (!w)
  4839. return started;
  4840. preload_node = i + 1;
  4841. if (fetch_worker_submit(w, url,
  4842. BR_IMG_FILE_MAX,
  4843. 0, 0, i, 1,
  4844. err,
  4845. sizeof(err)) != 0) {
  4846. nd->bg_img_index = -2;
  4847. fetch_worker_release(w);
  4848. continue;
  4849. }
  4850. w->image_job = 1;
  4851. w->deadline = u_ticks_ms() +
  4852. BR_IMG_JOB_TIMEOUT_MS;
  4853. /* in flight: rescans skip it */
  4854. nd->bg_img_index = -3;
  4855. started++;
  4856. continue;
  4857. }
  4858. }
  4859. nd->bg_img_index = -2;
  4860. }
  4861. preload_node++;
  4862. continue;
  4863. }
  4864. if (nd->img_index != -1) {
  4865. preload_node++;
  4866. continue;
  4867. }
  4868. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  4869. preload_node++;
  4870. continue;
  4871. }
  4872. src = br_src(&doc, i);
  4873. if (starts_with(src, "data:")) {
  4874. unsigned char *data;
  4875. unsigned int len;
  4876. preload_node = i + 1;
  4877. if (data_url_decode(src, &data, &len) == 0) {
  4878. preload_decode(i, 0, data, len, 0);
  4879. free(data);
  4880. } else {
  4881. doc.nodes[i].img_index = -2;
  4882. }
  4883. continue;
  4884. }
  4885. if (!src[0]) {
  4886. preload_node++;
  4887. continue;
  4888. }
  4889. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  4890. preload_node++;
  4891. continue;
  4892. }
  4893. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  4894. preload_node = doc.nnode;
  4895. break;
  4896. }
  4897. /* Do not stop at the first below-fold image: DOM order is
  4898. * not visual order, and a footer/ad image early in the DOM
  4899. * used to hide every later article image from the loader. */
  4900. if (img_top[i] >
  4901. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  4902. preload_pending = 1;
  4903. preload_node++;
  4904. continue;
  4905. }
  4906. {
  4907. unsigned int uh = script_cache_hash(url) | 1u;
  4908. int k;
  4909. for (k = 0; k < image_count; k++)
  4910. if (images[k].state == 1 &&
  4911. images[k].url_hash == uh)
  4912. break;
  4913. if (k < image_count) {
  4914. nd->img_index = (short)k;
  4915. layout_valid = 0;
  4916. preload_node = i + 1;
  4917. image_repaint();
  4918. continue;
  4919. }
  4920. }
  4921. if (url[0] == '/') {
  4922. unsigned char *data = 0;
  4923. unsigned int len = 0;
  4924. unsigned int t0;
  4925. int before;
  4926. preload_node = i + 1;
  4927. before = image_count;
  4928. t0 = u_ticks_ms();
  4929. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  4930. err, sizeof(err)) == 0) {
  4931. preload_decode(i, 0, data, len, url);
  4932. img_stat_local(before, len, u_ticks_ms() - t0);
  4933. } else {
  4934. nd->img_index = -2;
  4935. }
  4936. continue;
  4937. }
  4938. w = fetch_worker_alloc();
  4939. if (!w)
  4940. return started;
  4941. preload_node = i + 1;
  4942. {
  4943. char msg[64];
  4944. unsigned int n = 0;
  4945. s_append(msg, &n, "Loading images ", sizeof(msg));
  4946. s_append_dec(msg, &n,
  4947. (unsigned int)preload_loaded + 1,
  4948. sizeof(msg));
  4949. s_append(msg, &n, "...", sizeof(msg));
  4950. set_status_quiet(msg);
  4951. image_repaint();
  4952. }
  4953. {
  4954. int fit_w = 0, fit_h = 0;
  4955. image_fit_size(i, &fit_w, &fit_h);
  4956. if (!fit_w)
  4957. fit_w = BR_IMG_LAYOUT_W;
  4958. if (fetch_worker_submit_image(w, url, BR_IMG_FILE_MAX,
  4959. i, 0,
  4960. (unsigned int)fit_w,
  4961. (unsigned int)fit_h,
  4962. err, sizeof(err)) != 0) {
  4963. nd->img_index = -2;
  4964. fetch_worker_release(w);
  4965. continue;
  4966. }
  4967. }
  4968. w->image_job = 1;
  4969. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4970. nd->img_index = -3; /* in flight: rescans skip it */
  4971. started++;
  4972. }
  4973. return started;
  4974. }
  4975. /* Report where the image batch spent its time: status bar for the headline,
  4976. * /share/IMGSTAT for the per-image breakdown (cat it from a terminal). */
  4977. static void img_stats_report(void)
  4978. {
  4979. char msg[80];
  4980. static char out[BR_IMG_STAT_LOG + 512];
  4981. unsigned int n = 0, o = 0;
  4982. if (!img_stat_n)
  4983. return;
  4984. img_stat_wall = img_stat_start ?
  4985. u_ticks_ms() - img_stat_start : 1;
  4986. if (!img_stat_wall)
  4987. img_stat_wall = 1;
  4988. /* Compact on-screen form; /share/IMGSTAT has the full breakdown. */
  4989. s_append(msg, &n, "img ", sizeof(msg));
  4990. s_append_dec(msg, &n, (unsigned int)img_stat_n, sizeof(msg));
  4991. s_append(msg, &n, " ", sizeof(msg));
  4992. s_append_dec(msg, &n, img_stat_wall, sizeof(msg));
  4993. s_append(msg, &n, "ms net ", sizeof(msg));
  4994. s_append_dec(msg, &n, img_stat_net, sizeof(msg));
  4995. s_append(msg, &n, " dec ", sizeof(msg));
  4996. s_append_dec(msg, &n, img_stat_dec, sizeof(msg));
  4997. s_append(msg, &n, " sc ", sizeof(msg));
  4998. s_append_dec(msg, &n, img_stat_scale, sizeof(msg));
  4999. s_append(msg, &n, " paint ", sizeof(msg));
  5000. s_append_dec(msg, &n, img_stat_paint, sizeof(msg));
  5001. /* Keep the page's phase breakdown and append the image summary when
  5002. * it fits; never hide a JS error or a truncation notice. */
  5003. if (!post_status_error && !contains_ci(post_status_text, "truncated")) {
  5004. unsigned int plen = s_len(post_status_text);
  5005. if (!plen) {
  5006. s_copy(post_status_text, msg, sizeof(post_status_text));
  5007. } else if (plen + s_len(msg) + 4 < sizeof(post_status_text)) {
  5008. unsigned int pn = plen;
  5009. s_append(post_status_text, &pn, " | ",
  5010. sizeof(post_status_text));
  5011. s_append(post_status_text, &pn, msg,
  5012. sizeof(post_status_text));
  5013. } else {
  5014. s_copy(post_status_text, msg, sizeof(post_status_text));
  5015. }
  5016. post_status_ttl = 12000;
  5017. }
  5018. s_append(out, &o, "browser image stats\n", sizeof(out));
  5019. s_append(out, &o, "n=", sizeof(out));
  5020. s_append_dec(out, &o, (unsigned int)img_stat_n, sizeof(out));
  5021. s_append(out, &o, " wall=", sizeof(out));
  5022. s_append_dec(out, &o, img_stat_wall, sizeof(out));
  5023. s_append(out, &o, " net=", sizeof(out));
  5024. s_append_dec(out, &o, img_stat_net, sizeof(out));
  5025. s_append(out, &o, " open=", sizeof(out));
  5026. s_append_dec(out, &o, img_stat_open, sizeof(out));
  5027. s_append(out, &o, " first=", sizeof(out));
  5028. s_append_dec(out, &o, img_stat_first, sizeof(out));
  5029. s_append(out, &o, " io=", sizeof(out));
  5030. s_append_dec(out, &o, img_stat_io, sizeof(out));
  5031. s_append(out, &o, " dec=", sizeof(out));
  5032. s_append_dec(out, &o, img_stat_dec, sizeof(out));
  5033. s_append(out, &o, " scale=", sizeof(out));
  5034. s_append_dec(out, &o, img_stat_scale, sizeof(out));
  5035. s_append(out, &o, " paint=", sizeof(out));
  5036. s_append_dec(out, &o, img_stat_paint, sizeof(out));
  5037. s_append(out, &o, " reflow=", sizeof(out));
  5038. s_append_dec(out, &o, img_stat_reflow, sizeof(out));
  5039. s_append(out, &o, " bytes=", sizeof(out));
  5040. s_append_dec(out, &o, img_stat_bytes, sizeof(out));
  5041. s_append(out, &o, "\nurl bytes open first total io dec scale native bitmap\n",
  5042. sizeof(out));
  5043. s_append(out, &o, img_stat_log, sizeof(out));
  5044. u_syscall3(SYS_WRITE_FILE, (int)"/share/IMGSTAT", (int)out,
  5045. (int)s_len(out));
  5046. }
  5047. static void preload_step(void)
  5048. {
  5049. int i;
  5050. unsigned int t0;
  5051. if (!preload_active)
  5052. return;
  5053. if (cancel_fetch || pending_action) {
  5054. preload_active = 0;
  5055. preload_pending = 0;
  5056. fetch_workers_cancel_busy();
  5057. return;
  5058. }
  5059. preload_fill_jobs();
  5060. /* Decode completed images in a short batch instead of one per pass.
  5061. * A pass used to decode one image and then sleep 10 ms, so a page of
  5062. * small icons trickled in at the decode rate. The budget keeps a
  5063. * single huge JPEG from monopolising the UI while small images
  5064. * finish together. */
  5065. t0 = u_ticks_ms();
  5066. for (i = 0; i < FETCH_WORKERS; i++) {
  5067. if (!fetch_workers[i].busy)
  5068. continue;
  5069. if (preload_finish_worker(&fetch_workers[i]) &&
  5070. u_ticks_ms() - t0 >= BR_IMG_DECODE_BUDGET_MS)
  5071. break;
  5072. }
  5073. if (preload_active && preload_node >= doc.nnode &&
  5074. preload_active_jobs() == 0) {
  5075. preload_active = 0;
  5076. if (preload_pending)
  5077. preload_scroll = page_scroll.offset;
  5078. else
  5079. preload_pending = 0;
  5080. /* Keep the now idle helpers and their connections; a later
  5081. * navigation reuses them. They exit after ten idle seconds,
  5082. * and losing window focus stops them at once. */
  5083. if (img_repaint_pending) {
  5084. img_repaint_pending = 0;
  5085. ngui_invalidate(&ui);
  5086. }
  5087. img_stats_report();
  5088. set_status(post_status_text, post_status_error, post_status_ttl);
  5089. ngui_invalidate(&ui);
  5090. }
  5091. }
  5092. /* Set by navigate() when it turned a typed bare host into https://; the next
  5093. * load_page() consumes it and may retry over http. */
  5094. static int nav_https_upgraded;
  5095. /* Errors that mean "https is not served here" rather than "the site is
  5096. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  5097. static int https_fallback_error(int e)
  5098. {
  5099. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  5100. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  5101. e == UHTTP_ERR_RESET;
  5102. }
  5103. static void history_push(const char *url)
  5104. {
  5105. if (!url || !url[0])
  5106. return;
  5107. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  5108. s_eq(history[hist_pos], url))
  5109. return;
  5110. if (hist_len > 0 && hist_pos + 1 < hist_len)
  5111. hist_len = hist_pos + 1;
  5112. if (hist_len < BR_HISTORY) {
  5113. s_copy(history[hist_len], url, BR_URL_MAX);
  5114. hist_pos = hist_len;
  5115. hist_len++;
  5116. } else {
  5117. int i;
  5118. for (i = 1; i < BR_HISTORY; i++)
  5119. s_copy(history[i - 1], history[i], BR_URL_MAX);
  5120. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  5121. hist_pos = BR_HISTORY - 1;
  5122. }
  5123. }
  5124. static void load_page(const char *url, int local, int push)
  5125. {
  5126. unsigned char *body = 0;
  5127. unsigned int len = 0;
  5128. int truncated = 0;
  5129. struct img_info image_info;
  5130. char ctype[64];
  5131. char final[BR_URL_MAX];
  5132. char err[80];
  5133. const char *detail = 0;
  5134. const char *post = pending_post_is ? pending_post : 0;
  5135. unsigned int post_len = pending_post_len;
  5136. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  5137. /* Phase timings for the status line: where a slow load spends it. */
  5138. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  5139. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  5140. int upgraded = nav_https_upgraded;
  5141. int retried = 0;
  5142. int rv;
  5143. nav_https_upgraded = 0;
  5144. final[0] = '\0';
  5145. pending_post_len = 0;
  5146. pending_post_is = 0;
  5147. cancel_fetch = 0;
  5148. preload_active = 0;
  5149. preload_pending = 0;
  5150. fetch_workers_prepare_nav(url);
  5151. js_browser_stop();
  5152. js_last_status[0] = '\0';
  5153. js_last_error = 0;
  5154. heap_clear();
  5155. image_reset();
  5156. form_reset_state();
  5157. layout_valid = 0;
  5158. page_scroll.offset = 0;
  5159. page_scroll.dragging = 0;
  5160. page_title[0] = '\0';
  5161. page_loading = 1;
  5162. page_is_local = local;
  5163. s_copy(page_url, url, sizeof(page_url));
  5164. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5165. url_in.len = s_len(url_in.text);
  5166. url_in.cursor = url_in.len;
  5167. url_in.scroll = 0;
  5168. ngui_set_focus(&ui, 0);
  5169. if (final[0])
  5170. final[0] = '\0';
  5171. if (push)
  5172. history_push(url);
  5173. set_status("Loading...", 0, 0);
  5174. ngui_invalidate(&ui);
  5175. /* heap_clear() detaches the fonts, so attach them again before the
  5176. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  5177. if (heap_start() != 0) {
  5178. show_error("Out of memory", "Cannot allocate the page buffer");
  5179. return;
  5180. }
  5181. br_parse_plain(&doc, "", 0); /* blank while loading */
  5182. ngui_font_attach(&ui);
  5183. redraw_now();
  5184. browser_rules_alloc();
  5185. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5186. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  5187. &truncated, post, post_len);
  5188. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  5189. fetch_last_error == UHTTP_ERR_DNS) {
  5190. /* A busy previous page can leave the receiver ring full just
  5191. * long enough to lose a DNS reply. Tear the old helpers down
  5192. * and try once more before giving up. */
  5193. retried = 1;
  5194. fetch_workers_stop_all();
  5195. u_sleep_ms(500);
  5196. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5197. sizeof(ctype), final, sizeof(final), err,
  5198. sizeof(err), &truncated, post, post_len);
  5199. }
  5200. if (rv == FETCH_ABORT)
  5201. return;
  5202. t_fetch = u_ticks_ms() - t_start;
  5203. /* Capture the page timing before CSS/script/image fetches overwrite the
  5204. * shared fetch_meta block. */
  5205. if (rv == 0 && !local) {
  5206. page_open_ms = fetch_meta.open_ms;
  5207. page_first_ms = fetch_meta.first_ms;
  5208. page_total_ms = fetch_meta.total_ms;
  5209. }
  5210. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  5211. https_fallback_error(fetch_last_error)) {
  5212. char http_url[BR_URL_MAX];
  5213. unsigned int n = 0;
  5214. s_append(http_url, &n, "http://", sizeof(http_url));
  5215. s_append(http_url, &n, url + 8, sizeof(http_url));
  5216. /* Replace the https entry instead of adding a second one. */
  5217. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  5218. s_eq(history[hist_pos], url))
  5219. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  5220. load_page(http_url, 0, 0);
  5221. return;
  5222. }
  5223. if (rv != 0) {
  5224. detail = err;
  5225. show_error("Cannot load this page", detail);
  5226. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5227. url_in.len = s_len(url_in.text);
  5228. url_in.cursor = url_in.len;
  5229. url_in.scroll = 0;
  5230. return;
  5231. }
  5232. if (!local)
  5233. origin_cache_learn(url, final[0] ? final : url);
  5234. page_is_local = local;
  5235. if (final[0]) {
  5236. s_copy(page_url, final, sizeof(page_url));
  5237. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5238. url_in.len = s_len(url_in.text);
  5239. url_in.cursor = url_in.len;
  5240. url_in.scroll = 0;
  5241. }
  5242. if (contains_ci(ctype, "text/plain")) {
  5243. br_parse_plain(&doc, (const char *)body, len);
  5244. } else if (contains_ci(ctype, "image/") ||
  5245. (!contains_ci(ctype, "text/html") &&
  5246. img_sniff(body, len, &image_info) == 0)) {
  5247. unsigned int node = br_parse_image_doc(&doc, page_url);
  5248. if (node)
  5249. decode_direct_image(body, len, node);
  5250. s_copy(page_title, "Image", sizeof(page_title));
  5251. } else {
  5252. br_set_viewport(ui.w);
  5253. t_mark = u_ticks_ms();
  5254. br_parse(&doc, (const char *)body, len);
  5255. t_parse = u_ticks_ms() - t_mark;
  5256. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  5257. sizeof(page_title));
  5258. t_mark = u_ticks_ms();
  5259. if (load_stylesheets() == FETCH_ABORT)
  5260. return;
  5261. t_css = u_ticks_ms() - t_mark;
  5262. if (pending_action)
  5263. return;
  5264. }
  5265. preload_begin();
  5266. page_loading = 0;
  5267. hist_visit(page_url, page_title);
  5268. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5269. url_in.len = s_len(url_in.text);
  5270. url_in.cursor = url_in.len;
  5271. url_in.scroll = 0;
  5272. ngui_set_focus(&ui, 0);
  5273. /* Paint the parsed page before fetching/running scripts. A slow
  5274. * remote <script src> then does not hide the page behind the loading
  5275. * screen; the fetch helper pumps this UI while it waits. */
  5276. set_status("Loading scripts...", 0, 0);
  5277. t_mark = u_ticks_ms();
  5278. redraw_now();
  5279. t_paint = u_ticks_ms() - t_mark;
  5280. /* Start one image download before the scripts. The other workers
  5281. * fetch the external script bodies in parallel, and the remaining
  5282. * images start as soon as the script phase ends. */
  5283. preload_max_jobs = 1;
  5284. preload_fill_jobs();
  5285. preload_wait = 0;
  5286. t_mark = u_ticks_ms();
  5287. run_page_scripts();
  5288. t_js = u_ticks_ms() - t_mark;
  5289. preload_max_jobs = FETCH_WORKERS;
  5290. if (pending_action)
  5291. return;
  5292. post_status_text[0] = '\0';
  5293. post_status_error = 0;
  5294. post_status_ttl = 0;
  5295. if (js_last_status[0]) {
  5296. s_copy(post_status_text, js_last_status,
  5297. sizeof(post_status_text));
  5298. post_status_error = js_last_error;
  5299. post_status_ttl = 8000;
  5300. } else if (truncated) {
  5301. s_copy(post_status_text, "Page truncated at the buffer limit",
  5302. sizeof(post_status_text));
  5303. post_status_ttl = 6000;
  5304. } else if (doc.truncated) {
  5305. s_copy(post_status_text, "Page truncated by the parser",
  5306. sizeof(post_status_text));
  5307. post_status_ttl = 6000;
  5308. } else if (page_total_ms) {
  5309. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  5310. * paint 220, js 1750" -- the phases of this load. */
  5311. unsigned int n = 0;
  5312. static const char *const names[] = {
  5313. ", parse ", ", css ", ", paint ", ", js "
  5314. };
  5315. unsigned int vals[4];
  5316. int k;
  5317. vals[0] = t_parse;
  5318. vals[1] = t_css;
  5319. vals[2] = t_paint;
  5320. vals[3] = t_js;
  5321. (void)page_first_ms;
  5322. if (starts_with(page_url, "https://"))
  5323. s_append(post_status_text, &n,
  5324. "HTTPS (not verified), ",
  5325. sizeof(post_status_text));
  5326. s_append(post_status_text, &n, "Loaded in ",
  5327. sizeof(post_status_text));
  5328. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  5329. sizeof(post_status_text));
  5330. s_append(post_status_text, &n, " ms: page ",
  5331. sizeof(post_status_text));
  5332. s_append_dec(post_status_text, &n, t_fetch,
  5333. sizeof(post_status_text));
  5334. s_append(post_status_text, &n, " (headers ",
  5335. sizeof(post_status_text));
  5336. s_append_dec(post_status_text, &n, page_open_ms,
  5337. sizeof(post_status_text));
  5338. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  5339. for (k = 0; k < 4; k++) {
  5340. s_append(post_status_text, &n, names[k],
  5341. sizeof(post_status_text));
  5342. s_append_dec(post_status_text, &n, vals[k],
  5343. sizeof(post_status_text));
  5344. }
  5345. post_status_ttl = 12000;
  5346. } else if (starts_with(page_url, "https://")) {
  5347. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  5348. sizeof(post_status_text));
  5349. post_status_ttl = 6000;
  5350. }
  5351. set_status(post_status_text, post_status_error, post_status_ttl);
  5352. ngui_invalidate(&ui);
  5353. }
  5354. static void load_home(int push)
  5355. {
  5356. pending_post_len = 0;
  5357. pending_post_is = 0;
  5358. cancel_fetch = 0;
  5359. preload_active = 0;
  5360. preload_pending = 0;
  5361. js_browser_stop();
  5362. js_last_status[0] = '\0';
  5363. js_last_error = 0;
  5364. heap_clear();
  5365. image_reset();
  5366. form_reset_state();
  5367. layout_valid = 0;
  5368. page_scroll.offset = 0;
  5369. page_scroll.dragging = 0;
  5370. page_loading = 1;
  5371. page_is_local = 0;
  5372. s_copy(page_url, "about:home", sizeof(page_url));
  5373. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5374. url_in.len = s_len(url_in.text);
  5375. url_in.cursor = url_in.len;
  5376. url_in.scroll = 0;
  5377. ngui_set_focus(&ui, 0);
  5378. if (push)
  5379. history_push(page_url);
  5380. ngui_invalidate(&ui);
  5381. /* See load_page(): reattach the fonts before the first redraw. */
  5382. if (heap_start() != 0) {
  5383. show_error("Out of memory", "Cannot allocate the browser heap");
  5384. return;
  5385. }
  5386. br_parse_plain(&doc, "", 0);
  5387. ngui_font_attach(&ui);
  5388. redraw_now();
  5389. browser_rules_alloc();
  5390. {
  5391. static const char home[] =
  5392. "<html><head><title>NebOS Browser</title><style>"
  5393. "body { margin: 10px; color: #e4e6f0; }"
  5394. "h1 { color: #7fb0ff; }"
  5395. ".box { background-color: #262b3a; margin: 12px; "
  5396. "padding: 10px; }"
  5397. "a { color: #7fb0ff; }"
  5398. "pre { background-color: #32384a; }"
  5399. "</style></head><body>"
  5400. "<h1>NebOS Browser</h1>"
  5401. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  5402. "shared HTTP client and the image library.</p>"
  5403. "<div class=\"box\"><b>Try:</b>"
  5404. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  5405. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  5406. "<li><a href=\"/floppy1/JS.HTM\">/"
  5407. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  5408. "<li><a href=\"http://10.0.2.2:8000/\">"
  5409. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  5410. "<li><a href=\"https://example.com/\">"
  5411. "https://example.com/</a> (TLS, not verified)</li>"
  5412. "</ul></div>"
  5413. "<p>Type a URL in the bar above. Esc closes the "
  5414. "window, Ctrl+L focuses the address bar.</p>"
  5415. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  5416. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  5417. "</body></html>";
  5418. br_set_viewport(ui.w);
  5419. br_parse(&doc, home, sizeof(home) - 1);
  5420. br_parse_inline_css(&doc);
  5421. br_reset_styles(&doc);
  5422. s_copy(page_title, doc.title, sizeof(page_title));
  5423. }
  5424. post_status_text[0] = '\0';
  5425. post_status_error = 0;
  5426. post_status_ttl = 0;
  5427. page_loading = 0;
  5428. set_status("", 0, 0);
  5429. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5430. url_in.len = s_len(url_in.text);
  5431. url_in.cursor = url_in.len;
  5432. url_in.scroll = 0;
  5433. ngui_set_focus(&ui, 0);
  5434. ngui_invalidate(&ui);
  5435. }
  5436. /* Extensions the browser opens from the local filesystem. A dotted input
  5437. * with one of these still resolves relative to the cwd. */
  5438. static int local_file_ext(const char *s)
  5439. {
  5440. static const char *const exts[] = {
  5441. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  5442. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  5443. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  5444. "cfg", "conf", 0
  5445. };
  5446. unsigned int i = 0, start = 0, len = 0, e;
  5447. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  5448. s[i] != '#') {
  5449. if (s[i] == '.') {
  5450. start = i + 1;
  5451. len = 0;
  5452. } else if (start) {
  5453. len++;
  5454. }
  5455. i++;
  5456. }
  5457. if (!len)
  5458. return 0;
  5459. for (e = 0; exts[e]; e++) {
  5460. const char *x = exts[e];
  5461. unsigned int xn = s_len(x), k;
  5462. if (xn != len)
  5463. continue;
  5464. for (k = 0; k < len; k++) {
  5465. char a = s[start + k];
  5466. if (a >= 'A' && a <= 'Z')
  5467. a = (char)(a - 'A' + 'a');
  5468. if (a != x[k])
  5469. break;
  5470. }
  5471. if (k == len)
  5472. return 1;
  5473. }
  5474. return 0;
  5475. }
  5476. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  5477. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  5478. * Enter to the first network request. */
  5479. static int looks_like_host(const char *s)
  5480. {
  5481. unsigned int i = 0;
  5482. int dot = 0;
  5483. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  5484. s[i] != ':') {
  5485. char c = s[i];
  5486. if (c == '.') {
  5487. dot = 1;
  5488. } else if (!((c >= 'a' && c <= 'z') ||
  5489. (c >= 'A' && c <= 'Z') ||
  5490. (c >= '0' && c <= '9') ||
  5491. c == '-' || c == '_')) {
  5492. return 0;
  5493. }
  5494. i++;
  5495. }
  5496. return dot && i > 0 && !local_file_ext(s);
  5497. }
  5498. static void load_remote(const char *url, int push)
  5499. {
  5500. char canon[BR_URL_MAX];
  5501. s_copy(canon, url, sizeof(canon));
  5502. origin_cache_apply(canon, sizeof(canon));
  5503. load_page(canon, 0, push);
  5504. }
  5505. static void navigate(const char *input, int push)
  5506. {
  5507. char target[BR_URL_MAX];
  5508. char *t;
  5509. if (!input)
  5510. return;
  5511. s_copy(target, input, sizeof(target));
  5512. t = trim(target);
  5513. if (!t[0])
  5514. return;
  5515. if (s_eq(t, "about:home")) {
  5516. load_home(push);
  5517. return;
  5518. }
  5519. if (starts_with(t, "file://")) {
  5520. make_abs_local(t + 7, target, sizeof(target));
  5521. load_page(target, 1, push);
  5522. return;
  5523. }
  5524. if (is_http(t)) {
  5525. load_remote(t, push);
  5526. return;
  5527. }
  5528. if (t[0] == '/') {
  5529. make_abs_local(t, target, sizeof(target));
  5530. load_page(target, 1, push);
  5531. return;
  5532. }
  5533. if (!looks_like_host(t)) {
  5534. struct sys_stat st;
  5535. if (u_stat(t, &st) == 0 && !st.is_dir) {
  5536. make_abs_local(t, target, sizeof(target));
  5537. load_page(target, 1, push);
  5538. return;
  5539. }
  5540. }
  5541. {
  5542. /* A typed bare host tries https first: nearly every site
  5543. * redirects http -> https anyway, and that hop costs a whole
  5544. * extra connection. load_page() falls back to http when the
  5545. * https connection itself fails. */
  5546. char with_scheme[BR_URL_MAX];
  5547. unsigned int n = 0;
  5548. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  5549. s_append(with_scheme, &n, t, sizeof(with_scheme));
  5550. nav_https_upgraded = 1;
  5551. load_remote(with_scheme, push);
  5552. }
  5553. }
  5554. /* ---- layout ---- */
  5555. static struct ufont_face *style_face(const struct br_style *st)
  5556. {
  5557. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  5558. return font_faces[st->font_face - 1];
  5559. return 0;
  5560. }
  5561. static struct ufont_face *run_face(const struct lay_run *r)
  5562. {
  5563. if (r->font_face && r->font_face <= BR_MAX_FACES)
  5564. return font_faces[r->font_face - 1];
  5565. return 0;
  5566. }
  5567. static unsigned int face_text_width(struct ngui *gui,
  5568. const struct br_style *st,
  5569. const char *s, unsigned int n)
  5570. {
  5571. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  5572. st->bold, st->italic, st->mono);
  5573. }
  5574. static int face_line_height(struct ngui *gui, const struct br_style *st)
  5575. {
  5576. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  5577. st->mono);
  5578. }
  5579. static unsigned int run_text_width(struct ngui *gui,
  5580. const struct lay_run *r,
  5581. const char *s, unsigned int n)
  5582. {
  5583. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  5584. r->bold, r->italic, r->mono);
  5585. }
  5586. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  5587. {
  5588. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  5589. r->mono);
  5590. }
  5591. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  5592. {
  5593. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  5594. }
  5595. static struct br_style base_style(void)
  5596. {
  5597. struct br_style s = { 0 };
  5598. s.color = ui.theme.text;
  5599. s.bg = ui.theme.bg;
  5600. s.has_bg = 0;
  5601. for (int i = 0; i < 4; i++) {
  5602. s.border_c[i] = 0;
  5603. s.border_w[i] = 0;
  5604. s.border_s[i] = BR_BORDER_SOLID;
  5605. }
  5606. s.font_px = 16;
  5607. s.bold = 0;
  5608. s.italic = 0;
  5609. s.mono = 0;
  5610. s.underline = 0;
  5611. s.strike = 0;
  5612. s.overline = 0;
  5613. s.align = BR_ALIGN_LEFT;
  5614. s.display = BR_DISPLAY_BLOCK;
  5615. s.no_bullet = 0;
  5616. s.list_style = BR_LIST_AUTO;
  5617. s.uppercase = 0;
  5618. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  5619. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  5620. s.width = s.max_width = s.min_width = 0;
  5621. s.height = s.min_height = s.max_height = 0;
  5622. s.box_sizing = 0;
  5623. s.ml_auto = s.mr_auto = 0;
  5624. s.line_h_pct = 0;
  5625. s.line_h_px = 0;
  5626. s.mt = s.mb = s.ml = s.mr = 0;
  5627. s.pt = s.pb = s.pl = s.pr = 0;
  5628. return s;
  5629. }
  5630. /* The style node 0's children inherit. Node 0 is the first parsed node:
  5631. * a minified page that starts `<!doctype html><html ...>` makes it the
  5632. * <html> element itself, and the layout walks only its children, so its
  5633. * own cascade (html { color; font } -- Docusaurus/Infima put the page
  5634. * colour and font there) used to be skipped and the theme defaults showed
  5635. * through. Only inherited properties are taken: the root's box (margins,
  5636. * display, background) is not a container style for its children here. */
  5637. static struct br_style root_style(void)
  5638. {
  5639. struct br_style base = base_style(), st;
  5640. if (!doc.nnode || doc.nodes[doc.root].type != BR_NODE_ELEM ||
  5641. doc.nodes[doc.root].tag != BR_TAG_HTML)
  5642. return base;
  5643. br_style_for(&doc, doc.root, &base, &st);
  5644. base.color = st.color;
  5645. base.font_px = st.font_px;
  5646. base.bold = st.bold;
  5647. base.italic = st.italic;
  5648. base.mono = st.mono;
  5649. base.font_face = st.font_face;
  5650. base.align = st.align;
  5651. base.line_h_pct = st.line_h_pct;
  5652. base.line_h_px = st.line_h_px;
  5653. base.nowrap = st.nowrap;
  5654. base.uppercase = st.uppercase;
  5655. base.cursor = st.cursor;
  5656. base.vis_hidden = st.vis_hidden;
  5657. base.fill_mode = st.fill_mode;
  5658. base.fill = st.fill;
  5659. base.stroke_mode = st.stroke_mode;
  5660. base.stroke = st.stroke;
  5661. base.stroke_w = st.stroke_w;
  5662. base.fill_evenodd = st.fill_evenodd;
  5663. return base;
  5664. }
  5665. /* Resolve a margin/padding raw value. Percentages use the containing
  5666. * block width for all four sides, as CSS specifies. */
  5667. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  5668. {
  5669. if (unit == 1)
  5670. return base * v / 10000;
  5671. if (unit == 2)
  5672. return st->font_px * v / 100;
  5673. if (unit == 3)
  5674. return (int)br_root_font_px() * v / 100;
  5675. if (unit == 4)
  5676. return 0;
  5677. return v;
  5678. }
  5679. static int mp_px(const struct br_style *st, int side, int base)
  5680. {
  5681. int raw;
  5682. switch (side) {
  5683. case 0: raw = st->mt; break;
  5684. case 1: raw = st->mr; break;
  5685. case 2: raw = st->mb; break;
  5686. case 3: raw = st->ml; break;
  5687. case 4: raw = st->pt; break;
  5688. case 5: raw = st->pr; break;
  5689. case 6: raw = st->pb; break;
  5690. default: raw = st->pl; break;
  5691. }
  5692. if (st->mp_unit[side] == 5)
  5693. return base * raw / 100 + st->mp_calc_px[side];
  5694. return css_mp_px(st, raw, st->mp_unit[side], base);
  5695. }
  5696. static int style_width_px(const struct br_style *st, int base)
  5697. {
  5698. if (st->width_kind == 1)
  5699. return st->width;
  5700. if (st->width_kind == 2)
  5701. return base * (int)st->width / 100;
  5702. if (st->width_kind == 3)
  5703. return base * st->width_calc_pct / 100 + st->width_calc_px;
  5704. return 0;
  5705. }
  5706. static int style_height_px(const struct br_style *st, int base)
  5707. {
  5708. if (st->height_kind == 1)
  5709. return st->height;
  5710. if (st->height_kind == 2)
  5711. return base * (int)st->height / 100;
  5712. if (st->height_kind == 3)
  5713. return base * st->height_calc_pct / 100 + st->height_calc_px;
  5714. return 0;
  5715. }
  5716. static int css_size(unsigned char kind, int val, int base)
  5717. {
  5718. if (kind == 1)
  5719. return val;
  5720. if (kind == 2)
  5721. return base * val / 100;
  5722. return -1;
  5723. }
  5724. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  5725. int thick, int horizontal, unsigned short color,
  5726. unsigned char style)
  5727. {
  5728. int pos;
  5729. if (len <= 0 || thick <= 0)
  5730. return;
  5731. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  5732. if (horizontal)
  5733. ngui_fill_rect(ui, (struct ngui_rect){
  5734. x, y, len, thick}, color);
  5735. else
  5736. ngui_fill_rect(ui, (struct ngui_rect){
  5737. x, y, thick, len}, color);
  5738. return;
  5739. }
  5740. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  5741. int seg = len - pos;
  5742. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  5743. seg = style == BR_BORDER_DASHED ? 4 : 2;
  5744. if (horizontal)
  5745. ngui_fill_rect(ui, (struct ngui_rect){
  5746. x + pos, y, seg, thick}, color);
  5747. else
  5748. ngui_fill_rect(ui, (struct ngui_rect){
  5749. x, y + pos, thick, seg}, color);
  5750. }
  5751. }
  5752. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  5753. const struct br_style *st)
  5754. {
  5755. int top = st->border_w[0], right = st->border_w[1];
  5756. int bottom = st->border_w[2], left = st->border_w[3];
  5757. if (r.w <= 0 || r.h <= 0)
  5758. return;
  5759. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  5760. int i;
  5761. for (i = 0; i < 4; i++)
  5762. if (st->border_w[i] && !st->border_t[i]) {
  5763. ngui_fill_rect(ui, r, st->border_c[i]);
  5764. break;
  5765. }
  5766. return;
  5767. }
  5768. if (top && !st->border_t[0])
  5769. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  5770. st->border_c[0], st->border_s[0]);
  5771. if (bottom && !st->border_t[2])
  5772. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  5773. st->border_c[2], st->border_s[2]);
  5774. if (left && !st->border_t[3])
  5775. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  5776. left, 0, st->border_c[3], st->border_s[3]);
  5777. if (right && !st->border_t[1])
  5778. draw_border_side(ui, r.x + r.w - right, r.y + top,
  5779. r.h - top - bottom, right, 0,
  5780. st->border_c[1], st->border_s[1]);
  5781. }
  5782. static void transform_origin(const struct br_style *st, int w, int h,
  5783. int *ox, int *oy)
  5784. {
  5785. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  5786. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  5787. }
  5788. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  5789. unsigned int a)
  5790. {
  5791. unsigned int dr, dg, db, sr, sg, sb;
  5792. if (a >= 255)
  5793. return s;
  5794. dr = (d >> 11) & 31;
  5795. dg = (d >> 5) & 63;
  5796. db = d & 31;
  5797. sr = (s >> 11) & 31;
  5798. sg = (s >> 5) & 63;
  5799. sb = s & 31;
  5800. dr = (dr * (255 - a) + sr * a) / 255;
  5801. dg = (dg * (255 - a) + sg * a) / 255;
  5802. db = (db * (255 - a) + sb * a) / 255;
  5803. return (unsigned short)((dr << 11) | (dg << 5) | db);
  5804. }
  5805. /* Paint a solid box through scale()/rotate() around transform-origin. This
  5806. * transforms the element's own background box; text and descendants keep
  5807. * their layout (documented approximation). */
  5808. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  5809. unsigned short color,
  5810. const struct br_style *st)
  5811. {
  5812. double sx = st->scale_x / 100.0;
  5813. double sy = st->scale_y / 100.0;
  5814. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  5815. double c = cos(th), sn = sin(th);
  5816. int ox, oy, minx, miny, maxx, maxy, x, y;
  5817. double ax, ay;
  5818. double px[4], py[4];
  5819. int cx1, cy1, cx2, cy2, i;
  5820. if (sx == 0)
  5821. sx = 0.01;
  5822. if (sy == 0)
  5823. sy = 0.01;
  5824. transform_origin(st, box.w, box.h, &ox, &oy);
  5825. ax = box.x + ox;
  5826. ay = box.y + oy;
  5827. px[0] = -ox; py[0] = -oy;
  5828. px[1] = box.w - ox; py[1] = -oy;
  5829. px[2] = box.w - ox; py[2] = box.h - oy;
  5830. px[3] = -ox; py[3] = box.h - oy;
  5831. minx = miny = 1000000;
  5832. maxx = maxy = -1000000;
  5833. for (i = 0; i < 4; i++) {
  5834. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  5835. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  5836. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5837. if (dx < minx) minx = dx;
  5838. if (dx > maxx) maxx = dx;
  5839. if (dy < miny) miny = dy;
  5840. if (dy > maxy) maxy = dy;
  5841. }
  5842. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5843. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5844. cx2 = page_rect.x + page_rect.w - 12;
  5845. cy2 = page_rect.y + page_rect.h;
  5846. if (cx2 > gui->w) cx2 = gui->w;
  5847. if (cy2 > gui->h) cy2 = gui->h;
  5848. if (minx < cx1) minx = cx1;
  5849. if (miny < cy1) miny = cy1;
  5850. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5851. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5852. for (y = miny; y <= maxy; y++) {
  5853. for (x = minx; x <= maxx; x++) {
  5854. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  5855. double rx = dx * c + dy * sn;
  5856. double ry = -dx * sn + dy * c;
  5857. double bx = rx / sx + ox;
  5858. double by = ry / sy + oy;
  5859. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  5860. gui->px[y * gui->w + x] = color;
  5861. }
  5862. }
  5863. }
  5864. static void draw_image_transformed(struct ngui *gui,
  5865. const struct img_image *im,
  5866. int x, int y, int w, int h,
  5867. int sx100, int sy100, int rot100,
  5868. int origin_x, int origin_y,
  5869. int origin_x_kind, int origin_y_kind)
  5870. {
  5871. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  5872. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  5873. double c = cos(th), sn = sin(th);
  5874. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  5875. double ax, ay;
  5876. double bx[4], by[4];
  5877. int cx1, cy1, cx2, cy2;
  5878. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  5879. return;
  5880. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  5881. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  5882. ax = x + ox;
  5883. ay = y + oy;
  5884. bx[0] = -ox; by[0] = -oy;
  5885. bx[1] = w - ox; by[1] = -oy;
  5886. bx[2] = w - ox; by[2] = h - oy;
  5887. bx[3] = -ox; by[3] = h - oy;
  5888. minx = miny = 1000000;
  5889. maxx = maxy = -1000000;
  5890. for (i = 0; i < 4; i++) {
  5891. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  5892. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  5893. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5894. if (dx < minx) minx = dx;
  5895. if (dx > maxx) maxx = dx;
  5896. if (dy < miny) miny = dy;
  5897. if (dy > maxy) maxy = dy;
  5898. }
  5899. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5900. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5901. cx2 = page_rect.x + page_rect.w - 12;
  5902. cy2 = page_rect.y + page_rect.h;
  5903. if (cx2 > gui->w) cx2 = gui->w;
  5904. if (cy2 > gui->h) cy2 = gui->h;
  5905. if (minx < cx1) minx = cx1;
  5906. if (miny < cy1) miny = cy1;
  5907. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5908. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5909. for (py = miny; py <= maxy; py++) {
  5910. for (px = minx; px <= maxx; px++) {
  5911. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  5912. double rx = dx * c + dy * sn;
  5913. double ry = -dx * sn + dy * c;
  5914. double fx = rx / sx + ox;
  5915. double fy = ry / sy + oy;
  5916. int ix, iy;
  5917. unsigned int si, a;
  5918. unsigned short src;
  5919. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  5920. continue;
  5921. ix = (int)(fx * (double)im->w / w);
  5922. iy = (int)(fy * (double)im->h / h);
  5923. if (ix < 0 || ix >= (int)im->w ||
  5924. iy < 0 || iy >= (int)im->h)
  5925. continue;
  5926. si = (unsigned int)iy * im->w + (unsigned int)ix;
  5927. src = im->px[si];
  5928. a = im->alpha ? im->alpha[si] : 255;
  5929. gui->px[py * gui->w + px] =
  5930. a >= 255 ? src :
  5931. blend_rgb565(gui->px[py * gui->w + px],
  5932. src, a);
  5933. }
  5934. }
  5935. }
  5936. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5937. unsigned int node, const struct br_style *st);
  5938. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  5939. * first and every pixel outside a corner's arc is restored afterwards. */
  5940. #define BG_ROUND_MAX 64
  5941. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  5942. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  5943. unsigned int node, const struct br_style *st,
  5944. int rtl, int rtr, int rbr, int rbl)
  5945. {
  5946. struct ngui *ui = l->ui;
  5947. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  5948. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  5949. if (ui->nclip > 0)
  5950. clip = ui->clip[ui->nclip - 1];
  5951. for (c = 0; c < 4; c++) {
  5952. if (r[c] > BG_ROUND_MAX)
  5953. r[c] = BG_ROUND_MAX;
  5954. if (r[c] > box.w / 2)
  5955. r[c] = box.w / 2;
  5956. if (r[c] > box.h / 2)
  5957. r[c] = box.h / 2;
  5958. }
  5959. for (c = 0; c < 4; c++) {
  5960. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5961. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5962. for (dy = 0; dy < r[c]; dy++)
  5963. for (dx = 0; dx < r[c]; dx++) {
  5964. int px = ox + dx, py = oy + dy;
  5965. if (px >= clip.x && py >= clip.y &&
  5966. px < clip.x + clip.w && py < clip.y + clip.h)
  5967. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  5968. ui->px[py * ui->w + px];
  5969. }
  5970. }
  5971. draw_bg_image(l, box, node, st);
  5972. for (c = 0; c < 4; c++) {
  5973. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5974. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5975. /* arc centre, in corner-square coordinates */
  5976. int cx = (c == 1 || c == 2) ? 0 : r[c];
  5977. int cy = (c >= 2) ? 0 : r[c];
  5978. for (dy = 0; dy < r[c]; dy++)
  5979. for (dx = 0; dx < r[c]; dx++) {
  5980. int px = ox + dx, py = oy + dy;
  5981. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  5982. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  5983. continue;
  5984. if (px >= clip.x && py >= clip.y &&
  5985. px < clip.x + clip.w && py < clip.y + clip.h)
  5986. ui->px[py * ui->w + px] =
  5987. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  5988. }
  5989. }
  5990. }
  5991. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5992. unsigned int node, const struct br_style *st)
  5993. {
  5994. struct br_image *bi;
  5995. struct img_blit b;
  5996. int tw, th, x, y, rep_x, rep_y, posx, posy;
  5997. unsigned int scale = 65536;
  5998. int legacy, tiles = 0, rows = 0;
  5999. int cx1, cy1, cx2, cy2;
  6000. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  6001. return;
  6002. if (doc.nodes[node].bg_img_index < 0 ||
  6003. doc.nodes[node].bg_img_index >= image_count)
  6004. return;
  6005. bi = &images[doc.nodes[node].bg_img_index];
  6006. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  6007. return;
  6008. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  6009. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  6010. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  6011. if (legacy) {
  6012. scale = ((unsigned int)box.w << 16) / bi->img.w;
  6013. tw = box.w;
  6014. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6015. x = box.x;
  6016. y = box.y;
  6017. rep_x = rep_y = 0;
  6018. } else {
  6019. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  6020. unsigned int sx = ((unsigned int)box.w << 16) /
  6021. bi->img.w;
  6022. unsigned int sy = ((unsigned int)box.h << 16) /
  6023. bi->img.h;
  6024. scale = st->bg_size_kind == 3 ?
  6025. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  6026. } else if (st->bg_size_kind == 1 ||
  6027. st->bg_size_kind == 2) {
  6028. int w = st->bg_size_w;
  6029. int h = st->bg_size_h;
  6030. if (st->bg_size_kind == 2) {
  6031. if (w)
  6032. w = box.w * w / 100;
  6033. if (h)
  6034. h = box.h * h / 100;
  6035. }
  6036. if (w)
  6037. scale = ((unsigned int)w << 16) / bi->img.w;
  6038. else if (h)
  6039. scale = ((unsigned int)h << 16) / bi->img.h;
  6040. }
  6041. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  6042. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6043. if (tw < 1)
  6044. tw = 1;
  6045. if (th < 1)
  6046. th = 1;
  6047. posx = st->bg_pos_x_kind == 1 ?
  6048. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  6049. posy = st->bg_pos_y_kind == 1 ?
  6050. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  6051. x = box.x + posx;
  6052. y = box.y + posy;
  6053. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  6054. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  6055. if (rep_x) {
  6056. int m = (x - box.x) % tw;
  6057. if (m > 0)
  6058. m -= tw;
  6059. x = box.x + m;
  6060. }
  6061. if (rep_y) {
  6062. int m = (y - box.y) % th;
  6063. if (m > 0)
  6064. m -= th;
  6065. y = box.y + m;
  6066. }
  6067. }
  6068. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  6069. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  6070. cx2 = box.x + box.w;
  6071. cy2 = box.y + box.h;
  6072. if (cx2 > page_rect.x + page_rect.w - 12)
  6073. cx2 = page_rect.x + page_rect.w - 12;
  6074. if (cy2 > page_rect.y + page_rect.h)
  6075. cy2 = page_rect.y + page_rect.h;
  6076. if (cx1 >= cx2 || cy1 >= cy2)
  6077. return;
  6078. b.dst = l->ui->px;
  6079. b.dst_w = l->ui->w;
  6080. b.dst_h = l->ui->h;
  6081. b.clip_x = cx1;
  6082. b.clip_y = cy1;
  6083. b.clip_w = cx2 - cx1;
  6084. b.clip_h = cy2 - cy1;
  6085. b.bg = ui.theme.bg;
  6086. b.bg2 = ui.theme.bg;
  6087. b.dst_a = 0;
  6088. {
  6089. struct img_image *src = image_display_get(bi, tw, th);
  6090. int row_x;
  6091. if (!src)
  6092. src = &bi->img;
  6093. b.scale = ((unsigned int)tw << 16) / src->w;
  6094. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  6095. row_x = x;
  6096. for (;;) {
  6097. for (;;) {
  6098. b.x = x;
  6099. b.y = y;
  6100. img_draw(src, &b);
  6101. if (!rep_x || ++tiles > 512)
  6102. break;
  6103. x += tw;
  6104. if (x >= box.x + box.w)
  6105. break;
  6106. }
  6107. if (!rep_y || ++rows > 64)
  6108. break;
  6109. y += th;
  6110. if (y >= box.y + box.h)
  6111. break;
  6112. x = row_x;
  6113. }
  6114. }
  6115. }
  6116. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  6117. int *out_w, int *out_h);
  6118. static void svg_paint_box(struct ngui *ui, unsigned int node,
  6119. const struct br_style *st, int x, int y, int w,
  6120. int h);
  6121. /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
  6122. * RUN_SVG an inline <svg> icon (its node in off), RUN_PBOX an empty
  6123. * ::before/::after box with a background (Infima's menu chevrons). */
  6124. #define RUN_SVG (-3)
  6125. #define RUN_PBOX (-4)
  6126. static int run_width(const struct lay_run *r)
  6127. {
  6128. if (r->img >= 0)
  6129. return r->iw;
  6130. if (r->img == -2 || r->img == RUN_SVG || r->img == RUN_PBOX)
  6131. return r->iw;
  6132. return (int)r->w;
  6133. }
  6134. static void start_line(struct lay *l, const struct br_style *st)
  6135. {
  6136. (void)st;
  6137. if (l->nruns == 0) {
  6138. l->line_y = l->y;
  6139. l->line_h = 0;
  6140. }
  6141. l->line_left = l->left;
  6142. l->line_right = l->right;
  6143. if (l->float_active && l->line_y < l->float_bottom) {
  6144. if (l->float_left > l->line_left)
  6145. l->line_left = l->float_left;
  6146. if (l->float_right < l->line_right)
  6147. l->line_right = l->float_right;
  6148. }
  6149. if (l->line_right < l->line_left + 8)
  6150. l->line_right = l->line_left + 8;
  6151. l->line_x = l->line_left;
  6152. l->run_x = l->line_left;
  6153. }
  6154. static void flush_line(struct lay *l)
  6155. {
  6156. int total, x, i, vis;
  6157. if (!l->nruns && l->line_x == l->line_left) {
  6158. l->line_h = 0;
  6159. return;
  6160. }
  6161. total = l->line_x - l->line_left;
  6162. x = l->line_left;
  6163. vis = 1;
  6164. if (l->draw) {
  6165. int lh = l->line_h ? l->line_h : 16;
  6166. vis = l->line_y + lh >= page_rect.y &&
  6167. l->line_y <= page_rect.y + page_rect.h;
  6168. }
  6169. if (l->align == BR_ALIGN_CENTER)
  6170. x += (l->line_right - l->line_left - total) / 2;
  6171. else if (l->align == BR_ALIGN_RIGHT)
  6172. x = l->line_right - total;
  6173. if (x < l->line_left)
  6174. x = l->line_left;
  6175. for (i = 0; i < l->nruns; i++) {
  6176. struct lay_run *r = &l->runs[i];
  6177. int w = run_width(r);
  6178. int ry = l->line_y + r->dy;
  6179. x += r->gap;
  6180. if (l->draw && vis) {
  6181. if (r->form) {
  6182. unsigned int node = r->form - 1;
  6183. struct form_state *fs = form_get(node, 1);
  6184. int hh = r->ih ? r->ih : 20;
  6185. int focused = form_focus == node;
  6186. int disabled = r->form_disabled;
  6187. unsigned short bg = l->ui->theme.panel_alt;
  6188. unsigned short fg = disabled ? 0x8410 : r->color;
  6189. struct ngui_rect box = {x, ry, w, hh};
  6190. if (r->form_kind == FORM_CHECKBOX ||
  6191. r->form_kind == FORM_RADIO) {
  6192. ngui_fill_rect(l->ui, box, bg);
  6193. ngui_frame(l->ui, box,
  6194. focused ? l->ui->theme.accent :
  6195. l->ui->theme.border);
  6196. if (fs && fs->checked) {
  6197. struct ngui_rect dot = {
  6198. x + 4, ry + 4,
  6199. w > 8 ? w - 8 : 1,
  6200. hh > 8 ? hh - 8 : 1
  6201. };
  6202. if (r->form_kind == FORM_RADIO)
  6203. ngui_fill_round_rect(
  6204. l->ui, dot, 4,
  6205. 4, 4, 4,
  6206. l->ui->theme.accent);
  6207. else
  6208. ngui_fill_rect(l->ui,
  6209. dot,
  6210. l->ui->theme.accent);
  6211. }
  6212. } else {
  6213. int editable =
  6214. r->form_kind == FORM_TEXT ||
  6215. r->form_kind == FORM_PASSWORD ||
  6216. r->form_kind == FORM_TEXTAREA;
  6217. int scroll = 0;
  6218. /* Editable fields draw the live value
  6219. * (r->lit is a short copy). */
  6220. static char shown[FORM_VALUE_MAX + 1];
  6221. const char *txt = r->lit;
  6222. unsigned int tl = s_len(r->lit);
  6223. if (editable && fs && fs->len) {
  6224. unsigned int k;
  6225. if (r->form_kind == FORM_PASSWORD) {
  6226. for (k = 0; k < fs->len; k++)
  6227. shown[k] = '*';
  6228. shown[k] = '\0';
  6229. txt = shown;
  6230. } else {
  6231. txt = fs->value;
  6232. }
  6233. tl = fs->len;
  6234. }
  6235. struct br_style fst;
  6236. int author, tx = x + 6, pr = 6;
  6237. style_for_node(node, &fst);
  6238. author = form_author_styled(&fst);
  6239. if (author) {
  6240. /* The page styled the control:
  6241. * its background, border, radius
  6242. * and text colour. */
  6243. form_paint_author(l->ui, box, &fst,
  6244. focused);
  6245. tx = x + fst.border_w[3] +
  6246. mp_px(&fst, 7, w);
  6247. pr = fst.border_w[1] +
  6248. mp_px(&fst, 5, w);
  6249. if (tx < x + 2 && !editable)
  6250. tx = x + 2;
  6251. if (!disabled)
  6252. fg = editable && fs &&
  6253. !fs->len ?
  6254. 0x8410 : fst.color;
  6255. if (!editable) {
  6256. int tw0 = (int)
  6257. run_text_width(l->ui,
  6258. r, txt, tl);
  6259. tx = x + (w - tw0) / 2;
  6260. }
  6261. } else {
  6262. /* The box is drawn in theme colours, so
  6263. * the text is too: the page's CSS colour
  6264. * (dark on a light page) would vanish on
  6265. * the dark field. */
  6266. if (!disabled)
  6267. fg = editable && fs && !fs->len ?
  6268. l->ui->theme.text_dim :
  6269. l->ui->theme.text;
  6270. ngui_fill_rect(l->ui, box, bg);
  6271. ngui_frame(l->ui, box,
  6272. focused ? l->ui->theme.accent :
  6273. l->ui->theme.border);
  6274. }
  6275. /* A value wider than the field shows its
  6276. * tail (where typing happens). */
  6277. if (editable && fs && fs->len &&
  6278. w > (tx - x) + pr) {
  6279. int tw = (int)run_text_width(l->ui,
  6280. r, txt, tl);
  6281. int room = w - (tx - x) - pr;
  6282. if (tw > room)
  6283. scroll = tw - room;
  6284. }
  6285. ngui_push_clip(l->ui, (struct ngui_rect){
  6286. x + 1, ry + 1,
  6287. w > 2 ? w - 2 : 1,
  6288. hh > 2 ? hh - 2 : 1 });
  6289. ngui_text_px_face(l->ui, run_face(r),
  6290. tx - scroll,
  6291. ry + (hh - r->font_px) / 2 - 1,
  6292. txt, tl, fg, r->font_px,
  6293. r->bold, r->italic, r->mono);
  6294. if (focused && fs && editable) {
  6295. int cw = 0;
  6296. if (fs->len && fs->caret)
  6297. cw = (int)run_text_width(
  6298. l->ui, r, txt,
  6299. fs->caret < fs->len ?
  6300. fs->caret : fs->len);
  6301. ngui_fill_rect(l->ui,
  6302. (struct ngui_rect){
  6303. tx + cw - scroll,
  6304. ry + 4, 1,
  6305. hh > 8 ? hh - 8 : 1
  6306. },
  6307. l->ui->theme.accent);
  6308. }
  6309. ngui_pop_clip(l->ui);
  6310. if (r->form_kind == FORM_SELECT) {
  6311. ngui_text_px(l->ui, x + w - 12,
  6312. ry + 2, "v", 1, fg,
  6313. r->font_px, 0, 0, 0);
  6314. }
  6315. }
  6316. } else if (r->img == RUN_PBOX) {
  6317. struct ngui_rect bx = { x, ry, w, r->ih };
  6318. ngui_push_clip(l->ui, bx);
  6319. if (r->pb_has_bg)
  6320. ngui_fill_rect(l->ui, bx, r->pb_bg);
  6321. if (r->pb_img >= 0 && r->pb_img < image_count &&
  6322. images[r->pb_img].state == 1) {
  6323. /* Rotate about the box centre: the
  6324. * image is centred in it here. */
  6325. draw_image_transformed(l->ui,
  6326. &images[r->pb_img].img,
  6327. x + r->pb_x, ry + r->pb_y,
  6328. r->pb_w, r->pb_h,
  6329. r->transform_scale ?
  6330. r->scale_x : 100,
  6331. r->transform_scale ?
  6332. r->scale_y : 100,
  6333. r->transform_scale ?
  6334. r->rotate_x100 : 0,
  6335. 50, 50, 1, 1);
  6336. }
  6337. ngui_pop_clip(l->ui);
  6338. } else if (r->img == RUN_SVG) {
  6339. struct br_style sst;
  6340. style_for_node(r->off, &sst);
  6341. svg_paint_box(l->ui, r->off, &sst, x, ry, w,
  6342. r->ih);
  6343. } else if (r->img == -2) {
  6344. int hh = r->ih ? r->ih : 20;
  6345. ngui_fill_rect(l->ui,
  6346. (struct ngui_rect){x, ry, w, hh},
  6347. l->ui->theme.panel_alt);
  6348. ngui_frame(l->ui,
  6349. (struct ngui_rect){x, ry, w, hh},
  6350. l->ui->theme.border);
  6351. ngui_text_px_face(l->ui, run_face(r),
  6352. x + 6, ry + 2, r->lit,
  6353. s_len(r->lit), r->color,
  6354. r->font_px, r->bold, r->italic,
  6355. r->mono);
  6356. } else if (r->img >= 0) {
  6357. struct br_image *bi = &images[r->img];
  6358. if (bi->state == 1 && r->transform_scale) {
  6359. draw_image_transformed(l->ui, &bi->img,
  6360. x, ry, r->iw, r->ih,
  6361. r->scale_x, r->scale_y,
  6362. r->rotate_x100, r->origin_x,
  6363. r->origin_y, r->origin_x_kind,
  6364. r->origin_y_kind);
  6365. } else if (bi->state == 1) {
  6366. struct img_image *src =
  6367. image_display_get(bi, r->iw, r->ih);
  6368. struct img_blit b;
  6369. if (!src)
  6370. src = &bi->img;
  6371. b.dst = l->ui->px;
  6372. b.dst_w = l->ui->w;
  6373. b.dst_h = l->ui->h;
  6374. b.clip_x = page_rect.x;
  6375. b.clip_y = page_rect.y;
  6376. b.clip_w = page_rect.w - 12;
  6377. b.clip_h = page_rect.h;
  6378. b.x = x;
  6379. b.y = ry;
  6380. b.scale = ((unsigned int)r->iw << 16) /
  6381. src->w;
  6382. b.bg = ui.theme.bg;
  6383. b.bg2 = ui.theme.bg;
  6384. b.dst_a = 0;
  6385. b.flags = src->alpha ?
  6386. IMG_BLIT_OVER_DST : 0;
  6387. img_draw(src, &b);
  6388. }
  6389. } else {
  6390. const char *s = r->has_lit ? r->lit :
  6391. doc.text + r->off;
  6392. unsigned int n = r->has_lit ? s_len(r->lit) :
  6393. r->len;
  6394. ngui_text_px_face(l->ui, run_face(r), x, ry,
  6395. s, n, r->color, r->font_px,
  6396. r->bold, r->italic, r->mono);
  6397. if (r->underline)
  6398. ngui_fill_rect(l->ui,
  6399. (struct ngui_rect){x,
  6400. ry + run_ascent(l->ui, r) + 2,
  6401. w, 1}, r->color);
  6402. if (r->strike)
  6403. ngui_fill_rect(l->ui,
  6404. (struct ngui_rect){x,
  6405. ry + run_ascent(l->ui, r) -
  6406. (r->font_px > 3 ?
  6407. r->font_px / 3 : 1),
  6408. w, 1}, r->color);
  6409. if (r->overline)
  6410. ngui_fill_rect(l->ui,
  6411. (struct ngui_rect){x, ry,
  6412. w, 1}, r->color);
  6413. }
  6414. if (r->form || r->href) {
  6415. if (nhits < HIT_MAX) {
  6416. struct hit *h = &hits[nhits];
  6417. unsigned int target = r->form ?
  6418. r->form - 1 : r->href;
  6419. int hh = (r->form || r->img >= 0 ||
  6420. r->img == RUN_SVG) ?
  6421. r->ih :
  6422. run_line_height(l->ui, r);
  6423. int merge = nhits > 0 &&
  6424. hits[nhits - 1].node == target &&
  6425. hits[nhits - 1].y == ry &&
  6426. hits[nhits - 1].h == hh &&
  6427. x <= hits[nhits - 1].x +
  6428. hits[nhits - 1].w + 2;
  6429. if (merge) {
  6430. struct hit *p = &hits[nhits - 1];
  6431. int end = x + w;
  6432. if (end > p->x + p->w)
  6433. p->w = end - p->x;
  6434. } else {
  6435. h->x = x;
  6436. h->y = ry;
  6437. h->w = w;
  6438. h->h = hh;
  6439. h->node = (unsigned short)target;
  6440. nhits++;
  6441. }
  6442. }
  6443. }
  6444. }
  6445. x += w;
  6446. }
  6447. l->y += l->line_h + 2;
  6448. if (l->float_active && l->y >= l->float_bottom)
  6449. l->float_active = 0;
  6450. l->nruns = 0;
  6451. l->line_x = l->left;
  6452. l->run_x = l->left;
  6453. l->line_left = l->left;
  6454. l->line_right = l->right;
  6455. l->line_h = 0;
  6456. l->space_pending = 0;
  6457. }
  6458. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  6459. const struct br_style *st, unsigned short href,
  6460. const char *lit)
  6461. {
  6462. unsigned int n = lit ? s_len(lit) : len;
  6463. const char *tp = lit ? lit : doc.text + off;
  6464. int w = (int)face_text_width(l->ui, st, tp, n);
  6465. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6466. flush_line(l);
  6467. if (l->nruns == 0) {
  6468. l->line_y = l->y;
  6469. l->line_h = 0;
  6470. start_line(l, st);
  6471. }
  6472. {
  6473. struct lay_run *r = &l->runs[l->nruns++];
  6474. int gap = l->line_x - l->run_x;
  6475. if (gap < 0)
  6476. gap = 0;
  6477. r->gap = (unsigned short)gap;
  6478. r->off = off;
  6479. r->len = len;
  6480. r->color = st->color;
  6481. r->href = href;
  6482. r->dy = 0;
  6483. r->has_lit = 0;
  6484. r->form = 0;
  6485. r->form_kind = 0;
  6486. r->form_disabled = 0;
  6487. r->lit[0] = '\0';
  6488. if (lit && lit[0]) {
  6489. unsigned int i;
  6490. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  6491. r->lit[i] = lit[i];
  6492. r->lit[i] = '\0';
  6493. r->has_lit = 1;
  6494. }
  6495. r->img = -1;
  6496. r->iw = r->ih = 0;
  6497. r->font_px = st->font_px;
  6498. r->bold = st->bold;
  6499. r->italic = st->italic;
  6500. r->mono = st->mono;
  6501. r->font_face = st->font_face;
  6502. /* A control with its own background is a button, not body copy;
  6503. * an inherited link underline would strike through the fill. */
  6504. r->underline = st->underline && !st->has_bg;
  6505. r->strike = st->strike && !st->has_bg;
  6506. r->overline = st->overline && !st->has_bg;
  6507. r->w = (unsigned short)w;
  6508. if (r->has_lit)
  6509. r->w = (unsigned short)run_text_width(
  6510. l->ui, r, r->lit, s_len(r->lit));
  6511. w = r->w;
  6512. }
  6513. l->line_x += w;
  6514. l->run_x = l->line_x;
  6515. {
  6516. int lh = face_line_height(l->ui, st);
  6517. if (st->line_h_px)
  6518. lh = st->line_h_px;
  6519. else if (st->line_h_pct)
  6520. lh = st->font_px * st->line_h_pct / 100;
  6521. if (lh < face_line_height(l->ui, st))
  6522. lh = face_line_height(l->ui, st);
  6523. if (l->line_h < lh)
  6524. l->line_h = lh;
  6525. }
  6526. }
  6527. static void add_image_run(struct lay *l, unsigned int node,
  6528. const struct br_style *st, unsigned short href)
  6529. {
  6530. struct br_image *bi = 0;
  6531. int idx = doc.nodes[node].img_index;
  6532. int dw, dh, maxw;
  6533. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  6534. bi = &images[idx];
  6535. if (l->nruns == 0)
  6536. start_line(l, st);
  6537. if (l->space_pending &&
  6538. (l->nruns > 0 || l->line_x > l->line_left)) {
  6539. int sp = (int)face_text_width(l->ui, st, " ", 1);
  6540. if (l->line_x + sp <= l->line_right)
  6541. l->line_x += sp;
  6542. }
  6543. l->space_pending = 0;
  6544. if (!bi) {
  6545. const char *alt = br_alt(&doc, node);
  6546. struct br_style gs = *st;
  6547. char tmp[96];
  6548. unsigned int n = 0;
  6549. int w;
  6550. gs.color = BR_GRAY;
  6551. gs.underline = 0;
  6552. s_append(tmp, &n, "[", sizeof(tmp));
  6553. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  6554. s_append(tmp, &n, "]", sizeof(tmp));
  6555. w = (int)face_text_width(l->ui, &gs, tmp, n);
  6556. if (l->line_x + w > l->line_right &&
  6557. (l->nruns > 0 || l->line_x > l->line_left))
  6558. flush_line(l);
  6559. add_run(l, 0, 0, &gs, href, tmp);
  6560. if (!l->draw) {
  6561. int t = l->line_y < 0 ? 0 : l->line_y;
  6562. int hh = face_line_height(l->ui, &gs);
  6563. if (t > 65535)
  6564. t = 65535;
  6565. if (hh > 65535)
  6566. hh = 65535;
  6567. img_top[node] = (unsigned short)t;
  6568. img_h[node] = (unsigned short)hh;
  6569. }
  6570. return;
  6571. }
  6572. maxw = l->line_right - l->line_left;
  6573. if (maxw < 8)
  6574. maxw = 8;
  6575. {
  6576. int iw = bi->native_w, ih = bi->native_h;
  6577. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  6578. if (iw <= 0 || ih <= 0) {
  6579. iw = (int)bi->img.w;
  6580. ih = (int)bi->img.h;
  6581. }
  6582. dw = iw;
  6583. dh = ih;
  6584. if (doc.nodes[node].width_attr) {
  6585. int want = doc.nodes[node].width_attr;
  6586. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  6587. have_w = 1;
  6588. }
  6589. if (doc.nodes[node].height_attr) {
  6590. int want = doc.nodes[node].height_attr;
  6591. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  6592. have_h = 1;
  6593. }
  6594. if (have_w && !have_h)
  6595. dh = ih ? ih * dw / iw : 0;
  6596. if (have_h && !have_w)
  6597. dw = iw ? iw * dh / ih : 0;
  6598. if (st->width_kind) {
  6599. css_w = 1;
  6600. if (st->width_kind == 3)
  6601. dw = maxw * st->width_calc_pct / 100 +
  6602. st->width_calc_px;
  6603. else
  6604. dw = st->width_kind == 2 ?
  6605. maxw * (int)st->width / 100 :
  6606. (int)st->width;
  6607. }
  6608. /* Percentage heights resolve against the containing block's
  6609. * definite height (Docusaurus' logo: `.navbar__logo { height:
  6610. * 2rem }` holding an `img { height: 100% }`), and are auto
  6611. * when it has none; they used to use the width. */
  6612. if (st->height_kind == 1 ||
  6613. ((st->height_kind == 2 || st->height_kind == 3) &&
  6614. l->cb_h > 0)) {
  6615. css_h = 1;
  6616. if (st->height_kind == 3)
  6617. dh = l->cb_h * st->height_calc_pct / 100 +
  6618. st->height_calc_px;
  6619. else
  6620. dh = st->height_kind == 2 ?
  6621. l->cb_h * (int)st->height / 100 :
  6622. (int)st->height;
  6623. }
  6624. if (css_w && !css_h)
  6625. dh = ih ? ih * dw / iw : 0;
  6626. if (css_h && !css_w)
  6627. dw = iw ? iw * dh / ih : 0;
  6628. if (st->max_width_kind) {
  6629. int mw = st->max_width_kind == 3 ?
  6630. maxw * st->max_width_calc_pct / 100 +
  6631. st->max_width_calc_px :
  6632. st->max_width_kind == 2 ?
  6633. maxw * (int)st->max_width / 100 :
  6634. (int)st->max_width;
  6635. if (mw > 0 && dw > mw) {
  6636. dh = iw ? ih * mw / iw : 0;
  6637. dw = mw;
  6638. }
  6639. }
  6640. }
  6641. if (dw < 8)
  6642. dw = 8;
  6643. if (dh < 8)
  6644. dh = 8;
  6645. if (dw > maxw) {
  6646. dh = dw ? dh * maxw / dw : dh;
  6647. dw = maxw;
  6648. }
  6649. if (!l->draw) {
  6650. int t = l->line_y < 0 ? 0 : l->line_y;
  6651. if (t > 65535)
  6652. t = 65535;
  6653. if (dh > 65535)
  6654. dh = 65535;
  6655. img_top[node] = (unsigned short)t;
  6656. img_h[node] = (unsigned short)dh;
  6657. }
  6658. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  6659. l->line_x > l->line_left))
  6660. flush_line(l);
  6661. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6662. flush_line(l);
  6663. if (l->nruns == 0) {
  6664. l->line_y = l->y;
  6665. l->line_h = 0;
  6666. start_line(l, st);
  6667. }
  6668. {
  6669. struct lay_run *r = &l->runs[l->nruns++];
  6670. int gap = l->line_x - l->run_x;
  6671. if (gap < 0)
  6672. gap = 0;
  6673. r->gap = (unsigned short)gap;
  6674. r->off = 0;
  6675. r->len = 0;
  6676. r->color = 0;
  6677. r->href = href;
  6678. r->form = 0;
  6679. r->form_kind = 0;
  6680. r->form_disabled = 0;
  6681. /* Inline replaced elements honour their vertical margins; this
  6682. * is how Bootstrap's negative logo margins centre the wordmark. */
  6683. {
  6684. int idy = mp_px(st, 0, l->right - l->left);
  6685. if (idy < -2048)
  6686. idy = -2048;
  6687. if (idy > 2048)
  6688. idy = 2048;
  6689. r->dy = (signed short)idy;
  6690. }
  6691. r->has_lit = 0;
  6692. r->lit[0] = '\0';
  6693. r->img = (short)idx;
  6694. r->iw = (unsigned short)dw;
  6695. r->ih = (unsigned short)dh;
  6696. r->w = (unsigned short)dw;
  6697. r->font_px = st->font_px;
  6698. r->bold = st->bold;
  6699. r->italic = st->italic;
  6700. r->mono = st->mono;
  6701. r->font_face = st->font_face;
  6702. r->transform_scale = st->transform_scale;
  6703. r->scale_x = st->scale_x;
  6704. r->scale_y = st->scale_y;
  6705. r->rotate_x100 = st->rotate_x100;
  6706. r->origin_x = st->origin_x;
  6707. r->origin_y = st->origin_y;
  6708. r->origin_x_kind = st->origin_x_kind;
  6709. r->origin_y_kind = st->origin_y_kind;
  6710. r->underline = 0;
  6711. }
  6712. if (node < BR_MAX_NODES) {
  6713. layout_boxes[node].x = l->line_x;
  6714. layout_boxes[node].y = l->line_y +
  6715. mp_px(st, 0, l->right - l->left);
  6716. layout_boxes[node].w = dw;
  6717. layout_boxes[node].h = dh;
  6718. layout_boxes[node].valid = 1;
  6719. }
  6720. l->line_x += dw;
  6721. l->run_x = l->line_x;
  6722. if (l->line_h < dh)
  6723. l->line_h = dh;
  6724. }
  6725. /* An inline (or inline-block) <svg> is a replaced element in the text
  6726. * line, like an <img>: comment bubbles and arrows sit next to their label
  6727. * instead of starting a block of their own. */
  6728. static void add_svg_run(struct lay *l, unsigned int node,
  6729. const struct br_style *st, unsigned short href)
  6730. {
  6731. struct lay_run *r;
  6732. int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
  6733. if (lw < 8)
  6734. lw = 8;
  6735. cw = st->width_kind ? style_width_px(st, lw) : lw;
  6736. if (cw < 1)
  6737. cw = 1;
  6738. svg_size(node, st, cw, &dw, &dh);
  6739. if (dw > lw)
  6740. dw = lw;
  6741. ml = mp_px(st, 3, lw);
  6742. mr = mp_px(st, 1, lw);
  6743. if (ml < 0)
  6744. ml = 0;
  6745. if (mr < 0)
  6746. mr = 0;
  6747. if (l->line_x + ml + dw > l->line_right &&
  6748. (l->nruns > 0 || l->line_x > l->line_left))
  6749. flush_line(l);
  6750. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6751. flush_line(l);
  6752. if (l->nruns == 0) {
  6753. l->line_y = l->y;
  6754. l->line_h = 0;
  6755. start_line(l, st);
  6756. }
  6757. l->line_x += ml;
  6758. r = &l->runs[l->nruns++];
  6759. memset(r, 0, sizeof(*r));
  6760. r->gap = (unsigned short)(l->line_x > l->run_x ?
  6761. l->line_x - l->run_x : 0);
  6762. r->off = node;
  6763. r->color = st->color;
  6764. r->href = href;
  6765. r->img = RUN_SVG;
  6766. r->iw = (unsigned short)dw;
  6767. r->ih = (unsigned short)dh;
  6768. r->w = (unsigned short)dw;
  6769. r->font_px = st->font_px;
  6770. if (node < BR_MAX_NODES) {
  6771. layout_boxes[node].x = l->line_x;
  6772. layout_boxes[node].y = l->line_y;
  6773. layout_boxes[node].w = dw;
  6774. layout_boxes[node].h = dh;
  6775. layout_boxes[node].valid = 1;
  6776. }
  6777. l->line_x += dw + mr;
  6778. l->run_x = l->line_x;
  6779. if (l->line_h < dh)
  6780. l->line_h = dh;
  6781. }
  6782. static int text_width(struct lay *l, const char *s, unsigned int n,
  6783. const struct br_style *st)
  6784. {
  6785. return (int)face_text_width(l->ui, st, s, n);
  6786. }
  6787. /* Longest prefix that fits in maxw, at least one byte. */
  6788. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  6789. const struct br_style *st, int maxw)
  6790. {
  6791. unsigned int take = 0;
  6792. while (take < n) {
  6793. if (text_width(l, s, take + 1, st) > maxw)
  6794. break;
  6795. take++;
  6796. }
  6797. return take ? take : 1;
  6798. }
  6799. static void emit_word(struct lay *l, const char *s, unsigned int start,
  6800. unsigned int n, unsigned int base,
  6801. const struct br_style *st, unsigned short href)
  6802. {
  6803. int avail;
  6804. int w = text_width(l, s + start, n, st);
  6805. unsigned int off = start;
  6806. if (l->nruns == 0)
  6807. start_line(l, st);
  6808. avail = l->line_right - l->line_left;
  6809. if (st->nowrap) {
  6810. if (n)
  6811. add_run(l, base + start,
  6812. (unsigned short)n, st, href, 0);
  6813. return;
  6814. }
  6815. /* A padded/bordered one-word button can be a few pixels wider than
  6816. * the content box; keep it on one line instead of splitting it. */
  6817. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  6818. add_run(l, base + start,
  6819. (unsigned short)n, st, href, 0);
  6820. return;
  6821. }
  6822. if (l->line_x + w > l->line_right &&
  6823. (l->nruns > 0 || l->line_x > l->line_left)) {
  6824. flush_line(l);
  6825. start_line(l, st);
  6826. avail = l->line_right - l->line_left;
  6827. }
  6828. if (w <= avail) {
  6829. if (n)
  6830. add_run(l, base + start,
  6831. (unsigned short)n, st, href, 0);
  6832. return;
  6833. }
  6834. while (n > 0) {
  6835. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  6836. add_run(l, base + off,
  6837. (unsigned short)take, st, href, 0);
  6838. off += take;
  6839. n -= take;
  6840. if (n) {
  6841. flush_line(l);
  6842. start_line(l, st);
  6843. avail = l->line_right - l->line_left;
  6844. }
  6845. }
  6846. }
  6847. static void emit_text(struct lay *l, const char *s, unsigned int len,
  6848. const struct br_style *st, unsigned short href, int pre)
  6849. {
  6850. unsigned int i = 0;
  6851. unsigned int base;
  6852. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  6853. if (!s || !len)
  6854. return;
  6855. if (space_w <= 0)
  6856. space_w = 8;
  6857. if (l->nruns == 0)
  6858. start_line(l, st);
  6859. base = (unsigned int)(s - doc.text);
  6860. if (st->uppercase) {
  6861. char *p = (char *)s;
  6862. unsigned int j;
  6863. for (j = 0; j < len; j++)
  6864. if (p[j] >= 'a' && p[j] <= 'z')
  6865. p[j] = (char)(p[j] - 'a' + 'A');
  6866. }
  6867. if (pre) {
  6868. while (i < len) {
  6869. unsigned int start;
  6870. if (s[i] == '\n') {
  6871. flush_line(l);
  6872. start_line(l, st);
  6873. i++;
  6874. continue;
  6875. }
  6876. if (s[i] == ' ') {
  6877. if (l->line_x + space_w > l->line_right &&
  6878. (l->nruns > 0 || l->line_x > l->line_left)) {
  6879. flush_line(l);
  6880. start_line(l, st);
  6881. } else {
  6882. l->line_x += space_w;
  6883. }
  6884. i++;
  6885. continue;
  6886. }
  6887. start = i;
  6888. while (i < len && s[i] != ' ' && s[i] != '\n')
  6889. i++;
  6890. emit_word(l, s, start, i - start, base, st, href);
  6891. }
  6892. return;
  6893. }
  6894. while (i < len) {
  6895. unsigned int start, n;
  6896. if (s[i] == ' ') {
  6897. l->space_pending = 1;
  6898. i++;
  6899. continue;
  6900. }
  6901. start = i;
  6902. while (i < len && s[i] != ' ')
  6903. i++;
  6904. n = i - start;
  6905. if (l->space_pending &&
  6906. (l->nruns > 0 || l->line_x > l->line_left)) {
  6907. if (st->nowrap ||
  6908. l->line_x + space_w <= l->line_right)
  6909. l->line_x += space_w;
  6910. }
  6911. l->space_pending = 0;
  6912. emit_word(l, s, start, n, base, st, href);
  6913. }
  6914. }
  6915. static int list_index(unsigned int parent, unsigned int node)
  6916. {
  6917. unsigned int n = 0, i;
  6918. for (i = doc.nodes[parent].first; i && i != node;
  6919. i = doc.nodes[i].next)
  6920. if (doc.nodes[i].tag == BR_TAG_LI)
  6921. n++;
  6922. return (int)n + 1;
  6923. }
  6924. static void list_roman(char *m, unsigned int *n, int v, int upper,
  6925. unsigned int cap)
  6926. {
  6927. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  6928. 50, 40, 10, 9, 5, 4, 1 };
  6929. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  6930. "l", "xl", "x", "ix", "v", "iv", "i" };
  6931. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  6932. "L", "XL", "X", "IX", "V", "IV", "I" };
  6933. unsigned int i;
  6934. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  6935. while (v >= val[i] && *n + 1 < cap) {
  6936. const char *s = upper ? up[i] : lo[i];
  6937. while (*s && *n + 1 < cap)
  6938. m[(*n)++] = *s++;
  6939. v -= val[i];
  6940. }
  6941. }
  6942. }
  6943. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  6944. {
  6945. unsigned int n = 0;
  6946. if (style == BR_LIST_DISC) {
  6947. m[n++] = '-';
  6948. } else if (style == BR_LIST_CIRCLE) {
  6949. m[n++] = 'o';
  6950. } else if (style == BR_LIST_SQUARE) {
  6951. m[n++] = '+';
  6952. } else if (style == BR_LIST_LOWER_ALPHA ||
  6953. style == BR_LIST_UPPER_ALPHA) {
  6954. if (idx >= 1 && idx <= 26)
  6955. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  6956. 'A' : 'a') + idx - 1);
  6957. else
  6958. m[n++] = '?';
  6959. m[n++] = '.';
  6960. } else if (style == BR_LIST_LOWER_ROMAN ||
  6961. style == BR_LIST_UPPER_ROMAN) {
  6962. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  6963. if (n + 1 < cap)
  6964. m[n++] = '.';
  6965. } else {
  6966. s_append_dec(m, &n, (unsigned int)idx, cap);
  6967. if (n + 1 < cap)
  6968. m[n++] = '.';
  6969. }
  6970. m[n] = '\0';
  6971. }
  6972. /* A control the page styled itself (background, border or radius in author
  6973. * CSS -- `background:transparent;border:none` counts) is painted with that
  6974. * style, sized from its padding/height and keeps the page's text colour.
  6975. * Unstyled controls keep the ngui theme look. */
  6976. static int form_author_styled(const struct br_style *st)
  6977. {
  6978. int i;
  6979. if (st->bg_set)
  6980. return 1;
  6981. for (i = 0; i < 4; i++)
  6982. if (st->border_w[i] || st->radius[i])
  6983. return 1;
  6984. return 0;
  6985. }
  6986. /* Set by the layout when the control is stretched to its line: a flex item
  6987. * (its box width was assigned by the flex row) or a child of a flex column,
  6988. * whose default align-items: stretch makes inputs full width. */
  6989. static int form_fill_line;
  6990. static void add_form_run(struct lay *l, unsigned int node,
  6991. const struct br_style *st, unsigned short href)
  6992. {
  6993. struct form_state *fs = form_get(node, 1);
  6994. char shown[FORM_VALUE_MAX + 1];
  6995. char opt[64];
  6996. const char *text = "";
  6997. struct lay_run *r;
  6998. int kind = form_kind_of(node);
  6999. int disabled = form_disabled(node);
  7000. int author = form_author_styled(st);
  7001. int tw, w = 120, h = 20, i, line_w, pad_x, pad_y;
  7002. int ml = 0, mr = 0, mt = 0, mb = 0;
  7003. if (!fs)
  7004. return;
  7005. if (l->nruns == 0)
  7006. start_line(l, st);
  7007. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  7008. text = "";
  7009. w = 16;
  7010. h = 16;
  7011. } else if (kind == FORM_SELECT) {
  7012. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  7013. s_copy(opt, "Select", sizeof(opt));
  7014. text = opt;
  7015. w = 120;
  7016. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  7017. kind == FORM_RESET) {
  7018. if (fs->len)
  7019. text = fs->value;
  7020. else if (doc.nodes[node].tag == BR_TAG_BUTTON)
  7021. /* A <button>'s label is its content: an empty one
  7022. * (Docusaurus' sidebar caret, drawn by a CSS
  7023. * ::before icon) shows none. Only <input> buttons
  7024. * get the UA's default label. */
  7025. text = "";
  7026. else
  7027. text = kind == FORM_SUBMIT ? "Submit" :
  7028. kind == FORM_RESET ? "Reset" : "Button";
  7029. } else if (kind == FORM_PASSWORD) {
  7030. for (i = 0; i < fs->len; i++)
  7031. shown[i] = '*';
  7032. shown[fs->len] = '\0';
  7033. text = fs->len ? shown : br_placeholder(&doc, node);
  7034. } else {
  7035. if (fs->len)
  7036. text = fs->value;
  7037. else
  7038. text = br_placeholder(&doc, node);
  7039. if (kind == FORM_TEXTAREA) {
  7040. w = 180;
  7041. h = 40;
  7042. }
  7043. }
  7044. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  7045. line_w = l->line_right - l->line_left;
  7046. pad_x = mp_px(st, 7, line_w) + mp_px(st, 5, line_w) +
  7047. st->border_w[1] + st->border_w[3];
  7048. pad_y = mp_px(st, 4, line_w) + mp_px(st, 6, line_w) +
  7049. st->border_w[0] + st->border_w[2];
  7050. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  7051. /* Buttons are border-box in every UA stylesheet: an
  7052. * explicit width/height is the whole box. */
  7053. if (author || pad_x) {
  7054. w = tw + pad_x;
  7055. } else {
  7056. w = tw + 18;
  7057. if (w < 64)
  7058. w = 64;
  7059. }
  7060. if (st->width_kind)
  7061. w = style_width_px(st, line_w);
  7062. if (st->min_width_kind == 1 && w < (int)st->min_width)
  7063. w = st->min_width;
  7064. if (st->height_kind == 1)
  7065. h = st->height;
  7066. else if (author)
  7067. h = st->font_px + 6 + pad_y;
  7068. else
  7069. h = 22;
  7070. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  7071. kind == FORM_TEXTAREA) {
  7072. int fill = form_fill_line || st->display == BR_DISPLAY_BLOCK ||
  7073. st->display == BR_DISPLAY_FLEX;
  7074. int boxed = st->box_sizing ? 0 : pad_x;
  7075. if (st->width_kind)
  7076. w = style_width_px(st, line_w) + boxed;
  7077. else if (fill)
  7078. w = line_w - (l->line_x - l->line_left);
  7079. else
  7080. w = kind == FORM_TEXTAREA ? 180 : 120;
  7081. if (kind == FORM_TEXTAREA) {
  7082. const char *ra = br_find_attr(&doc, node, "rows");
  7083. int rows = 0;
  7084. int lh = st->line_h_px ? st->line_h_px :
  7085. st->font_px * 5 / 4;
  7086. while (ra && *ra >= '0' && *ra <= '9')
  7087. rows = rows * 10 + (*ra++ - '0');
  7088. if (rows < 1 || rows > 40)
  7089. rows = 2;
  7090. h = author ? rows * lh + pad_y : 40;
  7091. } else if (author) {
  7092. h = st->font_px + 8 + pad_y;
  7093. } else if (st->font_px + 8 > h) {
  7094. /* Taller fields for large text (min-height/padding
  7095. * on login pages): keep the box around the glyphs. */
  7096. h = st->font_px + 8;
  7097. }
  7098. if (st->height_kind == 1)
  7099. h = st->height + (st->box_sizing ? 0 : pad_y);
  7100. if (st->min_height_kind == 1 && h < (int)st->min_height)
  7101. h = st->min_height;
  7102. } else if (kind == FORM_SELECT) {
  7103. w = st->width_kind == 1 ? st->width : 120;
  7104. }
  7105. if (author) {
  7106. /* Inline margins (Google's `margin:11px 4px` between its
  7107. * two submit buttons). */
  7108. ml = mp_px(st, 3, line_w);
  7109. mr = mp_px(st, 1, line_w);
  7110. mt = mp_px(st, 0, line_w);
  7111. mb = mp_px(st, 2, line_w);
  7112. if (ml < 0 || ml > 64) ml = 0;
  7113. if (mr < 0 || mr > 64) mr = 0;
  7114. if (mt < 0 || mt > 64) mt = 0;
  7115. if (mb < 0 || mb > 64) mb = 0;
  7116. }
  7117. if (w > line_w - ml - mr)
  7118. w = line_w - ml - mr;
  7119. if (w < 8)
  7120. w = 8;
  7121. if (h > 400)
  7122. h = 400;
  7123. if (l->line_x + ml + w > l->line_right &&
  7124. (l->nruns > 0 || l->line_x > l->line_left))
  7125. flush_line(l);
  7126. if (l->nruns >= 96)
  7127. return;
  7128. if (l->nruns == 0) {
  7129. l->line_y = l->y;
  7130. l->line_h = 0;
  7131. start_line(l, st);
  7132. }
  7133. l->line_x += ml;
  7134. r = &l->runs[l->nruns++];
  7135. r->gap = (unsigned short)(l->line_x - l->run_x);
  7136. r->off = r->len = 0;
  7137. r->color = st->color;
  7138. r->href = href;
  7139. r->dy = (signed short)mt;
  7140. r->has_lit = 1;
  7141. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  7142. r->lit[i] = text[i];
  7143. r->lit[i] = '\0';
  7144. r->img = -2;
  7145. r->iw = (unsigned short)w;
  7146. r->ih = (unsigned short)h;
  7147. r->w = (unsigned short)w;
  7148. r->font_px = st->font_px;
  7149. r->bold = st->bold;
  7150. r->italic = st->italic;
  7151. r->mono = st->mono;
  7152. r->font_face = st->font_face;
  7153. r->underline = 0;
  7154. r->form = node + 1;
  7155. r->form_kind = (unsigned char)kind;
  7156. r->form_disabled = (unsigned char)disabled;
  7157. if (node < BR_MAX_NODES) {
  7158. layout_boxes[node].x = l->line_x;
  7159. layout_boxes[node].y = l->line_y + mt;
  7160. layout_boxes[node].w = w;
  7161. layout_boxes[node].h = h;
  7162. layout_boxes[node].valid = 1;
  7163. }
  7164. l->line_x += w;
  7165. l->run_x = l->line_x;
  7166. l->line_x += mr;
  7167. if (l->line_h < h + mt + mb)
  7168. l->line_h = h + mt + mb;
  7169. }
  7170. /* Background, border and corner radius of an author-styled control, the
  7171. * same decoration rules as a block box. */
  7172. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  7173. const struct br_style *st, int focused)
  7174. {
  7175. int rtl = css_radius(st, 0, box.w, box.h);
  7176. int rtr = css_radius(st, 1, box.w, box.h);
  7177. int rbr = css_radius(st, 2, box.w, box.h);
  7178. int rbl = css_radius(st, 3, box.w, box.h);
  7179. int bw = st->border_t[0] ? 0 : st->border_w[0];
  7180. (void)focused;
  7181. if (box.w <= 0 || box.h <= 0)
  7182. return;
  7183. if (rtl || rtr || rbr || rbl) {
  7184. if (bw > 0 && st->has_bg && st->border_c[0] != st->bg &&
  7185. box.w > bw * 2 && box.h > bw * 2) {
  7186. struct ngui_rect in = { box.x + bw, box.y + bw,
  7187. box.w - bw * 2,
  7188. box.h - bw * 2 };
  7189. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  7190. st->border_c[0]);
  7191. ngui_fill_round_rect(ui, in,
  7192. rtl > bw ? rtl - bw : 0,
  7193. rtr > bw ? rtr - bw : 0,
  7194. rbr > bw ? rbr - bw : 0,
  7195. rbl > bw ? rbl - bw : 0, st->bg);
  7196. } else if (st->has_bg) {
  7197. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  7198. st->bg);
  7199. } else if (bw > 0) {
  7200. ngui_frame_round(ui, box, rtl, rtr, rbr, rbl, bw,
  7201. st->border_c[0]);
  7202. }
  7203. return;
  7204. }
  7205. if (st->has_bg)
  7206. ngui_fill_rect(ui, box, st->bg);
  7207. if (st->border_w[0] || st->border_w[1] || st->border_w[2] ||
  7208. st->border_w[3])
  7209. draw_border_box(ui, box, st);
  7210. }
  7211. /* A poster wrapper is absolutely positioned over the media slot; the
  7212. * measured height of its picture is normally added back to the flow. When a
  7213. * loading-skeleton sibling already reserves that slot, adding both doubles
  7214. * the media height and pushes the article text a full screen down. */
  7215. static int has_skeleton_sibling(unsigned int node)
  7216. {
  7217. unsigned int p = doc.nodes[node].parent, c;
  7218. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  7219. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  7220. continue;
  7221. if (doc.nodes[c].class_off &&
  7222. contains_ci(doc.attrs + doc.nodes[c].class_off,
  7223. "skeleton"))
  7224. return 1;
  7225. }
  7226. return 0;
  7227. }
  7228. static void layout_children(struct lay *l, unsigned int parent,
  7229. const struct br_style *pst, int depth,
  7230. unsigned short link);
  7231. static void layout_flex_children(struct lay *l, unsigned int parent,
  7232. const struct br_style *pst, int depth,
  7233. unsigned short link);
  7234. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  7235. struct br_style *ps, int base);
  7236. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  7237. const struct br_style *ps, unsigned short link);
  7238. static void layout_grid_children(struct lay *l, unsigned int parent,
  7239. const struct br_style *pst, int depth,
  7240. unsigned short link);
  7241. static void layout_grid_auto(struct lay *l, unsigned int parent,
  7242. const struct br_style *pst, int depth,
  7243. unsigned short link);
  7244. static int flex_item_width(struct lay *l, unsigned int n,
  7245. const struct br_style *cs, int avail);
  7246. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  7247. const struct br_style *pst, int depth,
  7248. unsigned short link);
  7249. static void layout_table_row(struct lay *l, unsigned int row,
  7250. const struct br_style *pst, int depth,
  7251. unsigned short link);
  7252. static int table_has_rowspan(unsigned int table);
  7253. static void layout_table(struct lay *l, unsigned int table,
  7254. const struct br_style *st, int depth,
  7255. unsigned short link);
  7256. /* A flex container whose items are only inline spans is usually just a
  7257. * heading/icon pair. Our flex row positions such items without emitting
  7258. * their inline text in some deep page contexts; normal inline flow renders
  7259. * the same content correctly. */
  7260. static int layout_out_of_flow(struct lay *l, unsigned int n,
  7261. const struct br_style *cs, int depth,
  7262. unsigned short lk);
  7263. static void layout_flex_column(struct lay *l, unsigned int parent,
  7264. const struct br_style *pst, int depth,
  7265. unsigned short link);
  7266. static void emit_pseudo(struct lay *l, unsigned int node,
  7267. const struct br_style *st, int pe, unsigned short link);
  7268. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  7269. {
  7270. unsigned int c;
  7271. int items = 0;
  7272. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7273. struct br_node *nd = &doc.nodes[c];
  7274. struct br_style cs;
  7275. if (nd->type == BR_NODE_TEXT)
  7276. continue;
  7277. br_style_for(&doc, c, pst, &cs);
  7278. if (cs.display == BR_DISPLAY_NONE)
  7279. continue;
  7280. /* `justify-content: space-between` spreads even two plain
  7281. * inline items (a "Password ... Reset password" label row)
  7282. * across the line; inline flow would set them side by side. */
  7283. if (++items >= 2 && pst->justify >= 3)
  7284. return 1;
  7285. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  7286. cs.width_kind || cs.has_bg ||
  7287. cs.border_w[0] || cs.border_w[1] ||
  7288. cs.border_w[2] || cs.border_w[3] ||
  7289. nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG)
  7290. return 1;
  7291. }
  7292. return 0;
  7293. }
  7294. static int css_radius(const struct br_style *st, int corner,
  7295. int w, int h)
  7296. {
  7297. int r = st->radius[corner];
  7298. if (r <= 0)
  7299. return 0;
  7300. if (r > w / 2)
  7301. r = w / 2;
  7302. if (r > h / 2)
  7303. r = h / 2;
  7304. return r;
  7305. }
  7306. /* ---- inline SVG ----
  7307. *
  7308. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  7309. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  7310. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  7311. * opacity and solid paint; a gradient paints the average of its stops) and
  7312. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  7313. #define SVG_CACHE_MAX 48
  7314. #define SVG_CACHE_PIXELS (640 * 1024)
  7315. #define SVG_MAX_POINTS 24576
  7316. struct svg_cache_ent {
  7317. unsigned int node;
  7318. int w, h;
  7319. unsigned short *px;
  7320. unsigned char *a;
  7321. unsigned int stamp;
  7322. };
  7323. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  7324. static unsigned int svg_cache_pixels, svg_cache_clock;
  7325. static struct svgr svg_geom;
  7326. static void *svg_geom_buf;
  7327. /* Current viewport in user units: percentage lengths resolve against it
  7328. * (the viewBox size, not the device pixels). */
  7329. static double svg_vp_w = 300, svg_vp_h = 150;
  7330. /* The layers live in the page heap: forget them before heap_reset(). */
  7331. static void svg_cache_clear(void)
  7332. {
  7333. memset(svg_cache, 0, sizeof(svg_cache));
  7334. svg_cache_pixels = 0;
  7335. svg_geom_buf = 0;
  7336. }
  7337. static int svg_name_is(const char *a, const char *b)
  7338. {
  7339. while (*a && *b) {
  7340. char x = *a, y = *b;
  7341. if (x >= 'A' && x <= 'Z')
  7342. x = (char)(x - 'A' + 'a');
  7343. if (x != y)
  7344. return 0;
  7345. a++;
  7346. b++;
  7347. }
  7348. return *a == *b;
  7349. }
  7350. static const char *svg_elem_name(unsigned int node)
  7351. {
  7352. const struct br_node *nd = &doc.nodes[node];
  7353. if (nd->name_off)
  7354. return doc.attrs + nd->name_off;
  7355. return br_tag_name(nd->tag);
  7356. }
  7357. /* A numeric attribute; a percentage resolves against `base`. */
  7358. static double svg_attr_num(unsigned int node, const char *name, double def,
  7359. double base)
  7360. {
  7361. const char *v = br_find_attr(&doc, node, name);
  7362. const char *p = v;
  7363. int ok = 0;
  7364. double x;
  7365. if (!v)
  7366. return def;
  7367. x = svgr_num(&p, &ok);
  7368. if (!ok)
  7369. return def;
  7370. if (*p == '%')
  7371. x = x * base / 100.0;
  7372. return x;
  7373. }
  7374. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  7375. static int svg_viewbox4(unsigned int node, double vb[4])
  7376. {
  7377. const char *v = br_find_attr(&doc, node, "viewbox");
  7378. const char *p = v;
  7379. int i, ok = 1;
  7380. if (!v)
  7381. return 0;
  7382. for (i = 0; i < 4 && ok; i++)
  7383. vb[i] = svgr_num(&p, &ok);
  7384. return ok && vb[2] > 0 && vb[3] > 0;
  7385. }
  7386. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  7387. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  7388. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  7389. double w, double h, double m[6])
  7390. {
  7391. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  7392. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  7393. int ax = 1, ay = 1;
  7394. if (par && contains_ci(par, "none")) {
  7395. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  7396. m[4] = -vb[0] * sx;
  7397. m[5] = -vb[1] * sy;
  7398. return;
  7399. }
  7400. if (par) {
  7401. if (contains_ci(par, "xmin"))
  7402. ax = 0;
  7403. else if (contains_ci(par, "xmax"))
  7404. ax = 2;
  7405. if (contains_ci(par, "ymin"))
  7406. ay = 0;
  7407. else if (contains_ci(par, "ymax"))
  7408. ay = 2;
  7409. }
  7410. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  7411. (sx < sy ? sx : sy);
  7412. tx = (w - vb[2] * s) * ax / 2.0;
  7413. ty = (h - vb[3] * s) * ay / 2.0;
  7414. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  7415. m[4] = tx - vb[0] * s;
  7416. m[5] = ty - vb[1] * s;
  7417. }
  7418. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  7419. * the paint attribute, then average the gradient's stops. */
  7420. static int svg_url_paint(unsigned int node, const char *attr,
  7421. unsigned short *color, unsigned int *alpha)
  7422. {
  7423. const char *v = 0, *h;
  7424. char id[64];
  7425. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  7426. for (k = 0; node && k < 32 && !v; k++) {
  7427. v = br_find_attr(&doc, node, attr);
  7428. if (!v) {
  7429. const char *style = br_find_attr(&doc, node, "style");
  7430. if (style && contains_ci(style, "url(#"))
  7431. v = strstr(style, "url(#");
  7432. }
  7433. if (v && !contains_ci(v, "url("))
  7434. v = 0;
  7435. node = doc.nodes[node].parent;
  7436. }
  7437. if (!v || !(h = strstr(v, "#")))
  7438. return 0;
  7439. h++;
  7440. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  7441. id[n++] = *h++;
  7442. id[n] = '\0';
  7443. g = br_find_id(&doc, id);
  7444. /* Follow href chains (a gradient that only references another one's
  7445. * stops), at most a few hops. */
  7446. for (k = 0; g && k < 4; k++) {
  7447. unsigned int gi = g - 1;
  7448. const char *ref;
  7449. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  7450. const char *nm, *sc, *so;
  7451. unsigned short col = 0;
  7452. double op = 1;
  7453. if (doc.nodes[c].type != BR_NODE_ELEM)
  7454. continue;
  7455. nm = svg_elem_name(c);
  7456. if (!svg_name_is(nm, "stop"))
  7457. continue;
  7458. sc = br_find_attr(&doc, c, "stop-color");
  7459. so = br_find_attr(&doc, c, "stop-opacity");
  7460. {
  7461. const char *st = br_find_attr(&doc, c, "style");
  7462. const char *q;
  7463. if (st && (q = strstr(st, "stop-color:")) != 0)
  7464. sc = q + 11;
  7465. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  7466. so = q + 13;
  7467. }
  7468. if (sc) {
  7469. unsigned int L = 0;
  7470. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  7471. L++;
  7472. if (!br_parse_color(sc, L, &col))
  7473. col = 0;
  7474. }
  7475. if (so) {
  7476. const char *p = so;
  7477. int ok = 0;
  7478. double x = svgr_num(&p, &ok);
  7479. if (ok)
  7480. op = x < 0 ? 0 : x > 1 ? 1 : x;
  7481. }
  7482. sr += (col >> 11) & 31;
  7483. sg += (col >> 5) & 63;
  7484. sb += col & 31;
  7485. sa += (unsigned int)(op * 255);
  7486. cnt++;
  7487. }
  7488. if (cnt)
  7489. break;
  7490. ref = br_find_attr(&doc, gi, "href");
  7491. if (!ref)
  7492. ref = br_find_attr(&doc, gi, "xlink:href");
  7493. if (!ref || ref[0] != '#')
  7494. break;
  7495. g = br_find_id(&doc, ref + 1);
  7496. }
  7497. if (!cnt)
  7498. return 0;
  7499. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  7500. (sb / cnt));
  7501. *alpha = sa / cnt;
  7502. return 1;
  7503. }
  7504. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  7505. unsigned short *color, unsigned int *alpha)
  7506. {
  7507. int mode = fill ? st->fill_mode : st->stroke_mode;
  7508. const char *op = br_find_attr(&doc, node,
  7509. fill ? "fill-opacity" : "stroke-opacity");
  7510. *alpha = 255;
  7511. switch (mode) {
  7512. case BR_PAINT_UNSET:
  7513. if (!fill)
  7514. return 0;
  7515. *color = 0;
  7516. break;
  7517. case BR_PAINT_COLOR:
  7518. *color = fill ? st->fill : st->stroke;
  7519. break;
  7520. case BR_PAINT_CURRENT:
  7521. *color = st->color;
  7522. break;
  7523. case BR_PAINT_URL:
  7524. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  7525. alpha))
  7526. return 0;
  7527. break;
  7528. default:
  7529. return 0;
  7530. }
  7531. if (op) {
  7532. const char *p = op;
  7533. int ok = 0;
  7534. double x = svgr_num(&p, &ok);
  7535. if (ok)
  7536. *alpha = (unsigned int)(*alpha *
  7537. (x < 0 ? 0 : x > 1 ? 1 : x));
  7538. }
  7539. return *alpha > 0;
  7540. }
  7541. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7542. const double m[6], const struct br_style *pst,
  7543. unsigned int alpha, int depth);
  7544. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  7545. const double m[6], const struct br_style *st,
  7546. unsigned int alpha, int depth)
  7547. {
  7548. unsigned int c;
  7549. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  7550. if (doc.nodes[c].type == BR_NODE_ELEM)
  7551. svg_draw_node(L, c, m, st, alpha, depth + 1);
  7552. }
  7553. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7554. const double pm[6], const struct br_style *pst,
  7555. unsigned int alpha, int depth)
  7556. {
  7557. struct br_style st;
  7558. const char *nm = svg_elem_name(node);
  7559. const char *tf;
  7560. double m[6];
  7561. unsigned short color;
  7562. unsigned int pa;
  7563. int shape = 0, fillable = 1;
  7564. if (depth > 24 || !nm)
  7565. return;
  7566. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  7567. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  7568. svg_name_is(nm, "lineargradient") ||
  7569. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  7570. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  7571. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  7572. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  7573. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  7574. svg_name_is(nm, "foreignobject"))
  7575. return;
  7576. br_style_for(&doc, node, pst, &st);
  7577. if (st.display == BR_DISPLAY_NONE)
  7578. return;
  7579. memcpy(m, pm, sizeof(m));
  7580. tf = br_find_attr(&doc, node, "transform");
  7581. if (tf)
  7582. svgr_transform(m, tf);
  7583. {
  7584. const char *op = br_find_attr(&doc, node, "opacity");
  7585. if (op) {
  7586. const char *p = op;
  7587. int ok = 0;
  7588. double x = svgr_num(&p, &ok);
  7589. if (ok)
  7590. alpha = (unsigned int)(alpha *
  7591. (x < 0 ? 0 :
  7592. x > 1 ? 1 : x));
  7593. }
  7594. }
  7595. if (!alpha)
  7596. return;
  7597. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  7598. svg_name_is(nm, "switch")) {
  7599. svg_draw_children(L, node, m, &st, alpha, depth);
  7600. return;
  7601. }
  7602. if (svg_name_is(nm, "svg")) {
  7603. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  7604. y = svg_attr_num(node, "y", 0, 0);
  7605. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7606. t[4] = x;
  7607. t[5] = y;
  7608. svgr_mat_mul(m, m, t);
  7609. double ow = svg_vp_w, oh = svg_vp_h;
  7610. if (svg_viewbox4(node, vb)) {
  7611. double w = svg_attr_num(node, "width", vb[2], ow);
  7612. double h = svg_attr_num(node, "height", vb[3], oh);
  7613. double vm[6];
  7614. svg_viewport_matrix(node, vb, w, h, vm);
  7615. svgr_mat_mul(m, m, vm);
  7616. svg_vp_w = vb[2];
  7617. svg_vp_h = vb[3];
  7618. }
  7619. svg_draw_children(L, node, m, &st, alpha, depth);
  7620. svg_vp_w = ow;
  7621. svg_vp_h = oh;
  7622. return;
  7623. }
  7624. if (svg_name_is(nm, "use")) {
  7625. const char *ref = br_find_attr(&doc, node, "href");
  7626. unsigned int tgt;
  7627. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7628. if (!ref)
  7629. ref = br_find_attr(&doc, node, "xlink:href");
  7630. if (!ref || ref[0] != '#')
  7631. return;
  7632. tgt = br_find_id(&doc, ref + 1);
  7633. if (!tgt || tgt - 1 == node)
  7634. return;
  7635. tgt--;
  7636. t[4] = svg_attr_num(node, "x", 0, 0);
  7637. t[5] = svg_attr_num(node, "y", 0, 0);
  7638. svgr_mat_mul(m, m, t);
  7639. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  7640. double vb[4];
  7641. double ow = svg_vp_w, oh = svg_vp_h;
  7642. if (svg_viewbox4(tgt, vb)) {
  7643. /* A <use> without width/height sizes the
  7644. * symbol to 100% of the viewport: Docusaurus'
  7645. * 13.5px external-link icon references a
  7646. * 24-unit symbol and showed only its corner. */
  7647. double w = svg_attr_num(node, "width",
  7648. ow > 0 ? ow : vb[2], ow);
  7649. double h = svg_attr_num(node, "height",
  7650. oh > 0 ? oh : vb[3], oh);
  7651. double vm[6];
  7652. svg_viewport_matrix(tgt, vb, w, h, vm);
  7653. svgr_mat_mul(m, m, vm);
  7654. svg_vp_w = vb[2];
  7655. svg_vp_h = vb[3];
  7656. }
  7657. svg_draw_children(L, tgt, m, &st, alpha, depth);
  7658. svg_vp_w = ow;
  7659. svg_vp_h = oh;
  7660. } else {
  7661. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  7662. }
  7663. return;
  7664. }
  7665. svgr_reset(&svg_geom, m);
  7666. if (svg_name_is(nm, "path")) {
  7667. const char *d = br_find_attr(&doc, node, "d");
  7668. if (d) {
  7669. svgr_path(&svg_geom, d);
  7670. shape = 1;
  7671. }
  7672. } else if (svg_name_is(nm, "rect")) {
  7673. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  7674. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  7675. double rx = svg_attr_num(node, "rx", -1, w);
  7676. double ry = svg_attr_num(node, "ry", -1, h);
  7677. if (rx < 0)
  7678. rx = ry < 0 ? 0 : ry;
  7679. if (ry < 0)
  7680. ry = rx;
  7681. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  7682. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  7683. shape = 1;
  7684. } else if (svg_name_is(nm, "circle")) {
  7685. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  7686. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7687. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  7688. shape = 1;
  7689. } else if (svg_name_is(nm, "ellipse")) {
  7690. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7691. svg_attr_num(node, "cy", 0, svg_vp_h),
  7692. svg_attr_num(node, "rx", 0, svg_vp_w),
  7693. svg_attr_num(node, "ry", 0, svg_vp_h));
  7694. shape = 1;
  7695. } else if (svg_name_is(nm, "line")) {
  7696. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  7697. svg_attr_num(node, "y1", 0, svg_vp_h));
  7698. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  7699. svg_attr_num(node, "y2", 0, svg_vp_h));
  7700. shape = 1;
  7701. fillable = 0;
  7702. } else if (svg_name_is(nm, "polyline") ||
  7703. svg_name_is(nm, "polygon")) {
  7704. const char *pts = br_find_attr(&doc, node, "points");
  7705. if (pts) {
  7706. svgr_points(&svg_geom, pts,
  7707. svg_name_is(nm, "polygon"));
  7708. shape = 1;
  7709. }
  7710. }
  7711. if (!shape)
  7712. return;
  7713. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  7714. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  7715. st.fill_evenodd);
  7716. if (svg_paint(node, &st, 0, &color, &pa)) {
  7717. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  7718. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7719. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  7720. }
  7721. }
  7722. /* <text> elements: drawn straight onto the page every frame (the glyph
  7723. * renderer targets the ngui canvas, not a layer). x/y map through the
  7724. * accumulated transform; the font size scales with it. */
  7725. static void svg_draw_text(struct ngui *ui, unsigned int node,
  7726. const double pm[6], const struct br_style *pst,
  7727. int ox, int oy, int depth)
  7728. {
  7729. unsigned int c;
  7730. if (depth > 24)
  7731. return;
  7732. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7733. struct br_style st;
  7734. const char *nm, *tf;
  7735. double m[6];
  7736. if (doc.nodes[c].type != BR_NODE_ELEM)
  7737. continue;
  7738. nm = svg_elem_name(c);
  7739. if (!nm || svg_name_is(nm, "defs") ||
  7740. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  7741. svg_name_is(nm, "clippath"))
  7742. continue;
  7743. br_style_for(&doc, c, pst, &st);
  7744. if (st.display == BR_DISPLAY_NONE)
  7745. continue;
  7746. memcpy(m, pm, sizeof(m));
  7747. tf = br_find_attr(&doc, c, "transform");
  7748. if (tf)
  7749. svgr_transform(m, tf);
  7750. if (svg_name_is(nm, "text")) {
  7751. unsigned int t = doc.nodes[c].first;
  7752. const char *s;
  7753. unsigned int n, tw;
  7754. double x = svg_attr_num(c, "x", 0, 0),
  7755. y = svg_attr_num(c, "y", 0, 0);
  7756. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7757. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  7758. int tx, ty, anchor;
  7759. unsigned short col;
  7760. unsigned int pa;
  7761. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  7762. continue;
  7763. if (px < 6)
  7764. px = 6;
  7765. if (px > 72)
  7766. px = 72;
  7767. if (!svg_paint(c, &st, 1, &col, &pa))
  7768. continue;
  7769. s = doc.text + doc.nodes[t].text_off;
  7770. n = doc.nodes[t].text_len;
  7771. st.font_px = (unsigned char)px;
  7772. tw = face_text_width(ui, &st, s, n);
  7773. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  7774. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  7775. ngui_text_ascent_face(ui, style_face(&st), px,
  7776. st.mono);
  7777. anchor = st.align;
  7778. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  7779. anchor = BR_ALIGN_CENTER;
  7780. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  7781. anchor = BR_ALIGN_RIGHT;
  7782. if (anchor == BR_ALIGN_CENTER)
  7783. tx -= (int)tw / 2;
  7784. else if (anchor == BR_ALIGN_RIGHT)
  7785. tx -= (int)tw;
  7786. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  7787. col, px, st.bold, st.italic,
  7788. st.mono);
  7789. } else {
  7790. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  7791. }
  7792. }
  7793. }
  7794. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  7795. {
  7796. double vb[4];
  7797. if (svg_viewbox4(node, vb)) {
  7798. svg_viewport_matrix(node, vb, w, h, m);
  7799. } else {
  7800. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  7801. }
  7802. }
  7803. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  7804. const struct br_style *st)
  7805. {
  7806. struct svg_cache_ent *e = 0;
  7807. struct svgr_layer L;
  7808. double m[6];
  7809. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  7810. svg_cache_clock++;
  7811. for (i = 0; i < SVG_CACHE_MAX; i++)
  7812. if (svg_cache[i].px && svg_cache[i].node == node &&
  7813. svg_cache[i].w == w && svg_cache[i].h == h) {
  7814. svg_cache[i].stamp = svg_cache_clock;
  7815. return &svg_cache[i];
  7816. }
  7817. if (need > SVG_CACHE_PIXELS)
  7818. return 0;
  7819. /* Evict least recently used layers until this one fits. */
  7820. for (;;) {
  7821. struct svg_cache_ent *lru = 0, *free_slot = 0;
  7822. for (i = 0; i < SVG_CACHE_MAX; i++) {
  7823. if (!svg_cache[i].px) {
  7824. if (!free_slot)
  7825. free_slot = &svg_cache[i];
  7826. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  7827. lru = &svg_cache[i];
  7828. }
  7829. }
  7830. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  7831. e = free_slot;
  7832. break;
  7833. }
  7834. if (!lru)
  7835. return 0;
  7836. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  7837. free(lru->px);
  7838. free(lru->a);
  7839. memset(lru, 0, sizeof(*lru));
  7840. }
  7841. if (!svg_geom_buf) {
  7842. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7843. if (!svg_geom_buf)
  7844. return 0;
  7845. }
  7846. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  7847. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  7848. e->a = (unsigned char *)calloc(need, 1);
  7849. if (!e->px || !e->a) {
  7850. free(e->px);
  7851. free(e->a);
  7852. memset(e, 0, sizeof(*e));
  7853. return 0;
  7854. }
  7855. e->node = node;
  7856. e->w = w;
  7857. e->h = h;
  7858. e->stamp = svg_cache_clock;
  7859. svg_cache_pixels += need;
  7860. L.px = e->px;
  7861. L.a = e->a;
  7862. L.w = w;
  7863. L.h = h;
  7864. svg_root_matrix(node, w, h, m);
  7865. {
  7866. double vb[4];
  7867. if (svg_viewbox4(node, vb)) {
  7868. svg_vp_w = vb[2];
  7869. svg_vp_h = vb[3];
  7870. } else {
  7871. svg_vp_w = w;
  7872. svg_vp_h = h;
  7873. }
  7874. }
  7875. svg_draw_children(&L, node, m, st, 255, 0);
  7876. return e;
  7877. }
  7878. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  7879. *
  7880. * The markup is parsed into a detached subtree of the page document and
  7881. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  7882. * bitmap, which then behaves like any decoded image. currentColor is
  7883. * black (an image has no inherited text colour); <text> is not drawn. */
  7884. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  7885. {
  7886. unsigned int i = 0;
  7887. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  7888. i = 3;
  7889. while (i < len) {
  7890. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  7891. d[i] == '\r' || d[i] == '\n'))
  7892. i++;
  7893. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  7894. return 1;
  7895. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  7896. i += 4;
  7897. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  7898. i++;
  7899. i += 3;
  7900. continue;
  7901. }
  7902. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  7903. while (i < len && d[i] != '>')
  7904. i++;
  7905. i++;
  7906. continue;
  7907. }
  7908. return 0;
  7909. }
  7910. return 0;
  7911. }
  7912. static int svg_len_attr(unsigned int node, const char *name)
  7913. {
  7914. const char *v = br_find_attr(&doc, node, name);
  7915. int n = 0, any = 0;
  7916. if (!v)
  7917. return 0;
  7918. while (*v == ' ')
  7919. v++;
  7920. while (*v >= '0' && *v <= '9') {
  7921. n = n * 10 + (*v++ - '0');
  7922. any = 1;
  7923. }
  7924. if (*v == '.')
  7925. while (*++v >= '0' && *v <= '9')
  7926. ;
  7927. if (!any || *v == '%')
  7928. return 0;
  7929. return n;
  7930. }
  7931. static int svg_decode_image(const unsigned char *data, unsigned int len,
  7932. struct br_image *bi, int box_w, int box_h)
  7933. {
  7934. unsigned int holder, svg = 0, c, need, i;
  7935. struct br_style base = base_style(), st;
  7936. struct svgr_layer L;
  7937. double vb[4], m[6];
  7938. int w, h, have_vb, nat_w, nat_h;
  7939. holder = br_create_element(&doc, "div", 3);
  7940. if (!holder) {
  7941. s_copy(bi->err, "page is full", sizeof(bi->err));
  7942. return -1;
  7943. }
  7944. holder--;
  7945. br_set_inner_html(&doc, holder, (const char *)data, len);
  7946. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  7947. if (doc.nodes[c].type == BR_NODE_ELEM &&
  7948. doc.nodes[c].tag == BR_TAG_SVG) {
  7949. svg = c;
  7950. break;
  7951. }
  7952. if (!svg) {
  7953. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  7954. return -1;
  7955. }
  7956. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  7957. w = svg_len_attr(svg, "width");
  7958. h = svg_len_attr(svg, "height");
  7959. if (box_w > 0 && box_h > 0) {
  7960. w = box_w;
  7961. h = box_h;
  7962. } else if (!w && !h) {
  7963. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  7964. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  7965. } else if (!w) {
  7966. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  7967. } else if (!h) {
  7968. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  7969. }
  7970. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  7971. * so CSS scaling stays crisp. */
  7972. nat_w = w;
  7973. nat_h = h;
  7974. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  7975. w *= 2;
  7976. h *= 2;
  7977. }
  7978. if (w > BR_IMG_LAYOUT_W) {
  7979. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  7980. w = BR_IMG_LAYOUT_W;
  7981. }
  7982. if (h > 2048)
  7983. h = 2048;
  7984. if (w < 1)
  7985. w = 1;
  7986. if (h < 1)
  7987. h = 1;
  7988. need = (unsigned int)w * (unsigned int)h;
  7989. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  7990. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  7991. return -1;
  7992. }
  7993. if (!svg_geom_buf) {
  7994. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7995. if (!svg_geom_buf) {
  7996. s_copy(bi->err, "out of memory", sizeof(bi->err));
  7997. return -1;
  7998. }
  7999. }
  8000. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  8001. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  8002. L.a = (unsigned char *)calloc(need, 1);
  8003. if (!L.px || !L.a) {
  8004. free(L.px);
  8005. free(L.a);
  8006. s_copy(bi->err, "out of memory", sizeof(bi->err));
  8007. return -1;
  8008. }
  8009. for (i = 0; i < need; i++)
  8010. L.px[i] = 0xFFFF;
  8011. L.w = w;
  8012. L.h = h;
  8013. base.color = 0x0000;
  8014. br_style_for(&doc, svg, &base, &st);
  8015. svg_root_matrix(svg, w, h, m);
  8016. if (!have_vb && nat_w > 0 && nat_h > 0) {
  8017. /* No viewBox: user units are CSS pixels of the natural size,
  8018. * so the up-to-4x raster (and a box size) must scale them.
  8019. * A 40x20 icon used to fill only the top-left quarter of its
  8020. * 160x80 bitmap and was drawn at a quarter of its size. */
  8021. m[0] = (double)w / nat_w;
  8022. m[3] = (double)h / nat_h;
  8023. }
  8024. svg_vp_w = have_vb ? vb[2] : nat_w;
  8025. svg_vp_h = have_vb ? vb[3] : nat_h;
  8026. svg_draw_children(&L, svg, m, &st, 255, 0);
  8027. bi->native_w = nat_w;
  8028. bi->native_h = nat_h;
  8029. bi->img.format = 0;
  8030. bi->img.w = (unsigned int)w;
  8031. bi->img.h = (unsigned int)h;
  8032. bi->img.px = L.px;
  8033. bi->img.alpha = L.a;
  8034. bi->img.flags = 0;
  8035. bi->state = 1;
  8036. image_pixels += need;
  8037. return 0;
  8038. }
  8039. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  8040. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  8041. int *out_w, int *out_h)
  8042. {
  8043. double vb[4];
  8044. int has_vb = svg_viewbox4(node, vb);
  8045. double aw = svg_attr_num(node, "width", -1, cw);
  8046. double ah = svg_attr_num(node, "height", -1, 0);
  8047. int w, h;
  8048. if (st->width_kind)
  8049. w = cw;
  8050. else if (aw > 0)
  8051. w = (int)(aw + 0.5);
  8052. else if (st->height_kind == 1 && has_vb)
  8053. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  8054. else if (ah > 0 && has_vb)
  8055. w = (int)(ah * vb[2] / vb[3] + 0.5);
  8056. else if (has_vb)
  8057. w = cw;
  8058. else
  8059. w = 300;
  8060. if (st->max_width_kind == 1 && w > st->max_width)
  8061. w = st->max_width;
  8062. if (w > cw && cw > 0 && !(aw > 0))
  8063. w = cw;
  8064. if (w < 1)
  8065. w = 1;
  8066. if (w > 2000)
  8067. w = 2000;
  8068. if (st->height_kind == 1)
  8069. h = st->height;
  8070. else if (ah > 0)
  8071. h = (int)(ah + 0.5);
  8072. else if (has_vb)
  8073. h = (int)(w * vb[3] / vb[2] + 0.5);
  8074. else
  8075. h = 150;
  8076. if (h < 1)
  8077. h = 1;
  8078. if (h > 1400)
  8079. h = 1400;
  8080. *out_w = w;
  8081. *out_h = h;
  8082. }
  8083. static void svg_paint_box(struct ngui *ui, unsigned int node,
  8084. const struct br_style *st, int x, int y, int w, int h)
  8085. {
  8086. struct svg_cache_ent *e;
  8087. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  8088. int cx0, cy0, cx1, cy1, px, py;
  8089. double m[6];
  8090. if (ui->nclip > 0)
  8091. clip = ui->clip[ui->nclip - 1];
  8092. cx0 = r.x > clip.x ? r.x : clip.x;
  8093. cy0 = r.y > clip.y ? r.y : clip.y;
  8094. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  8095. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  8096. if (cx0 >= cx1 || cy0 >= cy1)
  8097. return;
  8098. e = svg_layer(node, w, h, st);
  8099. if (e) {
  8100. for (py = cy0; py < cy1; py++) {
  8101. unsigned int srow = (unsigned int)(py - y) *
  8102. (unsigned int)w;
  8103. unsigned short *dst = ui->px + py * ui->w;
  8104. for (px = cx0; px < cx1; px++) {
  8105. unsigned int si = srow + (unsigned int)(px - x);
  8106. unsigned int a = e->a[si];
  8107. if (!a)
  8108. continue;
  8109. dst[px] = a >= 255 ? e->px[si] :
  8110. blend_rgb565(dst[px], e->px[si], a);
  8111. }
  8112. }
  8113. }
  8114. svg_root_matrix(node, w, h, m);
  8115. ngui_push_clip(ui, r);
  8116. svg_draw_text(ui, node, m, st, x, y, 0);
  8117. ngui_pop_clip(ui);
  8118. }
  8119. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  8120. * keep using add_image_run(); this covers the CSS `position:absolute;
  8121. * width:100%` poster pattern used by news sites. */
  8122. static void image_block_size(unsigned int node, const struct br_style *st,
  8123. int cbw, int *out_w, int *out_h)
  8124. {
  8125. struct br_node *nd = &doc.nodes[node];
  8126. int idx = nd->img_index;
  8127. int iw = 0, ih = 0, w, h, aw, ah;
  8128. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  8129. iw = (int)images[idx].img.w;
  8130. ih = (int)images[idx].img.h;
  8131. if (iw <= 0 || ih <= 0) {
  8132. iw = (int)images[idx].native_w;
  8133. ih = (int)images[idx].native_h;
  8134. }
  8135. }
  8136. if (st->width_kind)
  8137. w = style_width_px(st, cbw);
  8138. else if (nd->width_attr)
  8139. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  8140. (int)nd->width_attr;
  8141. else if (nd->height_attr && !nd->height_pct && iw && ih)
  8142. w = iw * (int)nd->height_attr / ih;
  8143. else if (iw)
  8144. w = iw;
  8145. else
  8146. w = 64;
  8147. /* max-width/min-width against the containing block: Tailwind's
  8148. * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
  8149. * 300x300 thumbnail to its 75 px avatar box. */
  8150. if (st->max_width_kind) {
  8151. int mw = st->max_width_kind == 3 ?
  8152. cbw * st->max_width_calc_pct / 100 +
  8153. st->max_width_calc_px :
  8154. st->max_width_kind == 2 ?
  8155. cbw * (int)st->max_width / 100 : (int)st->max_width;
  8156. if (mw > 0 && w > mw)
  8157. w = mw;
  8158. }
  8159. if (st->min_width_kind) {
  8160. int mn = st->min_width_kind == 3 ?
  8161. cbw * st->min_width_calc_pct / 100 +
  8162. st->min_width_calc_px :
  8163. st->min_width_kind == 2 ?
  8164. cbw * (int)st->min_width / 100 : (int)st->min_width;
  8165. if (mn > w)
  8166. w = mn;
  8167. }
  8168. if (w < 8)
  8169. w = 8;
  8170. if (cbw > 0 && w > cbw)
  8171. w = cbw;
  8172. /* Without a CSS height the attributes (or the bitmap) only give the
  8173. * aspect ratio: a width clamped by max-width scales the height too,
  8174. * instead of letterboxing the image into its attribute height. */
  8175. aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
  8176. ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
  8177. if (st->height_kind)
  8178. h = style_height_px(st, cbw);
  8179. else if (aw > 0 && ah > 0)
  8180. h = w * ah / aw;
  8181. else if (nd->height_attr)
  8182. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  8183. (int)nd->height_attr;
  8184. else
  8185. h = 64;
  8186. if (h < 8)
  8187. h = 8;
  8188. *out_w = w;
  8189. *out_h = h;
  8190. }
  8191. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  8192. int dw, int dh)
  8193. {
  8194. int idx = doc.nodes[node].img_index;
  8195. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  8196. struct img_image *src = image_display_get(&images[idx], dw, dh);
  8197. struct img_blit b;
  8198. if (!src)
  8199. src = &images[idx].img;
  8200. b.dst = l->ui->px;
  8201. b.dst_w = l->ui->w;
  8202. b.dst_h = l->ui->h;
  8203. b.clip_x = page_rect.x;
  8204. b.clip_y = page_rect.y;
  8205. b.clip_w = page_rect.w - 12;
  8206. b.clip_h = page_rect.h;
  8207. b.x = x;
  8208. b.y = y;
  8209. b.scale = ((unsigned int)dw << 16) / src->w;
  8210. b.bg = ui.theme.bg;
  8211. b.bg2 = ui.theme.bg;
  8212. b.dst_a = 0;
  8213. /* OVER_DST is only needed for an alpha source; an opaque one can
  8214. * take img_draw's 1:1 copy path. */
  8215. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  8216. img_draw(src, &b);
  8217. } else if (l->draw) {
  8218. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  8219. 0xD69A);
  8220. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  8221. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  8222. }
  8223. }
  8224. static void layout_block(struct lay *l, unsigned int node,
  8225. const struct br_style *st, int depth,
  8226. unsigned short link)
  8227. {
  8228. int old_left = l->left, old_right = l->right, old_align = l->align;
  8229. int parent_cb_h = l->cb_h;
  8230. int saved_parent_top = l->parent_top;
  8231. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  8232. int saved_cb_top = l->cb_top;
  8233. int top, l0, r0;
  8234. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  8235. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  8236. int deco_w, deco_h, content_w, content_h, box_h;
  8237. int img_dh = 0;
  8238. int definite_w = 0;
  8239. int normal_top = 0;
  8240. int rel_dx = 0, rel_dy = 0;
  8241. int clip_pushed = 0;
  8242. struct ngui_rect clip_rect;
  8243. /* A DOM level costs about two depth units (layout_block ->
  8244. * layout_children), so 48 covers a ~24-level page. Real news pages
  8245. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  8246. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  8247. return;
  8248. flow_y = l->y;
  8249. flow_left = l->left;
  8250. flow_right = l->right;
  8251. positioned = st->pos == 1 || st->pos == 2;
  8252. relative = st->pos == 3;
  8253. sticky = st->pos == 4;
  8254. shifted = relative || sticky || st->transform_set;
  8255. if (positioned) {
  8256. int def_w = st->width_kind == 1 ? st->width : -1;
  8257. if (st->pos == 2) {
  8258. int avail_w = page_rect.w - 12;
  8259. if (st->right_set && def_w >= 0)
  8260. l->left = page_rect.x + avail_w - st->right -
  8261. def_w;
  8262. else if (!st->left_set && !st->right_set)
  8263. l->left = flow_left; /* static position */
  8264. else
  8265. l->left = page_rect.x +
  8266. (st->left_set ? st->left : 0);
  8267. l->right = def_w >= 0 ? l->left + def_w :
  8268. st->width_kind == 2 ?
  8269. l->left + avail_w * (int)st->width / 100 :
  8270. page_rect.x + avail_w;
  8271. /* Placed by `bottom` (a page footer): an auto
  8272. * height is the measured one. */
  8273. if (st->bottom_set && st->height_kind)
  8274. l->y = page_rect.y + page_rect.h -
  8275. st->bottom -
  8276. style_height_px(st, page_rect.w);
  8277. else if (st->bottom_set && !st->top_set &&
  8278. block_h[node])
  8279. l->y = page_rect.y + page_rect.h -
  8280. st->bottom - (int)block_h[node] -
  8281. mp_px(st, 0, avail_w) -
  8282. mp_px(st, 2, avail_w);
  8283. else
  8284. l->y = page_rect.y +
  8285. (st->top_set ? st->top : 0);
  8286. } else {
  8287. int left = flow_left + (st->left_set ? st->left : 0);
  8288. unsigned int parent = doc.nodes[node].parent;
  8289. if (st->right_set && def_w >= 0)
  8290. left = flow_right - st->right - def_w;
  8291. l->left = left;
  8292. l->right = def_w >= 0 ? left + def_w :
  8293. flow_right +
  8294. (st->left_set ? st->left : 0);
  8295. l->y = flow_y + (st->top_set ? st->top : 0);
  8296. if (st->bottom_set && st->height_kind &&
  8297. parent < BR_MAX_NODES && block_h[parent] > 0)
  8298. l->y = flow_y + block_h[parent] - st->bottom -
  8299. style_height_px(st, old_right - old_left);
  8300. else if (st->bottom_set && !st->top_set &&
  8301. parent < BR_MAX_NODES && block_h[parent] > 0 &&
  8302. block_h[node] > 0)
  8303. l->y = flow_y + block_h[parent] - st->bottom -
  8304. (int)block_h[node] -
  8305. mp_px(st, 0, old_right - old_left) -
  8306. mp_px(st, 2, old_right - old_left);
  8307. }
  8308. /* `left: 100%` parks a box (Docusaurus' "Skip to main
  8309. * content" link) past the containing block's right edge
  8310. * until it is focused. An auto width then has no room: it
  8311. * used to collapse to 8 px and wrap one word per line into a
  8312. * tall column painted over the page. Lay it out at the
  8313. * containing block's width so it stays one line and
  8314. * overflows (off-screen) like in a real browser. */
  8315. if (def_w < 0 && l->right - l->left < 8) {
  8316. int avail = st->pos == 2 ? page_rect.w - 12 :
  8317. flow_right - flow_left;
  8318. l->right = l->left + (avail > 8 ? avail : 8);
  8319. }
  8320. old_left = l->left;
  8321. old_right = l->right;
  8322. } else if (relative) {
  8323. rel_dx = st->left_set ? st->left :
  8324. (st->right_set ? -st->right : 0);
  8325. rel_dy = st->top_set ? st->top :
  8326. (st->bottom_set ? -st->bottom : 0);
  8327. }
  8328. if (st->transform_set) {
  8329. rel_dx += st->tx;
  8330. rel_dy += st->ty;
  8331. }
  8332. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  8333. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  8334. doc.nodes[node].tag == BR_TAG_SELECT ||
  8335. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  8336. !button_has_elements(node)) {
  8337. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  8338. s_eq(br_type(&doc, node), "hidden"))
  8339. return;
  8340. /* Reached as a block-level box (a flex item): the control
  8341. * fills the box the caller assigned, and its line is flushed
  8342. * here; flex layout resets the run list for the next item, so
  8343. * a queued run would never be drawn. */
  8344. form_fill_line = 1;
  8345. add_form_run(l, node, st, link);
  8346. form_fill_line = 0;
  8347. flush_line(l);
  8348. return;
  8349. }
  8350. flush_line(l);
  8351. cbw = old_right - old_left;
  8352. if (cbw < 8)
  8353. cbw = 8;
  8354. l->y += mp_px(st, 0, cbw);
  8355. top = l->y;
  8356. ml = mp_px(st, 3, cbw);
  8357. mr = mp_px(st, 1, cbw);
  8358. bl = st->border_w[3];
  8359. br = st->border_w[1];
  8360. pl = mp_px(st, 7, cbw);
  8361. pr = mp_px(st, 5, cbw);
  8362. bt = st->border_w[0];
  8363. bb = st->border_w[2];
  8364. pt = mp_px(st, 4, cbw);
  8365. pb = mp_px(st, 6, cbw);
  8366. deco_w = bl + br + pl + pr;
  8367. deco_h = bt + bb + pt + pb;
  8368. if (st->width_kind) {
  8369. int w;
  8370. if (st->width_kind == 3)
  8371. w = cbw * st->width_calc_pct / 100 +
  8372. st->width_calc_px;
  8373. else
  8374. w = css_size(st->width_kind, st->width, cbw);
  8375. if (w < 0)
  8376. w = 0;
  8377. content_w = st->box_sizing ? w - deco_w : w;
  8378. definite_w = 1;
  8379. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  8380. doc.nodes[node].tag == BR_TAG_TD ||
  8381. doc.nodes[node].tag == BR_TAG_TH) &&
  8382. doc.nodes[node].width_attr) {
  8383. /* Legacy table/cell width attributes: percentages resolve
  8384. * against the containing block, bare numbers are pixels. */
  8385. int w = doc.nodes[node].width_pct ?
  8386. cbw * doc.nodes[node].width_attr / 100 :
  8387. doc.nodes[node].width_attr;
  8388. if (w < 0)
  8389. w = 0;
  8390. content_w = st->box_sizing ? w - deco_w : w;
  8391. definite_w = 1;
  8392. } else {
  8393. content_w = cbw - ml - mr - deco_w;
  8394. }
  8395. if (content_w < 0)
  8396. content_w = 0;
  8397. if (st->max_width_kind) {
  8398. int mw = st->max_width_kind == 3 ?
  8399. cbw * st->max_width_calc_pct / 100 +
  8400. st->max_width_calc_px :
  8401. css_size(st->max_width_kind, st->max_width, cbw);
  8402. int max_box = st->box_sizing ? mw : mw + deco_w;
  8403. /* A clamped auto width is used as the width, so auto
  8404. * margins share the rest (Google's 688 px search box). */
  8405. if (content_w + deco_w > max_box) {
  8406. content_w = max_box - deco_w;
  8407. definite_w = 1;
  8408. }
  8409. }
  8410. if (st->min_width_kind) {
  8411. int mw = st->min_width_kind == 3 ?
  8412. cbw * st->min_width_calc_pct / 100 +
  8413. st->min_width_calc_px :
  8414. css_size(st->min_width_kind, st->min_width, cbw);
  8415. int min_box = st->box_sizing ? mw : mw + deco_w;
  8416. if (content_w + deco_w < min_box) {
  8417. content_w = min_box - deco_w;
  8418. definite_w = 1;
  8419. }
  8420. }
  8421. if (content_w < 8)
  8422. content_w = 8;
  8423. if (definite_w) {
  8424. int free_w = cbw - ml - mr - deco_w - content_w;
  8425. if (free_w < 0)
  8426. free_w = 0;
  8427. if (st->ml_auto && st->mr_auto) {
  8428. ml = free_w / 2;
  8429. mr = free_w - ml;
  8430. } else if (st->ml_auto) {
  8431. ml = free_w;
  8432. } else if (st->mr_auto) {
  8433. mr = free_w;
  8434. }
  8435. }
  8436. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8437. int iw, ih;
  8438. image_block_size(node, st, cbw, &iw, &ih);
  8439. content_w = iw;
  8440. img_dh = ih;
  8441. }
  8442. l0 = old_left + ml;
  8443. r0 = l0 + deco_w + content_w;
  8444. if (r0 < l0 + 8)
  8445. r0 = l0 + 8;
  8446. normal_top = top;
  8447. if (sticky) {
  8448. if (st->top_set) {
  8449. int stick = page_rect.y + st->top;
  8450. if (normal_top < stick)
  8451. rel_dy += stick - normal_top;
  8452. } else if (st->bottom_set && block_h[node]) {
  8453. int stick = page_rect.y + page_rect.h - st->bottom -
  8454. block_h[node];
  8455. if (normal_top > stick)
  8456. rel_dy += stick - normal_top;
  8457. }
  8458. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  8459. block_h[doc.nodes[node].parent]) {
  8460. unsigned int p = doc.nodes[node].parent;
  8461. int ptop = l->parent_top;
  8462. int pbottom = ptop + block_h[p];
  8463. int eh = block_h[node];
  8464. int moved_top = normal_top + rel_dy;
  8465. int moved_bottom = moved_top + eh;
  8466. if (moved_bottom > pbottom)
  8467. rel_dy -= moved_bottom - pbottom;
  8468. moved_top = normal_top + rel_dy;
  8469. if (moved_top < ptop)
  8470. rel_dy += ptop - moved_top;
  8471. }
  8472. }
  8473. if (shifted && l->draw) {
  8474. top += rel_dy;
  8475. l0 += rel_dx;
  8476. r0 += rel_dx;
  8477. }
  8478. l->parent_top = top;
  8479. if (st->pos != 0) {
  8480. /* Positioned boxes establish the containing block for their
  8481. * absolutely positioned descendants. */
  8482. l->cb_left = l0;
  8483. l->cb_right = r0;
  8484. l->cb_top = top;
  8485. }
  8486. if (l->draw && block_h[node] &&
  8487. top < page_rect.y + page_rect.h &&
  8488. top + block_h[node] > page_rect.y) {
  8489. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  8490. int rtl = css_radius(st, 0, box.w, box.h);
  8491. int rtr = css_radius(st, 1, box.w, box.h);
  8492. int rbr = css_radius(st, 2, box.w, box.h);
  8493. int rbl = css_radius(st, 3, box.w, box.h);
  8494. if (st->transform_scale) {
  8495. if (st->has_bg)
  8496. fill_transformed_rect(l->ui, box, st->bg, st);
  8497. } else if (rtl || rtr || rbr || rbl) {
  8498. if (st->has_bg) {
  8499. int bw = st->border_w[0];
  8500. if (bw > 0 && !st->border_t[0] &&
  8501. st->border_c[0] != st->bg &&
  8502. box.w > bw * 2 && box.h > bw * 2) {
  8503. struct ngui_rect inner = {
  8504. box.x + bw, box.y + bw,
  8505. box.w - bw * 2, box.h - bw * 2
  8506. };
  8507. int itl = rtl > bw ? rtl - bw : 0;
  8508. int itr = rtr > bw ? rtr - bw : 0;
  8509. int ibr = rbr > bw ? rbr - bw : 0;
  8510. int ibl = rbl > bw ? rbl - bw : 0;
  8511. ngui_fill_round_rect(l->ui, box, rtl,
  8512. rtr, rbr, rbl,
  8513. st->border_c[0]);
  8514. ngui_fill_round_rect(l->ui, inner,
  8515. itl, itr, ibr,
  8516. ibl, st->bg);
  8517. } else {
  8518. ngui_fill_round_rect(l->ui, box, rtl,
  8519. rtr, rbr, rbl,
  8520. st->bg);
  8521. }
  8522. } else if (st->border_w[0] && !st->border_t[0]) {
  8523. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  8524. rbl, st->border_w[0],
  8525. st->border_c[0]);
  8526. }
  8527. /* Rounded boxes paint their background image too
  8528. * (app icons are rounded squares), kept inside the
  8529. * corner arcs. */
  8530. if (st->bg_image)
  8531. draw_bg_image_round(l, box, node, st, rtl, rtr,
  8532. rbr, rbl);
  8533. } else {
  8534. if (st->has_bg)
  8535. ngui_fill_rect(l->ui, box, st->bg);
  8536. if (st->bg_image)
  8537. draw_bg_image(l, box, node, st);
  8538. if (st->border_w[0] || st->border_w[1] ||
  8539. st->border_w[2] || st->border_w[3])
  8540. draw_border_box(l->ui, box, st);
  8541. }
  8542. }
  8543. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  8544. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  8545. content_w, img_dh);
  8546. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  8547. l->ui && l->ui->nclip < 4) {
  8548. clip_rect.x = l0 + bl;
  8549. clip_rect.y = top + bt;
  8550. clip_rect.w = (r0 - l0) - bl - br;
  8551. clip_rect.h = (int)block_h[node] - bt - bb;
  8552. if (clip_rect.w > 0 && clip_rect.h > 0) {
  8553. ngui_push_clip(l->ui, clip_rect);
  8554. clip_pushed = 1;
  8555. }
  8556. }
  8557. l->left = l0 + bl + pl;
  8558. l->right = l->left + content_w;
  8559. if (l->right < l->left + 8)
  8560. l->right = l->left + 8;
  8561. l->align = st->align;
  8562. l->line_left = l->left;
  8563. l->line_right = l->right;
  8564. l->y = top + bt + pt;
  8565. if (doc.nodes[node].tag == BR_TAG_HR) {
  8566. if (l->draw)
  8567. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  8568. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  8569. l->y += 8;
  8570. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  8571. int vw = l->right - l->left;
  8572. int vh;
  8573. if (doc.nodes[node].width_pct)
  8574. vw = vw * doc.nodes[node].width_attr / 100;
  8575. else if (doc.nodes[node].width_attr)
  8576. vw = doc.nodes[node].width_attr;
  8577. if (vw > l->right - l->left)
  8578. vw = l->right - l->left;
  8579. if (vw < 8)
  8580. vw = 8;
  8581. vh = vw * 9 / 16;
  8582. if (vh > 240)
  8583. vh = 240;
  8584. if (vh < 80)
  8585. vh = 80;
  8586. if (l->draw) {
  8587. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  8588. vw, vh}, 0xD69A);
  8589. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  8590. vw, vh}, 0x8410);
  8591. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  8592. 0x4208);
  8593. }
  8594. l->y += vh + 4;
  8595. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  8596. int dw, dh, cw = l->right - l->left;
  8597. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  8598. if (l->draw && l->y < page_rect.y + page_rect.h &&
  8599. l->y + dh > page_rect.y)
  8600. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  8601. l->y += dh;
  8602. } else {
  8603. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  8604. !st->no_bullet) {
  8605. char *m = li_marker[node];
  8606. if (!m[0]) {
  8607. unsigned int parent = doc.nodes[node].parent;
  8608. int style = st->list_style;
  8609. int idx = parent ? list_index(parent, node) : 1;
  8610. if (style == BR_LIST_AUTO)
  8611. style = (parent &&
  8612. doc.nodes[parent].tag ==
  8613. BR_TAG_OL) ?
  8614. BR_LIST_DECIMAL : BR_LIST_DISC;
  8615. list_marker_text(m, sizeof(li_marker[node]),
  8616. style, idx);
  8617. }
  8618. if (l->draw && m[0]) {
  8619. int mw = (int)ngui_text_width_ui(l->ui, m);
  8620. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  8621. st->color);
  8622. }
  8623. }
  8624. /* This box's definite content height, for its children's
  8625. * percentage heights. */
  8626. if (doc.nodes[node].tag == BR_TAG_HTML ||
  8627. doc.nodes[node].tag == BR_TAG_BODY)
  8628. l->cb_h = layout_view_h;
  8629. else if (st->height_kind == 1)
  8630. l->cb_h = (int)st->height -
  8631. (st->box_sizing ? deco_h : 0);
  8632. else if (st->height_kind == 2 && parent_cb_h > 0)
  8633. l->cb_h = parent_cb_h * (int)st->height / 100 -
  8634. (st->box_sizing ? deco_h : 0);
  8635. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  8636. l->cb_h = content_w * (int)st->aspect_h /
  8637. (int)st->aspect_w;
  8638. else if (!st->height_kind && node < BR_MAX_NODES &&
  8639. flex_stretch_h[node] > deco_h)
  8640. l->cb_h = flex_stretch_h[node] - deco_h;
  8641. else
  8642. l->cb_h = 0;
  8643. if (l->cb_h < 0)
  8644. l->cb_h = 0;
  8645. if (doc.nodes[node].tag == BR_TAG_TR)
  8646. layout_table_row(l, node, st, depth + 1, link);
  8647. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  8648. table_has_rowspan(node))
  8649. layout_table(l, node, st, depth + 1, link);
  8650. else if (st->grid_auto)
  8651. layout_grid_auto(l, node, st, depth + 1, link);
  8652. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  8653. st->grid_gap > 0)
  8654. layout_grid_children(l, node, st, depth + 1, link);
  8655. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  8656. flex_wants_row(node, st))
  8657. layout_flex_children(l, node, st, depth + 1, link);
  8658. else if (st->display == BR_DISPLAY_FLEX && st->flex_col)
  8659. layout_flex_column(l, node, st, depth + 1, link);
  8660. else
  8661. layout_children(l, node, st, depth + 1, link);
  8662. l->cb_h = parent_cb_h;
  8663. }
  8664. flush_line(l);
  8665. if (clip_pushed)
  8666. ngui_pop_clip(l->ui);
  8667. if (l->float_active) {
  8668. if (l->y < l->float_bottom)
  8669. l->y = l->float_bottom;
  8670. l->float_active = 0;
  8671. }
  8672. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8673. content_h = img_dh;
  8674. } else if (st->height_kind == 2 &&
  8675. doc.nodes[node].tag != BR_TAG_HTML &&
  8676. doc.nodes[node].tag != BR_TAG_BODY) {
  8677. /* A percentage of the containing block's definite height, or
  8678. * auto when it has none (it used to resolve against the
  8679. * width). The result is a minimum: without scrollable inner
  8680. * boxes, an app shell's height:100%; overflow:hidden column
  8681. * would otherwise clip everything past the first screen. */
  8682. int auto_h = l->y - (top + bt + pt);
  8683. content_h = parent_cb_h > 0 ?
  8684. parent_cb_h * (int)st->height / 100 -
  8685. (st->box_sizing ? deco_h : 0) : 0;
  8686. if (content_h < auto_h)
  8687. content_h = auto_h;
  8688. } else if (st->height_kind &&
  8689. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8690. doc.nodes[node].tag == BR_TAG_BODY) &&
  8691. st->height_kind == 2)) {
  8692. content_h = style_height_px(st, cbw);
  8693. if (st->box_sizing)
  8694. content_h -= deco_h;
  8695. } else {
  8696. /* Percentage heights on html/body resolve against the
  8697. * viewport, but their content still defines the document
  8698. * scroll height. Treating them as auto avoids collapsing
  8699. * the measured page to the containing block width. */
  8700. content_h = l->y - (top + bt + pt);
  8701. /* aspect-ratio: the preferred height of an auto-height box
  8702. * (Tailwind aspect-video image frames); content can still
  8703. * make it taller, as with min-height: auto. */
  8704. if (st->aspect_w && st->aspect_h && content_w > 0) {
  8705. int ah = content_w * (int)st->aspect_h /
  8706. (int)st->aspect_w;
  8707. if (content_h < ah)
  8708. content_h = ah;
  8709. }
  8710. }
  8711. if (content_h < 0)
  8712. content_h = 0;
  8713. if (!st->height_kind && node < BR_MAX_NODES &&
  8714. content_h + deco_h < flex_stretch_h[node])
  8715. content_h = flex_stretch_h[node] - deco_h;
  8716. if (st->max_height_kind) {
  8717. int mh = st->max_height_kind == 3 ?
  8718. cbw * st->max_height_calc_pct / 100 +
  8719. st->max_height_calc_px :
  8720. css_size(st->max_height_kind, st->max_height, cbw);
  8721. int max_box = st->box_sizing ? mh : mh + deco_h;
  8722. if (content_h + deco_h > max_box)
  8723. content_h = max_box - deco_h;
  8724. }
  8725. if (st->min_height_kind &&
  8726. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8727. doc.nodes[node].tag == BR_TAG_BODY) &&
  8728. st->min_height_kind == 2)) {
  8729. int mh = st->min_height_kind == 3 ?
  8730. cbw * st->min_height_calc_pct / 100 +
  8731. st->min_height_calc_px :
  8732. css_size(st->min_height_kind, st->min_height, cbw);
  8733. int min_box = st->box_sizing ? mh : mh + deco_h;
  8734. if (content_h + deco_h < min_box)
  8735. content_h = min_box - deco_h;
  8736. }
  8737. if (content_h < 0)
  8738. content_h = 0;
  8739. box_h = deco_h + content_h;
  8740. if (box_h < 0)
  8741. box_h = 0;
  8742. l->y = (shifted ? normal_top : top) + box_h;
  8743. if (node < BR_MAX_NODES) {
  8744. layout_boxes[node].x = l0;
  8745. layout_boxes[node].y = top;
  8746. layout_boxes[node].w = r0 - l0;
  8747. layout_boxes[node].h = box_h;
  8748. layout_boxes[node].valid = r0 > l0;
  8749. }
  8750. l->left = old_left;
  8751. l->right = old_right;
  8752. l->align = old_align;
  8753. l->y += mp_px(st, 2, cbw);
  8754. if (!l->draw) {
  8755. if (box_h > 65535)
  8756. box_h = 65535;
  8757. block_h[node] = (unsigned short)box_h;
  8758. block_top[node] = (unsigned short)(top < 0 ? 0 :
  8759. top > 65535 ? 65535 : top);
  8760. }
  8761. if (positioned) {
  8762. l->y = flow_y;
  8763. l->left = flow_left;
  8764. l->right = flow_right;
  8765. }
  8766. l->parent_top = saved_parent_top;
  8767. l->cb_left = saved_cb_left;
  8768. l->cb_right = saved_cb_right;
  8769. l->cb_top = saved_cb_top;
  8770. }
  8771. static int text_node_blank(const struct br_node *nd)
  8772. {
  8773. const char *t = doc.text + nd->text_off;
  8774. unsigned int i;
  8775. for (i = 0; i < nd->text_len; i++)
  8776. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  8777. t[i] != '\r')
  8778. return 0;
  8779. return 1;
  8780. }
  8781. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  8782. * text/image widths in the subtree, plus padding and margins. This keeps
  8783. * Bootstrap's floated nav items on one line instead of giving each the whole
  8784. * row. */
  8785. static int text_space(char c)
  8786. {
  8787. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  8788. }
  8789. static int intrinsic_width(struct ngui *ui, unsigned int node,
  8790. const struct br_style *pst, int depth, int base)
  8791. {
  8792. unsigned int c;
  8793. int line_w = 0, max_w = 0;
  8794. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  8795. if (depth > 32)
  8796. return 0;
  8797. if (doc.npe_rules) {
  8798. struct br_style ps;
  8799. /* Icon boxes (::before/::after with a size) are inline
  8800. * content of the element. */
  8801. line_w += pseudo_box_w(node, pst, 1, &ps, base) +
  8802. pseudo_box_w(node, pst, 2, &ps, base);
  8803. }
  8804. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8805. struct br_node *nd = &doc.nodes[c];
  8806. struct br_style cs;
  8807. if (nd->type == BR_NODE_TEXT) {
  8808. const char *t = doc.text + nd->text_off;
  8809. unsigned int tn = nd->text_len;
  8810. if (doc.nodes[node].tag == BR_TAG_PRE) {
  8811. line_w += (int)face_text_width(ui, pst, t, tn);
  8812. } else {
  8813. unsigned int ti = 0;
  8814. int first = 1;
  8815. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  8816. int sp = (int)face_text_width(ui, pst, " ", 1);
  8817. while (ti < tn) {
  8818. unsigned int ts;
  8819. while (ti < tn && text_space(t[ti]))
  8820. ti++;
  8821. ts = ti;
  8822. while (ti < tn && !text_space(t[ti]))
  8823. ti++;
  8824. if (ti == ts)
  8825. break;
  8826. if (!first || lead)
  8827. line_w += sp;
  8828. lead = 0;
  8829. line_w += (int)face_text_width(ui, pst,
  8830. t + ts, ti - ts);
  8831. first = 0;
  8832. }
  8833. }
  8834. continue;
  8835. }
  8836. br_style_for(&doc, c, pst, &cs);
  8837. if (cs.display == BR_DISPLAY_NONE)
  8838. continue;
  8839. if (nd->tag == BR_TAG_BR) {
  8840. if (line_w > max_w)
  8841. max_w = line_w;
  8842. line_w = 0;
  8843. continue;
  8844. }
  8845. if (nd->tag == BR_TAG_IMG) {
  8846. /* Measure the image as layout will draw it: a CSS or
  8847. * attribute height keeps the intrinsic aspect ratio, and
  8848. * a CSS width overrides the native pixel width. Bootstrap
  8849. * sizes the Cloudron logo with height:40px only. */
  8850. int idx = nd->img_index;
  8851. int iw = 0, ih = 0;
  8852. if (idx >= 0 && idx < image_count &&
  8853. images[idx].state == 1) {
  8854. iw = (int)images[idx].native_w;
  8855. ih = (int)images[idx].native_h;
  8856. if (iw <= 0 || ih <= 0) {
  8857. iw = (int)images[idx].img.w;
  8858. ih = (int)images[idx].img.h;
  8859. }
  8860. }
  8861. if (cs.width_kind) {
  8862. int ww = style_width_px(&cs, base);
  8863. line_w += ww > 0 ? ww : 64;
  8864. } else if (nd->width_attr) {
  8865. line_w += nd->width_attr;
  8866. } else if (nd->height_attr && iw && ih) {
  8867. line_w += iw * (int)nd->height_attr / ih;
  8868. } else if (cs.height_kind && iw && ih) {
  8869. /* A percentage height needs the parent's
  8870. * definite height (the logo's 2rem box), as in
  8871. * add_image_run(); otherwise it is auto. */
  8872. int hh = cs.height_kind == 1 ?
  8873. style_height_px(&cs, base) :
  8874. cs.height_kind == 2 &&
  8875. pst->height_kind == 1 ?
  8876. (int)pst->height * (int)cs.height / 100 :
  8877. 0;
  8878. line_w += hh > 0 ? iw * hh / ih : iw;
  8879. } else if (iw) {
  8880. line_w += iw;
  8881. } else {
  8882. line_w += 64;
  8883. }
  8884. continue;
  8885. }
  8886. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  8887. nd->tag == BR_TAG_TEXTAREA) &&
  8888. !s_eq(br_type(&doc, c), "hidden")) {
  8889. /* Form controls are replaced: CSS width applies even
  8890. * when they are inline (add_form_run's sizes). */
  8891. int fw = cs.width_kind ? style_width_px(&cs, base) :
  8892. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  8893. if (s_eq(br_type(&doc, c), "checkbox") ||
  8894. s_eq(br_type(&doc, c), "radio"))
  8895. fw = 16;
  8896. line_w += (fw > 0 ? fw : 120) +
  8897. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  8898. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  8899. continue;
  8900. }
  8901. if (nd->tag == BR_TAG_SVG) {
  8902. /* A replaced element: its own size, like add_svg_run()
  8903. * (its path children have no width). */
  8904. int sw, sh, sb = cs.width_kind ?
  8905. style_width_px(&cs, base) : base;
  8906. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  8907. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  8908. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  8909. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8910. line_w += sw;
  8911. } else {
  8912. if (line_w > max_w)
  8913. max_w = line_w;
  8914. line_w = 0;
  8915. if (sw > max_w)
  8916. max_w = sw;
  8917. }
  8918. continue;
  8919. }
  8920. {
  8921. int cw = mp_px(&cs, 7, base) +
  8922. mp_px(&cs, 5, base) +
  8923. mp_px(&cs, 3, base) +
  8924. mp_px(&cs, 1, base) +
  8925. cs.border_w[1] + cs.border_w[3];
  8926. /* width/height do not apply to non-replaced inline
  8927. * boxes. The tagesschau home label is an inline span
  8928. * with width:1px for the mobile icon-only header; using
  8929. * that width made the whole subnav collapse to a
  8930. * one-character column. */
  8931. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  8932. cw += cs.width_kind == 1 ? cs.width :
  8933. style_width_px(&cs, base);
  8934. else
  8935. cw += intrinsic_width(ui, c, &cs, depth + 1,
  8936. base);
  8937. if (flex_row || cs.float_left ||
  8938. cs.display == BR_DISPLAY_INLINE ||
  8939. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8940. line_w += cw;
  8941. } else {
  8942. if (line_w > max_w)
  8943. max_w = line_w;
  8944. line_w = 0;
  8945. if (cw > max_w)
  8946. max_w = cw;
  8947. }
  8948. }
  8949. if (line_w > 4096 || max_w > 4096)
  8950. break;
  8951. }
  8952. return line_w > max_w ? line_w : max_w;
  8953. }
  8954. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  8955. * the main user: .row > .col-md-* with float:left and a percentage width.
  8956. * Each column is laid out with its own left/right edge and the row advances
  8957. * to the tallest column. Returns the first child not consumed. */
  8958. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  8959. const struct br_style *pst, int depth,
  8960. unsigned short link)
  8961. {
  8962. unsigned int n = first;
  8963. int row_left = l->left, row_right = l->right;
  8964. int row_top, row_bottom, xl, xr, any = 0;
  8965. int fl_left = row_left, fl_right = row_right, fl_bottom;
  8966. flush_line(l);
  8967. row_top = l->y;
  8968. row_bottom = l->y;
  8969. fl_bottom = row_top;
  8970. xl = row_left;
  8971. xr = row_right;
  8972. while (n) {
  8973. struct br_node *nd = &doc.nodes[n];
  8974. struct br_style cs;
  8975. unsigned short lk = link;
  8976. int colw, right;
  8977. if (nd->type == BR_NODE_TEXT) {
  8978. if (text_node_blank(nd)) {
  8979. n = nd->next;
  8980. continue;
  8981. }
  8982. break;
  8983. }
  8984. br_style_for(&doc, n, pst, &cs);
  8985. if (cs.display == BR_DISPLAY_NONE) {
  8986. n = nd->next;
  8987. continue;
  8988. }
  8989. /* A float blockifies its box: Bootstrap floats inline
  8990. * anchors too (the navbar brand and its text links), and
  8991. * their padding must be honoured. */
  8992. if (!cs.float_left)
  8993. break;
  8994. if (nd->tag == BR_TAG_A && nd->href_off)
  8995. lk = (unsigned short)n;
  8996. right = cs.float_left == 2;
  8997. if (cs.width_kind == 1 || cs.width_kind == 2 ||
  8998. cs.width_kind == 3) {
  8999. /* The column is the margin box: `width` is the
  9000. * content (or, with border-box, the border) box,
  9001. * and layout_block() takes margins, padding and
  9002. * borders back out of the column. A 200px float
  9003. * with margin-right:20px used to get 180px of
  9004. * content. */
  9005. int base = row_right - row_left;
  9006. colw = cs.width_kind == 1 ? (int)cs.width :
  9007. style_width_px(&cs, base);
  9008. colw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  9009. if (!cs.box_sizing)
  9010. colw += mp_px(&cs, 7, base) +
  9011. mp_px(&cs, 5, base) +
  9012. cs.border_w[1] + cs.border_w[3];
  9013. } else {
  9014. int base = row_right - row_left;
  9015. /* Shrink-to-fit outer width: borders too (Google's
  9016. * 1px-bordered "Anmelden" pill wrapped otherwise). */
  9017. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  9018. mp_px(&cs, 7, base) +
  9019. mp_px(&cs, 5, base) +
  9020. mp_px(&cs, 3, base) +
  9021. mp_px(&cs, 1, base) +
  9022. cs.border_w[1] + cs.border_w[3];
  9023. if (colw < 8)
  9024. colw = 8;
  9025. }
  9026. if (colw < 8)
  9027. colw = 8;
  9028. if (colw > row_right - row_left)
  9029. colw = row_right - row_left;
  9030. /* The float column width is already resolved. */
  9031. cs.width_kind = 0;
  9032. cs.max_width_kind = 0;
  9033. if (right) {
  9034. if (any && xr - colw < xl) {
  9035. row_top = row_bottom;
  9036. row_bottom = row_top;
  9037. xl = row_left;
  9038. xr = row_right;
  9039. }
  9040. if (xr - colw < xl)
  9041. colw = xr - xl;
  9042. if (colw < 8)
  9043. colw = 8;
  9044. l->left = xr - colw;
  9045. if (l->left < row_left)
  9046. l->left = row_left;
  9047. l->right = xr;
  9048. xr = l->left;
  9049. if (xr < fl_right)
  9050. fl_right = xr;
  9051. } else {
  9052. if (any && xl + colw > xr) {
  9053. row_top = row_bottom;
  9054. row_bottom = row_top;
  9055. xl = row_left;
  9056. xr = row_right;
  9057. }
  9058. l->left = xl;
  9059. l->right = xl + colw;
  9060. xl += colw;
  9061. if (xl > fl_left)
  9062. fl_left = xl;
  9063. }
  9064. if (l->right < l->left + 8)
  9065. l->right = l->left + 8;
  9066. l->y = row_top;
  9067. l->line_left = l->line_x = l->left;
  9068. l->run_x = l->left;
  9069. l->line_y = l->y;
  9070. l->line_h = 0;
  9071. l->nruns = 0;
  9072. l->space_pending = 0;
  9073. l->align = cs.align;
  9074. layout_block(l, n, &cs, depth + 1, lk);
  9075. if (l->y > row_bottom)
  9076. row_bottom = l->y;
  9077. if (l->y > fl_bottom)
  9078. fl_bottom = l->y;
  9079. any = 1;
  9080. n = nd->next;
  9081. }
  9082. l->left = row_left;
  9083. l->right = row_right;
  9084. if (n && any) {
  9085. struct br_node *nd = &doc.nodes[n];
  9086. int inline_next = 0;
  9087. if (nd->type == BR_NODE_TEXT) {
  9088. inline_next = 1;
  9089. } else if (nd->type == BR_NODE_ELEM) {
  9090. struct br_style cs;
  9091. br_style_for(&doc, n, pst, &cs);
  9092. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  9093. cs.display != BR_DISPLAY_NONE &&
  9094. !br_tag_is_block(nd->tag);
  9095. }
  9096. if (inline_next) {
  9097. if (l->float_active) {
  9098. if (l->float_left > fl_left)
  9099. fl_left = l->float_left;
  9100. if (l->float_right < fl_right)
  9101. fl_right = l->float_right;
  9102. if (l->float_bottom > fl_bottom)
  9103. fl_bottom = l->float_bottom;
  9104. }
  9105. l->float_active = 1;
  9106. l->float_left = fl_left;
  9107. l->float_right = fl_right;
  9108. l->float_bottom = fl_bottom;
  9109. l->y = row_top;
  9110. } else {
  9111. l->float_active = 0;
  9112. l->y = row_bottom;
  9113. }
  9114. } else {
  9115. l->float_active = 0;
  9116. l->y = row_bottom;
  9117. }
  9118. l->line_x = l->left;
  9119. l->run_x = l->left;
  9120. l->line_left = l->left;
  9121. l->line_right = l->right;
  9122. l->line_y = l->y;
  9123. l->line_h = 0;
  9124. l->nruns = 0;
  9125. l->space_pending = 0;
  9126. return n;
  9127. }
  9128. static int flex_item_width(struct lay *l, unsigned int n,
  9129. const struct br_style *cs, int avail)
  9130. {
  9131. struct br_node *nd = &doc.nodes[n];
  9132. (void)l;
  9133. int w;
  9134. if (cs->width_kind == 2 || cs->width_kind == 3)
  9135. w = style_width_px(cs, avail);
  9136. else if (cs->width_kind == 1)
  9137. w = (int)cs->width;
  9138. else if (nd->tag == BR_TAG_IMG) {
  9139. int idx = nd->img_index;
  9140. if (idx >= 0 && idx < image_count &&
  9141. images[idx].state == 1)
  9142. w = (int)images[idx].img.w;
  9143. else if (nd->width_attr)
  9144. w = (int)nd->width_attr;
  9145. else
  9146. w = 64;
  9147. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  9148. nd->tag == BR_TAG_TEXTAREA) {
  9149. /* A control has no content to measure: its default size
  9150. * (a search field in a filter bar). */
  9151. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  9152. } else {
  9153. w = intrinsic_width(l->ui, n, cs, 0, avail);
  9154. }
  9155. /* Explicit widths are content-box sizes; the flex item's outer width
  9156. * must include padding, borders and margins. */
  9157. w += mp_px(cs, 7, avail);
  9158. w += mp_px(cs, 5, avail);
  9159. w += mp_px(cs, 3, avail);
  9160. w += mp_px(cs, 1, avail);
  9161. w += cs->border_w[1] + cs->border_w[3];
  9162. if (w < 24)
  9163. w = 24;
  9164. if (w > avail)
  9165. w = avail;
  9166. return w;
  9167. }
  9168. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  9169. int depth);
  9170. /* An inline child of a text-only inline-block: the same test minus the
  9171. * display check (an inline <span> may have padding/background in CSS, but
  9172. * the inline path paints those for spans anyway). */
  9173. static int inline_block_flows_inline(unsigned int node,
  9174. const struct br_style *cs, int depth)
  9175. {
  9176. unsigned int c;
  9177. if (depth > 3 || cs->pos)
  9178. return 0;
  9179. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9180. const struct br_node *nd = &doc.nodes[c];
  9181. struct br_style ch;
  9182. if (nd->type != BR_NODE_ELEM)
  9183. continue;
  9184. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  9185. br_tag_is_block(nd->tag))
  9186. return 0;
  9187. br_style_for(&doc, c, cs, &ch);
  9188. if (ch.display == BR_DISPLAY_NONE)
  9189. continue;
  9190. if (ch.display != BR_DISPLAY_INLINE ||
  9191. !inline_block_flows_inline(c, &ch, depth + 1))
  9192. return 0;
  9193. }
  9194. return 1;
  9195. }
  9196. /* An inline-block that is only text in a line (a <time> in a byline, a
  9197. * label) with no box of its own -- no size, background, border or padding
  9198. * -- lays out exactly like an inline element, so it stays in the text line
  9199. * instead of ending it. Boxes with any of those keep the row path. */
  9200. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  9201. int depth)
  9202. {
  9203. unsigned int c;
  9204. int i;
  9205. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  9206. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  9207. cs->pos || depth > 3)
  9208. return 0;
  9209. for (i = 0; i < 4; i++)
  9210. if (cs->border_w[i])
  9211. return 0;
  9212. for (i = 4; i < 8; i++)
  9213. if (mp_px(cs, i, 0) > 0)
  9214. return 0;
  9215. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9216. const struct br_node *nd = &doc.nodes[c];
  9217. struct br_style ch;
  9218. if (nd->type != BR_NODE_ELEM)
  9219. continue;
  9220. if (nd->tag == BR_TAG_SVG) {
  9221. /* An icon box (Docusaurus' admonition heading:
  9222. * `<span inline-block><svg/></span>Note`): the SVG
  9223. * is an inline replaced run, so the box can stay in
  9224. * the text line. */
  9225. br_style_for(&doc, c, cs, &ch);
  9226. if (ch.display == BR_DISPLAY_NONE ||
  9227. ch.display == BR_DISPLAY_INLINE ||
  9228. ch.display == BR_DISPLAY_INLINE_BLOCK)
  9229. continue;
  9230. return 0;
  9231. }
  9232. if (nd->tag == BR_TAG_IMG || br_tag_is_block(nd->tag))
  9233. return 0;
  9234. br_style_for(&doc, c, cs, &ch);
  9235. if (ch.display == BR_DISPLAY_NONE)
  9236. continue;
  9237. if (ch.display != BR_DISPLAY_INLINE ||
  9238. !inline_block_flows_inline(c, &ch, depth + 1))
  9239. return 0;
  9240. }
  9241. return 1;
  9242. }
  9243. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  9244. * on one line, not one full-width block each. Place intrinsic widths from
  9245. * left to right and wrap when the row is full. */
  9246. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  9247. const struct br_style *pst, int depth,
  9248. unsigned short link)
  9249. {
  9250. unsigned int n = first;
  9251. int row_left = l->left, row_right = l->right;
  9252. int avail = row_right - row_left;
  9253. int x = row_left, y = l->y, row_h = 0, any = 0;
  9254. /* Each box sets l->align from its own style; the text after the row
  9255. * must keep the container's (a centred .fa-fw icon centred the menu
  9256. * label that followed it). */
  9257. unsigned char row_align = l->align;
  9258. flush_line(l);
  9259. y = l->y;
  9260. while (n) {
  9261. struct br_node *nd = &doc.nodes[n];
  9262. struct br_style cs;
  9263. unsigned short lk = link;
  9264. int colw, h;
  9265. if (nd->type == BR_NODE_TEXT) {
  9266. if (!text_node_blank(nd))
  9267. break;
  9268. if (any)
  9269. x += 4;
  9270. n = nd->next;
  9271. continue;
  9272. }
  9273. br_style_for(&doc, n, pst, &cs);
  9274. if (cs.display == BR_DISPLAY_NONE) {
  9275. n = nd->next;
  9276. continue;
  9277. }
  9278. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  9279. break;
  9280. if (nd->tag == BR_TAG_A && nd->href_off)
  9281. lk = (unsigned short)n;
  9282. colw = flex_item_width(l, n, &cs, avail);
  9283. /* A few pixels of slack keep a single long token (boot.S)
  9284. * from wrapping at the exact content width. */
  9285. colw += 8;
  9286. if (colw > avail)
  9287. colw = avail;
  9288. cs.width_kind = 0;
  9289. cs.max_width_kind = 0;
  9290. if (any && x + colw > row_right) {
  9291. y += row_h + 2;
  9292. x = row_left;
  9293. row_h = 0;
  9294. any = 0;
  9295. }
  9296. if (any && x > row_left)
  9297. x += 4;
  9298. l->left = x;
  9299. l->right = x + colw;
  9300. if (l->right < l->left + 8)
  9301. l->right = l->left + 8;
  9302. l->y = y;
  9303. l->line_left = l->line_x = l->left;
  9304. l->run_x = l->left;
  9305. l->line_y = l->y;
  9306. l->line_h = 0;
  9307. l->nruns = 0;
  9308. l->space_pending = 0;
  9309. l->align = cs.align;
  9310. layout_block(l, n, &cs, depth + 1, lk);
  9311. h = l->y - y;
  9312. if (h > row_h)
  9313. row_h = h;
  9314. x += colw;
  9315. any = 1;
  9316. n = nd->next;
  9317. }
  9318. if (any)
  9319. y += row_h;
  9320. l->left = row_left;
  9321. l->right = row_right;
  9322. l->align = row_align;
  9323. l->y = y;
  9324. l->line_left = l->line_x = l->left;
  9325. l->run_x = l->left;
  9326. l->line_y = l->y;
  9327. l->line_h = 0;
  9328. l->nruns = 0;
  9329. l->space_pending = 0;
  9330. return n;
  9331. }
  9332. struct flex_item {
  9333. unsigned int node;
  9334. unsigned short link;
  9335. int w;
  9336. };
  9337. /* An item's min-width/max-width as outer (margin-box) widths in the flex
  9338. * row, or -1 when unset. Percentages and calc() resolve against the
  9339. * container width. */
  9340. static int flex_limit_w(const struct br_style *cs, int which_max, int avail)
  9341. {
  9342. unsigned char kind = which_max ? cs->max_width_kind :
  9343. cs->min_width_kind;
  9344. int w;
  9345. if (kind == 3)
  9346. w = which_max ?
  9347. avail * cs->max_width_calc_pct / 100 +
  9348. cs->max_width_calc_px :
  9349. avail * cs->min_width_calc_pct / 100 +
  9350. cs->min_width_calc_px;
  9351. else
  9352. w = css_size(kind, which_max ? cs->max_width : cs->min_width,
  9353. avail);
  9354. if (w < 0)
  9355. return -1;
  9356. if (!cs->box_sizing)
  9357. w += mp_px(cs, 7, avail) + mp_px(cs, 5, avail) +
  9358. cs->border_w[1] + cs->border_w[3];
  9359. return w + mp_px(cs, 3, avail) + mp_px(cs, 1, avail);
  9360. }
  9361. static int flex_clamp_w(const struct br_style *cs, int w, int avail)
  9362. {
  9363. int mx = flex_limit_w(cs, 1, avail), mn = flex_limit_w(cs, 0, avail);
  9364. if (mx >= 0 && w > mx)
  9365. w = mx;
  9366. if (mn >= 0 && w < mn)
  9367. w = mn;
  9368. return w;
  9369. }
  9370. /* Does a flex row stretch this item to the line height? Only items with
  9371. * no height of their own and align-self/align-items stretch; replaced
  9372. * content (images, icons) keeps its aspect ratio. */
  9373. static int flex_item_stretches(unsigned int node, const struct br_style *cs,
  9374. const struct br_style *pst)
  9375. {
  9376. int ai = cs->align_self ? cs->align_self - 1 : pst->align_items;
  9377. unsigned char tag = doc.nodes[node].tag;
  9378. return ai == 0 && !cs->height_kind && !cs->max_height_kind &&
  9379. tag != BR_TAG_IMG && tag != BR_TAG_SVG && tag != BR_TAG_INPUT &&
  9380. tag != BR_TAG_SELECT && tag != BR_TAG_TEXTAREA &&
  9381. tag != BR_TAG_BUTTON;
  9382. }
  9383. static void flex_set_stretch(unsigned int node, const struct br_style *cs,
  9384. int line_h, int cbw)
  9385. {
  9386. int h = line_h - mp_px(cs, 0, cbw) - mp_px(cs, 2, cbw);
  9387. if (node >= BR_MAX_NODES || h <= 0)
  9388. return;
  9389. if (h > 65535)
  9390. h = 65535;
  9391. flex_stretch_h[node] = (unsigned short)h;
  9392. if (block_h[node] < h)
  9393. block_h[node] = (unsigned short)h;
  9394. }
  9395. static void layout_flex_children(struct lay *l, unsigned int parent,
  9396. const struct br_style *pst, int depth,
  9397. unsigned short link)
  9398. {
  9399. struct flex_item it[32];
  9400. unsigned int c;
  9401. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  9402. int grow_need = 0; /* growing items at their content width */
  9403. int row_left = l->left, row_right = l->right;
  9404. int avail = row_right - row_left;
  9405. int idx, row_top;
  9406. unsigned char row_align = l->align;
  9407. int box_left = l->left, box_right = l->right, row_top0 = l->y;
  9408. int bw = 0, aw = 0, first_h = -1;
  9409. int cont_h = l->cb_h; /* the container's definite content height */
  9410. struct br_style bps, aps;
  9411. if (avail < 8 || depth > 48) {
  9412. layout_children(l, parent, pst, depth, link);
  9413. return;
  9414. }
  9415. /* If direct text is not just whitespace, normal block flow handles it
  9416. * better than pretending it is a flex item. */
  9417. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9418. struct br_node *nd = &doc.nodes[c];
  9419. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9420. layout_children(l, parent, pst, depth, link);
  9421. return;
  9422. }
  9423. }
  9424. /* ::before/::after icon boxes are the row's first and last items
  9425. * (Docusaurus' sidebar chevron): reserve their columns. */
  9426. if (doc.npe_rules) {
  9427. bw = pseudo_box_w(parent, pst, 1, &bps, avail);
  9428. aw = pseudo_box_w(parent, pst, 2, &aps, avail);
  9429. if (bw + aw > avail - 8) {
  9430. bw = 0;
  9431. aw = 0;
  9432. }
  9433. row_left += bw;
  9434. row_right -= aw;
  9435. avail = row_right - row_left;
  9436. }
  9437. for (c = doc.nodes[parent].first;
  9438. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  9439. c = doc.nodes[c].next) {
  9440. struct br_node *nd = &doc.nodes[c];
  9441. struct br_style cs;
  9442. if (nd->type == BR_NODE_TEXT)
  9443. continue;
  9444. br_style_for(&doc, c, pst, &cs);
  9445. if (cs.display == BR_DISPLAY_NONE)
  9446. continue;
  9447. if ((cs.pos == 1 || cs.pos == 2) &&
  9448. layout_out_of_flow(l, c, &cs, depth,
  9449. (nd->tag == BR_TAG_A && nd->href_off) ?
  9450. (unsigned short)c : link))
  9451. continue; /* absolutely positioned: not an item */
  9452. it[nitem].node = c;
  9453. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  9454. (unsigned short)c : link;
  9455. it[nitem].w = 0;
  9456. if (cs.flex_grow && !cs.width_kind) {
  9457. grow_count++;
  9458. grow_need += flex_item_width(l, c, &cs, avail);
  9459. } else
  9460. fixed += flex_clamp_w(&cs,
  9461. flex_item_width(l, c, &cs, avail),
  9462. avail);
  9463. nitem++;
  9464. }
  9465. /* A narrow container (an icon row sized to its content, Google's
  9466. * mic + lens buttons) is still a row when its items fit; only a
  9467. * narrow one that would overflow or squeeze growing items falls
  9468. * back to block flow. */
  9469. if (avail < 160 && fixed + grow_need > avail) {
  9470. layout_children(l, parent, pst, depth, link);
  9471. return;
  9472. }
  9473. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  9474. /* A growing item capped by max-width (Docusaurus' doc column,
  9475. * `max-width: 75%`; its main container, `calc(100% - 300px)`)
  9476. * keeps its cap and leaves the rest of the free space to the other
  9477. * growing items. */
  9478. if (grow_count) {
  9479. int pass, capped[32] = { 0 };
  9480. for (pass = 0; pass < nitem; pass++) {
  9481. int changed = 0;
  9482. for (idx = 0; idx < nitem; idx++) {
  9483. struct br_style cs;
  9484. int lim;
  9485. if (capped[idx])
  9486. continue;
  9487. br_style_for(&doc, it[idx].node, pst, &cs);
  9488. if (!cs.flex_grow || cs.width_kind)
  9489. continue;
  9490. lim = flex_clamp_w(&cs, grow_w, avail);
  9491. if (lim == grow_w)
  9492. continue;
  9493. capped[idx] = lim + 1;
  9494. fixed += lim;
  9495. grow_count--;
  9496. changed = 1;
  9497. }
  9498. if (!changed || !grow_count)
  9499. break;
  9500. grow_w = (avail - fixed) / grow_count;
  9501. }
  9502. for (idx = 0; idx < nitem; idx++)
  9503. it[idx].w = capped[idx] ? capped[idx] - 1 : 0;
  9504. }
  9505. if (grow_w < 96 && avail >= 160)
  9506. grow_w = 96;
  9507. for (idx = 0; idx < nitem; idx++) {
  9508. struct br_style cs;
  9509. if (it[idx].w)
  9510. continue; /* capped growing item */
  9511. br_style_for(&doc, it[idx].node, pst, &cs);
  9512. if (cs.flex_grow && !cs.width_kind)
  9513. it[idx].w = grow_w;
  9514. else
  9515. it[idx].w = flex_clamp_w(&cs,
  9516. flex_item_width(l,
  9517. it[idx].node,
  9518. &cs, avail),
  9519. avail);
  9520. if (it[idx].w > avail)
  9521. it[idx].w = avail;
  9522. if (it[idx].w < 8)
  9523. it[idx].w = 8;
  9524. }
  9525. row_top = l->y;
  9526. idx = 0;
  9527. while (idx < nitem) {
  9528. int start = idx, count = 0, row_w = 0;
  9529. int free_w, x, extra = 0, row_h = 0, k;
  9530. while (idx < nitem) {
  9531. int add = it[idx].w + (count ? gap : 0);
  9532. /* CSS default is nowrap; only flex-wrap: wrap (1)
  9533. * starts a new row. */
  9534. if (count && pst->flex_wrap == 1 &&
  9535. row_w + add > avail)
  9536. break;
  9537. row_w += add;
  9538. count++;
  9539. idx++;
  9540. }
  9541. if (!count) {
  9542. count = 1;
  9543. row_w = it[start].w;
  9544. idx = start + 1;
  9545. }
  9546. free_w = avail - row_w;
  9547. if (free_w < 0)
  9548. free_w = 0;
  9549. x = row_left;
  9550. if (pst->justify == 1) {
  9551. x += free_w / 2;
  9552. } else if (pst->justify == 2) {
  9553. x += free_w;
  9554. } else if (pst->justify == 3) {
  9555. extra = count > 1 ? free_w / (count - 1) : 0;
  9556. } else if (pst->justify == 4) {
  9557. extra = count ? free_w / count : 0;
  9558. x += extra / 2;
  9559. } else if (pst->justify == 5) {
  9560. extra = count ? free_w / (count + 1) : 0;
  9561. x += extra;
  9562. }
  9563. for (k = 0; k < count; k++) {
  9564. int node = (int)it[start + k].node;
  9565. int h = block_h[node];
  9566. if (h > row_h)
  9567. row_h = h;
  9568. }
  9569. /* A single line fills a definite container height (an app
  9570. * shell's `height: 100%` sidebar + content row). */
  9571. if (pst->flex_wrap != 1 && cont_h > row_h)
  9572. row_h = cont_h;
  9573. else if (pst->height_kind == 1 && (int)pst->height > row_h)
  9574. row_h = pst->height;
  9575. for (k = 0; k < count; k++) {
  9576. struct br_style cs;
  9577. int node = (int)it[start + k].node;
  9578. int yoff = 0;
  9579. br_style_for(&doc, node, pst, &cs);
  9580. cs.width_kind = 0;
  9581. cs.max_width_kind = 0;
  9582. /* align-items: stretch. With a definite line height
  9583. * the item is laid out at it, so its own children see
  9584. * a definite height; otherwise the measure pass
  9585. * stretches it once the line is known (below). */
  9586. if (!l->draw && row_h > 0 && flex_item_stretches(node,
  9587. &cs, pst))
  9588. flex_set_stretch(node, &cs, row_h, avail);
  9589. {
  9590. int ai = cs.align_self ? cs.align_self - 1 :
  9591. pst->align_items;
  9592. if (l->draw && ai && row_h > block_h[node]) {
  9593. if (ai == 1)
  9594. yoff = (row_h -
  9595. block_h[node]) / 2;
  9596. else if (ai == 2)
  9597. yoff = row_h - block_h[node];
  9598. }
  9599. }
  9600. l->left = x;
  9601. l->right = x + it[start + k].w;
  9602. if (l->right < l->left + 8)
  9603. l->right = l->left + 8;
  9604. l->y = row_top + yoff;
  9605. /* line_left too: a stale one from the previous item
  9606. * made flush_line() see a non-empty line and push
  9607. * every later item down by an empty line's height. */
  9608. l->line_left = l->line_x = l->run_x = l->left;
  9609. l->line_right = l->right;
  9610. l->line_y = l->y;
  9611. l->line_h = 0;
  9612. l->nruns = 0;
  9613. l->space_pending = 0;
  9614. l->align = cs.align;
  9615. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  9616. {
  9617. /* Both passes: a form control item has no
  9618. * block_h of its own, so the draw pass would
  9619. * otherwise end a row of only an <input> at
  9620. * height 0 and pull the content below up. */
  9621. int h = l->y - row_top;
  9622. if (h > row_h)
  9623. row_h = h;
  9624. }
  9625. x += it[start + k].w;
  9626. if (k + 1 < count)
  9627. x += gap + extra;
  9628. }
  9629. if (!l->draw) {
  9630. for (k = 0; k < count; k++) {
  9631. struct br_style cs;
  9632. int node = (int)it[start + k].node;
  9633. br_style_for(&doc, node, pst, &cs);
  9634. if (!flex_item_stretches(node, &cs, pst))
  9635. continue;
  9636. /* To the line's bottom edge from where the
  9637. * item really starts (its top margin, or a
  9638. * line box above it). */
  9639. if (layout_boxes[node].valid)
  9640. flex_set_stretch(node, &cs,
  9641. row_top + row_h -
  9642. layout_boxes[node].y +
  9643. mp_px(&cs, 0, avail), avail);
  9644. else
  9645. flex_set_stretch(node, &cs, row_h, avail);
  9646. }
  9647. }
  9648. if (first_h < 0)
  9649. first_h = row_h;
  9650. row_top += row_h;
  9651. }
  9652. if (bw || aw) {
  9653. int pass;
  9654. for (pass = 0; pass < 2; pass++) {
  9655. const struct br_style *ps = pass ? &aps : &bps;
  9656. int a = pass ? row_right : box_left;
  9657. int b = pass ? box_right : row_left;
  9658. int h = ps->height_kind ?
  9659. style_height_px(ps, box_right - box_left) : 0;
  9660. if (!(pass ? aw : bw))
  9661. continue;
  9662. l->left = l->line_left = l->line_x = l->run_x = a;
  9663. l->right = l->line_right = b;
  9664. l->y = row_top0;
  9665. if (pst->align_items == 1 && first_h > h)
  9666. l->y += (first_h - h) / 2;
  9667. l->line_y = l->y;
  9668. l->line_h = 0;
  9669. l->nruns = 0;
  9670. l->space_pending = 0;
  9671. emit_pseudo_box(l, pst, ps, link);
  9672. flush_line(l);
  9673. /* The box sits inside the first row; it only makes
  9674. * the row taller when it is taller itself. */
  9675. if (row_top0 + h > row_top)
  9676. row_top = row_top0 + h;
  9677. }
  9678. }
  9679. l->left = box_left;
  9680. l->right = box_right;
  9681. l->align = row_align;
  9682. l->y = row_top;
  9683. l->line_left = l->line_x = l->run_x = l->left;
  9684. l->line_right = l->right;
  9685. l->line_y = l->y;
  9686. l->line_h = 0;
  9687. l->nruns = 0;
  9688. l->space_pending = 0;
  9689. }
  9690. /* flex-direction: column. Items stack in order with the gap and never
  9691. * collapse margins. In the draw pass justify-content shares out the free
  9692. * height of the container's measured box (a definite or min-height, or a
  9693. * row stretch), and align-items places each item: stretch (the default)
  9694. * fills the line, start/center/end shrink an item to its content width
  9695. * (a login form's "Log in" button, a centred logo and name). */
  9696. static void layout_flex_column(struct lay *l, unsigned int parent,
  9697. const struct br_style *pst, int depth,
  9698. unsigned short link)
  9699. {
  9700. unsigned int c;
  9701. int box_left = l->left, box_right = l->right;
  9702. int avail = box_right - box_left;
  9703. int gap = pst->grid_gap, y0 = l->y;
  9704. int n = 0, k = 0, total = 0, lead = 0, extra = 0;
  9705. unsigned char row_align = l->align;
  9706. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9707. struct br_node *nd = &doc.nodes[c];
  9708. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd))
  9709. break;
  9710. }
  9711. if (c || avail < 8 || depth > 48) {
  9712. /* Loose text: block flow, with centred lines standing in
  9713. * for align-items: center. */
  9714. struct br_style cst = *pst;
  9715. if (pst->align_items == 1) {
  9716. cst.align = BR_ALIGN_CENTER;
  9717. l->align = BR_ALIGN_CENTER;
  9718. }
  9719. layout_children(l, parent, &cst, depth, link);
  9720. return;
  9721. }
  9722. emit_pseudo(l, parent, pst, 1, link);
  9723. flush_line(l);
  9724. y0 = l->y;
  9725. if (l->draw && parent < BR_MAX_NODES && block_h[parent]) {
  9726. int inner = (int)block_h[parent] - pst->border_w[0] -
  9727. pst->border_w[2] - mp_px(pst, 4, avail) -
  9728. mp_px(pst, 6, avail) - (y0 - l->parent_top -
  9729. pst->border_w[0] - mp_px(pst, 4, avail));
  9730. int free_h;
  9731. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9732. struct br_style cs;
  9733. if (doc.nodes[c].type != BR_NODE_ELEM)
  9734. continue;
  9735. br_style_for(&doc, c, pst, &cs);
  9736. if (cs.display == BR_DISPLAY_NONE || cs.pos == 1 ||
  9737. cs.pos == 2)
  9738. continue;
  9739. total += block_h[c] + mp_px(&cs, 0, avail) +
  9740. mp_px(&cs, 2, avail);
  9741. n++;
  9742. }
  9743. if (n > 1)
  9744. total += gap * (n - 1);
  9745. free_h = inner - total;
  9746. if (n && free_h > 0) {
  9747. if (pst->justify == 1) {
  9748. lead = free_h / 2;
  9749. } else if (pst->justify == 2) {
  9750. lead = free_h;
  9751. } else if (pst->justify == 3) {
  9752. extra = n > 1 ? free_h / (n - 1) : 0;
  9753. } else if (pst->justify == 4) {
  9754. extra = free_h / n;
  9755. lead = extra / 2;
  9756. } else if (pst->justify == 5) {
  9757. extra = free_h / (n + 1);
  9758. lead = extra;
  9759. }
  9760. }
  9761. }
  9762. l->y = y0 + lead;
  9763. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9764. struct br_node *nd = &doc.nodes[c];
  9765. unsigned short lk = (nd->tag == BR_TAG_A && nd->href_off) ?
  9766. (unsigned short)c : link;
  9767. struct br_style cs;
  9768. int ai, left = box_left, right = box_right;
  9769. if (nd->type != BR_NODE_ELEM)
  9770. continue;
  9771. br_style_for(&doc, c, pst, &cs);
  9772. if (cs.display == BR_DISPLAY_NONE)
  9773. continue;
  9774. if ((cs.pos == 1 || cs.pos == 2) &&
  9775. layout_out_of_flow(l, c, &cs, depth, lk))
  9776. continue;
  9777. if (k++)
  9778. l->y += gap + extra;
  9779. ai = cs.align_self ? cs.align_self - 1 : pst->align_items;
  9780. if (ai) {
  9781. int w = flex_clamp_w(&cs, flex_item_width(l, c, &cs,
  9782. avail),
  9783. avail);
  9784. if (ai == 1)
  9785. left += (avail - w) / 2;
  9786. else if (ai == 2)
  9787. left += avail - w;
  9788. right = left + w;
  9789. cs.width_kind = 0;
  9790. cs.max_width_kind = 0;
  9791. }
  9792. l->left = l->line_left = l->line_x = l->run_x = left;
  9793. l->right = l->line_right = right;
  9794. l->line_y = l->y;
  9795. l->line_h = 0;
  9796. l->nruns = 0;
  9797. l->space_pending = 0;
  9798. l->align = cs.align;
  9799. layout_block(l, c, &cs, depth + 1, lk);
  9800. }
  9801. l->left = l->line_left = l->line_x = l->run_x = box_left;
  9802. l->right = l->line_right = box_right;
  9803. l->align = row_align;
  9804. l->line_y = l->y;
  9805. l->line_h = 0;
  9806. l->nruns = 0;
  9807. l->space_pending = 0;
  9808. emit_pseudo(l, parent, pst, 2, link);
  9809. }
  9810. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  9811. * plus the grid-area hints used by site shells (site notice/footer full
  9812. * width, column-start left, page-content right). Anything more elaborate
  9813. * falls back to normal block flow. */
  9814. static int grid_track_width(unsigned char kind, unsigned short val,
  9815. int avail, int other)
  9816. {
  9817. if (kind == 2)
  9818. return avail * (int)val / 100;
  9819. if (kind == 1)
  9820. return val;
  9821. return other;
  9822. }
  9823. static void layout_grid_children(struct lay *l, unsigned int parent,
  9824. const struct br_style *pst, int depth,
  9825. unsigned short link)
  9826. {
  9827. unsigned int n;
  9828. int row_left = l->left, row_right = l->right;
  9829. int avail = row_right - row_left;
  9830. int gap = pst->grid_gap;
  9831. int track_total = avail - gap;
  9832. int col0, col1, x0, x1;
  9833. int row_y, row_bottom, have_left = 0, have_right = 0;
  9834. unsigned int c;
  9835. if (avail < 32 || depth > 48)
  9836. return;
  9837. if (track_total < 16)
  9838. track_total = 16;
  9839. col0 = grid_track_width((unsigned char)(pst->width_kind),
  9840. pst->width, track_total, 0);
  9841. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  9842. pst->max_width, track_total, 0);
  9843. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  9844. int w0 = pst->width ? pst->width : 1;
  9845. int w1 = pst->max_width ? pst->max_width : 1;
  9846. col0 = track_total * w0 / (w0 + w1);
  9847. col1 = track_total - col0;
  9848. } else if (pst->width_kind == 3) {
  9849. col0 = track_total - col1;
  9850. if (col0 < 24)
  9851. col0 = 24;
  9852. } else if (pst->max_width_kind == 3) {
  9853. col1 = track_total - col0;
  9854. if (col1 < 24)
  9855. col1 = 24;
  9856. }
  9857. if (col0 < 24)
  9858. col0 = 24;
  9859. if (col1 < 24)
  9860. col1 = 24;
  9861. if (col0 + col1 > track_total) {
  9862. col1 = track_total - col0;
  9863. if (col1 < 24)
  9864. col1 = 24;
  9865. }
  9866. x0 = row_left;
  9867. x1 = row_left + col0 + gap;
  9868. /* Direct text makes a grid ambiguous; use block flow instead. */
  9869. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9870. struct br_node *nd = &doc.nodes[c];
  9871. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9872. layout_children(l, parent, pst, depth, link);
  9873. return;
  9874. }
  9875. }
  9876. row_y = row_bottom = l->y;
  9877. n = doc.nodes[parent].first;
  9878. while (n) {
  9879. struct br_node *nd = &doc.nodes[n];
  9880. struct br_style cs;
  9881. unsigned short lk = link;
  9882. int slot, x, w;
  9883. if (nd->type == BR_NODE_TEXT) {
  9884. n = nd->next;
  9885. continue;
  9886. }
  9887. br_style_for(&doc, n, pst, &cs);
  9888. if (cs.display == BR_DISPLAY_NONE) {
  9889. n = nd->next;
  9890. continue;
  9891. }
  9892. if (nd->tag == BR_TAG_A && nd->href_off)
  9893. lk = (unsigned short)n;
  9894. slot = cs.grid_slot;
  9895. if (!slot) {
  9896. if (!have_left)
  9897. slot = 2;
  9898. else if (!have_right)
  9899. slot = 3;
  9900. else
  9901. slot = 2;
  9902. }
  9903. if (slot == 1) {
  9904. if (have_left || have_right) {
  9905. row_y = row_bottom;
  9906. have_left = have_right = 0;
  9907. }
  9908. x = row_left;
  9909. w = avail;
  9910. } else if (slot == 2) {
  9911. if (have_left) {
  9912. row_y = row_bottom;
  9913. have_left = have_right = 0;
  9914. }
  9915. x = x0;
  9916. w = col0;
  9917. have_left = 1;
  9918. } else {
  9919. if (have_right) {
  9920. row_y = row_bottom;
  9921. have_left = have_right = 0;
  9922. }
  9923. x = x1;
  9924. w = col1;
  9925. have_right = 1;
  9926. }
  9927. cs.width_kind = 0;
  9928. cs.max_width_kind = 0;
  9929. l->left = x;
  9930. l->right = x + w;
  9931. if (l->right < l->left + 8)
  9932. l->right = l->left + 8;
  9933. l->y = row_y;
  9934. l->line_left = l->line_x = l->left;
  9935. l->run_x = l->left;
  9936. l->line_y = l->y;
  9937. l->line_h = 0;
  9938. l->nruns = 0;
  9939. l->space_pending = 0;
  9940. l->align = cs.align;
  9941. layout_block(l, n, &cs, depth + 1, lk);
  9942. if (l->y > row_bottom)
  9943. row_bottom = l->y;
  9944. n = nd->next;
  9945. }
  9946. l->left = row_left;
  9947. l->right = row_right;
  9948. l->y = row_bottom;
  9949. l->line_left = l->line_x = l->left;
  9950. l->run_x = l->left;
  9951. l->line_y = l->y;
  9952. l->line_h = 0;
  9953. l->nruns = 0;
  9954. l->space_pending = 0;
  9955. }
  9956. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  9957. * capped at four. Used by the project docs' card grids. A fixed
  9958. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  9959. static void layout_grid_auto(struct lay *l, unsigned int parent,
  9960. const struct br_style *pst, int depth,
  9961. unsigned short link)
  9962. {
  9963. unsigned int n, c;
  9964. int row_left = l->left, row_right = l->right;
  9965. int avail = row_right - row_left;
  9966. int gap = pst->grid_gap;
  9967. int minw = pst->width_kind == 1 ? pst->width : 200;
  9968. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  9969. if (avail < 32 || depth > 48) {
  9970. layout_children(l, parent, pst, depth, link);
  9971. return;
  9972. }
  9973. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9974. struct br_node *nd = &doc.nodes[c];
  9975. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9976. layout_children(l, parent, pst, depth, link);
  9977. return;
  9978. }
  9979. }
  9980. if (minw < 80)
  9981. minw = 80;
  9982. ncols = (avail + gap) / (minw + gap);
  9983. if (ncols < 1)
  9984. ncols = 1;
  9985. if (ncols > 4)
  9986. ncols = 4;
  9987. if (pst->grid_auto > BR_GRID_FIXED) {
  9988. /* grid-template-columns: repeat(N, 1fr) */
  9989. ncols = pst->grid_auto - BR_GRID_FIXED;
  9990. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  9991. ncols--;
  9992. }
  9993. colw = (avail - gap * (ncols - 1)) / ncols;
  9994. if (colw < 24)
  9995. colw = 24;
  9996. x = row_left;
  9997. n = doc.nodes[parent].first;
  9998. while (n) {
  9999. struct br_node *nd = &doc.nodes[n];
  10000. struct br_style cs;
  10001. unsigned short lk = link;
  10002. int h;
  10003. if (nd->type == BR_NODE_TEXT) {
  10004. n = nd->next;
  10005. continue;
  10006. }
  10007. br_style_for(&doc, n, pst, &cs);
  10008. if (cs.display == BR_DISPLAY_NONE) {
  10009. n = nd->next;
  10010. continue;
  10011. }
  10012. if (nd->tag == BR_TAG_A && nd->href_off)
  10013. lk = (unsigned short)n;
  10014. cs.width_kind = 0;
  10015. cs.max_width_kind = 0;
  10016. l->left = x;
  10017. l->right = x + colw;
  10018. if (l->right < l->left + 8)
  10019. l->right = l->left + 8;
  10020. l->y = y;
  10021. l->line_left = l->line_x = l->left;
  10022. l->run_x = l->left;
  10023. l->line_y = l->y;
  10024. l->line_h = 0;
  10025. l->nruns = 0;
  10026. l->space_pending = 0;
  10027. l->align = cs.align;
  10028. layout_block(l, n, &cs, depth + 1, lk);
  10029. h = l->y - y;
  10030. if (h > row_h)
  10031. row_h = h;
  10032. col++;
  10033. n = nd->next;
  10034. if (col == ncols) {
  10035. y += row_h + gap;
  10036. x = row_left;
  10037. row_h = 0;
  10038. col = 0;
  10039. } else {
  10040. x += colw + gap;
  10041. }
  10042. }
  10043. if (col)
  10044. y += row_h;
  10045. else if (y > start_y)
  10046. y -= gap;
  10047. l->left = row_left;
  10048. l->right = row_right;
  10049. l->y = y;
  10050. l->line_left = l->line_x = l->left;
  10051. l->run_x = l->left;
  10052. l->line_y = l->y;
  10053. l->line_h = 0;
  10054. l->nruns = 0;
  10055. l->space_pending = 0;
  10056. }
  10057. /* Column widths are the widest cell in each column across every row, so all
  10058. * rows line up. The table model is still deliberately basic: no colspan,
  10059. * border-collapse or percentage columns. */
  10060. static void table_columns(struct lay *l, unsigned int table,
  10061. const struct br_style *pst, int avail,
  10062. int *raw, int maxcols, int *out_cols,
  10063. int *out_total)
  10064. {
  10065. unsigned int r, c;
  10066. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  10067. int fixed[12];
  10068. for (c = 0; c < (unsigned int)maxcols; c++) {
  10069. raw[c] = 0;
  10070. fixed[c] = 0;
  10071. }
  10072. /* Intrinsic widths of single-column cells. */
  10073. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10074. struct br_node *rn = &doc.nodes[r];
  10075. int col = 0;
  10076. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10077. continue;
  10078. for (c = rn->first; c; c = doc.nodes[c].next) {
  10079. struct br_node *cn = &doc.nodes[c];
  10080. struct br_style cs;
  10081. int w, span;
  10082. if (cn->type != BR_NODE_ELEM ||
  10083. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10084. continue;
  10085. span = cn->colspan ? cn->colspan : 1;
  10086. br_style_for(&doc, c, pst, &cs);
  10087. if (cs.display == BR_DISPLAY_NONE)
  10088. continue;
  10089. if (col + span > maxcols)
  10090. span = maxcols - col;
  10091. if (span < 1)
  10092. break;
  10093. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  10094. mp_px(&cs, 7, avail) +
  10095. mp_px(&cs, 5, avail) +
  10096. mp_px(&cs, 3, avail) +
  10097. mp_px(&cs, 1, avail) +
  10098. cs.border_w[0] + cs.border_w[1] +
  10099. cs.border_w[2] + cs.border_w[3];
  10100. if (w < 24)
  10101. w = 24;
  10102. if (span == 1) {
  10103. if (w > raw[col])
  10104. raw[col] = w;
  10105. }
  10106. if (col + span > cols)
  10107. cols = col + span;
  10108. col += span;
  10109. }
  10110. }
  10111. /* A colspan cell only has to be as wide as the sum of its columns. */
  10112. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10113. struct br_node *rn = &doc.nodes[r];
  10114. int col = 0;
  10115. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10116. continue;
  10117. for (c = rn->first; c; c = doc.nodes[c].next) {
  10118. struct br_node *cn = &doc.nodes[c];
  10119. struct br_style cs;
  10120. int span, w, sum, i;
  10121. if (cn->type != BR_NODE_ELEM ||
  10122. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10123. continue;
  10124. span = cn->colspan ? cn->colspan : 1;
  10125. if (col + span > maxcols)
  10126. span = maxcols - col;
  10127. if (span < 1)
  10128. break;
  10129. if (span > 1) {
  10130. br_style_for(&doc, c, pst, &cs);
  10131. if (cs.display != BR_DISPLAY_NONE) {
  10132. w = intrinsic_width(l->ui, c, &cs,
  10133. 0, avail) +
  10134. mp_px(&cs, 7, avail) +
  10135. mp_px(&cs, 5, avail) +
  10136. mp_px(&cs, 3, avail) +
  10137. mp_px(&cs, 1, avail) +
  10138. cs.border_w[0] + cs.border_w[1] +
  10139. cs.border_w[2] + cs.border_w[3];
  10140. sum = 0;
  10141. for (i = 0; i < span; i++)
  10142. sum += raw[col + i];
  10143. if (w > sum)
  10144. raw[col + span - 1] += w - sum;
  10145. }
  10146. }
  10147. col += span;
  10148. }
  10149. }
  10150. /* Explicit and percentage widths override intrinsic widths. */
  10151. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10152. struct br_node *rn = &doc.nodes[r];
  10153. int col = 0;
  10154. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10155. continue;
  10156. for (c = rn->first; c; c = doc.nodes[c].next) {
  10157. struct br_node *cn = &doc.nodes[c];
  10158. struct br_style cs;
  10159. int span;
  10160. if (cn->type != BR_NODE_ELEM ||
  10161. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10162. continue;
  10163. span = cn->colspan ? cn->colspan : 1;
  10164. if (col + span > maxcols)
  10165. span = maxcols - col;
  10166. if (span < 1)
  10167. break;
  10168. if (span == 1) {
  10169. br_style_for(&doc, c, pst, &cs);
  10170. if (cs.display != BR_DISPLAY_NONE) {
  10171. if (cs.width_kind == 1) {
  10172. raw[col] = cs.width;
  10173. fixed[col] = 1;
  10174. } else if (cs.width_kind == 2 ||
  10175. cs.width_kind == 3) {
  10176. raw[col] = style_width_px(&cs,
  10177. avail);
  10178. fixed[col] = 1;
  10179. }
  10180. }
  10181. }
  10182. col += span;
  10183. }
  10184. }
  10185. for (c = 0; c < (unsigned int)cols; c++) {
  10186. if (raw[c] < 8)
  10187. raw[c] = 8;
  10188. total += raw[c];
  10189. if (fixed[c])
  10190. fixed_sum += raw[c];
  10191. else {
  10192. free_raw += raw[c];
  10193. free_cols++;
  10194. }
  10195. }
  10196. if (fixed_sum > 0 && fixed_sum < avail) {
  10197. int free_avail = avail - fixed_sum;
  10198. int i;
  10199. if (free_raw > 0) {
  10200. for (i = 0; i < cols; i++)
  10201. if (!fixed[i])
  10202. raw[i] = free_avail * raw[i] /
  10203. free_raw;
  10204. } else if (free_cols > 0) {
  10205. for (i = 0; i < cols; i++)
  10206. if (!fixed[i])
  10207. raw[i] = free_avail / free_cols;
  10208. }
  10209. total = 0;
  10210. for (i = 0; i < cols; i++)
  10211. total += raw[i];
  10212. } else if (total < avail && total > 0) {
  10213. int i;
  10214. for (i = 0; i < cols; i++)
  10215. raw[i] = raw[i] * avail / total;
  10216. total = 0;
  10217. for (i = 0; i < cols; i++)
  10218. total += raw[i];
  10219. }
  10220. *out_cols = cols;
  10221. *out_total = total;
  10222. }
  10223. static void layout_table_row(struct lay *l, unsigned int row,
  10224. const struct br_style *pst, int depth,
  10225. unsigned short link)
  10226. {
  10227. unsigned int n, cell[12];
  10228. int raw[12], colstart[12], colspan[12];
  10229. int prefix[13];
  10230. int ncell = 0, total = 0, cols = 0, col = 0;
  10231. int row_left = l->left, row_right = l->right;
  10232. int avail = row_right - row_left;
  10233. int y = l->y, bottom = l->y;
  10234. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  10235. struct br_node *nd = &doc.nodes[n];
  10236. struct br_style cs;
  10237. int span;
  10238. if (nd->type == BR_NODE_TEXT) {
  10239. if (text_node_blank(nd))
  10240. continue;
  10241. layout_children(l, row, pst, depth, link);
  10242. return;
  10243. }
  10244. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  10245. layout_children(l, row, pst, depth, link);
  10246. return;
  10247. }
  10248. br_style_for(&doc, n, pst, &cs);
  10249. if (cs.display == BR_DISPLAY_NONE)
  10250. continue;
  10251. if (ncell >= 12) {
  10252. layout_children(l, row, pst, depth, link);
  10253. return;
  10254. }
  10255. span = nd->colspan ? nd->colspan : 1;
  10256. if (span > 12 - col)
  10257. span = 12 - col;
  10258. if (span < 1)
  10259. continue;
  10260. cell[ncell] = n;
  10261. colstart[ncell] = col;
  10262. colspan[ncell] = span;
  10263. col += span;
  10264. ncell++;
  10265. }
  10266. if (ncell < 1 || avail < 32) {
  10267. layout_children(l, row, pst, depth, link);
  10268. return;
  10269. }
  10270. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  10271. &total);
  10272. if (cols < 2 || total <= 0) {
  10273. int c;
  10274. total = 0;
  10275. for (c = 0; c < ncell; c++) {
  10276. struct br_style cs;
  10277. br_style_for(&doc, cell[c], pst, &cs);
  10278. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  10279. avail) +
  10280. mp_px(&cs, 7, avail) +
  10281. mp_px(&cs, 5, avail) +
  10282. mp_px(&cs, 3, avail) +
  10283. mp_px(&cs, 1, avail);
  10284. if (raw[c] < 24)
  10285. raw[c] = 24;
  10286. total += raw[c];
  10287. }
  10288. /* A one-column table still has to fill its own width; the
  10289. * intrinsic fallback above otherwise leaves the cell at its
  10290. * text width (HN's outer table and nested story table). */
  10291. if (total > 0 && total < avail) {
  10292. int c;
  10293. for (c = 0; c < ncell; c++)
  10294. raw[c] = raw[c] * avail / total;
  10295. total = avail;
  10296. }
  10297. }
  10298. prefix[0] = row_left;
  10299. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  10300. prefix[n + 1] = prefix[n] + raw[n];
  10301. for (n = 0; n < (unsigned int)ncell; n++) {
  10302. struct br_style cs;
  10303. int start = colstart[n];
  10304. int end = start + colspan[n];
  10305. int w;
  10306. if (end > cols)
  10307. end = cols;
  10308. if (start >= cols)
  10309. continue;
  10310. w = prefix[end] - prefix[start];
  10311. br_style_for(&doc, cell[n], pst, &cs);
  10312. /* The column width already reflects the cell's width property. */
  10313. cs.width_kind = 0;
  10314. cs.max_width_kind = 0;
  10315. if (w < 24)
  10316. w = 24;
  10317. if (w < 8)
  10318. w = 8;
  10319. l->left = prefix[start];
  10320. l->right = l->left + w;
  10321. l->y = y;
  10322. l->line_left = l->line_x = l->left;
  10323. l->run_x = l->left;
  10324. l->line_y = l->y;
  10325. l->line_h = 0;
  10326. l->nruns = 0;
  10327. l->space_pending = 0;
  10328. l->align = cs.align;
  10329. layout_block(l, cell[n], &cs, depth + 1, link);
  10330. if (l->y > bottom)
  10331. bottom = l->y;
  10332. }
  10333. l->left = row_left;
  10334. l->right = row_right;
  10335. l->y = bottom;
  10336. l->line_left = l->line_x = l->left;
  10337. l->run_x = l->left;
  10338. l->line_y = l->y;
  10339. l->line_h = 0;
  10340. l->nruns = 0;
  10341. l->space_pending = 0;
  10342. }
  10343. #define TBL_MAX_ROWS 32
  10344. #define TBL_MAX_COLS 12
  10345. #define TBL_MAX_CELLS 128
  10346. struct tbl_cell {
  10347. unsigned int node;
  10348. unsigned char row, col, rowspan, colspan;
  10349. int height;
  10350. };
  10351. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  10352. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  10353. static int table_active;
  10354. static int table_has_rowspan(unsigned int table)
  10355. {
  10356. unsigned int r, c;
  10357. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10358. struct br_node *rn = &doc.nodes[r];
  10359. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10360. continue;
  10361. for (c = rn->first; c; c = doc.nodes[c].next) {
  10362. struct br_node *cn = &doc.nodes[c];
  10363. if (cn->type == BR_NODE_ELEM &&
  10364. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  10365. cn->rowspan > 1)
  10366. return 1;
  10367. }
  10368. }
  10369. return 0;
  10370. }
  10371. static void table_cell_style(unsigned int row, unsigned int cell,
  10372. const struct br_style *st, struct br_style *out)
  10373. {
  10374. struct br_style trs;
  10375. br_style_for(&doc, row, st, &trs);
  10376. br_style_for(&doc, cell, &trs, out);
  10377. }
  10378. /* Tables that use rowspan need row heights before anything is painted. This
  10379. * path builds a small occupancy grid, measures the natural cell heights, then
  10380. * lays every cell out at its row/column position. Tables without rowspan
  10381. * keep the lighter per-row path in layout_table_row(). */
  10382. static void layout_table(struct lay *l, unsigned int table,
  10383. const struct br_style *st, int depth,
  10384. unsigned short link)
  10385. {
  10386. unsigned int rows[TBL_MAX_ROWS];
  10387. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  10388. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  10389. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  10390. int free_raw = 0, free_cols = 0;
  10391. int table_left = l->left, table_right = l->right;
  10392. int top = l->y, avail = table_right - table_left;
  10393. unsigned int r, c;
  10394. int i, rr, cc;
  10395. if (depth > 48 || table_active) {
  10396. layout_children(l, table, st, depth, link);
  10397. return;
  10398. }
  10399. table_active = 1;
  10400. for (r = doc.nodes[table].first;
  10401. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  10402. struct br_node *rn = &doc.nodes[r];
  10403. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  10404. rows[nrows++] = r;
  10405. }
  10406. if (!nrows) {
  10407. table_active = 0;
  10408. layout_children(l, table, st, depth, link);
  10409. return;
  10410. }
  10411. for (rr = 0; rr < nrows; rr++)
  10412. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  10413. tbl_at[rr][cc] = 0;
  10414. for (rr = 0; rr < nrows; rr++) {
  10415. int col = 0;
  10416. for (c = doc.nodes[rows[rr]].first; c;
  10417. c = doc.nodes[c].next) {
  10418. struct br_node *cn = &doc.nodes[c];
  10419. struct br_style cs;
  10420. int rs, csn;
  10421. if (cn->type != BR_NODE_ELEM ||
  10422. (cn->tag != BR_TAG_TD &&
  10423. cn->tag != BR_TAG_TH))
  10424. continue;
  10425. table_cell_style(rows[rr], c, st, &cs);
  10426. if (cs.display == BR_DISPLAY_NONE)
  10427. continue;
  10428. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  10429. col++;
  10430. if (col >= TBL_MAX_COLS)
  10431. break;
  10432. rs = cn->rowspan ? cn->rowspan : 1;
  10433. csn = cn->colspan ? cn->colspan : 1;
  10434. if (rr + rs > nrows)
  10435. rs = nrows - rr;
  10436. if (col + csn > TBL_MAX_COLS)
  10437. csn = TBL_MAX_COLS - col;
  10438. if (rs < 1 || csn < 1)
  10439. continue;
  10440. if (ncells >= TBL_MAX_CELLS)
  10441. break;
  10442. tbl_cells[ncells].node = c;
  10443. tbl_cells[ncells].row = (unsigned char)rr;
  10444. tbl_cells[ncells].col = (unsigned char)col;
  10445. tbl_cells[ncells].rowspan = (unsigned char)rs;
  10446. tbl_cells[ncells].colspan = (unsigned char)csn;
  10447. tbl_cells[ncells].height = 0;
  10448. for (i = rr; i < rr + rs; i++)
  10449. for (int j = col; j < col + csn; j++)
  10450. tbl_at[i][j] =
  10451. (unsigned short)(ncells + 1);
  10452. ncells++;
  10453. col += csn;
  10454. if (col > cols)
  10455. cols = col;
  10456. }
  10457. }
  10458. if (!ncells || cols < 1) {
  10459. table_active = 0;
  10460. layout_children(l, table, st, depth, link);
  10461. return;
  10462. }
  10463. for (i = 0; i < cols; i++) {
  10464. raw[i] = 0;
  10465. fixed[i] = 0;
  10466. }
  10467. /* Intrinsic widths of single-column cells. */
  10468. for (i = 0; i < ncells; i++) {
  10469. struct br_style cs;
  10470. int w;
  10471. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10472. st, &cs);
  10473. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10474. mp_px(&cs, 7, avail) +
  10475. mp_px(&cs, 5, avail) +
  10476. mp_px(&cs, 3, avail) +
  10477. mp_px(&cs, 1, avail) +
  10478. cs.border_w[0] + cs.border_w[1] +
  10479. cs.border_w[2] + cs.border_w[3];
  10480. if (w < 24)
  10481. w = 24;
  10482. if (tbl_cells[i].colspan == 1) {
  10483. int col = tbl_cells[i].col;
  10484. if (w > raw[col])
  10485. raw[col] = w;
  10486. }
  10487. }
  10488. /* A spanning cell only needs the sum of its columns to be large
  10489. * enough; put the deficit in the last column. */
  10490. for (i = 0; i < ncells; i++) {
  10491. struct br_style cs;
  10492. int w, sum, col, span;
  10493. if (tbl_cells[i].colspan < 2)
  10494. continue;
  10495. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10496. st, &cs);
  10497. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10498. mp_px(&cs, 7, avail) +
  10499. mp_px(&cs, 5, avail) +
  10500. mp_px(&cs, 3, avail) +
  10501. mp_px(&cs, 1, avail) +
  10502. cs.border_w[0] + cs.border_w[1] +
  10503. cs.border_w[2] + cs.border_w[3];
  10504. col = tbl_cells[i].col;
  10505. span = tbl_cells[i].colspan;
  10506. sum = 0;
  10507. for (int j = 0; j < span; j++)
  10508. sum += raw[col + j];
  10509. if (w > sum)
  10510. raw[col + span - 1] += w - sum;
  10511. }
  10512. /* Explicit/percentage widths, as in table_columns(). */
  10513. for (i = 0; i < ncells; i++) {
  10514. struct br_style cs;
  10515. int col;
  10516. if (tbl_cells[i].colspan != 1)
  10517. continue;
  10518. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10519. st, &cs);
  10520. col = tbl_cells[i].col;
  10521. if (cs.width_kind == 1) {
  10522. raw[col] = cs.width;
  10523. fixed[col] = 1;
  10524. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  10525. raw[col] = style_width_px(&cs, avail);
  10526. fixed[col] = 1;
  10527. }
  10528. }
  10529. for (i = 0; i < cols; i++) {
  10530. if (raw[i] < 8)
  10531. raw[i] = 8;
  10532. total += raw[i];
  10533. if (fixed[i])
  10534. fixed_sum += raw[i];
  10535. else {
  10536. free_raw += raw[i];
  10537. free_cols++;
  10538. }
  10539. }
  10540. if (fixed_sum > 0 && fixed_sum < avail) {
  10541. int free_avail = avail - fixed_sum;
  10542. if (free_raw > 0) {
  10543. for (i = 0; i < cols; i++)
  10544. if (!fixed[i])
  10545. raw[i] = free_avail * raw[i] /
  10546. free_raw;
  10547. } else if (free_cols > 0) {
  10548. for (i = 0; i < cols; i++)
  10549. if (!fixed[i])
  10550. raw[i] = free_avail / free_cols;
  10551. }
  10552. } else if (total < avail && total > 0) {
  10553. for (i = 0; i < cols; i++)
  10554. raw[i] = raw[i] * avail / total;
  10555. }
  10556. prefix[0] = table_left;
  10557. for (i = 0; i < cols; i++)
  10558. prefix[i + 1] = prefix[i] + raw[i];
  10559. /* Measure natural cell heights with the column widths. */
  10560. for (i = 0; i < ncells; i++) {
  10561. struct br_style cs;
  10562. int col = tbl_cells[i].col;
  10563. int span = tbl_cells[i].colspan;
  10564. int w = prefix[col + span] - prefix[col];
  10565. int sl = l->left, sr = l->right, sy = l->y;
  10566. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10567. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10568. int sal = l->align, sdraw = l->draw;
  10569. struct ngui *sui = l->ui;
  10570. if (w < 8)
  10571. w = 8;
  10572. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10573. st, &cs);
  10574. cs.width_kind = 0;
  10575. cs.max_width_kind = 0;
  10576. l->draw = 0;
  10577. l->ui = 0;
  10578. l->left = prefix[col];
  10579. l->right = l->left + w;
  10580. l->y = 0;
  10581. l->line_left = l->line_x = l->left;
  10582. l->run_x = l->left;
  10583. l->line_y = 0;
  10584. l->line_h = 0;
  10585. l->nruns = 0;
  10586. l->space_pending = 0;
  10587. l->align = cs.align;
  10588. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10589. tbl_cells[i].height = block_h[tbl_cells[i].node];
  10590. l->left = sl;
  10591. l->right = sr;
  10592. l->y = sy;
  10593. l->line_x = slx;
  10594. l->run_x = srx;
  10595. l->line_y = sly;
  10596. l->line_h = slh;
  10597. l->nruns = snr;
  10598. l->space_pending = ssp;
  10599. l->align = sal;
  10600. l->draw = sdraw;
  10601. l->ui = sui;
  10602. }
  10603. for (i = 0; i < nrows; i++)
  10604. rowh[i] = 0;
  10605. for (i = 0; i < ncells; i++) {
  10606. int row = tbl_cells[i].row;
  10607. if (tbl_cells[i].rowspan == 1) {
  10608. if (tbl_cells[i].height > rowh[row])
  10609. rowh[row] = tbl_cells[i].height;
  10610. }
  10611. }
  10612. for (i = 0; i < ncells; i++) {
  10613. int row = tbl_cells[i].row;
  10614. int span = tbl_cells[i].rowspan;
  10615. int sum = 0;
  10616. if (span < 2)
  10617. continue;
  10618. for (int j = 0; j < span; j++)
  10619. sum += rowh[row + j];
  10620. if (sum < tbl_cells[i].height)
  10621. rowh[row + span - 1] +=
  10622. tbl_cells[i].height - sum;
  10623. }
  10624. for (i = 0; i < nrows; i++)
  10625. if (rowh[i] < 8)
  10626. rowh[i] = 8;
  10627. rowy[0] = top;
  10628. for (i = 1; i < nrows; i++)
  10629. rowy[i] = rowy[i - 1] + rowh[i - 1];
  10630. if (!l->draw) {
  10631. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10632. table_active = 0;
  10633. return;
  10634. }
  10635. for (i = 0; i < ncells; i++) {
  10636. struct br_style cs;
  10637. int col = tbl_cells[i].col;
  10638. int span = tbl_cells[i].colspan;
  10639. int row = tbl_cells[i].row;
  10640. int rspan = tbl_cells[i].rowspan;
  10641. int w = prefix[col + span] - prefix[col];
  10642. int h = 0;
  10643. int sl = l->left, sr = l->right, sy = l->y;
  10644. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10645. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10646. int sal = l->align;
  10647. int deco;
  10648. for (int j = 0; j < rspan; j++)
  10649. h += rowh[row + j];
  10650. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  10651. cs.width_kind = 0;
  10652. cs.max_width_kind = 0;
  10653. cs.box_sizing = 0;
  10654. deco = mp_px(&cs, 4, avail) +
  10655. mp_px(&cs, 6, avail) +
  10656. cs.border_w[0] + cs.border_w[2];
  10657. cs.height_kind = 1;
  10658. cs.height = h > deco ? h - deco : 0;
  10659. /* The block painter reads block_h[] from the measure pass; make
  10660. * the table cell fill its row/rowspan, not just its content. */
  10661. if (h > 0 && h < 65536)
  10662. block_h[tbl_cells[i].node] = (unsigned short)h;
  10663. l->left = prefix[col];
  10664. l->right = l->left + w;
  10665. l->y = rowy[row];
  10666. l->line_left = l->line_x = l->left;
  10667. l->run_x = l->left;
  10668. l->line_y = l->y;
  10669. l->line_h = 0;
  10670. l->nruns = 0;
  10671. l->space_pending = 0;
  10672. l->align = cs.align;
  10673. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10674. l->left = sl;
  10675. l->right = sr;
  10676. l->y = sy;
  10677. l->line_x = slx;
  10678. l->run_x = srx;
  10679. l->line_y = sly;
  10680. l->line_h = slh;
  10681. l->nruns = snr;
  10682. l->space_pending = ssp;
  10683. l->align = sal;
  10684. }
  10685. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10686. table_active = 0;
  10687. }
  10688. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  10689. * flow so they sit above it, like CSS painting order. Their flow origin is
  10690. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  10691. struct br_deferred {
  10692. unsigned int node;
  10693. int flow_y, flow_left, flow_right;
  10694. int parent_top; /* the parent box top, for sticky clamping */
  10695. unsigned short link;
  10696. signed short z_index;
  10697. unsigned char z_set;
  10698. unsigned int order;
  10699. };
  10700. /* Positioned boxes painted after the flow. News front pages have one or two
  10701. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  10702. * old 16 entries the rest fell back into the flow, so a hero image landed
  10703. * below its padding-top aspect box instead of on top of it. */
  10704. #define BR_MAX_DEFERRED 256
  10705. static struct br_deferred deferred[BR_MAX_DEFERRED];
  10706. static int ndeferred;
  10707. /* Outer width of an element's empty ::before (pe 1) / ::after (pe 2) icon
  10708. * box, 0 when it has none; *ps receives the pseudo-element's style. */
  10709. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  10710. struct br_style *ps, int base)
  10711. {
  10712. char buf[8];
  10713. int w, h;
  10714. if (!doc.npe_rules ||
  10715. br_pseudo(&doc, node, pe, st, ps, buf, sizeof(buf)) ||
  10716. ps->content != BR_CONTENT_EMPTY || ps->display == BR_DISPLAY_NONE)
  10717. return 0;
  10718. w = ps->width_kind ? style_width_px(ps, base) : 0;
  10719. h = ps->height_kind ? style_height_px(ps, base) : 0;
  10720. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  10721. w = (int)ps->min_width;
  10722. if (w <= 0)
  10723. w = h;
  10724. if (w <= 0 || w > 512)
  10725. return 0;
  10726. return w + (ps->ml_auto ? 0 : mp_px(ps, 3, base)) + mp_px(ps, 1, base);
  10727. }
  10728. /* An empty ::before/::after with a size and a background: one run the
  10729. * size of the box. Only data: background images are drawn (decoded at
  10730. * the background-size); `margin-left: auto` inside a flex parent pushes
  10731. * the box to the line's right edge like the flex row would. */
  10732. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  10733. const struct br_style *ps, unsigned short link)
  10734. {
  10735. struct lay_run *r;
  10736. int lw = l->line_right - l->line_left, w, h, ml, mr, tw, th;
  10737. const char *url = ps->bg_image ? br_bg_image_url(ps->bg_image - 1) : "";
  10738. if (lw < 8)
  10739. lw = 8;
  10740. w = ps->width_kind ? style_width_px(ps, lw) : 0;
  10741. h = ps->height_kind ? style_height_px(ps, lw) : 0;
  10742. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  10743. w = (int)ps->min_width;
  10744. if (w <= 0)
  10745. w = h;
  10746. if (h <= 0)
  10747. h = w;
  10748. if (w <= 0 || w > 512 || h > 512)
  10749. return;
  10750. ml = ps->ml_auto ? 0 : mp_px(ps, 3, lw);
  10751. mr = mp_px(ps, 1, lw);
  10752. if (ml < 0)
  10753. ml = 0;
  10754. if (mr < 0)
  10755. mr = 0;
  10756. if (l->line_x + ml + w > l->line_right &&
  10757. (l->nruns > 0 || l->line_x > l->line_left))
  10758. flush_line(l);
  10759. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  10760. flush_line(l);
  10761. if (l->nruns == 0) {
  10762. l->line_y = l->y;
  10763. l->line_h = 0;
  10764. start_line(l, ps);
  10765. }
  10766. if (ps->ml_auto && parent->display == BR_DISPLAY_FLEX &&
  10767. l->line_right - w - mr > l->line_x)
  10768. l->line_x = l->line_right - w - mr;
  10769. else
  10770. l->line_x += ml;
  10771. r = &l->runs[l->nruns++];
  10772. memset(r, 0, sizeof(*r));
  10773. r->gap = (unsigned short)(l->line_x > l->run_x ?
  10774. l->line_x - l->run_x : 0);
  10775. r->img = RUN_PBOX;
  10776. r->href = link;
  10777. r->iw = (unsigned short)w;
  10778. r->ih = (unsigned short)h;
  10779. r->w = (unsigned short)w;
  10780. r->font_px = ps->font_px;
  10781. r->pb_has_bg = ps->has_bg;
  10782. r->pb_bg = ps->bg;
  10783. r->pb_img = -1;
  10784. if (ps->transform_set) {
  10785. r->transform_scale = 1;
  10786. r->scale_x = ps->scale_x;
  10787. r->scale_y = ps->scale_y;
  10788. r->rotate_x100 = ps->rotate_x100;
  10789. }
  10790. /* Background size and position, as draw_bg_image() resolves them. */
  10791. tw = w;
  10792. th = h;
  10793. if (ps->bg_size_kind == 1 || ps->bg_size_kind == 2) {
  10794. int bw = ps->bg_size_w, bh = ps->bg_size_h;
  10795. if (ps->bg_size_kind == 2) {
  10796. bw = bw ? w * bw / 100 : 0;
  10797. bh = bh ? h * bh / 100 : 0;
  10798. }
  10799. tw = bw ? bw : (bh ? bh : w);
  10800. th = bh ? bh : tw;
  10801. }
  10802. if (tw > 0 && th > 0 && tw <= 512 && th <= 512 && url[0])
  10803. r->pb_img = (short)data_url_image(url, tw, th);
  10804. r->pb_w = (short)tw;
  10805. r->pb_h = (short)th;
  10806. r->pb_x = (short)(ps->bg_pos_x_kind == 1 ?
  10807. (w - tw) * ps->bg_pos_x / 100 : ps->bg_pos_x);
  10808. r->pb_y = (short)(ps->bg_pos_y_kind == 1 ?
  10809. (h - th) * ps->bg_pos_y / 100 : ps->bg_pos_y);
  10810. l->line_x += w + mr;
  10811. l->run_x = l->line_x;
  10812. if (l->line_h < h)
  10813. l->line_h = h;
  10814. }
  10815. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  10816. * element's line. A block-level pseudo-element gets its own line; its box
  10817. * (margins, padding, background) is not drawn. */
  10818. static void emit_pseudo(struct lay *l, unsigned int node,
  10819. const struct br_style *st, int pe, unsigned short link)
  10820. {
  10821. char buf[160];
  10822. struct br_style ps;
  10823. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  10824. unsigned int i = 0;
  10825. int block, space_w;
  10826. if (!n && ps.content == BR_CONTENT_EMPTY &&
  10827. ps.display != BR_DISPLAY_NONE) {
  10828. emit_pseudo_box(l, st, &ps, link);
  10829. return;
  10830. }
  10831. if (!n)
  10832. return;
  10833. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  10834. if (block)
  10835. flush_line(l);
  10836. if (ps.uppercase)
  10837. for (i = 0; i < n; i++)
  10838. if (buf[i] >= 'a' && buf[i] <= 'z')
  10839. buf[i] = (char)(buf[i] - 'a' + 'A');
  10840. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  10841. if (space_w <= 0)
  10842. space_w = 8;
  10843. i = 0;
  10844. while (i < n) {
  10845. char word[28];
  10846. unsigned int k = 0;
  10847. int w;
  10848. if (buf[i] == ' ') {
  10849. l->space_pending = 1;
  10850. i++;
  10851. continue;
  10852. }
  10853. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  10854. word[k++] = buf[i++];
  10855. word[k] = '\0';
  10856. if (l->space_pending &&
  10857. (l->nruns > 0 || l->line_x > l->line_left) &&
  10858. l->line_x + space_w <= l->line_right)
  10859. l->line_x += space_w;
  10860. l->space_pending = 0;
  10861. w = (int)face_text_width(l->ui, &ps, word, k);
  10862. if (l->line_x + w > l->line_right &&
  10863. (l->nruns > 0 || l->line_x > l->line_left))
  10864. flush_line(l);
  10865. add_run(l, 0, 0, &ps, link, word);
  10866. }
  10867. if (block)
  10868. flush_line(l);
  10869. }
  10870. /* An out-of-flow child (absolute/fixed, or a relative/sticky box with a
  10871. * z-index): measured in place, painted from the deferred stacked pass
  10872. * against its containing block. Shared by block and flex layout, so an
  10873. * absolute icon inside a flex row (a password field's reveal button) is
  10874. * not laid out as one of the row's items. Returns 1 when it handled n. */
  10875. static int layout_out_of_flow(struct lay *l, unsigned int n,
  10876. const struct br_style *cs, int depth,
  10877. unsigned short lk)
  10878. {
  10879. if (!(cs->pos == 1 || cs->pos == 2 ||
  10880. ((cs->pos == 3 || cs->pos == 4) && cs->z_set)))
  10881. return 0;
  10882. if ((cs->pos == 3 || cs->pos == 4) && l->draw &&
  10883. ndeferred < BR_MAX_DEFERRED) {
  10884. /* Relative or sticky z-index (a sticky site
  10885. * header): measure and advance the flow without
  10886. * painting, then paint it in the deferred
  10887. * (stacked) pass, above the content after it. */
  10888. int fy = l->y, fl = l->left, fr = l->right;
  10889. int save_draw = l->draw;
  10890. l->draw = 0;
  10891. layout_block(l, n, cs, depth + 1, lk);
  10892. l->draw = save_draw;
  10893. deferred[ndeferred].node = n;
  10894. deferred[ndeferred].parent_top = l->parent_top;
  10895. deferred[ndeferred].flow_y = fy;
  10896. deferred[ndeferred].flow_left = fl;
  10897. deferred[ndeferred].flow_right = fr;
  10898. deferred[ndeferred].link = lk;
  10899. deferred[ndeferred].z_index = cs->z_index;
  10900. deferred[ndeferred].z_set = cs->z_set;
  10901. deferred[ndeferred].order = (unsigned int)ndeferred;
  10902. ndeferred++;
  10903. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  10904. deferred[ndeferred].node = n;
  10905. deferred[ndeferred].parent_top = l->parent_top;
  10906. deferred[ndeferred].flow_y =
  10907. cs->pos == 1 ? l->cb_top : l->y;
  10908. deferred[ndeferred].flow_left =
  10909. cs->pos == 1 ? l->cb_left : l->left;
  10910. deferred[ndeferred].flow_right =
  10911. cs->pos == 1 ? l->cb_right : l->right;
  10912. deferred[ndeferred].link = lk;
  10913. deferred[ndeferred].z_index = cs->z_index;
  10914. deferred[ndeferred].z_set = cs->z_set;
  10915. deferred[ndeferred].order = (unsigned int)ndeferred;
  10916. ndeferred++;
  10917. } else if (l->draw && cs->pos == 1) {
  10918. /* Deferred list full: paint in place, but still
  10919. * against the containing block, not the flow. */
  10920. int fy = l->y, fl = l->left, fr = l->right;
  10921. l->y = l->cb_top;
  10922. l->left = l->cb_left;
  10923. l->right = l->cb_right;
  10924. layout_block(l, n, cs, depth + 1, lk);
  10925. l->y = fy;
  10926. l->left = fl;
  10927. l->right = fr;
  10928. } else {
  10929. layout_block(l, n, cs, depth + 1, lk);
  10930. }
  10931. if (cs->pos == 1 && block_h[n] &&
  10932. doc.nodes[n].class_off) {
  10933. const char *cl = doc.attrs +
  10934. doc.nodes[n].class_off;
  10935. if ((contains_ci(cl, "poster-wrapper") ||
  10936. contains_ci(cl, "ts-picture")) &&
  10937. !has_skeleton_sibling(n))
  10938. l->y += block_h[n];
  10939. }
  10940. return 1;
  10941. }
  10942. static void layout_children(struct lay *l, unsigned int parent,
  10943. const struct br_style *pst, int depth,
  10944. unsigned short link)
  10945. {
  10946. unsigned int n;
  10947. if (depth > 48)
  10948. return;
  10949. emit_pseudo(l, parent, pst, 1, link);
  10950. n = doc.nodes[parent].first;
  10951. while (n) {
  10952. struct br_node *nd = &doc.nodes[n];
  10953. struct br_style cs;
  10954. unsigned short lk = link;
  10955. if (nd->type == BR_NODE_TEXT) {
  10956. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  10957. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  10958. n = nd->next;
  10959. continue;
  10960. }
  10961. br_style_for(&doc, n, pst, &cs);
  10962. if (cs.display == BR_DISPLAY_NONE) {
  10963. n = nd->next;
  10964. continue;
  10965. }
  10966. if (cs.clear && l->float_active) {
  10967. flush_line(l);
  10968. if (l->y < l->float_bottom)
  10969. l->y = l->float_bottom;
  10970. l->float_active = 0;
  10971. l->line_x = l->left;
  10972. l->run_x = l->left;
  10973. l->line_left = l->left;
  10974. l->line_right = l->right;
  10975. l->line_y = l->y;
  10976. l->line_h = 0;
  10977. l->nruns = 0;
  10978. l->space_pending = 0;
  10979. }
  10980. if (nd->tag == BR_TAG_A && nd->href_off)
  10981. lk = (unsigned short)n;
  10982. if (layout_out_of_flow(l, n, &cs, depth, lk)) {
  10983. n = nd->next;
  10984. continue;
  10985. }
  10986. if (nd->tag == BR_TAG_BR) {
  10987. flush_line(l);
  10988. n = nd->next;
  10989. continue;
  10990. }
  10991. if (nd->tag == BR_TAG_HR) {
  10992. flush_line(l);
  10993. if (l->draw)
  10994. ngui_fill_rect(l->ui,
  10995. (struct ngui_rect){l->left, l->y + 2,
  10996. l->right - l->left, 1}, BR_GRAY);
  10997. l->y += 8;
  10998. n = nd->next;
  10999. continue;
  11000. }
  11001. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  11002. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  11003. !button_has_elements(n)) {
  11004. if (!(nd->tag == BR_TAG_INPUT &&
  11005. s_eq(br_type(&doc, n), "hidden"))) {
  11006. form_fill_line = pst->display ==
  11007. BR_DISPLAY_FLEX &&
  11008. pst->flex_col;
  11009. add_form_run(l, n, &cs, lk);
  11010. form_fill_line = 0;
  11011. }
  11012. n = nd->next;
  11013. continue;
  11014. }
  11015. if (nd->tag == BR_TAG_IMG) {
  11016. add_image_run(l, n, &cs, lk);
  11017. n = nd->next;
  11018. continue;
  11019. }
  11020. if (nd->tag == BR_TAG_SVG &&
  11021. (cs.display == BR_DISPLAY_INLINE ||
  11022. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  11023. !cs.float_left) {
  11024. add_svg_run(l, n, &cs, lk);
  11025. n = nd->next;
  11026. continue;
  11027. }
  11028. if (nd->tag == BR_TAG_VIDEO) {
  11029. layout_block(l, n, &cs, depth + 1, lk);
  11030. n = nd->next;
  11031. continue;
  11032. }
  11033. if (cs.float_left) {
  11034. n = layout_float_group(l, n, pst, depth, lk);
  11035. continue;
  11036. }
  11037. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  11038. inline_block_flows(n, &cs, 0)) {
  11039. layout_children(l, n, &cs, depth + 1, lk);
  11040. n = nd->next;
  11041. continue;
  11042. }
  11043. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  11044. n = layout_inline_blocks(l, n, pst, depth, link);
  11045. continue;
  11046. }
  11047. /* A flex container is block-level like any block box even when
  11048. * the element is an inline tag such as <a> (a link card with
  11049. * display:flex is common on news sites). Without the block box
  11050. * its children were laid out in the parent flow with a 0x0 box
  11051. * of their own. */
  11052. /* inline-flex around inline content only ("| mehr" link
  11053. * tails, icon+label pills) stays in the text line. */
  11054. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  11055. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  11056. !flex_wants_row(n, &cs)) {
  11057. layout_children(l, n, &cs, depth + 1, lk);
  11058. } else if (cs.display == BR_DISPLAY_BLOCK ||
  11059. cs.display == BR_DISPLAY_FLEX ||
  11060. br_tag_is_block(nd->tag))
  11061. layout_block(l, n, &cs, depth + 1, lk);
  11062. else {
  11063. layout_children(l, n, &cs, depth + 1, lk);
  11064. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  11065. l->space_pending = 1;
  11066. }
  11067. n = nd->next;
  11068. }
  11069. emit_pseudo(l, parent, pst, 2, link);
  11070. }
  11071. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  11072. * runs and a recursive page can otherwise overflow the stack. */
  11073. static struct lay layout_state;
  11074. static int measure_page(int left, int right)
  11075. {
  11076. struct lay *l = &layout_state;
  11077. struct br_style base = base_style();
  11078. unsigned int i;
  11079. for (i = 0; i < BR_MAX_NODES; i++) {
  11080. block_h[i] = 0;
  11081. flex_stretch_h[i] = 0;
  11082. img_top[i] = 0;
  11083. block_top[i] = 0;
  11084. img_h[i] = 0;
  11085. layout_boxes[i].valid = 0;
  11086. }
  11087. memset(li_marker, 0, sizeof(li_marker));
  11088. l->draw = 0;
  11089. l->ui = &ui;
  11090. l->left = left;
  11091. l->right = right;
  11092. l->y = 0;
  11093. l->line_x = left;
  11094. l->run_x = left;
  11095. l->line_left = left;
  11096. l->line_right = right;
  11097. l->line_y = 0;
  11098. l->line_h = 0;
  11099. l->align = BR_ALIGN_LEFT;
  11100. l->cb_h = layout_view_h;
  11101. l->float_active = 0;
  11102. l->parent_top = 0;
  11103. l->cb_left = left;
  11104. l->cb_right = right;
  11105. l->cb_top = 0;
  11106. l->depth = 0;
  11107. l->nruns = 0;
  11108. l->space_pending = 0;
  11109. base = root_style();
  11110. layout_children(l, doc.root, &base, 0, 0);
  11111. return l->y + 8;
  11112. }
  11113. static int deferred_cmp(const struct br_deferred *a,
  11114. const struct br_deferred *b)
  11115. {
  11116. int az = a->z_set ? a->z_index : 0;
  11117. int bz = b->z_set ? b->z_index : 0;
  11118. if (az != bz)
  11119. return az < bz ? -1 : 1;
  11120. if (a->order != b->order)
  11121. return a->order < b->order ? -1 : 1;
  11122. return 0;
  11123. }
  11124. static void sort_deferred(void)
  11125. {
  11126. int i;
  11127. for (i = 1; i < ndeferred; i++) {
  11128. struct br_deferred key = deferred[i];
  11129. int j = i;
  11130. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  11131. deferred[j] = deferred[j - 1];
  11132. j--;
  11133. }
  11134. deferred[j] = key;
  11135. }
  11136. }
  11137. static void render_page(int left, int right, int y0)
  11138. {
  11139. struct lay *l = &layout_state;
  11140. struct br_style base = base_style();
  11141. l->draw = 1;
  11142. l->ui = &ui;
  11143. l->left = left;
  11144. l->right = right;
  11145. l->y = y0;
  11146. l->line_x = left;
  11147. l->run_x = left;
  11148. l->line_left = left;
  11149. l->line_right = right;
  11150. l->line_y = y0;
  11151. l->line_h = 0;
  11152. l->align = BR_ALIGN_LEFT;
  11153. l->cb_h = layout_view_h;
  11154. l->float_active = 0;
  11155. l->parent_top = 0;
  11156. l->cb_left = left;
  11157. l->cb_right = right;
  11158. l->cb_top = y0;
  11159. l->depth = 0;
  11160. l->nruns = 0;
  11161. l->space_pending = 0;
  11162. nhits = 0;
  11163. ndeferred = 0;
  11164. base = root_style();
  11165. layout_children(l, doc.root, &base, 0, 0);
  11166. sort_deferred();
  11167. {
  11168. int i;
  11169. for (i = 0; i < ndeferred; i++) {
  11170. struct br_style st;
  11171. br_style_for(&doc, deferred[i].node, &base, &st);
  11172. if (st.display == BR_DISPLAY_NONE)
  11173. continue;
  11174. l->draw = 1;
  11175. l->left = deferred[i].flow_left;
  11176. l->right = deferred[i].flow_right;
  11177. l->y = deferred[i].flow_y;
  11178. l->parent_top = deferred[i].parent_top;
  11179. l->line_left = l->line_x = l->left;
  11180. l->run_x = l->left;
  11181. l->line_y = l->y;
  11182. l->line_h = 0;
  11183. l->nruns = 0;
  11184. l->space_pending = 0;
  11185. l->align = st.align;
  11186. if (st.pos == 2 && block_h[deferred[i].node]) {
  11187. struct ngui_rect clip;
  11188. int ch = block_h[deferred[i].node] + 24;
  11189. int pr = page_rect.x + page_rect.w - 12;
  11190. int x0 = page_rect.x, x1 = pr;
  11191. int y0 = page_rect.y;
  11192. /* A box placed by `bottom` (a page footer) is
  11193. * clipped and filled where layout_block puts
  11194. * it, against the bottom edge. */
  11195. if (st.bottom_set && !st.top_set) {
  11196. ch = block_h[deferred[i].node] +
  11197. mp_px(&st, 0, pr - page_rect.x) +
  11198. mp_px(&st, 2, pr - page_rect.x);
  11199. y0 = page_rect.y + page_rect.h -
  11200. st.bottom - ch;
  11201. }
  11202. /* The background pre-fill spans the box's own
  11203. * columns, not the whole page: Docusaurus parks
  11204. * a white "Skip to main content" link at
  11205. * `left: 100%` with a z-index above the navbar,
  11206. * and a full-width fill painted over the bar. */
  11207. if (st.left_set)
  11208. x0 = page_rect.x + st.left;
  11209. else if (!st.right_set)
  11210. x0 = deferred[i].flow_left;
  11211. if (st.width_kind == 1) {
  11212. if (st.right_set && !st.left_set)
  11213. x0 = pr - st.right - st.width;
  11214. x1 = x0 + st.width;
  11215. } else if (st.right_set) {
  11216. x1 = pr - st.right;
  11217. }
  11218. if (x0 >= pr || x1 <= page_rect.x)
  11219. continue; /* entirely off-screen */
  11220. if (x0 < page_rect.x)
  11221. x0 = page_rect.x;
  11222. if (x1 > pr)
  11223. x1 = pr;
  11224. if (y0 < page_rect.y) {
  11225. ch -= page_rect.y - y0;
  11226. y0 = page_rect.y;
  11227. }
  11228. clip.x = x0;
  11229. clip.y = y0;
  11230. clip.w = x1 - x0;
  11231. if (ch > page_rect.h)
  11232. ch = page_rect.h;
  11233. if (ch <= 0)
  11234. continue;
  11235. clip.h = ch;
  11236. ngui_push_clip(&ui, clip);
  11237. if (st.has_bg)
  11238. ngui_fill_rect(&ui, clip, st.bg);
  11239. layout_block(l, deferred[i].node, &st, 0,
  11240. deferred[i].link);
  11241. ngui_pop_clip(&ui);
  11242. } else {
  11243. layout_block(l, deferred[i].node, &st, 0,
  11244. deferred[i].link);
  11245. }
  11246. }
  11247. }
  11248. }
  11249. /* ---- UI ---- */
  11250. static int find_hit(int x, int y)
  11251. {
  11252. int i;
  11253. for (i = nhits - 1; i >= 0; i--) {
  11254. struct hit *h = &hits[i];
  11255. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  11256. y < h->y + h->h)
  11257. return (int)h->node;
  11258. }
  11259. return 0;
  11260. }
  11261. /* ---- URL-bar autocomplete ----
  11262. *
  11263. * While the address bar has the focus a dropdown lists up to SUG_MAX
  11264. * history entries. An empty bar (a fresh focus, Ctrl+L) shows the most
  11265. * visited/recent sites; typing ranks prefix matches of the URL (with or
  11266. * without the scheme and "www.") above substring matches of the URL, then
  11267. * of the title, and adds visit count and recency. Typing at the end of the
  11268. * text also completes inline to the next '/' of the best prefix match
  11269. * ("clo" -> "cloudron.io/"), with the added part selected so the next
  11270. * keystroke replaces it; Enter on that text opens the history URL it came
  11271. * from (scheme included). Up/Down preview a row in the bar, Delete on a
  11272. * highlighted row forgets it, Esc closes the list (a second Esc leaves the
  11273. * bar), and a click on a row opens it. */
  11274. #define SUG_MAX 6
  11275. #define SUG_ROW_H 36
  11276. static int sug_idx[SUG_MAX];
  11277. static int sug_n, sug_sel = -1, sug_open;
  11278. static char sug_typed[NGUI_INPUT_MAX]; /* what the user typed */
  11279. static char sug_restore[NGUI_INPUT_MAX]; /* bar text before a preview */
  11280. static char ac_text[NGUI_INPUT_MAX]; /* bar text of the inline completion */
  11281. static char ac_url[HIST_URL_MAX]; /* the history URL it stands for */
  11282. static struct ngui_rect url_rect, sug_rect;
  11283. static int url_had_focus;
  11284. static char lc(char c)
  11285. {
  11286. return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
  11287. }
  11288. static int prefix_ci(const char *s, const char *p) /* p is lower case */
  11289. {
  11290. for (; *p; s++, p++)
  11291. if (lc(*s) != *p)
  11292. return 0;
  11293. return 1;
  11294. }
  11295. static unsigned int url_scheme_len(const char *url)
  11296. {
  11297. if (starts_with(url, "https://"))
  11298. return 8;
  11299. if (starts_with(url, "http://"))
  11300. return 7;
  11301. return 0;
  11302. }
  11303. /* Offset in `url` where the lower-case text `t` matches as a prefix: the
  11304. * whole URL, the URL without its scheme, or without scheme and "www.". */
  11305. static int hist_prefix_at(const char *url, const char *t)
  11306. {
  11307. unsigned int s = url_scheme_len(url);
  11308. if (prefix_ci(url, t))
  11309. return 0;
  11310. if (s && prefix_ci(url + s, t))
  11311. return (int)s;
  11312. if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
  11313. return (int)s + 4;
  11314. return -1;
  11315. }
  11316. static int hist_score(const struct hist_ent *e, const char *t,
  11317. unsigned int next)
  11318. {
  11319. unsigned int age = next - e->stamp;
  11320. int sc, at;
  11321. if (!t[0]) {
  11322. sc = 0;
  11323. } else if ((at = hist_prefix_at(e->url, t)) >= 0) {
  11324. /* Shorter rests first: "cloudron.io/" before its subpages. */
  11325. int rest = (int)s_len(e->url + at);
  11326. sc = 4000 - (rest > 400 ? 400 : rest);
  11327. } else if (contains_ci(e->url, t)) {
  11328. sc = 1000;
  11329. } else if (contains_ci(e->title, t)) {
  11330. sc = 600;
  11331. } else {
  11332. return -1;
  11333. }
  11334. sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
  11335. sc += age >= 500 ? 0 : (int)(500 - age);
  11336. return sc;
  11337. }
  11338. static void sug_lower(char *t, unsigned int cap)
  11339. {
  11340. unsigned int k;
  11341. for (k = 0; sug_typed[k] && k + 1 < cap; k++)
  11342. t[k] = lc(sug_typed[k]);
  11343. t[k] = '\0';
  11344. }
  11345. static void sug_refresh(void)
  11346. {
  11347. char t[NGUI_INPUT_MAX];
  11348. int sc[SUG_MAX], i, j;
  11349. unsigned int next = hist_next_stamp();
  11350. sug_lower(t, sizeof(t));
  11351. sug_n = 0;
  11352. for (i = 0; i < hist_n; i++) {
  11353. int s = hist_score(&hist_tab[i], t, next);
  11354. if (s < 0)
  11355. continue;
  11356. j = sug_n;
  11357. if (j == SUG_MAX) {
  11358. if (sc[SUG_MAX - 1] >= s)
  11359. continue;
  11360. j = SUG_MAX - 1;
  11361. }
  11362. while (j > 0 && sc[j - 1] < s) {
  11363. sc[j] = sc[j - 1];
  11364. sug_idx[j] = sug_idx[j - 1];
  11365. j--;
  11366. }
  11367. sc[j] = s;
  11368. sug_idx[j] = i;
  11369. if (sug_n < SUG_MAX)
  11370. sug_n++;
  11371. }
  11372. if (sug_sel >= sug_n)
  11373. sug_sel = -1;
  11374. }
  11375. /* Complete the typed text inline to the next '/' of the best prefix match. */
  11376. static void sug_inline(void)
  11377. {
  11378. char t[NGUI_INPUT_MAX];
  11379. const char *url, *rest;
  11380. unsigned int L, start, end, hs, tn, n = 0;
  11381. unsigned int next = hist_next_stamp();
  11382. int i, best = -1, best_sc = -1, at = 0;
  11383. sug_lower(t, sizeof(t));
  11384. L = s_len(t);
  11385. if (!L)
  11386. return;
  11387. for (i = 0; i < hist_n; i++) {
  11388. int a = hist_prefix_at(hist_tab[i].url, t), s;
  11389. if (a < 0)
  11390. continue;
  11391. s = hist_score(&hist_tab[i], t, next);
  11392. if (s > best_sc) {
  11393. best_sc = s;
  11394. best = i;
  11395. at = a;
  11396. }
  11397. }
  11398. if (best < 0)
  11399. return;
  11400. url = hist_tab[best].url;
  11401. rest = url + at;
  11402. /* Typing the scheme ("htt") completes past "https://", not to it. */
  11403. hs = at == 0 ? url_scheme_len(url) : 0;
  11404. start = L > hs ? L : hs;
  11405. end = start;
  11406. while (rest[end] && rest[end] != '/')
  11407. end++;
  11408. if (rest[end] == '/')
  11409. end++;
  11410. tn = s_len(sug_typed);
  11411. if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
  11412. return;
  11413. s_append(ac_text, &n, sug_typed, sizeof(ac_text));
  11414. for (; L < end && n + 1 < sizeof(ac_text); L++)
  11415. ac_text[n++] = rest[L];
  11416. ac_text[n] = '\0';
  11417. s_copy(ac_url, url, (unsigned int)at + end + 1);
  11418. ngui_input_set(&url_in, ac_text);
  11419. url_in.anchor = tn; /* select the completed part */
  11420. }
  11421. static void sug_close(void)
  11422. {
  11423. sug_open = 0;
  11424. sug_sel = -1;
  11425. ac_text[0] = '\0';
  11426. }
  11427. static int sug_visible(void)
  11428. {
  11429. return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
  11430. }
  11431. /* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
  11432. * start page) lists the top sites until something is typed. */
  11433. static int sug_focus_check(void)
  11434. {
  11435. int focused = ngui_focus(&ui) == ID_URL;
  11436. if (focused && !url_had_focus) {
  11437. sug_typed[0] = '\0';
  11438. sug_close();
  11439. sug_open = 1;
  11440. sug_refresh();
  11441. }
  11442. url_had_focus = focused;
  11443. return focused;
  11444. }
  11445. static void url_submit(unsigned int *action)
  11446. {
  11447. if (ac_text[0] && s_eq(url_in.text, ac_text))
  11448. s_copy(click_url, ac_url, sizeof(click_url));
  11449. *action |= ACT_NAV;
  11450. sug_close();
  11451. }
  11452. /* The bar text changed through typing or editing. */
  11453. static void sug_changed(void)
  11454. {
  11455. unsigned int pl = s_len(sug_typed);
  11456. int grew = url_in.len > pl && url_in.cursor == url_in.len &&
  11457. !memcmp(url_in.text, sug_typed, pl);
  11458. s_copy(sug_typed, url_in.text, sizeof(sug_typed));
  11459. ac_text[0] = '\0';
  11460. sug_sel = -1;
  11461. sug_open = 1;
  11462. sug_refresh();
  11463. if (grew)
  11464. sug_inline();
  11465. }
  11466. /* Keys for the list, taken off the queue before the text field sees them.
  11467. * Only a leading run is handled; the rest goes to the field. */
  11468. static void sug_keys(void)
  11469. {
  11470. int k;
  11471. while ((k = ngui_key_peek(&ui)) != 0) {
  11472. if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
  11473. ngui_key(&ui);
  11474. if (!sug_open) {
  11475. sug_open = 1;
  11476. continue;
  11477. }
  11478. if (sug_sel < 0)
  11479. s_copy(sug_restore, url_in.text,
  11480. sizeof(sug_restore));
  11481. if (k == NGUI_KEY_DOWN)
  11482. sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
  11483. else
  11484. sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
  11485. ngui_input_set(&url_in, sug_sel >= 0 ?
  11486. hist_tab[sug_idx[sug_sel]].url :
  11487. sug_restore);
  11488. } else if (k == NGUI_KEY_ESC && sug_visible()) {
  11489. ngui_key(&ui);
  11490. if (sug_sel >= 0)
  11491. ngui_input_set(&url_in, sug_restore);
  11492. else if (ac_text[0] && s_eq(url_in.text, ac_text))
  11493. ngui_input_set(&url_in, sug_typed);
  11494. sug_close();
  11495. } else if (k == NGUI_KEY_DELETE && sug_visible() &&
  11496. sug_sel >= 0) {
  11497. ngui_key(&ui);
  11498. hist_forget(sug_idx[sug_sel]);
  11499. ngui_input_set(&url_in, sug_restore);
  11500. sug_sel = -1;
  11501. sug_refresh();
  11502. } else {
  11503. break;
  11504. }
  11505. }
  11506. }
  11507. /* A press on a row of last frame's list opens it; any press on the list is
  11508. * swallowed so the page underneath does not see it. */
  11509. static void sug_click(unsigned int *action)
  11510. {
  11511. int row;
  11512. if (!(ui.pressed & 1) || !sug_rect.w ||
  11513. !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
  11514. return;
  11515. row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
  11516. if (row >= 0 && row < sug_n) {
  11517. s_copy(click_url, hist_tab[sug_idx[row]].url,
  11518. sizeof(click_url));
  11519. *action |= ACT_NAV;
  11520. sug_close();
  11521. }
  11522. ui.pressed = 0;
  11523. }
  11524. static void draw_suggest(struct ngui_rect page)
  11525. {
  11526. struct ngui_rect r;
  11527. int i, rows = sug_n, hover = -1;
  11528. r.x = url_rect.x;
  11529. r.y = url_rect.y + url_rect.h + 1;
  11530. r.w = url_rect.w < 320 ? 320 : url_rect.w;
  11531. if (r.x + r.w > ui.w - 2)
  11532. r.w = ui.w - 2 - r.x;
  11533. while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
  11534. rows--;
  11535. if (rows <= 0 || r.w < 60) {
  11536. sug_rect.w = 0;
  11537. return;
  11538. }
  11539. r.h = rows * SUG_ROW_H + 2;
  11540. sug_rect = r;
  11541. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  11542. hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
  11543. ngui_set_cursor(&ui, CURSOR_POINTER);
  11544. }
  11545. ngui_fill_rect(&ui, r, ui.theme.border);
  11546. for (i = 0; i < rows; i++) {
  11547. const struct hist_ent *e = &hist_tab[sug_idx[i]];
  11548. struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
  11549. r.w - 2, SUG_ROW_H};
  11550. struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
  11551. unsigned short bg = i == sug_sel ? ui.theme.selection :
  11552. i == hover ? ui.theme.panel_alt :
  11553. ui.theme.panel;
  11554. ngui_fill_rect(&ui, rr, bg);
  11555. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
  11556. e->title[0] ? e->title : e->url,
  11557. ui.theme.text);
  11558. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
  11559. i == sug_sel ? ui.theme.text :
  11560. ui.theme.text_dim);
  11561. }
  11562. }
  11563. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  11564. {
  11565. int x = r.x + 4, y = r.y + 4, h = 22;
  11566. int compact = r.w < 560;
  11567. int go_w = r.w < 420 ? 32 : 42;
  11568. int in_x, in_w, res;
  11569. ngui_fill_rect(&ui, r, ui.theme.panel);
  11570. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  11571. ui.theme.border);
  11572. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  11573. NGUI_ICON_CHEVRON_LEFT))
  11574. *action |= ACT_BACK;
  11575. x += 32;
  11576. if (!compact) {
  11577. if (ngui_icon_button(&ui, ID_FORWARD,
  11578. (struct ngui_rect){x, y, 28, h},
  11579. NGUI_ICON_CHEVRON_RIGHT))
  11580. *action |= ACT_FORWARD;
  11581. x += 32;
  11582. }
  11583. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  11584. NGUI_ICON_REFRESH))
  11585. *action |= ACT_RELOAD;
  11586. x += 32;
  11587. if (!compact) {
  11588. if (ngui_icon_button(&ui, ID_HOME,
  11589. (struct ngui_rect){x, y, 28, h},
  11590. NGUI_ICON_HOME))
  11591. *action |= ACT_HOME;
  11592. x += 32;
  11593. }
  11594. in_x = x + 2;
  11595. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  11596. if (in_w < 60)
  11597. in_w = 60;
  11598. url_rect = (struct ngui_rect){in_x, y, in_w, h};
  11599. if (sug_focus_check())
  11600. sug_keys();
  11601. res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
  11602. sug_focus_check(); /* a click into the bar focuses it here */
  11603. if (res & NGUI_INPUT_CHANGED)
  11604. sug_changed();
  11605. if (res & NGUI_INPUT_SUBMIT)
  11606. url_submit(action);
  11607. if (res & NGUI_INPUT_CANCEL)
  11608. ngui_set_focus(&ui, 0);
  11609. if (ngui_button(&ui, ID_GO,
  11610. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  11611. "Go"))
  11612. url_submit(action);
  11613. if (!sug_focus_check())
  11614. sug_close();
  11615. }
  11616. static int page_hover_node(void)
  11617. {
  11618. if (!ui.inside)
  11619. return 0;
  11620. if (ui.mouse_x < page_rect.x ||
  11621. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  11622. ui.mouse_y < page_rect.y ||
  11623. ui.mouse_y >= page_rect.y + page_rect.h)
  11624. return 0;
  11625. return find_hit(ui.mouse_x, ui.mouse_y);
  11626. }
  11627. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  11628. {
  11629. int x, y, w = page.w, h = page.h;
  11630. if (!src || w <= 0 || h <= 0)
  11631. return;
  11632. for (y = 0; y < h; y++) {
  11633. unsigned short *s = src + (page.y + y) * sw + page.x;
  11634. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  11635. for (x = 0; x + 1 < w; x += 2) {
  11636. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  11637. }
  11638. if (x < w)
  11639. d[x] = s[x];
  11640. }
  11641. }
  11642. static void draw_page(struct ngui_rect page)
  11643. {
  11644. int left, right, ch;
  11645. int old_panel, old_dim;
  11646. unsigned short *saved_px;
  11647. unsigned short page_bg = ui.theme.bg;
  11648. int saved_w, saved_h, use_buf;
  11649. unsigned int t0 = u_ticks_ms();
  11650. page_rect = page;
  11651. {
  11652. unsigned int root = doc.nnode > 1 ?
  11653. br_find_tag(&doc, BR_TAG_HTML) : 0;
  11654. unsigned int body = doc.nnode > 1 ?
  11655. br_find_tag(&doc, BR_TAG_BODY) : 0;
  11656. struct br_style bs;
  11657. int bg_found = 0;
  11658. if (root) {
  11659. style_for_node(root - 1, &bs);
  11660. if (bs.has_bg) {
  11661. page_bg = bs.bg;
  11662. bg_found = 1;
  11663. }
  11664. }
  11665. if (body) {
  11666. style_for_node(body - 1, &bs);
  11667. if (bs.has_bg) {
  11668. page_bg = bs.bg;
  11669. bg_found = 1;
  11670. }
  11671. }
  11672. /* No canvas colour, but the author made the text dark
  11673. * (Infima's light theme: `--ifm-background-color:
  11674. * transparent` on html, #1c1e21 text): the page expects the
  11675. * white canvas of a normal browser, and dark text on the
  11676. * dark default canvas is unreadable. */
  11677. if (!bg_found && (body || root) && bs.color != ui.theme.text) {
  11678. unsigned int c = bs.color;
  11679. unsigned int lum = ((c >> 11) & 31) * 8 * 299 +
  11680. ((c >> 5) & 63) * 4 * 587 +
  11681. (c & 31) * 8 * 114;
  11682. if (lum < 100 * 1000)
  11683. page_bg = 0xFFFF;
  11684. }
  11685. }
  11686. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  11687. page_cache_valid && layout_valid &&
  11688. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  11689. !(ui.scroll_y &&
  11690. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  11691. page_scroll.offset == page_cache_scroll &&
  11692. page_cache_nnode == doc.nnode &&
  11693. page_cache_x == page.x && page_cache_y == page.y &&
  11694. page_cache_w == page.w && page_cache_h == page.h) {
  11695. blit_page(page, page_backbuf, pagebuf_w);
  11696. if (img_stat_n)
  11697. img_stat_paint += u_ticks_ms() - t0;
  11698. return;
  11699. }
  11700. ngui_fill_rect(&ui, page, page_bg);
  11701. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  11702. const char *s = page_loading ? "Loading..." : "No page";
  11703. int w = (int)ngui_text_width_ui(&ui, s);
  11704. ngui_text(&ui, page.x + (page.w - w) / 2,
  11705. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  11706. page_scroll.content_h = 0;
  11707. page_scroll.view_h = page.h;
  11708. page_cache_valid = 0;
  11709. return;
  11710. }
  11711. if (page.w < 40 || page.h < 40) {
  11712. page_cache_valid = 0;
  11713. return;
  11714. }
  11715. saved_px = ui.px;
  11716. saved_w = ui.w;
  11717. saved_h = ui.h;
  11718. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  11719. if (use_buf) {
  11720. ui.px = page_backbuf;
  11721. ui.w = pagebuf_w;
  11722. ui.h = pagebuf_h;
  11723. ngui_fill_rect(&ui, page, page_bg);
  11724. }
  11725. /* No gutter of our own: the body's UA margin provides it. The
  11726. * right 12 px stay clear for the scrollbar, like every viewport
  11727. * width below (page_rect.w - 12). */
  11728. left = page.x;
  11729. right = page.x + page.w - 12;
  11730. if (!layout_valid || left != layout_left || right != layout_right ||
  11731. layout_nnode != doc.nnode) {
  11732. unsigned int tm = u_ticks_ms();
  11733. layout_view_h = page.h;
  11734. layout_content_h = measure_page(left, right);
  11735. if (img_stat_n)
  11736. img_stat_reflow += u_ticks_ms() - tm;
  11737. layout_valid = 1;
  11738. layout_left = left;
  11739. layout_right = right;
  11740. layout_nnode = doc.nnode;
  11741. /* Scripts that measured before any layout (offsetWidth on
  11742. * mount) get a resize event once real boxes exist, and again
  11743. * whenever the page width changes. */
  11744. if (js_browser_active() && right - left != resize_sent_w)
  11745. resize_pending = 1;
  11746. }
  11747. ch = layout_content_h;
  11748. page_scroll.content_h = ch;
  11749. page_scroll.view_h = page.h;
  11750. t0 = u_ticks_ms();
  11751. ngui_scroll_begin(&ui, page, &page_scroll);
  11752. ngui_scroll_wheel(&ui, page, &page_scroll);
  11753. render_page(left, right, page.y - page_scroll.offset);
  11754. old_panel = ui.theme.panel_alt;
  11755. old_dim = ui.theme.text_dim;
  11756. ui.theme.panel_alt = 0xC618;
  11757. ui.theme.text_dim = 0x8410;
  11758. ngui_scroll_end(&ui, page, &page_scroll);
  11759. ui.theme.panel_alt = old_panel;
  11760. ui.theme.text_dim = old_dim;
  11761. if (use_buf) {
  11762. ui.px = saved_px;
  11763. ui.w = saved_w;
  11764. ui.h = saved_h;
  11765. blit_page(page, page_backbuf, pagebuf_w);
  11766. page_cache_valid = 1;
  11767. page_cache_scroll = page_scroll.offset;
  11768. page_cache_nnode = doc.nnode;
  11769. page_cache_x = page.x;
  11770. page_cache_y = page.y;
  11771. page_cache_w = page.w;
  11772. page_cache_h = page.h;
  11773. } else {
  11774. page_cache_valid = 0;
  11775. }
  11776. if (img_stat_n)
  11777. img_stat_paint += u_ticks_ms() - t0;
  11778. }
  11779. static void draw_status(struct ngui_rect r)
  11780. {
  11781. static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
  11782. unsigned int n = 0;
  11783. int hover = page_hover_node();
  11784. unsigned short color;
  11785. const char *kind;
  11786. ngui_fill_rect(&ui, r, ui.theme.panel);
  11787. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  11788. ui.theme.border);
  11789. /* A form control under the pointer is not a link. */
  11790. if (hover && !br_href(&doc, (unsigned int)hover) &&
  11791. form_is_control((unsigned int)hover))
  11792. hover = 0;
  11793. if (hover) {
  11794. const char *href = br_href(&doc, (unsigned int)hover);
  11795. char url[BR_URL_MAX];
  11796. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  11797. s_append(msg, &n, "Link: ", sizeof(msg));
  11798. s_append(msg, &n, url, sizeof(msg));
  11799. } else {
  11800. s_copy(msg, "Link", sizeof(msg));
  11801. }
  11802. color = ui.theme.accent;
  11803. } else if (status_text[0]) {
  11804. s_copy(msg, status_text, sizeof(msg));
  11805. color = status_error ? ui.theme.error : ui.theme.text;
  11806. } else if (page_title[0]) {
  11807. s_copy(msg, page_title, sizeof(msg));
  11808. color = ui.theme.text;
  11809. } else {
  11810. s_copy(msg, "Ready", sizeof(msg));
  11811. color = ui.theme.text_dim;
  11812. }
  11813. kind = s_eq(page_url, "about:home") ? "HOME" :
  11814. page_is_local ? "FILE" :
  11815. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  11816. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  11817. {
  11818. int kw = (int)ngui_text_width_ui(&ui, kind);
  11819. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  11820. ui.theme.text_dim);
  11821. }
  11822. }
  11823. /* Mouse cursor over the page: the hovered node's CSS `cursor` (inherited);
  11824. * for `auto`, a hand over links, the I-beam over text fields, and the
  11825. * progress arrow anywhere on the page while it is still loading. The
  11826. * toolbar's URL field sets its own I-beam through ngui. */
  11827. static void page_cursor(void)
  11828. {
  11829. int hover = page_hover_node();
  11830. struct br_style st;
  11831. if (!hover) {
  11832. if (page_loading && ui.inside &&
  11833. ngui_rect_contains(&page_rect, ui.mouse_x, ui.mouse_y))
  11834. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  11835. return;
  11836. }
  11837. style_for_node((unsigned int)hover, &st);
  11838. if (st.cursor != BR_CURSOR_AUTO) {
  11839. ngui_set_cursor(&ui, (int)st.cursor - 1);
  11840. return;
  11841. }
  11842. if (br_href(&doc, (unsigned int)hover)) {
  11843. ngui_set_cursor(&ui, CURSOR_POINTER);
  11844. return;
  11845. }
  11846. if (form_is_control((unsigned int)hover)) {
  11847. int k = form_kind_of((unsigned int)hover);
  11848. if (form_disabled((unsigned int)hover))
  11849. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  11850. else if (k == FORM_TEXT || k == FORM_PASSWORD ||
  11851. k == FORM_TEXTAREA)
  11852. ngui_set_cursor(&ui, CURSOR_TEXT);
  11853. return;
  11854. }
  11855. if (page_loading)
  11856. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  11857. }
  11858. static void draw(unsigned int *action)
  11859. {
  11860. struct ngui_rect r = {0, 0, ui.w, ui.h};
  11861. struct ngui_rect toolbar, status, page;
  11862. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  11863. status = ngui_cut_bottom(&r, BR_STATUS_H);
  11864. page = r;
  11865. if (sug_visible())
  11866. sug_click(action);
  11867. draw_toolbar(toolbar, action);
  11868. draw_page(page);
  11869. draw_status(status);
  11870. page_cursor();
  11871. if (sug_visible())
  11872. draw_suggest(page);
  11873. else
  11874. sug_rect.w = 0;
  11875. }
  11876. static void redraw_now(void)
  11877. {
  11878. unsigned int action = 0;
  11879. ngui_begin(&ui);
  11880. draw(&action);
  11881. ngui_end(&ui);
  11882. }
  11883. static void handle_keys(unsigned int *action)
  11884. {
  11885. int k, scrolled = 0;
  11886. if (form_focus >= doc.nnode)
  11887. form_focus = 0;
  11888. if (form_focus && !ngui_focus(&ui)) {
  11889. while ((k = ngui_key(&ui)) != 0)
  11890. form_key(k);
  11891. return;
  11892. }
  11893. /* Batch queued page keys: a slow full-page render must not make a
  11894. * held Page Down advance only once every few frames. */
  11895. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  11896. scrolled++;
  11897. if (scrolled)
  11898. ngui_invalidate(&ui);
  11899. if (ngui_focus(&ui))
  11900. return;
  11901. while ((k = ngui_key(&ui)) != 0) {
  11902. switch (k) {
  11903. case NGUI_KEY_ESC:
  11904. *action |= ACT_CLOSE;
  11905. break;
  11906. case NGUI_KEY_TAB:
  11907. case 0x0C: /* Ctrl+L */
  11908. ngui_set_focus(&ui, ID_URL);
  11909. break;
  11910. case 0x12: /* Ctrl+R */
  11911. *action |= ACT_RELOAD;
  11912. break;
  11913. case NGUI_KEY_BACKSPACE:
  11914. *action |= ACT_BACK;
  11915. break;
  11916. case NGUI_KEY_UP:
  11917. ngui_scroll_to(&page_scroll,
  11918. page_scroll.offset - 24);
  11919. ngui_invalidate(&ui);
  11920. break;
  11921. case NGUI_KEY_DOWN:
  11922. ngui_scroll_to(&page_scroll,
  11923. page_scroll.offset + 24);
  11924. ngui_invalidate(&ui);
  11925. break;
  11926. case NGUI_KEY_HOME:
  11927. ngui_scroll_to(&page_scroll, 0);
  11928. ngui_invalidate(&ui);
  11929. break;
  11930. case NGUI_KEY_END:
  11931. ngui_scroll_to(&page_scroll,
  11932. page_scroll.content_h -
  11933. page_scroll.view_h);
  11934. ngui_invalidate(&ui);
  11935. break;
  11936. default:
  11937. break;
  11938. }
  11939. }
  11940. }
  11941. static unsigned int form_ancestor(unsigned int node)
  11942. {
  11943. unsigned int p = node;
  11944. while (p && p < doc.nnode) {
  11945. if (doc.nodes[p].tag == BR_TAG_FORM &&
  11946. doc.nodes[p].type == BR_NODE_ELEM)
  11947. return p;
  11948. p = doc.nodes[p].parent;
  11949. }
  11950. return 0;
  11951. }
  11952. static int form_descendant(unsigned int node, unsigned int form)
  11953. {
  11954. unsigned int p = node;
  11955. while (p && p < doc.nnode) {
  11956. if (p == form)
  11957. return 1;
  11958. p = doc.nodes[p].parent;
  11959. }
  11960. return 0;
  11961. }
  11962. static void form_reset_form(unsigned int form)
  11963. {
  11964. unsigned int i;
  11965. for (i = 0; i < FORM_MAX; i++)
  11966. if (form_states[i].used &&
  11967. form_descendant(form_states[i].node, form))
  11968. form_states[i].used = 0;
  11969. form_focus = 0;
  11970. }
  11971. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  11972. const char *s)
  11973. {
  11974. static const char hex[] = "0123456789ABCDEF";
  11975. while (s && *s && *n + 1 < cap) {
  11976. unsigned char c = (unsigned char)*s++;
  11977. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  11978. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  11979. c == '.' || c == '~') {
  11980. dst[(*n)++] = (char)c;
  11981. } else if (c == ' ') {
  11982. dst[(*n)++] = '+';
  11983. } else if (*n + 3 < cap) {
  11984. dst[(*n)++] = '%';
  11985. dst[(*n)++] = hex[c >> 4];
  11986. dst[(*n)++] = hex[c & 15];
  11987. }
  11988. }
  11989. dst[*n] = '\0';
  11990. }
  11991. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  11992. const char *name, const char *value, int *first)
  11993. {
  11994. if (!name || !name[0])
  11995. return;
  11996. if (!*first && *n + 1 < cap)
  11997. dst[(*n)++] = '&';
  11998. *first = 0;
  11999. form_url_append(dst, n, cap, name);
  12000. if (*n + 1 < cap)
  12001. dst[(*n)++] = '=';
  12002. form_url_append(dst, n, cap, value ? value : "");
  12003. dst[*n] = '\0';
  12004. }
  12005. static int form_submit_form(unsigned int node, int fire_event)
  12006. {
  12007. unsigned int form = form_ancestor(node);
  12008. char action[BR_URL_MAX], query[2048];
  12009. unsigned int qn = 0, i;
  12010. int first = 1, is_post = 0;
  12011. const char *a, *method;
  12012. if (!form)
  12013. return 0;
  12014. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  12015. return 0;
  12016. method = br_find_attr(&doc, form, "method");
  12017. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  12018. is_post = 1;
  12019. a = br_find_attr(&doc, form, "action");
  12020. if (a && a[0]) {
  12021. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  12022. return 0;
  12023. } else {
  12024. s_copy(action, page_url, sizeof(action));
  12025. }
  12026. query[0] = '\0';
  12027. for (i = 0; i < doc.nnode; i++) {
  12028. struct br_node *nd = &doc.nodes[i];
  12029. struct form_state *fs;
  12030. const char *name;
  12031. const char *value = "";
  12032. if (nd->type != BR_NODE_ELEM || i == form ||
  12033. !form_descendant(i, form))
  12034. continue;
  12035. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  12036. nd->tag != BR_TAG_SELECT)
  12037. continue;
  12038. if (form_disabled(i))
  12039. continue;
  12040. name = br_find_attr(&doc, i, "name");
  12041. if (!name || !name[0])
  12042. continue;
  12043. fs = form_get(i, 1);
  12044. if (!fs)
  12045. continue;
  12046. if (nd->tag == BR_TAG_SELECT) {
  12047. char opt[64];
  12048. if (!form_option_text(i, fs->selected, opt,
  12049. sizeof(opt)))
  12050. s_copy(opt, "", sizeof(opt));
  12051. value = opt;
  12052. {
  12053. unsigned int c, oi = 0;
  12054. for (c = nd->first; c;
  12055. c = doc.nodes[c].next) {
  12056. if (doc.nodes[c].type != BR_NODE_ELEM ||
  12057. doc.nodes[c].tag != BR_TAG_OPTION)
  12058. continue;
  12059. if (oi == fs->selected) {
  12060. const char *v =
  12061. br_value(&doc, c);
  12062. if (v && v[0])
  12063. value = v;
  12064. break;
  12065. }
  12066. oi++;
  12067. }
  12068. }
  12069. } else if (nd->tag == BR_TAG_INPUT) {
  12070. int kind = form_kind_of(i);
  12071. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  12072. if (!fs->checked)
  12073. continue;
  12074. value = br_value(&doc, i);
  12075. if (!value || !value[0])
  12076. value = "on";
  12077. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  12078. kind == FORM_BUTTON) {
  12079. if (i != node)
  12080. continue;
  12081. value = fs->value;
  12082. } else {
  12083. value = fs->value;
  12084. }
  12085. } else {
  12086. value = fs->value;
  12087. }
  12088. form_add_param(query, &qn, sizeof(query), name, value, &first);
  12089. }
  12090. if (is_post) {
  12091. if (action[0] == '/') {
  12092. set_status("POST forms need an HTTP action URL", 1, 4000);
  12093. ngui_invalidate(&ui);
  12094. return 0;
  12095. }
  12096. if (qn >= sizeof(pending_post))
  12097. qn = sizeof(pending_post) - 1;
  12098. if (qn)
  12099. memcpy(pending_post, query, qn);
  12100. pending_post[qn] = '\0';
  12101. pending_post_len = qn;
  12102. pending_post_is = 1;
  12103. } else {
  12104. pending_post_len = 0;
  12105. pending_post_is = 0;
  12106. if (qn) {
  12107. unsigned int an = s_len(action);
  12108. if (an + qn + 2 < sizeof(action)) {
  12109. action[an++] = strchr(action, '?') ? '&' : '?';
  12110. action[an] = '\0';
  12111. s_copy(action + an, query,
  12112. sizeof(action) - an);
  12113. }
  12114. }
  12115. }
  12116. s_copy(pending_url, action, sizeof(pending_url));
  12117. pending_action |= ACT_NAV;
  12118. cancel_fetch = 1;
  12119. ngui_invalidate(&ui);
  12120. return 1;
  12121. }
  12122. static void form_reset_event(unsigned int form)
  12123. {
  12124. if (form && !js_browser_event(form, "reset", 1, 1))
  12125. return;
  12126. if (form)
  12127. form_reset_form(form);
  12128. else
  12129. form_reset_state();
  12130. form_dirty = 0;
  12131. layout_valid = 0;
  12132. ngui_invalidate(&ui);
  12133. }
  12134. static void form_blur(void)
  12135. {
  12136. unsigned int node = form_focus;
  12137. form_focus = 0;
  12138. if (node && form_dirty) {
  12139. form_dirty = 0;
  12140. js_browser_event(node, "change", 1, 0);
  12141. }
  12142. }
  12143. static void form_click(unsigned int node)
  12144. {
  12145. struct form_state *fs;
  12146. int kind, changed = 0;
  12147. if (!form_is_control(node) || form_disabled(node))
  12148. return;
  12149. if (form_focus != node)
  12150. form_blur();
  12151. fs = form_get(node, 1);
  12152. if (!fs)
  12153. return;
  12154. kind = form_kind_of(node);
  12155. /* Focus moves on the press, before `click` is dispatched: a page
  12156. * that cancels the click (a framework's root listener) suppresses
  12157. * the activation behaviour below, never the focus (as in other
  12158. * browsers, where focus follows mousedown). */
  12159. form_focus = node;
  12160. form_dirty = 0;
  12161. if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  12162. kind == FORM_TEXTAREA)
  12163. fs->caret = fs->len;
  12164. layout_valid = 0;
  12165. ngui_invalidate(&ui);
  12166. if (!js_browser_event(node, "click", 1, 1))
  12167. return;
  12168. fs = form_get(node, 0); /* the handler may have changed the DOM */
  12169. if (!fs)
  12170. return;
  12171. if (kind == FORM_CHECKBOX) {
  12172. fs->checked = !fs->checked;
  12173. changed = 1;
  12174. } else if (kind == FORM_RADIO) {
  12175. const char *name = br_find_attr(&doc, node, "name");
  12176. unsigned int i;
  12177. fs->checked = 1;
  12178. changed = 1;
  12179. if (name) {
  12180. for (i = 0; i < FORM_MAX; i++) {
  12181. struct form_state *o = &form_states[i];
  12182. if (!o->used || o->node == node)
  12183. continue;
  12184. if (form_kind_of(o->node) == FORM_RADIO) {
  12185. const char *on = br_find_attr(&doc,
  12186. o->node,
  12187. "name");
  12188. if (on && s_eq(on, name))
  12189. o->checked = 0;
  12190. }
  12191. }
  12192. }
  12193. } else if (kind == FORM_SELECT) {
  12194. unsigned int n = form_option_count(node);
  12195. if (n) {
  12196. fs->selected = (unsigned char)
  12197. ((fs->selected + 1) % n);
  12198. changed = 1;
  12199. }
  12200. } else if (kind == FORM_SUBMIT) {
  12201. form_submit_form(node, 1);
  12202. return;
  12203. } else if (kind == FORM_RESET) {
  12204. form_reset_event(form_ancestor(node));
  12205. return;
  12206. }
  12207. if (changed) {
  12208. js_browser_event(node, "input", 1, 0);
  12209. js_browser_event(node, "change", 1, 0);
  12210. }
  12211. layout_valid = 0;
  12212. ngui_invalidate(&ui);
  12213. }
  12214. static void form_focus_next(void)
  12215. {
  12216. unsigned int start = form_focus ? form_focus + 1 : 0;
  12217. unsigned int i;
  12218. form_blur();
  12219. for (i = start; i < doc.nnode; i++) {
  12220. if (form_is_control(i) && !form_disabled(i) &&
  12221. !s_eq(br_type(&doc, i), "hidden")) {
  12222. form_focus = i;
  12223. layout_valid = 0;
  12224. ngui_invalidate(&ui);
  12225. return;
  12226. }
  12227. }
  12228. form_focus = 0;
  12229. layout_valid = 0;
  12230. ngui_invalidate(&ui);
  12231. }
  12232. static void form_key(int k)
  12233. {
  12234. struct form_state *fs;
  12235. int kind;
  12236. if (!form_focus || form_focus >= doc.nnode) {
  12237. form_focus = 0;
  12238. return;
  12239. }
  12240. fs = form_get(form_focus, 1);
  12241. if (!fs || form_disabled(form_focus))
  12242. return;
  12243. kind = form_kind_of(form_focus);
  12244. if (kind == FORM_SELECT) {
  12245. unsigned int n = form_option_count(form_focus);
  12246. int changed = 0;
  12247. if (k == NGUI_KEY_UP && n) {
  12248. fs->selected = (unsigned char)
  12249. ((fs->selected + n - 1) % n);
  12250. changed = 1;
  12251. } else if (k == NGUI_KEY_DOWN && n) {
  12252. fs->selected = (unsigned char)
  12253. ((fs->selected + 1) % n);
  12254. changed = 1;
  12255. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  12256. form_blur();
  12257. layout_valid = 0;
  12258. ngui_invalidate(&ui);
  12259. return;
  12260. } else {
  12261. return;
  12262. }
  12263. if (changed) {
  12264. js_browser_event(form_focus, "input", 1, 0);
  12265. js_browser_event(form_focus, "change", 1, 0);
  12266. }
  12267. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  12268. if (k == ' ') {
  12269. form_click(form_focus);
  12270. return;
  12271. }
  12272. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  12273. form_blur();
  12274. layout_valid = 0;
  12275. ngui_invalidate(&ui);
  12276. }
  12277. return;
  12278. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  12279. kind == FORM_RESET) {
  12280. if (k == NGUI_KEY_ESC) {
  12281. form_blur();
  12282. layout_valid = 0;
  12283. ngui_invalidate(&ui);
  12284. } else if (k == '\r' || k == '\n' || k == ' ') {
  12285. form_click(form_focus);
  12286. }
  12287. return;
  12288. } else if (k == NGUI_KEY_TAB) {
  12289. form_focus_next();
  12290. return;
  12291. } else if (k == NGUI_KEY_ESC) {
  12292. form_blur();
  12293. layout_valid = 0;
  12294. ngui_invalidate(&ui);
  12295. return;
  12296. } else if (k == '\r' || k == '\n') {
  12297. unsigned int node = form_focus;
  12298. form_blur();
  12299. if (form_ancestor(node))
  12300. form_submit_form(node, 1);
  12301. layout_valid = 0;
  12302. ngui_invalidate(&ui);
  12303. return;
  12304. } else if (k == NGUI_KEY_BACKSPACE) {
  12305. if (fs->caret) {
  12306. unsigned int i = --fs->caret;
  12307. for (; i < fs->len; i++)
  12308. fs->value[i] = fs->value[i + 1];
  12309. if (fs->len)
  12310. fs->len--;
  12311. form_dirty = 1;
  12312. js_browser_event(form_focus, "input", 1, 0);
  12313. }
  12314. } else if (k == NGUI_KEY_DELETE) {
  12315. if (fs->caret < fs->len) {
  12316. unsigned int i;
  12317. for (i = fs->caret; i < fs->len; i++)
  12318. fs->value[i] = fs->value[i + 1];
  12319. fs->len--;
  12320. form_dirty = 1;
  12321. js_browser_event(form_focus, "input", 1, 0);
  12322. }
  12323. } else if (k == NGUI_KEY_LEFT) {
  12324. if (fs->caret)
  12325. fs->caret--;
  12326. } else if (k == NGUI_KEY_RIGHT) {
  12327. if (fs->caret < fs->len)
  12328. fs->caret++;
  12329. } else if (k == NGUI_KEY_HOME) {
  12330. fs->caret = 0;
  12331. } else if (k == NGUI_KEY_END) {
  12332. fs->caret = fs->len;
  12333. } else if (k >= 32 && k < 127) {
  12334. if (fs->len < FORM_VALUE_MAX) {
  12335. unsigned int i;
  12336. for (i = fs->len; i > fs->caret; i--)
  12337. fs->value[i] = fs->value[i - 1];
  12338. fs->value[fs->caret++] = (char)k;
  12339. fs->len++;
  12340. form_dirty = 1;
  12341. js_browser_event(form_focus, "input", 1, 0);
  12342. }
  12343. } else {
  12344. return;
  12345. }
  12346. fs->value[fs->len] = '\0';
  12347. layout_valid = 0;
  12348. ngui_invalidate(&ui);
  12349. }
  12350. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  12351. * a same-document navigation: update the URL and fire hashchange. Returns
  12352. * 1 when handled. */
  12353. static int link_fragment_nav(unsigned int node)
  12354. {
  12355. const char *href = br_href(&doc, node);
  12356. char url[BR_URL_MAX];
  12357. unsigned int n = 0;
  12358. if (!href || !href[0] || !js_browser_active())
  12359. return 0;
  12360. if (href[0] == '#') {
  12361. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  12362. url[n] = page_url[n];
  12363. n++;
  12364. }
  12365. url[n] = '\0';
  12366. s_append(url, &n, href, sizeof(url));
  12367. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  12368. return 0;
  12369. }
  12370. if (!same_doc_fragment(url))
  12371. return href[0] == '#';
  12372. page_set_fragment(url, 1);
  12373. js_browser_hashchange();
  12374. return 1;
  12375. }
  12376. /* The innermost laid-out box under a screen point: the smallest valid box
  12377. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  12378. * Used to deliver clicks to elements that are neither links nor controls
  12379. * (a Vue <div role="button">, a card with a click listener). */
  12380. static unsigned int find_box_hit(int x, int y)
  12381. {
  12382. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  12383. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  12384. const struct br_layout_box *b = &layout_boxes[i];
  12385. unsigned int area;
  12386. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  12387. x < b->x || y < b->y || x >= b->x + b->w ||
  12388. y >= b->y + b->h)
  12389. continue;
  12390. area = (unsigned int)b->w * (unsigned int)b->h;
  12391. if (area <= best_area) {
  12392. best = i;
  12393. best_area = area;
  12394. }
  12395. }
  12396. return best;
  12397. }
  12398. static void handle_page_click(unsigned int *action)
  12399. {
  12400. int node;
  12401. char url[BR_URL_MAX];
  12402. if (!ui.pressed)
  12403. return;
  12404. if (ui.press_x < page_rect.x ||
  12405. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  12406. ui.press_y < page_rect.y ||
  12407. ui.press_y >= page_rect.y + page_rect.h)
  12408. return;
  12409. node = find_hit(ui.press_x, ui.press_y);
  12410. if (!node) {
  12411. unsigned int box;
  12412. if (!js_browser_active())
  12413. return;
  12414. box = find_box_hit(ui.press_x, ui.press_y);
  12415. if (box) {
  12416. form_blur();
  12417. js_browser_event(box, "click", 1, 1);
  12418. }
  12419. return;
  12420. }
  12421. if (form_is_control((unsigned int)node)) {
  12422. form_click((unsigned int)node);
  12423. return;
  12424. }
  12425. form_blur();
  12426. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  12427. return;
  12428. if (link_fragment_nav((unsigned int)node))
  12429. return;
  12430. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  12431. sizeof(url)) != 0)
  12432. return;
  12433. s_copy(click_url, url, sizeof(click_url));
  12434. *action |= ACT_NAV;
  12435. }
  12436. void _start(const char *arg)
  12437. {
  12438. struct win_info wi;
  12439. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  12440. u_win_create(960, 640, "Browser", &wi) != 0 &&
  12441. u_win_create(780, 540, "Browser", &wi) != 0) {
  12442. u_puts("browser: no graphics window\n");
  12443. u_exit(1);
  12444. }
  12445. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  12446. url_in.placeholder = "http://...";
  12447. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  12448. ui.theme.accent);
  12449. br_set_viewport(wi.width);
  12450. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  12451. s_copy(cwd, "/", sizeof(cwd));
  12452. heap_clear();
  12453. origin_cache_load();
  12454. css_cache_init();
  12455. script_cache_init();
  12456. persist_restore();
  12457. hist_load();
  12458. page_scroll.offset = 0;
  12459. page_scroll.content_h = 0;
  12460. if (arg && arg[0]) {
  12461. navigate(arg, 1);
  12462. } else {
  12463. load_home(1);
  12464. /* Start ready to type: keep the home page, but leave the address
  12465. * bar empty instead of showing "about:home". */
  12466. ngui_input_set(&url_in, "");
  12467. ngui_set_focus(&ui, ID_URL);
  12468. }
  12469. for (;;) {
  12470. unsigned int action = 0;
  12471. unsigned int now;
  12472. click_url[0] = '\0';
  12473. if (pending_action) {
  12474. action |= pending_action & ACT_WAIT_NAV;
  12475. if (pending_url[0])
  12476. s_copy(click_url, pending_url, sizeof(click_url));
  12477. pending_action = 0;
  12478. pending_url[0] = '\0';
  12479. cancel_fetch = 0;
  12480. } else if (preload_active) {
  12481. if (preload_wait)
  12482. preload_wait = 0;
  12483. else
  12484. preload_step();
  12485. } else if ((preload_pending &&
  12486. page_scroll.offset != preload_scroll) ||
  12487. (preload_rescan && layout_valid)) {
  12488. preload_scroll = page_scroll.offset;
  12489. preload_rescan = 0;
  12490. preload_pending = 0;
  12491. preload_node = 0;
  12492. preload_active = 1;
  12493. }
  12494. js_browser_tick();
  12495. if (resize_pending && !pending_action) {
  12496. resize_pending = 0;
  12497. resize_sent_w = layout_right - layout_left;
  12498. js_browser_window_event("resize");
  12499. }
  12500. persist_tick();
  12501. if (pending_action)
  12502. continue;
  12503. now = u_ticks_ms();
  12504. if (status_until && (int)(now - status_until) >= 0) {
  12505. status_text[0] = '\0';
  12506. status_until = 0;
  12507. status_error = 0;
  12508. ngui_invalidate(&ui);
  12509. }
  12510. if (!ngui_begin(&ui)) {
  12511. /* A queued navigation (e.g. Enter in the URL bar during
  12512. * a slow fetch) must be handled even when this frame
  12513. * needs no redraw. */
  12514. if (!action) {
  12515. fetch_workers_stop_if_unfocused();
  12516. u_sleep_ms(10);
  12517. continue;
  12518. }
  12519. } else {
  12520. draw(&action);
  12521. handle_keys(&action);
  12522. handle_page_click(&action);
  12523. ngui_end(&ui);
  12524. }
  12525. if (action & ACT_NAV) {
  12526. if (click_url[0]) {
  12527. navigate(click_url, 1);
  12528. click_url[0] = '\0';
  12529. } else {
  12530. navigate(url_in.text, 1);
  12531. }
  12532. }
  12533. if (action & ACT_BACK) {
  12534. if (hist_pos > 0) {
  12535. hist_pos--;
  12536. if (same_doc_fragment(history[hist_pos])) {
  12537. page_set_fragment(history[hist_pos], 0);
  12538. js_browser_hashchange();
  12539. } else {
  12540. navigate(history[hist_pos], 0);
  12541. }
  12542. }
  12543. }
  12544. if (action & ACT_FORWARD) {
  12545. if (hist_pos + 1 < hist_len) {
  12546. hist_pos++;
  12547. if (same_doc_fragment(history[hist_pos])) {
  12548. page_set_fragment(history[hist_pos], 0);
  12549. js_browser_hashchange();
  12550. } else {
  12551. navigate(history[hist_pos], 0);
  12552. }
  12553. }
  12554. }
  12555. if (action & ACT_RELOAD) {
  12556. if (s_eq(page_url, "about:home"))
  12557. load_home(0);
  12558. else
  12559. navigate(page_url, 0);
  12560. }
  12561. if (action & ACT_HOME)
  12562. load_home(1);
  12563. if (action & ACT_CLOSE)
  12564. quit = 1;
  12565. if (quit)
  12566. break;
  12567. if (pending_action)
  12568. continue;
  12569. fetch_workers_stop_if_unfocused();
  12570. u_sleep_ms(10);
  12571. }
  12572. fetch_workers_stop_all();
  12573. u_win_close();
  12574. u_exit(0);
  12575. }