browser.c 340 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893
  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 + 4 - 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. };
  233. struct lay {
  234. int draw;
  235. struct ngui *ui;
  236. int left, right;
  237. int y;
  238. int line_x, line_y, line_h;
  239. int line_left, line_right;
  240. int parent_top;
  241. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  242. int cb_h; /* definite content height of the containing block for
  243. * percentage heights; 0 = indefinite (auto) */
  244. int run_x;
  245. int align;
  246. int depth;
  247. int space_pending;
  248. unsigned char float_active;
  249. int float_left, float_right, float_bottom;
  250. struct lay_run runs[96];
  251. int nruns;
  252. };
  253. struct hit {
  254. int x, y, w, h;
  255. unsigned short node;
  256. };
  257. /* Live form state; the DOM attributes stay the initial/default value. */
  258. #define FORM_MAX 64
  259. #define FORM_VALUE_MAX 63
  260. enum {
  261. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  262. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  263. };
  264. struct form_state {
  265. unsigned int node;
  266. char value[FORM_VALUE_MAX + 1];
  267. unsigned char len, caret, checked, selected, used;
  268. };
  269. static struct form_state form_states[FORM_MAX];
  270. static unsigned int form_focus;
  271. static unsigned int form_dirty;
  272. static int form_descendant(unsigned int node, unsigned int form);
  273. static int form_submit_form(unsigned int node, int fire_event);
  274. static int link_fragment_nav(unsigned int node);
  275. static void history_push(const char *url);
  276. static void form_reset_event(unsigned int form);
  277. static unsigned int s_len(const char *s);
  278. static int s_eq(const char *a, const char *b);
  279. static void form_key(int k);
  280. static void form_click(unsigned int node);
  281. static void style_for_node(unsigned int node, struct br_style *out);
  282. static int form_author_styled(const struct br_style *st);
  283. static int css_radius(const struct br_style *st, int corner, int w, int h);
  284. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  285. const struct br_style *st, int focused);
  286. static int form_disabled(unsigned int node)
  287. {
  288. struct br_node *n = &doc.nodes[node];
  289. if (n->attr_flags & BR_ATTR_DISABLED)
  290. return 1;
  291. return br_find_attr(&doc, node, "disabled") != 0;
  292. }
  293. static int form_kind_of(unsigned int node)
  294. {
  295. const char *type = br_type(&doc, node);
  296. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  297. return FORM_TEXTAREA;
  298. if (doc.nodes[node].tag == BR_TAG_SELECT)
  299. return FORM_SELECT;
  300. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  301. if (s_eq(type, "reset"))
  302. return FORM_RESET;
  303. if (s_eq(type, "button"))
  304. return FORM_BUTTON;
  305. return FORM_SUBMIT;
  306. }
  307. if (s_eq(type, "password"))
  308. return FORM_PASSWORD;
  309. if (s_eq(type, "checkbox"))
  310. return FORM_CHECKBOX;
  311. if (s_eq(type, "radio"))
  312. return FORM_RADIO;
  313. if (s_eq(type, "submit"))
  314. return FORM_SUBMIT;
  315. if (s_eq(type, "reset"))
  316. return FORM_RESET;
  317. if (s_eq(type, "button"))
  318. return FORM_BUTTON;
  319. return FORM_TEXT;
  320. }
  321. static unsigned int form_option_count(unsigned int node)
  322. {
  323. unsigned int c, n = 0;
  324. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  325. if (doc.nodes[c].type == BR_NODE_ELEM &&
  326. doc.nodes[c].tag == BR_TAG_OPTION)
  327. n++;
  328. return n;
  329. }
  330. static unsigned int form_option_selected(unsigned int node)
  331. {
  332. unsigned int c, i = 0;
  333. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  334. if (doc.nodes[c].type != BR_NODE_ELEM ||
  335. doc.nodes[c].tag != BR_TAG_OPTION)
  336. continue;
  337. if (br_find_attr(&doc, c, "selected"))
  338. return i;
  339. i++;
  340. }
  341. return 0;
  342. }
  343. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  344. char *out, unsigned int cap)
  345. {
  346. unsigned int c, i = 0;
  347. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  348. if (doc.nodes[c].type != BR_NODE_ELEM ||
  349. doc.nodes[c].tag != BR_TAG_OPTION)
  350. continue;
  351. if (i == idx)
  352. return br_text_content(&doc, c, out, cap);
  353. i++;
  354. }
  355. return 0;
  356. }
  357. static struct form_state *form_get(unsigned int node, int create)
  358. {
  359. struct form_state *slot = 0;
  360. unsigned int i;
  361. for (i = 0; i < FORM_MAX; i++) {
  362. if (form_states[i].used) {
  363. if (form_states[i].node == node)
  364. return &form_states[i];
  365. } else if (!slot) {
  366. slot = &form_states[i];
  367. }
  368. }
  369. if (!create || !slot)
  370. return 0;
  371. slot->node = node;
  372. slot->len = 0;
  373. slot->caret = 0;
  374. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  375. slot->selected = form_option_selected(node);
  376. slot->used = 1;
  377. {
  378. unsigned int n = 0;
  379. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  380. n = br_text_content(&doc, node, slot->value,
  381. FORM_VALUE_MAX + 1);
  382. } else {
  383. const char *v = br_value(&doc, node);
  384. if (v) {
  385. n = s_len(v);
  386. if (n > FORM_VALUE_MAX)
  387. n = FORM_VALUE_MAX;
  388. for (unsigned int j = 0; j < n; j++)
  389. slot->value[j] = v[j];
  390. }
  391. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  392. n = br_text_content(&doc, node, slot->value,
  393. FORM_VALUE_MAX + 1);
  394. }
  395. if (n > FORM_VALUE_MAX)
  396. n = FORM_VALUE_MAX;
  397. slot->value[n] = '\0';
  398. slot->len = (unsigned char)n;
  399. slot->caret = (unsigned char)n;
  400. }
  401. return slot;
  402. }
  403. static void form_reset_state(void)
  404. {
  405. unsigned int i;
  406. for (i = 0; i < FORM_MAX; i++)
  407. form_states[i].used = 0;
  408. form_focus = 0;
  409. }
  410. /* A <button> with element content (an icon <svg>/<img>, a <span> label)
  411. * is laid out like a normal element so that content shows; only a text or
  412. * empty button is drawn as a native control. Clicks still reach it
  413. * through the box hit test. */
  414. static int button_has_elements(unsigned int node)
  415. {
  416. unsigned int c;
  417. if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
  418. return 0;
  419. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  420. if (doc.nodes[c].type == BR_NODE_ELEM)
  421. return 1;
  422. return 0;
  423. }
  424. static int form_is_control(unsigned int node)
  425. {
  426. unsigned int tag;
  427. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  428. return 0;
  429. tag = doc.nodes[node].tag;
  430. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  431. tag == BR_TAG_SELECT ||
  432. (tag == BR_TAG_BUTTON && !button_has_elements(node));
  433. }
  434. #define HIT_MAX 96
  435. static struct hit hits[HIT_MAX];
  436. static int nhits;
  437. static unsigned short block_h[BR_MAX_NODES];
  438. /* Measure-pass top of each block, in the same document coordinates as
  439. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  440. * paint, so it cannot drive the lazy background loader). */
  441. static unsigned short block_top[BR_MAX_NODES];
  442. static char li_marker[BR_MAX_NODES][12];
  443. /* one connection object; the browser fetches one resource at a time */
  444. /* ---- tiny strings ---- */
  445. static unsigned int s_len(const char *s)
  446. {
  447. unsigned int n = 0;
  448. while (s && s[n])
  449. n++;
  450. return n;
  451. }
  452. static void s_copy(char *d, const char *s, unsigned int cap)
  453. {
  454. unsigned int i = 0;
  455. if (!cap)
  456. return;
  457. while (s && s[i] && i + 1 < cap) {
  458. d[i] = s[i];
  459. i++;
  460. }
  461. d[i] = '\0';
  462. }
  463. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  464. {
  465. while (s && *s && *n + 1 < cap)
  466. d[(*n)++] = *s++;
  467. d[*n] = '\0';
  468. }
  469. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  470. unsigned int cap)
  471. {
  472. char tmp[12];
  473. unsigned int i = 0, j;
  474. do {
  475. tmp[i++] = (char)('0' + v % 10);
  476. v /= 10;
  477. } while (v && i < sizeof(tmp));
  478. for (j = 0; j < i && *n + 1 < cap; j++)
  479. d[(*n)++] = tmp[i - 1 - j];
  480. d[*n] = '\0';
  481. }
  482. static int s_eq(const char *a, const char *b)
  483. {
  484. while (*a && *b) {
  485. if (*a != *b)
  486. return 0;
  487. a++;
  488. b++;
  489. }
  490. return *a == *b;
  491. }
  492. static int starts_with(const char *s, const char *p)
  493. {
  494. unsigned int i = 0;
  495. while (p[i]) {
  496. if (s[i] != p[i])
  497. return 0;
  498. i++;
  499. }
  500. return 1;
  501. }
  502. static int contains_ci(const char *s, const char *p)
  503. {
  504. unsigned int i, j;
  505. for (i = 0; s[i]; i++) {
  506. for (j = 0; p[j]; j++) {
  507. char a = s[i + j];
  508. if (a >= 'A' && a <= 'Z')
  509. a = (char)(a - 'A' + 'a');
  510. if (a != p[j])
  511. break;
  512. }
  513. if (!p[j])
  514. return 1;
  515. }
  516. return 0;
  517. }
  518. static char *trim(char *s)
  519. {
  520. unsigned int n;
  521. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  522. s++;
  523. n = s_len(s);
  524. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  525. s[n - 1] == '\r' || s[n - 1] == '\n'))
  526. s[--n] = '\0';
  527. return s;
  528. }
  529. /* ---- per-process heap ---- */
  530. static int heap_start(void)
  531. {
  532. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  533. if (!image_io_buf)
  534. return -1;
  535. page_backbuf = (unsigned short *)malloc(
  536. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  537. pagebuf_w = page_backbuf ? ui.w : 0;
  538. pagebuf_h = page_backbuf ? ui.h : 0;
  539. page_cache_valid = 0;
  540. return 0;
  541. }
  542. static void heap_clear(void)
  543. {
  544. memset(font_faces, 0, sizeof(font_faces));
  545. ngui_font_detach(&ui);
  546. svg_cache_clear();
  547. decode_arena = 0; /* lives in the page heap too */
  548. decode_arena_size = 0;
  549. heap_reset();
  550. /* The document arenas live in that heap; drop the stale pointers so
  551. * the next br_parse_plain() allocates fresh ones. */
  552. doc.nodes = 0;
  553. doc.text = 0;
  554. doc.attrs = 0;
  555. image_io_buf = 0;
  556. page_backbuf = 0;
  557. pagebuf_w = pagebuf_h = 0;
  558. page_cache_valid = 0;
  559. }
  560. static void browser_rules_alloc(void)
  561. {
  562. struct br_rule *rules;
  563. rules = (struct br_rule *)malloc(
  564. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  565. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  566. }
  567. /* ---- status ---- */
  568. static void set_status(const char *s, int err, unsigned int ttl_ms)
  569. {
  570. s_copy(status_text, s, sizeof(status_text));
  571. status_error = err;
  572. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  573. ngui_invalidate(&ui);
  574. }
  575. /* Update the status text without forcing a frame; the throttled image
  576. * repaint picks it up. Starting one helper per image used to invalidate the
  577. * whole page before every decode. */
  578. static void set_status_quiet(const char *s)
  579. {
  580. s_copy(status_text, s, sizeof(status_text));
  581. status_error = 0;
  582. status_until = 0;
  583. }
  584. /* ---- JavaScript ---- */
  585. static int resolve_link(const char *base, const char *href, char *out,
  586. unsigned int cap);
  587. static char js_last_status[BR_STATUS_MAX];
  588. static int js_last_error;
  589. static void js_host_status(const char *msg, int error)
  590. {
  591. s_copy(js_last_status, msg, sizeof(js_last_status));
  592. js_last_error = error;
  593. set_status(msg, error, 6000);
  594. }
  595. static void js_host_report(const char *msg)
  596. {
  597. u_puts("[js] ");
  598. u_puts(msg);
  599. u_putc('\n');
  600. s_copy(js_last_status, msg, sizeof(js_last_status));
  601. js_last_error = 1;
  602. set_status(msg, 1, 8000);
  603. }
  604. static void js_host_navigate(const char *url)
  605. {
  606. char resolved[BR_URL_MAX];
  607. if (!url || !url[0])
  608. return;
  609. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  610. return;
  611. s_copy(pending_url, resolved, sizeof(pending_url));
  612. pending_action |= ACT_NAV;
  613. cancel_fetch = 1;
  614. }
  615. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  616. * back/forward between fragments): the page URL, address bar and history
  617. * follow, nothing is reloaded. `push` adds a history entry. */
  618. static int page_set_fragment(const char *url, int push)
  619. {
  620. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  621. return -1;
  622. s_copy(page_url, url, sizeof(page_url));
  623. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  624. url_in.len = s_len(url_in.text);
  625. url_in.cursor = url_in.len;
  626. url_in.scroll = 0;
  627. if (push)
  628. history_push(page_url);
  629. ngui_invalidate(&ui);
  630. return 0;
  631. }
  632. static int js_host_set_hash(const char *url)
  633. {
  634. return page_set_fragment(url, 1);
  635. }
  636. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  637. * the page, so a hash router can react). */
  638. static int same_doc_fragment(const char *url)
  639. {
  640. unsigned int a = 0, b = 0;
  641. if (!js_browser_active() || !url)
  642. return 0;
  643. while (url[a] && url[a] != '#')
  644. a++;
  645. while (page_url[b] && page_url[b] != '#')
  646. b++;
  647. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  648. !s_eq(url, page_url);
  649. }
  650. static void js_host_changed(void)
  651. {
  652. /* Class/style/attribute mutations change computed styles, not just the
  653. * text: drop the per-node style cache before the next layout. */
  654. br_reset_styles(&doc);
  655. layout_valid = 0;
  656. /* Script-built content (Angular's ng-repeat cards) brings new images
  657. * and inline background styles: rescan once the main loop is idle. */
  658. preload_rescan = 1;
  659. ngui_invalidate(&ui);
  660. }
  661. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  662. {
  663. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  664. return 0;
  665. *x = layout_boxes[node].x - page_rect.x;
  666. *y = layout_boxes[node].y - page_rect.y;
  667. *w = layout_boxes[node].w;
  668. *h = layout_boxes[node].h;
  669. return 1;
  670. }
  671. static void form_copy_out(const char *s, char *buf, int cap)
  672. {
  673. int i = 0;
  674. if (!buf || cap <= 0)
  675. return;
  676. while (s && s[i] && i + 1 < cap) {
  677. buf[i] = s[i];
  678. i++;
  679. }
  680. buf[i] = '\0';
  681. }
  682. static int js_host_form_value(unsigned int node, char *buf, int cap)
  683. {
  684. struct form_state *fs;
  685. int kind;
  686. if (!form_is_control(node))
  687. return 0;
  688. kind = form_kind_of(node);
  689. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  690. return 0;
  691. if (kind == FORM_SELECT) {
  692. char opt[64] = "";
  693. unsigned int c, i = 0;
  694. fs = form_get(node, 1);
  695. if (!fs)
  696. return 0;
  697. form_option_text(node, fs->selected, opt, sizeof(opt));
  698. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  699. if (doc.nodes[c].type != BR_NODE_ELEM ||
  700. doc.nodes[c].tag != BR_TAG_OPTION)
  701. continue;
  702. if (i == fs->selected) {
  703. const char *v = br_value(&doc, c);
  704. if (v && v[0])
  705. form_copy_out(v, buf, cap);
  706. else
  707. form_copy_out(opt, buf, cap);
  708. return 1;
  709. }
  710. i++;
  711. }
  712. form_copy_out(opt, buf, cap);
  713. return 1;
  714. }
  715. fs = form_get(node, 1);
  716. if (!fs)
  717. return 0;
  718. form_copy_out(fs->value, buf, cap);
  719. return 1;
  720. }
  721. static int js_host_form_checked(unsigned int node)
  722. {
  723. struct form_state *fs;
  724. int kind;
  725. if (!form_is_control(node))
  726. return -1;
  727. kind = form_kind_of(node);
  728. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  729. return -1;
  730. fs = form_get(node, 1);
  731. return fs ? fs->checked : 0;
  732. }
  733. static int js_host_form_selected(unsigned int node)
  734. {
  735. struct form_state *fs;
  736. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  737. return -1;
  738. fs = form_get(node, 1);
  739. return fs ? fs->selected : 0;
  740. }
  741. static int js_host_form_set_value(unsigned int node, const char *value)
  742. {
  743. struct form_state *fs;
  744. unsigned int n;
  745. if (!form_is_control(node))
  746. return 0;
  747. fs = form_get(node, 1);
  748. if (!fs)
  749. return 0;
  750. n = s_len(value ? value : "");
  751. if (n > FORM_VALUE_MAX)
  752. n = FORM_VALUE_MAX;
  753. for (unsigned int i = 0; i < n; i++)
  754. fs->value[i] = value[i];
  755. fs->value[n] = '\0';
  756. fs->len = (unsigned char)n;
  757. fs->caret = (unsigned char)n;
  758. layout_valid = 0;
  759. ngui_invalidate(&ui);
  760. return 1;
  761. }
  762. static int js_host_form_set_checked(unsigned int node, int checked)
  763. {
  764. struct form_state *fs;
  765. int kind;
  766. if (!form_is_control(node))
  767. return 0;
  768. kind = form_kind_of(node);
  769. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  770. return 0;
  771. fs = form_get(node, 1);
  772. if (!fs)
  773. return 0;
  774. fs->checked = (unsigned char)(checked != 0);
  775. layout_valid = 0;
  776. ngui_invalidate(&ui);
  777. return 1;
  778. }
  779. static int js_host_form_set_selected(unsigned int node, int index)
  780. {
  781. struct form_state *fs;
  782. unsigned int n;
  783. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  784. return 0;
  785. fs = form_get(node, 1);
  786. if (!fs)
  787. return 0;
  788. n = form_option_count(node);
  789. if (index < 0)
  790. index = 0;
  791. if (n && (unsigned int)index >= n)
  792. index = (int)n - 1;
  793. fs->selected = (unsigned char)index;
  794. layout_valid = 0;
  795. ngui_invalidate(&ui);
  796. return 1;
  797. }
  798. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  799. {
  800. unsigned int i;
  801. int n = 0;
  802. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  803. doc.nodes[form].tag != BR_TAG_FORM)
  804. return 0;
  805. for (i = 0; i < doc.nnode && n < cap; i++) {
  806. struct br_node *nd = &doc.nodes[i];
  807. if (i == form || nd->type != BR_NODE_ELEM)
  808. continue;
  809. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  810. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  811. continue;
  812. if (!form_descendant(i, form))
  813. continue;
  814. out[n++] = i;
  815. }
  816. return n;
  817. }
  818. static int js_host_form_submit(unsigned int form)
  819. {
  820. form_submit_form(form, 0);
  821. return 1;
  822. }
  823. static int js_host_form_reset(unsigned int form)
  824. {
  825. form_reset_event(form);
  826. return 1;
  827. }
  828. static void css_computed_name(const char *p, char *out, int cap)
  829. {
  830. int n = 0;
  831. for (; p && *p && n + 2 < cap; p++) {
  832. char c = *p;
  833. if (c >= 'A' && c <= 'Z') {
  834. out[n++] = '-';
  835. c = (char)(c - 'A' + 'a');
  836. } else if (c == '_') {
  837. c = '-';
  838. } else if (c >= 'a' && c <= 'z') {
  839. /* keep */
  840. }
  841. out[n++] = c;
  842. }
  843. out[n] = '\0';
  844. if (!strcmp(out, "css-float"))
  845. strcpy(out, "float");
  846. }
  847. static void css_rgb(unsigned short c, char *buf, int cap)
  848. {
  849. int r = ((c >> 11) & 31) * 255 / 31;
  850. int g = ((c >> 5) & 63) * 255 / 63;
  851. int b = (c & 31) * 255 / 31;
  852. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  853. }
  854. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  855. int font_px)
  856. {
  857. if (unit == 4) {
  858. snprintf(buf, cap, "auto");
  859. } else if (unit == 0) {
  860. snprintf(buf, cap, "%dpx", raw);
  861. } else if (unit == 1) {
  862. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  863. } else if (unit == 2) {
  864. /* Chrome's getComputedStyle() reports used pixel values. */
  865. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  866. } else if (unit == 3) {
  867. snprintf(buf, cap, "%dpx",
  868. (int)br_root_font_px() * raw / 100);
  869. } else {
  870. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  871. raw / 100, raw % 100, px);
  872. }
  873. }
  874. static int js_host_computed(unsigned int node, const char *property,
  875. char *buf, int cap)
  876. {
  877. struct br_style st;
  878. char name[40];
  879. /* Node 0 is a real element when the page starts with <html>. */
  880. if (!buf || cap <= 0 || node >= doc.nnode ||
  881. (node == 0 && doc.nodes[0].type != BR_NODE_ELEM))
  882. return 0;
  883. buf[0] = '\0';
  884. css_computed_name(property, name, sizeof(name));
  885. style_for_node(node, &st);
  886. if (!strcmp(name, "display")) {
  887. const char *v = "inline";
  888. if (st.display == BR_DISPLAY_BLOCK)
  889. v = "block";
  890. else if (st.display == BR_DISPLAY_NONE)
  891. v = "none";
  892. else if (st.display == BR_DISPLAY_FLEX)
  893. v = "flex";
  894. else if (st.display == BR_DISPLAY_GRID)
  895. v = "grid";
  896. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  897. v = "inline-block";
  898. snprintf(buf, cap, "%s", v);
  899. } else if (!strcmp(name, "position")) {
  900. static const char *pos[] = {
  901. "static", "absolute", "fixed", "relative", "sticky"
  902. };
  903. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  904. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  905. int is_w = name[0] == 'w';
  906. int kind = is_w ? st.width_kind : st.height_kind;
  907. int val = is_w ? st.width : st.height;
  908. if (kind == 3) {
  909. if (is_w)
  910. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  911. st.width_calc_pct / 100,
  912. st.width_calc_pct % 100,
  913. st.width_calc_px);
  914. else
  915. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  916. st.height_calc_pct / 100,
  917. st.height_calc_pct % 100,
  918. st.height_calc_px);
  919. } else if (kind == 1) {
  920. snprintf(buf, cap, "%dpx", val);
  921. } else if (kind == 2) {
  922. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  923. } else {
  924. snprintf(buf, cap, "auto");
  925. }
  926. } else if (!strcmp(name, "color") ||
  927. !strcmp(name, "background-color")) {
  928. if (!strcmp(name, "background-color") && !st.has_bg)
  929. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  930. else
  931. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  932. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  933. int is_fill = name[0] == 'f';
  934. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  935. if (mode == BR_PAINT_COLOR)
  936. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  937. else if (mode == BR_PAINT_CURRENT)
  938. css_rgb(st.color, buf, cap);
  939. else if (mode == BR_PAINT_UNSET && is_fill)
  940. snprintf(buf, cap, "rgb(0, 0, 0)");
  941. else if (mode == BR_PAINT_URL)
  942. snprintf(buf, cap, "url()");
  943. else
  944. snprintf(buf, cap, "none");
  945. } else if (!strcmp(name, "font-size")) {
  946. snprintf(buf, cap, "%dpx", st.font_px);
  947. } else if (!strcmp(name, "font-weight")) {
  948. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  949. } else if (!strcmp(name, "font-style")) {
  950. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  951. } else if (!strcmp(name, "font-family")) {
  952. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  953. br_font_face_family(st.font_face)[0])
  954. snprintf(buf, cap, "%s",
  955. br_font_face_family(st.font_face));
  956. else
  957. snprintf(buf, cap, "%s",
  958. st.mono ? "monospace" : "sans-serif");
  959. } else if (!strcmp(name, "text-align")) {
  960. static const char *al[] = { "left", "center", "right", "justify" };
  961. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  962. } else if (!strcmp(name, "float")) {
  963. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  964. st.float_left == 2 ? "right" : "none");
  965. } else if (!strcmp(name, "clear")) {
  966. static const char *cl[] = { "none", "left", "right", "both" };
  967. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  968. } else if (!strcmp(name, "opacity")) {
  969. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  970. } else if (!strcmp(name, "visibility")) {
  971. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  972. } else if (!strcmp(name, "overflow")) {
  973. snprintf(buf, cap, "%s",
  974. st.overflow_hidden ? "hidden" : "visible");
  975. } else if (!strcmp(name, "white-space")) {
  976. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  977. } else if (!strcmp(name, "text-transform")) {
  978. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  979. } else if (!strcmp(name, "box-sizing")) {
  980. snprintf(buf, cap, "%s",
  981. st.box_sizing ? "border-box" : "content-box");
  982. } else if (!strcmp(name, "line-height")) {
  983. if (st.line_h_px)
  984. snprintf(buf, cap, "%dpx", st.line_h_px);
  985. else if (st.line_h_pct)
  986. snprintf(buf, cap, "%d%%", st.line_h_pct);
  987. else
  988. snprintf(buf, cap, "normal");
  989. } else if (!strcmp(name, "z-index")) {
  990. if (st.z_set)
  991. snprintf(buf, cap, "%d", st.z_index);
  992. else
  993. snprintf(buf, cap, "auto");
  994. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  995. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  996. int set = name[0] == 't' ? st.top_set :
  997. name[0] == 'l' ? st.left_set :
  998. name[0] == 'r' ? st.right_set : st.bottom_set;
  999. int v = name[0] == 't' ? st.top :
  1000. name[0] == 'l' ? st.left :
  1001. name[0] == 'r' ? st.right : st.bottom;
  1002. if (set)
  1003. snprintf(buf, cap, "%dpx", v);
  1004. else
  1005. snprintf(buf, cap, "auto");
  1006. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  1007. !strcmp(name, "margin-bottom") ||
  1008. !strcmp(name, "margin-left") ||
  1009. !strcmp(name, "padding-top") ||
  1010. !strcmp(name, "padding-right") ||
  1011. !strcmp(name, "padding-bottom") ||
  1012. !strcmp(name, "padding-left")) {
  1013. int is_pad = name[0] == 'p';
  1014. int side = name[strlen(name) - 1] == 'p' ? 0 :
  1015. name[strlen(name) - 1] == 't' ? 1 :
  1016. name[strlen(name) - 1] == 'm' ? 2 : 3;
  1017. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  1018. if (!strcmp(name, "margin-right") ||
  1019. !strcmp(name, "padding-right"))
  1020. side = 1;
  1021. else if (!strcmp(name, "margin-bottom") ||
  1022. !strcmp(name, "padding-bottom"))
  1023. side = 2;
  1024. else if (!strcmp(name, "margin-left") ||
  1025. !strcmp(name, "padding-left"))
  1026. side = 3;
  1027. else
  1028. side = 0;
  1029. side += is_pad ? 4 : 0;
  1030. css_mp_value(buf, cap,
  1031. side == 0 ? st.mt : side == 1 ? st.mr :
  1032. side == 2 ? st.mb : side == 3 ? st.ml :
  1033. side == 4 ? st.pt : side == 5 ? st.pr :
  1034. side == 6 ? st.pb : st.pl,
  1035. st.mp_unit[side], st.mp_calc_px[side],
  1036. st.font_px);
  1037. } else if (!strcmp(name, "border-top-width") ||
  1038. !strcmp(name, "border-right-width") ||
  1039. !strcmp(name, "border-bottom-width") ||
  1040. !strcmp(name, "border-left-width")) {
  1041. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1042. name[7] == 'b' ? 2 : 3;
  1043. snprintf(buf, cap, "%dpx", st.border_w[side]);
  1044. } else if (!strcmp(name, "border-top-color") ||
  1045. !strcmp(name, "border-right-color") ||
  1046. !strcmp(name, "border-bottom-color") ||
  1047. !strcmp(name, "border-left-color")) {
  1048. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1049. name[7] == 'b' ? 2 : 3;
  1050. if (st.border_w[side] && !st.border_t[side])
  1051. css_rgb(st.border_c[side], buf, cap);
  1052. else
  1053. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1054. } else if (!strcmp(name, "background-image")) {
  1055. if (st.bg_image)
  1056. snprintf(buf, cap, "url(\"%s\")",
  1057. br_bg_image_url(st.bg_image - 1));
  1058. else
  1059. snprintf(buf, cap, "none");
  1060. } else if (!strcmp(name, "background-repeat")) {
  1061. static const char *rp[] = {
  1062. "repeat", "no-repeat", "repeat-x", "repeat-y"
  1063. };
  1064. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  1065. st.bg_repeat : 0]);
  1066. } else if (!strcmp(name, "background-position")) {
  1067. if (st.bg_pos_x_kind == 1)
  1068. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  1069. st.bg_pos_y);
  1070. else
  1071. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1072. st.bg_pos_y);
  1073. } else if (!strcmp(name, "background-size")) {
  1074. if (st.bg_size_kind == 3)
  1075. snprintf(buf, cap, "cover");
  1076. else if (st.bg_size_kind == 4)
  1077. snprintf(buf, cap, "contain");
  1078. else if (st.bg_size_kind == 1)
  1079. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1080. st.bg_size_h);
  1081. else if (st.bg_size_kind == 2)
  1082. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1083. st.bg_size_h);
  1084. else
  1085. snprintf(buf, cap, "auto");
  1086. } else if (!strcmp(name, "transform")) {
  1087. char tmp[128];
  1088. unsigned int n = 0;
  1089. if (!st.transform_set) {
  1090. snprintf(buf, cap, "none");
  1091. } else {
  1092. tmp[0] = '\0';
  1093. if (st.tx || st.ty) {
  1094. snprintf(tmp + n, sizeof(tmp) - n,
  1095. "translate(%dpx, %dpx)", st.tx, st.ty);
  1096. n = (unsigned int)strlen(tmp);
  1097. }
  1098. if (st.transform_scale) {
  1099. snprintf(tmp + n, sizeof(tmp) - n,
  1100. "%sscale(%d.%02d, %d.%02d)",
  1101. n ? " " : "", st.scale_x / 100,
  1102. st.scale_x % 100, st.scale_y / 100,
  1103. st.scale_y % 100);
  1104. n = (unsigned int)strlen(tmp);
  1105. if (st.rotate_x100) {
  1106. snprintf(tmp + n, sizeof(tmp) - n,
  1107. " rotate(%d.%02ddeg)",
  1108. st.rotate_x100 / 100,
  1109. st.rotate_x100 % 100);
  1110. }
  1111. } else if (st.rotate_x100) {
  1112. snprintf(tmp + n, sizeof(tmp) - n,
  1113. "%srotate(%d.%02ddeg)",
  1114. n ? " " : "", st.rotate_x100 / 100,
  1115. st.rotate_x100 % 100);
  1116. }
  1117. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1118. }
  1119. } else {
  1120. return 0;
  1121. }
  1122. return buf[0] != '\0';
  1123. }
  1124. static int js_host_click(unsigned int node)
  1125. {
  1126. char url[BR_URL_MAX];
  1127. const char *href;
  1128. if (node >= doc.nnode)
  1129. return 0;
  1130. if (form_is_control(node)) {
  1131. form_click(node); /* dispatches its own click event */
  1132. return 1;
  1133. }
  1134. /* element.click() fires a bubbling, cancelable click before the
  1135. * default action, like a real click (delegated list handlers). */
  1136. if (!js_browser_event(node, "click", 1, 1))
  1137. return 1;
  1138. if (link_fragment_nav(node))
  1139. return 1;
  1140. href = br_href(&doc, node);
  1141. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1142. return 0;
  1143. s_copy(pending_url, url, sizeof(pending_url));
  1144. pending_action |= ACT_NAV;
  1145. cancel_fetch = 1;
  1146. ngui_invalidate(&ui);
  1147. return 1;
  1148. }
  1149. static int fetch_script_text(const char *url, unsigned char **out,
  1150. unsigned int *outlen, char *err,
  1151. unsigned int errcap);
  1152. struct fetch_worker;
  1153. static struct fetch_worker *fetch_worker_alloc(void);
  1154. static void fetch_worker_release(struct fetch_worker *w);
  1155. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1156. unsigned int cap, const char *post,
  1157. unsigned int post_len, unsigned int node,
  1158. int bg, char *err, unsigned int errcap);
  1159. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1160. unsigned int errcap);
  1161. static int fetch_worker_read_body(struct fetch_worker *w,
  1162. unsigned char *plain,
  1163. unsigned int plaincap,
  1164. unsigned char *comp,
  1165. unsigned int compcap,
  1166. int *truncated, char *err,
  1167. unsigned int errcap);
  1168. static void fetch_workers_stop_all(void);
  1169. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1170. unsigned int cap, const char *method,
  1171. const char *ctype, const char *post,
  1172. unsigned int post_len, unsigned int node,
  1173. int bg, unsigned int dec_w,
  1174. unsigned int dec_h, char *err,
  1175. unsigned int errcap);
  1176. static int script_cache_has(const char *url);
  1177. static void script_cache_put(const char *url, const unsigned char *data,
  1178. unsigned int len);
  1179. static unsigned int script_cache_hash(const char *s);
  1180. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1181. unsigned int errcap);
  1182. static void fetch_workers_cancel_busy(void);
  1183. static void worker_wait_ui(void);
  1184. static int fetch_worker_status(const struct fetch_worker *w);
  1185. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1186. * module load: the wait must not pump input, or a click would dispatch DOM
  1187. * events into the middle of the running script. */
  1188. static int fetch_wait_passive;
  1189. static void script_error(const char *what, const char *url, const char *why)
  1190. {
  1191. char msg[192];
  1192. unsigned int n = 0;
  1193. s_append(msg, &n, what, sizeof(msg));
  1194. if (url && url[0]) {
  1195. s_append(msg, &n, " ", sizeof(msg));
  1196. s_append(msg, &n, url, sizeof(msg));
  1197. }
  1198. if (why && why[0]) {
  1199. s_append(msg, &n, ": ", sizeof(msg));
  1200. s_append(msg, &n, why, sizeof(msg));
  1201. }
  1202. js_host_report(msg);
  1203. }
  1204. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1205. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1206. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1207. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1208. #define JS_HTTP_POST_MAX (16u * 1024u)
  1209. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1210. static int js_worker_http(const char *method, const char *url,
  1211. const char *ctype, const char *body,
  1212. unsigned int body_len, struct js_http_resp *r,
  1213. char *err, int errcap);
  1214. static int js_host_http(const char *method, const char *url,
  1215. const char *ctype, const char *body,
  1216. unsigned int body_len, struct js_http_resp *r,
  1217. char *err, int errcap)
  1218. {
  1219. if (pending_action) {
  1220. s_copy(err, "page is navigating", (unsigned int)errcap);
  1221. return -1;
  1222. }
  1223. if (url[0] == '/') {
  1224. /* Local file: GET only. */
  1225. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1226. int rv;
  1227. if (!buf) {
  1228. s_copy(err, "out of memory", (unsigned int)errcap);
  1229. return -1;
  1230. }
  1231. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1232. (int)JS_HTTP_MAX);
  1233. r->status = rv < 0 ? 404 : 200;
  1234. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1235. buf[r->len] = '\0';
  1236. r->body = (char *)buf;
  1237. s_copy(r->url, url, sizeof(r->url));
  1238. if (contains_ci(url, ".json"))
  1239. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1240. return 0;
  1241. }
  1242. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1243. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1244. return -1;
  1245. }
  1246. if (body_len > JS_HTTP_POST_MAX) {
  1247. s_copy(err, "request body too large", (unsigned int)errcap);
  1248. return -1;
  1249. }
  1250. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1251. errcap);
  1252. }
  1253. /* Module source for the engine's loader: the boot script cache first, then
  1254. * one blocking fetch with input pumping disabled (the loader runs inside
  1255. * JavaScript). */
  1256. static char *js_host_load_script(const char *url, unsigned int *len)
  1257. {
  1258. unsigned char *data = 0;
  1259. char err[64];
  1260. int rv;
  1261. fetch_wait_passive++;
  1262. set_status("Loading module...", 0, 0);
  1263. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1264. fetch_wait_passive--;
  1265. if (rv != 0) {
  1266. script_error("Cannot load module", url,
  1267. rv == FETCH_ABORT ? "navigation" : err);
  1268. return 0;
  1269. }
  1270. return (char *)data;
  1271. }
  1272. /* Web Storage lives in /share, outside the page heap that every navigation
  1273. * resets: localStorage per origin for the boot, sessionStorage per origin
  1274. * and browser window. */
  1275. #define JS_ORIGIN_MAX 160
  1276. /* scheme://host[:port] of the page (a local page's whole path). */
  1277. static void js_page_origin(char *origin, unsigned int cap)
  1278. {
  1279. unsigned int i = 0, slashes = 0;
  1280. while (page_url[i] && i + 1 < cap) {
  1281. if (page_url[i] == '/' && ++slashes == 3)
  1282. break;
  1283. origin[i] = page_url[i];
  1284. i++;
  1285. }
  1286. origin[i] = '\0';
  1287. }
  1288. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1289. {
  1290. unsigned int n = 0;
  1291. s_append(out, &n, "/share/bls", cap);
  1292. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1293. }
  1294. static void js_storage_path(int kind, char *out, unsigned int cap)
  1295. {
  1296. char origin[JS_ORIGIN_MAX];
  1297. unsigned int n = 0;
  1298. js_page_origin(origin, sizeof(origin));
  1299. if (!kind) {
  1300. js_origin_path(origin, out, cap);
  1301. return;
  1302. }
  1303. s_append(out, &n, "/share/bss", cap);
  1304. if (kind) {
  1305. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1306. s_append(out, &n, "-", cap);
  1307. }
  1308. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1309. }
  1310. static void persist_mark_origin(const char *origin);
  1311. static int persist_store_lookup(const char *origin, char *out, int cap);
  1312. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1313. {
  1314. char path[48], origin[JS_ORIGIN_MAX];
  1315. int rv;
  1316. js_storage_path(kind, path, sizeof(path));
  1317. if (set) {
  1318. if (kind) {
  1319. if (!set[0] || !strcmp(set, "{}")) {
  1320. u_syscall1(SYS_UNLINK, (int)path);
  1321. return 0;
  1322. }
  1323. } else {
  1324. /* localStorage keeps an explicit "{}" rather than no
  1325. * file: a missing /share file means "not loaded from
  1326. * /data yet", and a cleared store must not come back
  1327. * from the disk copy before it is flushed. */
  1328. if (!set[0])
  1329. set = "{}";
  1330. js_page_origin(origin, sizeof(origin));
  1331. persist_mark_origin(origin);
  1332. }
  1333. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1334. (int)strlen(set)) < 0 ? -1 : 0;
  1335. }
  1336. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1337. if (rv < 0 && !kind) {
  1338. /* First use this boot: the persistent copy on /data. */
  1339. js_page_origin(origin, sizeof(origin));
  1340. rv = persist_store_lookup(origin, out, cap);
  1341. if (rv >= 0)
  1342. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1343. }
  1344. if (rv < 0)
  1345. return -1;
  1346. out[rv] = '\0';
  1347. return rv;
  1348. }
  1349. /* ---- persistence on /data ----
  1350. *
  1351. * /share is the working copy (RAM, shared by every helper and window); the
  1352. * installed disk's /data volume keeps the cookie jar and localStorage
  1353. * across reboots when it is mounted. The browser owns the disk copies: at
  1354. * start it restores the jar into /share, and its main loop writes back
  1355. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1356. * setItem updates costs one FAT write. The helpers only touch /share (they
  1357. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1358. * /data mount every disk access simply fails. Both files are plaintext
  1359. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1360. #define PERSIST_MS 3000u
  1361. #define SHARE_COOKIES "/share/bcookies"
  1362. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1363. #define DATA_STORE "/data/BSTORE.DAT"
  1364. #define DATA_STORE_MAGIC "NBLS1\n"
  1365. #define DATA_STORE_MAX (192u * 1024u)
  1366. #define PERSIST_DIRTY_MAX 8
  1367. static unsigned int persist_due;
  1368. static unsigned int cookie_sum_saved;
  1369. static int cookie_sum_valid;
  1370. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1371. static int persist_ndirty;
  1372. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1373. {
  1374. unsigned int h = 2166136261u, i;
  1375. for (i = 0; i < n; i++)
  1376. h = (h ^ p[i]) * 16777619u;
  1377. return h;
  1378. }
  1379. /* Called once at startup, before any helper runs. */
  1380. static void persist_restore(void)
  1381. {
  1382. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1383. int n;
  1384. if (!jar)
  1385. return;
  1386. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1387. (int)sizeof(struct uhttp_jar));
  1388. if (n != (int)sizeof(struct uhttp_jar)) {
  1389. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1390. (int)sizeof(struct uhttp_jar));
  1391. if (n == (int)sizeof(struct uhttp_jar)) {
  1392. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1393. (int)jar, n);
  1394. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1395. cookie_sum_valid = 1;
  1396. }
  1397. }
  1398. free(jar);
  1399. persist_due = u_ticks_ms() + PERSIST_MS;
  1400. }
  1401. static void persist_mark_origin(const char *origin)
  1402. {
  1403. int i;
  1404. for (i = 0; i < persist_ndirty; i++)
  1405. if (s_eq(persist_dirty[i], origin))
  1406. return;
  1407. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1408. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1409. }
  1410. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1411. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1412. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1413. unsigned int *o_off, unsigned int *o_len,
  1414. unsigned int *d_off, unsigned int *d_len,
  1415. unsigned int *rec_end)
  1416. {
  1417. unsigned int p = *pos, v = 0;
  1418. if (p >= len)
  1419. return 0;
  1420. *o_off = p;
  1421. while (p < len && buf[p] != '\n')
  1422. p++;
  1423. if (p >= len)
  1424. return 0;
  1425. *o_len = p - *o_off;
  1426. p++;
  1427. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1428. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1429. if (p >= len || buf[p] != '\n')
  1430. return 0;
  1431. p++;
  1432. if (v > len - p)
  1433. return 0;
  1434. *d_off = p;
  1435. *d_len = v;
  1436. p += v;
  1437. if (p < len && buf[p] == '\n')
  1438. p++;
  1439. *rec_end = p;
  1440. *pos = p;
  1441. return 1;
  1442. }
  1443. static int store_load(char **out)
  1444. {
  1445. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1446. int n;
  1447. *out = buf;
  1448. if (!buf)
  1449. return -1;
  1450. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1451. (int)DATA_STORE_MAX);
  1452. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1453. !starts_with(buf, DATA_STORE_MAGIC))
  1454. return 0;
  1455. return n;
  1456. }
  1457. static int persist_store_lookup(const char *origin, char *out, int cap)
  1458. {
  1459. char *buf;
  1460. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1461. unsigned int olen = s_len(origin);
  1462. int n = store_load(&buf), rv = -1;
  1463. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1464. &dl, &e)) {
  1465. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1466. if ((int)dl < cap) {
  1467. memcpy(out, buf + d, dl);
  1468. out[dl] = '\0';
  1469. rv = (int)dl;
  1470. }
  1471. break;
  1472. }
  1473. }
  1474. free(buf);
  1475. return rv;
  1476. }
  1477. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1478. static void persist_store_flush(void)
  1479. {
  1480. char *old, *nb, path[48];
  1481. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1482. int n = store_load(&old), i, w;
  1483. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1484. if (n < 0 || !nb) {
  1485. free(old);
  1486. free(nb);
  1487. return;
  1488. }
  1489. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1490. /* Untouched origins first, in their old order. */
  1491. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1492. &dl, &e)) {
  1493. int dirty = 0;
  1494. for (i = 0; i < persist_ndirty; i++)
  1495. if (s_len(persist_dirty[i]) == ol &&
  1496. !memcmp(persist_dirty[i], old + oo, ol))
  1497. dirty = 1;
  1498. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1499. continue;
  1500. memcpy(nb + nn, old + oo, e - oo);
  1501. nn += e - oo;
  1502. }
  1503. /* Then the changed ones (an emptied store is dropped). */
  1504. for (i = 0; i < persist_ndirty; i++) {
  1505. char num[12];
  1506. unsigned int k = 0;
  1507. js_origin_path(persist_dirty[i], path, sizeof(path));
  1508. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1509. (int)DATA_STORE_MAX);
  1510. if (w <= 2) /* missing or "{}" */
  1511. continue;
  1512. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1513. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1514. DATA_STORE_MAX) {
  1515. set_status("Saved site data is full; a site's "
  1516. "localStorage was not saved", 1, 6000);
  1517. continue;
  1518. }
  1519. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1520. nb[nn++] = '\n';
  1521. s_append(nb, &nn, num, DATA_STORE_MAX);
  1522. nb[nn++] = '\n';
  1523. memcpy(nb + nn, old, (unsigned int)w);
  1524. nn += (unsigned int)w;
  1525. nb[nn++] = '\n';
  1526. }
  1527. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1528. persist_ndirty = 0;
  1529. free(old);
  1530. free(nb);
  1531. }
  1532. static void persist_cookies_flush(void)
  1533. {
  1534. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1535. unsigned int sum;
  1536. int n;
  1537. if (!jar)
  1538. return;
  1539. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1540. (int)sizeof(struct uhttp_jar));
  1541. if (n == (int)sizeof(struct uhttp_jar)) {
  1542. sum = persist_sum(jar, (unsigned int)n);
  1543. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1544. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1545. (int)jar, n) >= 0) {
  1546. cookie_sum_saved = sum;
  1547. cookie_sum_valid = 1;
  1548. }
  1549. }
  1550. }
  1551. free(jar);
  1552. }
  1553. /* ---- visit history (URL-bar autocomplete) ----
  1554. *
  1555. * Every page that finishes loading is recorded with its title, a visit
  1556. * count and a stamp: a counter that only grows and travels with the file,
  1557. * so it orders visits across windows and boots without a wall clock. The
  1558. * table lives in BSS, because the page heap is reset on every navigation.
  1559. * The boot's browser windows share it through /share/bhist (rewritten on
  1560. * every visit) and it is persisted to /data/BHIST.DAT from persist_tick()
  1561. * at most every PERSIST_MS, like the cookie jar. A save re-reads
  1562. * /share/bhist and merges it first, so two windows add to one history
  1563. * instead of overwriting each other. File format: "NBHIST1\n", then
  1564. * "<visits> <stamp> <url>\t<title>\n" per entry. Plaintext, like the
  1565. * other browser state on /data. */
  1566. #define HIST_MAX 128
  1567. #define HIST_URL_MAX 512
  1568. #define HIST_FILE_MAX (HIST_MAX * (HIST_URL_MAX + BR_TITLE_MAX + 24) + 16)
  1569. #define HIST_MAGIC "NBHIST1\n"
  1570. #define SHARE_HIST "/share/bhist"
  1571. #define DATA_HIST "/data/BHIST.DAT"
  1572. #define HIST_FORGET_MAX 16
  1573. struct hist_ent {
  1574. unsigned int visits;
  1575. unsigned int stamp;
  1576. char url[HIST_URL_MAX];
  1577. char title[BR_TITLE_MAX];
  1578. };
  1579. static struct hist_ent hist_tab[HIST_MAX];
  1580. static int hist_n;
  1581. static int hist_share_dirty, hist_data_dirty;
  1582. /* URLs removed in this process: a merge must not bring them back. */
  1583. static unsigned int hist_forgot[HIST_FORGET_MAX];
  1584. static int hist_nforgot;
  1585. static unsigned int hist_hash(const char *s)
  1586. {
  1587. return persist_sum((const unsigned char *)s, s_len(s));
  1588. }
  1589. static int hist_is_forgotten(const char *url)
  1590. {
  1591. unsigned int h = hist_hash(url);
  1592. int i;
  1593. for (i = 0; i < hist_nforgot; i++)
  1594. if (hist_forgot[i] == h)
  1595. return 1;
  1596. return 0;
  1597. }
  1598. static int hist_find(const char *url)
  1599. {
  1600. int i;
  1601. for (i = 0; i < hist_n; i++)
  1602. if (s_eq(hist_tab[i].url, url))
  1603. return i;
  1604. return -1;
  1605. }
  1606. static unsigned int hist_next_stamp(void)
  1607. {
  1608. unsigned int m = 0;
  1609. int i;
  1610. for (i = 0; i < hist_n; i++)
  1611. if (hist_tab[i].stamp > m)
  1612. m = hist_tab[i].stamp;
  1613. return m + 1;
  1614. }
  1615. /* Copy a title, turning tabs/newlines (the file separators) into spaces. */
  1616. static void hist_copy_title(char *d, const char *s, unsigned int n)
  1617. {
  1618. unsigned int i;
  1619. for (i = 0; i + 1 < BR_TITLE_MAX && i < n && s[i]; i++)
  1620. d[i] = (unsigned char)s[i] < 0x20 ? ' ' : s[i];
  1621. d[i] = '\0';
  1622. }
  1623. /* Insert or update an entry; the newer stamp wins the title, the larger
  1624. * visit count is kept. A full table evicts the least recent entry, unless
  1625. * the new one is older still. Returns NULL when nothing was stored. */
  1626. static struct hist_ent *hist_put(const char *url, const char *title,
  1627. unsigned int visits, unsigned int stamp)
  1628. {
  1629. struct hist_ent *e;
  1630. int i = hist_find(url);
  1631. if (i < 0) {
  1632. if (hist_n < HIST_MAX) {
  1633. i = hist_n++;
  1634. } else {
  1635. int j;
  1636. i = 0;
  1637. for (j = 1; j < hist_n; j++)
  1638. if (hist_tab[j].stamp < hist_tab[i].stamp)
  1639. i = j;
  1640. if (hist_tab[i].stamp >= stamp)
  1641. return 0;
  1642. }
  1643. e = &hist_tab[i];
  1644. e->visits = 0;
  1645. e->stamp = 0;
  1646. e->title[0] = '\0';
  1647. s_copy(e->url, url, sizeof(e->url));
  1648. }
  1649. e = &hist_tab[i];
  1650. if (visits > e->visits)
  1651. e->visits = visits;
  1652. if (stamp >= e->stamp) {
  1653. e->stamp = stamp;
  1654. if (title && title[0])
  1655. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1656. } else if (!e->title[0] && title) {
  1657. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1658. }
  1659. return e;
  1660. }
  1661. static unsigned int hist_parse_dec(const char *b, int n, int *pos)
  1662. {
  1663. unsigned int v = 0;
  1664. while (*pos < n && b[*pos] >= '0' && b[*pos] <= '9')
  1665. v = v * 10 + (unsigned int)(b[(*pos)++] - '0');
  1666. return v;
  1667. }
  1668. static void hist_merge_buf(const char *b, int n)
  1669. {
  1670. int pos = (int)s_len(HIST_MAGIC);
  1671. char url[HIST_URL_MAX], title[BR_TITLE_MAX];
  1672. if (n < pos || memcmp(b, HIST_MAGIC, (unsigned int)pos))
  1673. return;
  1674. while (pos < n) {
  1675. unsigned int visits, stamp, ul = 0;
  1676. int t0, t1;
  1677. visits = hist_parse_dec(b, n, &pos);
  1678. if (pos < n && b[pos] == ' ')
  1679. pos++;
  1680. stamp = hist_parse_dec(b, n, &pos);
  1681. if (pos < n && b[pos] == ' ')
  1682. pos++;
  1683. while (pos < n && b[pos] != '\t' && b[pos] != '\n') {
  1684. if (ul + 1 < sizeof(url))
  1685. url[ul++] = b[pos];
  1686. pos++;
  1687. }
  1688. url[ul] = '\0';
  1689. t0 = t1 = pos < n && b[pos] == '\t' ? pos + 1 : pos;
  1690. while (t1 < n && b[t1] != '\n')
  1691. t1++;
  1692. pos = t1 + 1;
  1693. hist_copy_title(title, b + t0, (unsigned int)(t1 - t0));
  1694. if (ul && ul + 1 < sizeof(url) && !hist_is_forgotten(url))
  1695. hist_put(url, title, visits, stamp);
  1696. }
  1697. }
  1698. static int hist_serialize(char *b, unsigned int cap)
  1699. {
  1700. unsigned int n = 0;
  1701. int i;
  1702. s_append(b, &n, HIST_MAGIC, cap);
  1703. for (i = 0; i < hist_n; i++) {
  1704. struct hist_ent *e = &hist_tab[i];
  1705. if (n + s_len(e->url) + s_len(e->title) + 26 >= cap)
  1706. break;
  1707. s_append_dec(b, &n, e->visits, cap);
  1708. b[n++] = ' ';
  1709. s_append_dec(b, &n, e->stamp, cap);
  1710. b[n++] = ' ';
  1711. s_append(b, &n, e->url, cap);
  1712. b[n++] = '\t';
  1713. s_append(b, &n, e->title, cap);
  1714. b[n++] = '\n';
  1715. }
  1716. return (int)n;
  1717. }
  1718. /* Merge /share/bhist, then write it back (and /data when asked). */
  1719. static void hist_sync(int to_data)
  1720. {
  1721. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1722. int n;
  1723. if (!b)
  1724. return;
  1725. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1726. (int)HIST_FILE_MAX);
  1727. if (n > 0)
  1728. hist_merge_buf(b, n);
  1729. n = hist_serialize(b, HIST_FILE_MAX);
  1730. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1731. hist_share_dirty = 0;
  1732. if (to_data) {
  1733. /* No /data mount: the write fails, and there is nothing to
  1734. * retry until the next visit. */
  1735. u_syscall3(SYS_WRITE_FILE, (int)DATA_HIST, (int)b, n);
  1736. hist_data_dirty = 0;
  1737. }
  1738. free(b);
  1739. }
  1740. /* Startup: the boot's shared copy, else the saved one from /data. */
  1741. static void hist_load(void)
  1742. {
  1743. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1744. int n;
  1745. if (!b)
  1746. return;
  1747. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1748. (int)HIST_FILE_MAX);
  1749. if (n <= 0) {
  1750. n = u_syscall3(SYS_READ_FILE, (int)DATA_HIST, (int)b,
  1751. (int)HIST_FILE_MAX);
  1752. if (n > 0)
  1753. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1754. }
  1755. if (n > 0)
  1756. hist_merge_buf(b, n);
  1757. free(b);
  1758. }
  1759. static void hist_visit(const char *url, const char *title)
  1760. {
  1761. struct hist_ent *e;
  1762. unsigned int i;
  1763. if (!url[0] || starts_with(url, "about:") ||
  1764. s_len(url) >= HIST_URL_MAX)
  1765. return;
  1766. for (i = 0; url[i]; i++)
  1767. if ((unsigned char)url[i] < 0x20)
  1768. return;
  1769. e = hist_put(url, title, 0, hist_next_stamp());
  1770. if (!e)
  1771. return;
  1772. e->visits++;
  1773. hist_data_dirty = 1;
  1774. hist_sync(0);
  1775. }
  1776. static void hist_forget(int i)
  1777. {
  1778. if (i < 0 || i >= hist_n)
  1779. return;
  1780. if (hist_nforgot < HIST_FORGET_MAX)
  1781. hist_forgot[hist_nforgot++] = hist_hash(hist_tab[i].url);
  1782. hist_n--;
  1783. for (; i < hist_n; i++)
  1784. hist_tab[i] = hist_tab[i + 1];
  1785. hist_data_dirty = 1;
  1786. hist_sync(0);
  1787. }
  1788. static void hist_tick(void)
  1789. {
  1790. if (hist_share_dirty || hist_data_dirty)
  1791. hist_sync(hist_data_dirty);
  1792. }
  1793. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1794. static void persist_tick(void)
  1795. {
  1796. unsigned int now = u_ticks_ms();
  1797. if ((int)(now - persist_due) < 0)
  1798. return;
  1799. persist_due = now + PERSIST_MS;
  1800. persist_cookies_flush();
  1801. if (persist_ndirty)
  1802. persist_store_flush();
  1803. hist_tick();
  1804. }
  1805. /* <link rel="modulepreload">: download the page's module graph on all
  1806. * helpers at once into the boot script cache, before any script runs. The
  1807. * engine's module loader is sequential (one blocking fetch per import), so
  1808. * without this a Vite app with a dozen chunks pays every round trip in a
  1809. * row. Failures are ignored; the loader fetches what is missing. */
  1810. #define MODULE_PRELOAD_MAX 24
  1811. static void prefetch_module_preloads(void)
  1812. {
  1813. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1814. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1815. unsigned int count = 0, next = 0, done = 0, i;
  1816. char err[64];
  1817. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1818. struct br_node *nd = &doc.nodes[i];
  1819. const char *rel, *href;
  1820. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1821. continue;
  1822. rel = br_rel(&doc, i);
  1823. href = br_href(&doc, i);
  1824. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1825. continue;
  1826. if (resolve_link(page_url, href, urls[count],
  1827. sizeof(urls[count])) != 0 ||
  1828. urls[count][0] == '/' || script_cache_has(urls[count]))
  1829. continue;
  1830. slot[count++] = 0;
  1831. }
  1832. if (!count)
  1833. return;
  1834. set_status("Loading modules...", 0, 0);
  1835. while (done < count) {
  1836. struct fetch_worker *w;
  1837. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1838. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1839. 0, 0, 0, err,
  1840. sizeof(err)) != 0) {
  1841. fetch_worker_release(w);
  1842. done++;
  1843. } else {
  1844. slot[next] = w;
  1845. }
  1846. next++;
  1847. }
  1848. worker_wait_ui();
  1849. if (cancel_fetch || pending_action) {
  1850. fetch_workers_cancel_busy();
  1851. return;
  1852. }
  1853. for (i = 0; i < next; i++) {
  1854. unsigned char *body;
  1855. int rv, tr = 0;
  1856. if (!slot[i])
  1857. continue;
  1858. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1859. if (rv == 0)
  1860. continue;
  1861. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1862. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1863. if (body) {
  1864. rv = fetch_worker_read_body(slot[i], body,
  1865. BR_SCRIPT_MAX, image_io_buf,
  1866. BR_PAGE_COMP_MAX, &tr, err,
  1867. sizeof(err));
  1868. if (rv > 0 && !tr)
  1869. script_cache_put(urls[i], body,
  1870. (unsigned int)rv);
  1871. free(body);
  1872. }
  1873. fetch_worker_release(slot[i]);
  1874. slot[i] = 0;
  1875. done++;
  1876. }
  1877. u_sleep_ms(10);
  1878. }
  1879. }
  1880. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1881. * submitted to helper workers ahead of time, but scripts still execute in
  1882. * document order. */
  1883. #define SCRIPT_INLINE 0
  1884. #define SCRIPT_LOCAL 1
  1885. #define SCRIPT_REMOTE 2
  1886. #define SCRIPT_ERROR 3
  1887. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1888. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1889. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1890. static void script_submit_window(unsigned int *next, char *err,
  1891. unsigned int errcap)
  1892. {
  1893. while (*next < doc.nscripts) {
  1894. struct fetch_worker *w;
  1895. if (script_kind[*next] != SCRIPT_REMOTE) {
  1896. (*next)++;
  1897. continue;
  1898. }
  1899. w = fetch_worker_alloc();
  1900. if (!w)
  1901. return;
  1902. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1903. 0, 0, 0, 0, err, errcap) != 0) {
  1904. fetch_worker_release(w);
  1905. script_kind[*next] = SCRIPT_ERROR;
  1906. (*next)++;
  1907. continue;
  1908. }
  1909. script_slot[*next] = w;
  1910. (*next)++;
  1911. }
  1912. }
  1913. /* Run the page's scripts in document order. External bodies are prefetched
  1914. * in parallel so downloading script N+1 overlaps executing script N; inline
  1915. * bodies are copied because the engine needs NUL-terminated text. */
  1916. static void run_page_scripts(void)
  1917. {
  1918. struct js_browser_host host;
  1919. unsigned int i, next = 0;
  1920. char err[64], ferr[64];
  1921. if (!doc.nscripts)
  1922. return;
  1923. host.status = js_host_status;
  1924. host.report = js_host_report;
  1925. host.navigate = js_host_navigate;
  1926. host.changed = js_host_changed;
  1927. host.rect = js_host_rect;
  1928. host.form_value = js_host_form_value;
  1929. host.form_checked = js_host_form_checked;
  1930. host.form_selected = js_host_form_selected;
  1931. host.form_set_value = js_host_form_set_value;
  1932. host.form_set_checked = js_host_form_set_checked;
  1933. host.form_set_selected = js_host_form_set_selected;
  1934. host.form_elements = js_host_form_elements;
  1935. host.form_submit = js_host_form_submit;
  1936. host.form_reset = js_host_form_reset;
  1937. host.click = js_host_click;
  1938. host.computed = js_host_computed;
  1939. host.http = js_host_http;
  1940. host.load_script = js_host_load_script;
  1941. host.storage = js_host_storage;
  1942. host.set_hash = js_host_set_hash;
  1943. host.page_url = page_url;
  1944. host.width = ui.w;
  1945. host.height = ui.h;
  1946. if (js_browser_start(&doc, &host) != 0) {
  1947. js_host_status("JavaScript: out of memory", 1);
  1948. return;
  1949. }
  1950. resize_sent_w = -1;
  1951. resize_pending = 0;
  1952. prefetch_module_preloads();
  1953. for (i = 0; i < doc.nscripts; i++) {
  1954. struct br_script *script = &doc.scripts[i];
  1955. const char *src_attr = script->src_off ?
  1956. doc.attrs + script->src_off : "";
  1957. script_slot[i] = 0;
  1958. if (!script->src_off) {
  1959. script_kind[i] = SCRIPT_INLINE;
  1960. continue;
  1961. }
  1962. if (!src_attr[0] ||
  1963. resolve_link(page_url, src_attr, script_urls[i],
  1964. sizeof(script_urls[i])) != 0) {
  1965. script_urls[i][0] = '\0';
  1966. script_kind[i] = SCRIPT_ERROR;
  1967. continue;
  1968. }
  1969. if (script_urls[i][0] == '/' ||
  1970. script_cache_has(script_urls[i]))
  1971. script_kind[i] = SCRIPT_LOCAL;
  1972. else
  1973. script_kind[i] = SCRIPT_REMOTE;
  1974. }
  1975. script_submit_window(&next, ferr, sizeof(ferr));
  1976. for (i = 0; i < doc.nscripts; i++) {
  1977. struct br_script *script = &doc.scripts[i];
  1978. /* document.currentScript for classic scripts (null for modules) */
  1979. js_browser_set_current_script(script->module ? 0 : script->node);
  1980. if (script_kind[i] == SCRIPT_INLINE) {
  1981. unsigned int off = script->off;
  1982. unsigned int len = script->len;
  1983. unsigned int k;
  1984. char *src = (char *)malloc(len + 1);
  1985. if (!src) {
  1986. js_host_status("JavaScript: out of memory", 1);
  1987. break;
  1988. }
  1989. for (k = 0; k < len; k++)
  1990. src[k] = doc.script_src[off + k];
  1991. src[len] = '\0';
  1992. if (script->module) {
  1993. /* A distinct module name per inline module
  1994. * (QuickJS registers modules by name); the
  1995. * fragment keeps relative imports resolving
  1996. * against the page. */
  1997. char mname[BR_URL_MAX + 16];
  1998. unsigned int mn = 0;
  1999. s_append(mname, &mn, page_url, sizeof(mname));
  2000. s_append(mname, &mn, "#module", sizeof(mname));
  2001. s_append_dec(mname, &mn, i, sizeof(mname));
  2002. js_browser_run_module(src, mname);
  2003. } else {
  2004. js_browser_run(src, page_url);
  2005. }
  2006. free(src);
  2007. } else if (script->src_off) {
  2008. const char *src_attr = doc.attrs + script->src_off;
  2009. if (script_kind[i] == SCRIPT_ERROR) {
  2010. script_error("Cannot load script", src_attr,
  2011. script_urls[i][0] ?
  2012. "network busy" :
  2013. "unsupported URL");
  2014. continue;
  2015. }
  2016. if (script_kind[i] == SCRIPT_LOCAL) {
  2017. unsigned char *data = 0;
  2018. unsigned int len = 0;
  2019. int rv;
  2020. set_status("Loading script...", 0, 0);
  2021. rv = fetch_script_text(script_urls[i], &data,
  2022. &len, err, sizeof(err));
  2023. if (rv == FETCH_ABORT)
  2024. break;
  2025. if (rv != 0) {
  2026. script_error("Cannot load script",
  2027. script_urls[i], err);
  2028. continue;
  2029. }
  2030. if (script->module)
  2031. js_browser_run_module(
  2032. (const char *)data,
  2033. script_urls[i]);
  2034. else
  2035. js_browser_run((const char *)data,
  2036. script_urls[i]);
  2037. free(data);
  2038. } else {
  2039. struct fetch_worker *w = script_slot[i];
  2040. unsigned char *body = 0;
  2041. int tr = 0, rv;
  2042. if (!w) {
  2043. w = fetch_worker_alloc();
  2044. if (!w)
  2045. continue;
  2046. if (fetch_worker_submit(w,
  2047. script_urls[i],
  2048. BR_SCRIPT_MAX,
  2049. 0, 0, 0, 0, err,
  2050. sizeof(err)) != 0) {
  2051. fetch_worker_release(w);
  2052. script_kind[i] = SCRIPT_ERROR;
  2053. if (i == next)
  2054. next++;
  2055. continue;
  2056. }
  2057. script_slot[i] = w;
  2058. if (i == next)
  2059. next++;
  2060. }
  2061. set_status("Loading script...", 0, 0);
  2062. rv = fetch_worker_wait(w, err, sizeof(err));
  2063. if (rv == FETCH_ABORT) {
  2064. fetch_workers_stop_all();
  2065. break;
  2066. }
  2067. /* The body gets its own buffer (scripts are up
  2068. * to 2 MB); image_io_buf takes the gzip
  2069. * stream. */
  2070. body = rv == 0 ? (unsigned char *)malloc(
  2071. BR_SCRIPT_MAX + 1) : 0;
  2072. if (body)
  2073. rv = fetch_worker_read_body(w, body,
  2074. BR_SCRIPT_MAX, image_io_buf,
  2075. BR_PAGE_COMP_MAX, &tr, err,
  2076. sizeof(err));
  2077. else {
  2078. if (rv == 0)
  2079. s_copy(err, "out of memory",
  2080. sizeof(err));
  2081. rv = -1;
  2082. }
  2083. fetch_worker_release(w);
  2084. script_slot[i] = 0;
  2085. script_submit_window(&next, ferr, sizeof(ferr));
  2086. if (rv <= 0)
  2087. script_error("Cannot load script",
  2088. script_urls[i], err);
  2089. else if (tr || (unsigned int)rv >=
  2090. BR_SCRIPT_MAX)
  2091. script_error("Cannot load script",
  2092. script_urls[i],
  2093. "script is too large");
  2094. else {
  2095. body[rv] = '\0';
  2096. script_cache_put(script_urls[i], body,
  2097. (unsigned int)rv);
  2098. if (script->module)
  2099. js_browser_run_module(
  2100. (const char *)body,
  2101. script_urls[i]);
  2102. else
  2103. js_browser_run(
  2104. (const char *)body,
  2105. script_urls[i]);
  2106. }
  2107. free(body);
  2108. }
  2109. }
  2110. if (pending_action)
  2111. break;
  2112. }
  2113. js_browser_set_current_script(0);
  2114. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  2115. * load_home() stop it before the next navigation. */
  2116. if (doc.scripts_truncated && !js_last_error)
  2117. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  2118. 1);
  2119. }
  2120. /* ---- images ---- */
  2121. static void image_reset(void)
  2122. {
  2123. int i;
  2124. for (i = 0; i < BR_MAX_IMAGES; i++) {
  2125. images[i].state = 0;
  2126. images[i].native_w = images[i].native_h = 0;
  2127. images[i].err[0] = '\0';
  2128. /* heap_clear() ran before us, so these pointers are stale: drop
  2129. * them without calling free(). */
  2130. memset(&images[i].disp, 0, sizeof(images[i].disp));
  2131. images[i].disp_pixels = 0;
  2132. images[i].disp_last = 0;
  2133. }
  2134. image_count = 0;
  2135. image_pixels = 0;
  2136. image_disp_pixels = 0;
  2137. image_disp_clock = 0;
  2138. memset(img_stat_log, 0, sizeof(img_stat_log));
  2139. img_stat_log_len = 0;
  2140. img_stat_start = 0;
  2141. img_stat_wall = 0;
  2142. img_stat_net = img_stat_open = img_stat_first = 0;
  2143. img_stat_io = img_stat_dec = img_stat_scale = 0;
  2144. img_stat_paint = img_stat_reflow = 0;
  2145. img_stat_bytes = 0;
  2146. img_stat_n = 0;
  2147. img_last_dec_ms = img_last_scale_ms = 0;
  2148. img_repaint_ms = 0;
  2149. img_repaint_pending = 0;
  2150. preload_active = 0;
  2151. preload_pending = 0;
  2152. preload_wait = 0;
  2153. preload_node = 0;
  2154. preload_loaded = 0;
  2155. }
  2156. /* Ask for a repaint, but not more often than BR_IMG_REPAINT_MS while images
  2157. * are arriving. The main loop draws once per dirty frame; without this a
  2158. * page of N images did N full layout+paint passes. */
  2159. static void image_repaint(void)
  2160. {
  2161. unsigned int now = u_ticks_ms();
  2162. if (!img_repaint_ms || (now - img_repaint_ms) >= BR_IMG_REPAINT_MS) {
  2163. img_repaint_ms = now;
  2164. img_repaint_pending = 0;
  2165. ngui_invalidate(&ui);
  2166. } else {
  2167. img_repaint_pending = 1;
  2168. }
  2169. }
  2170. static void image_disp_drop(struct br_image *bi)
  2171. {
  2172. if (bi->disp.px)
  2173. free(bi->disp.px);
  2174. if (bi->disp.alpha)
  2175. free(bi->disp.alpha);
  2176. memset(&bi->disp, 0, sizeof(bi->disp));
  2177. if (bi->disp_pixels) {
  2178. if (image_disp_pixels >= bi->disp_pixels)
  2179. image_disp_pixels -= bi->disp_pixels;
  2180. bi->disp_pixels = 0;
  2181. }
  2182. }
  2183. /* Free the least recently used display caches until need pixels fit. The
  2184. * source bitmap (bi->img) is never evicted; a later draw rescales it again. */
  2185. static int image_disp_room(unsigned int need)
  2186. {
  2187. while (image_disp_pixels + need > BR_IMG_DISP_BUDGET) {
  2188. unsigned int oldest = ~0u;
  2189. int i, victim = -1;
  2190. for (i = 0; i < image_count; i++) {
  2191. if (!images[i].disp.px)
  2192. continue;
  2193. if (images[i].disp_last < oldest) {
  2194. oldest = images[i].disp_last;
  2195. victim = i;
  2196. }
  2197. }
  2198. if (victim < 0)
  2199. return -1;
  2200. image_disp_drop(&images[victim]);
  2201. }
  2202. return 0;
  2203. }
  2204. /* Return a bitmap at exactly dw x dh, building it once from the capped source
  2205. * bitmap. Callers then draw with scale 1 and img_draw's copy fast path. */
  2206. static struct img_image *image_display_get(struct br_image *bi, int dw, int dh)
  2207. {
  2208. struct img_blit b;
  2209. unsigned int px;
  2210. if (!bi || bi->state != 1 || !bi->img.px || dw < 1 || dh < 1)
  2211. return 0;
  2212. if (dw == (int)bi->img.w && dh == (int)bi->img.h)
  2213. return &bi->img;
  2214. if (dw > 4096 || dh > 4096)
  2215. return &bi->img;
  2216. if (bi->disp.px && bi->disp.w == (unsigned int)dw &&
  2217. bi->disp.h == (unsigned int)dh) {
  2218. bi->disp_last = ++image_disp_clock;
  2219. return &bi->disp;
  2220. }
  2221. px = (unsigned int)dw * (unsigned int)dh;
  2222. if (px > BR_IMG_DISP_BUDGET || image_disp_room(px) != 0)
  2223. return &bi->img;
  2224. image_disp_drop(bi);
  2225. bi->disp.px = (unsigned short *)malloc(px * 2u);
  2226. if (!bi->disp.px)
  2227. return &bi->img;
  2228. if (bi->img.alpha) {
  2229. bi->disp.alpha = (unsigned char *)malloc(px);
  2230. if (!bi->disp.alpha) {
  2231. free(bi->disp.px);
  2232. bi->disp.px = 0;
  2233. return &bi->img;
  2234. }
  2235. }
  2236. bi->disp.w = (unsigned int)dw;
  2237. bi->disp.h = (unsigned int)dh;
  2238. bi->disp.format = bi->img.format;
  2239. bi->disp.flags = 0;
  2240. memset(&b, 0, sizeof(b));
  2241. b.dst = bi->disp.px;
  2242. b.dst_w = dw;
  2243. b.dst_h = dh;
  2244. b.clip_w = dw;
  2245. b.clip_h = dh;
  2246. b.scale = ((unsigned int)dw << 16) / bi->img.w;
  2247. b.dst_a = bi->disp.alpha;
  2248. b.flags = bi->disp.alpha ? IMG_BLIT_SAVE_ALPHA : 0;
  2249. img_draw(&bi->img, &b);
  2250. bi->disp_pixels = px;
  2251. image_disp_pixels += px;
  2252. bi->disp_last = ++image_disp_clock;
  2253. return &bi->disp;
  2254. }
  2255. /* Decode into the shared arena, then copy/scale the result into a display
  2256. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  2257. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  2258. * pixels. Transparent edges are composited over white. */
  2259. /* One decode scratch arena per page, reused across images. Allocating and
  2260. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  2261. * each small display bitmap landed in the hole the previous arena left, so
  2262. * the next arena no longer fit and the heap ratcheted up until an app
  2263. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  2264. * still released right after their one image. */
  2265. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  2266. static unsigned char *decode_arena_get(unsigned int bytes)
  2267. {
  2268. if (decode_arena && decode_arena_size >= bytes)
  2269. return decode_arena;
  2270. free(decode_arena);
  2271. decode_arena = (unsigned char *)malloc(bytes);
  2272. decode_arena_size = decode_arena ? bytes : 0;
  2273. return decode_arena;
  2274. }
  2275. static void decode_arena_put(void)
  2276. {
  2277. if (decode_arena_size > DECODE_ARENA_KEEP) {
  2278. free(decode_arena);
  2279. decode_arena = 0;
  2280. decode_arena_size = 0;
  2281. }
  2282. }
  2283. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  2284. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  2285. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  2286. static int svg_text_sniff(const unsigned char *d, unsigned int len);
  2287. static int svg_decode_image(const unsigned char *data, unsigned int len,
  2288. struct br_image *bi, int box_w, int box_h);
  2289. static int decode_image_data(const unsigned char *data, unsigned int len,
  2290. struct br_image *bi, int box_w, int box_h,
  2291. int fit_w, int fit_h)
  2292. {
  2293. struct img_info info;
  2294. struct img_options opt;
  2295. struct img_mem mem;
  2296. struct img_image decoded;
  2297. unsigned char *arena;
  2298. unsigned int est, bytes, i;
  2299. unsigned int t0;
  2300. unsigned short *px;
  2301. unsigned char *alpha = 0;
  2302. int dw, dh, r;
  2303. bi->url_hash = 0;
  2304. img_last_dec_ms = 0;
  2305. img_last_scale_ms = 0;
  2306. if (img_sniff(data, len, &info) != 0) {
  2307. if (svg_text_sniff(data, len))
  2308. return svg_decode_image(data, len, bi,
  2309. box_w > 0 && box_h > 0 ? box_w : fit_w,
  2310. box_w > 0 && box_h > 0 ? box_h : fit_h);
  2311. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  2312. return -1;
  2313. }
  2314. est = img_estimate(&info);
  2315. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  2316. s_copy(bi->err, "image too large", sizeof(bi->err));
  2317. return -1;
  2318. }
  2319. arena = decode_arena_get(est);
  2320. if (!arena) {
  2321. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2322. return -1;
  2323. }
  2324. img_mem_init(&mem, arena, est);
  2325. opt.max_pixels = BR_IMG_PIX_MAX;
  2326. opt.max_w = fit_w > 0 ? (unsigned int)fit_w :
  2327. (box_w > 0 ? (unsigned int)box_w : 0);
  2328. opt.max_h = fit_h > 0 ? (unsigned int)fit_h :
  2329. (box_h > 0 ? (unsigned int)box_h : 0);
  2330. t0 = u_ticks_ms();
  2331. r = img_decode(data, len, &opt, &mem, &decoded);
  2332. img_last_dec_ms = u_ticks_ms() - t0;
  2333. if (r != 0) {
  2334. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  2335. goto fail;
  2336. }
  2337. if (decoded.w == 0 || decoded.h == 0) {
  2338. s_copy(bi->err, "empty image", sizeof(bi->err));
  2339. goto fail;
  2340. }
  2341. /* The JPEG decoder may have reduced the IDCT output; the layout still
  2342. * needs the intrinsic dimensions from the header. */
  2343. bi->native_w = info.width ? (int)info.width : (int)decoded.w;
  2344. bi->native_h = info.height ? (int)info.height : (int)decoded.h;
  2345. dw = (int)decoded.w;
  2346. dh = (int)decoded.h;
  2347. /* An <img> with a CSS/attribute box only ever needs a bitmap that big:
  2348. * decoding 1200x800 and then box-filtering it to 1000x666, only to
  2349. * paint it at 400x267, doubled the decode-time scaling work. cap both
  2350. * axes with one scale so the aspect ratio is preserved. */
  2351. if (fit_w > 0 || fit_h > 0) {
  2352. unsigned int scw = fit_w > 0 ?
  2353. ((unsigned int)fit_w << 16) / decoded.w : ~0u;
  2354. unsigned int sch = fit_h > 0 ?
  2355. ((unsigned int)fit_h << 16) / decoded.h : ~0u;
  2356. unsigned int sc = scw < sch ? scw : sch;
  2357. if (sc < 0x10000u) {
  2358. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2359. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2360. if (dw < 1)
  2361. dw = 1;
  2362. if (dh < 1)
  2363. dh = 1;
  2364. }
  2365. }
  2366. if (box_w > 0 && box_h > 0) {
  2367. /* cover: scale so both box sides are filled, never up */
  2368. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  2369. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  2370. unsigned int sc = sw > sh ? sw : sh;
  2371. if (sc < 0x10000u) {
  2372. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2373. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2374. }
  2375. }
  2376. if (dw > BR_IMG_LAYOUT_W) {
  2377. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  2378. dw = BR_IMG_LAYOUT_W;
  2379. }
  2380. if (dh < 1)
  2381. dh = 1;
  2382. if (dw < 1)
  2383. dw = 1;
  2384. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  2385. BR_IMG_PIXEL_BUDGET) {
  2386. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  2387. goto fail;
  2388. }
  2389. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  2390. px = (unsigned short *)malloc(bytes);
  2391. if (!px) {
  2392. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2393. goto fail;
  2394. }
  2395. /* Keep the alpha plane for the scaled image so transparent logos and
  2396. * icons composite over the page instead of the browser's dark theme
  2397. * background. Very large alpha images stay flattened to bound the
  2398. * heap use. */
  2399. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  2400. alpha = (unsigned char *)malloc((unsigned int)dw *
  2401. (unsigned int)dh);
  2402. if (alpha) {
  2403. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2404. alpha[i] = 255;
  2405. }
  2406. }
  2407. /* With an alpha plane the colour under transparent pixels only shows
  2408. * through partially covered edge pixels of the downscale: use white,
  2409. * as documented above, not the dark browser theme (which left a dark
  2410. * fringe around scaled app icons). */
  2411. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2412. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  2413. {
  2414. struct img_blit b;
  2415. b.dst = px;
  2416. b.dst_w = dw;
  2417. b.dst_h = dh;
  2418. b.clip_x = 0;
  2419. b.clip_y = 0;
  2420. b.clip_w = dw;
  2421. b.clip_h = dh;
  2422. b.x = 0;
  2423. b.y = 0;
  2424. b.scale = ((unsigned int)dw << 16) / decoded.w;
  2425. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  2426. b.bg2 = b.bg;
  2427. b.dst_a = alpha;
  2428. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  2429. t0 = u_ticks_ms();
  2430. img_draw(&decoded, &b);
  2431. img_last_scale_ms = u_ticks_ms() - t0;
  2432. }
  2433. bi->img.format = decoded.format;
  2434. bi->img.w = (unsigned int)dw;
  2435. bi->img.h = (unsigned int)dh;
  2436. bi->img.px = px;
  2437. bi->img.alpha = alpha;
  2438. bi->img.flags = 0;
  2439. bi->state = 1;
  2440. image_pixels += (unsigned int)dw * (unsigned int)dh;
  2441. decode_arena_put();
  2442. return 0;
  2443. fail:
  2444. decode_arena_put();
  2445. return -1;
  2446. }
  2447. /* ---- URL / local path handling ---- */
  2448. static int is_http(const char *s)
  2449. {
  2450. return starts_with(s, "http://") || starts_with(s, "https://");
  2451. }
  2452. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  2453. static int normalize_abs(const char *in, char *out, unsigned int cap)
  2454. {
  2455. char seg[64];
  2456. unsigned int i = 0, o = 1;
  2457. int depth = 0;
  2458. int trailing;
  2459. if (!in || in[0] != '/' || cap < 2)
  2460. return -1;
  2461. trailing = 0;
  2462. {
  2463. unsigned int n = s_len(in);
  2464. if (n > 1 && in[n - 1] == '/')
  2465. trailing = 1;
  2466. }
  2467. out[0] = '/';
  2468. while (in[i]) {
  2469. unsigned int n = 0;
  2470. while (in[i] == '/')
  2471. i++;
  2472. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  2473. if (n + 1 < sizeof(seg))
  2474. seg[n++] = in[i];
  2475. i++;
  2476. }
  2477. seg[n] = '\0';
  2478. if (n == 0)
  2479. break;
  2480. if (s_eq(seg, "."))
  2481. continue;
  2482. if (s_eq(seg, "..")) {
  2483. if (depth > 0) {
  2484. while (o > 1 && out[o - 1] != '/')
  2485. o--;
  2486. if (o > 1)
  2487. o--;
  2488. depth--;
  2489. }
  2490. continue;
  2491. }
  2492. if (o > 1) {
  2493. if (o + 1 >= cap)
  2494. return -1;
  2495. out[o++] = '/';
  2496. }
  2497. if (o + n + 1 >= cap)
  2498. return -1;
  2499. {
  2500. unsigned int j;
  2501. for (j = 0; j < n; j++)
  2502. out[o++] = seg[j];
  2503. }
  2504. depth++;
  2505. }
  2506. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2507. if (o + 1 >= cap)
  2508. return -1;
  2509. out[o++] = '/';
  2510. }
  2511. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2512. if (in[i] == '?' || in[i] == '#') {
  2513. while (in[i]) {
  2514. if (o + 1 >= cap)
  2515. return -1;
  2516. out[o++] = in[i++];
  2517. }
  2518. }
  2519. out[o] = '\0';
  2520. return 0;
  2521. }
  2522. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2523. {
  2524. char joined[BR_URL_MAX];
  2525. if (!in || !in[0]) {
  2526. s_copy(out, cwd[0] ? cwd : "/", cap);
  2527. return;
  2528. }
  2529. if (in[0] == '/') {
  2530. if (normalize_abs(in, out, cap) != 0)
  2531. s_copy(out, in, cap);
  2532. return;
  2533. }
  2534. {
  2535. unsigned int n = 0;
  2536. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2537. s_append(joined, &n, "/", sizeof(joined));
  2538. s_append(joined, &n, in, sizeof(joined));
  2539. }
  2540. if (normalize_abs(joined, out, cap) != 0)
  2541. s_copy(out, joined, cap);
  2542. }
  2543. /* ---- canonical origin cache ---- *
  2544. *
  2545. * Sites commonly redirect http://host to https://host and then to
  2546. * https://www.host. Remember the final scheme/host of the last navigation so
  2547. * a bare domain typed again goes straight there instead of paying for two
  2548. * more connections and TLS handshakes. Only default-port requests are
  2549. * rewritten; explicit ports are left alone. */
  2550. #define ORIGIN_CACHE_MAX 8
  2551. #define ORIGIN_FILE "/share/borigins"
  2552. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2553. UHTTP_HOST_MAX + 2))
  2554. struct origin_cache_entry {
  2555. char host[UHTTP_HOST_MAX];
  2556. char origin[UHTTP_HOST_MAX + 16];
  2557. };
  2558. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2559. static int origin_count;
  2560. static char origin_buf[ORIGIN_BUF_SIZE];
  2561. static int default_port(const struct uhttp_url *u)
  2562. {
  2563. return u->secure ? u->port == 443 : u->port == 80;
  2564. }
  2565. static void url_origin(const struct uhttp_url *u, char *out,
  2566. unsigned int cap)
  2567. {
  2568. unsigned int n = 0;
  2569. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2570. s_append(out, &n, u->host, cap);
  2571. if (!default_port(u)) {
  2572. s_append(out, &n, ":", cap);
  2573. s_append_dec(out, &n, u->port, cap);
  2574. }
  2575. }
  2576. static void origin_cache_apply(char *url, unsigned int cap)
  2577. {
  2578. struct uhttp_url u;
  2579. char out[BR_URL_MAX];
  2580. unsigned int n = 0;
  2581. int i;
  2582. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2583. return;
  2584. for (i = 0; i < origin_count; i++) {
  2585. if (!s_eq(u.host, origins[i].host))
  2586. continue;
  2587. s_append(out, &n, origins[i].origin, sizeof(out));
  2588. s_append(out, &n, u.path, sizeof(out));
  2589. s_copy(url, out, cap);
  2590. return;
  2591. }
  2592. }
  2593. static void origin_cache_save(void)
  2594. {
  2595. unsigned int n = 0;
  2596. int i;
  2597. for (i = 0; i < origin_count; i++) {
  2598. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2599. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2600. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2601. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2602. }
  2603. if (n)
  2604. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2605. (int)origin_buf, (int)n);
  2606. }
  2607. static void origin_cache_load(void)
  2608. {
  2609. char *p;
  2610. int rn;
  2611. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2612. (int)(sizeof(origin_buf) - 1));
  2613. if (rn <= 0)
  2614. return;
  2615. origin_buf[rn] = '\0';
  2616. p = origin_buf;
  2617. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2618. char *line = p, *origin;
  2619. while (*p && *p != '\n')
  2620. p++;
  2621. if (*p)
  2622. *p++ = '\0';
  2623. if (!line[0])
  2624. continue;
  2625. origin = line;
  2626. while (*origin && *origin != ' ')
  2627. origin++;
  2628. if (!*origin)
  2629. continue;
  2630. *origin++ = '\0';
  2631. if (!line[0] || !is_http(origin))
  2632. continue;
  2633. {
  2634. struct uhttp_url uo;
  2635. if (uhttp_parse_url(origin, &uo) != 0 ||
  2636. !s_eq(uo.path, "/"))
  2637. continue;
  2638. }
  2639. s_copy(origins[origin_count].host, line,
  2640. sizeof(origins[origin_count].host));
  2641. s_copy(origins[origin_count].origin, origin,
  2642. sizeof(origins[origin_count].origin));
  2643. origin_count++;
  2644. }
  2645. }
  2646. static int host_is_www_of(const char *host, const char *base)
  2647. {
  2648. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2649. host[3] == '.' && s_eq(host + 4, base);
  2650. }
  2651. static void origin_cache_learn(const char *requested, const char *final)
  2652. {
  2653. struct uhttp_url from, to;
  2654. char origin[UHTTP_HOST_MAX + 16];
  2655. int i;
  2656. if (!is_http(requested) || !is_http(final))
  2657. return;
  2658. if (uhttp_parse_url(requested, &from) != 0 ||
  2659. uhttp_parse_url(final, &to) != 0)
  2660. return;
  2661. if (!default_port(&from))
  2662. return;
  2663. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2664. from.port == to.port)
  2665. return;
  2666. /* Only remember origin-level canonicalisation: the same path, and
  2667. * either the same host or its www./apex sibling. A path- or
  2668. * host-specific redirect (a shortener, a login page) must not poison
  2669. * every request to the typed host. */
  2670. if (!s_eq(from.path, to.path))
  2671. return;
  2672. if (!s_eq(from.host, to.host) &&
  2673. !host_is_www_of(to.host, from.host) &&
  2674. !host_is_www_of(from.host, to.host))
  2675. return;
  2676. url_origin(&to, origin, sizeof(origin));
  2677. for (i = 0; i < origin_count; i++) {
  2678. if (s_eq(origins[i].host, from.host)) {
  2679. if (!s_eq(origins[i].origin, origin)) {
  2680. s_copy(origins[i].origin, origin,
  2681. sizeof(origins[i].origin));
  2682. origin_cache_save();
  2683. }
  2684. return;
  2685. }
  2686. }
  2687. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2688. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2689. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2690. origin_cache_save();
  2691. }
  2692. static int path_dir(const char *path, char *out, unsigned int cap)
  2693. {
  2694. unsigned int i, last = 0;
  2695. for (i = 0; path[i]; i++)
  2696. if (path[i] == '/')
  2697. last = i;
  2698. if (last == 0) {
  2699. if (cap < 2)
  2700. return -1;
  2701. out[0] = '/';
  2702. out[1] = '\0';
  2703. return 0;
  2704. }
  2705. if (last + 1 >= cap)
  2706. return -1;
  2707. {
  2708. unsigned int j;
  2709. for (j = 0; j < last; j++)
  2710. out[j] = path[j];
  2711. out[last] = '\0';
  2712. }
  2713. return 0;
  2714. }
  2715. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2716. static int resolve_link(const char *base, const char *href, char *out,
  2717. unsigned int cap)
  2718. {
  2719. static char joined[BR_URL_MAX]; /* leaf: off the stack */
  2720. if (!href || !href[0] || href[0] == '#')
  2721. return -1;
  2722. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2723. starts_with(href, "data:") || starts_with(href, "tel:"))
  2724. return -1;
  2725. if (starts_with(href, "about:")) {
  2726. s_copy(out, href, cap);
  2727. return 0;
  2728. }
  2729. if (is_http(href)) {
  2730. s_copy(out, href, cap);
  2731. return 0;
  2732. }
  2733. if (starts_with(href, "//")) {
  2734. if (is_http(base)) {
  2735. unsigned int n = 0;
  2736. s_append(out, &n, starts_with(base, "https:") ?
  2737. "https:" : "http:", cap);
  2738. s_append(out, &n, href, cap);
  2739. return 0;
  2740. }
  2741. return -1;
  2742. }
  2743. if (is_http(base)) {
  2744. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2745. }
  2746. /* local page */
  2747. if (href[0] == '/') {
  2748. if (normalize_abs(href, out, cap) != 0)
  2749. return -1;
  2750. return 0;
  2751. }
  2752. {
  2753. static char dir[BR_URL_MAX];
  2754. unsigned int n = 0;
  2755. if (s_eq(base, "about:home"))
  2756. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2757. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2758. s_copy(dir, "/", sizeof(dir));
  2759. s_append(joined, &n, dir, sizeof(joined));
  2760. if (n == 0 || joined[n - 1] != '/')
  2761. s_append(joined, &n, "/", sizeof(joined));
  2762. s_append(joined, &n, href, sizeof(joined));
  2763. }
  2764. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2765. }
  2766. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2767. * rest instead of failing when a page or stylesheet is larger than the
  2768. * buffer. The stream is still walked to the end, so a normal page is
  2769. * verified; a truncated compressed input still returns whatever was decoded
  2770. * so far. */
  2771. struct trunc_buf {
  2772. unsigned char *dst;
  2773. unsigned int cap, pos;
  2774. int full;
  2775. };
  2776. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2777. {
  2778. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2779. if (len > m->cap - m->pos) {
  2780. unsigned int room = m->cap - m->pos;
  2781. if (room) {
  2782. unsigned int i;
  2783. for (i = 0; i < room; i++)
  2784. m->dst[m->pos + i] = data[i];
  2785. m->pos += room;
  2786. }
  2787. m->full = 1;
  2788. return 0;
  2789. }
  2790. {
  2791. unsigned int i;
  2792. for (i = 0; i < len; i++)
  2793. m->dst[m->pos + i] = data[i];
  2794. }
  2795. m->pos += len;
  2796. return 0;
  2797. }
  2798. static void worker_wait_ui(void);
  2799. static void inflate_ui_pump(void *ctx)
  2800. {
  2801. static unsigned int last;
  2802. unsigned int now = u_ticks_ms();
  2803. (void)ctx;
  2804. if ((int)(now - last) >= 50) {
  2805. last = now;
  2806. worker_wait_ui();
  2807. }
  2808. }
  2809. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2810. unsigned char *dst, unsigned int cap,
  2811. unsigned int *outlen, int gzip, int *truncated)
  2812. {
  2813. struct inflate_src in;
  2814. struct inflate_sink sink;
  2815. struct trunc_buf m;
  2816. unsigned int got = 0;
  2817. int r;
  2818. in.p = src;
  2819. in.len = len;
  2820. in.more = 0;
  2821. in.ctx = 0;
  2822. m.dst = dst;
  2823. m.cap = cap;
  2824. m.pos = 0;
  2825. m.full = 0;
  2826. sink.write = trunc_write;
  2827. sink.ctx = &m;
  2828. inflate_init(&image_inflate_ws, &in, &sink);
  2829. image_inflate_ws.progress = inflate_ui_pump;
  2830. image_inflate_ws.progress_ctx = 0;
  2831. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2832. inflate_zlib(&image_inflate_ws, &got);
  2833. *outlen = m.pos;
  2834. *truncated = m.full || r != 0;
  2835. if (r != 0 && m.pos == 0)
  2836. return -1;
  2837. return 0;
  2838. }
  2839. /* ---- headless fetch workers ------------------------------------------ *
  2840. *
  2841. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2842. * writes the raw response, a small metadata file and a done marker under
  2843. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2844. * or a multi-megabyte body never freezes the UI and images download in
  2845. * parallel.
  2846. */
  2847. struct fetch_meta {
  2848. int status;
  2849. int error;
  2850. int trunc;
  2851. unsigned int len;
  2852. unsigned int open_ms;
  2853. unsigned int first_ms;
  2854. unsigned int total_ms;
  2855. /* Optional decoded bitmap produced by the helper (image jobs). */
  2856. unsigned int dw, dh, nw, nh;
  2857. unsigned int alpha;
  2858. unsigned int px_len;
  2859. unsigned int dec_ms;
  2860. int dec_err;
  2861. char encoding[16];
  2862. char ctype[64];
  2863. char final[BR_URL_MAX];
  2864. };
  2865. static void draw(unsigned int *action);
  2866. static void handle_keys(unsigned int *action);
  2867. static void handle_page_click(unsigned int *action);
  2868. #define FETCH_WORKERS 4
  2869. #define FETCH_PATH_MAX 32
  2870. /* One long-lived curl __serve helper per worker. Each worker has its own
  2871. * request/body/meta/done files under /share so several downloads can be in
  2872. * flight at once; the keep-alive connection stays in the helper process, so
  2873. * tls.c's per-process state remains valid. */
  2874. struct fetch_worker {
  2875. int pid;
  2876. int slot;
  2877. int busy;
  2878. int ready;
  2879. int image_job;
  2880. unsigned int seq;
  2881. unsigned int deadline;
  2882. int retried;
  2883. unsigned int dec_w, dec_h;
  2884. int dec_retried;
  2885. char req[FETCH_PATH_MAX];
  2886. char body[FETCH_PATH_MAX];
  2887. char meta[FETCH_PATH_MAX];
  2888. char done[FETCH_PATH_MAX];
  2889. char post[FETCH_PATH_MAX];
  2890. char px[FETCH_PATH_MAX];
  2891. /* Optional preload job attached to this worker. */
  2892. unsigned int node;
  2893. int bg;
  2894. char url[BR_URL_MAX];
  2895. struct fetch_meta m;
  2896. };
  2897. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2898. static int fetch_tty = -2;
  2899. static void fetch_tty_drain(void);
  2900. static unsigned int fetch_session;
  2901. static unsigned int fetch_seq;
  2902. static struct fetch_meta fetch_meta;
  2903. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2904. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2905. static int fetch_last_error;
  2906. static unsigned int meta_uint(char **pp)
  2907. {
  2908. char *p = *pp;
  2909. unsigned int v = 0;
  2910. while (*p >= '0' && *p <= '9') {
  2911. v = v * 10 + (unsigned int)(*p - '0');
  2912. p++;
  2913. }
  2914. while (*p && *p != '\n')
  2915. p++;
  2916. if (*p == '\n')
  2917. p++;
  2918. *pp = p;
  2919. return v;
  2920. }
  2921. static void meta_str(char **pp, char *out, unsigned int cap)
  2922. {
  2923. char *p = *pp;
  2924. unsigned int n = 0;
  2925. while (*p && *p != '\n' && n + 1 < cap)
  2926. out[n++] = *p++;
  2927. out[n] = '\0';
  2928. while (*p && *p != '\n')
  2929. p++;
  2930. if (*p == '\n')
  2931. p++;
  2932. *pp = p;
  2933. }
  2934. static void worker_wait_ui(void)
  2935. {
  2936. unsigned int action = 0;
  2937. if (!ngui_begin(&ui))
  2938. return;
  2939. draw(&action);
  2940. handle_keys(&action);
  2941. handle_page_click(&action);
  2942. if (action & ACT_WAIT_NAV) {
  2943. pending_action |= action & ACT_WAIT_NAV;
  2944. if ((action & ACT_NAV) && click_url[0])
  2945. s_copy(pending_url, click_url, sizeof(pending_url));
  2946. click_url[0] = '\0';
  2947. cancel_fetch = 1;
  2948. }
  2949. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  2950. ngui_invalidate(&ui);
  2951. ngui_end(&ui);
  2952. }
  2953. static void fetch_path(char *out, unsigned int cap, const char *kind,
  2954. unsigned int session, int slot)
  2955. {
  2956. unsigned int n = 0;
  2957. s_append(out, &n, "/share/bf", cap);
  2958. s_append_dec(out, &n, session, cap);
  2959. s_append(out, &n, "_", cap);
  2960. s_append_dec(out, &n, (unsigned int)slot, cap);
  2961. s_append(out, &n, kind, cap);
  2962. }
  2963. static void fetch_pool_init(void)
  2964. {
  2965. static int ready;
  2966. int i;
  2967. if (ready)
  2968. return;
  2969. ready = 1;
  2970. fetch_session = ((unsigned int)u_getpid() << 16) ^
  2971. (u_ticks_ms() & 0xFFFFu);
  2972. if (!fetch_session)
  2973. fetch_session = 1;
  2974. for (i = 0; i < FETCH_WORKERS; i++) {
  2975. struct fetch_worker *w = &fetch_workers[i];
  2976. w->pid = -1;
  2977. w->slot = i;
  2978. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  2979. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  2980. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  2981. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  2982. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  2983. fetch_path(w->px, sizeof(w->px), "px", fetch_session, i);
  2984. }
  2985. }
  2986. static void fetch_worker_stop(struct fetch_worker *w)
  2987. {
  2988. int i;
  2989. /* An abandoned image job leaves its node loadable again. */
  2990. if (w->busy && w->image_job && w->node < doc.nnode) {
  2991. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  2992. doc.nodes[w->node].bg_img_index = -1;
  2993. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  2994. doc.nodes[w->node].img_index = -1;
  2995. }
  2996. if (w->pid > 0) {
  2997. u_kill((unsigned int)w->pid);
  2998. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  2999. u_sleep_ms(5);
  3000. /* Let the reaper close the socket before we reuse the slot. */
  3001. u_sleep_ms(10);
  3002. }
  3003. w->pid = -1;
  3004. w->busy = 0;
  3005. w->ready = 0;
  3006. w->image_job = 0;
  3007. if (w->req[0]) {
  3008. u_syscall1(SYS_UNLINK, (int)w->done);
  3009. u_syscall1(SYS_UNLINK, (int)w->meta);
  3010. u_syscall1(SYS_UNLINK, (int)w->body);
  3011. u_syscall1(SYS_UNLINK, (int)w->post);
  3012. u_syscall1(SYS_UNLINK, (int)w->req);
  3013. }
  3014. }
  3015. static void fetch_workers_stop_all(void)
  3016. {
  3017. int i;
  3018. for (i = 0; i < FETCH_WORKERS; i++)
  3019. fetch_worker_stop(&fetch_workers[i]);
  3020. }
  3021. /* Abandon the transfers of the current page but keep idle helpers and their
  3022. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  3023. * because its response would otherwise land in a reused /share slot. */
  3024. static void fetch_workers_cancel_busy(void)
  3025. {
  3026. int i;
  3027. for (i = 0; i < FETCH_WORKERS; i++)
  3028. if (fetch_workers[i].busy)
  3029. fetch_worker_stop(&fetch_workers[i]);
  3030. }
  3031. static void fetch_workers_prepare_nav(const char *url)
  3032. {
  3033. int i;
  3034. (void)url;
  3035. for (i = 0; i < FETCH_WORKERS; i++) {
  3036. struct fetch_worker *w = &fetch_workers[i];
  3037. if (w->pid <= 0)
  3038. continue;
  3039. /* Only an in-flight transfer must be aborted. Idle helpers
  3040. * stay warm across origins: there are just FETCH_WORKERS of
  3041. * them, and uhttp_open drops the old connection when the
  3042. * next job is for another host. Killing and respawning all
  3043. * four on every navigation churned processes and sockets
  3044. * while images were still loading. */
  3045. if (w->busy)
  3046. fetch_worker_stop(w);
  3047. }
  3048. }
  3049. /* The browser is no longer the active window and no fetch is running: give
  3050. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  3051. static void fetch_workers_stop_if_unfocused(void)
  3052. {
  3053. int i;
  3054. fetch_tty_drain();
  3055. if (ui.focused || page_loading || preload_active)
  3056. return;
  3057. for (i = 0; i < FETCH_WORKERS; i++)
  3058. if (fetch_workers[i].pid > 0) {
  3059. fetch_workers_stop_all();
  3060. return;
  3061. }
  3062. }
  3063. /* The helpers (and this process, since u_tty_create() rebinds our own
  3064. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  3065. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  3066. * a dozen TLS connections every helper hung in its next log line, so the
  3067. * following cross-origin navigation sat at "Loading..." until it timed out.
  3068. * Drain and discard it from every wait/poll loop. */
  3069. static void fetch_tty_drain(void)
  3070. {
  3071. char sink[512];
  3072. int i;
  3073. if (fetch_tty <= 0)
  3074. return;
  3075. for (i = 0; i < 16; i++)
  3076. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  3077. break;
  3078. }
  3079. static int fetch_worker_start(struct fetch_worker *w, char *err,
  3080. unsigned int errcap)
  3081. {
  3082. char arg[40];
  3083. unsigned int n = 0;
  3084. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  3085. return 0;
  3086. w->pid = -1;
  3087. fetch_pool_init();
  3088. if (fetch_tty == -2) {
  3089. int t = u_tty_create();
  3090. fetch_tty = t > 0 ? t : 0;
  3091. }
  3092. s_append(arg, &n, "__serve ", sizeof(arg));
  3093. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  3094. s_append(arg, &n, " ", sizeof(arg));
  3095. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  3096. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  3097. if (w->pid <= 0) {
  3098. w->pid = -1;
  3099. s_copy(err, "cannot start network helper", errcap);
  3100. return -1;
  3101. }
  3102. return 0;
  3103. }
  3104. static struct fetch_worker *fetch_worker_alloc(void)
  3105. {
  3106. int i;
  3107. fetch_pool_init();
  3108. for (i = 0; i < FETCH_WORKERS; i++)
  3109. if (!fetch_workers[i].busy)
  3110. return &fetch_workers[i];
  3111. return 0;
  3112. }
  3113. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3114. unsigned int cap, const char *method,
  3115. const char *ctype, const char *post,
  3116. unsigned int post_len, unsigned int node,
  3117. int bg, unsigned int dec_w,
  3118. unsigned int dec_h, char *err,
  3119. unsigned int errcap);
  3120. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  3121. unsigned int cap, const char *post,
  3122. unsigned int post_len, unsigned int node,
  3123. int bg, char *err, unsigned int errcap)
  3124. {
  3125. /* A body pointer with no bytes is still a POST: the classic request
  3126. * line would turn it into a GET. */
  3127. if (post && !post_len)
  3128. return fetch_worker_submit_req(w, url, cap, "POST",
  3129. "application/x-www-form-urlencoded", post, 0, node,
  3130. bg, 0, 0, err, errcap);
  3131. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  3132. node, bg, 0, 0, err, errcap);
  3133. }
  3134. /* Image job: ask the helper to decode at these display bounds as well. */
  3135. static int fetch_worker_submit_image(struct fetch_worker *w, const char *url,
  3136. unsigned int cap, unsigned int node,
  3137. int bg, unsigned int dec_w,
  3138. unsigned int dec_h, char *err,
  3139. unsigned int errcap)
  3140. {
  3141. return fetch_worker_submit_req(w, url, cap, 0, 0, 0, 0, node, bg,
  3142. dec_w, dec_h, err, errcap);
  3143. }
  3144. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  3145. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  3146. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3147. unsigned int cap, const char *method,
  3148. const char *ctype, const char *post,
  3149. unsigned int post_len, unsigned int node,
  3150. int bg, unsigned int dec_w,
  3151. unsigned int dec_h, char *err,
  3152. unsigned int errcap)
  3153. {
  3154. static char req[BR_URL_MAX + 256];
  3155. unsigned int n = 0;
  3156. fetch_seq++;
  3157. if (!fetch_seq)
  3158. fetch_seq = 1;
  3159. w->seq = fetch_seq;
  3160. w->ready = 0;
  3161. w->image_job = 0;
  3162. w->retried = 0;
  3163. w->m.error = 0;
  3164. w->node = node;
  3165. w->bg = bg;
  3166. w->dec_w = dec_w;
  3167. w->dec_h = dec_h;
  3168. w->dec_retried = 0;
  3169. s_copy(w->url, url, sizeof(w->url));
  3170. s_append_dec(req, &n, w->seq, sizeof(req));
  3171. s_append(req, &n, " ", sizeof(req));
  3172. s_append_dec(req, &n, cap, sizeof(req));
  3173. s_append(req, &n, " ", sizeof(req));
  3174. if (dec_w || dec_h) {
  3175. s_append(req, &n, "D ", sizeof(req));
  3176. s_append_dec(req, &n, dec_w, sizeof(req));
  3177. s_append(req, &n, " ", sizeof(req));
  3178. s_append_dec(req, &n, dec_h, sizeof(req));
  3179. s_append(req, &n, " ", sizeof(req));
  3180. } else if (method) {
  3181. unsigned int k;
  3182. s_append(req, &n, "X ", sizeof(req));
  3183. s_append(req, &n, method, sizeof(req));
  3184. s_append(req, &n, " ", sizeof(req));
  3185. s_append_dec(req, &n, post_len, sizeof(req));
  3186. s_append(req, &n, " ", sizeof(req));
  3187. if (!ctype || !ctype[0])
  3188. s_append(req, &n, "-", sizeof(req));
  3189. /* One token on the request line: drop the spaces
  3190. * ("application/json; charset=utf-8" stays valid). */
  3191. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  3192. if (ctype[k] != ' ')
  3193. req[n++] = ctype[k];
  3194. req[n] = '\0';
  3195. s_append(req, &n, " ", sizeof(req));
  3196. } else if (post_len) {
  3197. s_append(req, &n, "POST ", sizeof(req));
  3198. s_append_dec(req, &n, post_len, sizeof(req));
  3199. s_append(req, &n, " ", sizeof(req));
  3200. }
  3201. s_append(req, &n, url, sizeof(req));
  3202. s_append(req, &n, "\n", sizeof(req));
  3203. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  3204. (int)post, (int)post_len) < 0) {
  3205. s_copy(err, "cannot queue form body", errcap);
  3206. return -1;
  3207. }
  3208. u_syscall1(SYS_UNLINK, (int)w->done);
  3209. u_syscall1(SYS_UNLINK, (int)w->meta);
  3210. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  3211. s_copy(err, "cannot queue network request", errcap);
  3212. return -1;
  3213. }
  3214. if (fetch_worker_start(w, err, errcap) != 0)
  3215. return -1;
  3216. w->busy = 1;
  3217. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  3218. return 0;
  3219. }
  3220. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  3221. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  3222. unsigned int errcap)
  3223. {
  3224. static char meta[BR_URL_MAX + 1024];
  3225. char *p;
  3226. int rn, mseq;
  3227. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  3228. (int)(sizeof(meta) - 1));
  3229. if (rn <= 0) {
  3230. s_copy(err, "network helper failed", errcap);
  3231. return -1;
  3232. }
  3233. meta[rn] = '\0';
  3234. p = meta;
  3235. mseq = (int)meta_uint(&p);
  3236. if (mseq != (int)w->seq) {
  3237. s_copy(err, "stale network response", errcap);
  3238. return -1;
  3239. }
  3240. w->m.status = (int)meta_uint(&p);
  3241. w->m.error = (int)meta_uint(&p);
  3242. w->m.trunc = (int)meta_uint(&p);
  3243. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  3244. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  3245. meta_str(&p, w->m.final, sizeof(w->m.final));
  3246. w->m.len = meta_uint(&p);
  3247. w->m.open_ms = 0;
  3248. w->m.first_ms = 0;
  3249. w->m.total_ms = 0;
  3250. if (*p) {
  3251. w->m.open_ms = meta_uint(&p);
  3252. w->m.first_ms = meta_uint(&p);
  3253. w->m.total_ms = meta_uint(&p);
  3254. }
  3255. w->m.dw = w->m.dh = w->m.nw = w->m.nh = 0;
  3256. w->m.alpha = w->m.px_len = w->m.dec_ms = 0;
  3257. w->m.dec_err = 0;
  3258. if (*p) {
  3259. w->m.dw = meta_uint(&p);
  3260. w->m.dh = meta_uint(&p);
  3261. w->m.nw = meta_uint(&p);
  3262. w->m.nh = meta_uint(&p);
  3263. w->m.alpha = meta_uint(&p);
  3264. w->m.px_len = meta_uint(&p);
  3265. w->m.dec_err = (int)meta_uint(&p);
  3266. w->m.dec_ms = meta_uint(&p);
  3267. }
  3268. if (w->m.error) {
  3269. s_copy(err, uhttp_error_string(w->m.error), errcap);
  3270. return -1;
  3271. }
  3272. w->ready = 1;
  3273. return 0;
  3274. }
  3275. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  3276. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  3277. unsigned int errcap)
  3278. {
  3279. static char done[24];
  3280. char *p;
  3281. int rn, mseq;
  3282. fetch_tty_drain();
  3283. if (!w->busy)
  3284. return -1;
  3285. if (w->ready)
  3286. return 1;
  3287. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  3288. (int)(sizeof(done) - 1));
  3289. if (rn > 0) {
  3290. done[rn] = '\0';
  3291. p = done;
  3292. mseq = (int)meta_uint(&p);
  3293. if (mseq == (int)w->seq) {
  3294. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  3295. fetch_worker_stop(w);
  3296. return -1;
  3297. }
  3298. return 1;
  3299. }
  3300. }
  3301. if (!u_alive((unsigned int)w->pid)) {
  3302. w->pid = -1;
  3303. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  3304. w->retried = 1;
  3305. return 0;
  3306. }
  3307. s_copy(err, "network helper stopped", errcap);
  3308. fetch_worker_stop(w);
  3309. return -1;
  3310. }
  3311. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  3312. s_copy(err, "network request timed out", errcap);
  3313. fetch_worker_stop(w);
  3314. return -1;
  3315. }
  3316. return 0;
  3317. }
  3318. /* Copy the completed body, inflating it if the server ignored our identity
  3319. * request. Mirrors the old fetch_remote body path. */
  3320. static int fetch_worker_read_body(struct fetch_worker *w,
  3321. unsigned char *plain,
  3322. unsigned int plaincap,
  3323. unsigned char *comp,
  3324. unsigned int compcap,
  3325. int *truncated, char *err,
  3326. unsigned int errcap)
  3327. {
  3328. int rv, zr, was_trunc;
  3329. if (contains_ci(w->m.encoding, "gzip") ||
  3330. contains_ci(w->m.encoding, "deflate")) {
  3331. unsigned int comp_len = 0, plen = 0;
  3332. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  3333. (int)compcap);
  3334. if (rv < 0) {
  3335. s_copy(err, "empty response", errcap);
  3336. return -1;
  3337. }
  3338. comp_len = (unsigned int)rv;
  3339. if (comp_len < w->m.len) {
  3340. s_copy(err, "compressed response is too large", errcap);
  3341. return -1;
  3342. }
  3343. if (contains_ci(w->m.encoding, "deflate"))
  3344. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3345. &plen, 0, &was_trunc);
  3346. else
  3347. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3348. &plen, 1, &was_trunc);
  3349. if (zr != 0) {
  3350. s_copy(err, "compressed response is corrupt", errcap);
  3351. return -1;
  3352. }
  3353. *truncated = w->m.trunc || was_trunc;
  3354. return (int)plen;
  3355. }
  3356. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  3357. if (rv < 0) {
  3358. s_copy(err, "empty response", errcap);
  3359. return -1;
  3360. }
  3361. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  3362. return rv;
  3363. }
  3364. static void fetch_worker_release(struct fetch_worker *w)
  3365. {
  3366. u_syscall1(SYS_UNLINK, (int)w->done);
  3367. u_syscall1(SYS_UNLINK, (int)w->meta);
  3368. u_syscall1(SYS_UNLINK, (int)w->body);
  3369. u_syscall1(SYS_UNLINK, (int)w->post);
  3370. u_syscall1(SYS_UNLINK, (int)w->px);
  3371. u_syscall1(SYS_UNLINK, (int)w->req);
  3372. w->busy = 0;
  3373. w->ready = 0;
  3374. w->image_job = 0;
  3375. w->dec_w = 0;
  3376. w->dec_h = 0;
  3377. w->dec_retried = 0;
  3378. }
  3379. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  3380. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  3381. unsigned int errcap)
  3382. {
  3383. for (;;) {
  3384. int rv;
  3385. if (!fetch_wait_passive)
  3386. worker_wait_ui();
  3387. if (cancel_fetch || pending_action) {
  3388. fetch_workers_cancel_busy();
  3389. return FETCH_ABORT;
  3390. }
  3391. rv = fetch_worker_poll(w, err, errcap);
  3392. if (rv != 0)
  3393. return rv == 1 ? 0 : -1;
  3394. u_sleep_ms(10);
  3395. }
  3396. }
  3397. static int fetch_remote(const char *url, unsigned int cap,
  3398. const char *post, unsigned int post_len,
  3399. unsigned char *plain, unsigned int plaincap,
  3400. unsigned char *comp, unsigned int compcap,
  3401. struct fetch_meta *m, int *truncated,
  3402. char *err, unsigned int errcap)
  3403. {
  3404. struct fetch_worker *w = fetch_worker_alloc();
  3405. int rv;
  3406. fetch_last_error = 0;
  3407. if (!w) {
  3408. s_copy(err, "network busy", errcap);
  3409. return -1;
  3410. }
  3411. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  3412. err, errcap) != 0) {
  3413. fetch_worker_release(w);
  3414. return -1;
  3415. }
  3416. rv = fetch_worker_wait(w, err, errcap);
  3417. if (rv == FETCH_ABORT) {
  3418. fetch_worker_release(w);
  3419. return FETCH_ABORT;
  3420. }
  3421. if (rv != 0) {
  3422. fetch_last_error = w->m.error;
  3423. fetch_worker_release(w);
  3424. return -1;
  3425. }
  3426. *m = w->m;
  3427. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  3428. truncated, err, errcap);
  3429. fetch_worker_release(w);
  3430. if (rv >= 0 && (cancel_fetch || pending_action))
  3431. return FETCH_ABORT;
  3432. return rv;
  3433. }
  3434. static int fetch_worker_status(const struct fetch_worker *w)
  3435. {
  3436. return w->m.status;
  3437. }
  3438. /* fetch()/XHR through a helper: one request, the status and body come back
  3439. * whatever the HTTP status (a 401 is an answer, not a network error). */
  3440. static int js_worker_http(const char *method, const char *url,
  3441. const char *ctype, const char *body,
  3442. unsigned int body_len, struct js_http_resp *r,
  3443. char *err, int errcap)
  3444. {
  3445. struct fetch_worker *w = fetch_worker_alloc();
  3446. unsigned char *plain;
  3447. int rv, tr = 0;
  3448. if (!w) {
  3449. s_copy(err, "network busy", (unsigned int)errcap);
  3450. return -1;
  3451. }
  3452. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  3453. body_len, 0, 0, 0, 0, err,
  3454. (unsigned int)errcap) != 0) {
  3455. fetch_worker_release(w);
  3456. return -1;
  3457. }
  3458. fetch_wait_passive++;
  3459. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  3460. fetch_wait_passive--;
  3461. if (rv != 0) {
  3462. if (rv == FETCH_ABORT)
  3463. s_copy(err, "page is navigating", (unsigned int)errcap);
  3464. fetch_worker_release(w);
  3465. return -1;
  3466. }
  3467. r->status = w->m.status;
  3468. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  3469. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  3470. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  3471. if (!plain) {
  3472. fetch_worker_release(w);
  3473. s_copy(err, "out of memory", (unsigned int)errcap);
  3474. return -1;
  3475. }
  3476. if (w->m.len == 0) {
  3477. rv = 0; /* 204, an empty 200: no body file */
  3478. } else {
  3479. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  3480. image_io_buf, BR_PAGE_COMP_MAX,
  3481. &tr, err, (unsigned int)errcap);
  3482. }
  3483. fetch_worker_release(w);
  3484. if (rv < 0) {
  3485. free(plain);
  3486. return -1;
  3487. }
  3488. plain[rv] = '\0';
  3489. r->body = (char *)plain;
  3490. r->len = (unsigned int)rv;
  3491. return 0;
  3492. }
  3493. /* ---- HTTP / file fetch ---- */
  3494. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  3495. unsigned int *outlen, int *is_local, char *ctype,
  3496. unsigned int ctcap, char *final, unsigned int finalcap,
  3497. char *err, unsigned int errcap, int *truncated,
  3498. const char *post, unsigned int post_len)
  3499. {
  3500. unsigned char *buf;
  3501. unsigned int len;
  3502. int tr = 0;
  3503. int rv;
  3504. *out = 0;
  3505. *outlen = 0;
  3506. *truncated = 0;
  3507. if (final && finalcap)
  3508. final[0] = '\0';
  3509. if (ctype && ctcap)
  3510. ctype[0] = '\0';
  3511. if (url[0] == '/') {
  3512. char pathbuf[BR_URL_MAX];
  3513. const char *open_url = url;
  3514. unsigned int i = 0;
  3515. /* A local form GET keeps ?query in the address bar but the
  3516. * file lookup uses the path alone, like a real browser. */
  3517. while (url[i] && url[i] != '?' && url[i] != '#')
  3518. i++;
  3519. if (url[i]) {
  3520. s_copy(pathbuf, url, i + 1);
  3521. open_url = pathbuf;
  3522. }
  3523. buf = (unsigned char *)malloc(cap);
  3524. if (!buf) {
  3525. s_copy(err, "out of memory", errcap);
  3526. return -1;
  3527. }
  3528. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  3529. if (rv < 0) {
  3530. free(buf);
  3531. s_copy(err, "file not found", errcap);
  3532. return -1;
  3533. }
  3534. *out = buf;
  3535. *outlen = (unsigned int)rv;
  3536. *is_local = 1;
  3537. if (ctype)
  3538. s_copy(ctype, "text/html", ctcap);
  3539. if (final)
  3540. s_copy(final, url, finalcap);
  3541. if ((unsigned int)rv == cap)
  3542. *truncated = 1;
  3543. return 0;
  3544. }
  3545. buf = (unsigned char *)malloc(cap);
  3546. if (!buf) {
  3547. s_copy(err, "out of memory", errcap);
  3548. return -1;
  3549. }
  3550. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3551. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3552. if (rv == FETCH_ABORT) {
  3553. free(buf);
  3554. return FETCH_ABORT;
  3555. }
  3556. if (rv < 0) {
  3557. free(buf);
  3558. return -1;
  3559. }
  3560. len = (unsigned int)rv;
  3561. if (len == 0) {
  3562. free(buf);
  3563. s_copy(err, "empty response", errcap);
  3564. return -1;
  3565. }
  3566. if (ctype)
  3567. s_copy(ctype, fetch_meta.ctype, ctcap);
  3568. if (final && fetch_meta.final[0])
  3569. s_copy(final, fetch_meta.final, finalcap);
  3570. *is_local = 0;
  3571. *out = buf;
  3572. *outlen = len;
  3573. *truncated = tr;
  3574. return 0;
  3575. }
  3576. /* Load every @font-face the parser registered. Local files go through
  3577. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  3578. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  3579. * to the built-in regular/bold/italic/mono set. */
  3580. static void load_font_faces(void)
  3581. {
  3582. unsigned int i;
  3583. memset(font_faces, 0, sizeof(font_faces));
  3584. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  3585. i <= BR_MAX_FACES; i++) {
  3586. const char *url = br_font_face_url((int)i);
  3587. const char *base = br_font_face_base((int)i);
  3588. char abs[BR_URL_MAX];
  3589. if (!url || !url[0])
  3590. continue;
  3591. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  3592. sizeof(abs)) != 0)
  3593. continue;
  3594. if (abs[0] == '/') {
  3595. font_faces[i - 1] = ufont_face_open_path(abs);
  3596. } else if (is_http(abs)) {
  3597. unsigned char *buf;
  3598. char err[64];
  3599. int rv, tr = 0;
  3600. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  3601. if (!buf)
  3602. continue;
  3603. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3604. UFONT_MAX_FILE, image_io_buf,
  3605. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  3606. err, sizeof(err));
  3607. if (rv > 0)
  3608. font_faces[i - 1] = ufont_face_open_mem(buf,
  3609. rv);
  3610. free(buf);
  3611. }
  3612. }
  3613. }
  3614. /* Remote scripts are cached under /share for the current boot, like the
  3615. * stylesheet cache, so reloads and later visits skip the network. */
  3616. static int script_cache_count;
  3617. static unsigned int script_cache_hash(const char *s)
  3618. {
  3619. unsigned int h = 2166136261u;
  3620. while (*s) {
  3621. h ^= (unsigned char)*s++;
  3622. h *= 16777619u;
  3623. }
  3624. return h;
  3625. }
  3626. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3627. {
  3628. unsigned int n = 0;
  3629. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3630. s_append_dec(out, &n, script_cache_hash(url), cap);
  3631. }
  3632. static void script_cache_clear(void)
  3633. {
  3634. struct sys_dirent d;
  3635. char path[96];
  3636. for (;;) {
  3637. int i, found = 0;
  3638. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3639. (int)&d) == 1; i++) {
  3640. unsigned int n = 0;
  3641. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3642. continue;
  3643. s_append(path, &n, "/share/", sizeof(path));
  3644. s_append(path, &n, d.name, sizeof(path));
  3645. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3646. return;
  3647. found = 1;
  3648. break;
  3649. }
  3650. if (!found)
  3651. break;
  3652. }
  3653. script_cache_count = 0;
  3654. }
  3655. static void script_cache_init(void)
  3656. {
  3657. struct sys_dirent d;
  3658. int i, count = 0;
  3659. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3660. (int)&d) == 1; i++)
  3661. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3662. count++;
  3663. if (count >= SCRIPT_CACHE_MAX) {
  3664. script_cache_clear();
  3665. return;
  3666. }
  3667. script_cache_count = count;
  3668. }
  3669. static int script_cache_get(const char *url, unsigned char **out,
  3670. unsigned int *outlen)
  3671. {
  3672. char path[96];
  3673. struct sys_stat st;
  3674. unsigned char *buf;
  3675. int rn;
  3676. script_cache_path(url, path, sizeof(path));
  3677. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3678. st.size >= SCRIPT_CACHE_FILE_MAX)
  3679. return 0;
  3680. buf = (unsigned char *)malloc(st.size + 1);
  3681. if (!buf)
  3682. return 0;
  3683. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3684. if (rn != (int)st.size) {
  3685. free(buf);
  3686. return 0;
  3687. }
  3688. buf[st.size] = '\0';
  3689. *out = buf;
  3690. *outlen = st.size;
  3691. return 1;
  3692. }
  3693. static void script_cache_put(const char *url, const unsigned char *data,
  3694. unsigned int len)
  3695. {
  3696. char path[96];
  3697. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3698. len >= SCRIPT_CACHE_FILE_MAX)
  3699. return;
  3700. script_cache_path(url, path, sizeof(path));
  3701. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3702. (int)len) >= 0)
  3703. script_cache_count++;
  3704. }
  3705. static int script_cache_has(const char *url)
  3706. {
  3707. char path[96];
  3708. struct sys_stat st;
  3709. script_cache_path(url, path, sizeof(path));
  3710. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3711. st.size < SCRIPT_CACHE_FILE_MAX;
  3712. }
  3713. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3714. static int fetch_script_text(const char *url, unsigned char **out,
  3715. unsigned int *outlen, char *err,
  3716. unsigned int errcap)
  3717. {
  3718. unsigned char *buf;
  3719. unsigned int len;
  3720. int local, truncated = 0;
  3721. char ctype[64], final[BR_URL_MAX];
  3722. int rv;
  3723. *out = 0;
  3724. *outlen = 0;
  3725. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3726. return 0;
  3727. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3728. sizeof(ctype), final, sizeof(final), err, errcap,
  3729. &truncated, 0, 0);
  3730. if (rv != 0)
  3731. return rv;
  3732. if (truncated || len >= BR_SCRIPT_MAX) {
  3733. free(buf);
  3734. s_copy(err, "script is too large", errcap);
  3735. return -1;
  3736. }
  3737. buf[len] = '\0';
  3738. if (!local)
  3739. script_cache_put(url, buf, len);
  3740. *out = buf;
  3741. *outlen = len;
  3742. return 0;
  3743. }
  3744. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  3745. * the heap, so images must not allocate their file body from it as well. */
  3746. static int fetch_image(const char *url, unsigned int cap,
  3747. unsigned char **out, unsigned int *outlen,
  3748. char *err, unsigned int errcap)
  3749. {
  3750. unsigned int len;
  3751. int tr = 0;
  3752. int rv;
  3753. *out = 0;
  3754. *outlen = 0;
  3755. if (cap > BR_IMG_FILE_MAX)
  3756. cap = BR_IMG_FILE_MAX;
  3757. if (url[0] == '/') {
  3758. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  3759. (int)cap);
  3760. if (rv < 0) {
  3761. s_copy(err, "file not found", errcap);
  3762. return -1;
  3763. }
  3764. *out = image_file_buf;
  3765. *outlen = (unsigned int)rv;
  3766. return 0;
  3767. }
  3768. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  3769. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  3770. if (rv == FETCH_ABORT)
  3771. return FETCH_ABORT;
  3772. if (rv < 0)
  3773. return -1;
  3774. len = (unsigned int)rv;
  3775. if (len == 0) {
  3776. s_copy(err, "empty image", errcap);
  3777. return -1;
  3778. }
  3779. *out = image_file_buf;
  3780. *outlen = len;
  3781. return 0;
  3782. }
  3783. /* Remote stylesheets are immutable enough for the current boot: keep
  3784. * successful responses under /share so a reload, a second visit or a fresh
  3785. * browser launch does not fetch the same five sheets over the network again.
  3786. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  3787. static int css_cache_count;
  3788. static unsigned int css_cache_hash(const char *s)
  3789. {
  3790. unsigned int h = 2166136261u;
  3791. while (*s) {
  3792. h ^= (unsigned char)*s++;
  3793. h *= 16777619u;
  3794. }
  3795. return h;
  3796. }
  3797. static void css_cache_path(const char *url, char *out, unsigned int cap)
  3798. {
  3799. unsigned int n = 0;
  3800. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  3801. s_append_dec(out, &n, css_cache_hash(url), cap);
  3802. }
  3803. static void css_cache_clear(void)
  3804. {
  3805. struct sys_dirent d;
  3806. char path[96];
  3807. for (;;) {
  3808. int i, found = 0;
  3809. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3810. (int)&d) == 1; i++) {
  3811. unsigned int n = 0;
  3812. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  3813. continue;
  3814. s_append(path, &n, "/share/", sizeof(path));
  3815. s_append(path, &n, d.name, sizeof(path));
  3816. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3817. return;
  3818. found = 1;
  3819. break;
  3820. }
  3821. if (!found)
  3822. break;
  3823. }
  3824. css_cache_count = 0;
  3825. }
  3826. static void css_cache_init(void)
  3827. {
  3828. struct sys_dirent d;
  3829. int i, count = 0;
  3830. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3831. (int)&d) == 1; i++)
  3832. if (starts_with(d.name, CSS_CACHE_PREFIX))
  3833. count++;
  3834. if (count >= CSS_CACHE_MAX) {
  3835. css_cache_clear();
  3836. return;
  3837. }
  3838. css_cache_count = count;
  3839. }
  3840. static int css_cache_get(const char *url, unsigned char **out,
  3841. unsigned int *outlen)
  3842. {
  3843. char path[96];
  3844. int rn;
  3845. css_cache_path(url, path, sizeof(path));
  3846. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  3847. (int)CSS_CACHE_FILE_MAX);
  3848. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  3849. return 0;
  3850. *out = image_io_buf;
  3851. *outlen = (unsigned int)rn;
  3852. return 1;
  3853. }
  3854. static void css_cache_put(const char *url, const unsigned char *data,
  3855. unsigned int len)
  3856. {
  3857. char path[96];
  3858. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  3859. len >= CSS_CACHE_FILE_MAX)
  3860. return;
  3861. css_cache_path(url, path, sizeof(path));
  3862. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3863. (int)len) >= 0)
  3864. css_cache_count++;
  3865. }
  3866. static int css_cache_has(const char *url)
  3867. {
  3868. char path[96];
  3869. struct sys_stat st;
  3870. css_cache_path(url, path, sizeof(path));
  3871. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3872. st.size < CSS_CACHE_FILE_MAX;
  3873. }
  3874. /* Read one stylesheet into the shared static buffer. CSS is parsed
  3875. * immediately, so it does not need the page heap; this leaves the heap for
  3876. * the 2 MB page body, the rules and the scaled image bitmaps. */
  3877. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  3878. char *err, unsigned int errcap)
  3879. {
  3880. unsigned int len;
  3881. int tr = 0;
  3882. int rv;
  3883. *out = 0;
  3884. *outlen = 0;
  3885. if (url[0] == '/') {
  3886. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  3887. (int)BR_CSS_MAX);
  3888. if (rv < 0) {
  3889. s_copy(err, "stylesheet not found", errcap);
  3890. return -1;
  3891. }
  3892. *out = image_io_buf;
  3893. *outlen = (unsigned int)rv;
  3894. return 0;
  3895. }
  3896. if (css_cache_get(url, out, outlen))
  3897. return 0;
  3898. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  3899. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  3900. &fetch_meta, &tr, err, errcap);
  3901. if (rv == FETCH_ABORT)
  3902. return FETCH_ABORT;
  3903. if (rv < 0)
  3904. return -1;
  3905. len = (unsigned int)rv;
  3906. if (len == 0) {
  3907. s_copy(err, "empty stylesheet", errcap);
  3908. return -1;
  3909. }
  3910. *out = image_io_buf;
  3911. *outlen = len;
  3912. css_cache_put(url, image_io_buf, len);
  3913. return 0;
  3914. }
  3915. static void redraw_now(void);
  3916. static char error_page[1024];
  3917. static void show_error(const char *title, const char *detail)
  3918. {
  3919. char *page = error_page;
  3920. unsigned int n = 0;
  3921. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  3922. s_append(page, &n, title, sizeof(error_page));
  3923. s_append(page, &n, "</h2><p>", sizeof(error_page));
  3924. {
  3925. const char *p = detail;
  3926. while (*p && n + 1 < sizeof(error_page)) {
  3927. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  3928. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  3929. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  3930. else page[n++] = *p;
  3931. p++;
  3932. }
  3933. }
  3934. page[n] = '\0';
  3935. s_append(page, &n, "</p><p>", sizeof(error_page));
  3936. s_append(page, &n, page_url, sizeof(error_page));
  3937. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  3938. sizeof(error_page));
  3939. br_parse(&doc, page, n);
  3940. layout_valid = 0;
  3941. preload_active = 0;
  3942. preload_pending = 0;
  3943. preload_wait = 0;
  3944. fetch_workers_cancel_busy();
  3945. s_copy(page_title, title, sizeof(page_title));
  3946. page_loading = 0;
  3947. set_status(title, 1, 0);
  3948. ngui_invalidate(&ui);
  3949. }
  3950. static int decode_direct_image(const unsigned char *data, unsigned int len,
  3951. unsigned int node)
  3952. {
  3953. if (image_count >= BR_MAX_IMAGES)
  3954. return -1;
  3955. if (decode_image_data(data, len, &images[0], 0, 0, 0, 0) != 0)
  3956. return -1;
  3957. doc.nodes[node].img_index = 0;
  3958. image_count = 1;
  3959. return 0;
  3960. }
  3961. static int ancestor_is(unsigned int node, unsigned int tag)
  3962. {
  3963. unsigned int p = doc.nodes[node].parent;
  3964. while (p) {
  3965. if (doc.nodes[p].tag == tag)
  3966. return 1;
  3967. p = doc.nodes[p].parent;
  3968. }
  3969. return 0;
  3970. }
  3971. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  3972. * parallel but parsed in document order, so the cascade is unchanged. */
  3973. static int load_stylesheets(void)
  3974. {
  3975. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  3976. static unsigned char remote[BR_MAX_SHEETS];
  3977. struct fetch_worker *slot[BR_MAX_SHEETS];
  3978. unsigned int i, n = 0, next = 0, k;
  3979. char err[64];
  3980. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  3981. struct br_node *nd = &doc.nodes[i];
  3982. const char *rel, *href;
  3983. char url[BR_URL_MAX];
  3984. int dup = 0;
  3985. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  3986. continue;
  3987. rel = br_rel(&doc, i);
  3988. if (!contains_ci(rel, "stylesheet"))
  3989. continue;
  3990. href = br_href(&doc, i);
  3991. if (!href[0])
  3992. continue;
  3993. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  3994. continue;
  3995. for (k = 0; k < n; k++)
  3996. if (s_eq(urls[k], url)) {
  3997. dup = 1;
  3998. break;
  3999. }
  4000. if (dup)
  4001. continue;
  4002. s_copy(urls[n], url, BR_URL_MAX);
  4003. remote[n] = url[0] != '/' && !css_cache_has(url);
  4004. n++;
  4005. }
  4006. for (i = 0; i < BR_MAX_SHEETS; i++)
  4007. slot[i] = 0;
  4008. /* Start as many remote sheets as there are free workers. */
  4009. for (; next < n; next++) {
  4010. struct fetch_worker *w;
  4011. if (!remote[next])
  4012. continue;
  4013. w = fetch_worker_alloc();
  4014. if (!w)
  4015. break;
  4016. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  4017. err, sizeof(err)) != 0) {
  4018. fetch_worker_release(w);
  4019. remote[next] = 0;
  4020. continue;
  4021. }
  4022. slot[next] = w;
  4023. }
  4024. for (i = 0; i < n; i++) {
  4025. unsigned char *data = 0;
  4026. unsigned int len = 0;
  4027. int rv;
  4028. if (!remote[i]) {
  4029. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  4030. if (rv == FETCH_ABORT) {
  4031. fetch_workers_stop_all();
  4032. return FETCH_ABORT;
  4033. }
  4034. if (rv != 0 || !len)
  4035. continue;
  4036. } else {
  4037. struct fetch_worker *w = slot[i];
  4038. int tr = 0;
  4039. if (!w) {
  4040. w = fetch_worker_alloc();
  4041. if (!w) {
  4042. rv = -1;
  4043. goto css_failed;
  4044. }
  4045. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  4046. 0, 0, 0, 0, err,
  4047. sizeof(err)) != 0) {
  4048. fetch_worker_release(w);
  4049. remote[i] = 0;
  4050. if (i == next)
  4051. next++;
  4052. continue;
  4053. }
  4054. slot[i] = w;
  4055. if (i == next)
  4056. next++;
  4057. }
  4058. rv = fetch_worker_wait(w, err, sizeof(err));
  4059. if (rv == FETCH_ABORT) {
  4060. fetch_workers_stop_all();
  4061. return FETCH_ABORT;
  4062. }
  4063. if (rv == 0)
  4064. rv = fetch_worker_read_body(w, image_io_buf,
  4065. BR_CSS_MAX,
  4066. image_io_buf + BR_CSS_MAX,
  4067. BR_CSS_COMP_MAX, &tr,
  4068. err, sizeof(err));
  4069. else
  4070. rv = -1;
  4071. fetch_worker_release(w);
  4072. slot[i] = 0;
  4073. /* Refill the worker window before parsing this sheet. */
  4074. for (; next < n; next++) {
  4075. struct fetch_worker *nw;
  4076. if (!remote[next])
  4077. continue;
  4078. nw = fetch_worker_alloc();
  4079. if (!nw)
  4080. break;
  4081. if (fetch_worker_submit(nw, urls[next],
  4082. BR_CSS_MAX, 0, 0, 0, 0,
  4083. err, sizeof(err)) != 0) {
  4084. fetch_worker_release(nw);
  4085. remote[next] = 0;
  4086. continue;
  4087. }
  4088. slot[next] = nw;
  4089. }
  4090. css_failed:
  4091. if (rv <= 0) {
  4092. /* One synchronous retry: a dropped sheet leaves the
  4093. * whole page unstyled (seen intermittently on
  4094. * arstechnica's CDN). */
  4095. u_puts("[css] retry ");
  4096. u_puts(urls[i]);
  4097. u_puts(": ");
  4098. u_puts(err[0] ? err : "no worker/empty body");
  4099. u_putc('\n');
  4100. err[0] = '\0';
  4101. rv = fetch_css(urls[i], &data, &len, err,
  4102. sizeof(err));
  4103. if (rv == FETCH_ABORT) {
  4104. fetch_workers_stop_all();
  4105. return FETCH_ABORT;
  4106. }
  4107. if (rv != 0 || !len) {
  4108. u_puts("[css] failed: ");
  4109. u_puts(err);
  4110. u_putc('\n');
  4111. continue;
  4112. }
  4113. } else {
  4114. len = (unsigned int)rv;
  4115. data = image_io_buf;
  4116. css_cache_put(urls[i], data, len);
  4117. }
  4118. }
  4119. if (len) {
  4120. br_set_font_base(urls[i]);
  4121. br_parse_css_text(&doc, (const char *)data, len);
  4122. }
  4123. }
  4124. br_set_font_base(page_url);
  4125. br_parse_inline_css(&doc);
  4126. load_font_faces();
  4127. br_reset_styles(&doc);
  4128. layout_valid = 0;
  4129. return 0;
  4130. }
  4131. static void preload_begin(void)
  4132. {
  4133. preload_active = 1;
  4134. preload_pending = 0;
  4135. preload_wait = 1;
  4136. preload_max_jobs = FETCH_WORKERS;
  4137. preload_node = 0;
  4138. preload_loaded = 0;
  4139. preload_scroll = 0;
  4140. img_stat_start = u_ticks_ms();
  4141. img_stat_wall = 0;
  4142. img_stat_net = img_stat_open = img_stat_first = 0;
  4143. img_stat_io = img_stat_dec = img_stat_scale = 0;
  4144. img_stat_paint = img_stat_reflow = 0;
  4145. img_stat_bytes = 0;
  4146. img_stat_n = 0;
  4147. img_stat_log_len = 0;
  4148. if (img_stat_log[0])
  4149. img_stat_log[0] = '\0';
  4150. img_repaint_ms = 0;
  4151. img_repaint_pending = 0;
  4152. }
  4153. /* Styles are computed top-down during layout, but images inside a hidden
  4154. * menu/carousel are never visited and keep img_top == 0. Without this check
  4155. * the preloader walks the DOM in node order and spends the whole image
  4156. * budget on logos and off-canvas thumbnails the reader cannot see. */
  4157. static struct br_style base_style(void);
  4158. static int node_hidden(unsigned int node)
  4159. {
  4160. unsigned int path[32], n = 0, p = node, i;
  4161. struct br_style st, parent;
  4162. while (p && n < sizeof(path) / sizeof(path[0])) {
  4163. path[n++] = p;
  4164. p = doc.nodes[p].parent;
  4165. }
  4166. /* Node 0 is the <html> element when the page starts with one: it
  4167. * is an ancestor too. Styles are cached per node, so the chain
  4168. * must start from the same base as style_for_node(); seeding it
  4169. * with a zeroed style left <body> cached with black text and no
  4170. * line-height once an image job ran (docs.cloudron.io). */
  4171. if (!p && n && n < sizeof(path) / sizeof(path[0]) &&
  4172. doc.nodes[0].type == BR_NODE_ELEM &&
  4173. doc.nodes[0].tag == BR_TAG_HTML &&
  4174. !(doc.nodes[path[n - 1]].flags & BR_NODE_DETACHED))
  4175. path[n++] = 0;
  4176. parent = base_style();
  4177. for (i = n; i > 0; i--) {
  4178. br_style_for(&doc, path[i - 1], &parent, &st);
  4179. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  4180. st.opacity_hidden)
  4181. return 1;
  4182. parent = st;
  4183. }
  4184. return 0;
  4185. }
  4186. static struct br_style base_style(void);
  4187. static int style_width_px(const struct br_style *st, int base);
  4188. static int style_height_px(const struct br_style *st, int base);
  4189. static void style_for_node(unsigned int node, struct br_style *out)
  4190. {
  4191. unsigned int p = doc.nodes[node].parent;
  4192. struct br_style parent;
  4193. /* Parent index 0 is ambiguous: it is the <html> element when the page
  4194. * starts with one (see root_style()), but also the parent field of a
  4195. * detached subtree root. */
  4196. if (p || (node != 0 && doc.nodes[0].type == BR_NODE_ELEM &&
  4197. doc.nodes[0].tag == BR_TAG_HTML &&
  4198. !(doc.nodes[node].flags & BR_NODE_DETACHED))) {
  4199. style_for_node(p, &parent);
  4200. br_style_for(&doc, node, &parent, out);
  4201. } else {
  4202. parent = base_style();
  4203. br_style_for(&doc, node, &parent, out);
  4204. }
  4205. }
  4206. /* ---- parallel image preloading ---- *
  4207. *
  4208. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  4209. * preload_step() only starts jobs and harvests completed ones; the browser
  4210. * main loop keeps drawing between calls, instead of blocking on one fetch.
  4211. */
  4212. static int preload_active_jobs(void)
  4213. {
  4214. int i, n = 0;
  4215. for (i = 0; i < FETCH_WORKERS; i++)
  4216. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  4217. n++;
  4218. return n;
  4219. }
  4220. static void preload_job_error(struct fetch_worker *w)
  4221. {
  4222. if (w->node < doc.nnode) {
  4223. if (w->bg)
  4224. doc.nodes[w->node].bg_img_index = -2;
  4225. else
  4226. doc.nodes[w->node].img_index = -2;
  4227. image_repaint();
  4228. }
  4229. }
  4230. /* Is the image's box anywhere near the visible page? A decode below the
  4231. * fold changes the layout (scroll extent) but not a single on-screen pixel,
  4232. * so it does not need a repaint. top/h come from the last layout; treat an
  4233. * unknown box as visible to stay safe. */
  4234. static int image_preload_visible(unsigned int node, int bg)
  4235. {
  4236. int top, h, scroll;
  4237. if (node >= BR_MAX_NODES || node >= doc.nnode || page_rect.h <= 0)
  4238. return 1;
  4239. if (bg) {
  4240. top = (int)block_top[node];
  4241. h = (int)block_h[node];
  4242. } else {
  4243. top = (int)img_top[node];
  4244. h = (int)img_h[node];
  4245. }
  4246. if (!top && !h)
  4247. return 1;
  4248. scroll = (int)page_scroll.offset;
  4249. if (top > scroll + page_rect.h + 160)
  4250. return 0;
  4251. if (top + h + 160 < scroll)
  4252. return 0;
  4253. return 1;
  4254. }
  4255. /* Upper bounds for the bitmap an <img> will paint. Zero means "unbounded";
  4256. * decode_image_data applies one scale to both axes so the aspect ratio is
  4257. * preserved. This is what keeps a 1200x800 photo that CSS paints at 400 px
  4258. * from being decoded and box-filtered to the 1000 px layout cap first. */
  4259. static void image_fit_size(unsigned int node, int *out_w, int *out_h)
  4260. {
  4261. struct br_style st;
  4262. struct br_node *nd;
  4263. unsigned int p;
  4264. int cw, w = 0, h = 0;
  4265. *out_w = *out_h = 0;
  4266. if (node >= doc.nnode)
  4267. return;
  4268. nd = &doc.nodes[node];
  4269. style_for_node(node, &st);
  4270. cw = page_rect.w > 24 ? page_rect.w - 24 : 0;
  4271. p = doc.nodes[node].parent;
  4272. if (p && p < BR_MAX_NODES && layout_boxes[p].valid &&
  4273. layout_boxes[p].w > 0 && layout_boxes[p].w < cw)
  4274. cw = layout_boxes[p].w;
  4275. if (st.width_kind)
  4276. w = style_width_px(&st, cw);
  4277. else if (nd->width_attr)
  4278. w = nd->width_pct ? cw * (int)nd->width_attr / 100 :
  4279. (int)nd->width_attr;
  4280. if (st.height_kind)
  4281. h = style_height_px(&st, cw);
  4282. else if (nd->height_attr)
  4283. h = nd->height_pct ? cw * (int)nd->height_attr / 100 :
  4284. (int)nd->height_attr;
  4285. if (st.max_width_kind) {
  4286. int mw = st.max_width_kind == 3 ?
  4287. cw * st.max_width_calc_pct / 100 +
  4288. st.max_width_calc_px :
  4289. st.max_width_kind == 2 ?
  4290. cw * (int)st.max_width / 100 :
  4291. (int)st.max_width;
  4292. if (mw > 0 && (w == 0 || w > mw))
  4293. w = mw;
  4294. }
  4295. if (st.max_height_kind) {
  4296. int mh = st.max_height_kind == 3 ?
  4297. cw * st.max_height_calc_pct / 100 +
  4298. st.max_height_calc_px :
  4299. st.max_height_kind == 2 ?
  4300. cw * (int)st.max_height / 100 :
  4301. (int)st.max_height;
  4302. if (mh > 0 && (h == 0 || h > mh))
  4303. h = mh;
  4304. }
  4305. if (w > BR_IMG_LAYOUT_W)
  4306. w = BR_IMG_LAYOUT_W;
  4307. if (h > 4096)
  4308. h = 4096;
  4309. if (w < 0)
  4310. w = 0;
  4311. if (h < 0)
  4312. h = 0;
  4313. *out_w = w;
  4314. *out_h = h;
  4315. }
  4316. static void preload_accept_image(unsigned int node, int bg, const char *url)
  4317. {
  4318. /* An <img> bitmap only depends on its URL, so the next <img> with the
  4319. * same source reuses it (heise repeats one comment icon 85 times).
  4320. * Backgrounds are scaled to their box and are not shared. */
  4321. images[image_count].url_hash =
  4322. !bg && url ? script_cache_hash(url) | 1u : 0;
  4323. if (bg)
  4324. doc.nodes[node].bg_img_index = (short)image_count;
  4325. else
  4326. doc.nodes[node].img_index = (short)image_count;
  4327. image_count++;
  4328. preload_loaded++;
  4329. /* A background bitmap never changes its box, so keep the (expensive)
  4330. * measured layout and only repaint the pixels. */
  4331. if (bg)
  4332. page_cache_valid = 0;
  4333. else
  4334. layout_valid = 0;
  4335. if (image_preload_visible(node, bg))
  4336. image_repaint();
  4337. }
  4338. /* Install a bitmap decoded by the fetch helper. The helper already applied
  4339. * the display bounds (and the JPEG reduced IDCT), so this is a read + copy
  4340. * on the UI thread instead of a decode. */
  4341. static int preload_store_helper(unsigned int node, int bg,
  4342. unsigned char *px, unsigned int pxlen,
  4343. unsigned int dw, unsigned int dh,
  4344. int alpha, unsigned int nw, unsigned int nh,
  4345. const char *url)
  4346. {
  4347. struct br_image *bi;
  4348. unsigned int npx;
  4349. if (image_count >= BR_MAX_IMAGES || !px || !dw || !dh ||
  4350. dw > 4096 || dh > 4096) {
  4351. free(px);
  4352. return -1;
  4353. }
  4354. npx = dw * dh;
  4355. if (image_pixels + npx > BR_IMG_PIXEL_BUDGET ||
  4356. pxlen < npx * 2u + (alpha ? npx : 0)) {
  4357. free(px);
  4358. return -1;
  4359. }
  4360. bi = &images[image_count];
  4361. bi->img.format = 0;
  4362. bi->img.w = dw;
  4363. bi->img.h = dh;
  4364. bi->img.px = (unsigned short *)px;
  4365. bi->img.alpha = alpha ? px + npx * 2u : 0;
  4366. bi->img.flags = 0;
  4367. bi->native_w = nw ? (int)nw : (int)dw;
  4368. bi->native_h = nh ? (int)nh : (int)dh;
  4369. bi->state = 1;
  4370. image_pixels += npx;
  4371. preload_accept_image(node, bg, url);
  4372. return 0;
  4373. }
  4374. static void preload_decode(unsigned int node, int bg,
  4375. const unsigned char *data, unsigned int len,
  4376. const char *url)
  4377. {
  4378. int fit_w = 0, fit_h = 0;
  4379. if (image_count >= BR_MAX_IMAGES) {
  4380. if (bg)
  4381. doc.nodes[node].bg_img_index = -2;
  4382. else
  4383. doc.nodes[node].img_index = -2;
  4384. return;
  4385. }
  4386. if (!bg)
  4387. image_fit_size(node, &fit_w, &fit_h);
  4388. if (decode_image_data(data, len, &images[image_count],
  4389. bg && node < BR_MAX_NODES &&
  4390. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  4391. bg && node < BR_MAX_NODES &&
  4392. layout_boxes[node].valid ? layout_boxes[node].h : 0,
  4393. fit_w, fit_h) == 0) {
  4394. preload_accept_image(node, bg, url);
  4395. } else {
  4396. if (bg)
  4397. doc.nodes[node].bg_img_index = -2;
  4398. else
  4399. doc.nodes[node].img_index = -2;
  4400. layout_valid = 0;
  4401. }
  4402. if (image_preload_visible(node, bg))
  4403. image_repaint();
  4404. }
  4405. /* A local file image bypasses the helpers: count its decode so a page opened
  4406. * from /share or /data still produces the same timing breakdown. */
  4407. static void img_stat_local(int before, unsigned int bytes, unsigned int io_ms)
  4408. {
  4409. img_stat_n++;
  4410. img_stat_bytes += bytes;
  4411. img_stat_io += io_ms;
  4412. if (image_count > before) {
  4413. struct br_image *bi = &images[image_count - 1];
  4414. img_stat_dec += img_last_dec_ms;
  4415. img_stat_scale += img_last_scale_ms;
  4416. if (img_stat_log_len + 100 < sizeof(img_stat_log)) {
  4417. unsigned int n = img_stat_log_len;
  4418. s_append(img_stat_log, &n, "local ", sizeof(img_stat_log));
  4419. s_append_dec(img_stat_log, &n, bytes,
  4420. sizeof(img_stat_log));
  4421. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4422. s_append_dec(img_stat_log, &n, img_last_dec_ms,
  4423. sizeof(img_stat_log));
  4424. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4425. s_append_dec(img_stat_log, &n, img_last_scale_ms,
  4426. sizeof(img_stat_log));
  4427. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4428. s_append_dec(img_stat_log, &n,
  4429. (unsigned int)bi->native_w,
  4430. sizeof(img_stat_log));
  4431. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4432. s_append_dec(img_stat_log, &n,
  4433. (unsigned int)bi->native_h,
  4434. sizeof(img_stat_log));
  4435. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4436. s_append_dec(img_stat_log, &n, bi->img.w,
  4437. sizeof(img_stat_log));
  4438. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4439. s_append_dec(img_stat_log, &n, bi->img.h,
  4440. sizeof(img_stat_log));
  4441. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4442. s_append_dec(img_stat_log, &n,
  4443. bi->img.alpha ? 1u : 0u,
  4444. sizeof(img_stat_log));
  4445. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4446. img_stat_log_len = n;
  4447. }
  4448. }
  4449. }
  4450. /* Harvest one completed worker. Returns 1 when a job was finished. */
  4451. static int preload_finish_worker(struct fetch_worker *w)
  4452. {
  4453. char err[64];
  4454. int rv, tr = 0;
  4455. unsigned int t0, io_ms;
  4456. int before;
  4457. int used_px = 0;
  4458. rv = fetch_worker_poll(w, err, sizeof(err));
  4459. if (rv < 0) {
  4460. /* A helper from an older pack does not understand the image
  4461. * decode request; retry once without it and decode in-process. */
  4462. if (w->image_job && w->dec_w && !w->dec_retried &&
  4463. fetch_worker_submit_req(w, w->url, BR_IMG_FILE_MAX,
  4464. 0, 0, 0, 0, w->node, w->bg,
  4465. 0, 0, err, sizeof(err)) == 0) {
  4466. w->image_job = 1;
  4467. w->dec_retried = 1;
  4468. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4469. return 0;
  4470. }
  4471. preload_job_error(w);
  4472. if (img_stat_log_len + 64 < sizeof(img_stat_log)) {
  4473. unsigned int n = img_stat_log_len;
  4474. char u[48];
  4475. s_copy(u, w->url, sizeof(u));
  4476. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4477. s_append(img_stat_log, &n, " error\n",
  4478. sizeof(img_stat_log));
  4479. img_stat_log_len = n;
  4480. }
  4481. img_stat_n++;
  4482. fetch_worker_release(w);
  4483. return 1;
  4484. }
  4485. if (rv == 0)
  4486. return 0;
  4487. t0 = u_ticks_ms();
  4488. rv = -1;
  4489. before = image_count;
  4490. if (w->m.px_len && !w->m.dec_err && w->m.dw && w->m.dh &&
  4491. w->m.px_len <= 8u * 1024u * 1024u) {
  4492. unsigned char *px = (unsigned char *)malloc(w->m.px_len);
  4493. int pr = -1;
  4494. if (px)
  4495. pr = u_syscall3(SYS_READ_FILE, (int)w->px, (int)px,
  4496. (int)w->m.px_len);
  4497. if (pr == (int)w->m.px_len) {
  4498. if (preload_store_helper(w->node, w->bg, px,
  4499. w->m.px_len, w->m.dw,
  4500. w->m.dh, (int)w->m.alpha,
  4501. w->m.nw, w->m.nh,
  4502. w->url) == 0) {
  4503. rv = (int)w->m.len;
  4504. img_last_dec_ms = w->m.dec_ms;
  4505. img_last_scale_ms = 0;
  4506. used_px = 1;
  4507. } else {
  4508. px = 0; /* the helper freed it */
  4509. }
  4510. }
  4511. if (px && !(pr == (int)w->m.px_len))
  4512. free(px);
  4513. }
  4514. io_ms = u_ticks_ms() - t0;
  4515. if (rv < 0) {
  4516. t0 = u_ticks_ms();
  4517. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  4518. image_comp_buf, BR_IMG_FILE_MAX,
  4519. &tr, err, sizeof(err));
  4520. io_ms += u_ticks_ms() - t0;
  4521. before = image_count;
  4522. if (rv >= 0)
  4523. preload_decode(w->node, w->bg, image_file_buf,
  4524. (unsigned int)rv, w->url);
  4525. else
  4526. preload_job_error(w);
  4527. }
  4528. img_stat_n++;
  4529. img_stat_net += w->m.total_ms;
  4530. img_stat_open += w->m.open_ms;
  4531. img_stat_first += w->m.first_ms;
  4532. img_stat_io += io_ms;
  4533. img_stat_bytes += rv > 0 ? (unsigned int)rv : 0;
  4534. img_stat_dec += w->m.dec_ms;
  4535. if (rv >= 0 && !used_px) {
  4536. img_stat_dec += img_last_dec_ms;
  4537. img_stat_scale += img_last_scale_ms;
  4538. }
  4539. if (img_stat_log_len + 160 < sizeof(img_stat_log)) {
  4540. unsigned int n = img_stat_log_len;
  4541. char u[48];
  4542. s_copy(u, w->url, sizeof(u));
  4543. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4544. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4545. s_append_dec(img_stat_log, &n,
  4546. rv > 0 ? (unsigned int)rv : 0,
  4547. sizeof(img_stat_log));
  4548. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4549. s_append_dec(img_stat_log, &n, w->m.open_ms,
  4550. sizeof(img_stat_log));
  4551. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4552. s_append_dec(img_stat_log, &n, w->m.first_ms,
  4553. sizeof(img_stat_log));
  4554. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4555. s_append_dec(img_stat_log, &n, w->m.total_ms,
  4556. sizeof(img_stat_log));
  4557. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4558. s_append_dec(img_stat_log, &n, io_ms, sizeof(img_stat_log));
  4559. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4560. s_append_dec(img_stat_log, &n,
  4561. rv >= 0 ? img_last_dec_ms : 0,
  4562. sizeof(img_stat_log));
  4563. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4564. s_append_dec(img_stat_log, &n,
  4565. rv >= 0 ? img_last_scale_ms : 0,
  4566. sizeof(img_stat_log));
  4567. if (image_count > before) {
  4568. struct br_image *bi = &images[image_count - 1];
  4569. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4570. s_append_dec(img_stat_log, &n,
  4571. (unsigned int)bi->native_w,
  4572. sizeof(img_stat_log));
  4573. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4574. s_append_dec(img_stat_log, &n,
  4575. (unsigned int)bi->native_h,
  4576. sizeof(img_stat_log));
  4577. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4578. s_append_dec(img_stat_log, &n, bi->img.w,
  4579. sizeof(img_stat_log));
  4580. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4581. s_append_dec(img_stat_log, &n, bi->img.h,
  4582. sizeof(img_stat_log));
  4583. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4584. s_append_dec(img_stat_log, &n,
  4585. bi->img.alpha ? 1u : 0u,
  4586. sizeof(img_stat_log));
  4587. }
  4588. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4589. img_stat_log_len = n;
  4590. }
  4591. fetch_worker_release(w);
  4592. return 1;
  4593. }
  4594. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  4595. * the number of jobs started. */
  4596. static int preload_fill_jobs(void)
  4597. {
  4598. int started = 0;
  4599. char err[64];
  4600. while (preload_active && preload_node < doc.nnode) {
  4601. unsigned int i = preload_node;
  4602. struct br_node *nd = &doc.nodes[i];
  4603. const char *src;
  4604. char url[BR_URL_MAX];
  4605. struct fetch_worker *w;
  4606. if (preload_active_jobs() >= preload_max_jobs)
  4607. break;
  4608. if (nd->type != BR_NODE_ELEM) {
  4609. preload_node++;
  4610. continue;
  4611. }
  4612. if (nd->tag != BR_TAG_IMG) {
  4613. if (nd->bg_img_index == -1) {
  4614. struct br_style bs;
  4615. style_for_node(i, &bs);
  4616. if (bs.display != BR_DISPLAY_NONE &&
  4617. !bs.vis_hidden && bs.bg_image) {
  4618. const char *bsrc =
  4619. br_bg_image_url(bs.bg_image - 1);
  4620. /* Lazy like <img>: a background box
  4621. * below the viewport (or not laid
  4622. * out yet) waits for the next scan. */
  4623. if (bsrc[0] &&
  4624. (!layout_boxes[i].valid ||
  4625. block_top[i] >
  4626. (unsigned int)(page_scroll.offset +
  4627. page_rect.h + 160))) {
  4628. preload_pending = 1;
  4629. preload_node++;
  4630. continue;
  4631. }
  4632. if (bsrc[0] &&
  4633. !starts_with(bsrc, "data:") &&
  4634. resolve_link(page_url, bsrc, url,
  4635. sizeof(url)) == 0) {
  4636. if (image_count +
  4637. preload_active_jobs() >=
  4638. BR_MAX_IMAGES) {
  4639. preload_node = doc.nnode;
  4640. break;
  4641. }
  4642. if (url[0] == '/') {
  4643. unsigned char *data = 0;
  4644. unsigned int len = 0;
  4645. unsigned int t0;
  4646. int before;
  4647. preload_node = i + 1;
  4648. before = image_count;
  4649. t0 = u_ticks_ms();
  4650. if (fetch_image(url,
  4651. BR_IMG_FILE_MAX,
  4652. &data, &len,
  4653. err,
  4654. sizeof(err)) == 0) {
  4655. preload_decode(i, 1, data, len, 0);
  4656. img_stat_local(before, len,
  4657. u_ticks_ms() - t0);
  4658. } else {
  4659. nd->bg_img_index = -2;
  4660. }
  4661. continue;
  4662. }
  4663. w = fetch_worker_alloc();
  4664. if (!w)
  4665. return started;
  4666. preload_node = i + 1;
  4667. if (fetch_worker_submit(w, url,
  4668. BR_IMG_FILE_MAX,
  4669. 0, 0, i, 1,
  4670. err,
  4671. sizeof(err)) != 0) {
  4672. nd->bg_img_index = -2;
  4673. fetch_worker_release(w);
  4674. continue;
  4675. }
  4676. w->image_job = 1;
  4677. w->deadline = u_ticks_ms() +
  4678. BR_IMG_JOB_TIMEOUT_MS;
  4679. /* in flight: rescans skip it */
  4680. nd->bg_img_index = -3;
  4681. started++;
  4682. continue;
  4683. }
  4684. }
  4685. nd->bg_img_index = -2;
  4686. }
  4687. preload_node++;
  4688. continue;
  4689. }
  4690. if (nd->img_index != -1) {
  4691. preload_node++;
  4692. continue;
  4693. }
  4694. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  4695. preload_node++;
  4696. continue;
  4697. }
  4698. src = br_src(&doc, i);
  4699. if (!src[0] || starts_with(src, "data:")) {
  4700. preload_node++;
  4701. continue;
  4702. }
  4703. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  4704. preload_node++;
  4705. continue;
  4706. }
  4707. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  4708. preload_node = doc.nnode;
  4709. break;
  4710. }
  4711. /* Do not stop at the first below-fold image: DOM order is
  4712. * not visual order, and a footer/ad image early in the DOM
  4713. * used to hide every later article image from the loader. */
  4714. if (img_top[i] >
  4715. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  4716. preload_pending = 1;
  4717. preload_node++;
  4718. continue;
  4719. }
  4720. {
  4721. unsigned int uh = script_cache_hash(url) | 1u;
  4722. int k;
  4723. for (k = 0; k < image_count; k++)
  4724. if (images[k].state == 1 &&
  4725. images[k].url_hash == uh)
  4726. break;
  4727. if (k < image_count) {
  4728. nd->img_index = (short)k;
  4729. layout_valid = 0;
  4730. preload_node = i + 1;
  4731. image_repaint();
  4732. continue;
  4733. }
  4734. }
  4735. if (url[0] == '/') {
  4736. unsigned char *data = 0;
  4737. unsigned int len = 0;
  4738. unsigned int t0;
  4739. int before;
  4740. preload_node = i + 1;
  4741. before = image_count;
  4742. t0 = u_ticks_ms();
  4743. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  4744. err, sizeof(err)) == 0) {
  4745. preload_decode(i, 0, data, len, url);
  4746. img_stat_local(before, len, u_ticks_ms() - t0);
  4747. } else {
  4748. nd->img_index = -2;
  4749. }
  4750. continue;
  4751. }
  4752. w = fetch_worker_alloc();
  4753. if (!w)
  4754. return started;
  4755. preload_node = i + 1;
  4756. {
  4757. char msg[64];
  4758. unsigned int n = 0;
  4759. s_append(msg, &n, "Loading images ", sizeof(msg));
  4760. s_append_dec(msg, &n,
  4761. (unsigned int)preload_loaded + 1,
  4762. sizeof(msg));
  4763. s_append(msg, &n, "...", sizeof(msg));
  4764. set_status_quiet(msg);
  4765. image_repaint();
  4766. }
  4767. {
  4768. int fit_w = 0, fit_h = 0;
  4769. image_fit_size(i, &fit_w, &fit_h);
  4770. if (!fit_w)
  4771. fit_w = BR_IMG_LAYOUT_W;
  4772. if (fetch_worker_submit_image(w, url, BR_IMG_FILE_MAX,
  4773. i, 0,
  4774. (unsigned int)fit_w,
  4775. (unsigned int)fit_h,
  4776. err, sizeof(err)) != 0) {
  4777. nd->img_index = -2;
  4778. fetch_worker_release(w);
  4779. continue;
  4780. }
  4781. }
  4782. w->image_job = 1;
  4783. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4784. nd->img_index = -3; /* in flight: rescans skip it */
  4785. started++;
  4786. }
  4787. return started;
  4788. }
  4789. /* Report where the image batch spent its time: status bar for the headline,
  4790. * /share/IMGSTAT for the per-image breakdown (cat it from a terminal). */
  4791. static void img_stats_report(void)
  4792. {
  4793. char msg[80];
  4794. static char out[BR_IMG_STAT_LOG + 512];
  4795. unsigned int n = 0, o = 0;
  4796. if (!img_stat_n)
  4797. return;
  4798. img_stat_wall = img_stat_start ?
  4799. u_ticks_ms() - img_stat_start : 1;
  4800. if (!img_stat_wall)
  4801. img_stat_wall = 1;
  4802. /* Compact on-screen form; /share/IMGSTAT has the full breakdown. */
  4803. s_append(msg, &n, "img ", sizeof(msg));
  4804. s_append_dec(msg, &n, (unsigned int)img_stat_n, sizeof(msg));
  4805. s_append(msg, &n, " ", sizeof(msg));
  4806. s_append_dec(msg, &n, img_stat_wall, sizeof(msg));
  4807. s_append(msg, &n, "ms net ", sizeof(msg));
  4808. s_append_dec(msg, &n, img_stat_net, sizeof(msg));
  4809. s_append(msg, &n, " dec ", sizeof(msg));
  4810. s_append_dec(msg, &n, img_stat_dec, sizeof(msg));
  4811. s_append(msg, &n, " sc ", sizeof(msg));
  4812. s_append_dec(msg, &n, img_stat_scale, sizeof(msg));
  4813. s_append(msg, &n, " paint ", sizeof(msg));
  4814. s_append_dec(msg, &n, img_stat_paint, sizeof(msg));
  4815. /* Keep the page's phase breakdown and append the image summary when
  4816. * it fits; never hide a JS error or a truncation notice. */
  4817. if (!post_status_error && !contains_ci(post_status_text, "truncated")) {
  4818. unsigned int plen = s_len(post_status_text);
  4819. if (!plen) {
  4820. s_copy(post_status_text, msg, sizeof(post_status_text));
  4821. } else if (plen + s_len(msg) + 4 < sizeof(post_status_text)) {
  4822. unsigned int pn = plen;
  4823. s_append(post_status_text, &pn, " | ",
  4824. sizeof(post_status_text));
  4825. s_append(post_status_text, &pn, msg,
  4826. sizeof(post_status_text));
  4827. } else {
  4828. s_copy(post_status_text, msg, sizeof(post_status_text));
  4829. }
  4830. post_status_ttl = 12000;
  4831. }
  4832. s_append(out, &o, "browser image stats\n", sizeof(out));
  4833. s_append(out, &o, "n=", sizeof(out));
  4834. s_append_dec(out, &o, (unsigned int)img_stat_n, sizeof(out));
  4835. s_append(out, &o, " wall=", sizeof(out));
  4836. s_append_dec(out, &o, img_stat_wall, sizeof(out));
  4837. s_append(out, &o, " net=", sizeof(out));
  4838. s_append_dec(out, &o, img_stat_net, sizeof(out));
  4839. s_append(out, &o, " open=", sizeof(out));
  4840. s_append_dec(out, &o, img_stat_open, sizeof(out));
  4841. s_append(out, &o, " first=", sizeof(out));
  4842. s_append_dec(out, &o, img_stat_first, sizeof(out));
  4843. s_append(out, &o, " io=", sizeof(out));
  4844. s_append_dec(out, &o, img_stat_io, sizeof(out));
  4845. s_append(out, &o, " dec=", sizeof(out));
  4846. s_append_dec(out, &o, img_stat_dec, sizeof(out));
  4847. s_append(out, &o, " scale=", sizeof(out));
  4848. s_append_dec(out, &o, img_stat_scale, sizeof(out));
  4849. s_append(out, &o, " paint=", sizeof(out));
  4850. s_append_dec(out, &o, img_stat_paint, sizeof(out));
  4851. s_append(out, &o, " reflow=", sizeof(out));
  4852. s_append_dec(out, &o, img_stat_reflow, sizeof(out));
  4853. s_append(out, &o, " bytes=", sizeof(out));
  4854. s_append_dec(out, &o, img_stat_bytes, sizeof(out));
  4855. s_append(out, &o, "\nurl bytes open first total io dec scale native bitmap\n",
  4856. sizeof(out));
  4857. s_append(out, &o, img_stat_log, sizeof(out));
  4858. u_syscall3(SYS_WRITE_FILE, (int)"/share/IMGSTAT", (int)out,
  4859. (int)s_len(out));
  4860. }
  4861. static void preload_step(void)
  4862. {
  4863. int i;
  4864. unsigned int t0;
  4865. if (!preload_active)
  4866. return;
  4867. if (cancel_fetch || pending_action) {
  4868. preload_active = 0;
  4869. preload_pending = 0;
  4870. fetch_workers_cancel_busy();
  4871. return;
  4872. }
  4873. preload_fill_jobs();
  4874. /* Decode completed images in a short batch instead of one per pass.
  4875. * A pass used to decode one image and then sleep 10 ms, so a page of
  4876. * small icons trickled in at the decode rate. The budget keeps a
  4877. * single huge JPEG from monopolising the UI while small images
  4878. * finish together. */
  4879. t0 = u_ticks_ms();
  4880. for (i = 0; i < FETCH_WORKERS; i++) {
  4881. if (!fetch_workers[i].busy)
  4882. continue;
  4883. if (preload_finish_worker(&fetch_workers[i]) &&
  4884. u_ticks_ms() - t0 >= BR_IMG_DECODE_BUDGET_MS)
  4885. break;
  4886. }
  4887. if (preload_active && preload_node >= doc.nnode &&
  4888. preload_active_jobs() == 0) {
  4889. preload_active = 0;
  4890. if (preload_pending)
  4891. preload_scroll = page_scroll.offset;
  4892. else
  4893. preload_pending = 0;
  4894. /* Keep the now idle helpers and their connections; a later
  4895. * navigation reuses them. They exit after ten idle seconds,
  4896. * and losing window focus stops them at once. */
  4897. if (img_repaint_pending) {
  4898. img_repaint_pending = 0;
  4899. ngui_invalidate(&ui);
  4900. }
  4901. img_stats_report();
  4902. set_status(post_status_text, post_status_error, post_status_ttl);
  4903. ngui_invalidate(&ui);
  4904. }
  4905. }
  4906. /* Set by navigate() when it turned a typed bare host into https://; the next
  4907. * load_page() consumes it and may retry over http. */
  4908. static int nav_https_upgraded;
  4909. /* Errors that mean "https is not served here" rather than "the site is
  4910. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  4911. static int https_fallback_error(int e)
  4912. {
  4913. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  4914. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  4915. e == UHTTP_ERR_RESET;
  4916. }
  4917. static void history_push(const char *url)
  4918. {
  4919. if (!url || !url[0])
  4920. return;
  4921. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  4922. s_eq(history[hist_pos], url))
  4923. return;
  4924. if (hist_len > 0 && hist_pos + 1 < hist_len)
  4925. hist_len = hist_pos + 1;
  4926. if (hist_len < BR_HISTORY) {
  4927. s_copy(history[hist_len], url, BR_URL_MAX);
  4928. hist_pos = hist_len;
  4929. hist_len++;
  4930. } else {
  4931. int i;
  4932. for (i = 1; i < BR_HISTORY; i++)
  4933. s_copy(history[i - 1], history[i], BR_URL_MAX);
  4934. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  4935. hist_pos = BR_HISTORY - 1;
  4936. }
  4937. }
  4938. static void load_page(const char *url, int local, int push)
  4939. {
  4940. unsigned char *body = 0;
  4941. unsigned int len = 0;
  4942. int truncated = 0;
  4943. struct img_info image_info;
  4944. char ctype[64];
  4945. char final[BR_URL_MAX];
  4946. char err[80];
  4947. const char *detail = 0;
  4948. const char *post = pending_post_is ? pending_post : 0;
  4949. unsigned int post_len = pending_post_len;
  4950. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  4951. /* Phase timings for the status line: where a slow load spends it. */
  4952. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  4953. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  4954. int upgraded = nav_https_upgraded;
  4955. int retried = 0;
  4956. int rv;
  4957. nav_https_upgraded = 0;
  4958. final[0] = '\0';
  4959. pending_post_len = 0;
  4960. pending_post_is = 0;
  4961. cancel_fetch = 0;
  4962. preload_active = 0;
  4963. preload_pending = 0;
  4964. fetch_workers_prepare_nav(url);
  4965. js_browser_stop();
  4966. js_last_status[0] = '\0';
  4967. js_last_error = 0;
  4968. heap_clear();
  4969. image_reset();
  4970. form_reset_state();
  4971. layout_valid = 0;
  4972. page_scroll.offset = 0;
  4973. page_scroll.dragging = 0;
  4974. page_title[0] = '\0';
  4975. page_loading = 1;
  4976. page_is_local = local;
  4977. s_copy(page_url, url, sizeof(page_url));
  4978. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4979. url_in.len = s_len(url_in.text);
  4980. url_in.cursor = url_in.len;
  4981. url_in.scroll = 0;
  4982. ngui_set_focus(&ui, 0);
  4983. if (final[0])
  4984. final[0] = '\0';
  4985. if (push)
  4986. history_push(url);
  4987. set_status("Loading...", 0, 0);
  4988. ngui_invalidate(&ui);
  4989. /* heap_clear() detaches the fonts, so attach them again before the
  4990. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  4991. if (heap_start() != 0) {
  4992. show_error("Out of memory", "Cannot allocate the page buffer");
  4993. return;
  4994. }
  4995. br_parse_plain(&doc, "", 0); /* blank while loading */
  4996. ngui_font_attach(&ui);
  4997. redraw_now();
  4998. browser_rules_alloc();
  4999. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5000. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  5001. &truncated, post, post_len);
  5002. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  5003. fetch_last_error == UHTTP_ERR_DNS) {
  5004. /* A busy previous page can leave the receiver ring full just
  5005. * long enough to lose a DNS reply. Tear the old helpers down
  5006. * and try once more before giving up. */
  5007. retried = 1;
  5008. fetch_workers_stop_all();
  5009. u_sleep_ms(500);
  5010. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5011. sizeof(ctype), final, sizeof(final), err,
  5012. sizeof(err), &truncated, post, post_len);
  5013. }
  5014. if (rv == FETCH_ABORT)
  5015. return;
  5016. t_fetch = u_ticks_ms() - t_start;
  5017. /* Capture the page timing before CSS/script/image fetches overwrite the
  5018. * shared fetch_meta block. */
  5019. if (rv == 0 && !local) {
  5020. page_open_ms = fetch_meta.open_ms;
  5021. page_first_ms = fetch_meta.first_ms;
  5022. page_total_ms = fetch_meta.total_ms;
  5023. }
  5024. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  5025. https_fallback_error(fetch_last_error)) {
  5026. char http_url[BR_URL_MAX];
  5027. unsigned int n = 0;
  5028. s_append(http_url, &n, "http://", sizeof(http_url));
  5029. s_append(http_url, &n, url + 8, sizeof(http_url));
  5030. /* Replace the https entry instead of adding a second one. */
  5031. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  5032. s_eq(history[hist_pos], url))
  5033. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  5034. load_page(http_url, 0, 0);
  5035. return;
  5036. }
  5037. if (rv != 0) {
  5038. detail = err;
  5039. show_error("Cannot load this page", detail);
  5040. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5041. url_in.len = s_len(url_in.text);
  5042. url_in.cursor = url_in.len;
  5043. url_in.scroll = 0;
  5044. return;
  5045. }
  5046. if (!local)
  5047. origin_cache_learn(url, final[0] ? final : url);
  5048. page_is_local = local;
  5049. if (final[0]) {
  5050. s_copy(page_url, final, sizeof(page_url));
  5051. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5052. url_in.len = s_len(url_in.text);
  5053. url_in.cursor = url_in.len;
  5054. url_in.scroll = 0;
  5055. }
  5056. if (contains_ci(ctype, "text/plain")) {
  5057. br_parse_plain(&doc, (const char *)body, len);
  5058. } else if (contains_ci(ctype, "image/") ||
  5059. (!contains_ci(ctype, "text/html") &&
  5060. img_sniff(body, len, &image_info) == 0)) {
  5061. unsigned int node = br_parse_image_doc(&doc, page_url);
  5062. if (node)
  5063. decode_direct_image(body, len, node);
  5064. s_copy(page_title, "Image", sizeof(page_title));
  5065. } else {
  5066. br_set_viewport(ui.w);
  5067. t_mark = u_ticks_ms();
  5068. br_parse(&doc, (const char *)body, len);
  5069. t_parse = u_ticks_ms() - t_mark;
  5070. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  5071. sizeof(page_title));
  5072. t_mark = u_ticks_ms();
  5073. if (load_stylesheets() == FETCH_ABORT)
  5074. return;
  5075. t_css = u_ticks_ms() - t_mark;
  5076. if (pending_action)
  5077. return;
  5078. }
  5079. preload_begin();
  5080. page_loading = 0;
  5081. hist_visit(page_url, page_title);
  5082. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5083. url_in.len = s_len(url_in.text);
  5084. url_in.cursor = url_in.len;
  5085. url_in.scroll = 0;
  5086. ngui_set_focus(&ui, 0);
  5087. /* Paint the parsed page before fetching/running scripts. A slow
  5088. * remote <script src> then does not hide the page behind the loading
  5089. * screen; the fetch helper pumps this UI while it waits. */
  5090. set_status("Loading scripts...", 0, 0);
  5091. t_mark = u_ticks_ms();
  5092. redraw_now();
  5093. t_paint = u_ticks_ms() - t_mark;
  5094. /* Start one image download before the scripts. The other workers
  5095. * fetch the external script bodies in parallel, and the remaining
  5096. * images start as soon as the script phase ends. */
  5097. preload_max_jobs = 1;
  5098. preload_fill_jobs();
  5099. preload_wait = 0;
  5100. t_mark = u_ticks_ms();
  5101. run_page_scripts();
  5102. t_js = u_ticks_ms() - t_mark;
  5103. preload_max_jobs = FETCH_WORKERS;
  5104. if (pending_action)
  5105. return;
  5106. post_status_text[0] = '\0';
  5107. post_status_error = 0;
  5108. post_status_ttl = 0;
  5109. if (js_last_status[0]) {
  5110. s_copy(post_status_text, js_last_status,
  5111. sizeof(post_status_text));
  5112. post_status_error = js_last_error;
  5113. post_status_ttl = 8000;
  5114. } else if (truncated) {
  5115. s_copy(post_status_text, "Page truncated at the buffer limit",
  5116. sizeof(post_status_text));
  5117. post_status_ttl = 6000;
  5118. } else if (doc.truncated) {
  5119. s_copy(post_status_text, "Page truncated by the parser",
  5120. sizeof(post_status_text));
  5121. post_status_ttl = 6000;
  5122. } else if (page_total_ms) {
  5123. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  5124. * paint 220, js 1750" -- the phases of this load. */
  5125. unsigned int n = 0;
  5126. static const char *const names[] = {
  5127. ", parse ", ", css ", ", paint ", ", js "
  5128. };
  5129. unsigned int vals[4];
  5130. int k;
  5131. vals[0] = t_parse;
  5132. vals[1] = t_css;
  5133. vals[2] = t_paint;
  5134. vals[3] = t_js;
  5135. (void)page_first_ms;
  5136. if (starts_with(page_url, "https://"))
  5137. s_append(post_status_text, &n,
  5138. "HTTPS (not verified), ",
  5139. sizeof(post_status_text));
  5140. s_append(post_status_text, &n, "Loaded in ",
  5141. sizeof(post_status_text));
  5142. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  5143. sizeof(post_status_text));
  5144. s_append(post_status_text, &n, " ms: page ",
  5145. sizeof(post_status_text));
  5146. s_append_dec(post_status_text, &n, t_fetch,
  5147. sizeof(post_status_text));
  5148. s_append(post_status_text, &n, " (headers ",
  5149. sizeof(post_status_text));
  5150. s_append_dec(post_status_text, &n, page_open_ms,
  5151. sizeof(post_status_text));
  5152. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  5153. for (k = 0; k < 4; k++) {
  5154. s_append(post_status_text, &n, names[k],
  5155. sizeof(post_status_text));
  5156. s_append_dec(post_status_text, &n, vals[k],
  5157. sizeof(post_status_text));
  5158. }
  5159. post_status_ttl = 12000;
  5160. } else if (starts_with(page_url, "https://")) {
  5161. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  5162. sizeof(post_status_text));
  5163. post_status_ttl = 6000;
  5164. }
  5165. set_status(post_status_text, post_status_error, post_status_ttl);
  5166. ngui_invalidate(&ui);
  5167. }
  5168. static void load_home(int push)
  5169. {
  5170. pending_post_len = 0;
  5171. pending_post_is = 0;
  5172. cancel_fetch = 0;
  5173. preload_active = 0;
  5174. preload_pending = 0;
  5175. js_browser_stop();
  5176. js_last_status[0] = '\0';
  5177. js_last_error = 0;
  5178. heap_clear();
  5179. image_reset();
  5180. form_reset_state();
  5181. layout_valid = 0;
  5182. page_scroll.offset = 0;
  5183. page_scroll.dragging = 0;
  5184. page_loading = 1;
  5185. page_is_local = 0;
  5186. s_copy(page_url, "about:home", sizeof(page_url));
  5187. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5188. url_in.len = s_len(url_in.text);
  5189. url_in.cursor = url_in.len;
  5190. url_in.scroll = 0;
  5191. ngui_set_focus(&ui, 0);
  5192. if (push)
  5193. history_push(page_url);
  5194. ngui_invalidate(&ui);
  5195. /* See load_page(): reattach the fonts before the first redraw. */
  5196. if (heap_start() != 0) {
  5197. show_error("Out of memory", "Cannot allocate the browser heap");
  5198. return;
  5199. }
  5200. br_parse_plain(&doc, "", 0);
  5201. ngui_font_attach(&ui);
  5202. redraw_now();
  5203. browser_rules_alloc();
  5204. {
  5205. static const char home[] =
  5206. "<html><head><title>NebOS Browser</title><style>"
  5207. "body { margin: 10px; color: #e4e6f0; }"
  5208. "h1 { color: #7fb0ff; }"
  5209. ".box { background-color: #262b3a; margin: 12px; "
  5210. "padding: 10px; }"
  5211. "a { color: #7fb0ff; }"
  5212. "pre { background-color: #32384a; }"
  5213. "</style></head><body>"
  5214. "<h1>NebOS Browser</h1>"
  5215. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  5216. "shared HTTP client and the image library.</p>"
  5217. "<div class=\"box\"><b>Try:</b>"
  5218. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  5219. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  5220. "<li><a href=\"/floppy1/JS.HTM\">/"
  5221. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  5222. "<li><a href=\"http://10.0.2.2:8000/\">"
  5223. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  5224. "<li><a href=\"https://example.com/\">"
  5225. "https://example.com/</a> (TLS, not verified)</li>"
  5226. "</ul></div>"
  5227. "<p>Type a URL in the bar above. Esc closes the "
  5228. "window, Ctrl+L focuses the address bar.</p>"
  5229. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  5230. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  5231. "</body></html>";
  5232. br_set_viewport(ui.w);
  5233. br_parse(&doc, home, sizeof(home) - 1);
  5234. br_parse_inline_css(&doc);
  5235. br_reset_styles(&doc);
  5236. s_copy(page_title, doc.title, sizeof(page_title));
  5237. }
  5238. post_status_text[0] = '\0';
  5239. post_status_error = 0;
  5240. post_status_ttl = 0;
  5241. page_loading = 0;
  5242. set_status("", 0, 0);
  5243. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5244. url_in.len = s_len(url_in.text);
  5245. url_in.cursor = url_in.len;
  5246. url_in.scroll = 0;
  5247. ngui_set_focus(&ui, 0);
  5248. ngui_invalidate(&ui);
  5249. }
  5250. /* Extensions the browser opens from the local filesystem. A dotted input
  5251. * with one of these still resolves relative to the cwd. */
  5252. static int local_file_ext(const char *s)
  5253. {
  5254. static const char *const exts[] = {
  5255. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  5256. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  5257. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  5258. "cfg", "conf", 0
  5259. };
  5260. unsigned int i = 0, start = 0, len = 0, e;
  5261. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  5262. s[i] != '#') {
  5263. if (s[i] == '.') {
  5264. start = i + 1;
  5265. len = 0;
  5266. } else if (start) {
  5267. len++;
  5268. }
  5269. i++;
  5270. }
  5271. if (!len)
  5272. return 0;
  5273. for (e = 0; exts[e]; e++) {
  5274. const char *x = exts[e];
  5275. unsigned int xn = s_len(x), k;
  5276. if (xn != len)
  5277. continue;
  5278. for (k = 0; k < len; k++) {
  5279. char a = s[start + k];
  5280. if (a >= 'A' && a <= 'Z')
  5281. a = (char)(a - 'A' + 'a');
  5282. if (a != x[k])
  5283. break;
  5284. }
  5285. if (k == len)
  5286. return 1;
  5287. }
  5288. return 0;
  5289. }
  5290. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  5291. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  5292. * Enter to the first network request. */
  5293. static int looks_like_host(const char *s)
  5294. {
  5295. unsigned int i = 0;
  5296. int dot = 0;
  5297. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  5298. s[i] != ':') {
  5299. char c = s[i];
  5300. if (c == '.') {
  5301. dot = 1;
  5302. } else if (!((c >= 'a' && c <= 'z') ||
  5303. (c >= 'A' && c <= 'Z') ||
  5304. (c >= '0' && c <= '9') ||
  5305. c == '-' || c == '_')) {
  5306. return 0;
  5307. }
  5308. i++;
  5309. }
  5310. return dot && i > 0 && !local_file_ext(s);
  5311. }
  5312. static void load_remote(const char *url, int push)
  5313. {
  5314. char canon[BR_URL_MAX];
  5315. s_copy(canon, url, sizeof(canon));
  5316. origin_cache_apply(canon, sizeof(canon));
  5317. load_page(canon, 0, push);
  5318. }
  5319. static void navigate(const char *input, int push)
  5320. {
  5321. char target[BR_URL_MAX];
  5322. char *t;
  5323. if (!input)
  5324. return;
  5325. s_copy(target, input, sizeof(target));
  5326. t = trim(target);
  5327. if (!t[0])
  5328. return;
  5329. if (s_eq(t, "about:home")) {
  5330. load_home(push);
  5331. return;
  5332. }
  5333. if (starts_with(t, "file://")) {
  5334. make_abs_local(t + 7, target, sizeof(target));
  5335. load_page(target, 1, push);
  5336. return;
  5337. }
  5338. if (is_http(t)) {
  5339. load_remote(t, push);
  5340. return;
  5341. }
  5342. if (t[0] == '/') {
  5343. make_abs_local(t, target, sizeof(target));
  5344. load_page(target, 1, push);
  5345. return;
  5346. }
  5347. if (!looks_like_host(t)) {
  5348. struct sys_stat st;
  5349. if (u_stat(t, &st) == 0 && !st.is_dir) {
  5350. make_abs_local(t, target, sizeof(target));
  5351. load_page(target, 1, push);
  5352. return;
  5353. }
  5354. }
  5355. {
  5356. /* A typed bare host tries https first: nearly every site
  5357. * redirects http -> https anyway, and that hop costs a whole
  5358. * extra connection. load_page() falls back to http when the
  5359. * https connection itself fails. */
  5360. char with_scheme[BR_URL_MAX];
  5361. unsigned int n = 0;
  5362. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  5363. s_append(with_scheme, &n, t, sizeof(with_scheme));
  5364. nav_https_upgraded = 1;
  5365. load_remote(with_scheme, push);
  5366. }
  5367. }
  5368. /* ---- layout ---- */
  5369. static struct ufont_face *style_face(const struct br_style *st)
  5370. {
  5371. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  5372. return font_faces[st->font_face - 1];
  5373. return 0;
  5374. }
  5375. static struct ufont_face *run_face(const struct lay_run *r)
  5376. {
  5377. if (r->font_face && r->font_face <= BR_MAX_FACES)
  5378. return font_faces[r->font_face - 1];
  5379. return 0;
  5380. }
  5381. static unsigned int face_text_width(struct ngui *gui,
  5382. const struct br_style *st,
  5383. const char *s, unsigned int n)
  5384. {
  5385. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  5386. st->bold, st->italic, st->mono);
  5387. }
  5388. static int face_line_height(struct ngui *gui, const struct br_style *st)
  5389. {
  5390. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  5391. st->mono);
  5392. }
  5393. static unsigned int run_text_width(struct ngui *gui,
  5394. const struct lay_run *r,
  5395. const char *s, unsigned int n)
  5396. {
  5397. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  5398. r->bold, r->italic, r->mono);
  5399. }
  5400. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  5401. {
  5402. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  5403. r->mono);
  5404. }
  5405. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  5406. {
  5407. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  5408. }
  5409. static struct br_style base_style(void)
  5410. {
  5411. struct br_style s = { 0 };
  5412. s.color = ui.theme.text;
  5413. s.bg = ui.theme.bg;
  5414. s.has_bg = 0;
  5415. for (int i = 0; i < 4; i++) {
  5416. s.border_c[i] = 0;
  5417. s.border_w[i] = 0;
  5418. s.border_s[i] = BR_BORDER_SOLID;
  5419. }
  5420. s.font_px = 16;
  5421. s.bold = 0;
  5422. s.italic = 0;
  5423. s.mono = 0;
  5424. s.underline = 0;
  5425. s.strike = 0;
  5426. s.overline = 0;
  5427. s.align = BR_ALIGN_LEFT;
  5428. s.display = BR_DISPLAY_BLOCK;
  5429. s.no_bullet = 0;
  5430. s.list_style = BR_LIST_AUTO;
  5431. s.uppercase = 0;
  5432. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  5433. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  5434. s.width = s.max_width = s.min_width = 0;
  5435. s.height = s.min_height = s.max_height = 0;
  5436. s.box_sizing = 0;
  5437. s.ml_auto = s.mr_auto = 0;
  5438. s.line_h_pct = 0;
  5439. s.line_h_px = 0;
  5440. s.mt = s.mb = s.ml = s.mr = 0;
  5441. s.pt = s.pb = s.pl = s.pr = 0;
  5442. return s;
  5443. }
  5444. /* The style node 0's children inherit. Node 0 is the first parsed node:
  5445. * a minified page that starts `<!doctype html><html ...>` makes it the
  5446. * <html> element itself, and the layout walks only its children, so its
  5447. * own cascade (html { color; font } -- Docusaurus/Infima put the page
  5448. * colour and font there) used to be skipped and the theme defaults showed
  5449. * through. Only inherited properties are taken: the root's box (margins,
  5450. * display, background) is not a container style for its children here. */
  5451. static struct br_style root_style(void)
  5452. {
  5453. struct br_style base = base_style(), st;
  5454. if (!doc.nnode || doc.nodes[doc.root].type != BR_NODE_ELEM ||
  5455. doc.nodes[doc.root].tag != BR_TAG_HTML)
  5456. return base;
  5457. br_style_for(&doc, doc.root, &base, &st);
  5458. base.color = st.color;
  5459. base.font_px = st.font_px;
  5460. base.bold = st.bold;
  5461. base.italic = st.italic;
  5462. base.mono = st.mono;
  5463. base.font_face = st.font_face;
  5464. base.align = st.align;
  5465. base.line_h_pct = st.line_h_pct;
  5466. base.line_h_px = st.line_h_px;
  5467. base.nowrap = st.nowrap;
  5468. base.uppercase = st.uppercase;
  5469. base.cursor = st.cursor;
  5470. base.vis_hidden = st.vis_hidden;
  5471. base.fill_mode = st.fill_mode;
  5472. base.fill = st.fill;
  5473. base.stroke_mode = st.stroke_mode;
  5474. base.stroke = st.stroke;
  5475. base.stroke_w = st.stroke_w;
  5476. base.fill_evenodd = st.fill_evenodd;
  5477. return base;
  5478. }
  5479. /* Resolve a margin/padding raw value. Percentages use the containing
  5480. * block width for all four sides, as CSS specifies. */
  5481. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  5482. {
  5483. if (unit == 1)
  5484. return base * v / 10000;
  5485. if (unit == 2)
  5486. return st->font_px * v / 100;
  5487. if (unit == 3)
  5488. return (int)br_root_font_px() * v / 100;
  5489. if (unit == 4)
  5490. return 0;
  5491. return v;
  5492. }
  5493. static int mp_px(const struct br_style *st, int side, int base)
  5494. {
  5495. int raw;
  5496. switch (side) {
  5497. case 0: raw = st->mt; break;
  5498. case 1: raw = st->mr; break;
  5499. case 2: raw = st->mb; break;
  5500. case 3: raw = st->ml; break;
  5501. case 4: raw = st->pt; break;
  5502. case 5: raw = st->pr; break;
  5503. case 6: raw = st->pb; break;
  5504. default: raw = st->pl; break;
  5505. }
  5506. if (st->mp_unit[side] == 5)
  5507. return base * raw / 100 + st->mp_calc_px[side];
  5508. return css_mp_px(st, raw, st->mp_unit[side], base);
  5509. }
  5510. static int style_width_px(const struct br_style *st, int base)
  5511. {
  5512. if (st->width_kind == 1)
  5513. return st->width;
  5514. if (st->width_kind == 2)
  5515. return base * (int)st->width / 100;
  5516. if (st->width_kind == 3)
  5517. return base * st->width_calc_pct / 100 + st->width_calc_px;
  5518. return 0;
  5519. }
  5520. static int style_height_px(const struct br_style *st, int base)
  5521. {
  5522. if (st->height_kind == 1)
  5523. return st->height;
  5524. if (st->height_kind == 2)
  5525. return base * (int)st->height / 100;
  5526. if (st->height_kind == 3)
  5527. return base * st->height_calc_pct / 100 + st->height_calc_px;
  5528. return 0;
  5529. }
  5530. static int css_size(unsigned char kind, int val, int base)
  5531. {
  5532. if (kind == 1)
  5533. return val;
  5534. if (kind == 2)
  5535. return base * val / 100;
  5536. return -1;
  5537. }
  5538. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  5539. int thick, int horizontal, unsigned short color,
  5540. unsigned char style)
  5541. {
  5542. int pos;
  5543. if (len <= 0 || thick <= 0)
  5544. return;
  5545. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  5546. if (horizontal)
  5547. ngui_fill_rect(ui, (struct ngui_rect){
  5548. x, y, len, thick}, color);
  5549. else
  5550. ngui_fill_rect(ui, (struct ngui_rect){
  5551. x, y, thick, len}, color);
  5552. return;
  5553. }
  5554. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  5555. int seg = len - pos;
  5556. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  5557. seg = style == BR_BORDER_DASHED ? 4 : 2;
  5558. if (horizontal)
  5559. ngui_fill_rect(ui, (struct ngui_rect){
  5560. x + pos, y, seg, thick}, color);
  5561. else
  5562. ngui_fill_rect(ui, (struct ngui_rect){
  5563. x, y + pos, thick, seg}, color);
  5564. }
  5565. }
  5566. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  5567. const struct br_style *st)
  5568. {
  5569. int top = st->border_w[0], right = st->border_w[1];
  5570. int bottom = st->border_w[2], left = st->border_w[3];
  5571. if (r.w <= 0 || r.h <= 0)
  5572. return;
  5573. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  5574. int i;
  5575. for (i = 0; i < 4; i++)
  5576. if (st->border_w[i] && !st->border_t[i]) {
  5577. ngui_fill_rect(ui, r, st->border_c[i]);
  5578. break;
  5579. }
  5580. return;
  5581. }
  5582. if (top && !st->border_t[0])
  5583. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  5584. st->border_c[0], st->border_s[0]);
  5585. if (bottom && !st->border_t[2])
  5586. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  5587. st->border_c[2], st->border_s[2]);
  5588. if (left && !st->border_t[3])
  5589. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  5590. left, 0, st->border_c[3], st->border_s[3]);
  5591. if (right && !st->border_t[1])
  5592. draw_border_side(ui, r.x + r.w - right, r.y + top,
  5593. r.h - top - bottom, right, 0,
  5594. st->border_c[1], st->border_s[1]);
  5595. }
  5596. static void transform_origin(const struct br_style *st, int w, int h,
  5597. int *ox, int *oy)
  5598. {
  5599. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  5600. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  5601. }
  5602. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  5603. unsigned int a)
  5604. {
  5605. unsigned int dr, dg, db, sr, sg, sb;
  5606. if (a >= 255)
  5607. return s;
  5608. dr = (d >> 11) & 31;
  5609. dg = (d >> 5) & 63;
  5610. db = d & 31;
  5611. sr = (s >> 11) & 31;
  5612. sg = (s >> 5) & 63;
  5613. sb = s & 31;
  5614. dr = (dr * (255 - a) + sr * a) / 255;
  5615. dg = (dg * (255 - a) + sg * a) / 255;
  5616. db = (db * (255 - a) + sb * a) / 255;
  5617. return (unsigned short)((dr << 11) | (dg << 5) | db);
  5618. }
  5619. /* Paint a solid box through scale()/rotate() around transform-origin. This
  5620. * transforms the element's own background box; text and descendants keep
  5621. * their layout (documented approximation). */
  5622. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  5623. unsigned short color,
  5624. const struct br_style *st)
  5625. {
  5626. double sx = st->scale_x / 100.0;
  5627. double sy = st->scale_y / 100.0;
  5628. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  5629. double c = cos(th), sn = sin(th);
  5630. int ox, oy, minx, miny, maxx, maxy, x, y;
  5631. double ax, ay;
  5632. double px[4], py[4];
  5633. int cx1, cy1, cx2, cy2, i;
  5634. if (sx == 0)
  5635. sx = 0.01;
  5636. if (sy == 0)
  5637. sy = 0.01;
  5638. transform_origin(st, box.w, box.h, &ox, &oy);
  5639. ax = box.x + ox;
  5640. ay = box.y + oy;
  5641. px[0] = -ox; py[0] = -oy;
  5642. px[1] = box.w - ox; py[1] = -oy;
  5643. px[2] = box.w - ox; py[2] = box.h - oy;
  5644. px[3] = -ox; py[3] = box.h - oy;
  5645. minx = miny = 1000000;
  5646. maxx = maxy = -1000000;
  5647. for (i = 0; i < 4; i++) {
  5648. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  5649. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  5650. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5651. if (dx < minx) minx = dx;
  5652. if (dx > maxx) maxx = dx;
  5653. if (dy < miny) miny = dy;
  5654. if (dy > maxy) maxy = dy;
  5655. }
  5656. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5657. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5658. cx2 = page_rect.x + page_rect.w - 12;
  5659. cy2 = page_rect.y + page_rect.h;
  5660. if (cx2 > gui->w) cx2 = gui->w;
  5661. if (cy2 > gui->h) cy2 = gui->h;
  5662. if (minx < cx1) minx = cx1;
  5663. if (miny < cy1) miny = cy1;
  5664. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5665. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5666. for (y = miny; y <= maxy; y++) {
  5667. for (x = minx; x <= maxx; x++) {
  5668. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  5669. double rx = dx * c + dy * sn;
  5670. double ry = -dx * sn + dy * c;
  5671. double bx = rx / sx + ox;
  5672. double by = ry / sy + oy;
  5673. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  5674. gui->px[y * gui->w + x] = color;
  5675. }
  5676. }
  5677. }
  5678. static void draw_image_transformed(struct ngui *gui,
  5679. const struct img_image *im,
  5680. int x, int y, int w, int h,
  5681. int sx100, int sy100, int rot100,
  5682. int origin_x, int origin_y,
  5683. int origin_x_kind, int origin_y_kind)
  5684. {
  5685. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  5686. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  5687. double c = cos(th), sn = sin(th);
  5688. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  5689. double ax, ay;
  5690. double bx[4], by[4];
  5691. int cx1, cy1, cx2, cy2;
  5692. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  5693. return;
  5694. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  5695. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  5696. ax = x + ox;
  5697. ay = y + oy;
  5698. bx[0] = -ox; by[0] = -oy;
  5699. bx[1] = w - ox; by[1] = -oy;
  5700. bx[2] = w - ox; by[2] = h - oy;
  5701. bx[3] = -ox; by[3] = h - oy;
  5702. minx = miny = 1000000;
  5703. maxx = maxy = -1000000;
  5704. for (i = 0; i < 4; i++) {
  5705. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  5706. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  5707. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5708. if (dx < minx) minx = dx;
  5709. if (dx > maxx) maxx = dx;
  5710. if (dy < miny) miny = dy;
  5711. if (dy > maxy) maxy = dy;
  5712. }
  5713. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5714. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5715. cx2 = page_rect.x + page_rect.w - 12;
  5716. cy2 = page_rect.y + page_rect.h;
  5717. if (cx2 > gui->w) cx2 = gui->w;
  5718. if (cy2 > gui->h) cy2 = gui->h;
  5719. if (minx < cx1) minx = cx1;
  5720. if (miny < cy1) miny = cy1;
  5721. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5722. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5723. for (py = miny; py <= maxy; py++) {
  5724. for (px = minx; px <= maxx; px++) {
  5725. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  5726. double rx = dx * c + dy * sn;
  5727. double ry = -dx * sn + dy * c;
  5728. double fx = rx / sx + ox;
  5729. double fy = ry / sy + oy;
  5730. int ix, iy;
  5731. unsigned int si, a;
  5732. unsigned short src;
  5733. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  5734. continue;
  5735. ix = (int)(fx * (double)im->w / w);
  5736. iy = (int)(fy * (double)im->h / h);
  5737. if (ix < 0 || ix >= (int)im->w ||
  5738. iy < 0 || iy >= (int)im->h)
  5739. continue;
  5740. si = (unsigned int)iy * im->w + (unsigned int)ix;
  5741. src = im->px[si];
  5742. a = im->alpha ? im->alpha[si] : 255;
  5743. gui->px[py * gui->w + px] =
  5744. a >= 255 ? src :
  5745. blend_rgb565(gui->px[py * gui->w + px],
  5746. src, a);
  5747. }
  5748. }
  5749. }
  5750. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5751. unsigned int node, const struct br_style *st);
  5752. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  5753. * first and every pixel outside a corner's arc is restored afterwards. */
  5754. #define BG_ROUND_MAX 64
  5755. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  5756. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  5757. unsigned int node, const struct br_style *st,
  5758. int rtl, int rtr, int rbr, int rbl)
  5759. {
  5760. struct ngui *ui = l->ui;
  5761. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  5762. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  5763. if (ui->nclip > 0)
  5764. clip = ui->clip[ui->nclip - 1];
  5765. for (c = 0; c < 4; c++) {
  5766. if (r[c] > BG_ROUND_MAX)
  5767. r[c] = BG_ROUND_MAX;
  5768. if (r[c] > box.w / 2)
  5769. r[c] = box.w / 2;
  5770. if (r[c] > box.h / 2)
  5771. r[c] = box.h / 2;
  5772. }
  5773. for (c = 0; c < 4; c++) {
  5774. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5775. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5776. for (dy = 0; dy < r[c]; dy++)
  5777. for (dx = 0; dx < r[c]; dx++) {
  5778. int px = ox + dx, py = oy + dy;
  5779. if (px >= clip.x && py >= clip.y &&
  5780. px < clip.x + clip.w && py < clip.y + clip.h)
  5781. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  5782. ui->px[py * ui->w + px];
  5783. }
  5784. }
  5785. draw_bg_image(l, box, node, st);
  5786. for (c = 0; c < 4; c++) {
  5787. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5788. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5789. /* arc centre, in corner-square coordinates */
  5790. int cx = (c == 1 || c == 2) ? 0 : r[c];
  5791. int cy = (c >= 2) ? 0 : r[c];
  5792. for (dy = 0; dy < r[c]; dy++)
  5793. for (dx = 0; dx < r[c]; dx++) {
  5794. int px = ox + dx, py = oy + dy;
  5795. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  5796. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  5797. continue;
  5798. if (px >= clip.x && py >= clip.y &&
  5799. px < clip.x + clip.w && py < clip.y + clip.h)
  5800. ui->px[py * ui->w + px] =
  5801. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  5802. }
  5803. }
  5804. }
  5805. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5806. unsigned int node, const struct br_style *st)
  5807. {
  5808. struct br_image *bi;
  5809. struct img_blit b;
  5810. int tw, th, x, y, rep_x, rep_y, posx, posy;
  5811. unsigned int scale = 65536;
  5812. int legacy, tiles = 0, rows = 0;
  5813. int cx1, cy1, cx2, cy2;
  5814. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  5815. return;
  5816. if (doc.nodes[node].bg_img_index < 0 ||
  5817. doc.nodes[node].bg_img_index >= image_count)
  5818. return;
  5819. bi = &images[doc.nodes[node].bg_img_index];
  5820. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  5821. return;
  5822. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  5823. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  5824. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  5825. if (legacy) {
  5826. scale = ((unsigned int)box.w << 16) / bi->img.w;
  5827. tw = box.w;
  5828. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  5829. x = box.x;
  5830. y = box.y;
  5831. rep_x = rep_y = 0;
  5832. } else {
  5833. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  5834. unsigned int sx = ((unsigned int)box.w << 16) /
  5835. bi->img.w;
  5836. unsigned int sy = ((unsigned int)box.h << 16) /
  5837. bi->img.h;
  5838. scale = st->bg_size_kind == 3 ?
  5839. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  5840. } else if (st->bg_size_kind == 1 ||
  5841. st->bg_size_kind == 2) {
  5842. int w = st->bg_size_w;
  5843. int h = st->bg_size_h;
  5844. if (st->bg_size_kind == 2) {
  5845. if (w)
  5846. w = box.w * w / 100;
  5847. if (h)
  5848. h = box.h * h / 100;
  5849. }
  5850. if (w)
  5851. scale = ((unsigned int)w << 16) / bi->img.w;
  5852. else if (h)
  5853. scale = ((unsigned int)h << 16) / bi->img.h;
  5854. }
  5855. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  5856. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  5857. if (tw < 1)
  5858. tw = 1;
  5859. if (th < 1)
  5860. th = 1;
  5861. posx = st->bg_pos_x_kind == 1 ?
  5862. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  5863. posy = st->bg_pos_y_kind == 1 ?
  5864. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  5865. x = box.x + posx;
  5866. y = box.y + posy;
  5867. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  5868. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  5869. if (rep_x) {
  5870. int m = (x - box.x) % tw;
  5871. if (m > 0)
  5872. m -= tw;
  5873. x = box.x + m;
  5874. }
  5875. if (rep_y) {
  5876. int m = (y - box.y) % th;
  5877. if (m > 0)
  5878. m -= th;
  5879. y = box.y + m;
  5880. }
  5881. }
  5882. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  5883. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  5884. cx2 = box.x + box.w;
  5885. cy2 = box.y + box.h;
  5886. if (cx2 > page_rect.x + page_rect.w - 12)
  5887. cx2 = page_rect.x + page_rect.w - 12;
  5888. if (cy2 > page_rect.y + page_rect.h)
  5889. cy2 = page_rect.y + page_rect.h;
  5890. if (cx1 >= cx2 || cy1 >= cy2)
  5891. return;
  5892. b.dst = l->ui->px;
  5893. b.dst_w = l->ui->w;
  5894. b.dst_h = l->ui->h;
  5895. b.clip_x = cx1;
  5896. b.clip_y = cy1;
  5897. b.clip_w = cx2 - cx1;
  5898. b.clip_h = cy2 - cy1;
  5899. b.bg = ui.theme.bg;
  5900. b.bg2 = ui.theme.bg;
  5901. b.dst_a = 0;
  5902. {
  5903. struct img_image *src = image_display_get(bi, tw, th);
  5904. int row_x;
  5905. if (!src)
  5906. src = &bi->img;
  5907. b.scale = ((unsigned int)tw << 16) / src->w;
  5908. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  5909. row_x = x;
  5910. for (;;) {
  5911. for (;;) {
  5912. b.x = x;
  5913. b.y = y;
  5914. img_draw(src, &b);
  5915. if (!rep_x || ++tiles > 512)
  5916. break;
  5917. x += tw;
  5918. if (x >= box.x + box.w)
  5919. break;
  5920. }
  5921. if (!rep_y || ++rows > 64)
  5922. break;
  5923. y += th;
  5924. if (y >= box.y + box.h)
  5925. break;
  5926. x = row_x;
  5927. }
  5928. }
  5929. }
  5930. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  5931. int *out_w, int *out_h);
  5932. static void svg_paint_box(struct ngui *ui, unsigned int node,
  5933. const struct br_style *st, int x, int y, int w,
  5934. int h);
  5935. /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
  5936. * RUN_SVG an inline <svg> icon (its node in off). */
  5937. #define RUN_SVG (-3)
  5938. static int run_width(const struct lay_run *r)
  5939. {
  5940. if (r->img >= 0)
  5941. return r->iw;
  5942. if (r->img == -2 || r->img == RUN_SVG)
  5943. return r->iw;
  5944. return (int)r->w;
  5945. }
  5946. static void start_line(struct lay *l, const struct br_style *st)
  5947. {
  5948. (void)st;
  5949. if (l->nruns == 0) {
  5950. l->line_y = l->y;
  5951. l->line_h = 0;
  5952. }
  5953. l->line_left = l->left;
  5954. l->line_right = l->right;
  5955. if (l->float_active && l->line_y < l->float_bottom) {
  5956. if (l->float_left > l->line_left)
  5957. l->line_left = l->float_left;
  5958. if (l->float_right < l->line_right)
  5959. l->line_right = l->float_right;
  5960. }
  5961. if (l->line_right < l->line_left + 8)
  5962. l->line_right = l->line_left + 8;
  5963. l->line_x = l->line_left;
  5964. l->run_x = l->line_left;
  5965. }
  5966. static void flush_line(struct lay *l)
  5967. {
  5968. int total, x, i, vis;
  5969. if (!l->nruns && l->line_x == l->line_left) {
  5970. l->line_h = 0;
  5971. return;
  5972. }
  5973. total = l->line_x - l->line_left;
  5974. x = l->line_left;
  5975. vis = 1;
  5976. if (l->draw) {
  5977. int lh = l->line_h ? l->line_h : 16;
  5978. vis = l->line_y + lh >= page_rect.y &&
  5979. l->line_y <= page_rect.y + page_rect.h;
  5980. }
  5981. if (l->align == BR_ALIGN_CENTER)
  5982. x += (l->line_right - l->line_left - total) / 2;
  5983. else if (l->align == BR_ALIGN_RIGHT)
  5984. x = l->line_right - total;
  5985. if (x < l->line_left)
  5986. x = l->line_left;
  5987. for (i = 0; i < l->nruns; i++) {
  5988. struct lay_run *r = &l->runs[i];
  5989. int w = run_width(r);
  5990. int ry = l->line_y + r->dy;
  5991. x += r->gap;
  5992. if (l->draw && vis) {
  5993. if (r->form) {
  5994. unsigned int node = r->form - 1;
  5995. struct form_state *fs = form_get(node, 1);
  5996. int hh = r->ih ? r->ih : 20;
  5997. int focused = form_focus == node;
  5998. int disabled = r->form_disabled;
  5999. unsigned short bg = l->ui->theme.panel_alt;
  6000. unsigned short fg = disabled ? 0x8410 : r->color;
  6001. struct ngui_rect box = {x, ry, w, hh};
  6002. if (r->form_kind == FORM_CHECKBOX ||
  6003. r->form_kind == FORM_RADIO) {
  6004. ngui_fill_rect(l->ui, box, bg);
  6005. ngui_frame(l->ui, box,
  6006. focused ? l->ui->theme.accent :
  6007. l->ui->theme.border);
  6008. if (fs && fs->checked) {
  6009. struct ngui_rect dot = {
  6010. x + 4, ry + 4,
  6011. w > 8 ? w - 8 : 1,
  6012. hh > 8 ? hh - 8 : 1
  6013. };
  6014. if (r->form_kind == FORM_RADIO)
  6015. ngui_fill_round_rect(
  6016. l->ui, dot, 4,
  6017. 4, 4, 4,
  6018. l->ui->theme.accent);
  6019. else
  6020. ngui_fill_rect(l->ui,
  6021. dot,
  6022. l->ui->theme.accent);
  6023. }
  6024. } else {
  6025. int editable =
  6026. r->form_kind == FORM_TEXT ||
  6027. r->form_kind == FORM_PASSWORD ||
  6028. r->form_kind == FORM_TEXTAREA;
  6029. int scroll = 0;
  6030. /* Editable fields draw the live value
  6031. * (r->lit is a short copy). */
  6032. static char shown[FORM_VALUE_MAX + 1];
  6033. const char *txt = r->lit;
  6034. unsigned int tl = s_len(r->lit);
  6035. if (editable && fs && fs->len) {
  6036. unsigned int k;
  6037. if (r->form_kind == FORM_PASSWORD) {
  6038. for (k = 0; k < fs->len; k++)
  6039. shown[k] = '*';
  6040. shown[k] = '\0';
  6041. txt = shown;
  6042. } else {
  6043. txt = fs->value;
  6044. }
  6045. tl = fs->len;
  6046. }
  6047. struct br_style fst;
  6048. int author, tx = x + 6, pr = 6;
  6049. style_for_node(node, &fst);
  6050. author = form_author_styled(&fst);
  6051. if (author) {
  6052. /* The page styled the control:
  6053. * its background, border, radius
  6054. * and text colour. */
  6055. form_paint_author(l->ui, box, &fst,
  6056. focused);
  6057. tx = x + fst.border_w[3] +
  6058. mp_px(&fst, 7, w);
  6059. pr = fst.border_w[1] +
  6060. mp_px(&fst, 5, w);
  6061. if (tx < x + 2 && !editable)
  6062. tx = x + 2;
  6063. if (!disabled)
  6064. fg = editable && fs &&
  6065. !fs->len ?
  6066. 0x8410 : fst.color;
  6067. if (!editable) {
  6068. int tw0 = (int)
  6069. run_text_width(l->ui,
  6070. r, txt, tl);
  6071. tx = x + (w - tw0) / 2;
  6072. }
  6073. } else {
  6074. /* The box is drawn in theme colours, so
  6075. * the text is too: the page's CSS colour
  6076. * (dark on a light page) would vanish on
  6077. * the dark field. */
  6078. if (!disabled)
  6079. fg = editable && fs && !fs->len ?
  6080. l->ui->theme.text_dim :
  6081. l->ui->theme.text;
  6082. ngui_fill_rect(l->ui, box, bg);
  6083. ngui_frame(l->ui, box,
  6084. focused ? l->ui->theme.accent :
  6085. l->ui->theme.border);
  6086. }
  6087. /* A value wider than the field shows its
  6088. * tail (where typing happens). */
  6089. if (editable && fs && fs->len &&
  6090. w > (tx - x) + pr) {
  6091. int tw = (int)run_text_width(l->ui,
  6092. r, txt, tl);
  6093. int room = w - (tx - x) - pr;
  6094. if (tw > room)
  6095. scroll = tw - room;
  6096. }
  6097. ngui_push_clip(l->ui, (struct ngui_rect){
  6098. x + 1, ry + 1,
  6099. w > 2 ? w - 2 : 1,
  6100. hh > 2 ? hh - 2 : 1 });
  6101. ngui_text_px_face(l->ui, run_face(r),
  6102. tx - scroll,
  6103. ry + (hh - r->font_px) / 2 - 1,
  6104. txt, tl, fg, r->font_px,
  6105. r->bold, r->italic, r->mono);
  6106. if (focused && fs && editable) {
  6107. int cw = 0;
  6108. if (fs->len && fs->caret)
  6109. cw = (int)run_text_width(
  6110. l->ui, r, txt,
  6111. fs->caret < fs->len ?
  6112. fs->caret : fs->len);
  6113. ngui_fill_rect(l->ui,
  6114. (struct ngui_rect){
  6115. tx + cw - scroll,
  6116. ry + 4, 1,
  6117. hh > 8 ? hh - 8 : 1
  6118. },
  6119. l->ui->theme.accent);
  6120. }
  6121. ngui_pop_clip(l->ui);
  6122. if (r->form_kind == FORM_SELECT) {
  6123. ngui_text_px(l->ui, x + w - 12,
  6124. ry + 2, "v", 1, fg,
  6125. r->font_px, 0, 0, 0);
  6126. }
  6127. }
  6128. } else if (r->img == RUN_SVG) {
  6129. struct br_style sst;
  6130. style_for_node(r->off, &sst);
  6131. svg_paint_box(l->ui, r->off, &sst, x, ry, w,
  6132. r->ih);
  6133. } else if (r->img == -2) {
  6134. int hh = r->ih ? r->ih : 20;
  6135. ngui_fill_rect(l->ui,
  6136. (struct ngui_rect){x, ry, w, hh},
  6137. l->ui->theme.panel_alt);
  6138. ngui_frame(l->ui,
  6139. (struct ngui_rect){x, ry, w, hh},
  6140. l->ui->theme.border);
  6141. ngui_text_px_face(l->ui, run_face(r),
  6142. x + 6, ry + 2, r->lit,
  6143. s_len(r->lit), r->color,
  6144. r->font_px, r->bold, r->italic,
  6145. r->mono);
  6146. } else if (r->img >= 0) {
  6147. struct br_image *bi = &images[r->img];
  6148. if (bi->state == 1 && r->transform_scale) {
  6149. draw_image_transformed(l->ui, &bi->img,
  6150. x, ry, r->iw, r->ih,
  6151. r->scale_x, r->scale_y,
  6152. r->rotate_x100, r->origin_x,
  6153. r->origin_y, r->origin_x_kind,
  6154. r->origin_y_kind);
  6155. } else if (bi->state == 1) {
  6156. struct img_image *src =
  6157. image_display_get(bi, r->iw, r->ih);
  6158. struct img_blit b;
  6159. if (!src)
  6160. src = &bi->img;
  6161. b.dst = l->ui->px;
  6162. b.dst_w = l->ui->w;
  6163. b.dst_h = l->ui->h;
  6164. b.clip_x = page_rect.x;
  6165. b.clip_y = page_rect.y;
  6166. b.clip_w = page_rect.w - 12;
  6167. b.clip_h = page_rect.h;
  6168. b.x = x;
  6169. b.y = ry;
  6170. b.scale = ((unsigned int)r->iw << 16) /
  6171. src->w;
  6172. b.bg = ui.theme.bg;
  6173. b.bg2 = ui.theme.bg;
  6174. b.dst_a = 0;
  6175. b.flags = src->alpha ?
  6176. IMG_BLIT_OVER_DST : 0;
  6177. img_draw(src, &b);
  6178. }
  6179. } else {
  6180. const char *s = r->has_lit ? r->lit :
  6181. doc.text + r->off;
  6182. unsigned int n = r->has_lit ? s_len(r->lit) :
  6183. r->len;
  6184. ngui_text_px_face(l->ui, run_face(r), x, ry,
  6185. s, n, r->color, r->font_px,
  6186. r->bold, r->italic, r->mono);
  6187. if (r->underline)
  6188. ngui_fill_rect(l->ui,
  6189. (struct ngui_rect){x,
  6190. ry + run_ascent(l->ui, r) + 2,
  6191. w, 1}, r->color);
  6192. if (r->strike)
  6193. ngui_fill_rect(l->ui,
  6194. (struct ngui_rect){x,
  6195. ry + run_ascent(l->ui, r) -
  6196. (r->font_px > 3 ?
  6197. r->font_px / 3 : 1),
  6198. w, 1}, r->color);
  6199. if (r->overline)
  6200. ngui_fill_rect(l->ui,
  6201. (struct ngui_rect){x, ry,
  6202. w, 1}, r->color);
  6203. }
  6204. if (r->form || r->href) {
  6205. if (nhits < HIT_MAX) {
  6206. struct hit *h = &hits[nhits];
  6207. unsigned int target = r->form ?
  6208. r->form - 1 : r->href;
  6209. int hh = (r->form || r->img >= 0 ||
  6210. r->img == RUN_SVG) ?
  6211. r->ih :
  6212. run_line_height(l->ui, r);
  6213. int merge = nhits > 0 &&
  6214. hits[nhits - 1].node == target &&
  6215. hits[nhits - 1].y == ry &&
  6216. hits[nhits - 1].h == hh &&
  6217. x <= hits[nhits - 1].x +
  6218. hits[nhits - 1].w + 2;
  6219. if (merge) {
  6220. struct hit *p = &hits[nhits - 1];
  6221. int end = x + w;
  6222. if (end > p->x + p->w)
  6223. p->w = end - p->x;
  6224. } else {
  6225. h->x = x;
  6226. h->y = ry;
  6227. h->w = w;
  6228. h->h = hh;
  6229. h->node = (unsigned short)target;
  6230. nhits++;
  6231. }
  6232. }
  6233. }
  6234. }
  6235. x += w;
  6236. }
  6237. l->y += l->line_h + 2;
  6238. if (l->float_active && l->y >= l->float_bottom)
  6239. l->float_active = 0;
  6240. l->nruns = 0;
  6241. l->line_x = l->left;
  6242. l->run_x = l->left;
  6243. l->line_left = l->left;
  6244. l->line_right = l->right;
  6245. l->line_h = 0;
  6246. l->space_pending = 0;
  6247. }
  6248. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  6249. const struct br_style *st, unsigned short href,
  6250. const char *lit)
  6251. {
  6252. unsigned int n = lit ? s_len(lit) : len;
  6253. const char *tp = lit ? lit : doc.text + off;
  6254. int w = (int)face_text_width(l->ui, st, tp, n);
  6255. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6256. flush_line(l);
  6257. if (l->nruns == 0) {
  6258. l->line_y = l->y;
  6259. l->line_h = 0;
  6260. start_line(l, st);
  6261. }
  6262. {
  6263. struct lay_run *r = &l->runs[l->nruns++];
  6264. int gap = l->line_x - l->run_x;
  6265. if (gap < 0)
  6266. gap = 0;
  6267. r->gap = (unsigned short)gap;
  6268. r->off = off;
  6269. r->len = len;
  6270. r->color = st->color;
  6271. r->href = href;
  6272. r->dy = 0;
  6273. r->has_lit = 0;
  6274. r->form = 0;
  6275. r->form_kind = 0;
  6276. r->form_disabled = 0;
  6277. r->lit[0] = '\0';
  6278. if (lit && lit[0]) {
  6279. unsigned int i;
  6280. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  6281. r->lit[i] = lit[i];
  6282. r->lit[i] = '\0';
  6283. r->has_lit = 1;
  6284. }
  6285. r->img = -1;
  6286. r->iw = r->ih = 0;
  6287. r->font_px = st->font_px;
  6288. r->bold = st->bold;
  6289. r->italic = st->italic;
  6290. r->mono = st->mono;
  6291. r->font_face = st->font_face;
  6292. /* A control with its own background is a button, not body copy;
  6293. * an inherited link underline would strike through the fill. */
  6294. r->underline = st->underline && !st->has_bg;
  6295. r->strike = st->strike && !st->has_bg;
  6296. r->overline = st->overline && !st->has_bg;
  6297. r->w = (unsigned short)w;
  6298. if (r->has_lit)
  6299. r->w = (unsigned short)run_text_width(
  6300. l->ui, r, r->lit, s_len(r->lit));
  6301. w = r->w;
  6302. }
  6303. l->line_x += w;
  6304. l->run_x = l->line_x;
  6305. {
  6306. int lh = face_line_height(l->ui, st);
  6307. if (st->line_h_px)
  6308. lh = st->line_h_px;
  6309. else if (st->line_h_pct)
  6310. lh = st->font_px * st->line_h_pct / 100;
  6311. if (lh < face_line_height(l->ui, st))
  6312. lh = face_line_height(l->ui, st);
  6313. if (l->line_h < lh)
  6314. l->line_h = lh;
  6315. }
  6316. }
  6317. static void add_image_run(struct lay *l, unsigned int node,
  6318. const struct br_style *st, unsigned short href)
  6319. {
  6320. struct br_image *bi = 0;
  6321. int idx = doc.nodes[node].img_index;
  6322. int dw, dh, maxw;
  6323. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  6324. bi = &images[idx];
  6325. if (l->nruns == 0)
  6326. start_line(l, st);
  6327. if (l->space_pending &&
  6328. (l->nruns > 0 || l->line_x > l->line_left)) {
  6329. int sp = (int)face_text_width(l->ui, st, " ", 1);
  6330. if (l->line_x + sp <= l->line_right)
  6331. l->line_x += sp;
  6332. }
  6333. l->space_pending = 0;
  6334. if (!bi) {
  6335. const char *alt = br_alt(&doc, node);
  6336. struct br_style gs = *st;
  6337. char tmp[96];
  6338. unsigned int n = 0;
  6339. int w;
  6340. gs.color = BR_GRAY;
  6341. gs.underline = 0;
  6342. s_append(tmp, &n, "[", sizeof(tmp));
  6343. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  6344. s_append(tmp, &n, "]", sizeof(tmp));
  6345. w = (int)face_text_width(l->ui, &gs, tmp, n);
  6346. if (l->line_x + w > l->line_right &&
  6347. (l->nruns > 0 || l->line_x > l->line_left))
  6348. flush_line(l);
  6349. add_run(l, 0, 0, &gs, href, tmp);
  6350. if (!l->draw) {
  6351. int t = l->line_y < 0 ? 0 : l->line_y;
  6352. int hh = face_line_height(l->ui, &gs);
  6353. if (t > 65535)
  6354. t = 65535;
  6355. if (hh > 65535)
  6356. hh = 65535;
  6357. img_top[node] = (unsigned short)t;
  6358. img_h[node] = (unsigned short)hh;
  6359. }
  6360. return;
  6361. }
  6362. maxw = l->line_right - l->line_left;
  6363. if (maxw < 8)
  6364. maxw = 8;
  6365. {
  6366. int iw = bi->native_w, ih = bi->native_h;
  6367. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  6368. if (iw <= 0 || ih <= 0) {
  6369. iw = (int)bi->img.w;
  6370. ih = (int)bi->img.h;
  6371. }
  6372. dw = iw;
  6373. dh = ih;
  6374. if (doc.nodes[node].width_attr) {
  6375. int want = doc.nodes[node].width_attr;
  6376. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  6377. have_w = 1;
  6378. }
  6379. if (doc.nodes[node].height_attr) {
  6380. int want = doc.nodes[node].height_attr;
  6381. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  6382. have_h = 1;
  6383. }
  6384. if (have_w && !have_h)
  6385. dh = ih ? ih * dw / iw : 0;
  6386. if (have_h && !have_w)
  6387. dw = iw ? iw * dh / ih : 0;
  6388. if (st->width_kind) {
  6389. css_w = 1;
  6390. if (st->width_kind == 3)
  6391. dw = maxw * st->width_calc_pct / 100 +
  6392. st->width_calc_px;
  6393. else
  6394. dw = st->width_kind == 2 ?
  6395. maxw * (int)st->width / 100 :
  6396. (int)st->width;
  6397. }
  6398. /* Percentage heights resolve against the containing block's
  6399. * definite height (Docusaurus' logo: `.navbar__logo { height:
  6400. * 2rem }` holding an `img { height: 100% }`), and are auto
  6401. * when it has none; they used to use the width. */
  6402. if (st->height_kind == 1 ||
  6403. ((st->height_kind == 2 || st->height_kind == 3) &&
  6404. l->cb_h > 0)) {
  6405. css_h = 1;
  6406. if (st->height_kind == 3)
  6407. dh = l->cb_h * st->height_calc_pct / 100 +
  6408. st->height_calc_px;
  6409. else
  6410. dh = st->height_kind == 2 ?
  6411. l->cb_h * (int)st->height / 100 :
  6412. (int)st->height;
  6413. }
  6414. if (css_w && !css_h)
  6415. dh = ih ? ih * dw / iw : 0;
  6416. if (css_h && !css_w)
  6417. dw = iw ? iw * dh / ih : 0;
  6418. if (st->max_width_kind) {
  6419. int mw = st->max_width_kind == 3 ?
  6420. maxw * st->max_width_calc_pct / 100 +
  6421. st->max_width_calc_px :
  6422. st->max_width_kind == 2 ?
  6423. maxw * (int)st->max_width / 100 :
  6424. (int)st->max_width;
  6425. if (mw > 0 && dw > mw) {
  6426. dh = iw ? ih * mw / iw : 0;
  6427. dw = mw;
  6428. }
  6429. }
  6430. }
  6431. if (dw < 8)
  6432. dw = 8;
  6433. if (dh < 8)
  6434. dh = 8;
  6435. if (dw > maxw) {
  6436. dh = dw ? dh * maxw / dw : dh;
  6437. dw = maxw;
  6438. }
  6439. if (!l->draw) {
  6440. int t = l->line_y < 0 ? 0 : l->line_y;
  6441. if (t > 65535)
  6442. t = 65535;
  6443. if (dh > 65535)
  6444. dh = 65535;
  6445. img_top[node] = (unsigned short)t;
  6446. img_h[node] = (unsigned short)dh;
  6447. }
  6448. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  6449. l->line_x > l->line_left))
  6450. flush_line(l);
  6451. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6452. flush_line(l);
  6453. if (l->nruns == 0) {
  6454. l->line_y = l->y;
  6455. l->line_h = 0;
  6456. start_line(l, st);
  6457. }
  6458. {
  6459. struct lay_run *r = &l->runs[l->nruns++];
  6460. int gap = l->line_x - l->run_x;
  6461. if (gap < 0)
  6462. gap = 0;
  6463. r->gap = (unsigned short)gap;
  6464. r->off = 0;
  6465. r->len = 0;
  6466. r->color = 0;
  6467. r->href = href;
  6468. r->form = 0;
  6469. r->form_kind = 0;
  6470. r->form_disabled = 0;
  6471. /* Inline replaced elements honour their vertical margins; this
  6472. * is how Bootstrap's negative logo margins centre the wordmark. */
  6473. {
  6474. int idy = mp_px(st, 0, l->right - l->left);
  6475. if (idy < -2048)
  6476. idy = -2048;
  6477. if (idy > 2048)
  6478. idy = 2048;
  6479. r->dy = (signed short)idy;
  6480. }
  6481. r->has_lit = 0;
  6482. r->lit[0] = '\0';
  6483. r->img = (short)idx;
  6484. r->iw = (unsigned short)dw;
  6485. r->ih = (unsigned short)dh;
  6486. r->w = (unsigned short)dw;
  6487. r->font_px = st->font_px;
  6488. r->bold = st->bold;
  6489. r->italic = st->italic;
  6490. r->mono = st->mono;
  6491. r->font_face = st->font_face;
  6492. r->transform_scale = st->transform_scale;
  6493. r->scale_x = st->scale_x;
  6494. r->scale_y = st->scale_y;
  6495. r->rotate_x100 = st->rotate_x100;
  6496. r->origin_x = st->origin_x;
  6497. r->origin_y = st->origin_y;
  6498. r->origin_x_kind = st->origin_x_kind;
  6499. r->origin_y_kind = st->origin_y_kind;
  6500. r->underline = 0;
  6501. }
  6502. if (node < BR_MAX_NODES) {
  6503. layout_boxes[node].x = l->line_x;
  6504. layout_boxes[node].y = l->line_y +
  6505. mp_px(st, 0, l->right - l->left);
  6506. layout_boxes[node].w = dw;
  6507. layout_boxes[node].h = dh;
  6508. layout_boxes[node].valid = 1;
  6509. }
  6510. l->line_x += dw;
  6511. l->run_x = l->line_x;
  6512. if (l->line_h < dh)
  6513. l->line_h = dh;
  6514. }
  6515. /* An inline (or inline-block) <svg> is a replaced element in the text
  6516. * line, like an <img>: comment bubbles and arrows sit next to their label
  6517. * instead of starting a block of their own. */
  6518. static void add_svg_run(struct lay *l, unsigned int node,
  6519. const struct br_style *st, unsigned short href)
  6520. {
  6521. struct lay_run *r;
  6522. int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
  6523. if (lw < 8)
  6524. lw = 8;
  6525. cw = st->width_kind ? style_width_px(st, lw) : lw;
  6526. if (cw < 1)
  6527. cw = 1;
  6528. svg_size(node, st, cw, &dw, &dh);
  6529. if (dw > lw)
  6530. dw = lw;
  6531. ml = mp_px(st, 3, lw);
  6532. mr = mp_px(st, 1, lw);
  6533. if (ml < 0)
  6534. ml = 0;
  6535. if (mr < 0)
  6536. mr = 0;
  6537. if (l->line_x + ml + dw > l->line_right &&
  6538. (l->nruns > 0 || l->line_x > l->line_left))
  6539. flush_line(l);
  6540. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6541. flush_line(l);
  6542. if (l->nruns == 0) {
  6543. l->line_y = l->y;
  6544. l->line_h = 0;
  6545. start_line(l, st);
  6546. }
  6547. l->line_x += ml;
  6548. r = &l->runs[l->nruns++];
  6549. memset(r, 0, sizeof(*r));
  6550. r->gap = (unsigned short)(l->line_x > l->run_x ?
  6551. l->line_x - l->run_x : 0);
  6552. r->off = node;
  6553. r->color = st->color;
  6554. r->href = href;
  6555. r->img = RUN_SVG;
  6556. r->iw = (unsigned short)dw;
  6557. r->ih = (unsigned short)dh;
  6558. r->w = (unsigned short)dw;
  6559. r->font_px = st->font_px;
  6560. if (node < BR_MAX_NODES) {
  6561. layout_boxes[node].x = l->line_x;
  6562. layout_boxes[node].y = l->line_y;
  6563. layout_boxes[node].w = dw;
  6564. layout_boxes[node].h = dh;
  6565. layout_boxes[node].valid = 1;
  6566. }
  6567. l->line_x += dw + mr;
  6568. l->run_x = l->line_x;
  6569. if (l->line_h < dh)
  6570. l->line_h = dh;
  6571. }
  6572. static int text_width(struct lay *l, const char *s, unsigned int n,
  6573. const struct br_style *st)
  6574. {
  6575. return (int)face_text_width(l->ui, st, s, n);
  6576. }
  6577. /* Longest prefix that fits in maxw, at least one byte. */
  6578. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  6579. const struct br_style *st, int maxw)
  6580. {
  6581. unsigned int take = 0;
  6582. while (take < n) {
  6583. if (text_width(l, s, take + 1, st) > maxw)
  6584. break;
  6585. take++;
  6586. }
  6587. return take ? take : 1;
  6588. }
  6589. static void emit_word(struct lay *l, const char *s, unsigned int start,
  6590. unsigned int n, unsigned int base,
  6591. const struct br_style *st, unsigned short href)
  6592. {
  6593. int avail;
  6594. int w = text_width(l, s + start, n, st);
  6595. unsigned int off = start;
  6596. if (l->nruns == 0)
  6597. start_line(l, st);
  6598. avail = l->line_right - l->line_left;
  6599. if (st->nowrap) {
  6600. if (n)
  6601. add_run(l, base + start,
  6602. (unsigned short)n, st, href, 0);
  6603. return;
  6604. }
  6605. /* A padded/bordered one-word button can be a few pixels wider than
  6606. * the content box; keep it on one line instead of splitting it. */
  6607. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  6608. add_run(l, base + start,
  6609. (unsigned short)n, st, href, 0);
  6610. return;
  6611. }
  6612. if (l->line_x + w > l->line_right &&
  6613. (l->nruns > 0 || l->line_x > l->line_left)) {
  6614. flush_line(l);
  6615. start_line(l, st);
  6616. avail = l->line_right - l->line_left;
  6617. }
  6618. if (w <= avail) {
  6619. if (n)
  6620. add_run(l, base + start,
  6621. (unsigned short)n, st, href, 0);
  6622. return;
  6623. }
  6624. while (n > 0) {
  6625. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  6626. add_run(l, base + off,
  6627. (unsigned short)take, st, href, 0);
  6628. off += take;
  6629. n -= take;
  6630. if (n) {
  6631. flush_line(l);
  6632. start_line(l, st);
  6633. avail = l->line_right - l->line_left;
  6634. }
  6635. }
  6636. }
  6637. static void emit_text(struct lay *l, const char *s, unsigned int len,
  6638. const struct br_style *st, unsigned short href, int pre)
  6639. {
  6640. unsigned int i = 0;
  6641. unsigned int base;
  6642. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  6643. if (!s || !len)
  6644. return;
  6645. if (space_w <= 0)
  6646. space_w = 8;
  6647. if (l->nruns == 0)
  6648. start_line(l, st);
  6649. base = (unsigned int)(s - doc.text);
  6650. if (st->uppercase) {
  6651. char *p = (char *)s;
  6652. unsigned int j;
  6653. for (j = 0; j < len; j++)
  6654. if (p[j] >= 'a' && p[j] <= 'z')
  6655. p[j] = (char)(p[j] - 'a' + 'A');
  6656. }
  6657. if (pre) {
  6658. while (i < len) {
  6659. unsigned int start;
  6660. if (s[i] == '\n') {
  6661. flush_line(l);
  6662. start_line(l, st);
  6663. i++;
  6664. continue;
  6665. }
  6666. if (s[i] == ' ') {
  6667. if (l->line_x + space_w > l->line_right &&
  6668. (l->nruns > 0 || l->line_x > l->line_left)) {
  6669. flush_line(l);
  6670. start_line(l, st);
  6671. } else {
  6672. l->line_x += space_w;
  6673. }
  6674. i++;
  6675. continue;
  6676. }
  6677. start = i;
  6678. while (i < len && s[i] != ' ' && s[i] != '\n')
  6679. i++;
  6680. emit_word(l, s, start, i - start, base, st, href);
  6681. }
  6682. return;
  6683. }
  6684. while (i < len) {
  6685. unsigned int start, n;
  6686. if (s[i] == ' ') {
  6687. l->space_pending = 1;
  6688. i++;
  6689. continue;
  6690. }
  6691. start = i;
  6692. while (i < len && s[i] != ' ')
  6693. i++;
  6694. n = i - start;
  6695. if (l->space_pending &&
  6696. (l->nruns > 0 || l->line_x > l->line_left)) {
  6697. if (st->nowrap ||
  6698. l->line_x + space_w <= l->line_right)
  6699. l->line_x += space_w;
  6700. }
  6701. l->space_pending = 0;
  6702. emit_word(l, s, start, n, base, st, href);
  6703. }
  6704. }
  6705. static int list_index(unsigned int parent, unsigned int node)
  6706. {
  6707. unsigned int n = 0, i;
  6708. for (i = doc.nodes[parent].first; i && i != node;
  6709. i = doc.nodes[i].next)
  6710. if (doc.nodes[i].tag == BR_TAG_LI)
  6711. n++;
  6712. return (int)n + 1;
  6713. }
  6714. static void list_roman(char *m, unsigned int *n, int v, int upper,
  6715. unsigned int cap)
  6716. {
  6717. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  6718. 50, 40, 10, 9, 5, 4, 1 };
  6719. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  6720. "l", "xl", "x", "ix", "v", "iv", "i" };
  6721. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  6722. "L", "XL", "X", "IX", "V", "IV", "I" };
  6723. unsigned int i;
  6724. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  6725. while (v >= val[i] && *n + 1 < cap) {
  6726. const char *s = upper ? up[i] : lo[i];
  6727. while (*s && *n + 1 < cap)
  6728. m[(*n)++] = *s++;
  6729. v -= val[i];
  6730. }
  6731. }
  6732. }
  6733. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  6734. {
  6735. unsigned int n = 0;
  6736. if (style == BR_LIST_DISC) {
  6737. m[n++] = '-';
  6738. } else if (style == BR_LIST_CIRCLE) {
  6739. m[n++] = 'o';
  6740. } else if (style == BR_LIST_SQUARE) {
  6741. m[n++] = '+';
  6742. } else if (style == BR_LIST_LOWER_ALPHA ||
  6743. style == BR_LIST_UPPER_ALPHA) {
  6744. if (idx >= 1 && idx <= 26)
  6745. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  6746. 'A' : 'a') + idx - 1);
  6747. else
  6748. m[n++] = '?';
  6749. m[n++] = '.';
  6750. } else if (style == BR_LIST_LOWER_ROMAN ||
  6751. style == BR_LIST_UPPER_ROMAN) {
  6752. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  6753. if (n + 1 < cap)
  6754. m[n++] = '.';
  6755. } else {
  6756. s_append_dec(m, &n, (unsigned int)idx, cap);
  6757. if (n + 1 < cap)
  6758. m[n++] = '.';
  6759. }
  6760. m[n] = '\0';
  6761. }
  6762. /* A control the page styled itself (background, border or radius in author
  6763. * CSS -- `background:transparent;border:none` counts) is painted with that
  6764. * style, sized from its padding/height and keeps the page's text colour.
  6765. * Unstyled controls keep the ngui theme look. */
  6766. static int form_author_styled(const struct br_style *st)
  6767. {
  6768. int i;
  6769. if (st->bg_set)
  6770. return 1;
  6771. for (i = 0; i < 4; i++)
  6772. if (st->border_w[i] || st->radius[i])
  6773. return 1;
  6774. return 0;
  6775. }
  6776. /* Set by the layout when the control is stretched to its line: a flex item
  6777. * (its box width was assigned by the flex row) or a child of a flex column,
  6778. * whose default align-items: stretch makes inputs full width. */
  6779. static int form_fill_line;
  6780. static void add_form_run(struct lay *l, unsigned int node,
  6781. const struct br_style *st, unsigned short href)
  6782. {
  6783. struct form_state *fs = form_get(node, 1);
  6784. char shown[FORM_VALUE_MAX + 1];
  6785. char opt[64];
  6786. const char *text = "";
  6787. struct lay_run *r;
  6788. int kind = form_kind_of(node);
  6789. int disabled = form_disabled(node);
  6790. int author = form_author_styled(st);
  6791. int tw, w = 120, h = 20, i, line_w, pad_x, pad_y;
  6792. int ml = 0, mr = 0, mt = 0, mb = 0;
  6793. if (!fs)
  6794. return;
  6795. if (l->nruns == 0)
  6796. start_line(l, st);
  6797. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  6798. text = "";
  6799. w = 16;
  6800. h = 16;
  6801. } else if (kind == FORM_SELECT) {
  6802. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  6803. s_copy(opt, "Select", sizeof(opt));
  6804. text = opt;
  6805. w = 120;
  6806. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  6807. kind == FORM_RESET) {
  6808. if (fs->len)
  6809. text = fs->value;
  6810. else if (doc.nodes[node].tag == BR_TAG_BUTTON)
  6811. /* A <button>'s label is its content: an empty one
  6812. * (Docusaurus' sidebar caret, drawn by a CSS
  6813. * ::before icon) shows none. Only <input> buttons
  6814. * get the UA's default label. */
  6815. text = "";
  6816. else
  6817. text = kind == FORM_SUBMIT ? "Submit" :
  6818. kind == FORM_RESET ? "Reset" : "Button";
  6819. } else if (kind == FORM_PASSWORD) {
  6820. for (i = 0; i < fs->len; i++)
  6821. shown[i] = '*';
  6822. shown[fs->len] = '\0';
  6823. text = fs->len ? shown : br_placeholder(&doc, node);
  6824. } else {
  6825. if (fs->len)
  6826. text = fs->value;
  6827. else
  6828. text = br_placeholder(&doc, node);
  6829. if (kind == FORM_TEXTAREA) {
  6830. w = 180;
  6831. h = 40;
  6832. }
  6833. }
  6834. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  6835. line_w = l->line_right - l->line_left;
  6836. pad_x = mp_px(st, 7, line_w) + mp_px(st, 5, line_w) +
  6837. st->border_w[1] + st->border_w[3];
  6838. pad_y = mp_px(st, 4, line_w) + mp_px(st, 6, line_w) +
  6839. st->border_w[0] + st->border_w[2];
  6840. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  6841. /* Buttons are border-box in every UA stylesheet: an
  6842. * explicit width/height is the whole box. */
  6843. if (author || pad_x) {
  6844. w = tw + pad_x;
  6845. } else {
  6846. w = tw + 18;
  6847. if (w < 64)
  6848. w = 64;
  6849. }
  6850. if (st->width_kind)
  6851. w = style_width_px(st, line_w);
  6852. if (st->min_width_kind == 1 && w < (int)st->min_width)
  6853. w = st->min_width;
  6854. if (st->height_kind == 1)
  6855. h = st->height;
  6856. else if (author)
  6857. h = st->font_px + 6 + pad_y;
  6858. else
  6859. h = 22;
  6860. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  6861. kind == FORM_TEXTAREA) {
  6862. int fill = form_fill_line || st->display == BR_DISPLAY_BLOCK ||
  6863. st->display == BR_DISPLAY_FLEX;
  6864. int boxed = st->box_sizing ? 0 : pad_x;
  6865. if (st->width_kind)
  6866. w = style_width_px(st, line_w) + boxed;
  6867. else if (fill)
  6868. w = line_w - (l->line_x - l->line_left);
  6869. else
  6870. w = kind == FORM_TEXTAREA ? 180 : 120;
  6871. if (kind == FORM_TEXTAREA) {
  6872. const char *ra = br_find_attr(&doc, node, "rows");
  6873. int rows = 0;
  6874. int lh = st->line_h_px ? st->line_h_px :
  6875. st->font_px * 5 / 4;
  6876. while (ra && *ra >= '0' && *ra <= '9')
  6877. rows = rows * 10 + (*ra++ - '0');
  6878. if (rows < 1 || rows > 40)
  6879. rows = 2;
  6880. h = author ? rows * lh + pad_y : 40;
  6881. } else if (author) {
  6882. h = st->font_px + 8 + pad_y;
  6883. } else if (st->font_px + 8 > h) {
  6884. /* Taller fields for large text (min-height/padding
  6885. * on login pages): keep the box around the glyphs. */
  6886. h = st->font_px + 8;
  6887. }
  6888. if (st->height_kind == 1)
  6889. h = st->height + (st->box_sizing ? 0 : pad_y);
  6890. if (st->min_height_kind == 1 && h < (int)st->min_height)
  6891. h = st->min_height;
  6892. } else if (kind == FORM_SELECT) {
  6893. w = st->width_kind == 1 ? st->width : 120;
  6894. }
  6895. if (author) {
  6896. /* Inline margins (Google's `margin:11px 4px` between its
  6897. * two submit buttons). */
  6898. ml = mp_px(st, 3, line_w);
  6899. mr = mp_px(st, 1, line_w);
  6900. mt = mp_px(st, 0, line_w);
  6901. mb = mp_px(st, 2, line_w);
  6902. if (ml < 0 || ml > 64) ml = 0;
  6903. if (mr < 0 || mr > 64) mr = 0;
  6904. if (mt < 0 || mt > 64) mt = 0;
  6905. if (mb < 0 || mb > 64) mb = 0;
  6906. }
  6907. if (w > line_w - ml - mr)
  6908. w = line_w - ml - mr;
  6909. if (w < 8)
  6910. w = 8;
  6911. if (h > 400)
  6912. h = 400;
  6913. if (l->line_x + ml + w > l->line_right &&
  6914. (l->nruns > 0 || l->line_x > l->line_left))
  6915. flush_line(l);
  6916. if (l->nruns >= 96)
  6917. return;
  6918. if (l->nruns == 0) {
  6919. l->line_y = l->y;
  6920. l->line_h = 0;
  6921. start_line(l, st);
  6922. }
  6923. l->line_x += ml;
  6924. r = &l->runs[l->nruns++];
  6925. r->gap = (unsigned short)(l->line_x - l->run_x);
  6926. r->off = r->len = 0;
  6927. r->color = st->color;
  6928. r->href = href;
  6929. r->dy = (signed short)mt;
  6930. r->has_lit = 1;
  6931. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  6932. r->lit[i] = text[i];
  6933. r->lit[i] = '\0';
  6934. r->img = -2;
  6935. r->iw = (unsigned short)w;
  6936. r->ih = (unsigned short)h;
  6937. r->w = (unsigned short)w;
  6938. r->font_px = st->font_px;
  6939. r->bold = st->bold;
  6940. r->italic = st->italic;
  6941. r->mono = st->mono;
  6942. r->font_face = st->font_face;
  6943. r->underline = 0;
  6944. r->form = node + 1;
  6945. r->form_kind = (unsigned char)kind;
  6946. r->form_disabled = (unsigned char)disabled;
  6947. if (node < BR_MAX_NODES) {
  6948. layout_boxes[node].x = l->line_x;
  6949. layout_boxes[node].y = l->line_y + mt;
  6950. layout_boxes[node].w = w;
  6951. layout_boxes[node].h = h;
  6952. layout_boxes[node].valid = 1;
  6953. }
  6954. l->line_x += w;
  6955. l->run_x = l->line_x;
  6956. l->line_x += mr;
  6957. if (l->line_h < h + mt + mb)
  6958. l->line_h = h + mt + mb;
  6959. }
  6960. /* Background, border and corner radius of an author-styled control, the
  6961. * same decoration rules as a block box. */
  6962. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  6963. const struct br_style *st, int focused)
  6964. {
  6965. int rtl = css_radius(st, 0, box.w, box.h);
  6966. int rtr = css_radius(st, 1, box.w, box.h);
  6967. int rbr = css_radius(st, 2, box.w, box.h);
  6968. int rbl = css_radius(st, 3, box.w, box.h);
  6969. int bw = st->border_t[0] ? 0 : st->border_w[0];
  6970. (void)focused;
  6971. if (box.w <= 0 || box.h <= 0)
  6972. return;
  6973. if (rtl || rtr || rbr || rbl) {
  6974. if (bw > 0 && st->has_bg && st->border_c[0] != st->bg &&
  6975. box.w > bw * 2 && box.h > bw * 2) {
  6976. struct ngui_rect in = { box.x + bw, box.y + bw,
  6977. box.w - bw * 2,
  6978. box.h - bw * 2 };
  6979. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  6980. st->border_c[0]);
  6981. ngui_fill_round_rect(ui, in,
  6982. rtl > bw ? rtl - bw : 0,
  6983. rtr > bw ? rtr - bw : 0,
  6984. rbr > bw ? rbr - bw : 0,
  6985. rbl > bw ? rbl - bw : 0, st->bg);
  6986. } else if (st->has_bg) {
  6987. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  6988. st->bg);
  6989. } else if (bw > 0) {
  6990. ngui_frame_round(ui, box, rtl, rtr, rbr, rbl, bw,
  6991. st->border_c[0]);
  6992. }
  6993. return;
  6994. }
  6995. if (st->has_bg)
  6996. ngui_fill_rect(ui, box, st->bg);
  6997. if (st->border_w[0] || st->border_w[1] || st->border_w[2] ||
  6998. st->border_w[3])
  6999. draw_border_box(ui, box, st);
  7000. }
  7001. /* A poster wrapper is absolutely positioned over the media slot; the
  7002. * measured height of its picture is normally added back to the flow. When a
  7003. * loading-skeleton sibling already reserves that slot, adding both doubles
  7004. * the media height and pushes the article text a full screen down. */
  7005. static int has_skeleton_sibling(unsigned int node)
  7006. {
  7007. unsigned int p = doc.nodes[node].parent, c;
  7008. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  7009. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  7010. continue;
  7011. if (doc.nodes[c].class_off &&
  7012. contains_ci(doc.attrs + doc.nodes[c].class_off,
  7013. "skeleton"))
  7014. return 1;
  7015. }
  7016. return 0;
  7017. }
  7018. static void layout_children(struct lay *l, unsigned int parent,
  7019. const struct br_style *pst, int depth,
  7020. unsigned short link);
  7021. static void layout_flex_children(struct lay *l, unsigned int parent,
  7022. const struct br_style *pst, int depth,
  7023. unsigned short link);
  7024. static void layout_grid_children(struct lay *l, unsigned int parent,
  7025. const struct br_style *pst, int depth,
  7026. unsigned short link);
  7027. static void layout_grid_auto(struct lay *l, unsigned int parent,
  7028. const struct br_style *pst, int depth,
  7029. unsigned short link);
  7030. static int flex_item_width(struct lay *l, unsigned int n,
  7031. const struct br_style *cs, int avail);
  7032. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  7033. const struct br_style *pst, int depth,
  7034. unsigned short link);
  7035. static void layout_table_row(struct lay *l, unsigned int row,
  7036. const struct br_style *pst, int depth,
  7037. unsigned short link);
  7038. static int table_has_rowspan(unsigned int table);
  7039. static void layout_table(struct lay *l, unsigned int table,
  7040. const struct br_style *st, int depth,
  7041. unsigned short link);
  7042. /* A flex container whose items are only inline spans is usually just a
  7043. * heading/icon pair. Our flex row positions such items without emitting
  7044. * their inline text in some deep page contexts; normal inline flow renders
  7045. * the same content correctly. */
  7046. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  7047. {
  7048. unsigned int c;
  7049. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7050. struct br_node *nd = &doc.nodes[c];
  7051. struct br_style cs;
  7052. if (nd->type == BR_NODE_TEXT)
  7053. continue;
  7054. br_style_for(&doc, c, pst, &cs);
  7055. if (cs.display == BR_DISPLAY_NONE)
  7056. continue;
  7057. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  7058. cs.width_kind || cs.has_bg ||
  7059. cs.border_w[0] || cs.border_w[1] ||
  7060. cs.border_w[2] || cs.border_w[3] ||
  7061. nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG)
  7062. return 1;
  7063. }
  7064. return 0;
  7065. }
  7066. static int css_radius(const struct br_style *st, int corner,
  7067. int w, int h)
  7068. {
  7069. int r = st->radius[corner];
  7070. if (r <= 0)
  7071. return 0;
  7072. if (r > w / 2)
  7073. r = w / 2;
  7074. if (r > h / 2)
  7075. r = h / 2;
  7076. return r;
  7077. }
  7078. /* ---- inline SVG ----
  7079. *
  7080. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  7081. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  7082. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  7083. * opacity and solid paint; a gradient paints the average of its stops) and
  7084. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  7085. #define SVG_CACHE_MAX 48
  7086. #define SVG_CACHE_PIXELS (640 * 1024)
  7087. #define SVG_MAX_POINTS 24576
  7088. struct svg_cache_ent {
  7089. unsigned int node;
  7090. int w, h;
  7091. unsigned short *px;
  7092. unsigned char *a;
  7093. unsigned int stamp;
  7094. };
  7095. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  7096. static unsigned int svg_cache_pixels, svg_cache_clock;
  7097. static struct svgr svg_geom;
  7098. static void *svg_geom_buf;
  7099. /* Current viewport in user units: percentage lengths resolve against it
  7100. * (the viewBox size, not the device pixels). */
  7101. static double svg_vp_w = 300, svg_vp_h = 150;
  7102. /* The layers live in the page heap: forget them before heap_reset(). */
  7103. static void svg_cache_clear(void)
  7104. {
  7105. memset(svg_cache, 0, sizeof(svg_cache));
  7106. svg_cache_pixels = 0;
  7107. svg_geom_buf = 0;
  7108. }
  7109. static int svg_name_is(const char *a, const char *b)
  7110. {
  7111. while (*a && *b) {
  7112. char x = *a, y = *b;
  7113. if (x >= 'A' && x <= 'Z')
  7114. x = (char)(x - 'A' + 'a');
  7115. if (x != y)
  7116. return 0;
  7117. a++;
  7118. b++;
  7119. }
  7120. return *a == *b;
  7121. }
  7122. static const char *svg_elem_name(unsigned int node)
  7123. {
  7124. const struct br_node *nd = &doc.nodes[node];
  7125. if (nd->name_off)
  7126. return doc.attrs + nd->name_off;
  7127. return br_tag_name(nd->tag);
  7128. }
  7129. /* A numeric attribute; a percentage resolves against `base`. */
  7130. static double svg_attr_num(unsigned int node, const char *name, double def,
  7131. double base)
  7132. {
  7133. const char *v = br_find_attr(&doc, node, name);
  7134. const char *p = v;
  7135. int ok = 0;
  7136. double x;
  7137. if (!v)
  7138. return def;
  7139. x = svgr_num(&p, &ok);
  7140. if (!ok)
  7141. return def;
  7142. if (*p == '%')
  7143. x = x * base / 100.0;
  7144. return x;
  7145. }
  7146. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  7147. static int svg_viewbox4(unsigned int node, double vb[4])
  7148. {
  7149. const char *v = br_find_attr(&doc, node, "viewbox");
  7150. const char *p = v;
  7151. int i, ok = 1;
  7152. if (!v)
  7153. return 0;
  7154. for (i = 0; i < 4 && ok; i++)
  7155. vb[i] = svgr_num(&p, &ok);
  7156. return ok && vb[2] > 0 && vb[3] > 0;
  7157. }
  7158. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  7159. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  7160. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  7161. double w, double h, double m[6])
  7162. {
  7163. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  7164. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  7165. int ax = 1, ay = 1;
  7166. if (par && contains_ci(par, "none")) {
  7167. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  7168. m[4] = -vb[0] * sx;
  7169. m[5] = -vb[1] * sy;
  7170. return;
  7171. }
  7172. if (par) {
  7173. if (contains_ci(par, "xmin"))
  7174. ax = 0;
  7175. else if (contains_ci(par, "xmax"))
  7176. ax = 2;
  7177. if (contains_ci(par, "ymin"))
  7178. ay = 0;
  7179. else if (contains_ci(par, "ymax"))
  7180. ay = 2;
  7181. }
  7182. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  7183. (sx < sy ? sx : sy);
  7184. tx = (w - vb[2] * s) * ax / 2.0;
  7185. ty = (h - vb[3] * s) * ay / 2.0;
  7186. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  7187. m[4] = tx - vb[0] * s;
  7188. m[5] = ty - vb[1] * s;
  7189. }
  7190. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  7191. * the paint attribute, then average the gradient's stops. */
  7192. static int svg_url_paint(unsigned int node, const char *attr,
  7193. unsigned short *color, unsigned int *alpha)
  7194. {
  7195. const char *v = 0, *h;
  7196. char id[64];
  7197. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  7198. for (k = 0; node && k < 32 && !v; k++) {
  7199. v = br_find_attr(&doc, node, attr);
  7200. if (!v) {
  7201. const char *style = br_find_attr(&doc, node, "style");
  7202. if (style && contains_ci(style, "url(#"))
  7203. v = strstr(style, "url(#");
  7204. }
  7205. if (v && !contains_ci(v, "url("))
  7206. v = 0;
  7207. node = doc.nodes[node].parent;
  7208. }
  7209. if (!v || !(h = strstr(v, "#")))
  7210. return 0;
  7211. h++;
  7212. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  7213. id[n++] = *h++;
  7214. id[n] = '\0';
  7215. g = br_find_id(&doc, id);
  7216. /* Follow href chains (a gradient that only references another one's
  7217. * stops), at most a few hops. */
  7218. for (k = 0; g && k < 4; k++) {
  7219. unsigned int gi = g - 1;
  7220. const char *ref;
  7221. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  7222. const char *nm, *sc, *so;
  7223. unsigned short col = 0;
  7224. double op = 1;
  7225. if (doc.nodes[c].type != BR_NODE_ELEM)
  7226. continue;
  7227. nm = svg_elem_name(c);
  7228. if (!svg_name_is(nm, "stop"))
  7229. continue;
  7230. sc = br_find_attr(&doc, c, "stop-color");
  7231. so = br_find_attr(&doc, c, "stop-opacity");
  7232. {
  7233. const char *st = br_find_attr(&doc, c, "style");
  7234. const char *q;
  7235. if (st && (q = strstr(st, "stop-color:")) != 0)
  7236. sc = q + 11;
  7237. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  7238. so = q + 13;
  7239. }
  7240. if (sc) {
  7241. unsigned int L = 0;
  7242. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  7243. L++;
  7244. if (!br_parse_color(sc, L, &col))
  7245. col = 0;
  7246. }
  7247. if (so) {
  7248. const char *p = so;
  7249. int ok = 0;
  7250. double x = svgr_num(&p, &ok);
  7251. if (ok)
  7252. op = x < 0 ? 0 : x > 1 ? 1 : x;
  7253. }
  7254. sr += (col >> 11) & 31;
  7255. sg += (col >> 5) & 63;
  7256. sb += col & 31;
  7257. sa += (unsigned int)(op * 255);
  7258. cnt++;
  7259. }
  7260. if (cnt)
  7261. break;
  7262. ref = br_find_attr(&doc, gi, "href");
  7263. if (!ref)
  7264. ref = br_find_attr(&doc, gi, "xlink:href");
  7265. if (!ref || ref[0] != '#')
  7266. break;
  7267. g = br_find_id(&doc, ref + 1);
  7268. }
  7269. if (!cnt)
  7270. return 0;
  7271. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  7272. (sb / cnt));
  7273. *alpha = sa / cnt;
  7274. return 1;
  7275. }
  7276. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  7277. unsigned short *color, unsigned int *alpha)
  7278. {
  7279. int mode = fill ? st->fill_mode : st->stroke_mode;
  7280. const char *op = br_find_attr(&doc, node,
  7281. fill ? "fill-opacity" : "stroke-opacity");
  7282. *alpha = 255;
  7283. switch (mode) {
  7284. case BR_PAINT_UNSET:
  7285. if (!fill)
  7286. return 0;
  7287. *color = 0;
  7288. break;
  7289. case BR_PAINT_COLOR:
  7290. *color = fill ? st->fill : st->stroke;
  7291. break;
  7292. case BR_PAINT_CURRENT:
  7293. *color = st->color;
  7294. break;
  7295. case BR_PAINT_URL:
  7296. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  7297. alpha))
  7298. return 0;
  7299. break;
  7300. default:
  7301. return 0;
  7302. }
  7303. if (op) {
  7304. const char *p = op;
  7305. int ok = 0;
  7306. double x = svgr_num(&p, &ok);
  7307. if (ok)
  7308. *alpha = (unsigned int)(*alpha *
  7309. (x < 0 ? 0 : x > 1 ? 1 : x));
  7310. }
  7311. return *alpha > 0;
  7312. }
  7313. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7314. const double m[6], const struct br_style *pst,
  7315. unsigned int alpha, int depth);
  7316. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  7317. const double m[6], const struct br_style *st,
  7318. unsigned int alpha, int depth)
  7319. {
  7320. unsigned int c;
  7321. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  7322. if (doc.nodes[c].type == BR_NODE_ELEM)
  7323. svg_draw_node(L, c, m, st, alpha, depth + 1);
  7324. }
  7325. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7326. const double pm[6], const struct br_style *pst,
  7327. unsigned int alpha, int depth)
  7328. {
  7329. struct br_style st;
  7330. const char *nm = svg_elem_name(node);
  7331. const char *tf;
  7332. double m[6];
  7333. unsigned short color;
  7334. unsigned int pa;
  7335. int shape = 0, fillable = 1;
  7336. if (depth > 24 || !nm)
  7337. return;
  7338. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  7339. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  7340. svg_name_is(nm, "lineargradient") ||
  7341. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  7342. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  7343. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  7344. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  7345. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  7346. svg_name_is(nm, "foreignobject"))
  7347. return;
  7348. br_style_for(&doc, node, pst, &st);
  7349. if (st.display == BR_DISPLAY_NONE)
  7350. return;
  7351. memcpy(m, pm, sizeof(m));
  7352. tf = br_find_attr(&doc, node, "transform");
  7353. if (tf)
  7354. svgr_transform(m, tf);
  7355. {
  7356. const char *op = br_find_attr(&doc, node, "opacity");
  7357. if (op) {
  7358. const char *p = op;
  7359. int ok = 0;
  7360. double x = svgr_num(&p, &ok);
  7361. if (ok)
  7362. alpha = (unsigned int)(alpha *
  7363. (x < 0 ? 0 :
  7364. x > 1 ? 1 : x));
  7365. }
  7366. }
  7367. if (!alpha)
  7368. return;
  7369. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  7370. svg_name_is(nm, "switch")) {
  7371. svg_draw_children(L, node, m, &st, alpha, depth);
  7372. return;
  7373. }
  7374. if (svg_name_is(nm, "svg")) {
  7375. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  7376. y = svg_attr_num(node, "y", 0, 0);
  7377. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7378. t[4] = x;
  7379. t[5] = y;
  7380. svgr_mat_mul(m, m, t);
  7381. double ow = svg_vp_w, oh = svg_vp_h;
  7382. if (svg_viewbox4(node, vb)) {
  7383. double w = svg_attr_num(node, "width", vb[2], ow);
  7384. double h = svg_attr_num(node, "height", vb[3], oh);
  7385. double vm[6];
  7386. svg_viewport_matrix(node, vb, w, h, vm);
  7387. svgr_mat_mul(m, m, vm);
  7388. svg_vp_w = vb[2];
  7389. svg_vp_h = vb[3];
  7390. }
  7391. svg_draw_children(L, node, m, &st, alpha, depth);
  7392. svg_vp_w = ow;
  7393. svg_vp_h = oh;
  7394. return;
  7395. }
  7396. if (svg_name_is(nm, "use")) {
  7397. const char *ref = br_find_attr(&doc, node, "href");
  7398. unsigned int tgt;
  7399. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7400. if (!ref)
  7401. ref = br_find_attr(&doc, node, "xlink:href");
  7402. if (!ref || ref[0] != '#')
  7403. return;
  7404. tgt = br_find_id(&doc, ref + 1);
  7405. if (!tgt || tgt - 1 == node)
  7406. return;
  7407. tgt--;
  7408. t[4] = svg_attr_num(node, "x", 0, 0);
  7409. t[5] = svg_attr_num(node, "y", 0, 0);
  7410. svgr_mat_mul(m, m, t);
  7411. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  7412. double vb[4];
  7413. double ow = svg_vp_w, oh = svg_vp_h;
  7414. if (svg_viewbox4(tgt, vb)) {
  7415. double w = svg_attr_num(node, "width", vb[2],
  7416. ow);
  7417. double h = svg_attr_num(node, "height", vb[3],
  7418. oh);
  7419. double vm[6];
  7420. svg_viewport_matrix(tgt, vb, w, h, vm);
  7421. svgr_mat_mul(m, m, vm);
  7422. svg_vp_w = vb[2];
  7423. svg_vp_h = vb[3];
  7424. }
  7425. svg_draw_children(L, tgt, m, &st, alpha, depth);
  7426. svg_vp_w = ow;
  7427. svg_vp_h = oh;
  7428. } else {
  7429. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  7430. }
  7431. return;
  7432. }
  7433. svgr_reset(&svg_geom, m);
  7434. if (svg_name_is(nm, "path")) {
  7435. const char *d = br_find_attr(&doc, node, "d");
  7436. if (d) {
  7437. svgr_path(&svg_geom, d);
  7438. shape = 1;
  7439. }
  7440. } else if (svg_name_is(nm, "rect")) {
  7441. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  7442. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  7443. double rx = svg_attr_num(node, "rx", -1, w);
  7444. double ry = svg_attr_num(node, "ry", -1, h);
  7445. if (rx < 0)
  7446. rx = ry < 0 ? 0 : ry;
  7447. if (ry < 0)
  7448. ry = rx;
  7449. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  7450. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  7451. shape = 1;
  7452. } else if (svg_name_is(nm, "circle")) {
  7453. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  7454. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7455. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  7456. shape = 1;
  7457. } else if (svg_name_is(nm, "ellipse")) {
  7458. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7459. svg_attr_num(node, "cy", 0, svg_vp_h),
  7460. svg_attr_num(node, "rx", 0, svg_vp_w),
  7461. svg_attr_num(node, "ry", 0, svg_vp_h));
  7462. shape = 1;
  7463. } else if (svg_name_is(nm, "line")) {
  7464. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  7465. svg_attr_num(node, "y1", 0, svg_vp_h));
  7466. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  7467. svg_attr_num(node, "y2", 0, svg_vp_h));
  7468. shape = 1;
  7469. fillable = 0;
  7470. } else if (svg_name_is(nm, "polyline") ||
  7471. svg_name_is(nm, "polygon")) {
  7472. const char *pts = br_find_attr(&doc, node, "points");
  7473. if (pts) {
  7474. svgr_points(&svg_geom, pts,
  7475. svg_name_is(nm, "polygon"));
  7476. shape = 1;
  7477. }
  7478. }
  7479. if (!shape)
  7480. return;
  7481. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  7482. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  7483. st.fill_evenodd);
  7484. if (svg_paint(node, &st, 0, &color, &pa)) {
  7485. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  7486. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7487. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  7488. }
  7489. }
  7490. /* <text> elements: drawn straight onto the page every frame (the glyph
  7491. * renderer targets the ngui canvas, not a layer). x/y map through the
  7492. * accumulated transform; the font size scales with it. */
  7493. static void svg_draw_text(struct ngui *ui, unsigned int node,
  7494. const double pm[6], const struct br_style *pst,
  7495. int ox, int oy, int depth)
  7496. {
  7497. unsigned int c;
  7498. if (depth > 24)
  7499. return;
  7500. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7501. struct br_style st;
  7502. const char *nm, *tf;
  7503. double m[6];
  7504. if (doc.nodes[c].type != BR_NODE_ELEM)
  7505. continue;
  7506. nm = svg_elem_name(c);
  7507. if (!nm || svg_name_is(nm, "defs") ||
  7508. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  7509. svg_name_is(nm, "clippath"))
  7510. continue;
  7511. br_style_for(&doc, c, pst, &st);
  7512. if (st.display == BR_DISPLAY_NONE)
  7513. continue;
  7514. memcpy(m, pm, sizeof(m));
  7515. tf = br_find_attr(&doc, c, "transform");
  7516. if (tf)
  7517. svgr_transform(m, tf);
  7518. if (svg_name_is(nm, "text")) {
  7519. unsigned int t = doc.nodes[c].first;
  7520. const char *s;
  7521. unsigned int n, tw;
  7522. double x = svg_attr_num(c, "x", 0, 0),
  7523. y = svg_attr_num(c, "y", 0, 0);
  7524. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7525. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  7526. int tx, ty, anchor;
  7527. unsigned short col;
  7528. unsigned int pa;
  7529. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  7530. continue;
  7531. if (px < 6)
  7532. px = 6;
  7533. if (px > 72)
  7534. px = 72;
  7535. if (!svg_paint(c, &st, 1, &col, &pa))
  7536. continue;
  7537. s = doc.text + doc.nodes[t].text_off;
  7538. n = doc.nodes[t].text_len;
  7539. st.font_px = (unsigned char)px;
  7540. tw = face_text_width(ui, &st, s, n);
  7541. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  7542. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  7543. ngui_text_ascent_face(ui, style_face(&st), px,
  7544. st.mono);
  7545. anchor = st.align;
  7546. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  7547. anchor = BR_ALIGN_CENTER;
  7548. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  7549. anchor = BR_ALIGN_RIGHT;
  7550. if (anchor == BR_ALIGN_CENTER)
  7551. tx -= (int)tw / 2;
  7552. else if (anchor == BR_ALIGN_RIGHT)
  7553. tx -= (int)tw;
  7554. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  7555. col, px, st.bold, st.italic,
  7556. st.mono);
  7557. } else {
  7558. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  7559. }
  7560. }
  7561. }
  7562. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  7563. {
  7564. double vb[4];
  7565. if (svg_viewbox4(node, vb)) {
  7566. svg_viewport_matrix(node, vb, w, h, m);
  7567. } else {
  7568. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  7569. }
  7570. }
  7571. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  7572. const struct br_style *st)
  7573. {
  7574. struct svg_cache_ent *e = 0;
  7575. struct svgr_layer L;
  7576. double m[6];
  7577. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  7578. svg_cache_clock++;
  7579. for (i = 0; i < SVG_CACHE_MAX; i++)
  7580. if (svg_cache[i].px && svg_cache[i].node == node &&
  7581. svg_cache[i].w == w && svg_cache[i].h == h) {
  7582. svg_cache[i].stamp = svg_cache_clock;
  7583. return &svg_cache[i];
  7584. }
  7585. if (need > SVG_CACHE_PIXELS)
  7586. return 0;
  7587. /* Evict least recently used layers until this one fits. */
  7588. for (;;) {
  7589. struct svg_cache_ent *lru = 0, *free_slot = 0;
  7590. for (i = 0; i < SVG_CACHE_MAX; i++) {
  7591. if (!svg_cache[i].px) {
  7592. if (!free_slot)
  7593. free_slot = &svg_cache[i];
  7594. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  7595. lru = &svg_cache[i];
  7596. }
  7597. }
  7598. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  7599. e = free_slot;
  7600. break;
  7601. }
  7602. if (!lru)
  7603. return 0;
  7604. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  7605. free(lru->px);
  7606. free(lru->a);
  7607. memset(lru, 0, sizeof(*lru));
  7608. }
  7609. if (!svg_geom_buf) {
  7610. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7611. if (!svg_geom_buf)
  7612. return 0;
  7613. }
  7614. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  7615. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  7616. e->a = (unsigned char *)calloc(need, 1);
  7617. if (!e->px || !e->a) {
  7618. free(e->px);
  7619. free(e->a);
  7620. memset(e, 0, sizeof(*e));
  7621. return 0;
  7622. }
  7623. e->node = node;
  7624. e->w = w;
  7625. e->h = h;
  7626. e->stamp = svg_cache_clock;
  7627. svg_cache_pixels += need;
  7628. L.px = e->px;
  7629. L.a = e->a;
  7630. L.w = w;
  7631. L.h = h;
  7632. svg_root_matrix(node, w, h, m);
  7633. {
  7634. double vb[4];
  7635. if (svg_viewbox4(node, vb)) {
  7636. svg_vp_w = vb[2];
  7637. svg_vp_h = vb[3];
  7638. } else {
  7639. svg_vp_w = w;
  7640. svg_vp_h = h;
  7641. }
  7642. }
  7643. svg_draw_children(&L, node, m, st, 255, 0);
  7644. return e;
  7645. }
  7646. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  7647. *
  7648. * The markup is parsed into a detached subtree of the page document and
  7649. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  7650. * bitmap, which then behaves like any decoded image. currentColor is
  7651. * black (an image has no inherited text colour); <text> is not drawn. */
  7652. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  7653. {
  7654. unsigned int i = 0;
  7655. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  7656. i = 3;
  7657. while (i < len) {
  7658. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  7659. d[i] == '\r' || d[i] == '\n'))
  7660. i++;
  7661. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  7662. return 1;
  7663. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  7664. i += 4;
  7665. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  7666. i++;
  7667. i += 3;
  7668. continue;
  7669. }
  7670. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  7671. while (i < len && d[i] != '>')
  7672. i++;
  7673. i++;
  7674. continue;
  7675. }
  7676. return 0;
  7677. }
  7678. return 0;
  7679. }
  7680. static int svg_len_attr(unsigned int node, const char *name)
  7681. {
  7682. const char *v = br_find_attr(&doc, node, name);
  7683. int n = 0, any = 0;
  7684. if (!v)
  7685. return 0;
  7686. while (*v == ' ')
  7687. v++;
  7688. while (*v >= '0' && *v <= '9') {
  7689. n = n * 10 + (*v++ - '0');
  7690. any = 1;
  7691. }
  7692. if (*v == '.')
  7693. while (*++v >= '0' && *v <= '9')
  7694. ;
  7695. if (!any || *v == '%')
  7696. return 0;
  7697. return n;
  7698. }
  7699. static int svg_decode_image(const unsigned char *data, unsigned int len,
  7700. struct br_image *bi, int box_w, int box_h)
  7701. {
  7702. unsigned int holder, svg = 0, c, need, i;
  7703. struct br_style base = base_style(), st;
  7704. struct svgr_layer L;
  7705. double vb[4], m[6];
  7706. int w, h, have_vb, nat_w, nat_h;
  7707. holder = br_create_element(&doc, "div", 3);
  7708. if (!holder) {
  7709. s_copy(bi->err, "page is full", sizeof(bi->err));
  7710. return -1;
  7711. }
  7712. holder--;
  7713. br_set_inner_html(&doc, holder, (const char *)data, len);
  7714. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  7715. if (doc.nodes[c].type == BR_NODE_ELEM &&
  7716. doc.nodes[c].tag == BR_TAG_SVG) {
  7717. svg = c;
  7718. break;
  7719. }
  7720. if (!svg) {
  7721. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  7722. return -1;
  7723. }
  7724. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  7725. w = svg_len_attr(svg, "width");
  7726. h = svg_len_attr(svg, "height");
  7727. if (box_w > 0 && box_h > 0) {
  7728. w = box_w;
  7729. h = box_h;
  7730. } else if (!w && !h) {
  7731. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  7732. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  7733. } else if (!w) {
  7734. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  7735. } else if (!h) {
  7736. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  7737. }
  7738. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  7739. * so CSS scaling stays crisp. */
  7740. nat_w = w;
  7741. nat_h = h;
  7742. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  7743. w *= 2;
  7744. h *= 2;
  7745. }
  7746. if (w > BR_IMG_LAYOUT_W) {
  7747. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  7748. w = BR_IMG_LAYOUT_W;
  7749. }
  7750. if (h > 2048)
  7751. h = 2048;
  7752. if (w < 1)
  7753. w = 1;
  7754. if (h < 1)
  7755. h = 1;
  7756. need = (unsigned int)w * (unsigned int)h;
  7757. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  7758. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  7759. return -1;
  7760. }
  7761. if (!svg_geom_buf) {
  7762. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7763. if (!svg_geom_buf) {
  7764. s_copy(bi->err, "out of memory", sizeof(bi->err));
  7765. return -1;
  7766. }
  7767. }
  7768. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  7769. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  7770. L.a = (unsigned char *)calloc(need, 1);
  7771. if (!L.px || !L.a) {
  7772. free(L.px);
  7773. free(L.a);
  7774. s_copy(bi->err, "out of memory", sizeof(bi->err));
  7775. return -1;
  7776. }
  7777. for (i = 0; i < need; i++)
  7778. L.px[i] = 0xFFFF;
  7779. L.w = w;
  7780. L.h = h;
  7781. base.color = 0x0000;
  7782. br_style_for(&doc, svg, &base, &st);
  7783. svg_root_matrix(svg, w, h, m);
  7784. svg_vp_w = have_vb ? vb[2] : w;
  7785. svg_vp_h = have_vb ? vb[3] : h;
  7786. svg_draw_children(&L, svg, m, &st, 255, 0);
  7787. bi->native_w = nat_w;
  7788. bi->native_h = nat_h;
  7789. bi->img.format = 0;
  7790. bi->img.w = (unsigned int)w;
  7791. bi->img.h = (unsigned int)h;
  7792. bi->img.px = L.px;
  7793. bi->img.alpha = L.a;
  7794. bi->img.flags = 0;
  7795. bi->state = 1;
  7796. image_pixels += need;
  7797. return 0;
  7798. }
  7799. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  7800. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  7801. int *out_w, int *out_h)
  7802. {
  7803. double vb[4];
  7804. int has_vb = svg_viewbox4(node, vb);
  7805. double aw = svg_attr_num(node, "width", -1, cw);
  7806. double ah = svg_attr_num(node, "height", -1, 0);
  7807. int w, h;
  7808. if (st->width_kind)
  7809. w = cw;
  7810. else if (aw > 0)
  7811. w = (int)(aw + 0.5);
  7812. else if (st->height_kind == 1 && has_vb)
  7813. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  7814. else if (ah > 0 && has_vb)
  7815. w = (int)(ah * vb[2] / vb[3] + 0.5);
  7816. else if (has_vb)
  7817. w = cw;
  7818. else
  7819. w = 300;
  7820. if (st->max_width_kind == 1 && w > st->max_width)
  7821. w = st->max_width;
  7822. if (w > cw && cw > 0 && !(aw > 0))
  7823. w = cw;
  7824. if (w < 1)
  7825. w = 1;
  7826. if (w > 2000)
  7827. w = 2000;
  7828. if (st->height_kind == 1)
  7829. h = st->height;
  7830. else if (ah > 0)
  7831. h = (int)(ah + 0.5);
  7832. else if (has_vb)
  7833. h = (int)(w * vb[3] / vb[2] + 0.5);
  7834. else
  7835. h = 150;
  7836. if (h < 1)
  7837. h = 1;
  7838. if (h > 1400)
  7839. h = 1400;
  7840. *out_w = w;
  7841. *out_h = h;
  7842. }
  7843. static void svg_paint_box(struct ngui *ui, unsigned int node,
  7844. const struct br_style *st, int x, int y, int w, int h)
  7845. {
  7846. struct svg_cache_ent *e;
  7847. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  7848. int cx0, cy0, cx1, cy1, px, py;
  7849. double m[6];
  7850. if (ui->nclip > 0)
  7851. clip = ui->clip[ui->nclip - 1];
  7852. cx0 = r.x > clip.x ? r.x : clip.x;
  7853. cy0 = r.y > clip.y ? r.y : clip.y;
  7854. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  7855. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  7856. if (cx0 >= cx1 || cy0 >= cy1)
  7857. return;
  7858. e = svg_layer(node, w, h, st);
  7859. if (e) {
  7860. for (py = cy0; py < cy1; py++) {
  7861. unsigned int srow = (unsigned int)(py - y) *
  7862. (unsigned int)w;
  7863. unsigned short *dst = ui->px + py * ui->w;
  7864. for (px = cx0; px < cx1; px++) {
  7865. unsigned int si = srow + (unsigned int)(px - x);
  7866. unsigned int a = e->a[si];
  7867. if (!a)
  7868. continue;
  7869. dst[px] = a >= 255 ? e->px[si] :
  7870. blend_rgb565(dst[px], e->px[si], a);
  7871. }
  7872. }
  7873. }
  7874. svg_root_matrix(node, w, h, m);
  7875. ngui_push_clip(ui, r);
  7876. svg_draw_text(ui, node, m, st, x, y, 0);
  7877. ngui_pop_clip(ui);
  7878. }
  7879. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  7880. * keep using add_image_run(); this covers the CSS `position:absolute;
  7881. * width:100%` poster pattern used by news sites. */
  7882. static void image_block_size(unsigned int node, const struct br_style *st,
  7883. int cbw, int *out_w, int *out_h)
  7884. {
  7885. struct br_node *nd = &doc.nodes[node];
  7886. int idx = nd->img_index;
  7887. int iw = 0, ih = 0, w, h, aw, ah;
  7888. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  7889. iw = (int)images[idx].img.w;
  7890. ih = (int)images[idx].img.h;
  7891. if (iw <= 0 || ih <= 0) {
  7892. iw = (int)images[idx].native_w;
  7893. ih = (int)images[idx].native_h;
  7894. }
  7895. }
  7896. if (st->width_kind)
  7897. w = style_width_px(st, cbw);
  7898. else if (nd->width_attr)
  7899. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  7900. (int)nd->width_attr;
  7901. else if (nd->height_attr && !nd->height_pct && iw && ih)
  7902. w = iw * (int)nd->height_attr / ih;
  7903. else if (iw)
  7904. w = iw;
  7905. else
  7906. w = 64;
  7907. /* max-width/min-width against the containing block: Tailwind's
  7908. * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
  7909. * 300x300 thumbnail to its 75 px avatar box. */
  7910. if (st->max_width_kind) {
  7911. int mw = st->max_width_kind == 3 ?
  7912. cbw * st->max_width_calc_pct / 100 +
  7913. st->max_width_calc_px :
  7914. st->max_width_kind == 2 ?
  7915. cbw * (int)st->max_width / 100 : (int)st->max_width;
  7916. if (mw > 0 && w > mw)
  7917. w = mw;
  7918. }
  7919. if (st->min_width_kind) {
  7920. int mn = st->min_width_kind == 3 ?
  7921. cbw * st->min_width_calc_pct / 100 +
  7922. st->min_width_calc_px :
  7923. st->min_width_kind == 2 ?
  7924. cbw * (int)st->min_width / 100 : (int)st->min_width;
  7925. if (mn > w)
  7926. w = mn;
  7927. }
  7928. if (w < 8)
  7929. w = 8;
  7930. if (cbw > 0 && w > cbw)
  7931. w = cbw;
  7932. /* Without a CSS height the attributes (or the bitmap) only give the
  7933. * aspect ratio: a width clamped by max-width scales the height too,
  7934. * instead of letterboxing the image into its attribute height. */
  7935. aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
  7936. ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
  7937. if (st->height_kind)
  7938. h = style_height_px(st, cbw);
  7939. else if (aw > 0 && ah > 0)
  7940. h = w * ah / aw;
  7941. else if (nd->height_attr)
  7942. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  7943. (int)nd->height_attr;
  7944. else
  7945. h = 64;
  7946. if (h < 8)
  7947. h = 8;
  7948. *out_w = w;
  7949. *out_h = h;
  7950. }
  7951. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  7952. int dw, int dh)
  7953. {
  7954. int idx = doc.nodes[node].img_index;
  7955. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  7956. struct img_image *src = image_display_get(&images[idx], dw, dh);
  7957. struct img_blit b;
  7958. if (!src)
  7959. src = &images[idx].img;
  7960. b.dst = l->ui->px;
  7961. b.dst_w = l->ui->w;
  7962. b.dst_h = l->ui->h;
  7963. b.clip_x = page_rect.x;
  7964. b.clip_y = page_rect.y;
  7965. b.clip_w = page_rect.w - 12;
  7966. b.clip_h = page_rect.h;
  7967. b.x = x;
  7968. b.y = y;
  7969. b.scale = ((unsigned int)dw << 16) / src->w;
  7970. b.bg = ui.theme.bg;
  7971. b.bg2 = ui.theme.bg;
  7972. b.dst_a = 0;
  7973. /* OVER_DST is only needed for an alpha source; an opaque one can
  7974. * take img_draw's 1:1 copy path. */
  7975. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  7976. img_draw(src, &b);
  7977. } else if (l->draw) {
  7978. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  7979. 0xD69A);
  7980. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  7981. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  7982. }
  7983. }
  7984. static void layout_block(struct lay *l, unsigned int node,
  7985. const struct br_style *st, int depth,
  7986. unsigned short link)
  7987. {
  7988. int old_left = l->left, old_right = l->right, old_align = l->align;
  7989. int parent_cb_h = l->cb_h;
  7990. int saved_parent_top = l->parent_top;
  7991. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  7992. int saved_cb_top = l->cb_top;
  7993. int top, l0, r0;
  7994. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  7995. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  7996. int deco_w, deco_h, content_w, content_h, box_h;
  7997. int img_dh = 0;
  7998. int definite_w = 0;
  7999. int normal_top = 0;
  8000. int rel_dx = 0, rel_dy = 0;
  8001. int clip_pushed = 0;
  8002. struct ngui_rect clip_rect;
  8003. /* A DOM level costs about two depth units (layout_block ->
  8004. * layout_children), so 48 covers a ~24-level page. Real news pages
  8005. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  8006. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  8007. return;
  8008. flow_y = l->y;
  8009. flow_left = l->left;
  8010. flow_right = l->right;
  8011. positioned = st->pos == 1 || st->pos == 2;
  8012. relative = st->pos == 3;
  8013. sticky = st->pos == 4;
  8014. shifted = relative || sticky || st->transform_set;
  8015. if (positioned) {
  8016. int def_w = st->width_kind == 1 ? st->width : -1;
  8017. if (st->pos == 2) {
  8018. int avail_w = page_rect.w - 12;
  8019. if (st->right_set && def_w >= 0)
  8020. l->left = page_rect.x + avail_w - st->right -
  8021. def_w;
  8022. else
  8023. l->left = page_rect.x +
  8024. (st->left_set ? st->left : 0);
  8025. l->right = def_w >= 0 ? l->left + def_w :
  8026. page_rect.x + avail_w;
  8027. if (st->bottom_set && st->height_kind)
  8028. l->y = page_rect.y + page_rect.h -
  8029. st->bottom -
  8030. style_height_px(st, page_rect.w);
  8031. else
  8032. l->y = page_rect.y +
  8033. (st->top_set ? st->top : 0);
  8034. } else {
  8035. int left = flow_left + (st->left_set ? st->left : 0);
  8036. unsigned int parent = doc.nodes[node].parent;
  8037. if (st->right_set && def_w >= 0)
  8038. left = flow_right - st->right - def_w;
  8039. l->left = left;
  8040. l->right = def_w >= 0 ? left + def_w :
  8041. flow_right +
  8042. (st->left_set ? st->left : 0);
  8043. l->y = flow_y + (st->top_set ? st->top : 0);
  8044. if (st->bottom_set && st->height_kind &&
  8045. parent < BR_MAX_NODES && block_h[parent] > 0)
  8046. l->y = flow_y + block_h[parent] - st->bottom -
  8047. style_height_px(st, old_right - old_left);
  8048. }
  8049. /* `left: 100%` parks a box (Docusaurus' "Skip to main
  8050. * content" link) past the containing block's right edge
  8051. * until it is focused. An auto width then has no room: it
  8052. * used to collapse to 8 px and wrap one word per line into a
  8053. * tall column painted over the page. Lay it out at the
  8054. * containing block's width so it stays one line and
  8055. * overflows (off-screen) like in a real browser. */
  8056. if (def_w < 0 && l->right - l->left < 8) {
  8057. int avail = st->pos == 2 ? page_rect.w - 12 :
  8058. flow_right - flow_left;
  8059. l->right = l->left + (avail > 8 ? avail : 8);
  8060. }
  8061. old_left = l->left;
  8062. old_right = l->right;
  8063. } else if (relative) {
  8064. rel_dx = st->left_set ? st->left :
  8065. (st->right_set ? -st->right : 0);
  8066. rel_dy = st->top_set ? st->top :
  8067. (st->bottom_set ? -st->bottom : 0);
  8068. }
  8069. if (st->transform_set) {
  8070. rel_dx += st->tx;
  8071. rel_dy += st->ty;
  8072. }
  8073. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  8074. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  8075. doc.nodes[node].tag == BR_TAG_SELECT ||
  8076. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  8077. !button_has_elements(node)) {
  8078. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  8079. s_eq(br_type(&doc, node), "hidden"))
  8080. return;
  8081. /* Reached as a block-level box (a flex item): the control
  8082. * fills the box the caller assigned, and its line is flushed
  8083. * here; flex layout resets the run list for the next item, so
  8084. * a queued run would never be drawn. */
  8085. form_fill_line = 1;
  8086. add_form_run(l, node, st, link);
  8087. form_fill_line = 0;
  8088. flush_line(l);
  8089. return;
  8090. }
  8091. flush_line(l);
  8092. cbw = old_right - old_left;
  8093. if (cbw < 8)
  8094. cbw = 8;
  8095. l->y += mp_px(st, 0, cbw);
  8096. top = l->y;
  8097. ml = mp_px(st, 3, cbw);
  8098. mr = mp_px(st, 1, cbw);
  8099. bl = st->border_w[3];
  8100. br = st->border_w[1];
  8101. pl = mp_px(st, 7, cbw);
  8102. pr = mp_px(st, 5, cbw);
  8103. bt = st->border_w[0];
  8104. bb = st->border_w[2];
  8105. pt = mp_px(st, 4, cbw);
  8106. pb = mp_px(st, 6, cbw);
  8107. deco_w = bl + br + pl + pr;
  8108. deco_h = bt + bb + pt + pb;
  8109. if (st->width_kind) {
  8110. int w;
  8111. if (st->width_kind == 3)
  8112. w = cbw * st->width_calc_pct / 100 +
  8113. st->width_calc_px;
  8114. else
  8115. w = css_size(st->width_kind, st->width, cbw);
  8116. if (w < 0)
  8117. w = 0;
  8118. content_w = st->box_sizing ? w - deco_w : w;
  8119. definite_w = 1;
  8120. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  8121. doc.nodes[node].tag == BR_TAG_TD ||
  8122. doc.nodes[node].tag == BR_TAG_TH) &&
  8123. doc.nodes[node].width_attr) {
  8124. /* Legacy table/cell width attributes: percentages resolve
  8125. * against the containing block, bare numbers are pixels. */
  8126. int w = doc.nodes[node].width_pct ?
  8127. cbw * doc.nodes[node].width_attr / 100 :
  8128. doc.nodes[node].width_attr;
  8129. if (w < 0)
  8130. w = 0;
  8131. content_w = st->box_sizing ? w - deco_w : w;
  8132. definite_w = 1;
  8133. } else {
  8134. content_w = cbw - ml - mr - deco_w;
  8135. }
  8136. if (content_w < 0)
  8137. content_w = 0;
  8138. if (st->max_width_kind) {
  8139. int mw = st->max_width_kind == 3 ?
  8140. cbw * st->max_width_calc_pct / 100 +
  8141. st->max_width_calc_px :
  8142. css_size(st->max_width_kind, st->max_width, cbw);
  8143. int max_box = st->box_sizing ? mw : mw + deco_w;
  8144. /* A clamped auto width is used as the width, so auto
  8145. * margins share the rest (Google's 688 px search box). */
  8146. if (content_w + deco_w > max_box) {
  8147. content_w = max_box - deco_w;
  8148. definite_w = 1;
  8149. }
  8150. }
  8151. if (st->min_width_kind) {
  8152. int mw = st->min_width_kind == 3 ?
  8153. cbw * st->min_width_calc_pct / 100 +
  8154. st->min_width_calc_px :
  8155. css_size(st->min_width_kind, st->min_width, cbw);
  8156. int min_box = st->box_sizing ? mw : mw + deco_w;
  8157. if (content_w + deco_w < min_box) {
  8158. content_w = min_box - deco_w;
  8159. definite_w = 1;
  8160. }
  8161. }
  8162. if (content_w < 8)
  8163. content_w = 8;
  8164. if (definite_w) {
  8165. int free_w = cbw - ml - mr - deco_w - content_w;
  8166. if (free_w < 0)
  8167. free_w = 0;
  8168. if (st->ml_auto && st->mr_auto) {
  8169. ml = free_w / 2;
  8170. mr = free_w - ml;
  8171. } else if (st->ml_auto) {
  8172. ml = free_w;
  8173. } else if (st->mr_auto) {
  8174. mr = free_w;
  8175. }
  8176. }
  8177. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8178. int iw, ih;
  8179. image_block_size(node, st, cbw, &iw, &ih);
  8180. content_w = iw;
  8181. img_dh = ih;
  8182. }
  8183. l0 = old_left + ml;
  8184. r0 = l0 + deco_w + content_w;
  8185. if (r0 < l0 + 8)
  8186. r0 = l0 + 8;
  8187. normal_top = top;
  8188. if (sticky) {
  8189. if (st->top_set) {
  8190. int stick = page_rect.y + 4 + st->top;
  8191. if (normal_top < stick)
  8192. rel_dy += stick - normal_top;
  8193. } else if (st->bottom_set && block_h[node]) {
  8194. int stick = page_rect.y + page_rect.h - st->bottom -
  8195. block_h[node];
  8196. if (normal_top > stick)
  8197. rel_dy += stick - normal_top;
  8198. }
  8199. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  8200. block_h[doc.nodes[node].parent]) {
  8201. unsigned int p = doc.nodes[node].parent;
  8202. int ptop = l->parent_top;
  8203. int pbottom = ptop + block_h[p];
  8204. int eh = block_h[node];
  8205. int moved_top = normal_top + rel_dy;
  8206. int moved_bottom = moved_top + eh;
  8207. if (moved_bottom > pbottom)
  8208. rel_dy -= moved_bottom - pbottom;
  8209. moved_top = normal_top + rel_dy;
  8210. if (moved_top < ptop)
  8211. rel_dy += ptop - moved_top;
  8212. }
  8213. }
  8214. if (shifted && l->draw) {
  8215. top += rel_dy;
  8216. l0 += rel_dx;
  8217. r0 += rel_dx;
  8218. }
  8219. l->parent_top = top;
  8220. if (st->pos != 0) {
  8221. /* Positioned boxes establish the containing block for their
  8222. * absolutely positioned descendants. */
  8223. l->cb_left = l0;
  8224. l->cb_right = r0;
  8225. l->cb_top = top;
  8226. }
  8227. if (l->draw && block_h[node] &&
  8228. top < page_rect.y + page_rect.h &&
  8229. top + block_h[node] > page_rect.y) {
  8230. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  8231. int rtl = css_radius(st, 0, box.w, box.h);
  8232. int rtr = css_radius(st, 1, box.w, box.h);
  8233. int rbr = css_radius(st, 2, box.w, box.h);
  8234. int rbl = css_radius(st, 3, box.w, box.h);
  8235. if (st->transform_scale) {
  8236. if (st->has_bg)
  8237. fill_transformed_rect(l->ui, box, st->bg, st);
  8238. } else if (rtl || rtr || rbr || rbl) {
  8239. if (st->has_bg) {
  8240. int bw = st->border_w[0];
  8241. if (bw > 0 && !st->border_t[0] &&
  8242. st->border_c[0] != st->bg &&
  8243. box.w > bw * 2 && box.h > bw * 2) {
  8244. struct ngui_rect inner = {
  8245. box.x + bw, box.y + bw,
  8246. box.w - bw * 2, box.h - bw * 2
  8247. };
  8248. int itl = rtl > bw ? rtl - bw : 0;
  8249. int itr = rtr > bw ? rtr - bw : 0;
  8250. int ibr = rbr > bw ? rbr - bw : 0;
  8251. int ibl = rbl > bw ? rbl - bw : 0;
  8252. ngui_fill_round_rect(l->ui, box, rtl,
  8253. rtr, rbr, rbl,
  8254. st->border_c[0]);
  8255. ngui_fill_round_rect(l->ui, inner,
  8256. itl, itr, ibr,
  8257. ibl, st->bg);
  8258. } else {
  8259. ngui_fill_round_rect(l->ui, box, rtl,
  8260. rtr, rbr, rbl,
  8261. st->bg);
  8262. }
  8263. } else if (st->border_w[0] && !st->border_t[0]) {
  8264. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  8265. rbl, st->border_w[0],
  8266. st->border_c[0]);
  8267. }
  8268. /* Rounded boxes paint their background image too
  8269. * (app icons are rounded squares), kept inside the
  8270. * corner arcs. */
  8271. if (st->bg_image)
  8272. draw_bg_image_round(l, box, node, st, rtl, rtr,
  8273. rbr, rbl);
  8274. } else {
  8275. if (st->has_bg)
  8276. ngui_fill_rect(l->ui, box, st->bg);
  8277. if (st->bg_image)
  8278. draw_bg_image(l, box, node, st);
  8279. if (st->border_w[0] || st->border_w[1] ||
  8280. st->border_w[2] || st->border_w[3])
  8281. draw_border_box(l->ui, box, st);
  8282. }
  8283. }
  8284. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  8285. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  8286. content_w, img_dh);
  8287. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  8288. l->ui && l->ui->nclip < 4) {
  8289. clip_rect.x = l0 + bl;
  8290. clip_rect.y = top + bt;
  8291. clip_rect.w = (r0 - l0) - bl - br;
  8292. clip_rect.h = (int)block_h[node] - bt - bb;
  8293. if (clip_rect.w > 0 && clip_rect.h > 0) {
  8294. ngui_push_clip(l->ui, clip_rect);
  8295. clip_pushed = 1;
  8296. }
  8297. }
  8298. l->left = l0 + bl + pl;
  8299. l->right = l->left + content_w;
  8300. if (l->right < l->left + 8)
  8301. l->right = l->left + 8;
  8302. l->align = st->align;
  8303. l->line_left = l->left;
  8304. l->line_right = l->right;
  8305. l->y = top + bt + pt;
  8306. if (doc.nodes[node].tag == BR_TAG_HR) {
  8307. if (l->draw)
  8308. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  8309. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  8310. l->y += 8;
  8311. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  8312. int vw = l->right - l->left;
  8313. int vh;
  8314. if (doc.nodes[node].width_pct)
  8315. vw = vw * doc.nodes[node].width_attr / 100;
  8316. else if (doc.nodes[node].width_attr)
  8317. vw = doc.nodes[node].width_attr;
  8318. if (vw > l->right - l->left)
  8319. vw = l->right - l->left;
  8320. if (vw < 8)
  8321. vw = 8;
  8322. vh = vw * 9 / 16;
  8323. if (vh > 240)
  8324. vh = 240;
  8325. if (vh < 80)
  8326. vh = 80;
  8327. if (l->draw) {
  8328. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  8329. vw, vh}, 0xD69A);
  8330. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  8331. vw, vh}, 0x8410);
  8332. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  8333. 0x4208);
  8334. }
  8335. l->y += vh + 4;
  8336. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  8337. int dw, dh, cw = l->right - l->left;
  8338. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  8339. if (l->draw && l->y < page_rect.y + page_rect.h &&
  8340. l->y + dh > page_rect.y)
  8341. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  8342. l->y += dh;
  8343. } else {
  8344. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  8345. !st->no_bullet) {
  8346. char *m = li_marker[node];
  8347. if (!m[0]) {
  8348. unsigned int parent = doc.nodes[node].parent;
  8349. int style = st->list_style;
  8350. int idx = parent ? list_index(parent, node) : 1;
  8351. if (style == BR_LIST_AUTO)
  8352. style = (parent &&
  8353. doc.nodes[parent].tag ==
  8354. BR_TAG_OL) ?
  8355. BR_LIST_DECIMAL : BR_LIST_DISC;
  8356. list_marker_text(m, sizeof(li_marker[node]),
  8357. style, idx);
  8358. }
  8359. if (l->draw && m[0]) {
  8360. int mw = (int)ngui_text_width_ui(l->ui, m);
  8361. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  8362. st->color);
  8363. }
  8364. }
  8365. /* This box's definite content height, for its children's
  8366. * percentage heights. */
  8367. if (doc.nodes[node].tag == BR_TAG_HTML ||
  8368. doc.nodes[node].tag == BR_TAG_BODY)
  8369. l->cb_h = layout_view_h;
  8370. else if (st->height_kind == 1)
  8371. l->cb_h = (int)st->height -
  8372. (st->box_sizing ? deco_h : 0);
  8373. else if (st->height_kind == 2 && parent_cb_h > 0)
  8374. l->cb_h = parent_cb_h * (int)st->height / 100 -
  8375. (st->box_sizing ? deco_h : 0);
  8376. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  8377. l->cb_h = content_w * (int)st->aspect_h /
  8378. (int)st->aspect_w;
  8379. else
  8380. l->cb_h = 0;
  8381. if (l->cb_h < 0)
  8382. l->cb_h = 0;
  8383. if (doc.nodes[node].tag == BR_TAG_TR)
  8384. layout_table_row(l, node, st, depth + 1, link);
  8385. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  8386. table_has_rowspan(node))
  8387. layout_table(l, node, st, depth + 1, link);
  8388. else if (st->grid_auto)
  8389. layout_grid_auto(l, node, st, depth + 1, link);
  8390. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  8391. st->grid_gap > 0)
  8392. layout_grid_children(l, node, st, depth + 1, link);
  8393. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  8394. flex_wants_row(node, st))
  8395. layout_flex_children(l, node, st, depth + 1, link);
  8396. else if (st->display == BR_DISPLAY_FLEX && st->flex_col &&
  8397. st->align_items == 1) {
  8398. /* align-items: center in a column: the items' lines
  8399. * (an app card's icon and label) are centred; a child
  8400. * with its own text-align keeps it. */
  8401. struct br_style cst = *st;
  8402. cst.align = BR_ALIGN_CENTER;
  8403. l->align = BR_ALIGN_CENTER;
  8404. layout_children(l, node, &cst, depth + 1, link);
  8405. } else
  8406. layout_children(l, node, st, depth + 1, link);
  8407. l->cb_h = parent_cb_h;
  8408. }
  8409. flush_line(l);
  8410. if (clip_pushed)
  8411. ngui_pop_clip(l->ui);
  8412. if (l->float_active) {
  8413. if (l->y < l->float_bottom)
  8414. l->y = l->float_bottom;
  8415. l->float_active = 0;
  8416. }
  8417. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8418. content_h = img_dh;
  8419. } else if (st->height_kind == 2 &&
  8420. doc.nodes[node].tag != BR_TAG_HTML &&
  8421. doc.nodes[node].tag != BR_TAG_BODY) {
  8422. /* A percentage of the containing block's definite height, or
  8423. * auto when it has none (it used to resolve against the
  8424. * width). The result is a minimum: without scrollable inner
  8425. * boxes, an app shell's height:100%; overflow:hidden column
  8426. * would otherwise clip everything past the first screen. */
  8427. int auto_h = l->y - (top + bt + pt);
  8428. content_h = parent_cb_h > 0 ?
  8429. parent_cb_h * (int)st->height / 100 -
  8430. (st->box_sizing ? deco_h : 0) : 0;
  8431. if (content_h < auto_h)
  8432. content_h = auto_h;
  8433. } else if (st->height_kind &&
  8434. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8435. doc.nodes[node].tag == BR_TAG_BODY) &&
  8436. st->height_kind == 2)) {
  8437. content_h = style_height_px(st, cbw);
  8438. if (st->box_sizing)
  8439. content_h -= deco_h;
  8440. } else {
  8441. /* Percentage heights on html/body resolve against the
  8442. * viewport, but their content still defines the document
  8443. * scroll height. Treating them as auto avoids collapsing
  8444. * the measured page to the containing block width. */
  8445. content_h = l->y - (top + bt + pt);
  8446. /* aspect-ratio: the preferred height of an auto-height box
  8447. * (Tailwind aspect-video image frames); content can still
  8448. * make it taller, as with min-height: auto. */
  8449. if (st->aspect_w && st->aspect_h && content_w > 0) {
  8450. int ah = content_w * (int)st->aspect_h /
  8451. (int)st->aspect_w;
  8452. if (content_h < ah)
  8453. content_h = ah;
  8454. }
  8455. }
  8456. if (content_h < 0)
  8457. content_h = 0;
  8458. if (st->max_height_kind) {
  8459. int mh = st->max_height_kind == 3 ?
  8460. cbw * st->max_height_calc_pct / 100 +
  8461. st->max_height_calc_px :
  8462. css_size(st->max_height_kind, st->max_height, cbw);
  8463. int max_box = st->box_sizing ? mh : mh + deco_h;
  8464. if (content_h + deco_h > max_box)
  8465. content_h = max_box - deco_h;
  8466. }
  8467. if (st->min_height_kind &&
  8468. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8469. doc.nodes[node].tag == BR_TAG_BODY) &&
  8470. st->min_height_kind == 2)) {
  8471. int mh = st->min_height_kind == 3 ?
  8472. cbw * st->min_height_calc_pct / 100 +
  8473. st->min_height_calc_px :
  8474. css_size(st->min_height_kind, st->min_height, cbw);
  8475. int min_box = st->box_sizing ? mh : mh + deco_h;
  8476. if (content_h + deco_h < min_box)
  8477. content_h = min_box - deco_h;
  8478. }
  8479. if (content_h < 0)
  8480. content_h = 0;
  8481. box_h = deco_h + content_h;
  8482. if (box_h < 0)
  8483. box_h = 0;
  8484. l->y = (shifted ? normal_top : top) + box_h;
  8485. if (node < BR_MAX_NODES) {
  8486. layout_boxes[node].x = l0;
  8487. layout_boxes[node].y = top;
  8488. layout_boxes[node].w = r0 - l0;
  8489. layout_boxes[node].h = box_h;
  8490. layout_boxes[node].valid = r0 > l0;
  8491. }
  8492. l->left = old_left;
  8493. l->right = old_right;
  8494. l->align = old_align;
  8495. l->y += mp_px(st, 2, cbw);
  8496. if (!l->draw) {
  8497. if (box_h > 65535)
  8498. box_h = 65535;
  8499. block_h[node] = (unsigned short)box_h;
  8500. block_top[node] = (unsigned short)(top < 0 ? 0 :
  8501. top > 65535 ? 65535 : top);
  8502. }
  8503. if (positioned) {
  8504. l->y = flow_y;
  8505. l->left = flow_left;
  8506. l->right = flow_right;
  8507. }
  8508. l->parent_top = saved_parent_top;
  8509. l->cb_left = saved_cb_left;
  8510. l->cb_right = saved_cb_right;
  8511. l->cb_top = saved_cb_top;
  8512. }
  8513. static int text_node_blank(const struct br_node *nd)
  8514. {
  8515. const char *t = doc.text + nd->text_off;
  8516. unsigned int i;
  8517. for (i = 0; i < nd->text_len; i++)
  8518. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  8519. t[i] != '\r')
  8520. return 0;
  8521. return 1;
  8522. }
  8523. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  8524. * text/image widths in the subtree, plus padding and margins. This keeps
  8525. * Bootstrap's floated nav items on one line instead of giving each the whole
  8526. * row. */
  8527. static int text_space(char c)
  8528. {
  8529. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  8530. }
  8531. static int intrinsic_width(struct ngui *ui, unsigned int node,
  8532. const struct br_style *pst, int depth, int base)
  8533. {
  8534. unsigned int c;
  8535. int line_w = 0, max_w = 0;
  8536. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  8537. if (depth > 32)
  8538. return 0;
  8539. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8540. struct br_node *nd = &doc.nodes[c];
  8541. struct br_style cs;
  8542. if (nd->type == BR_NODE_TEXT) {
  8543. const char *t = doc.text + nd->text_off;
  8544. unsigned int tn = nd->text_len;
  8545. if (doc.nodes[node].tag == BR_TAG_PRE) {
  8546. line_w += (int)face_text_width(ui, pst, t, tn);
  8547. } else {
  8548. unsigned int ti = 0;
  8549. int first = 1;
  8550. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  8551. int sp = (int)face_text_width(ui, pst, " ", 1);
  8552. while (ti < tn) {
  8553. unsigned int ts;
  8554. while (ti < tn && text_space(t[ti]))
  8555. ti++;
  8556. ts = ti;
  8557. while (ti < tn && !text_space(t[ti]))
  8558. ti++;
  8559. if (ti == ts)
  8560. break;
  8561. if (!first || lead)
  8562. line_w += sp;
  8563. lead = 0;
  8564. line_w += (int)face_text_width(ui, pst,
  8565. t + ts, ti - ts);
  8566. first = 0;
  8567. }
  8568. }
  8569. continue;
  8570. }
  8571. br_style_for(&doc, c, pst, &cs);
  8572. if (cs.display == BR_DISPLAY_NONE)
  8573. continue;
  8574. if (nd->tag == BR_TAG_BR) {
  8575. if (line_w > max_w)
  8576. max_w = line_w;
  8577. line_w = 0;
  8578. continue;
  8579. }
  8580. if (nd->tag == BR_TAG_IMG) {
  8581. /* Measure the image as layout will draw it: a CSS or
  8582. * attribute height keeps the intrinsic aspect ratio, and
  8583. * a CSS width overrides the native pixel width. Bootstrap
  8584. * sizes the Cloudron logo with height:40px only. */
  8585. int idx = nd->img_index;
  8586. int iw = 0, ih = 0;
  8587. if (idx >= 0 && idx < image_count &&
  8588. images[idx].state == 1) {
  8589. iw = (int)images[idx].native_w;
  8590. ih = (int)images[idx].native_h;
  8591. if (iw <= 0 || ih <= 0) {
  8592. iw = (int)images[idx].img.w;
  8593. ih = (int)images[idx].img.h;
  8594. }
  8595. }
  8596. if (cs.width_kind) {
  8597. int ww = style_width_px(&cs, base);
  8598. line_w += ww > 0 ? ww : 64;
  8599. } else if (nd->width_attr) {
  8600. line_w += nd->width_attr;
  8601. } else if (nd->height_attr && iw && ih) {
  8602. line_w += iw * (int)nd->height_attr / ih;
  8603. } else if (cs.height_kind && iw && ih) {
  8604. /* A percentage height needs the parent's
  8605. * definite height (the logo's 2rem box), as in
  8606. * add_image_run(); otherwise it is auto. */
  8607. int hh = cs.height_kind == 1 ?
  8608. style_height_px(&cs, base) :
  8609. cs.height_kind == 2 &&
  8610. pst->height_kind == 1 ?
  8611. (int)pst->height * (int)cs.height / 100 :
  8612. 0;
  8613. line_w += hh > 0 ? iw * hh / ih : iw;
  8614. } else if (iw) {
  8615. line_w += iw;
  8616. } else {
  8617. line_w += 64;
  8618. }
  8619. continue;
  8620. }
  8621. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  8622. nd->tag == BR_TAG_TEXTAREA) &&
  8623. !s_eq(br_type(&doc, c), "hidden")) {
  8624. /* Form controls are replaced: CSS width applies even
  8625. * when they are inline (add_form_run's sizes). */
  8626. int fw = cs.width_kind ? style_width_px(&cs, base) :
  8627. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  8628. if (s_eq(br_type(&doc, c), "checkbox") ||
  8629. s_eq(br_type(&doc, c), "radio"))
  8630. fw = 16;
  8631. line_w += (fw > 0 ? fw : 120) +
  8632. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  8633. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  8634. continue;
  8635. }
  8636. if (nd->tag == BR_TAG_SVG) {
  8637. /* A replaced element: its own size, like add_svg_run()
  8638. * (its path children have no width). */
  8639. int sw, sh, sb = cs.width_kind ?
  8640. style_width_px(&cs, base) : base;
  8641. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  8642. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  8643. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  8644. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8645. line_w += sw;
  8646. } else {
  8647. if (line_w > max_w)
  8648. max_w = line_w;
  8649. line_w = 0;
  8650. if (sw > max_w)
  8651. max_w = sw;
  8652. }
  8653. continue;
  8654. }
  8655. {
  8656. int cw = mp_px(&cs, 7, base) +
  8657. mp_px(&cs, 5, base) +
  8658. mp_px(&cs, 3, base) +
  8659. mp_px(&cs, 1, base) +
  8660. cs.border_w[1] + cs.border_w[3];
  8661. /* width/height do not apply to non-replaced inline
  8662. * boxes. The tagesschau home label is an inline span
  8663. * with width:1px for the mobile icon-only header; using
  8664. * that width made the whole subnav collapse to a
  8665. * one-character column. */
  8666. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  8667. cw += cs.width_kind == 1 ? cs.width :
  8668. style_width_px(&cs, base);
  8669. else
  8670. cw += intrinsic_width(ui, c, &cs, depth + 1,
  8671. base);
  8672. if (flex_row || cs.float_left ||
  8673. cs.display == BR_DISPLAY_INLINE ||
  8674. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8675. line_w += cw;
  8676. } else {
  8677. if (line_w > max_w)
  8678. max_w = line_w;
  8679. line_w = 0;
  8680. if (cw > max_w)
  8681. max_w = cw;
  8682. }
  8683. }
  8684. if (line_w > 4096 || max_w > 4096)
  8685. break;
  8686. }
  8687. return line_w > max_w ? line_w : max_w;
  8688. }
  8689. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  8690. * the main user: .row > .col-md-* with float:left and a percentage width.
  8691. * Each column is laid out with its own left/right edge and the row advances
  8692. * to the tallest column. Returns the first child not consumed. */
  8693. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  8694. const struct br_style *pst, int depth,
  8695. unsigned short link)
  8696. {
  8697. unsigned int n = first;
  8698. int row_left = l->left, row_right = l->right;
  8699. int row_top, row_bottom, xl, xr, any = 0;
  8700. int fl_left = row_left, fl_right = row_right, fl_bottom;
  8701. flush_line(l);
  8702. row_top = l->y;
  8703. row_bottom = l->y;
  8704. fl_bottom = row_top;
  8705. xl = row_left;
  8706. xr = row_right;
  8707. while (n) {
  8708. struct br_node *nd = &doc.nodes[n];
  8709. struct br_style cs;
  8710. unsigned short lk = link;
  8711. int colw, right;
  8712. if (nd->type == BR_NODE_TEXT) {
  8713. if (text_node_blank(nd)) {
  8714. n = nd->next;
  8715. continue;
  8716. }
  8717. break;
  8718. }
  8719. br_style_for(&doc, n, pst, &cs);
  8720. if (cs.display == BR_DISPLAY_NONE) {
  8721. n = nd->next;
  8722. continue;
  8723. }
  8724. /* A float blockifies its box: Bootstrap floats inline
  8725. * anchors too (the navbar brand and its text links), and
  8726. * their padding must be honoured. */
  8727. if (!cs.float_left)
  8728. break;
  8729. if (nd->tag == BR_TAG_A && nd->href_off)
  8730. lk = (unsigned short)n;
  8731. right = cs.float_left == 2;
  8732. if (cs.width_kind == 1 || cs.width_kind == 2 ||
  8733. cs.width_kind == 3) {
  8734. /* The column is the margin box: `width` is the
  8735. * content (or, with border-box, the border) box,
  8736. * and layout_block() takes margins, padding and
  8737. * borders back out of the column. A 200px float
  8738. * with margin-right:20px used to get 180px of
  8739. * content. */
  8740. int base = row_right - row_left;
  8741. colw = cs.width_kind == 1 ? (int)cs.width :
  8742. style_width_px(&cs, base);
  8743. colw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  8744. if (!cs.box_sizing)
  8745. colw += mp_px(&cs, 7, base) +
  8746. mp_px(&cs, 5, base) +
  8747. cs.border_w[1] + cs.border_w[3];
  8748. } else {
  8749. int base = row_right - row_left;
  8750. /* Shrink-to-fit outer width: borders too (Google's
  8751. * 1px-bordered "Anmelden" pill wrapped otherwise). */
  8752. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  8753. mp_px(&cs, 7, base) +
  8754. mp_px(&cs, 5, base) +
  8755. mp_px(&cs, 3, base) +
  8756. mp_px(&cs, 1, base) +
  8757. cs.border_w[1] + cs.border_w[3];
  8758. if (colw < 8)
  8759. colw = 8;
  8760. }
  8761. if (colw < 8)
  8762. colw = 8;
  8763. if (colw > row_right - row_left)
  8764. colw = row_right - row_left;
  8765. /* The float column width is already resolved. */
  8766. cs.width_kind = 0;
  8767. cs.max_width_kind = 0;
  8768. if (right) {
  8769. if (any && xr - colw < xl) {
  8770. row_top = row_bottom;
  8771. row_bottom = row_top;
  8772. xl = row_left;
  8773. xr = row_right;
  8774. }
  8775. if (xr - colw < xl)
  8776. colw = xr - xl;
  8777. if (colw < 8)
  8778. colw = 8;
  8779. l->left = xr - colw;
  8780. if (l->left < row_left)
  8781. l->left = row_left;
  8782. l->right = xr;
  8783. xr = l->left;
  8784. if (xr < fl_right)
  8785. fl_right = xr;
  8786. } else {
  8787. if (any && xl + colw > xr) {
  8788. row_top = row_bottom;
  8789. row_bottom = row_top;
  8790. xl = row_left;
  8791. xr = row_right;
  8792. }
  8793. l->left = xl;
  8794. l->right = xl + colw;
  8795. xl += colw;
  8796. if (xl > fl_left)
  8797. fl_left = xl;
  8798. }
  8799. if (l->right < l->left + 8)
  8800. l->right = l->left + 8;
  8801. l->y = row_top;
  8802. l->line_x = l->left;
  8803. l->run_x = l->left;
  8804. l->line_y = l->y;
  8805. l->line_h = 0;
  8806. l->nruns = 0;
  8807. l->space_pending = 0;
  8808. l->align = cs.align;
  8809. layout_block(l, n, &cs, depth + 1, lk);
  8810. if (l->y > row_bottom)
  8811. row_bottom = l->y;
  8812. if (l->y > fl_bottom)
  8813. fl_bottom = l->y;
  8814. any = 1;
  8815. n = nd->next;
  8816. }
  8817. l->left = row_left;
  8818. l->right = row_right;
  8819. if (n && any) {
  8820. struct br_node *nd = &doc.nodes[n];
  8821. int inline_next = 0;
  8822. if (nd->type == BR_NODE_TEXT) {
  8823. inline_next = 1;
  8824. } else if (nd->type == BR_NODE_ELEM) {
  8825. struct br_style cs;
  8826. br_style_for(&doc, n, pst, &cs);
  8827. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  8828. cs.display != BR_DISPLAY_NONE &&
  8829. !br_tag_is_block(nd->tag);
  8830. }
  8831. if (inline_next) {
  8832. if (l->float_active) {
  8833. if (l->float_left > fl_left)
  8834. fl_left = l->float_left;
  8835. if (l->float_right < fl_right)
  8836. fl_right = l->float_right;
  8837. if (l->float_bottom > fl_bottom)
  8838. fl_bottom = l->float_bottom;
  8839. }
  8840. l->float_active = 1;
  8841. l->float_left = fl_left;
  8842. l->float_right = fl_right;
  8843. l->float_bottom = fl_bottom;
  8844. l->y = row_top;
  8845. } else {
  8846. l->float_active = 0;
  8847. l->y = row_bottom;
  8848. }
  8849. } else {
  8850. l->float_active = 0;
  8851. l->y = row_bottom;
  8852. }
  8853. l->line_x = l->left;
  8854. l->run_x = l->left;
  8855. l->line_left = l->left;
  8856. l->line_right = l->right;
  8857. l->line_y = l->y;
  8858. l->line_h = 0;
  8859. l->nruns = 0;
  8860. l->space_pending = 0;
  8861. return n;
  8862. }
  8863. static int flex_item_width(struct lay *l, unsigned int n,
  8864. const struct br_style *cs, int avail)
  8865. {
  8866. struct br_node *nd = &doc.nodes[n];
  8867. (void)l;
  8868. int w;
  8869. if (cs->width_kind == 2 || cs->width_kind == 3)
  8870. w = style_width_px(cs, avail);
  8871. else if (cs->width_kind == 1)
  8872. w = (int)cs->width;
  8873. else if (nd->tag == BR_TAG_IMG) {
  8874. int idx = nd->img_index;
  8875. if (idx >= 0 && idx < image_count &&
  8876. images[idx].state == 1)
  8877. w = (int)images[idx].img.w;
  8878. else if (nd->width_attr)
  8879. w = (int)nd->width_attr;
  8880. else
  8881. w = 64;
  8882. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  8883. nd->tag == BR_TAG_TEXTAREA) {
  8884. /* A control has no content to measure: its default size
  8885. * (a search field in a filter bar). */
  8886. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  8887. } else {
  8888. w = intrinsic_width(l->ui, n, cs, 0, avail);
  8889. }
  8890. /* Explicit widths are content-box sizes; the flex item's outer width
  8891. * must include padding, borders and margins. */
  8892. w += mp_px(cs, 7, avail);
  8893. w += mp_px(cs, 5, avail);
  8894. w += mp_px(cs, 3, avail);
  8895. w += mp_px(cs, 1, avail);
  8896. w += cs->border_w[1] + cs->border_w[3];
  8897. if (w < 24)
  8898. w = 24;
  8899. if (w > avail)
  8900. w = avail;
  8901. return w;
  8902. }
  8903. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  8904. int depth);
  8905. /* An inline child of a text-only inline-block: the same test minus the
  8906. * display check (an inline <span> may have padding/background in CSS, but
  8907. * the inline path paints those for spans anyway). */
  8908. static int inline_block_flows_inline(unsigned int node,
  8909. const struct br_style *cs, int depth)
  8910. {
  8911. unsigned int c;
  8912. if (depth > 3 || cs->pos)
  8913. return 0;
  8914. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8915. const struct br_node *nd = &doc.nodes[c];
  8916. struct br_style ch;
  8917. if (nd->type != BR_NODE_ELEM)
  8918. continue;
  8919. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  8920. br_tag_is_block(nd->tag))
  8921. return 0;
  8922. br_style_for(&doc, c, cs, &ch);
  8923. if (ch.display == BR_DISPLAY_NONE)
  8924. continue;
  8925. if (ch.display != BR_DISPLAY_INLINE ||
  8926. !inline_block_flows_inline(c, &ch, depth + 1))
  8927. return 0;
  8928. }
  8929. return 1;
  8930. }
  8931. /* An inline-block that is only text in a line (a <time> in a byline, a
  8932. * label) with no box of its own -- no size, background, border or padding
  8933. * -- lays out exactly like an inline element, so it stays in the text line
  8934. * instead of ending it. Boxes with any of those keep the row path. */
  8935. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  8936. int depth)
  8937. {
  8938. unsigned int c;
  8939. int i;
  8940. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  8941. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  8942. cs->pos || depth > 3)
  8943. return 0;
  8944. for (i = 0; i < 4; i++)
  8945. if (cs->border_w[i])
  8946. return 0;
  8947. for (i = 4; i < 8; i++)
  8948. if (mp_px(cs, i, 0) > 0)
  8949. return 0;
  8950. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8951. const struct br_node *nd = &doc.nodes[c];
  8952. struct br_style ch;
  8953. if (nd->type != BR_NODE_ELEM)
  8954. continue;
  8955. if (nd->tag == BR_TAG_SVG) {
  8956. /* An icon box (Docusaurus' admonition heading:
  8957. * `<span inline-block><svg/></span>Note`): the SVG
  8958. * is an inline replaced run, so the box can stay in
  8959. * the text line. */
  8960. br_style_for(&doc, c, cs, &ch);
  8961. if (ch.display == BR_DISPLAY_NONE ||
  8962. ch.display == BR_DISPLAY_INLINE ||
  8963. ch.display == BR_DISPLAY_INLINE_BLOCK)
  8964. continue;
  8965. return 0;
  8966. }
  8967. if (nd->tag == BR_TAG_IMG || br_tag_is_block(nd->tag))
  8968. return 0;
  8969. br_style_for(&doc, c, cs, &ch);
  8970. if (ch.display == BR_DISPLAY_NONE)
  8971. continue;
  8972. if (ch.display != BR_DISPLAY_INLINE ||
  8973. !inline_block_flows_inline(c, &ch, depth + 1))
  8974. return 0;
  8975. }
  8976. return 1;
  8977. }
  8978. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  8979. * on one line, not one full-width block each. Place intrinsic widths from
  8980. * left to right and wrap when the row is full. */
  8981. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  8982. const struct br_style *pst, int depth,
  8983. unsigned short link)
  8984. {
  8985. unsigned int n = first;
  8986. int row_left = l->left, row_right = l->right;
  8987. int avail = row_right - row_left;
  8988. int x = row_left, y = l->y, row_h = 0, any = 0;
  8989. /* Each box sets l->align from its own style; the text after the row
  8990. * must keep the container's (a centred .fa-fw icon centred the menu
  8991. * label that followed it). */
  8992. unsigned char row_align = l->align;
  8993. flush_line(l);
  8994. y = l->y;
  8995. while (n) {
  8996. struct br_node *nd = &doc.nodes[n];
  8997. struct br_style cs;
  8998. unsigned short lk = link;
  8999. int colw, h;
  9000. if (nd->type == BR_NODE_TEXT) {
  9001. if (!text_node_blank(nd))
  9002. break;
  9003. if (any)
  9004. x += 4;
  9005. n = nd->next;
  9006. continue;
  9007. }
  9008. br_style_for(&doc, n, pst, &cs);
  9009. if (cs.display == BR_DISPLAY_NONE) {
  9010. n = nd->next;
  9011. continue;
  9012. }
  9013. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  9014. break;
  9015. if (nd->tag == BR_TAG_A && nd->href_off)
  9016. lk = (unsigned short)n;
  9017. colw = flex_item_width(l, n, &cs, avail);
  9018. /* A few pixels of slack keep a single long token (boot.S)
  9019. * from wrapping at the exact content width. */
  9020. colw += 8;
  9021. if (colw > avail)
  9022. colw = avail;
  9023. cs.width_kind = 0;
  9024. cs.max_width_kind = 0;
  9025. if (any && x + colw > row_right) {
  9026. y += row_h + 2;
  9027. x = row_left;
  9028. row_h = 0;
  9029. any = 0;
  9030. }
  9031. if (any && x > row_left)
  9032. x += 4;
  9033. l->left = x;
  9034. l->right = x + colw;
  9035. if (l->right < l->left + 8)
  9036. l->right = l->left + 8;
  9037. l->y = y;
  9038. l->line_x = l->left;
  9039. l->run_x = l->left;
  9040. l->line_y = l->y;
  9041. l->line_h = 0;
  9042. l->nruns = 0;
  9043. l->space_pending = 0;
  9044. l->align = cs.align;
  9045. layout_block(l, n, &cs, depth + 1, lk);
  9046. h = l->y - y;
  9047. if (h > row_h)
  9048. row_h = h;
  9049. x += colw;
  9050. any = 1;
  9051. n = nd->next;
  9052. }
  9053. if (any)
  9054. y += row_h;
  9055. l->left = row_left;
  9056. l->right = row_right;
  9057. l->align = row_align;
  9058. l->y = y;
  9059. l->line_x = l->left;
  9060. l->run_x = l->left;
  9061. l->line_y = l->y;
  9062. l->line_h = 0;
  9063. l->nruns = 0;
  9064. l->space_pending = 0;
  9065. return n;
  9066. }
  9067. struct flex_item {
  9068. unsigned int node;
  9069. unsigned short link;
  9070. int w;
  9071. };
  9072. /* An item's min-width/max-width as outer (margin-box) widths in the flex
  9073. * row, or -1 when unset. Percentages and calc() resolve against the
  9074. * container width. */
  9075. static int flex_limit_w(const struct br_style *cs, int which_max, int avail)
  9076. {
  9077. unsigned char kind = which_max ? cs->max_width_kind :
  9078. cs->min_width_kind;
  9079. int w;
  9080. if (kind == 3)
  9081. w = which_max ?
  9082. avail * cs->max_width_calc_pct / 100 +
  9083. cs->max_width_calc_px :
  9084. avail * cs->min_width_calc_pct / 100 +
  9085. cs->min_width_calc_px;
  9086. else
  9087. w = css_size(kind, which_max ? cs->max_width : cs->min_width,
  9088. avail);
  9089. if (w < 0)
  9090. return -1;
  9091. if (!cs->box_sizing)
  9092. w += mp_px(cs, 7, avail) + mp_px(cs, 5, avail) +
  9093. cs->border_w[1] + cs->border_w[3];
  9094. return w + mp_px(cs, 3, avail) + mp_px(cs, 1, avail);
  9095. }
  9096. static int flex_clamp_w(const struct br_style *cs, int w, int avail)
  9097. {
  9098. int mx = flex_limit_w(cs, 1, avail), mn = flex_limit_w(cs, 0, avail);
  9099. if (mx >= 0 && w > mx)
  9100. w = mx;
  9101. if (mn >= 0 && w < mn)
  9102. w = mn;
  9103. return w;
  9104. }
  9105. static void layout_flex_children(struct lay *l, unsigned int parent,
  9106. const struct br_style *pst, int depth,
  9107. unsigned short link)
  9108. {
  9109. struct flex_item it[32];
  9110. unsigned int c;
  9111. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  9112. int grow_need = 0; /* growing items at their content width */
  9113. int row_left = l->left, row_right = l->right;
  9114. int avail = row_right - row_left;
  9115. int idx, row_top;
  9116. unsigned char row_align = l->align;
  9117. if (avail < 8 || depth > 48) {
  9118. layout_children(l, parent, pst, depth, link);
  9119. return;
  9120. }
  9121. /* If direct text is not just whitespace, normal block flow handles it
  9122. * better than pretending it is a flex item. */
  9123. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9124. struct br_node *nd = &doc.nodes[c];
  9125. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9126. layout_children(l, parent, pst, depth, link);
  9127. return;
  9128. }
  9129. }
  9130. for (c = doc.nodes[parent].first;
  9131. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  9132. c = doc.nodes[c].next) {
  9133. struct br_node *nd = &doc.nodes[c];
  9134. struct br_style cs;
  9135. if (nd->type == BR_NODE_TEXT)
  9136. continue;
  9137. br_style_for(&doc, c, pst, &cs);
  9138. if (cs.display == BR_DISPLAY_NONE)
  9139. continue;
  9140. it[nitem].node = c;
  9141. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  9142. (unsigned short)c : link;
  9143. it[nitem].w = 0;
  9144. if (cs.flex_grow && !cs.width_kind) {
  9145. grow_count++;
  9146. grow_need += flex_item_width(l, c, &cs, avail);
  9147. } else
  9148. fixed += flex_clamp_w(&cs,
  9149. flex_item_width(l, c, &cs, avail),
  9150. avail);
  9151. nitem++;
  9152. }
  9153. /* A narrow container (an icon row sized to its content, Google's
  9154. * mic + lens buttons) is still a row when its items fit; only a
  9155. * narrow one that would overflow or squeeze growing items falls
  9156. * back to block flow. */
  9157. if (avail < 160 && fixed + grow_need > avail) {
  9158. layout_children(l, parent, pst, depth, link);
  9159. return;
  9160. }
  9161. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  9162. /* A growing item capped by max-width (Docusaurus' doc column,
  9163. * `max-width: 75%`; its main container, `calc(100% - 300px)`)
  9164. * keeps its cap and leaves the rest of the free space to the other
  9165. * growing items. */
  9166. if (grow_count) {
  9167. int pass, capped[32] = { 0 };
  9168. for (pass = 0; pass < nitem; pass++) {
  9169. int changed = 0;
  9170. for (idx = 0; idx < nitem; idx++) {
  9171. struct br_style cs;
  9172. int lim;
  9173. if (capped[idx])
  9174. continue;
  9175. br_style_for(&doc, it[idx].node, pst, &cs);
  9176. if (!cs.flex_grow || cs.width_kind)
  9177. continue;
  9178. lim = flex_clamp_w(&cs, grow_w, avail);
  9179. if (lim == grow_w)
  9180. continue;
  9181. capped[idx] = lim + 1;
  9182. fixed += lim;
  9183. grow_count--;
  9184. changed = 1;
  9185. }
  9186. if (!changed || !grow_count)
  9187. break;
  9188. grow_w = (avail - fixed) / grow_count;
  9189. }
  9190. for (idx = 0; idx < nitem; idx++)
  9191. it[idx].w = capped[idx] ? capped[idx] - 1 : 0;
  9192. }
  9193. if (grow_w < 96 && avail >= 160)
  9194. grow_w = 96;
  9195. for (idx = 0; idx < nitem; idx++) {
  9196. struct br_style cs;
  9197. if (it[idx].w)
  9198. continue; /* capped growing item */
  9199. br_style_for(&doc, it[idx].node, pst, &cs);
  9200. if (cs.flex_grow && !cs.width_kind)
  9201. it[idx].w = grow_w;
  9202. else
  9203. it[idx].w = flex_clamp_w(&cs,
  9204. flex_item_width(l,
  9205. it[idx].node,
  9206. &cs, avail),
  9207. avail);
  9208. if (it[idx].w > avail)
  9209. it[idx].w = avail;
  9210. if (it[idx].w < 8)
  9211. it[idx].w = 8;
  9212. }
  9213. row_top = l->y;
  9214. idx = 0;
  9215. while (idx < nitem) {
  9216. int start = idx, count = 0, row_w = 0;
  9217. int free_w, x, extra = 0, row_h = 0, k;
  9218. while (idx < nitem) {
  9219. int add = it[idx].w + (count ? gap : 0);
  9220. /* CSS default is nowrap; only flex-wrap: wrap (1)
  9221. * starts a new row. */
  9222. if (count && pst->flex_wrap == 1 &&
  9223. row_w + add > avail)
  9224. break;
  9225. row_w += add;
  9226. count++;
  9227. idx++;
  9228. }
  9229. if (!count) {
  9230. count = 1;
  9231. row_w = it[start].w;
  9232. idx = start + 1;
  9233. }
  9234. free_w = avail - row_w;
  9235. if (free_w < 0)
  9236. free_w = 0;
  9237. x = row_left;
  9238. if (pst->justify == 1) {
  9239. x += free_w / 2;
  9240. } else if (pst->justify == 2) {
  9241. x += free_w;
  9242. } else if (pst->justify == 3) {
  9243. extra = count > 1 ? free_w / (count - 1) : 0;
  9244. } else if (pst->justify == 4) {
  9245. extra = count ? free_w / count : 0;
  9246. x += extra / 2;
  9247. } else if (pst->justify == 5) {
  9248. extra = count ? free_w / (count + 1) : 0;
  9249. x += extra;
  9250. }
  9251. for (k = 0; k < count; k++) {
  9252. int node = (int)it[start + k].node;
  9253. int h = block_h[node];
  9254. if (h > row_h)
  9255. row_h = h;
  9256. }
  9257. if (pst->height_kind) {
  9258. int hh = style_height_px(pst, avail);
  9259. if (hh > row_h)
  9260. row_h = hh;
  9261. }
  9262. for (k = 0; k < count; k++) {
  9263. struct br_style cs;
  9264. int node = (int)it[start + k].node;
  9265. int yoff = 0;
  9266. br_style_for(&doc, node, pst, &cs);
  9267. cs.width_kind = 0;
  9268. cs.max_width_kind = 0;
  9269. {
  9270. int ai = cs.align_self ? cs.align_self - 1 :
  9271. pst->align_items;
  9272. if (l->draw && ai && row_h > block_h[node]) {
  9273. if (ai == 1)
  9274. yoff = (row_h -
  9275. block_h[node]) / 2;
  9276. else if (ai == 2)
  9277. yoff = row_h - block_h[node];
  9278. }
  9279. }
  9280. l->left = x;
  9281. l->right = x + it[start + k].w;
  9282. if (l->right < l->left + 8)
  9283. l->right = l->left + 8;
  9284. l->y = row_top + yoff;
  9285. l->line_x = l->left;
  9286. l->run_x = l->left;
  9287. l->line_y = l->y;
  9288. l->line_h = 0;
  9289. l->nruns = 0;
  9290. l->space_pending = 0;
  9291. l->align = cs.align;
  9292. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  9293. if (!l->draw) {
  9294. int h = l->y - row_top;
  9295. if (h > row_h)
  9296. row_h = h;
  9297. }
  9298. x += it[start + k].w;
  9299. if (k + 1 < count)
  9300. x += gap + extra;
  9301. }
  9302. row_top += row_h;
  9303. }
  9304. l->left = row_left;
  9305. l->right = row_right;
  9306. l->align = row_align;
  9307. l->y = row_top;
  9308. l->line_x = l->left;
  9309. l->run_x = l->left;
  9310. l->line_y = l->y;
  9311. l->line_h = 0;
  9312. l->nruns = 0;
  9313. l->space_pending = 0;
  9314. }
  9315. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  9316. * plus the grid-area hints used by site shells (site notice/footer full
  9317. * width, column-start left, page-content right). Anything more elaborate
  9318. * falls back to normal block flow. */
  9319. static int grid_track_width(unsigned char kind, unsigned short val,
  9320. int avail, int other)
  9321. {
  9322. if (kind == 2)
  9323. return avail * (int)val / 100;
  9324. if (kind == 1)
  9325. return val;
  9326. return other;
  9327. }
  9328. static void layout_grid_children(struct lay *l, unsigned int parent,
  9329. const struct br_style *pst, int depth,
  9330. unsigned short link)
  9331. {
  9332. unsigned int n;
  9333. int row_left = l->left, row_right = l->right;
  9334. int avail = row_right - row_left;
  9335. int gap = pst->grid_gap;
  9336. int track_total = avail - gap;
  9337. int col0, col1, x0, x1;
  9338. int row_y, row_bottom, have_left = 0, have_right = 0;
  9339. unsigned int c;
  9340. if (avail < 32 || depth > 48)
  9341. return;
  9342. if (track_total < 16)
  9343. track_total = 16;
  9344. col0 = grid_track_width((unsigned char)(pst->width_kind),
  9345. pst->width, track_total, 0);
  9346. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  9347. pst->max_width, track_total, 0);
  9348. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  9349. int w0 = pst->width ? pst->width : 1;
  9350. int w1 = pst->max_width ? pst->max_width : 1;
  9351. col0 = track_total * w0 / (w0 + w1);
  9352. col1 = track_total - col0;
  9353. } else if (pst->width_kind == 3) {
  9354. col0 = track_total - col1;
  9355. if (col0 < 24)
  9356. col0 = 24;
  9357. } else if (pst->max_width_kind == 3) {
  9358. col1 = track_total - col0;
  9359. if (col1 < 24)
  9360. col1 = 24;
  9361. }
  9362. if (col0 < 24)
  9363. col0 = 24;
  9364. if (col1 < 24)
  9365. col1 = 24;
  9366. if (col0 + col1 > track_total) {
  9367. col1 = track_total - col0;
  9368. if (col1 < 24)
  9369. col1 = 24;
  9370. }
  9371. x0 = row_left;
  9372. x1 = row_left + col0 + gap;
  9373. /* Direct text makes a grid ambiguous; use block flow instead. */
  9374. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9375. struct br_node *nd = &doc.nodes[c];
  9376. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9377. layout_children(l, parent, pst, depth, link);
  9378. return;
  9379. }
  9380. }
  9381. row_y = row_bottom = l->y;
  9382. n = doc.nodes[parent].first;
  9383. while (n) {
  9384. struct br_node *nd = &doc.nodes[n];
  9385. struct br_style cs;
  9386. unsigned short lk = link;
  9387. int slot, x, w;
  9388. if (nd->type == BR_NODE_TEXT) {
  9389. n = nd->next;
  9390. continue;
  9391. }
  9392. br_style_for(&doc, n, pst, &cs);
  9393. if (cs.display == BR_DISPLAY_NONE) {
  9394. n = nd->next;
  9395. continue;
  9396. }
  9397. if (nd->tag == BR_TAG_A && nd->href_off)
  9398. lk = (unsigned short)n;
  9399. slot = cs.grid_slot;
  9400. if (!slot) {
  9401. if (!have_left)
  9402. slot = 2;
  9403. else if (!have_right)
  9404. slot = 3;
  9405. else
  9406. slot = 2;
  9407. }
  9408. if (slot == 1) {
  9409. if (have_left || have_right) {
  9410. row_y = row_bottom;
  9411. have_left = have_right = 0;
  9412. }
  9413. x = row_left;
  9414. w = avail;
  9415. } else if (slot == 2) {
  9416. if (have_left) {
  9417. row_y = row_bottom;
  9418. have_left = have_right = 0;
  9419. }
  9420. x = x0;
  9421. w = col0;
  9422. have_left = 1;
  9423. } else {
  9424. if (have_right) {
  9425. row_y = row_bottom;
  9426. have_left = have_right = 0;
  9427. }
  9428. x = x1;
  9429. w = col1;
  9430. have_right = 1;
  9431. }
  9432. cs.width_kind = 0;
  9433. cs.max_width_kind = 0;
  9434. l->left = x;
  9435. l->right = x + w;
  9436. if (l->right < l->left + 8)
  9437. l->right = l->left + 8;
  9438. l->y = row_y;
  9439. l->line_x = l->left;
  9440. l->run_x = l->left;
  9441. l->line_y = l->y;
  9442. l->line_h = 0;
  9443. l->nruns = 0;
  9444. l->space_pending = 0;
  9445. l->align = cs.align;
  9446. layout_block(l, n, &cs, depth + 1, lk);
  9447. if (l->y > row_bottom)
  9448. row_bottom = l->y;
  9449. n = nd->next;
  9450. }
  9451. l->left = row_left;
  9452. l->right = row_right;
  9453. l->y = row_bottom;
  9454. l->line_x = l->left;
  9455. l->run_x = l->left;
  9456. l->line_y = l->y;
  9457. l->line_h = 0;
  9458. l->nruns = 0;
  9459. l->space_pending = 0;
  9460. }
  9461. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  9462. * capped at four. Used by the project docs' card grids. A fixed
  9463. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  9464. static void layout_grid_auto(struct lay *l, unsigned int parent,
  9465. const struct br_style *pst, int depth,
  9466. unsigned short link)
  9467. {
  9468. unsigned int n, c;
  9469. int row_left = l->left, row_right = l->right;
  9470. int avail = row_right - row_left;
  9471. int gap = pst->grid_gap;
  9472. int minw = pst->width_kind == 1 ? pst->width : 200;
  9473. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  9474. if (avail < 32 || depth > 48) {
  9475. layout_children(l, parent, pst, depth, link);
  9476. return;
  9477. }
  9478. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9479. struct br_node *nd = &doc.nodes[c];
  9480. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9481. layout_children(l, parent, pst, depth, link);
  9482. return;
  9483. }
  9484. }
  9485. if (minw < 80)
  9486. minw = 80;
  9487. ncols = (avail + gap) / (minw + gap);
  9488. if (ncols < 1)
  9489. ncols = 1;
  9490. if (ncols > 4)
  9491. ncols = 4;
  9492. if (pst->grid_auto > BR_GRID_FIXED) {
  9493. /* grid-template-columns: repeat(N, 1fr) */
  9494. ncols = pst->grid_auto - BR_GRID_FIXED;
  9495. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  9496. ncols--;
  9497. }
  9498. colw = (avail - gap * (ncols - 1)) / ncols;
  9499. if (colw < 24)
  9500. colw = 24;
  9501. x = row_left;
  9502. n = doc.nodes[parent].first;
  9503. while (n) {
  9504. struct br_node *nd = &doc.nodes[n];
  9505. struct br_style cs;
  9506. unsigned short lk = link;
  9507. int h;
  9508. if (nd->type == BR_NODE_TEXT) {
  9509. n = nd->next;
  9510. continue;
  9511. }
  9512. br_style_for(&doc, n, pst, &cs);
  9513. if (cs.display == BR_DISPLAY_NONE) {
  9514. n = nd->next;
  9515. continue;
  9516. }
  9517. if (nd->tag == BR_TAG_A && nd->href_off)
  9518. lk = (unsigned short)n;
  9519. cs.width_kind = 0;
  9520. cs.max_width_kind = 0;
  9521. l->left = x;
  9522. l->right = x + colw;
  9523. if (l->right < l->left + 8)
  9524. l->right = l->left + 8;
  9525. l->y = y;
  9526. l->line_x = l->left;
  9527. l->run_x = l->left;
  9528. l->line_y = l->y;
  9529. l->line_h = 0;
  9530. l->nruns = 0;
  9531. l->space_pending = 0;
  9532. l->align = cs.align;
  9533. layout_block(l, n, &cs, depth + 1, lk);
  9534. h = l->y - y;
  9535. if (h > row_h)
  9536. row_h = h;
  9537. col++;
  9538. n = nd->next;
  9539. if (col == ncols) {
  9540. y += row_h + gap;
  9541. x = row_left;
  9542. row_h = 0;
  9543. col = 0;
  9544. } else {
  9545. x += colw + gap;
  9546. }
  9547. }
  9548. if (col)
  9549. y += row_h;
  9550. else if (y > start_y)
  9551. y -= gap;
  9552. l->left = row_left;
  9553. l->right = row_right;
  9554. l->y = y;
  9555. l->line_x = l->left;
  9556. l->run_x = l->left;
  9557. l->line_y = l->y;
  9558. l->line_h = 0;
  9559. l->nruns = 0;
  9560. l->space_pending = 0;
  9561. }
  9562. /* Column widths are the widest cell in each column across every row, so all
  9563. * rows line up. The table model is still deliberately basic: no colspan,
  9564. * border-collapse or percentage columns. */
  9565. static void table_columns(struct lay *l, unsigned int table,
  9566. const struct br_style *pst, int avail,
  9567. int *raw, int maxcols, int *out_cols,
  9568. int *out_total)
  9569. {
  9570. unsigned int r, c;
  9571. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  9572. int fixed[12];
  9573. for (c = 0; c < (unsigned int)maxcols; c++) {
  9574. raw[c] = 0;
  9575. fixed[c] = 0;
  9576. }
  9577. /* Intrinsic widths of single-column cells. */
  9578. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9579. struct br_node *rn = &doc.nodes[r];
  9580. int col = 0;
  9581. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9582. continue;
  9583. for (c = rn->first; c; c = doc.nodes[c].next) {
  9584. struct br_node *cn = &doc.nodes[c];
  9585. struct br_style cs;
  9586. int w, span;
  9587. if (cn->type != BR_NODE_ELEM ||
  9588. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9589. continue;
  9590. span = cn->colspan ? cn->colspan : 1;
  9591. br_style_for(&doc, c, pst, &cs);
  9592. if (cs.display == BR_DISPLAY_NONE)
  9593. continue;
  9594. if (col + span > maxcols)
  9595. span = maxcols - col;
  9596. if (span < 1)
  9597. break;
  9598. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  9599. mp_px(&cs, 7, avail) +
  9600. mp_px(&cs, 5, avail) +
  9601. mp_px(&cs, 3, avail) +
  9602. mp_px(&cs, 1, avail) +
  9603. cs.border_w[0] + cs.border_w[1] +
  9604. cs.border_w[2] + cs.border_w[3];
  9605. if (w < 24)
  9606. w = 24;
  9607. if (span == 1) {
  9608. if (w > raw[col])
  9609. raw[col] = w;
  9610. }
  9611. if (col + span > cols)
  9612. cols = col + span;
  9613. col += span;
  9614. }
  9615. }
  9616. /* A colspan cell only has to be as wide as the sum of its columns. */
  9617. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9618. struct br_node *rn = &doc.nodes[r];
  9619. int col = 0;
  9620. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9621. continue;
  9622. for (c = rn->first; c; c = doc.nodes[c].next) {
  9623. struct br_node *cn = &doc.nodes[c];
  9624. struct br_style cs;
  9625. int span, w, sum, i;
  9626. if (cn->type != BR_NODE_ELEM ||
  9627. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9628. continue;
  9629. span = cn->colspan ? cn->colspan : 1;
  9630. if (col + span > maxcols)
  9631. span = maxcols - col;
  9632. if (span < 1)
  9633. break;
  9634. if (span > 1) {
  9635. br_style_for(&doc, c, pst, &cs);
  9636. if (cs.display != BR_DISPLAY_NONE) {
  9637. w = intrinsic_width(l->ui, c, &cs,
  9638. 0, avail) +
  9639. mp_px(&cs, 7, avail) +
  9640. mp_px(&cs, 5, avail) +
  9641. mp_px(&cs, 3, avail) +
  9642. mp_px(&cs, 1, avail) +
  9643. cs.border_w[0] + cs.border_w[1] +
  9644. cs.border_w[2] + cs.border_w[3];
  9645. sum = 0;
  9646. for (i = 0; i < span; i++)
  9647. sum += raw[col + i];
  9648. if (w > sum)
  9649. raw[col + span - 1] += w - sum;
  9650. }
  9651. }
  9652. col += span;
  9653. }
  9654. }
  9655. /* Explicit and percentage widths override intrinsic widths. */
  9656. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9657. struct br_node *rn = &doc.nodes[r];
  9658. int col = 0;
  9659. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9660. continue;
  9661. for (c = rn->first; c; c = doc.nodes[c].next) {
  9662. struct br_node *cn = &doc.nodes[c];
  9663. struct br_style cs;
  9664. int span;
  9665. if (cn->type != BR_NODE_ELEM ||
  9666. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9667. continue;
  9668. span = cn->colspan ? cn->colspan : 1;
  9669. if (col + span > maxcols)
  9670. span = maxcols - col;
  9671. if (span < 1)
  9672. break;
  9673. if (span == 1) {
  9674. br_style_for(&doc, c, pst, &cs);
  9675. if (cs.display != BR_DISPLAY_NONE) {
  9676. if (cs.width_kind == 1) {
  9677. raw[col] = cs.width;
  9678. fixed[col] = 1;
  9679. } else if (cs.width_kind == 2 ||
  9680. cs.width_kind == 3) {
  9681. raw[col] = style_width_px(&cs,
  9682. avail);
  9683. fixed[col] = 1;
  9684. }
  9685. }
  9686. }
  9687. col += span;
  9688. }
  9689. }
  9690. for (c = 0; c < (unsigned int)cols; c++) {
  9691. if (raw[c] < 8)
  9692. raw[c] = 8;
  9693. total += raw[c];
  9694. if (fixed[c])
  9695. fixed_sum += raw[c];
  9696. else {
  9697. free_raw += raw[c];
  9698. free_cols++;
  9699. }
  9700. }
  9701. if (fixed_sum > 0 && fixed_sum < avail) {
  9702. int free_avail = avail - fixed_sum;
  9703. int i;
  9704. if (free_raw > 0) {
  9705. for (i = 0; i < cols; i++)
  9706. if (!fixed[i])
  9707. raw[i] = free_avail * raw[i] /
  9708. free_raw;
  9709. } else if (free_cols > 0) {
  9710. for (i = 0; i < cols; i++)
  9711. if (!fixed[i])
  9712. raw[i] = free_avail / free_cols;
  9713. }
  9714. total = 0;
  9715. for (i = 0; i < cols; i++)
  9716. total += raw[i];
  9717. } else if (total < avail && total > 0) {
  9718. int i;
  9719. for (i = 0; i < cols; i++)
  9720. raw[i] = raw[i] * avail / total;
  9721. total = 0;
  9722. for (i = 0; i < cols; i++)
  9723. total += raw[i];
  9724. }
  9725. *out_cols = cols;
  9726. *out_total = total;
  9727. }
  9728. static void layout_table_row(struct lay *l, unsigned int row,
  9729. const struct br_style *pst, int depth,
  9730. unsigned short link)
  9731. {
  9732. unsigned int n, cell[12];
  9733. int raw[12], colstart[12], colspan[12];
  9734. int prefix[13];
  9735. int ncell = 0, total = 0, cols = 0, col = 0;
  9736. int row_left = l->left, row_right = l->right;
  9737. int avail = row_right - row_left;
  9738. int y = l->y, bottom = l->y;
  9739. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  9740. struct br_node *nd = &doc.nodes[n];
  9741. struct br_style cs;
  9742. int span;
  9743. if (nd->type == BR_NODE_TEXT) {
  9744. if (text_node_blank(nd))
  9745. continue;
  9746. layout_children(l, row, pst, depth, link);
  9747. return;
  9748. }
  9749. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  9750. layout_children(l, row, pst, depth, link);
  9751. return;
  9752. }
  9753. br_style_for(&doc, n, pst, &cs);
  9754. if (cs.display == BR_DISPLAY_NONE)
  9755. continue;
  9756. if (ncell >= 12) {
  9757. layout_children(l, row, pst, depth, link);
  9758. return;
  9759. }
  9760. span = nd->colspan ? nd->colspan : 1;
  9761. if (span > 12 - col)
  9762. span = 12 - col;
  9763. if (span < 1)
  9764. continue;
  9765. cell[ncell] = n;
  9766. colstart[ncell] = col;
  9767. colspan[ncell] = span;
  9768. col += span;
  9769. ncell++;
  9770. }
  9771. if (ncell < 1 || avail < 32) {
  9772. layout_children(l, row, pst, depth, link);
  9773. return;
  9774. }
  9775. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  9776. &total);
  9777. if (cols < 2 || total <= 0) {
  9778. int c;
  9779. total = 0;
  9780. for (c = 0; c < ncell; c++) {
  9781. struct br_style cs;
  9782. br_style_for(&doc, cell[c], pst, &cs);
  9783. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  9784. avail) +
  9785. mp_px(&cs, 7, avail) +
  9786. mp_px(&cs, 5, avail) +
  9787. mp_px(&cs, 3, avail) +
  9788. mp_px(&cs, 1, avail);
  9789. if (raw[c] < 24)
  9790. raw[c] = 24;
  9791. total += raw[c];
  9792. }
  9793. /* A one-column table still has to fill its own width; the
  9794. * intrinsic fallback above otherwise leaves the cell at its
  9795. * text width (HN's outer table and nested story table). */
  9796. if (total > 0 && total < avail) {
  9797. int c;
  9798. for (c = 0; c < ncell; c++)
  9799. raw[c] = raw[c] * avail / total;
  9800. total = avail;
  9801. }
  9802. }
  9803. prefix[0] = row_left;
  9804. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  9805. prefix[n + 1] = prefix[n] + raw[n];
  9806. for (n = 0; n < (unsigned int)ncell; n++) {
  9807. struct br_style cs;
  9808. int start = colstart[n];
  9809. int end = start + colspan[n];
  9810. int w;
  9811. if (end > cols)
  9812. end = cols;
  9813. if (start >= cols)
  9814. continue;
  9815. w = prefix[end] - prefix[start];
  9816. br_style_for(&doc, cell[n], pst, &cs);
  9817. /* The column width already reflects the cell's width property. */
  9818. cs.width_kind = 0;
  9819. cs.max_width_kind = 0;
  9820. if (w < 24)
  9821. w = 24;
  9822. if (w < 8)
  9823. w = 8;
  9824. l->left = prefix[start];
  9825. l->right = l->left + w;
  9826. l->y = y;
  9827. l->line_x = l->left;
  9828. l->run_x = l->left;
  9829. l->line_y = l->y;
  9830. l->line_h = 0;
  9831. l->nruns = 0;
  9832. l->space_pending = 0;
  9833. l->align = cs.align;
  9834. layout_block(l, cell[n], &cs, depth + 1, link);
  9835. if (l->y > bottom)
  9836. bottom = l->y;
  9837. }
  9838. l->left = row_left;
  9839. l->right = row_right;
  9840. l->y = bottom;
  9841. l->line_x = l->left;
  9842. l->run_x = l->left;
  9843. l->line_y = l->y;
  9844. l->line_h = 0;
  9845. l->nruns = 0;
  9846. l->space_pending = 0;
  9847. }
  9848. #define TBL_MAX_ROWS 32
  9849. #define TBL_MAX_COLS 12
  9850. #define TBL_MAX_CELLS 128
  9851. struct tbl_cell {
  9852. unsigned int node;
  9853. unsigned char row, col, rowspan, colspan;
  9854. int height;
  9855. };
  9856. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  9857. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  9858. static int table_active;
  9859. static int table_has_rowspan(unsigned int table)
  9860. {
  9861. unsigned int r, c;
  9862. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9863. struct br_node *rn = &doc.nodes[r];
  9864. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9865. continue;
  9866. for (c = rn->first; c; c = doc.nodes[c].next) {
  9867. struct br_node *cn = &doc.nodes[c];
  9868. if (cn->type == BR_NODE_ELEM &&
  9869. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  9870. cn->rowspan > 1)
  9871. return 1;
  9872. }
  9873. }
  9874. return 0;
  9875. }
  9876. static void table_cell_style(unsigned int row, unsigned int cell,
  9877. const struct br_style *st, struct br_style *out)
  9878. {
  9879. struct br_style trs;
  9880. br_style_for(&doc, row, st, &trs);
  9881. br_style_for(&doc, cell, &trs, out);
  9882. }
  9883. /* Tables that use rowspan need row heights before anything is painted. This
  9884. * path builds a small occupancy grid, measures the natural cell heights, then
  9885. * lays every cell out at its row/column position. Tables without rowspan
  9886. * keep the lighter per-row path in layout_table_row(). */
  9887. static void layout_table(struct lay *l, unsigned int table,
  9888. const struct br_style *st, int depth,
  9889. unsigned short link)
  9890. {
  9891. unsigned int rows[TBL_MAX_ROWS];
  9892. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  9893. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  9894. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  9895. int free_raw = 0, free_cols = 0;
  9896. int table_left = l->left, table_right = l->right;
  9897. int top = l->y, avail = table_right - table_left;
  9898. unsigned int r, c;
  9899. int i, rr, cc;
  9900. if (depth > 48 || table_active) {
  9901. layout_children(l, table, st, depth, link);
  9902. return;
  9903. }
  9904. table_active = 1;
  9905. for (r = doc.nodes[table].first;
  9906. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  9907. struct br_node *rn = &doc.nodes[r];
  9908. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  9909. rows[nrows++] = r;
  9910. }
  9911. if (!nrows) {
  9912. table_active = 0;
  9913. layout_children(l, table, st, depth, link);
  9914. return;
  9915. }
  9916. for (rr = 0; rr < nrows; rr++)
  9917. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  9918. tbl_at[rr][cc] = 0;
  9919. for (rr = 0; rr < nrows; rr++) {
  9920. int col = 0;
  9921. for (c = doc.nodes[rows[rr]].first; c;
  9922. c = doc.nodes[c].next) {
  9923. struct br_node *cn = &doc.nodes[c];
  9924. struct br_style cs;
  9925. int rs, csn;
  9926. if (cn->type != BR_NODE_ELEM ||
  9927. (cn->tag != BR_TAG_TD &&
  9928. cn->tag != BR_TAG_TH))
  9929. continue;
  9930. table_cell_style(rows[rr], c, st, &cs);
  9931. if (cs.display == BR_DISPLAY_NONE)
  9932. continue;
  9933. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  9934. col++;
  9935. if (col >= TBL_MAX_COLS)
  9936. break;
  9937. rs = cn->rowspan ? cn->rowspan : 1;
  9938. csn = cn->colspan ? cn->colspan : 1;
  9939. if (rr + rs > nrows)
  9940. rs = nrows - rr;
  9941. if (col + csn > TBL_MAX_COLS)
  9942. csn = TBL_MAX_COLS - col;
  9943. if (rs < 1 || csn < 1)
  9944. continue;
  9945. if (ncells >= TBL_MAX_CELLS)
  9946. break;
  9947. tbl_cells[ncells].node = c;
  9948. tbl_cells[ncells].row = (unsigned char)rr;
  9949. tbl_cells[ncells].col = (unsigned char)col;
  9950. tbl_cells[ncells].rowspan = (unsigned char)rs;
  9951. tbl_cells[ncells].colspan = (unsigned char)csn;
  9952. tbl_cells[ncells].height = 0;
  9953. for (i = rr; i < rr + rs; i++)
  9954. for (int j = col; j < col + csn; j++)
  9955. tbl_at[i][j] =
  9956. (unsigned short)(ncells + 1);
  9957. ncells++;
  9958. col += csn;
  9959. if (col > cols)
  9960. cols = col;
  9961. }
  9962. }
  9963. if (!ncells || cols < 1) {
  9964. table_active = 0;
  9965. layout_children(l, table, st, depth, link);
  9966. return;
  9967. }
  9968. for (i = 0; i < cols; i++) {
  9969. raw[i] = 0;
  9970. fixed[i] = 0;
  9971. }
  9972. /* Intrinsic widths of single-column cells. */
  9973. for (i = 0; i < ncells; i++) {
  9974. struct br_style cs;
  9975. int w;
  9976. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  9977. st, &cs);
  9978. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  9979. mp_px(&cs, 7, avail) +
  9980. mp_px(&cs, 5, avail) +
  9981. mp_px(&cs, 3, avail) +
  9982. mp_px(&cs, 1, avail) +
  9983. cs.border_w[0] + cs.border_w[1] +
  9984. cs.border_w[2] + cs.border_w[3];
  9985. if (w < 24)
  9986. w = 24;
  9987. if (tbl_cells[i].colspan == 1) {
  9988. int col = tbl_cells[i].col;
  9989. if (w > raw[col])
  9990. raw[col] = w;
  9991. }
  9992. }
  9993. /* A spanning cell only needs the sum of its columns to be large
  9994. * enough; put the deficit in the last column. */
  9995. for (i = 0; i < ncells; i++) {
  9996. struct br_style cs;
  9997. int w, sum, col, span;
  9998. if (tbl_cells[i].colspan < 2)
  9999. continue;
  10000. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10001. st, &cs);
  10002. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10003. mp_px(&cs, 7, avail) +
  10004. mp_px(&cs, 5, avail) +
  10005. mp_px(&cs, 3, avail) +
  10006. mp_px(&cs, 1, avail) +
  10007. cs.border_w[0] + cs.border_w[1] +
  10008. cs.border_w[2] + cs.border_w[3];
  10009. col = tbl_cells[i].col;
  10010. span = tbl_cells[i].colspan;
  10011. sum = 0;
  10012. for (int j = 0; j < span; j++)
  10013. sum += raw[col + j];
  10014. if (w > sum)
  10015. raw[col + span - 1] += w - sum;
  10016. }
  10017. /* Explicit/percentage widths, as in table_columns(). */
  10018. for (i = 0; i < ncells; i++) {
  10019. struct br_style cs;
  10020. int col;
  10021. if (tbl_cells[i].colspan != 1)
  10022. continue;
  10023. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10024. st, &cs);
  10025. col = tbl_cells[i].col;
  10026. if (cs.width_kind == 1) {
  10027. raw[col] = cs.width;
  10028. fixed[col] = 1;
  10029. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  10030. raw[col] = style_width_px(&cs, avail);
  10031. fixed[col] = 1;
  10032. }
  10033. }
  10034. for (i = 0; i < cols; i++) {
  10035. if (raw[i] < 8)
  10036. raw[i] = 8;
  10037. total += raw[i];
  10038. if (fixed[i])
  10039. fixed_sum += raw[i];
  10040. else {
  10041. free_raw += raw[i];
  10042. free_cols++;
  10043. }
  10044. }
  10045. if (fixed_sum > 0 && fixed_sum < avail) {
  10046. int free_avail = avail - fixed_sum;
  10047. if (free_raw > 0) {
  10048. for (i = 0; i < cols; i++)
  10049. if (!fixed[i])
  10050. raw[i] = free_avail * raw[i] /
  10051. free_raw;
  10052. } else if (free_cols > 0) {
  10053. for (i = 0; i < cols; i++)
  10054. if (!fixed[i])
  10055. raw[i] = free_avail / free_cols;
  10056. }
  10057. } else if (total < avail && total > 0) {
  10058. for (i = 0; i < cols; i++)
  10059. raw[i] = raw[i] * avail / total;
  10060. }
  10061. prefix[0] = table_left;
  10062. for (i = 0; i < cols; i++)
  10063. prefix[i + 1] = prefix[i] + raw[i];
  10064. /* Measure natural cell heights with the column widths. */
  10065. for (i = 0; i < ncells; i++) {
  10066. struct br_style cs;
  10067. int col = tbl_cells[i].col;
  10068. int span = tbl_cells[i].colspan;
  10069. int w = prefix[col + span] - prefix[col];
  10070. int sl = l->left, sr = l->right, sy = l->y;
  10071. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10072. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10073. int sal = l->align, sdraw = l->draw;
  10074. struct ngui *sui = l->ui;
  10075. if (w < 8)
  10076. w = 8;
  10077. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10078. st, &cs);
  10079. cs.width_kind = 0;
  10080. cs.max_width_kind = 0;
  10081. l->draw = 0;
  10082. l->ui = 0;
  10083. l->left = prefix[col];
  10084. l->right = l->left + w;
  10085. l->y = 0;
  10086. l->line_x = l->left;
  10087. l->run_x = l->left;
  10088. l->line_y = 0;
  10089. l->line_h = 0;
  10090. l->nruns = 0;
  10091. l->space_pending = 0;
  10092. l->align = cs.align;
  10093. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10094. tbl_cells[i].height = block_h[tbl_cells[i].node];
  10095. l->left = sl;
  10096. l->right = sr;
  10097. l->y = sy;
  10098. l->line_x = slx;
  10099. l->run_x = srx;
  10100. l->line_y = sly;
  10101. l->line_h = slh;
  10102. l->nruns = snr;
  10103. l->space_pending = ssp;
  10104. l->align = sal;
  10105. l->draw = sdraw;
  10106. l->ui = sui;
  10107. }
  10108. for (i = 0; i < nrows; i++)
  10109. rowh[i] = 0;
  10110. for (i = 0; i < ncells; i++) {
  10111. int row = tbl_cells[i].row;
  10112. if (tbl_cells[i].rowspan == 1) {
  10113. if (tbl_cells[i].height > rowh[row])
  10114. rowh[row] = tbl_cells[i].height;
  10115. }
  10116. }
  10117. for (i = 0; i < ncells; i++) {
  10118. int row = tbl_cells[i].row;
  10119. int span = tbl_cells[i].rowspan;
  10120. int sum = 0;
  10121. if (span < 2)
  10122. continue;
  10123. for (int j = 0; j < span; j++)
  10124. sum += rowh[row + j];
  10125. if (sum < tbl_cells[i].height)
  10126. rowh[row + span - 1] +=
  10127. tbl_cells[i].height - sum;
  10128. }
  10129. for (i = 0; i < nrows; i++)
  10130. if (rowh[i] < 8)
  10131. rowh[i] = 8;
  10132. rowy[0] = top;
  10133. for (i = 1; i < nrows; i++)
  10134. rowy[i] = rowy[i - 1] + rowh[i - 1];
  10135. if (!l->draw) {
  10136. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10137. table_active = 0;
  10138. return;
  10139. }
  10140. for (i = 0; i < ncells; i++) {
  10141. struct br_style cs;
  10142. int col = tbl_cells[i].col;
  10143. int span = tbl_cells[i].colspan;
  10144. int row = tbl_cells[i].row;
  10145. int rspan = tbl_cells[i].rowspan;
  10146. int w = prefix[col + span] - prefix[col];
  10147. int h = 0;
  10148. int sl = l->left, sr = l->right, sy = l->y;
  10149. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10150. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10151. int sal = l->align;
  10152. int deco;
  10153. for (int j = 0; j < rspan; j++)
  10154. h += rowh[row + j];
  10155. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  10156. cs.width_kind = 0;
  10157. cs.max_width_kind = 0;
  10158. cs.box_sizing = 0;
  10159. deco = mp_px(&cs, 4, avail) +
  10160. mp_px(&cs, 6, avail) +
  10161. cs.border_w[0] + cs.border_w[2];
  10162. cs.height_kind = 1;
  10163. cs.height = h > deco ? h - deco : 0;
  10164. /* The block painter reads block_h[] from the measure pass; make
  10165. * the table cell fill its row/rowspan, not just its content. */
  10166. if (h > 0 && h < 65536)
  10167. block_h[tbl_cells[i].node] = (unsigned short)h;
  10168. l->left = prefix[col];
  10169. l->right = l->left + w;
  10170. l->y = rowy[row];
  10171. l->line_x = l->left;
  10172. l->run_x = l->left;
  10173. l->line_y = l->y;
  10174. l->line_h = 0;
  10175. l->nruns = 0;
  10176. l->space_pending = 0;
  10177. l->align = cs.align;
  10178. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10179. l->left = sl;
  10180. l->right = sr;
  10181. l->y = sy;
  10182. l->line_x = slx;
  10183. l->run_x = srx;
  10184. l->line_y = sly;
  10185. l->line_h = slh;
  10186. l->nruns = snr;
  10187. l->space_pending = ssp;
  10188. l->align = sal;
  10189. }
  10190. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10191. table_active = 0;
  10192. }
  10193. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  10194. * flow so they sit above it, like CSS painting order. Their flow origin is
  10195. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  10196. struct br_deferred {
  10197. unsigned int node;
  10198. int flow_y, flow_left, flow_right;
  10199. int parent_top; /* the parent box top, for sticky clamping */
  10200. unsigned short link;
  10201. signed short z_index;
  10202. unsigned char z_set;
  10203. unsigned int order;
  10204. };
  10205. /* Positioned boxes painted after the flow. News front pages have one or two
  10206. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  10207. * old 16 entries the rest fell back into the flow, so a hero image landed
  10208. * below its padding-top aspect box instead of on top of it. */
  10209. #define BR_MAX_DEFERRED 256
  10210. static struct br_deferred deferred[BR_MAX_DEFERRED];
  10211. static int ndeferred;
  10212. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  10213. * element's line. A block-level pseudo-element gets its own line; its box
  10214. * (margins, padding, background) is not drawn. */
  10215. static void emit_pseudo(struct lay *l, unsigned int node,
  10216. const struct br_style *st, int pe, unsigned short link)
  10217. {
  10218. char buf[160];
  10219. struct br_style ps;
  10220. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  10221. unsigned int i = 0;
  10222. int block, space_w;
  10223. if (!n)
  10224. return;
  10225. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  10226. if (block)
  10227. flush_line(l);
  10228. if (ps.uppercase)
  10229. for (i = 0; i < n; i++)
  10230. if (buf[i] >= 'a' && buf[i] <= 'z')
  10231. buf[i] = (char)(buf[i] - 'a' + 'A');
  10232. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  10233. if (space_w <= 0)
  10234. space_w = 8;
  10235. i = 0;
  10236. while (i < n) {
  10237. char word[28];
  10238. unsigned int k = 0;
  10239. int w;
  10240. if (buf[i] == ' ') {
  10241. l->space_pending = 1;
  10242. i++;
  10243. continue;
  10244. }
  10245. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  10246. word[k++] = buf[i++];
  10247. word[k] = '\0';
  10248. if (l->space_pending &&
  10249. (l->nruns > 0 || l->line_x > l->line_left) &&
  10250. l->line_x + space_w <= l->line_right)
  10251. l->line_x += space_w;
  10252. l->space_pending = 0;
  10253. w = (int)face_text_width(l->ui, &ps, word, k);
  10254. if (l->line_x + w > l->line_right &&
  10255. (l->nruns > 0 || l->line_x > l->line_left))
  10256. flush_line(l);
  10257. add_run(l, 0, 0, &ps, link, word);
  10258. }
  10259. if (block)
  10260. flush_line(l);
  10261. }
  10262. static void layout_children(struct lay *l, unsigned int parent,
  10263. const struct br_style *pst, int depth,
  10264. unsigned short link)
  10265. {
  10266. unsigned int n;
  10267. if (depth > 48)
  10268. return;
  10269. emit_pseudo(l, parent, pst, 1, link);
  10270. n = doc.nodes[parent].first;
  10271. while (n) {
  10272. struct br_node *nd = &doc.nodes[n];
  10273. struct br_style cs;
  10274. unsigned short lk = link;
  10275. if (nd->type == BR_NODE_TEXT) {
  10276. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  10277. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  10278. n = nd->next;
  10279. continue;
  10280. }
  10281. br_style_for(&doc, n, pst, &cs);
  10282. if (cs.display == BR_DISPLAY_NONE) {
  10283. n = nd->next;
  10284. continue;
  10285. }
  10286. if (cs.clear && l->float_active) {
  10287. flush_line(l);
  10288. if (l->y < l->float_bottom)
  10289. l->y = l->float_bottom;
  10290. l->float_active = 0;
  10291. l->line_x = l->left;
  10292. l->run_x = l->left;
  10293. l->line_left = l->left;
  10294. l->line_right = l->right;
  10295. l->line_y = l->y;
  10296. l->line_h = 0;
  10297. l->nruns = 0;
  10298. l->space_pending = 0;
  10299. }
  10300. if (nd->tag == BR_TAG_A && nd->href_off)
  10301. lk = (unsigned short)n;
  10302. if (cs.pos == 1 || cs.pos == 2 ||
  10303. ((cs.pos == 3 || cs.pos == 4) && cs.z_set)) {
  10304. if ((cs.pos == 3 || cs.pos == 4) && l->draw &&
  10305. ndeferred < BR_MAX_DEFERRED) {
  10306. /* Relative or sticky z-index (a sticky site
  10307. * header): measure and advance the flow without
  10308. * painting, then paint it in the deferred
  10309. * (stacked) pass, above the content after it. */
  10310. int fy = l->y, fl = l->left, fr = l->right;
  10311. int save_draw = l->draw;
  10312. l->draw = 0;
  10313. layout_block(l, n, &cs, depth + 1, lk);
  10314. l->draw = save_draw;
  10315. deferred[ndeferred].node = n;
  10316. deferred[ndeferred].parent_top = l->parent_top;
  10317. deferred[ndeferred].flow_y = fy;
  10318. deferred[ndeferred].flow_left = fl;
  10319. deferred[ndeferred].flow_right = fr;
  10320. deferred[ndeferred].link = lk;
  10321. deferred[ndeferred].z_index = cs.z_index;
  10322. deferred[ndeferred].z_set = cs.z_set;
  10323. deferred[ndeferred].order = (unsigned int)ndeferred;
  10324. ndeferred++;
  10325. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  10326. deferred[ndeferred].node = n;
  10327. deferred[ndeferred].parent_top = l->parent_top;
  10328. deferred[ndeferred].flow_y =
  10329. cs.pos == 1 ? l->cb_top : l->y;
  10330. deferred[ndeferred].flow_left =
  10331. cs.pos == 1 ? l->cb_left : l->left;
  10332. deferred[ndeferred].flow_right =
  10333. cs.pos == 1 ? l->cb_right : l->right;
  10334. deferred[ndeferred].link = lk;
  10335. deferred[ndeferred].z_index = cs.z_index;
  10336. deferred[ndeferred].z_set = cs.z_set;
  10337. deferred[ndeferred].order = (unsigned int)ndeferred;
  10338. ndeferred++;
  10339. } else if (l->draw && cs.pos == 1) {
  10340. /* Deferred list full: paint in place, but still
  10341. * against the containing block, not the flow. */
  10342. int fy = l->y, fl = l->left, fr = l->right;
  10343. l->y = l->cb_top;
  10344. l->left = l->cb_left;
  10345. l->right = l->cb_right;
  10346. layout_block(l, n, &cs, depth + 1, lk);
  10347. l->y = fy;
  10348. l->left = fl;
  10349. l->right = fr;
  10350. } else {
  10351. layout_block(l, n, &cs, depth + 1, lk);
  10352. }
  10353. if (cs.pos == 1 && block_h[n] &&
  10354. doc.nodes[n].class_off) {
  10355. const char *cl = doc.attrs +
  10356. doc.nodes[n].class_off;
  10357. if ((contains_ci(cl, "poster-wrapper") ||
  10358. contains_ci(cl, "ts-picture")) &&
  10359. !has_skeleton_sibling(n))
  10360. l->y += block_h[n];
  10361. }
  10362. n = nd->next;
  10363. continue;
  10364. }
  10365. if (nd->tag == BR_TAG_BR) {
  10366. flush_line(l);
  10367. n = nd->next;
  10368. continue;
  10369. }
  10370. if (nd->tag == BR_TAG_HR) {
  10371. flush_line(l);
  10372. if (l->draw)
  10373. ngui_fill_rect(l->ui,
  10374. (struct ngui_rect){l->left, l->y + 2,
  10375. l->right - l->left, 1}, BR_GRAY);
  10376. l->y += 8;
  10377. n = nd->next;
  10378. continue;
  10379. }
  10380. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  10381. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  10382. !button_has_elements(n)) {
  10383. if (!(nd->tag == BR_TAG_INPUT &&
  10384. s_eq(br_type(&doc, n), "hidden"))) {
  10385. form_fill_line = pst->display ==
  10386. BR_DISPLAY_FLEX &&
  10387. pst->flex_col;
  10388. add_form_run(l, n, &cs, lk);
  10389. form_fill_line = 0;
  10390. }
  10391. n = nd->next;
  10392. continue;
  10393. }
  10394. if (nd->tag == BR_TAG_IMG) {
  10395. add_image_run(l, n, &cs, lk);
  10396. n = nd->next;
  10397. continue;
  10398. }
  10399. if (nd->tag == BR_TAG_SVG &&
  10400. (cs.display == BR_DISPLAY_INLINE ||
  10401. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  10402. !cs.float_left) {
  10403. add_svg_run(l, n, &cs, lk);
  10404. n = nd->next;
  10405. continue;
  10406. }
  10407. if (nd->tag == BR_TAG_VIDEO) {
  10408. layout_block(l, n, &cs, depth + 1, lk);
  10409. n = nd->next;
  10410. continue;
  10411. }
  10412. if (cs.float_left) {
  10413. n = layout_float_group(l, n, pst, depth, lk);
  10414. continue;
  10415. }
  10416. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  10417. inline_block_flows(n, &cs, 0)) {
  10418. layout_children(l, n, &cs, depth + 1, lk);
  10419. n = nd->next;
  10420. continue;
  10421. }
  10422. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  10423. n = layout_inline_blocks(l, n, pst, depth, link);
  10424. continue;
  10425. }
  10426. /* A flex container is block-level like any block box even when
  10427. * the element is an inline tag such as <a> (a link card with
  10428. * display:flex is common on news sites). Without the block box
  10429. * its children were laid out in the parent flow with a 0x0 box
  10430. * of their own. */
  10431. /* inline-flex around inline content only ("| mehr" link
  10432. * tails, icon+label pills) stays in the text line. */
  10433. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  10434. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  10435. !flex_wants_row(n, &cs)) {
  10436. layout_children(l, n, &cs, depth + 1, lk);
  10437. } else if (cs.display == BR_DISPLAY_BLOCK ||
  10438. cs.display == BR_DISPLAY_FLEX ||
  10439. br_tag_is_block(nd->tag))
  10440. layout_block(l, n, &cs, depth + 1, lk);
  10441. else {
  10442. layout_children(l, n, &cs, depth + 1, lk);
  10443. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  10444. l->space_pending = 1;
  10445. }
  10446. n = nd->next;
  10447. }
  10448. emit_pseudo(l, parent, pst, 2, link);
  10449. }
  10450. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  10451. * runs and a recursive page can otherwise overflow the stack. */
  10452. static struct lay layout_state;
  10453. static int measure_page(int left, int right)
  10454. {
  10455. struct lay *l = &layout_state;
  10456. struct br_style base = base_style();
  10457. unsigned int i;
  10458. for (i = 0; i < BR_MAX_NODES; i++) {
  10459. block_h[i] = 0;
  10460. img_top[i] = 0;
  10461. block_top[i] = 0;
  10462. img_h[i] = 0;
  10463. layout_boxes[i].valid = 0;
  10464. }
  10465. memset(li_marker, 0, sizeof(li_marker));
  10466. l->draw = 0;
  10467. l->ui = &ui;
  10468. l->left = left;
  10469. l->right = right;
  10470. l->y = 0;
  10471. l->line_x = left;
  10472. l->run_x = left;
  10473. l->line_left = left;
  10474. l->line_right = right;
  10475. l->line_y = 0;
  10476. l->line_h = 0;
  10477. l->align = BR_ALIGN_LEFT;
  10478. l->cb_h = layout_view_h;
  10479. l->float_active = 0;
  10480. l->parent_top = 0;
  10481. l->cb_left = left;
  10482. l->cb_right = right;
  10483. l->cb_top = 0;
  10484. l->depth = 0;
  10485. l->nruns = 0;
  10486. l->space_pending = 0;
  10487. base = root_style();
  10488. layout_children(l, doc.root, &base, 0, 0);
  10489. return l->y + 8;
  10490. }
  10491. static int deferred_cmp(const struct br_deferred *a,
  10492. const struct br_deferred *b)
  10493. {
  10494. int az = a->z_set ? a->z_index : 0;
  10495. int bz = b->z_set ? b->z_index : 0;
  10496. if (az != bz)
  10497. return az < bz ? -1 : 1;
  10498. if (a->order != b->order)
  10499. return a->order < b->order ? -1 : 1;
  10500. return 0;
  10501. }
  10502. static void sort_deferred(void)
  10503. {
  10504. int i;
  10505. for (i = 1; i < ndeferred; i++) {
  10506. struct br_deferred key = deferred[i];
  10507. int j = i;
  10508. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  10509. deferred[j] = deferred[j - 1];
  10510. j--;
  10511. }
  10512. deferred[j] = key;
  10513. }
  10514. }
  10515. static void render_page(int left, int right, int y0)
  10516. {
  10517. struct lay *l = &layout_state;
  10518. struct br_style base = base_style();
  10519. l->draw = 1;
  10520. l->ui = &ui;
  10521. l->left = left;
  10522. l->right = right;
  10523. l->y = y0;
  10524. l->line_x = left;
  10525. l->run_x = left;
  10526. l->line_left = left;
  10527. l->line_right = right;
  10528. l->line_y = y0;
  10529. l->line_h = 0;
  10530. l->align = BR_ALIGN_LEFT;
  10531. l->cb_h = layout_view_h;
  10532. l->float_active = 0;
  10533. l->parent_top = 0;
  10534. l->cb_left = left;
  10535. l->cb_right = right;
  10536. l->cb_top = y0;
  10537. l->depth = 0;
  10538. l->nruns = 0;
  10539. l->space_pending = 0;
  10540. nhits = 0;
  10541. ndeferred = 0;
  10542. base = root_style();
  10543. layout_children(l, doc.root, &base, 0, 0);
  10544. sort_deferred();
  10545. {
  10546. int i;
  10547. for (i = 0; i < ndeferred; i++) {
  10548. struct br_style st;
  10549. br_style_for(&doc, deferred[i].node, &base, &st);
  10550. if (st.display == BR_DISPLAY_NONE)
  10551. continue;
  10552. l->draw = 1;
  10553. l->left = deferred[i].flow_left;
  10554. l->right = deferred[i].flow_right;
  10555. l->y = deferred[i].flow_y;
  10556. l->parent_top = deferred[i].parent_top;
  10557. l->line_x = l->left;
  10558. l->run_x = l->left;
  10559. l->line_y = l->y;
  10560. l->line_h = 0;
  10561. l->nruns = 0;
  10562. l->space_pending = 0;
  10563. l->align = st.align;
  10564. if (st.pos == 2 && block_h[deferred[i].node]) {
  10565. struct ngui_rect clip;
  10566. int ch = block_h[deferred[i].node] + 24;
  10567. int pr = page_rect.x + page_rect.w - 12;
  10568. int x0 = page_rect.x, x1 = pr;
  10569. /* The background pre-fill spans the box's own
  10570. * columns, not the whole page: Docusaurus parks
  10571. * a white "Skip to main content" link at
  10572. * `left: 100%` with a z-index above the navbar,
  10573. * and a full-width fill painted over the bar. */
  10574. if (st.left_set)
  10575. x0 = page_rect.x + st.left;
  10576. if (st.width_kind == 1) {
  10577. if (st.right_set && !st.left_set)
  10578. x0 = pr - st.right - st.width;
  10579. x1 = x0 + st.width;
  10580. } else if (st.right_set) {
  10581. x1 = pr - st.right;
  10582. }
  10583. if (x0 >= pr || x1 <= page_rect.x)
  10584. continue; /* entirely off-screen */
  10585. if (x0 < page_rect.x)
  10586. x0 = page_rect.x;
  10587. if (x1 > pr)
  10588. x1 = pr;
  10589. clip.x = x0;
  10590. clip.y = page_rect.y;
  10591. clip.w = x1 - x0;
  10592. if (ch > page_rect.h)
  10593. ch = page_rect.h;
  10594. clip.h = ch;
  10595. ngui_push_clip(&ui, clip);
  10596. if (st.has_bg)
  10597. ngui_fill_rect(&ui, clip, st.bg);
  10598. layout_block(l, deferred[i].node, &st, 0,
  10599. deferred[i].link);
  10600. ngui_pop_clip(&ui);
  10601. } else {
  10602. layout_block(l, deferred[i].node, &st, 0,
  10603. deferred[i].link);
  10604. }
  10605. }
  10606. }
  10607. }
  10608. /* ---- UI ---- */
  10609. static int find_hit(int x, int y)
  10610. {
  10611. int i;
  10612. for (i = nhits - 1; i >= 0; i--) {
  10613. struct hit *h = &hits[i];
  10614. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  10615. y < h->y + h->h)
  10616. return (int)h->node;
  10617. }
  10618. return 0;
  10619. }
  10620. /* ---- URL-bar autocomplete ----
  10621. *
  10622. * While the address bar has the focus a dropdown lists up to SUG_MAX
  10623. * history entries. An empty bar (a fresh focus, Ctrl+L) shows the most
  10624. * visited/recent sites; typing ranks prefix matches of the URL (with or
  10625. * without the scheme and "www.") above substring matches of the URL, then
  10626. * of the title, and adds visit count and recency. Typing at the end of the
  10627. * text also completes inline to the next '/' of the best prefix match
  10628. * ("clo" -> "cloudron.io/"), with the added part selected so the next
  10629. * keystroke replaces it; Enter on that text opens the history URL it came
  10630. * from (scheme included). Up/Down preview a row in the bar, Delete on a
  10631. * highlighted row forgets it, Esc closes the list (a second Esc leaves the
  10632. * bar), and a click on a row opens it. */
  10633. #define SUG_MAX 6
  10634. #define SUG_ROW_H 36
  10635. static int sug_idx[SUG_MAX];
  10636. static int sug_n, sug_sel = -1, sug_open;
  10637. static char sug_typed[NGUI_INPUT_MAX]; /* what the user typed */
  10638. static char sug_restore[NGUI_INPUT_MAX]; /* bar text before a preview */
  10639. static char ac_text[NGUI_INPUT_MAX]; /* bar text of the inline completion */
  10640. static char ac_url[HIST_URL_MAX]; /* the history URL it stands for */
  10641. static struct ngui_rect url_rect, sug_rect;
  10642. static int url_had_focus;
  10643. static char lc(char c)
  10644. {
  10645. return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
  10646. }
  10647. static int prefix_ci(const char *s, const char *p) /* p is lower case */
  10648. {
  10649. for (; *p; s++, p++)
  10650. if (lc(*s) != *p)
  10651. return 0;
  10652. return 1;
  10653. }
  10654. static unsigned int url_scheme_len(const char *url)
  10655. {
  10656. if (starts_with(url, "https://"))
  10657. return 8;
  10658. if (starts_with(url, "http://"))
  10659. return 7;
  10660. return 0;
  10661. }
  10662. /* Offset in `url` where the lower-case text `t` matches as a prefix: the
  10663. * whole URL, the URL without its scheme, or without scheme and "www.". */
  10664. static int hist_prefix_at(const char *url, const char *t)
  10665. {
  10666. unsigned int s = url_scheme_len(url);
  10667. if (prefix_ci(url, t))
  10668. return 0;
  10669. if (s && prefix_ci(url + s, t))
  10670. return (int)s;
  10671. if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
  10672. return (int)s + 4;
  10673. return -1;
  10674. }
  10675. static int hist_score(const struct hist_ent *e, const char *t,
  10676. unsigned int next)
  10677. {
  10678. unsigned int age = next - e->stamp;
  10679. int sc, at;
  10680. if (!t[0]) {
  10681. sc = 0;
  10682. } else if ((at = hist_prefix_at(e->url, t)) >= 0) {
  10683. /* Shorter rests first: "cloudron.io/" before its subpages. */
  10684. int rest = (int)s_len(e->url + at);
  10685. sc = 4000 - (rest > 400 ? 400 : rest);
  10686. } else if (contains_ci(e->url, t)) {
  10687. sc = 1000;
  10688. } else if (contains_ci(e->title, t)) {
  10689. sc = 600;
  10690. } else {
  10691. return -1;
  10692. }
  10693. sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
  10694. sc += age >= 500 ? 0 : (int)(500 - age);
  10695. return sc;
  10696. }
  10697. static void sug_lower(char *t, unsigned int cap)
  10698. {
  10699. unsigned int k;
  10700. for (k = 0; sug_typed[k] && k + 1 < cap; k++)
  10701. t[k] = lc(sug_typed[k]);
  10702. t[k] = '\0';
  10703. }
  10704. static void sug_refresh(void)
  10705. {
  10706. char t[NGUI_INPUT_MAX];
  10707. int sc[SUG_MAX], i, j;
  10708. unsigned int next = hist_next_stamp();
  10709. sug_lower(t, sizeof(t));
  10710. sug_n = 0;
  10711. for (i = 0; i < hist_n; i++) {
  10712. int s = hist_score(&hist_tab[i], t, next);
  10713. if (s < 0)
  10714. continue;
  10715. j = sug_n;
  10716. if (j == SUG_MAX) {
  10717. if (sc[SUG_MAX - 1] >= s)
  10718. continue;
  10719. j = SUG_MAX - 1;
  10720. }
  10721. while (j > 0 && sc[j - 1] < s) {
  10722. sc[j] = sc[j - 1];
  10723. sug_idx[j] = sug_idx[j - 1];
  10724. j--;
  10725. }
  10726. sc[j] = s;
  10727. sug_idx[j] = i;
  10728. if (sug_n < SUG_MAX)
  10729. sug_n++;
  10730. }
  10731. if (sug_sel >= sug_n)
  10732. sug_sel = -1;
  10733. }
  10734. /* Complete the typed text inline to the next '/' of the best prefix match. */
  10735. static void sug_inline(void)
  10736. {
  10737. char t[NGUI_INPUT_MAX];
  10738. const char *url, *rest;
  10739. unsigned int L, start, end, hs, tn, n = 0;
  10740. unsigned int next = hist_next_stamp();
  10741. int i, best = -1, best_sc = -1, at = 0;
  10742. sug_lower(t, sizeof(t));
  10743. L = s_len(t);
  10744. if (!L)
  10745. return;
  10746. for (i = 0; i < hist_n; i++) {
  10747. int a = hist_prefix_at(hist_tab[i].url, t), s;
  10748. if (a < 0)
  10749. continue;
  10750. s = hist_score(&hist_tab[i], t, next);
  10751. if (s > best_sc) {
  10752. best_sc = s;
  10753. best = i;
  10754. at = a;
  10755. }
  10756. }
  10757. if (best < 0)
  10758. return;
  10759. url = hist_tab[best].url;
  10760. rest = url + at;
  10761. /* Typing the scheme ("htt") completes past "https://", not to it. */
  10762. hs = at == 0 ? url_scheme_len(url) : 0;
  10763. start = L > hs ? L : hs;
  10764. end = start;
  10765. while (rest[end] && rest[end] != '/')
  10766. end++;
  10767. if (rest[end] == '/')
  10768. end++;
  10769. tn = s_len(sug_typed);
  10770. if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
  10771. return;
  10772. s_append(ac_text, &n, sug_typed, sizeof(ac_text));
  10773. for (; L < end && n + 1 < sizeof(ac_text); L++)
  10774. ac_text[n++] = rest[L];
  10775. ac_text[n] = '\0';
  10776. s_copy(ac_url, url, (unsigned int)at + end + 1);
  10777. ngui_input_set(&url_in, ac_text);
  10778. url_in.anchor = tn; /* select the completed part */
  10779. }
  10780. static void sug_close(void)
  10781. {
  10782. sug_open = 0;
  10783. sug_sel = -1;
  10784. ac_text[0] = '\0';
  10785. }
  10786. static int sug_visible(void)
  10787. {
  10788. return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
  10789. }
  10790. /* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
  10791. * start page) lists the top sites until something is typed. */
  10792. static int sug_focus_check(void)
  10793. {
  10794. int focused = ngui_focus(&ui) == ID_URL;
  10795. if (focused && !url_had_focus) {
  10796. sug_typed[0] = '\0';
  10797. sug_close();
  10798. sug_open = 1;
  10799. sug_refresh();
  10800. }
  10801. url_had_focus = focused;
  10802. return focused;
  10803. }
  10804. static void url_submit(unsigned int *action)
  10805. {
  10806. if (ac_text[0] && s_eq(url_in.text, ac_text))
  10807. s_copy(click_url, ac_url, sizeof(click_url));
  10808. *action |= ACT_NAV;
  10809. sug_close();
  10810. }
  10811. /* The bar text changed through typing or editing. */
  10812. static void sug_changed(void)
  10813. {
  10814. unsigned int pl = s_len(sug_typed);
  10815. int grew = url_in.len > pl && url_in.cursor == url_in.len &&
  10816. !memcmp(url_in.text, sug_typed, pl);
  10817. s_copy(sug_typed, url_in.text, sizeof(sug_typed));
  10818. ac_text[0] = '\0';
  10819. sug_sel = -1;
  10820. sug_open = 1;
  10821. sug_refresh();
  10822. if (grew)
  10823. sug_inline();
  10824. }
  10825. /* Keys for the list, taken off the queue before the text field sees them.
  10826. * Only a leading run is handled; the rest goes to the field. */
  10827. static void sug_keys(void)
  10828. {
  10829. int k;
  10830. while ((k = ngui_key_peek(&ui)) != 0) {
  10831. if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
  10832. ngui_key(&ui);
  10833. if (!sug_open) {
  10834. sug_open = 1;
  10835. continue;
  10836. }
  10837. if (sug_sel < 0)
  10838. s_copy(sug_restore, url_in.text,
  10839. sizeof(sug_restore));
  10840. if (k == NGUI_KEY_DOWN)
  10841. sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
  10842. else
  10843. sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
  10844. ngui_input_set(&url_in, sug_sel >= 0 ?
  10845. hist_tab[sug_idx[sug_sel]].url :
  10846. sug_restore);
  10847. } else if (k == NGUI_KEY_ESC && sug_visible()) {
  10848. ngui_key(&ui);
  10849. if (sug_sel >= 0)
  10850. ngui_input_set(&url_in, sug_restore);
  10851. else if (ac_text[0] && s_eq(url_in.text, ac_text))
  10852. ngui_input_set(&url_in, sug_typed);
  10853. sug_close();
  10854. } else if (k == NGUI_KEY_DELETE && sug_visible() &&
  10855. sug_sel >= 0) {
  10856. ngui_key(&ui);
  10857. hist_forget(sug_idx[sug_sel]);
  10858. ngui_input_set(&url_in, sug_restore);
  10859. sug_sel = -1;
  10860. sug_refresh();
  10861. } else {
  10862. break;
  10863. }
  10864. }
  10865. }
  10866. /* A press on a row of last frame's list opens it; any press on the list is
  10867. * swallowed so the page underneath does not see it. */
  10868. static void sug_click(unsigned int *action)
  10869. {
  10870. int row;
  10871. if (!(ui.pressed & 1) || !sug_rect.w ||
  10872. !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
  10873. return;
  10874. row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
  10875. if (row >= 0 && row < sug_n) {
  10876. s_copy(click_url, hist_tab[sug_idx[row]].url,
  10877. sizeof(click_url));
  10878. *action |= ACT_NAV;
  10879. sug_close();
  10880. }
  10881. ui.pressed = 0;
  10882. }
  10883. static void draw_suggest(struct ngui_rect page)
  10884. {
  10885. struct ngui_rect r;
  10886. int i, rows = sug_n, hover = -1;
  10887. r.x = url_rect.x;
  10888. r.y = url_rect.y + url_rect.h + 1;
  10889. r.w = url_rect.w < 320 ? 320 : url_rect.w;
  10890. if (r.x + r.w > ui.w - 2)
  10891. r.w = ui.w - 2 - r.x;
  10892. while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
  10893. rows--;
  10894. if (rows <= 0 || r.w < 60) {
  10895. sug_rect.w = 0;
  10896. return;
  10897. }
  10898. r.h = rows * SUG_ROW_H + 2;
  10899. sug_rect = r;
  10900. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  10901. hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
  10902. }
  10903. ngui_fill_rect(&ui, r, ui.theme.border);
  10904. for (i = 0; i < rows; i++) {
  10905. const struct hist_ent *e = &hist_tab[sug_idx[i]];
  10906. struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
  10907. r.w - 2, SUG_ROW_H};
  10908. struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
  10909. unsigned short bg = i == sug_sel ? ui.theme.selection :
  10910. i == hover ? ui.theme.panel_alt :
  10911. ui.theme.panel;
  10912. ngui_fill_rect(&ui, rr, bg);
  10913. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
  10914. e->title[0] ? e->title : e->url,
  10915. ui.theme.text);
  10916. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
  10917. i == sug_sel ? ui.theme.text :
  10918. ui.theme.text_dim);
  10919. }
  10920. }
  10921. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  10922. {
  10923. int x = r.x + 4, y = r.y + 4, h = 22;
  10924. int compact = r.w < 560;
  10925. int go_w = r.w < 420 ? 32 : 42;
  10926. int in_x, in_w, res;
  10927. ngui_fill_rect(&ui, r, ui.theme.panel);
  10928. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  10929. ui.theme.border);
  10930. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  10931. NGUI_ICON_CHEVRON_LEFT))
  10932. *action |= ACT_BACK;
  10933. x += 32;
  10934. if (!compact) {
  10935. if (ngui_icon_button(&ui, ID_FORWARD,
  10936. (struct ngui_rect){x, y, 28, h},
  10937. NGUI_ICON_CHEVRON_RIGHT))
  10938. *action |= ACT_FORWARD;
  10939. x += 32;
  10940. }
  10941. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  10942. NGUI_ICON_REFRESH))
  10943. *action |= ACT_RELOAD;
  10944. x += 32;
  10945. if (!compact) {
  10946. if (ngui_icon_button(&ui, ID_HOME,
  10947. (struct ngui_rect){x, y, 28, h},
  10948. NGUI_ICON_HOME))
  10949. *action |= ACT_HOME;
  10950. x += 32;
  10951. }
  10952. in_x = x + 2;
  10953. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  10954. if (in_w < 60)
  10955. in_w = 60;
  10956. url_rect = (struct ngui_rect){in_x, y, in_w, h};
  10957. if (sug_focus_check())
  10958. sug_keys();
  10959. res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
  10960. sug_focus_check(); /* a click into the bar focuses it here */
  10961. if (res & NGUI_INPUT_CHANGED)
  10962. sug_changed();
  10963. if (res & NGUI_INPUT_SUBMIT)
  10964. url_submit(action);
  10965. if (res & NGUI_INPUT_CANCEL)
  10966. ngui_set_focus(&ui, 0);
  10967. if (ngui_button(&ui, ID_GO,
  10968. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  10969. "Go"))
  10970. url_submit(action);
  10971. if (!sug_focus_check())
  10972. sug_close();
  10973. }
  10974. static int page_hover_node(void)
  10975. {
  10976. if (!ui.inside)
  10977. return 0;
  10978. if (ui.mouse_x < page_rect.x ||
  10979. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  10980. ui.mouse_y < page_rect.y ||
  10981. ui.mouse_y >= page_rect.y + page_rect.h)
  10982. return 0;
  10983. return find_hit(ui.mouse_x, ui.mouse_y);
  10984. }
  10985. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  10986. {
  10987. int x, y, w = page.w, h = page.h;
  10988. if (!src || w <= 0 || h <= 0)
  10989. return;
  10990. for (y = 0; y < h; y++) {
  10991. unsigned short *s = src + (page.y + y) * sw + page.x;
  10992. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  10993. for (x = 0; x + 1 < w; x += 2) {
  10994. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  10995. }
  10996. if (x < w)
  10997. d[x] = s[x];
  10998. }
  10999. }
  11000. static void draw_page(struct ngui_rect page)
  11001. {
  11002. int left, right, ch;
  11003. int old_panel, old_dim;
  11004. unsigned short *saved_px;
  11005. unsigned short page_bg = ui.theme.bg;
  11006. int saved_w, saved_h, use_buf;
  11007. unsigned int t0 = u_ticks_ms();
  11008. page_rect = page;
  11009. {
  11010. unsigned int root = doc.nnode > 1 ?
  11011. br_find_tag(&doc, BR_TAG_HTML) : 0;
  11012. unsigned int body = doc.nnode > 1 ?
  11013. br_find_tag(&doc, BR_TAG_BODY) : 0;
  11014. struct br_style bs;
  11015. int bg_found = 0;
  11016. if (root) {
  11017. style_for_node(root - 1, &bs);
  11018. if (bs.has_bg) {
  11019. page_bg = bs.bg;
  11020. bg_found = 1;
  11021. }
  11022. }
  11023. if (body) {
  11024. style_for_node(body - 1, &bs);
  11025. if (bs.has_bg) {
  11026. page_bg = bs.bg;
  11027. bg_found = 1;
  11028. }
  11029. }
  11030. /* No canvas colour, but the author made the text dark
  11031. * (Infima's light theme: `--ifm-background-color:
  11032. * transparent` on html, #1c1e21 text): the page expects the
  11033. * white canvas of a normal browser, and dark text on the
  11034. * dark default canvas is unreadable. */
  11035. if (!bg_found && (body || root) && bs.color != ui.theme.text) {
  11036. unsigned int c = bs.color;
  11037. unsigned int lum = ((c >> 11) & 31) * 8 * 299 +
  11038. ((c >> 5) & 63) * 4 * 587 +
  11039. (c & 31) * 8 * 114;
  11040. if (lum < 100 * 1000)
  11041. page_bg = 0xFFFF;
  11042. }
  11043. }
  11044. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  11045. page_cache_valid && layout_valid &&
  11046. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  11047. !(ui.scroll_y &&
  11048. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  11049. page_scroll.offset == page_cache_scroll &&
  11050. page_cache_nnode == doc.nnode &&
  11051. page_cache_x == page.x && page_cache_y == page.y &&
  11052. page_cache_w == page.w && page_cache_h == page.h) {
  11053. blit_page(page, page_backbuf, pagebuf_w);
  11054. if (img_stat_n)
  11055. img_stat_paint += u_ticks_ms() - t0;
  11056. return;
  11057. }
  11058. ngui_fill_rect(&ui, page, page_bg);
  11059. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  11060. const char *s = page_loading ? "Loading..." : "No page";
  11061. int w = (int)ngui_text_width_ui(&ui, s);
  11062. ngui_text(&ui, page.x + (page.w - w) / 2,
  11063. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  11064. page_scroll.content_h = 0;
  11065. page_scroll.view_h = page.h;
  11066. page_cache_valid = 0;
  11067. return;
  11068. }
  11069. if (page.w < 40 || page.h < 40) {
  11070. page_cache_valid = 0;
  11071. return;
  11072. }
  11073. saved_px = ui.px;
  11074. saved_w = ui.w;
  11075. saved_h = ui.h;
  11076. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  11077. if (use_buf) {
  11078. ui.px = page_backbuf;
  11079. ui.w = pagebuf_w;
  11080. ui.h = pagebuf_h;
  11081. ngui_fill_rect(&ui, page, page_bg);
  11082. }
  11083. left = page.x + 8;
  11084. right = page.x + page.w - 16;
  11085. if (!layout_valid || left != layout_left || right != layout_right ||
  11086. layout_nnode != doc.nnode) {
  11087. unsigned int tm = u_ticks_ms();
  11088. layout_view_h = page.h - 8;
  11089. layout_content_h = measure_page(left, right);
  11090. if (img_stat_n)
  11091. img_stat_reflow += u_ticks_ms() - tm;
  11092. layout_valid = 1;
  11093. layout_left = left;
  11094. layout_right = right;
  11095. layout_nnode = doc.nnode;
  11096. /* Scripts that measured before any layout (offsetWidth on
  11097. * mount) get a resize event once real boxes exist, and again
  11098. * whenever the page width changes. */
  11099. if (js_browser_active() && right - left != resize_sent_w)
  11100. resize_pending = 1;
  11101. }
  11102. ch = layout_content_h;
  11103. page_scroll.content_h = ch;
  11104. page_scroll.view_h = page.h;
  11105. t0 = u_ticks_ms();
  11106. ngui_scroll_begin(&ui, page, &page_scroll);
  11107. ngui_scroll_wheel(&ui, page, &page_scroll);
  11108. render_page(left, right, page.y + 4 - page_scroll.offset);
  11109. old_panel = ui.theme.panel_alt;
  11110. old_dim = ui.theme.text_dim;
  11111. ui.theme.panel_alt = 0xC618;
  11112. ui.theme.text_dim = 0x8410;
  11113. ngui_scroll_end(&ui, page, &page_scroll);
  11114. ui.theme.panel_alt = old_panel;
  11115. ui.theme.text_dim = old_dim;
  11116. if (use_buf) {
  11117. ui.px = saved_px;
  11118. ui.w = saved_w;
  11119. ui.h = saved_h;
  11120. blit_page(page, page_backbuf, pagebuf_w);
  11121. page_cache_valid = 1;
  11122. page_cache_scroll = page_scroll.offset;
  11123. page_cache_nnode = doc.nnode;
  11124. page_cache_x = page.x;
  11125. page_cache_y = page.y;
  11126. page_cache_w = page.w;
  11127. page_cache_h = page.h;
  11128. } else {
  11129. page_cache_valid = 0;
  11130. }
  11131. if (img_stat_n)
  11132. img_stat_paint += u_ticks_ms() - t0;
  11133. }
  11134. static void draw_status(struct ngui_rect r)
  11135. {
  11136. static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
  11137. unsigned int n = 0;
  11138. int hover = page_hover_node();
  11139. unsigned short color;
  11140. const char *kind;
  11141. ngui_fill_rect(&ui, r, ui.theme.panel);
  11142. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  11143. ui.theme.border);
  11144. if (hover) {
  11145. const char *href = br_href(&doc, (unsigned int)hover);
  11146. char url[BR_URL_MAX];
  11147. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  11148. s_append(msg, &n, "Link: ", sizeof(msg));
  11149. s_append(msg, &n, url, sizeof(msg));
  11150. } else {
  11151. s_copy(msg, "Link", sizeof(msg));
  11152. }
  11153. color = ui.theme.accent;
  11154. } else if (status_text[0]) {
  11155. s_copy(msg, status_text, sizeof(msg));
  11156. color = status_error ? ui.theme.error : ui.theme.text;
  11157. } else if (page_title[0]) {
  11158. s_copy(msg, page_title, sizeof(msg));
  11159. color = ui.theme.text;
  11160. } else {
  11161. s_copy(msg, "Ready", sizeof(msg));
  11162. color = ui.theme.text_dim;
  11163. }
  11164. kind = s_eq(page_url, "about:home") ? "HOME" :
  11165. page_is_local ? "FILE" :
  11166. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  11167. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  11168. {
  11169. int kw = (int)ngui_text_width_ui(&ui, kind);
  11170. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  11171. ui.theme.text_dim);
  11172. }
  11173. }
  11174. /* Mouse cursor over the page: the hovered node's CSS `cursor` (inherited);
  11175. * for `auto`, a hand over links, the I-beam over text fields, and the
  11176. * progress arrow anywhere on the page while it is still loading. The
  11177. * toolbar's URL field sets its own I-beam through ngui. */
  11178. static void page_cursor(void)
  11179. {
  11180. int hover = page_hover_node();
  11181. struct br_style st;
  11182. if (!hover) {
  11183. if (page_loading && ui.inside &&
  11184. ngui_rect_contains(&page_rect, ui.mouse_x, ui.mouse_y))
  11185. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  11186. return;
  11187. }
  11188. style_for_node((unsigned int)hover, &st);
  11189. if (st.cursor != BR_CURSOR_AUTO) {
  11190. ngui_set_cursor(&ui, (int)st.cursor - 1);
  11191. return;
  11192. }
  11193. if (br_href(&doc, (unsigned int)hover)) {
  11194. ngui_set_cursor(&ui, CURSOR_POINTER);
  11195. return;
  11196. }
  11197. if (form_is_control((unsigned int)hover)) {
  11198. int k = form_kind_of((unsigned int)hover);
  11199. if (form_disabled((unsigned int)hover))
  11200. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  11201. else if (k == FORM_TEXT || k == FORM_PASSWORD ||
  11202. k == FORM_TEXTAREA)
  11203. ngui_set_cursor(&ui, CURSOR_TEXT);
  11204. return;
  11205. }
  11206. if (page_loading)
  11207. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  11208. }
  11209. static void draw(unsigned int *action)
  11210. {
  11211. struct ngui_rect r = {0, 0, ui.w, ui.h};
  11212. struct ngui_rect toolbar, status, page;
  11213. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  11214. status = ngui_cut_bottom(&r, BR_STATUS_H);
  11215. page = r;
  11216. if (sug_visible())
  11217. sug_click(action);
  11218. draw_toolbar(toolbar, action);
  11219. draw_page(page);
  11220. draw_status(status);
  11221. page_cursor();
  11222. if (sug_visible())
  11223. draw_suggest(page);
  11224. else
  11225. sug_rect.w = 0;
  11226. }
  11227. static void redraw_now(void)
  11228. {
  11229. unsigned int action = 0;
  11230. ngui_begin(&ui);
  11231. draw(&action);
  11232. ngui_end(&ui);
  11233. }
  11234. static void handle_keys(unsigned int *action)
  11235. {
  11236. int k, scrolled = 0;
  11237. if (form_focus >= doc.nnode)
  11238. form_focus = 0;
  11239. if (form_focus && !ngui_focus(&ui)) {
  11240. while ((k = ngui_key(&ui)) != 0)
  11241. form_key(k);
  11242. return;
  11243. }
  11244. /* Batch queued page keys: a slow full-page render must not make a
  11245. * held Page Down advance only once every few frames. */
  11246. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  11247. scrolled++;
  11248. if (scrolled)
  11249. ngui_invalidate(&ui);
  11250. if (ngui_focus(&ui))
  11251. return;
  11252. while ((k = ngui_key(&ui)) != 0) {
  11253. switch (k) {
  11254. case NGUI_KEY_ESC:
  11255. *action |= ACT_CLOSE;
  11256. break;
  11257. case NGUI_KEY_TAB:
  11258. case 0x0C: /* Ctrl+L */
  11259. ngui_set_focus(&ui, ID_URL);
  11260. break;
  11261. case 0x12: /* Ctrl+R */
  11262. *action |= ACT_RELOAD;
  11263. break;
  11264. case NGUI_KEY_BACKSPACE:
  11265. *action |= ACT_BACK;
  11266. break;
  11267. case NGUI_KEY_UP:
  11268. ngui_scroll_to(&page_scroll,
  11269. page_scroll.offset - 24);
  11270. ngui_invalidate(&ui);
  11271. break;
  11272. case NGUI_KEY_DOWN:
  11273. ngui_scroll_to(&page_scroll,
  11274. page_scroll.offset + 24);
  11275. ngui_invalidate(&ui);
  11276. break;
  11277. case NGUI_KEY_HOME:
  11278. ngui_scroll_to(&page_scroll, 0);
  11279. ngui_invalidate(&ui);
  11280. break;
  11281. case NGUI_KEY_END:
  11282. ngui_scroll_to(&page_scroll,
  11283. page_scroll.content_h -
  11284. page_scroll.view_h);
  11285. ngui_invalidate(&ui);
  11286. break;
  11287. default:
  11288. break;
  11289. }
  11290. }
  11291. }
  11292. static unsigned int form_ancestor(unsigned int node)
  11293. {
  11294. unsigned int p = node;
  11295. while (p && p < doc.nnode) {
  11296. if (doc.nodes[p].tag == BR_TAG_FORM &&
  11297. doc.nodes[p].type == BR_NODE_ELEM)
  11298. return p;
  11299. p = doc.nodes[p].parent;
  11300. }
  11301. return 0;
  11302. }
  11303. static int form_descendant(unsigned int node, unsigned int form)
  11304. {
  11305. unsigned int p = node;
  11306. while (p && p < doc.nnode) {
  11307. if (p == form)
  11308. return 1;
  11309. p = doc.nodes[p].parent;
  11310. }
  11311. return 0;
  11312. }
  11313. static void form_reset_form(unsigned int form)
  11314. {
  11315. unsigned int i;
  11316. for (i = 0; i < FORM_MAX; i++)
  11317. if (form_states[i].used &&
  11318. form_descendant(form_states[i].node, form))
  11319. form_states[i].used = 0;
  11320. form_focus = 0;
  11321. }
  11322. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  11323. const char *s)
  11324. {
  11325. static const char hex[] = "0123456789ABCDEF";
  11326. while (s && *s && *n + 1 < cap) {
  11327. unsigned char c = (unsigned char)*s++;
  11328. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  11329. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  11330. c == '.' || c == '~') {
  11331. dst[(*n)++] = (char)c;
  11332. } else if (c == ' ') {
  11333. dst[(*n)++] = '+';
  11334. } else if (*n + 3 < cap) {
  11335. dst[(*n)++] = '%';
  11336. dst[(*n)++] = hex[c >> 4];
  11337. dst[(*n)++] = hex[c & 15];
  11338. }
  11339. }
  11340. dst[*n] = '\0';
  11341. }
  11342. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  11343. const char *name, const char *value, int *first)
  11344. {
  11345. if (!name || !name[0])
  11346. return;
  11347. if (!*first && *n + 1 < cap)
  11348. dst[(*n)++] = '&';
  11349. *first = 0;
  11350. form_url_append(dst, n, cap, name);
  11351. if (*n + 1 < cap)
  11352. dst[(*n)++] = '=';
  11353. form_url_append(dst, n, cap, value ? value : "");
  11354. dst[*n] = '\0';
  11355. }
  11356. static int form_submit_form(unsigned int node, int fire_event)
  11357. {
  11358. unsigned int form = form_ancestor(node);
  11359. char action[BR_URL_MAX], query[2048];
  11360. unsigned int qn = 0, i;
  11361. int first = 1, is_post = 0;
  11362. const char *a, *method;
  11363. if (!form)
  11364. return 0;
  11365. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  11366. return 0;
  11367. method = br_find_attr(&doc, form, "method");
  11368. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  11369. is_post = 1;
  11370. a = br_find_attr(&doc, form, "action");
  11371. if (a && a[0]) {
  11372. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  11373. return 0;
  11374. } else {
  11375. s_copy(action, page_url, sizeof(action));
  11376. }
  11377. query[0] = '\0';
  11378. for (i = 0; i < doc.nnode; i++) {
  11379. struct br_node *nd = &doc.nodes[i];
  11380. struct form_state *fs;
  11381. const char *name;
  11382. const char *value = "";
  11383. if (nd->type != BR_NODE_ELEM || i == form ||
  11384. !form_descendant(i, form))
  11385. continue;
  11386. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  11387. nd->tag != BR_TAG_SELECT)
  11388. continue;
  11389. if (form_disabled(i))
  11390. continue;
  11391. name = br_find_attr(&doc, i, "name");
  11392. if (!name || !name[0])
  11393. continue;
  11394. fs = form_get(i, 1);
  11395. if (!fs)
  11396. continue;
  11397. if (nd->tag == BR_TAG_SELECT) {
  11398. char opt[64];
  11399. if (!form_option_text(i, fs->selected, opt,
  11400. sizeof(opt)))
  11401. s_copy(opt, "", sizeof(opt));
  11402. value = opt;
  11403. {
  11404. unsigned int c, oi = 0;
  11405. for (c = nd->first; c;
  11406. c = doc.nodes[c].next) {
  11407. if (doc.nodes[c].type != BR_NODE_ELEM ||
  11408. doc.nodes[c].tag != BR_TAG_OPTION)
  11409. continue;
  11410. if (oi == fs->selected) {
  11411. const char *v =
  11412. br_value(&doc, c);
  11413. if (v && v[0])
  11414. value = v;
  11415. break;
  11416. }
  11417. oi++;
  11418. }
  11419. }
  11420. } else if (nd->tag == BR_TAG_INPUT) {
  11421. int kind = form_kind_of(i);
  11422. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  11423. if (!fs->checked)
  11424. continue;
  11425. value = br_value(&doc, i);
  11426. if (!value || !value[0])
  11427. value = "on";
  11428. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  11429. kind == FORM_BUTTON) {
  11430. if (i != node)
  11431. continue;
  11432. value = fs->value;
  11433. } else {
  11434. value = fs->value;
  11435. }
  11436. } else {
  11437. value = fs->value;
  11438. }
  11439. form_add_param(query, &qn, sizeof(query), name, value, &first);
  11440. }
  11441. if (is_post) {
  11442. if (action[0] == '/') {
  11443. set_status("POST forms need an HTTP action URL", 1, 4000);
  11444. ngui_invalidate(&ui);
  11445. return 0;
  11446. }
  11447. if (qn >= sizeof(pending_post))
  11448. qn = sizeof(pending_post) - 1;
  11449. if (qn)
  11450. memcpy(pending_post, query, qn);
  11451. pending_post[qn] = '\0';
  11452. pending_post_len = qn;
  11453. pending_post_is = 1;
  11454. } else {
  11455. pending_post_len = 0;
  11456. pending_post_is = 0;
  11457. if (qn) {
  11458. unsigned int an = s_len(action);
  11459. if (an + qn + 2 < sizeof(action)) {
  11460. action[an++] = strchr(action, '?') ? '&' : '?';
  11461. action[an] = '\0';
  11462. s_copy(action + an, query,
  11463. sizeof(action) - an);
  11464. }
  11465. }
  11466. }
  11467. s_copy(pending_url, action, sizeof(pending_url));
  11468. pending_action |= ACT_NAV;
  11469. cancel_fetch = 1;
  11470. ngui_invalidate(&ui);
  11471. return 1;
  11472. }
  11473. static void form_reset_event(unsigned int form)
  11474. {
  11475. if (form && !js_browser_event(form, "reset", 1, 1))
  11476. return;
  11477. if (form)
  11478. form_reset_form(form);
  11479. else
  11480. form_reset_state();
  11481. form_dirty = 0;
  11482. layout_valid = 0;
  11483. ngui_invalidate(&ui);
  11484. }
  11485. static void form_blur(void)
  11486. {
  11487. unsigned int node = form_focus;
  11488. form_focus = 0;
  11489. if (node && form_dirty) {
  11490. form_dirty = 0;
  11491. js_browser_event(node, "change", 1, 0);
  11492. }
  11493. }
  11494. static void form_click(unsigned int node)
  11495. {
  11496. struct form_state *fs;
  11497. int kind, changed = 0;
  11498. if (!form_is_control(node) || form_disabled(node))
  11499. return;
  11500. if (form_focus != node)
  11501. form_blur();
  11502. if (!js_browser_event(node, "click", 1, 1))
  11503. return;
  11504. fs = form_get(node, 1);
  11505. if (!fs)
  11506. return;
  11507. kind = form_kind_of(node);
  11508. form_focus = node;
  11509. form_dirty = 0;
  11510. if (kind == FORM_CHECKBOX) {
  11511. fs->checked = !fs->checked;
  11512. changed = 1;
  11513. } else if (kind == FORM_RADIO) {
  11514. const char *name = br_find_attr(&doc, node, "name");
  11515. unsigned int i;
  11516. fs->checked = 1;
  11517. changed = 1;
  11518. if (name) {
  11519. for (i = 0; i < FORM_MAX; i++) {
  11520. struct form_state *o = &form_states[i];
  11521. if (!o->used || o->node == node)
  11522. continue;
  11523. if (form_kind_of(o->node) == FORM_RADIO) {
  11524. const char *on = br_find_attr(&doc,
  11525. o->node,
  11526. "name");
  11527. if (on && s_eq(on, name))
  11528. o->checked = 0;
  11529. }
  11530. }
  11531. }
  11532. } else if (kind == FORM_SELECT) {
  11533. unsigned int n = form_option_count(node);
  11534. if (n) {
  11535. fs->selected = (unsigned char)
  11536. ((fs->selected + 1) % n);
  11537. changed = 1;
  11538. }
  11539. } else if (kind == FORM_SUBMIT) {
  11540. form_submit_form(node, 1);
  11541. return;
  11542. } else if (kind == FORM_RESET) {
  11543. form_reset_event(form_ancestor(node));
  11544. return;
  11545. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  11546. kind == FORM_TEXTAREA) {
  11547. fs->caret = fs->len;
  11548. }
  11549. if (changed) {
  11550. js_browser_event(node, "input", 1, 0);
  11551. js_browser_event(node, "change", 1, 0);
  11552. }
  11553. layout_valid = 0;
  11554. ngui_invalidate(&ui);
  11555. }
  11556. static void form_focus_next(void)
  11557. {
  11558. unsigned int start = form_focus ? form_focus + 1 : 0;
  11559. unsigned int i;
  11560. form_blur();
  11561. for (i = start; i < doc.nnode; i++) {
  11562. if (form_is_control(i) && !form_disabled(i) &&
  11563. !s_eq(br_type(&doc, i), "hidden")) {
  11564. form_focus = i;
  11565. layout_valid = 0;
  11566. ngui_invalidate(&ui);
  11567. return;
  11568. }
  11569. }
  11570. form_focus = 0;
  11571. layout_valid = 0;
  11572. ngui_invalidate(&ui);
  11573. }
  11574. static void form_key(int k)
  11575. {
  11576. struct form_state *fs;
  11577. int kind;
  11578. if (!form_focus || form_focus >= doc.nnode) {
  11579. form_focus = 0;
  11580. return;
  11581. }
  11582. fs = form_get(form_focus, 1);
  11583. if (!fs || form_disabled(form_focus))
  11584. return;
  11585. kind = form_kind_of(form_focus);
  11586. if (kind == FORM_SELECT) {
  11587. unsigned int n = form_option_count(form_focus);
  11588. int changed = 0;
  11589. if (k == NGUI_KEY_UP && n) {
  11590. fs->selected = (unsigned char)
  11591. ((fs->selected + n - 1) % n);
  11592. changed = 1;
  11593. } else if (k == NGUI_KEY_DOWN && n) {
  11594. fs->selected = (unsigned char)
  11595. ((fs->selected + 1) % n);
  11596. changed = 1;
  11597. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  11598. form_blur();
  11599. layout_valid = 0;
  11600. ngui_invalidate(&ui);
  11601. return;
  11602. } else {
  11603. return;
  11604. }
  11605. if (changed) {
  11606. js_browser_event(form_focus, "input", 1, 0);
  11607. js_browser_event(form_focus, "change", 1, 0);
  11608. }
  11609. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  11610. if (k == ' ') {
  11611. form_click(form_focus);
  11612. return;
  11613. }
  11614. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  11615. form_blur();
  11616. layout_valid = 0;
  11617. ngui_invalidate(&ui);
  11618. }
  11619. return;
  11620. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  11621. kind == FORM_RESET) {
  11622. if (k == NGUI_KEY_ESC) {
  11623. form_blur();
  11624. layout_valid = 0;
  11625. ngui_invalidate(&ui);
  11626. } else if (k == '\r' || k == '\n' || k == ' ') {
  11627. form_click(form_focus);
  11628. }
  11629. return;
  11630. } else if (k == NGUI_KEY_TAB) {
  11631. form_focus_next();
  11632. return;
  11633. } else if (k == NGUI_KEY_ESC) {
  11634. form_blur();
  11635. layout_valid = 0;
  11636. ngui_invalidate(&ui);
  11637. return;
  11638. } else if (k == '\r' || k == '\n') {
  11639. unsigned int node = form_focus;
  11640. form_blur();
  11641. if (form_ancestor(node))
  11642. form_submit_form(node, 1);
  11643. layout_valid = 0;
  11644. ngui_invalidate(&ui);
  11645. return;
  11646. } else if (k == NGUI_KEY_BACKSPACE) {
  11647. if (fs->caret) {
  11648. unsigned int i = --fs->caret;
  11649. for (; i < fs->len; i++)
  11650. fs->value[i] = fs->value[i + 1];
  11651. if (fs->len)
  11652. fs->len--;
  11653. form_dirty = 1;
  11654. js_browser_event(form_focus, "input", 1, 0);
  11655. }
  11656. } else if (k == NGUI_KEY_DELETE) {
  11657. if (fs->caret < fs->len) {
  11658. unsigned int i;
  11659. for (i = fs->caret; i < fs->len; i++)
  11660. fs->value[i] = fs->value[i + 1];
  11661. fs->len--;
  11662. form_dirty = 1;
  11663. js_browser_event(form_focus, "input", 1, 0);
  11664. }
  11665. } else if (k == NGUI_KEY_LEFT) {
  11666. if (fs->caret)
  11667. fs->caret--;
  11668. } else if (k == NGUI_KEY_RIGHT) {
  11669. if (fs->caret < fs->len)
  11670. fs->caret++;
  11671. } else if (k == NGUI_KEY_HOME) {
  11672. fs->caret = 0;
  11673. } else if (k == NGUI_KEY_END) {
  11674. fs->caret = fs->len;
  11675. } else if (k >= 32 && k < 127) {
  11676. if (fs->len < FORM_VALUE_MAX) {
  11677. unsigned int i;
  11678. for (i = fs->len; i > fs->caret; i--)
  11679. fs->value[i] = fs->value[i - 1];
  11680. fs->value[fs->caret++] = (char)k;
  11681. fs->len++;
  11682. form_dirty = 1;
  11683. js_browser_event(form_focus, "input", 1, 0);
  11684. }
  11685. } else {
  11686. return;
  11687. }
  11688. fs->value[fs->len] = '\0';
  11689. layout_valid = 0;
  11690. ngui_invalidate(&ui);
  11691. }
  11692. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  11693. * a same-document navigation: update the URL and fire hashchange. Returns
  11694. * 1 when handled. */
  11695. static int link_fragment_nav(unsigned int node)
  11696. {
  11697. const char *href = br_href(&doc, node);
  11698. char url[BR_URL_MAX];
  11699. unsigned int n = 0;
  11700. if (!href || !href[0] || !js_browser_active())
  11701. return 0;
  11702. if (href[0] == '#') {
  11703. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  11704. url[n] = page_url[n];
  11705. n++;
  11706. }
  11707. url[n] = '\0';
  11708. s_append(url, &n, href, sizeof(url));
  11709. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  11710. return 0;
  11711. }
  11712. if (!same_doc_fragment(url))
  11713. return href[0] == '#';
  11714. page_set_fragment(url, 1);
  11715. js_browser_hashchange();
  11716. return 1;
  11717. }
  11718. /* The innermost laid-out box under a screen point: the smallest valid box
  11719. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  11720. * Used to deliver clicks to elements that are neither links nor controls
  11721. * (a Vue <div role="button">, a card with a click listener). */
  11722. static unsigned int find_box_hit(int x, int y)
  11723. {
  11724. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  11725. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  11726. const struct br_layout_box *b = &layout_boxes[i];
  11727. unsigned int area;
  11728. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  11729. x < b->x || y < b->y || x >= b->x + b->w ||
  11730. y >= b->y + b->h)
  11731. continue;
  11732. area = (unsigned int)b->w * (unsigned int)b->h;
  11733. if (area <= best_area) {
  11734. best = i;
  11735. best_area = area;
  11736. }
  11737. }
  11738. return best;
  11739. }
  11740. static void handle_page_click(unsigned int *action)
  11741. {
  11742. int node;
  11743. char url[BR_URL_MAX];
  11744. if (!ui.pressed)
  11745. return;
  11746. if (ui.press_x < page_rect.x ||
  11747. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  11748. ui.press_y < page_rect.y ||
  11749. ui.press_y >= page_rect.y + page_rect.h)
  11750. return;
  11751. node = find_hit(ui.press_x, ui.press_y);
  11752. if (!node) {
  11753. unsigned int box;
  11754. if (!js_browser_active())
  11755. return;
  11756. box = find_box_hit(ui.press_x, ui.press_y);
  11757. if (box) {
  11758. form_blur();
  11759. js_browser_event(box, "click", 1, 1);
  11760. }
  11761. return;
  11762. }
  11763. if (form_is_control((unsigned int)node)) {
  11764. form_click((unsigned int)node);
  11765. return;
  11766. }
  11767. form_blur();
  11768. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  11769. return;
  11770. if (link_fragment_nav((unsigned int)node))
  11771. return;
  11772. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  11773. sizeof(url)) != 0)
  11774. return;
  11775. s_copy(click_url, url, sizeof(click_url));
  11776. *action |= ACT_NAV;
  11777. }
  11778. void _start(const char *arg)
  11779. {
  11780. struct win_info wi;
  11781. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  11782. u_win_create(960, 640, "Browser", &wi) != 0 &&
  11783. u_win_create(780, 540, "Browser", &wi) != 0) {
  11784. u_puts("browser: no graphics window\n");
  11785. u_exit(1);
  11786. }
  11787. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  11788. url_in.placeholder = "http://...";
  11789. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  11790. ui.theme.accent);
  11791. br_set_viewport(wi.width);
  11792. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  11793. s_copy(cwd, "/", sizeof(cwd));
  11794. heap_clear();
  11795. origin_cache_load();
  11796. css_cache_init();
  11797. script_cache_init();
  11798. persist_restore();
  11799. hist_load();
  11800. page_scroll.offset = 0;
  11801. page_scroll.content_h = 0;
  11802. if (arg && arg[0]) {
  11803. navigate(arg, 1);
  11804. } else {
  11805. load_home(1);
  11806. /* Start ready to type: keep the home page, but leave the address
  11807. * bar empty instead of showing "about:home". */
  11808. ngui_input_set(&url_in, "");
  11809. ngui_set_focus(&ui, ID_URL);
  11810. }
  11811. for (;;) {
  11812. unsigned int action = 0;
  11813. unsigned int now;
  11814. click_url[0] = '\0';
  11815. if (pending_action) {
  11816. action |= pending_action & ACT_WAIT_NAV;
  11817. if (pending_url[0])
  11818. s_copy(click_url, pending_url, sizeof(click_url));
  11819. pending_action = 0;
  11820. pending_url[0] = '\0';
  11821. cancel_fetch = 0;
  11822. } else if (preload_active) {
  11823. if (preload_wait)
  11824. preload_wait = 0;
  11825. else
  11826. preload_step();
  11827. } else if ((preload_pending &&
  11828. page_scroll.offset != preload_scroll) ||
  11829. (preload_rescan && layout_valid)) {
  11830. preload_scroll = page_scroll.offset;
  11831. preload_rescan = 0;
  11832. preload_pending = 0;
  11833. preload_node = 0;
  11834. preload_active = 1;
  11835. }
  11836. js_browser_tick();
  11837. if (resize_pending && !pending_action) {
  11838. resize_pending = 0;
  11839. resize_sent_w = layout_right - layout_left;
  11840. js_browser_window_event("resize");
  11841. }
  11842. persist_tick();
  11843. if (pending_action)
  11844. continue;
  11845. now = u_ticks_ms();
  11846. if (status_until && (int)(now - status_until) >= 0) {
  11847. status_text[0] = '\0';
  11848. status_until = 0;
  11849. status_error = 0;
  11850. ngui_invalidate(&ui);
  11851. }
  11852. if (!ngui_begin(&ui)) {
  11853. /* A queued navigation (e.g. Enter in the URL bar during
  11854. * a slow fetch) must be handled even when this frame
  11855. * needs no redraw. */
  11856. if (!action) {
  11857. fetch_workers_stop_if_unfocused();
  11858. u_sleep_ms(10);
  11859. continue;
  11860. }
  11861. } else {
  11862. draw(&action);
  11863. handle_keys(&action);
  11864. handle_page_click(&action);
  11865. ngui_end(&ui);
  11866. }
  11867. if (action & ACT_NAV) {
  11868. if (click_url[0]) {
  11869. navigate(click_url, 1);
  11870. click_url[0] = '\0';
  11871. } else {
  11872. navigate(url_in.text, 1);
  11873. }
  11874. }
  11875. if (action & ACT_BACK) {
  11876. if (hist_pos > 0) {
  11877. hist_pos--;
  11878. if (same_doc_fragment(history[hist_pos])) {
  11879. page_set_fragment(history[hist_pos], 0);
  11880. js_browser_hashchange();
  11881. } else {
  11882. navigate(history[hist_pos], 0);
  11883. }
  11884. }
  11885. }
  11886. if (action & ACT_FORWARD) {
  11887. if (hist_pos + 1 < hist_len) {
  11888. hist_pos++;
  11889. if (same_doc_fragment(history[hist_pos])) {
  11890. page_set_fragment(history[hist_pos], 0);
  11891. js_browser_hashchange();
  11892. } else {
  11893. navigate(history[hist_pos], 0);
  11894. }
  11895. }
  11896. }
  11897. if (action & ACT_RELOAD) {
  11898. if (s_eq(page_url, "about:home"))
  11899. load_home(0);
  11900. else
  11901. navigate(page_url, 0);
  11902. }
  11903. if (action & ACT_HOME)
  11904. load_home(1);
  11905. if (action & ACT_CLOSE)
  11906. quit = 1;
  11907. if (quit)
  11908. break;
  11909. if (pending_action)
  11910. continue;
  11911. fetch_workers_stop_if_unfocused();
  11912. u_sleep_ms(10);
  11913. }
  11914. fetch_workers_stop_all();
  11915. u_win_close();
  11916. u_exit(0);
  11917. }