browser.c 416 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657
  1. /* browser: a small HTML/CSS browser built on ngui, the image library and the
  2. * shared uhttp client.
  3. *
  4. * Page scripts run on the vendored QuickJS engine (modern ECMAScript) through
  5. * the DOM layer in js_browser.c; forms render and submit natively. External CSS is loaded over uhttp, and images are
  6. * decoded with img.c and drawn inline. Page-scoped buffers (page body,
  7. * rules and image bitmaps) come from the ring-3 libc heap; each image gets an
  8. * exact-size decode arena that is freed as soon as the scaled bitmap exists.
  9. * The DOM and the image/CSS I/O scratch use fixed static arenas.
  10. */
  11. #include <stdlib.h>
  12. #include <stdio.h>
  13. #include <string.h>
  14. #include <math.h>
  15. #include <ucmd_heap.h>
  16. #include "ucmd_lib.h"
  17. #include "ngui.h"
  18. #include "browser_html.h"
  19. #include "js_browser.h"
  20. #include "uhttp.h"
  21. #include "uhttp_cookie.h"
  22. #include "img.h"
  23. #include "inflate.h"
  24. #include "ufont.h"
  25. #include "svg_raster.h"
  26. static void svg_cache_clear(void);
  27. static unsigned char *decode_arena; /* see decode_arena_get() */
  28. static unsigned int decode_arena_size;
  29. /* Start wide enough for the desktop nav; smaller screens fall back to
  30. * 960x640 and 780x540, which still fit a 1024x768 panel. */
  31. #define BR_W 1100
  32. #define BR_H 700
  33. #define BR_TOOLBAR_H 30
  34. #define BR_STATUS_H 18
  35. #define BR_PAGE_MAX (2u * 1024u * 1024u)
  36. #define BR_IMG_FILE_MAX (1024u * 1024u)
  37. #define BR_IMG_PIX_MAX (8u * 1024u * 1024u)
  38. #define BR_MAX_IMAGES 256
  39. /* Decoded display bitmaps share the page heap: cap their total pixels
  40. * (RGB565 plus an optional alpha plane) instead of their count. */
  41. #define BR_IMG_PIXEL_BUDGET (4u * 1024u * 1024u)
  42. #define BR_IMG_DISP_BUDGET (6u * 1024u * 1024u)
  43. #define BR_IMG_ARENA_MAX (24u * 1024u * 1024u)
  44. #define BR_IMG_LAYOUT_W 1000
  45. /* Decode completed image jobs for at most this long per main-loop pass, then
  46. * return to input/painting. One image per pass plus a 10 ms sleep made a
  47. * page of small icons trickle in. */
  48. #define BR_IMG_DECODE_BUDGET_MS 40u
  49. /* Coalesce image-driven repaints: each decode invalidates the page, and a
  50. * full repaint per image made loading superlinear on image-heavy pages. */
  51. #define BR_IMG_REPAINT_MS 100u
  52. #define BR_IMG_STAT_LOG 3584
  53. /* An image job may hold a fetch helper this long. The page/script
  54. * deadline (UHTTP_TOTAL_TIMEOUT_MS) is minutes; one unreachable image host
  55. * must not starve the other images of all four helpers that long. */
  56. #define BR_IMG_JOB_TIMEOUT_MS 30000u
  57. #define BR_CSS_MAX (832u * 1024u)
  58. #define BR_CSS_COMP_MAX (192u * 1024u)
  59. /* Scripts and ES modules: Vite bundles reach ~1.7 MB (the Cloudron
  60. * dashboard's main chunk); the helper's FETCH_MAX is the same 2 MB. */
  61. #define BR_SCRIPT_MAX (2u * 1024u * 1024u)
  62. #define FETCH_ABORT (-2)
  63. /* Session cache for remote stylesheets (per launch; cleared at startup). */
  64. #define CSS_CACHE_MAX 16
  65. #define CSS_CACHE_FILE_MAX (256u * 1024u)
  66. #define CSS_CACHE_PREFIX "bcss-"
  67. #define SCRIPT_CACHE_MAX 24
  68. #define SCRIPT_CACHE_FILE_MAX BR_SCRIPT_MAX
  69. #define SCRIPT_CACHE_PREFIX "bjs-"
  70. /* Web fonts cached for the boot; /share holds 64 entries / 16 MB in all. */
  71. #define FONT_CACHE_MAX 8
  72. #define FONT_CACHE_PREFIX "bfont-"
  73. /* The ufont arena (built-in faces, @font-face files and glyph masks); the
  74. * 512 KB default holds the built-in set but not a page's web fonts. */
  75. #define BR_FONT_ARENA (3u * 1024u * 1024u)
  76. #define BR_MAX_SHEETS 6
  77. #define BR_HISTORY 16
  78. #define BR_URL_MAX 4096 /* = UHTTP_PATH_MAX: google.com's JS URL is ~3.7 KB */
  79. #define BR_STATUS_MAX 200
  80. #define BR_IMG_RGB565(r, g, b) \
  81. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  82. #define BR_GRAY 0x8410
  83. enum {
  84. ID_URL = 1,
  85. ID_GO,
  86. ID_BACK,
  87. ID_FORWARD,
  88. ID_RELOAD,
  89. ID_HOME,
  90. ID_DOWNLOADS
  91. };
  92. #define ACT_NAV (1u << 0)
  93. #define ACT_BACK (1u << 1)
  94. #define ACT_FORWARD (1u << 2)
  95. #define ACT_RELOAD (1u << 3)
  96. #define ACT_HOME (1u << 4)
  97. #define ACT_CLOSE (1u << 5)
  98. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  99. ACT_HOME | ACT_CLOSE)
  100. /* ---- downloads --------------------------------------------------------
  101. * A context-menu download is one entry in dl_tab; one curl __serve helper
  102. * fetches at a time so the page's own workers keep their slots. The body
  103. * lands in /share/bf..., then the browser copies it to /data/DOWNLOAD (or
  104. * /share/DOWNLOAD without an installed disk). The list doubles as the
  105. * toolbar panel's history and is persisted best-effort next to the other
  106. * browser state. */
  107. #define DL_MAX 24
  108. #define DL_URL_MAX 1024
  109. #define DL_NAME_MAX 32
  110. #define DL_PATH_MAX 64
  111. #define DL_ERR_MAX 64
  112. #define DL_FILE_MAX (4u * 1024u * 1024u) /* the helper's FETCH_MAX */
  113. #define DL_PANEL_W 380
  114. #define DL_ROW_H 38
  115. #define DL_PANEL_ROWS 12
  116. #define DL_DIR_DATA "/data/DOWNLOAD"
  117. #define DL_DIR_SHARE "/share/DOWNLOAD"
  118. #define DL_SHARE_LIST "/share/bdownloads"
  119. #define DL_DATA_LIST "/data/BDOWN.DAT"
  120. enum { DL_QUEUED, DL_RUNNING, DL_SAVING, DL_DONE, DL_FAILED };
  121. struct dl_ent {
  122. unsigned char used;
  123. unsigned char state;
  124. char err[DL_ERR_MAX];
  125. char name[DL_NAME_MAX];
  126. char path[DL_PATH_MAX];
  127. char url[DL_URL_MAX];
  128. unsigned int got, total, size, stamp;
  129. };
  130. static struct dl_ent dl_tab[DL_MAX];
  131. static int dl_active = -1;
  132. static unsigned int dl_stamp = 1;
  133. static int dl_unseen;
  134. static int dl_panel_open;
  135. static struct ngui_rect dl_button_rect, dl_panel_rect, dl_clear_rect;
  136. static int dl_panel_rows;
  137. /* Context menu opened by a right click on the page. */
  138. #define CTX_MAX 3
  139. #define CTX_ROW_H 28
  140. #define CTX_LABEL_MAX 28
  141. static int ctx_open;
  142. static int ctx_x, ctx_y, ctx_w, ctx_h, ctx_n;
  143. static unsigned int ctx_action[CTX_MAX];
  144. static char ctx_label[CTX_MAX][CTX_LABEL_MAX];
  145. static char ctx_url[CTX_MAX][DL_URL_MAX];
  146. enum { CTX_SAVE_IMAGE, CTX_SAVE_LINK, CTX_SAVE_PAGE };
  147. struct br_image {
  148. int state; /* 0 empty, 1 ready */
  149. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  150. int native_w, native_h;
  151. unsigned int url_hash; /* <img> source, 0 = not shareable */
  152. char err[32];
  153. /* Display-size cache: the box an image is actually painted in. The
  154. * source bitmap above is deliberately capped at BR_IMG_LAYOUT_W so a
  155. * window resize can re-scale it; the cached copy is exactly dw x dh,
  156. * so every repaint is a 1:1 blit instead of a per-pixel resample. */
  157. struct img_image disp;
  158. unsigned int disp_pixels;
  159. unsigned int disp_last;
  160. };
  161. static struct ngui ui;
  162. static struct ngui_input url_in;
  163. static struct ngui_scroll page_scroll;
  164. static struct br_doc doc;
  165. static struct br_image images[BR_MAX_IMAGES];
  166. static int image_count;
  167. static unsigned int image_pixels;
  168. static unsigned int image_disp_pixels;
  169. static unsigned int image_disp_clock;
  170. /* Per-image pipeline timing for the status line and /share/IMGSTAT. The
  171. * numbers are what decides whether the next work is network, decode or
  172. * display; keep them cheap (one tick read per phase). */
  173. static unsigned int img_stat_start;
  174. static unsigned int img_stat_wall;
  175. static unsigned int img_stat_net;
  176. static unsigned int img_stat_open;
  177. static unsigned int img_stat_first;
  178. static unsigned int img_stat_io;
  179. static unsigned int img_stat_dec;
  180. static unsigned int img_stat_scale;
  181. static unsigned int img_stat_paint;
  182. static unsigned int img_stat_reflow;
  183. static unsigned int img_stat_bytes;
  184. static int img_stat_n;
  185. static unsigned int img_last_dec_ms;
  186. static unsigned int img_last_scale_ms;
  187. static char img_stat_log[BR_IMG_STAT_LOG];
  188. static unsigned int img_stat_log_len;
  189. static unsigned int img_repaint_ms;
  190. static int img_repaint_pending;
  191. /* Painted border boxes, in page/screen coordinates (layout starts at
  192. * page_rect.y - scroll). getBoundingClientRect() subtracts page_rect. */
  193. struct br_layout_box {
  194. int x, y;
  195. int w, h;
  196. unsigned char valid;
  197. };
  198. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  199. /* Inline boxes are built from their line runs in flush_line(): a box is
  200. * replaced when a new layout pass (or a re-layout at the same or an
  201. * earlier line) reaches it, and grown when its runs continue on the same
  202. * or a later line of the same pass. inline_box_parent[] is the enclosing
  203. * inline box (node + 1), so nested spans grow their ancestors too. */
  204. static unsigned int inline_box_pass_id;
  205. static unsigned int inline_box_flush_id;
  206. static unsigned int inline_box_pass[BR_MAX_NODES];
  207. static unsigned int inline_box_flush[BR_MAX_NODES];
  208. static int inline_box_y[BR_MAX_NODES];
  209. static unsigned short inline_box_parent[BR_MAX_NODES];
  210. /* Images are loaded one per main-loop iteration so the parsed page stays
  211. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  212. static int preload_active;
  213. static int preload_max_jobs;
  214. static int preload_pending;
  215. static int preload_wait;
  216. static unsigned int preload_node;
  217. static int preload_loaded;
  218. static int preload_scroll;
  219. static int preload_rescan;
  220. static char post_status_text[BR_STATUS_MAX];
  221. static int post_status_error;
  222. static unsigned int post_status_ttl;
  223. /* Content-relative position/height of each <img>, recorded by the measure
  224. * pass so image loading can be deferred until it is near the viewport. */
  225. static unsigned short img_top[BR_MAX_NODES];
  226. static unsigned short img_h[BR_MAX_NODES];
  227. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  228. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  229. * body. Decode arenas are allocated per image instead of living here. */
  230. static unsigned char *image_io_buf;
  231. static struct ufont_face *font_faces[BR_MAX_FACES];
  232. /* [family id - 1][bold * 2 + italic] -> 1-based face id, 0 = built-in. */
  233. static unsigned char font_pick[BR_MAX_FACES][4];
  234. #define image_file_buf (image_io_buf)
  235. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  236. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  237. static struct inflate image_inflate_ws;
  238. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  239. #error "CSS scratch must fit in image_io_buf"
  240. #endif
  241. static char page_url[BR_URL_MAX];
  242. static char page_title[BR_TITLE_MAX];
  243. static char cwd[64];
  244. static int page_is_local;
  245. static int page_loading;
  246. static char status_text[BR_STATUS_MAX];
  247. static unsigned int status_until;
  248. static int status_error;
  249. static char history[BR_HISTORY][BR_URL_MAX];
  250. static int hist_len, hist_pos;
  251. static char click_url[BR_URL_MAX];
  252. static char pending_url[BR_URL_MAX];
  253. #define BR_POST_MAX 4096
  254. static char pending_post[BR_POST_MAX];
  255. static unsigned int pending_post_len;
  256. /* The pending navigation is a POST even when its body is empty (a form
  257. * without fields, e.g. the OIDC consent auto-submit). */
  258. static int pending_post_is;
  259. /* window "resize" bookkeeping: the page width the last event was for. */
  260. static int resize_sent_w = -1;
  261. static int resize_pending;
  262. static unsigned int pending_action;
  263. static int cancel_fetch;
  264. static int quit;
  265. static struct ngui_rect page_rect;
  266. static unsigned short *page_backbuf;
  267. static int pagebuf_w, pagebuf_h;
  268. static int page_cache_valid;
  269. static int page_cache_scroll;
  270. static unsigned int page_cache_nnode;
  271. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  272. static int layout_valid, layout_left, layout_right;
  273. /* Height of the page viewport: what html/body height:100% resolves to. */
  274. static int layout_view_h;
  275. static unsigned int layout_nnode;
  276. static int layout_content_h;
  277. /* layout output */
  278. struct lay_run {
  279. unsigned int off;
  280. unsigned short len;
  281. unsigned short gap;
  282. unsigned short color;
  283. unsigned short href;
  284. char lit[28];
  285. short img;
  286. signed short dy; /* inline image vertical offset */
  287. unsigned short iw, ih;
  288. unsigned short w;
  289. unsigned char font_px, bold, italic, mono, underline, strike;
  290. unsigned char overline, font_face;
  291. unsigned char transform_scale;
  292. unsigned char origin_x_kind, origin_y_kind;
  293. signed short scale_x, scale_y, rotate_x100;
  294. signed short origin_x, origin_y;
  295. unsigned char has_lit;
  296. unsigned int form; /* node + 1, 0 = not a control */
  297. unsigned char form_kind;
  298. unsigned char form_disabled;
  299. /* RUN_PBOX: background colour, background image and its placement
  300. * inside the iw x ih box (relative offsets, drawn size). */
  301. unsigned char pb_has_bg;
  302. unsigned short pb_bg;
  303. short pb_img;
  304. short pb_x, pb_y, pb_w, pb_h;
  305. /* Innermost inline element (node + 1) whose box this run belongs
  306. * to, 0 = none; flush_line() unions the placed runs into
  307. * layout_boxes[] so getBoundingClientRect() sees inline boxes. */
  308. unsigned short box;
  309. };
  310. struct lay {
  311. int draw;
  312. struct ngui *ui;
  313. int left, right;
  314. int y;
  315. int line_x, line_y, line_h;
  316. int line_left, line_right;
  317. int parent_top;
  318. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  319. int cb_h; /* definite content height of the containing block for
  320. * percentage heights; 0 = indefinite (auto) */
  321. int run_x;
  322. int align;
  323. int depth;
  324. int space_pending;
  325. unsigned char float_active;
  326. int float_left, float_right, float_bottom;
  327. struct lay_run runs[96];
  328. int nruns;
  329. unsigned short box_owner; /* node + 1 of the open inline box */
  330. };
  331. struct hit {
  332. int x, y, w, h;
  333. unsigned short node;
  334. /* A painted absolute/fixed box (a modal, its backdrop, a fixed
  335. * header): it hides the hits painted before it. Inserted below the
  336. * box's own hits, so its links still win. */
  337. unsigned char occl;
  338. };
  339. /* Live form state; the DOM attributes stay the initial/default value. */
  340. #define FORM_MAX 64
  341. #define FORM_VALUE_MAX 63
  342. enum {
  343. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  344. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  345. };
  346. struct form_state {
  347. unsigned int node;
  348. char value[FORM_VALUE_MAX + 1];
  349. unsigned char len, caret, checked, selected, used;
  350. };
  351. static struct form_state form_states[FORM_MAX];
  352. static unsigned int form_focus;
  353. static unsigned int form_dirty;
  354. static int form_descendant(unsigned int node, unsigned int form);
  355. static int form_submit_form(unsigned int node, int fire_event);
  356. static int link_fragment_nav(unsigned int node);
  357. static void history_push(const char *url);
  358. static void form_reset_event(unsigned int form);
  359. static unsigned int s_len(const char *s);
  360. static int s_eq(const char *a, const char *b);
  361. static void form_key(int k);
  362. static void form_click(unsigned int node);
  363. static void style_for_node(unsigned int node, struct br_style *out);
  364. static void anim_reset(void);
  365. static void anim_after_frame(void);
  366. static int form_author_styled(const struct br_style *st);
  367. static int css_radius(const struct br_style *st, int corner, int w, int h);
  368. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  369. const struct br_style *st, int focused);
  370. static int form_disabled(unsigned int node)
  371. {
  372. struct br_node *n = &doc.nodes[node];
  373. if (n->attr_flags & BR_ATTR_DISABLED)
  374. return 1;
  375. return br_find_attr(&doc, node, "disabled") != 0;
  376. }
  377. static int form_kind_of(unsigned int node)
  378. {
  379. const char *type = br_type(&doc, node);
  380. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  381. return FORM_TEXTAREA;
  382. if (doc.nodes[node].tag == BR_TAG_SELECT)
  383. return FORM_SELECT;
  384. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  385. if (s_eq(type, "reset"))
  386. return FORM_RESET;
  387. if (s_eq(type, "button"))
  388. return FORM_BUTTON;
  389. return FORM_SUBMIT;
  390. }
  391. if (s_eq(type, "password"))
  392. return FORM_PASSWORD;
  393. if (s_eq(type, "checkbox"))
  394. return FORM_CHECKBOX;
  395. if (s_eq(type, "radio"))
  396. return FORM_RADIO;
  397. if (s_eq(type, "submit"))
  398. return FORM_SUBMIT;
  399. if (s_eq(type, "reset"))
  400. return FORM_RESET;
  401. if (s_eq(type, "button"))
  402. return FORM_BUTTON;
  403. return FORM_TEXT;
  404. }
  405. static unsigned int form_option_count(unsigned int node)
  406. {
  407. unsigned int c, n = 0;
  408. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  409. if (doc.nodes[c].type == BR_NODE_ELEM &&
  410. doc.nodes[c].tag == BR_TAG_OPTION)
  411. n++;
  412. return n;
  413. }
  414. static unsigned int form_option_selected(unsigned int node)
  415. {
  416. unsigned int c, i = 0;
  417. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  418. if (doc.nodes[c].type != BR_NODE_ELEM ||
  419. doc.nodes[c].tag != BR_TAG_OPTION)
  420. continue;
  421. if (br_find_attr(&doc, c, "selected"))
  422. return i;
  423. i++;
  424. }
  425. return 0;
  426. }
  427. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  428. char *out, unsigned int cap)
  429. {
  430. unsigned int c, i = 0;
  431. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  432. if (doc.nodes[c].type != BR_NODE_ELEM ||
  433. doc.nodes[c].tag != BR_TAG_OPTION)
  434. continue;
  435. if (i == idx)
  436. return br_text_content(&doc, c, out, cap);
  437. i++;
  438. }
  439. return 0;
  440. }
  441. static int form_is_control(unsigned int node);
  442. static struct form_state *form_get(unsigned int node, int create)
  443. {
  444. struct form_state *slot = 0;
  445. unsigned int i;
  446. for (i = 0; i < FORM_MAX; i++) {
  447. if (form_states[i].used) {
  448. if (form_states[i].node == node)
  449. return &form_states[i];
  450. } else if (!slot) {
  451. slot = &form_states[i];
  452. }
  453. }
  454. if (create && !slot) {
  455. /* Full: a client-side router (Docusaurus' React Router)
  456. * replaces page content without a navigation, so slots of
  457. * controls that left the document pile up until no new
  458. * control can be drawn or focused.
  459. * Reuse those first, then slots of nodes that are no longer
  460. * controls. */
  461. for (i = 0; i < FORM_MAX && !slot; i++)
  462. if (form_states[i].node != form_focus &&
  463. br_node_detached(&doc, form_states[i].node))
  464. slot = &form_states[i];
  465. for (i = 0; i < FORM_MAX && !slot; i++)
  466. if (form_states[i].node != form_focus &&
  467. !form_is_control(form_states[i].node))
  468. slot = &form_states[i];
  469. }
  470. if (!create || !slot)
  471. return 0;
  472. slot->node = node;
  473. slot->len = 0;
  474. slot->caret = 0;
  475. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  476. slot->selected = form_option_selected(node);
  477. slot->used = 1;
  478. {
  479. unsigned int n = 0;
  480. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  481. n = br_text_content(&doc, node, slot->value,
  482. FORM_VALUE_MAX + 1);
  483. } else {
  484. const char *v = br_value(&doc, node);
  485. if (v) {
  486. n = s_len(v);
  487. if (n > FORM_VALUE_MAX)
  488. n = FORM_VALUE_MAX;
  489. for (unsigned int j = 0; j < n; j++)
  490. slot->value[j] = v[j];
  491. }
  492. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  493. n = br_text_content(&doc, node, slot->value,
  494. FORM_VALUE_MAX + 1);
  495. }
  496. if (n > FORM_VALUE_MAX)
  497. n = FORM_VALUE_MAX;
  498. slot->value[n] = '\0';
  499. slot->len = (unsigned char)n;
  500. slot->caret = (unsigned char)n;
  501. }
  502. return slot;
  503. }
  504. static void form_reset_state(void)
  505. {
  506. unsigned int i;
  507. for (i = 0; i < FORM_MAX; i++)
  508. form_states[i].used = 0;
  509. form_focus = 0;
  510. }
  511. /* A <button> with element content (an icon <svg>/<img>, a <span> label)
  512. * is laid out like a normal element so that content shows; only a text or
  513. * empty button is drawn as a native control. Clicks still reach it
  514. * through the box hit test. */
  515. static int button_has_elements(unsigned int node)
  516. {
  517. unsigned int c;
  518. if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
  519. return 0;
  520. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  521. if (doc.nodes[c].type == BR_NODE_ELEM)
  522. return 1;
  523. /* An empty button whose icon is a ::before/::after box (Docusaurus'
  524. * sidebar caret) is laid out as an element so the box is drawn. */
  525. if (!doc.nodes[node].first && doc.npe_rules) {
  526. struct br_style st, ps;
  527. char buf[8];
  528. int pe;
  529. style_for_node(node, &st);
  530. for (pe = 1; pe <= 2; pe++)
  531. if (!br_pseudo(&doc, node, pe, &st, &ps, buf,
  532. sizeof(buf)) &&
  533. ps.content == BR_CONTENT_EMPTY &&
  534. ps.display != BR_DISPLAY_NONE)
  535. return 1;
  536. }
  537. return 0;
  538. }
  539. static int form_is_control(unsigned int node)
  540. {
  541. unsigned int tag;
  542. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  543. return 0;
  544. tag = doc.nodes[node].tag;
  545. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  546. tag == BR_TAG_SELECT ||
  547. (tag == BR_TAG_BUTTON && !button_has_elements(node));
  548. }
  549. #define HIT_MAX 96
  550. static struct hit hits[HIT_MAX];
  551. static int nhits;
  552. static unsigned short block_h[BR_MAX_NODES];
  553. /* Border-box height a flex container stretches an item to (align-items:
  554. * stretch in a row with a taller line or a definite height), 0 = none.
  555. * Written by the measure pass, read by both. */
  556. static unsigned short flex_stretch_h[BR_MAX_NODES];
  557. /* Measure-pass top of each block, in the same document coordinates as
  558. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  559. * paint, so it cannot drive the lazy background loader). */
  560. static unsigned short block_top[BR_MAX_NODES];
  561. static char li_marker[BR_MAX_NODES][12];
  562. /* one connection object; the browser fetches one resource at a time */
  563. /* ---- tiny strings ---- */
  564. static unsigned int s_len(const char *s)
  565. {
  566. unsigned int n = 0;
  567. while (s && s[n])
  568. n++;
  569. return n;
  570. }
  571. static void s_copy(char *d, const char *s, unsigned int cap)
  572. {
  573. unsigned int i = 0;
  574. if (!cap)
  575. return;
  576. while (s && s[i] && i + 1 < cap) {
  577. d[i] = s[i];
  578. i++;
  579. }
  580. d[i] = '\0';
  581. }
  582. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  583. {
  584. while (s && *s && *n + 1 < cap)
  585. d[(*n)++] = *s++;
  586. d[*n] = '\0';
  587. }
  588. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  589. unsigned int cap)
  590. {
  591. char tmp[12];
  592. unsigned int i = 0, j;
  593. do {
  594. tmp[i++] = (char)('0' + v % 10);
  595. v /= 10;
  596. } while (v && i < sizeof(tmp));
  597. for (j = 0; j < i && *n + 1 < cap; j++)
  598. d[(*n)++] = tmp[i - 1 - j];
  599. d[*n] = '\0';
  600. }
  601. static int s_eq(const char *a, const char *b)
  602. {
  603. while (*a && *b) {
  604. if (*a != *b)
  605. return 0;
  606. a++;
  607. b++;
  608. }
  609. return *a == *b;
  610. }
  611. static int starts_with(const char *s, const char *p)
  612. {
  613. unsigned int i = 0;
  614. while (p[i]) {
  615. if (s[i] != p[i])
  616. return 0;
  617. i++;
  618. }
  619. return 1;
  620. }
  621. static int contains_ci(const char *s, const char *p)
  622. {
  623. unsigned int i, j;
  624. for (i = 0; s[i]; i++) {
  625. for (j = 0; p[j]; j++) {
  626. char a = s[i + j];
  627. if (a >= 'A' && a <= 'Z')
  628. a = (char)(a - 'A' + 'a');
  629. if (a != p[j])
  630. break;
  631. }
  632. if (!p[j])
  633. return 1;
  634. }
  635. return 0;
  636. }
  637. static char *trim(char *s)
  638. {
  639. unsigned int n;
  640. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  641. s++;
  642. n = s_len(s);
  643. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  644. s[n - 1] == '\r' || s[n - 1] == '\n'))
  645. s[--n] = '\0';
  646. return s;
  647. }
  648. /* ---- per-process heap ---- */
  649. static int heap_start(void)
  650. {
  651. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  652. if (!image_io_buf)
  653. return -1;
  654. page_backbuf = (unsigned short *)malloc(
  655. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  656. pagebuf_w = page_backbuf ? ui.w : 0;
  657. pagebuf_h = page_backbuf ? ui.h : 0;
  658. page_cache_valid = 0;
  659. return 0;
  660. }
  661. static void heap_clear(void)
  662. {
  663. anim_reset(); /* also drops the page-heap alpha buffer */
  664. memset(font_faces, 0, sizeof(font_faces));
  665. memset(font_pick, 0, sizeof(font_pick));
  666. ngui_font_detach(&ui);
  667. svg_cache_clear();
  668. decode_arena = 0; /* lives in the page heap too */
  669. decode_arena_size = 0;
  670. heap_reset();
  671. /* The document arenas live in that heap; drop the stale pointers so
  672. * the next br_parse_plain() allocates fresh ones. */
  673. doc.nodes = 0;
  674. doc.text = 0;
  675. doc.attrs = 0;
  676. image_io_buf = 0;
  677. page_backbuf = 0;
  678. pagebuf_w = pagebuf_h = 0;
  679. page_cache_valid = 0;
  680. }
  681. static void browser_rules_alloc(void)
  682. {
  683. struct br_rule *rules;
  684. rules = (struct br_rule *)malloc(
  685. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  686. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  687. }
  688. /* ---- status ---- */
  689. static void set_status(const char *s, int err, unsigned int ttl_ms)
  690. {
  691. s_copy(status_text, s, sizeof(status_text));
  692. status_error = err;
  693. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  694. ngui_invalidate(&ui);
  695. }
  696. /* Update the status text without forcing a frame; the throttled image
  697. * repaint picks it up. Starting one helper per image used to invalidate the
  698. * whole page before every decode. */
  699. static void set_status_quiet(const char *s)
  700. {
  701. s_copy(status_text, s, sizeof(status_text));
  702. status_error = 0;
  703. status_until = 0;
  704. }
  705. /* ---- JavaScript ---- */
  706. static int resolve_link(const char *base, const char *href, char *out,
  707. unsigned int cap);
  708. static char js_last_status[BR_STATUS_MAX];
  709. static int js_last_error;
  710. static void js_host_status(const char *msg, int error)
  711. {
  712. s_copy(js_last_status, msg, sizeof(js_last_status));
  713. js_last_error = error;
  714. set_status(msg, error, 6000);
  715. }
  716. static void js_host_report(const char *msg)
  717. {
  718. u_puts("[js] ");
  719. u_puts(msg);
  720. u_putc('\n');
  721. s_copy(js_last_status, msg, sizeof(js_last_status));
  722. js_last_error = 1;
  723. set_status(msg, 1, 8000);
  724. }
  725. static void js_host_navigate(const char *url)
  726. {
  727. char resolved[BR_URL_MAX];
  728. if (!url || !url[0])
  729. return;
  730. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  731. return;
  732. s_copy(pending_url, resolved, sizeof(pending_url));
  733. pending_action |= ACT_NAV;
  734. cancel_fetch = 1;
  735. }
  736. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  737. * back/forward between fragments): the page URL, address bar and history
  738. * follow, nothing is reloaded. `push` adds a history entry. */
  739. static int page_set_fragment(const char *url, int push)
  740. {
  741. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  742. return -1;
  743. s_copy(page_url, url, sizeof(page_url));
  744. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  745. url_in.len = s_len(url_in.text);
  746. url_in.cursor = url_in.len;
  747. url_in.scroll = 0;
  748. if (push)
  749. history_push(page_url);
  750. ngui_invalidate(&ui);
  751. return 0;
  752. }
  753. static int js_host_set_hash(const char *url)
  754. {
  755. return page_set_fragment(url, 1);
  756. }
  757. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  758. * the page, so a hash router can react). */
  759. static int same_doc_fragment(const char *url)
  760. {
  761. unsigned int a = 0, b = 0;
  762. if (!js_browser_active() || !url)
  763. return 0;
  764. while (url[a] && url[a] != '#')
  765. a++;
  766. while (page_url[b] && page_url[b] != '#')
  767. b++;
  768. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  769. !s_eq(url, page_url);
  770. }
  771. static void js_host_changed(void)
  772. {
  773. /* Class/style/attribute mutations change computed styles, not just the
  774. * text: drop the per-node style cache before the next layout. */
  775. br_reset_styles(&doc);
  776. layout_valid = 0;
  777. /* Script-built content (Angular's ng-repeat cards) brings new images
  778. * and inline background styles: rescan once the main loop is idle. */
  779. preload_rescan = 1;
  780. ngui_invalidate(&ui);
  781. }
  782. static void js_force_layout(void);
  783. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  784. {
  785. if (node >= BR_MAX_NODES)
  786. return 0;
  787. /* A geometry read after a DOM change gets a synchronous layout, like
  788. * a browser's forced reflow: Bootstrap's tooltip inserts itself,
  789. * reads offsetWidth, then moves itself twice with $.offset(), which
  790. * reads its own current position each time. */
  791. if (!layout_valid)
  792. js_force_layout();
  793. if (!layout_boxes[node].valid)
  794. return 0;
  795. *x = layout_boxes[node].x - page_rect.x;
  796. *y = layout_boxes[node].y - page_rect.y;
  797. *w = layout_boxes[node].w;
  798. *h = layout_boxes[node].h;
  799. return 1;
  800. }
  801. static void form_copy_out(const char *s, char *buf, int cap)
  802. {
  803. int i = 0;
  804. if (!buf || cap <= 0)
  805. return;
  806. while (s && s[i] && i + 1 < cap) {
  807. buf[i] = s[i];
  808. i++;
  809. }
  810. buf[i] = '\0';
  811. }
  812. static int js_host_form_value(unsigned int node, char *buf, int cap)
  813. {
  814. struct form_state *fs;
  815. int kind;
  816. if (!form_is_control(node))
  817. return 0;
  818. kind = form_kind_of(node);
  819. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  820. return 0;
  821. if (kind == FORM_SELECT) {
  822. char opt[64] = "";
  823. unsigned int c, i = 0;
  824. fs = form_get(node, 1);
  825. if (!fs)
  826. return 0;
  827. form_option_text(node, fs->selected, opt, sizeof(opt));
  828. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  829. if (doc.nodes[c].type != BR_NODE_ELEM ||
  830. doc.nodes[c].tag != BR_TAG_OPTION)
  831. continue;
  832. if (i == fs->selected) {
  833. const char *v = br_value(&doc, c);
  834. if (v && v[0])
  835. form_copy_out(v, buf, cap);
  836. else
  837. form_copy_out(opt, buf, cap);
  838. return 1;
  839. }
  840. i++;
  841. }
  842. form_copy_out(opt, buf, cap);
  843. return 1;
  844. }
  845. fs = form_get(node, 1);
  846. if (!fs)
  847. return 0;
  848. form_copy_out(fs->value, buf, cap);
  849. return 1;
  850. }
  851. static int js_host_form_checked(unsigned int node)
  852. {
  853. struct form_state *fs;
  854. int kind;
  855. if (!form_is_control(node))
  856. return -1;
  857. kind = form_kind_of(node);
  858. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  859. return -1;
  860. fs = form_get(node, 1);
  861. return fs ? fs->checked : 0;
  862. }
  863. static int js_host_form_selected(unsigned int node)
  864. {
  865. struct form_state *fs;
  866. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  867. return -1;
  868. fs = form_get(node, 1);
  869. return fs ? fs->selected : 0;
  870. }
  871. static int js_host_form_set_value(unsigned int node, const char *value)
  872. {
  873. struct form_state *fs;
  874. unsigned int n;
  875. if (!form_is_control(node))
  876. return 0;
  877. fs = form_get(node, 1);
  878. if (!fs)
  879. return 0;
  880. n = s_len(value ? value : "");
  881. if (n > FORM_VALUE_MAX)
  882. n = FORM_VALUE_MAX;
  883. for (unsigned int i = 0; i < n; i++)
  884. fs->value[i] = value[i];
  885. fs->value[n] = '\0';
  886. fs->len = (unsigned char)n;
  887. fs->caret = (unsigned char)n;
  888. layout_valid = 0;
  889. ngui_invalidate(&ui);
  890. return 1;
  891. }
  892. static int js_host_form_set_checked(unsigned int node, int checked)
  893. {
  894. struct form_state *fs;
  895. int kind;
  896. if (!form_is_control(node))
  897. return 0;
  898. kind = form_kind_of(node);
  899. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  900. return 0;
  901. fs = form_get(node, 1);
  902. if (!fs)
  903. return 0;
  904. fs->checked = (unsigned char)(checked != 0);
  905. layout_valid = 0;
  906. ngui_invalidate(&ui);
  907. return 1;
  908. }
  909. static int js_host_form_set_selected(unsigned int node, int index)
  910. {
  911. struct form_state *fs;
  912. unsigned int n;
  913. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  914. return 0;
  915. fs = form_get(node, 1);
  916. if (!fs)
  917. return 0;
  918. n = form_option_count(node);
  919. if (index < 0)
  920. index = 0;
  921. if (n && (unsigned int)index >= n)
  922. index = (int)n - 1;
  923. fs->selected = (unsigned char)index;
  924. layout_valid = 0;
  925. ngui_invalidate(&ui);
  926. return 1;
  927. }
  928. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  929. {
  930. unsigned int i;
  931. int n = 0;
  932. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  933. doc.nodes[form].tag != BR_TAG_FORM)
  934. return 0;
  935. for (i = 0; i < doc.nnode && n < cap; i++) {
  936. struct br_node *nd = &doc.nodes[i];
  937. if (i == form || nd->type != BR_NODE_ELEM)
  938. continue;
  939. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  940. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  941. continue;
  942. if (!form_descendant(i, form))
  943. continue;
  944. out[n++] = i;
  945. }
  946. return n;
  947. }
  948. static int js_host_form_submit(unsigned int form)
  949. {
  950. form_submit_form(form, 0);
  951. return 1;
  952. }
  953. static int js_host_form_reset(unsigned int form)
  954. {
  955. form_reset_event(form);
  956. return 1;
  957. }
  958. static void css_computed_name(const char *p, char *out, int cap)
  959. {
  960. int n = 0;
  961. for (; p && *p && n + 2 < cap; p++) {
  962. char c = *p;
  963. if (c >= 'A' && c <= 'Z') {
  964. out[n++] = '-';
  965. c = (char)(c - 'A' + 'a');
  966. } else if (c == '_') {
  967. c = '-';
  968. } else if (c >= 'a' && c <= 'z') {
  969. /* keep */
  970. }
  971. out[n++] = c;
  972. }
  973. out[n] = '\0';
  974. if (!strcmp(out, "css-float"))
  975. strcpy(out, "float");
  976. }
  977. static void css_rgb(unsigned short c, char *buf, int cap)
  978. {
  979. int r = ((c >> 11) & 31) * 255 / 31;
  980. int g = ((c >> 5) & 63) * 255 / 63;
  981. int b = (c & 31) * 255 / 31;
  982. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  983. }
  984. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  985. int font_px)
  986. {
  987. if (unit == 4) {
  988. snprintf(buf, cap, "auto");
  989. } else if (unit == 0) {
  990. snprintf(buf, cap, "%dpx", raw);
  991. } else if (unit == 1) {
  992. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  993. } else if (unit == 2) {
  994. /* Chrome's getComputedStyle() reports used pixel values. */
  995. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  996. } else if (unit == 3) {
  997. snprintf(buf, cap, "%dpx",
  998. (int)br_root_font_px() * raw / 100);
  999. } else {
  1000. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  1001. raw / 100, raw % 100, px);
  1002. }
  1003. }
  1004. static int js_host_computed(unsigned int node, const char *property,
  1005. char *buf, int cap)
  1006. {
  1007. struct br_style st;
  1008. char name[40];
  1009. /* Node 0 is a real element when the page starts with <html>. */
  1010. if (!buf || cap <= 0 || node >= doc.nnode ||
  1011. (node == 0 && doc.nodes[0].type != BR_NODE_ELEM))
  1012. return 0;
  1013. buf[0] = '\0';
  1014. css_computed_name(property, name, sizeof(name));
  1015. style_for_node(node, &st);
  1016. if (!strcmp(name, "display")) {
  1017. const char *v = "inline";
  1018. if (st.display == BR_DISPLAY_BLOCK)
  1019. v = "block";
  1020. else if (st.display == BR_DISPLAY_NONE)
  1021. v = "none";
  1022. else if (st.display == BR_DISPLAY_FLEX)
  1023. v = "flex";
  1024. else if (st.display == BR_DISPLAY_GRID)
  1025. v = "grid";
  1026. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  1027. v = "inline-block";
  1028. snprintf(buf, cap, "%s", v);
  1029. } else if (!strcmp(name, "position")) {
  1030. static const char *pos[] = {
  1031. "static", "absolute", "fixed", "relative", "sticky"
  1032. };
  1033. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  1034. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  1035. int is_w = name[0] == 'w';
  1036. int kind = is_w ? st.width_kind : st.height_kind;
  1037. int val = is_w ? st.width : st.height;
  1038. if (kind == 3) {
  1039. if (is_w)
  1040. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  1041. st.width_calc_pct / 100,
  1042. st.width_calc_pct % 100,
  1043. st.width_calc_px);
  1044. else
  1045. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  1046. st.height_calc_pct / 100,
  1047. st.height_calc_pct % 100,
  1048. st.height_calc_px);
  1049. } else if (kind == 1) {
  1050. snprintf(buf, cap, "%dpx", val);
  1051. } else if (kind == 2) {
  1052. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  1053. } else {
  1054. snprintf(buf, cap, "auto");
  1055. }
  1056. } else if (!strcmp(name, "color") ||
  1057. !strcmp(name, "background-color")) {
  1058. if (!strcmp(name, "background-color") && !st.has_bg)
  1059. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1060. else
  1061. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  1062. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  1063. int is_fill = name[0] == 'f';
  1064. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  1065. if (mode == BR_PAINT_COLOR)
  1066. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  1067. else if (mode == BR_PAINT_CURRENT)
  1068. css_rgb(st.color, buf, cap);
  1069. else if (mode == BR_PAINT_UNSET && is_fill)
  1070. snprintf(buf, cap, "rgb(0, 0, 0)");
  1071. else if (mode == BR_PAINT_URL)
  1072. snprintf(buf, cap, "url()");
  1073. else
  1074. snprintf(buf, cap, "none");
  1075. } else if (!strcmp(name, "font-size")) {
  1076. snprintf(buf, cap, "%dpx", st.font_px);
  1077. } else if (!strcmp(name, "font-weight")) {
  1078. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  1079. } else if (!strcmp(name, "font-style")) {
  1080. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  1081. } else if (!strcmp(name, "font-family")) {
  1082. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  1083. br_font_face_family(st.font_face)[0])
  1084. snprintf(buf, cap, "%s",
  1085. br_font_face_family(st.font_face));
  1086. else
  1087. snprintf(buf, cap, "%s",
  1088. st.mono ? "monospace" : "sans-serif");
  1089. } else if (!strcmp(name, "text-align")) {
  1090. static const char *al[] = { "left", "center", "right", "justify" };
  1091. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  1092. } else if (!strcmp(name, "float")) {
  1093. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  1094. st.float_left == 2 ? "right" : "none");
  1095. } else if (!strcmp(name, "clear")) {
  1096. static const char *cl[] = { "none", "left", "right", "both" };
  1097. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  1098. } else if (!strcmp(name, "opacity")) {
  1099. if (st.opacity >= 255)
  1100. snprintf(buf, cap, "1");
  1101. else
  1102. snprintf(buf, cap, "0.%02d",
  1103. (st.opacity * 100 + 127) / 255 > 99 ? 99 :
  1104. (st.opacity * 100 + 127) / 255);
  1105. } else if (!strcmp(name, "visibility")) {
  1106. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  1107. } else if (!strcmp(name, "overflow")) {
  1108. snprintf(buf, cap, "%s",
  1109. st.overflow_hidden ? "hidden" : "visible");
  1110. } else if (!strcmp(name, "white-space")) {
  1111. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  1112. } else if (!strcmp(name, "text-transform")) {
  1113. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  1114. } else if (!strcmp(name, "box-sizing")) {
  1115. snprintf(buf, cap, "%s",
  1116. st.box_sizing ? "border-box" : "content-box");
  1117. } else if (!strcmp(name, "line-height")) {
  1118. if (st.line_h_px)
  1119. snprintf(buf, cap, "%dpx", st.line_h_px);
  1120. else if (st.line_h_pct)
  1121. snprintf(buf, cap, "%d%%", st.line_h_pct);
  1122. else
  1123. snprintf(buf, cap, "normal");
  1124. } else if (!strcmp(name, "z-index")) {
  1125. if (st.z_set)
  1126. snprintf(buf, cap, "%d", st.z_index);
  1127. else
  1128. snprintf(buf, cap, "auto");
  1129. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  1130. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  1131. int set = name[0] == 't' ? st.top_set :
  1132. name[0] == 'l' ? st.left_set :
  1133. name[0] == 'r' ? st.right_set : st.bottom_set;
  1134. int v = name[0] == 't' ? st.top :
  1135. name[0] == 'l' ? st.left :
  1136. name[0] == 'r' ? st.right : st.bottom;
  1137. if (set)
  1138. snprintf(buf, cap, "%dpx", v);
  1139. else
  1140. snprintf(buf, cap, "auto");
  1141. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  1142. !strcmp(name, "margin-bottom") ||
  1143. !strcmp(name, "margin-left") ||
  1144. !strcmp(name, "padding-top") ||
  1145. !strcmp(name, "padding-right") ||
  1146. !strcmp(name, "padding-bottom") ||
  1147. !strcmp(name, "padding-left")) {
  1148. int is_pad = name[0] == 'p';
  1149. int side = name[strlen(name) - 1] == 'p' ? 0 :
  1150. name[strlen(name) - 1] == 't' ? 1 :
  1151. name[strlen(name) - 1] == 'm' ? 2 : 3;
  1152. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  1153. if (!strcmp(name, "margin-right") ||
  1154. !strcmp(name, "padding-right"))
  1155. side = 1;
  1156. else if (!strcmp(name, "margin-bottom") ||
  1157. !strcmp(name, "padding-bottom"))
  1158. side = 2;
  1159. else if (!strcmp(name, "margin-left") ||
  1160. !strcmp(name, "padding-left"))
  1161. side = 3;
  1162. else
  1163. side = 0;
  1164. side += is_pad ? 4 : 0;
  1165. css_mp_value(buf, cap,
  1166. side == 0 ? st.mt : side == 1 ? st.mr :
  1167. side == 2 ? st.mb : side == 3 ? st.ml :
  1168. side == 4 ? st.pt : side == 5 ? st.pr :
  1169. side == 6 ? st.pb : st.pl,
  1170. st.mp_unit[side], st.mp_calc_px[side],
  1171. st.font_px);
  1172. } else if (!strcmp(name, "border-top-width") ||
  1173. !strcmp(name, "border-right-width") ||
  1174. !strcmp(name, "border-bottom-width") ||
  1175. !strcmp(name, "border-left-width")) {
  1176. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1177. name[7] == 'b' ? 2 : 3;
  1178. snprintf(buf, cap, "%dpx", st.border_w[side]);
  1179. } else if (!strcmp(name, "border-top-color") ||
  1180. !strcmp(name, "border-right-color") ||
  1181. !strcmp(name, "border-bottom-color") ||
  1182. !strcmp(name, "border-left-color")) {
  1183. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1184. name[7] == 'b' ? 2 : 3;
  1185. if (st.border_w[side] && !st.border_t[side])
  1186. css_rgb(st.border_c[side], buf, cap);
  1187. else
  1188. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1189. } else if (!strcmp(name, "background-image")) {
  1190. if (st.bg_image)
  1191. snprintf(buf, cap, "url(\"%s\")",
  1192. br_bg_image_url(st.bg_image - 1));
  1193. else
  1194. snprintf(buf, cap, "none");
  1195. } else if (!strcmp(name, "background-repeat")) {
  1196. static const char *rp[] = {
  1197. "repeat", "no-repeat", "repeat-x", "repeat-y"
  1198. };
  1199. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  1200. st.bg_repeat : 0]);
  1201. } else if (!strcmp(name, "background-position")) {
  1202. if (st.bg_pos_x_kind == 1)
  1203. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  1204. st.bg_pos_y);
  1205. else
  1206. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1207. st.bg_pos_y);
  1208. } else if (!strcmp(name, "background-size")) {
  1209. if (st.bg_size_kind == 3)
  1210. snprintf(buf, cap, "cover");
  1211. else if (st.bg_size_kind == 4)
  1212. snprintf(buf, cap, "contain");
  1213. else if (st.bg_size_kind == 1)
  1214. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1215. st.bg_size_h);
  1216. else if (st.bg_size_kind == 2)
  1217. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1218. st.bg_size_h);
  1219. else
  1220. snprintf(buf, cap, "auto");
  1221. } else if (!strcmp(name, "transform")) {
  1222. char tmp[128];
  1223. unsigned int n = 0;
  1224. if (!st.transform_set) {
  1225. snprintf(buf, cap, "none");
  1226. } else {
  1227. tmp[0] = '\0';
  1228. if (st.tx || st.ty) {
  1229. snprintf(tmp + n, sizeof(tmp) - n,
  1230. "translate(%dpx, %dpx)", st.tx, st.ty);
  1231. n = (unsigned int)strlen(tmp);
  1232. }
  1233. if (st.transform_scale) {
  1234. snprintf(tmp + n, sizeof(tmp) - n,
  1235. "%sscale(%d.%02d, %d.%02d)",
  1236. n ? " " : "", st.scale_x / 100,
  1237. st.scale_x % 100, st.scale_y / 100,
  1238. st.scale_y % 100);
  1239. n = (unsigned int)strlen(tmp);
  1240. if (st.rotate_x100) {
  1241. snprintf(tmp + n, sizeof(tmp) - n,
  1242. " rotate(%d.%02ddeg)",
  1243. st.rotate_x100 / 100,
  1244. st.rotate_x100 % 100);
  1245. }
  1246. } else if (st.rotate_x100) {
  1247. snprintf(tmp + n, sizeof(tmp) - n,
  1248. "%srotate(%d.%02ddeg)",
  1249. n ? " " : "", st.rotate_x100 / 100,
  1250. st.rotate_x100 % 100);
  1251. }
  1252. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1253. }
  1254. } else {
  1255. return 0;
  1256. }
  1257. return buf[0] != '\0';
  1258. }
  1259. static int js_host_click(unsigned int node)
  1260. {
  1261. char url[BR_URL_MAX];
  1262. const char *href;
  1263. if (node >= doc.nnode)
  1264. return 0;
  1265. if (form_is_control(node)) {
  1266. form_click(node); /* dispatches its own click event */
  1267. return 1;
  1268. }
  1269. /* element.click() fires a bubbling, cancelable click before the
  1270. * default action, like a real click (delegated list handlers). */
  1271. if (!js_browser_event(node, "click", 1, 1))
  1272. return 1;
  1273. if (link_fragment_nav(node))
  1274. return 1;
  1275. href = br_href(&doc, node);
  1276. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1277. return 0;
  1278. s_copy(pending_url, url, sizeof(pending_url));
  1279. pending_action |= ACT_NAV;
  1280. cancel_fetch = 1;
  1281. ngui_invalidate(&ui);
  1282. return 1;
  1283. }
  1284. static int fetch_script_text(const char *url, unsigned char **out,
  1285. unsigned int *outlen, char *err,
  1286. unsigned int errcap);
  1287. struct fetch_worker;
  1288. static struct fetch_worker *fetch_worker_alloc(void);
  1289. static void fetch_worker_release(struct fetch_worker *w);
  1290. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1291. unsigned int cap, const char *post,
  1292. unsigned int post_len, unsigned int node,
  1293. int bg, char *err, unsigned int errcap);
  1294. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1295. unsigned int errcap);
  1296. static int fetch_worker_read_body(struct fetch_worker *w,
  1297. unsigned char *plain,
  1298. unsigned int plaincap,
  1299. unsigned char *comp,
  1300. unsigned int compcap,
  1301. int *truncated, char *err,
  1302. unsigned int errcap);
  1303. static void fetch_workers_stop_all(void);
  1304. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1305. unsigned int cap, const char *method,
  1306. const char *ctype, const char *post,
  1307. unsigned int post_len, unsigned int node,
  1308. int bg, unsigned int dec_w,
  1309. unsigned int dec_h, int download,
  1310. char *err, unsigned int errcap);
  1311. static int script_cache_has(const char *url);
  1312. static void script_cache_put(const char *url, const unsigned char *data,
  1313. unsigned int len);
  1314. static unsigned int script_cache_hash(const char *s);
  1315. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1316. unsigned int errcap);
  1317. static void fetch_workers_cancel_busy(void);
  1318. static void worker_wait_ui(void);
  1319. static int fetch_worker_status(const struct fetch_worker *w);
  1320. static void dl_poll(void);
  1321. static void dl_load(void);
  1322. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1323. * module load: the wait must not pump input, or a click would dispatch DOM
  1324. * events into the middle of the running script. */
  1325. static int fetch_wait_passive;
  1326. static void script_error(const char *what, const char *url, const char *why)
  1327. {
  1328. char msg[192];
  1329. unsigned int n = 0;
  1330. s_append(msg, &n, what, sizeof(msg));
  1331. if (url && url[0]) {
  1332. s_append(msg, &n, " ", sizeof(msg));
  1333. s_append(msg, &n, url, sizeof(msg));
  1334. }
  1335. if (why && why[0]) {
  1336. s_append(msg, &n, ": ", sizeof(msg));
  1337. s_append(msg, &n, why, sizeof(msg));
  1338. }
  1339. js_host_report(msg);
  1340. }
  1341. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1342. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1343. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1344. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1345. #define JS_HTTP_POST_MAX (16u * 1024u)
  1346. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1347. static int js_worker_http(const char *method, const char *url,
  1348. const char *ctype, const char *body,
  1349. unsigned int body_len, struct js_http_resp *r,
  1350. char *err, int errcap);
  1351. static int js_host_http(const char *method, const char *url,
  1352. const char *ctype, const char *body,
  1353. unsigned int body_len, struct js_http_resp *r,
  1354. char *err, int errcap)
  1355. {
  1356. if (pending_action) {
  1357. s_copy(err, "page is navigating", (unsigned int)errcap);
  1358. return -1;
  1359. }
  1360. if (url[0] == '/') {
  1361. /* Local file: GET only. */
  1362. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1363. int rv;
  1364. if (!buf) {
  1365. s_copy(err, "out of memory", (unsigned int)errcap);
  1366. return -1;
  1367. }
  1368. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1369. (int)JS_HTTP_MAX);
  1370. r->status = rv < 0 ? 404 : 200;
  1371. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1372. buf[r->len] = '\0';
  1373. r->body = (char *)buf;
  1374. s_copy(r->url, url, sizeof(r->url));
  1375. if (contains_ci(url, ".json"))
  1376. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1377. return 0;
  1378. }
  1379. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1380. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1381. return -1;
  1382. }
  1383. if (body_len > JS_HTTP_POST_MAX) {
  1384. s_copy(err, "request body too large", (unsigned int)errcap);
  1385. return -1;
  1386. }
  1387. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1388. errcap);
  1389. }
  1390. /* Module source for the engine's loader: the boot script cache first, then
  1391. * one blocking fetch with input pumping disabled (the loader runs inside
  1392. * JavaScript). */
  1393. static char *js_host_load_script(const char *url, unsigned int *len)
  1394. {
  1395. unsigned char *data = 0;
  1396. char err[64];
  1397. int rv;
  1398. fetch_wait_passive++;
  1399. set_status("Loading module...", 0, 0);
  1400. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1401. fetch_wait_passive--;
  1402. if (rv != 0) {
  1403. script_error("Cannot load module", url,
  1404. rv == FETCH_ABORT ? "navigation" : err);
  1405. return 0;
  1406. }
  1407. return (char *)data;
  1408. }
  1409. /* Web Storage lives in /share, outside the page heap that every navigation
  1410. * resets: localStorage per origin for the boot, sessionStorage per origin
  1411. * and browser window. */
  1412. #define JS_ORIGIN_MAX 160
  1413. /* scheme://host[:port] of the page (a local page's whole path). */
  1414. static void js_page_origin(char *origin, unsigned int cap)
  1415. {
  1416. unsigned int i = 0, slashes = 0;
  1417. while (page_url[i] && i + 1 < cap) {
  1418. if (page_url[i] == '/' && ++slashes == 3)
  1419. break;
  1420. origin[i] = page_url[i];
  1421. i++;
  1422. }
  1423. origin[i] = '\0';
  1424. }
  1425. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1426. {
  1427. unsigned int n = 0;
  1428. s_append(out, &n, "/share/bls", cap);
  1429. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1430. }
  1431. static void js_storage_path(int kind, char *out, unsigned int cap)
  1432. {
  1433. char origin[JS_ORIGIN_MAX];
  1434. unsigned int n = 0;
  1435. js_page_origin(origin, sizeof(origin));
  1436. if (!kind) {
  1437. js_origin_path(origin, out, cap);
  1438. return;
  1439. }
  1440. s_append(out, &n, "/share/bss", cap);
  1441. if (kind) {
  1442. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1443. s_append(out, &n, "-", cap);
  1444. }
  1445. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1446. }
  1447. static void persist_mark_origin(const char *origin);
  1448. static int persist_store_lookup(const char *origin, char *out, int cap);
  1449. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1450. {
  1451. char path[48], origin[JS_ORIGIN_MAX];
  1452. int rv;
  1453. js_storage_path(kind, path, sizeof(path));
  1454. if (set) {
  1455. if (kind) {
  1456. if (!set[0] || !strcmp(set, "{}")) {
  1457. u_syscall1(SYS_UNLINK, (int)path);
  1458. return 0;
  1459. }
  1460. } else {
  1461. /* localStorage keeps an explicit "{}" rather than no
  1462. * file: a missing /share file means "not loaded from
  1463. * /data yet", and a cleared store must not come back
  1464. * from the disk copy before it is flushed. */
  1465. if (!set[0])
  1466. set = "{}";
  1467. js_page_origin(origin, sizeof(origin));
  1468. persist_mark_origin(origin);
  1469. }
  1470. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1471. (int)strlen(set)) < 0 ? -1 : 0;
  1472. }
  1473. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1474. if (rv < 0 && !kind) {
  1475. /* First use this boot: the persistent copy on /data. */
  1476. js_page_origin(origin, sizeof(origin));
  1477. rv = persist_store_lookup(origin, out, cap);
  1478. if (rv >= 0)
  1479. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1480. }
  1481. if (rv < 0)
  1482. return -1;
  1483. out[rv] = '\0';
  1484. return rv;
  1485. }
  1486. /* ---- persistence on /data ----
  1487. *
  1488. * /share is the working copy (RAM, shared by every helper and window); the
  1489. * installed disk's /data volume keeps the cookie jar and localStorage
  1490. * across reboots when it is mounted. The browser owns the disk copies: at
  1491. * start it restores the jar into /share, and its main loop writes back
  1492. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1493. * setItem updates costs one FAT write. The helpers only touch /share (they
  1494. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1495. * /data mount every disk access simply fails. Both files are plaintext
  1496. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1497. #define PERSIST_MS 3000u
  1498. #define SHARE_COOKIES "/share/bcookies"
  1499. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1500. #define DATA_STORE "/data/BSTORE.DAT"
  1501. #define DATA_STORE_MAGIC "NBLS1\n"
  1502. #define DATA_STORE_MAX (192u * 1024u)
  1503. #define PERSIST_DIRTY_MAX 8
  1504. static unsigned int persist_due;
  1505. static unsigned int cookie_sum_saved;
  1506. static int cookie_sum_valid;
  1507. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1508. static int persist_ndirty;
  1509. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1510. {
  1511. unsigned int h = 2166136261u, i;
  1512. for (i = 0; i < n; i++)
  1513. h = (h ^ p[i]) * 16777619u;
  1514. return h;
  1515. }
  1516. /* Called once at startup, before any helper runs. */
  1517. static void persist_restore(void)
  1518. {
  1519. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1520. int n;
  1521. if (!jar)
  1522. return;
  1523. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1524. (int)sizeof(struct uhttp_jar));
  1525. if (n != (int)sizeof(struct uhttp_jar)) {
  1526. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1527. (int)sizeof(struct uhttp_jar));
  1528. if (n == (int)sizeof(struct uhttp_jar)) {
  1529. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1530. (int)jar, n);
  1531. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1532. cookie_sum_valid = 1;
  1533. }
  1534. }
  1535. free(jar);
  1536. persist_due = u_ticks_ms() + PERSIST_MS;
  1537. }
  1538. static void persist_mark_origin(const char *origin)
  1539. {
  1540. int i;
  1541. for (i = 0; i < persist_ndirty; i++)
  1542. if (s_eq(persist_dirty[i], origin))
  1543. return;
  1544. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1545. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1546. }
  1547. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1548. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1549. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1550. unsigned int *o_off, unsigned int *o_len,
  1551. unsigned int *d_off, unsigned int *d_len,
  1552. unsigned int *rec_end)
  1553. {
  1554. unsigned int p = *pos, v = 0;
  1555. if (p >= len)
  1556. return 0;
  1557. *o_off = p;
  1558. while (p < len && buf[p] != '\n')
  1559. p++;
  1560. if (p >= len)
  1561. return 0;
  1562. *o_len = p - *o_off;
  1563. p++;
  1564. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1565. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1566. if (p >= len || buf[p] != '\n')
  1567. return 0;
  1568. p++;
  1569. if (v > len - p)
  1570. return 0;
  1571. *d_off = p;
  1572. *d_len = v;
  1573. p += v;
  1574. if (p < len && buf[p] == '\n')
  1575. p++;
  1576. *rec_end = p;
  1577. *pos = p;
  1578. return 1;
  1579. }
  1580. static int store_load(char **out)
  1581. {
  1582. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1583. int n;
  1584. *out = buf;
  1585. if (!buf)
  1586. return -1;
  1587. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1588. (int)DATA_STORE_MAX);
  1589. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1590. !starts_with(buf, DATA_STORE_MAGIC))
  1591. return 0;
  1592. return n;
  1593. }
  1594. static int persist_store_lookup(const char *origin, char *out, int cap)
  1595. {
  1596. char *buf;
  1597. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1598. unsigned int olen = s_len(origin);
  1599. int n = store_load(&buf), rv = -1;
  1600. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1601. &dl, &e)) {
  1602. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1603. if ((int)dl < cap) {
  1604. memcpy(out, buf + d, dl);
  1605. out[dl] = '\0';
  1606. rv = (int)dl;
  1607. }
  1608. break;
  1609. }
  1610. }
  1611. free(buf);
  1612. return rv;
  1613. }
  1614. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1615. static void persist_store_flush(void)
  1616. {
  1617. char *old, *nb, path[48];
  1618. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1619. int n = store_load(&old), i, w;
  1620. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1621. if (n < 0 || !nb) {
  1622. free(old);
  1623. free(nb);
  1624. return;
  1625. }
  1626. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1627. /* Untouched origins first, in their old order. */
  1628. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1629. &dl, &e)) {
  1630. int dirty = 0;
  1631. for (i = 0; i < persist_ndirty; i++)
  1632. if (s_len(persist_dirty[i]) == ol &&
  1633. !memcmp(persist_dirty[i], old + oo, ol))
  1634. dirty = 1;
  1635. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1636. continue;
  1637. memcpy(nb + nn, old + oo, e - oo);
  1638. nn += e - oo;
  1639. }
  1640. /* Then the changed ones (an emptied store is dropped). */
  1641. for (i = 0; i < persist_ndirty; i++) {
  1642. char num[12];
  1643. unsigned int k = 0;
  1644. js_origin_path(persist_dirty[i], path, sizeof(path));
  1645. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1646. (int)DATA_STORE_MAX);
  1647. if (w <= 2) /* missing or "{}" */
  1648. continue;
  1649. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1650. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1651. DATA_STORE_MAX) {
  1652. set_status("Saved site data is full; a site's "
  1653. "localStorage was not saved", 1, 6000);
  1654. continue;
  1655. }
  1656. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1657. nb[nn++] = '\n';
  1658. s_append(nb, &nn, num, DATA_STORE_MAX);
  1659. nb[nn++] = '\n';
  1660. memcpy(nb + nn, old, (unsigned int)w);
  1661. nn += (unsigned int)w;
  1662. nb[nn++] = '\n';
  1663. }
  1664. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1665. persist_ndirty = 0;
  1666. free(old);
  1667. free(nb);
  1668. }
  1669. static void persist_cookies_flush(void)
  1670. {
  1671. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1672. unsigned int sum;
  1673. int n;
  1674. if (!jar)
  1675. return;
  1676. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1677. (int)sizeof(struct uhttp_jar));
  1678. if (n == (int)sizeof(struct uhttp_jar)) {
  1679. sum = persist_sum(jar, (unsigned int)n);
  1680. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1681. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1682. (int)jar, n) >= 0) {
  1683. cookie_sum_saved = sum;
  1684. cookie_sum_valid = 1;
  1685. }
  1686. }
  1687. }
  1688. free(jar);
  1689. }
  1690. /* ---- visit history (URL-bar autocomplete) ----
  1691. *
  1692. * Every page that finishes loading is recorded with its title, a visit
  1693. * count and a stamp: a counter that only grows and travels with the file,
  1694. * so it orders visits across windows and boots without a wall clock. The
  1695. * table lives in BSS, because the page heap is reset on every navigation.
  1696. * The boot's browser windows share it through /share/bhist (rewritten on
  1697. * every visit) and it is persisted to /data/BHIST.DAT from persist_tick()
  1698. * at most every PERSIST_MS, like the cookie jar. A save re-reads
  1699. * /share/bhist and merges it first, so two windows add to one history
  1700. * instead of overwriting each other. File format: "NBHIST1\n", then
  1701. * "<visits> <stamp> <url>\t<title>\n" per entry. Plaintext, like the
  1702. * other browser state on /data. */
  1703. #define HIST_MAX 128
  1704. #define HIST_URL_MAX 512
  1705. #define HIST_FILE_MAX (HIST_MAX * (HIST_URL_MAX + BR_TITLE_MAX + 24) + 16)
  1706. #define HIST_MAGIC "NBHIST1\n"
  1707. #define SHARE_HIST "/share/bhist"
  1708. #define DATA_HIST "/data/BHIST.DAT"
  1709. #define HIST_FORGET_MAX 16
  1710. struct hist_ent {
  1711. unsigned int visits;
  1712. unsigned int stamp;
  1713. char url[HIST_URL_MAX];
  1714. char title[BR_TITLE_MAX];
  1715. };
  1716. static struct hist_ent hist_tab[HIST_MAX];
  1717. static int hist_n;
  1718. static int hist_share_dirty, hist_data_dirty;
  1719. /* URLs removed in this process: a merge must not bring them back. */
  1720. static unsigned int hist_forgot[HIST_FORGET_MAX];
  1721. static int hist_nforgot;
  1722. static unsigned int hist_hash(const char *s)
  1723. {
  1724. return persist_sum((const unsigned char *)s, s_len(s));
  1725. }
  1726. static int hist_is_forgotten(const char *url)
  1727. {
  1728. unsigned int h = hist_hash(url);
  1729. int i;
  1730. for (i = 0; i < hist_nforgot; i++)
  1731. if (hist_forgot[i] == h)
  1732. return 1;
  1733. return 0;
  1734. }
  1735. static int hist_find(const char *url)
  1736. {
  1737. int i;
  1738. for (i = 0; i < hist_n; i++)
  1739. if (s_eq(hist_tab[i].url, url))
  1740. return i;
  1741. return -1;
  1742. }
  1743. static unsigned int hist_next_stamp(void)
  1744. {
  1745. unsigned int m = 0;
  1746. int i;
  1747. for (i = 0; i < hist_n; i++)
  1748. if (hist_tab[i].stamp > m)
  1749. m = hist_tab[i].stamp;
  1750. return m + 1;
  1751. }
  1752. /* Copy a title, turning tabs/newlines (the file separators) into spaces. */
  1753. static void hist_copy_title(char *d, const char *s, unsigned int n)
  1754. {
  1755. unsigned int i;
  1756. for (i = 0; i + 1 < BR_TITLE_MAX && i < n && s[i]; i++)
  1757. d[i] = (unsigned char)s[i] < 0x20 ? ' ' : s[i];
  1758. d[i] = '\0';
  1759. }
  1760. /* Insert or update an entry; the newer stamp wins the title, the larger
  1761. * visit count is kept. A full table evicts the least recent entry, unless
  1762. * the new one is older still. Returns NULL when nothing was stored. */
  1763. static struct hist_ent *hist_put(const char *url, const char *title,
  1764. unsigned int visits, unsigned int stamp)
  1765. {
  1766. struct hist_ent *e;
  1767. int i = hist_find(url);
  1768. if (i < 0) {
  1769. if (hist_n < HIST_MAX) {
  1770. i = hist_n++;
  1771. } else {
  1772. int j;
  1773. i = 0;
  1774. for (j = 1; j < hist_n; j++)
  1775. if (hist_tab[j].stamp < hist_tab[i].stamp)
  1776. i = j;
  1777. if (hist_tab[i].stamp >= stamp)
  1778. return 0;
  1779. }
  1780. e = &hist_tab[i];
  1781. e->visits = 0;
  1782. e->stamp = 0;
  1783. e->title[0] = '\0';
  1784. s_copy(e->url, url, sizeof(e->url));
  1785. }
  1786. e = &hist_tab[i];
  1787. if (visits > e->visits)
  1788. e->visits = visits;
  1789. if (stamp >= e->stamp) {
  1790. e->stamp = stamp;
  1791. if (title && title[0])
  1792. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1793. } else if (!e->title[0] && title) {
  1794. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1795. }
  1796. return e;
  1797. }
  1798. static unsigned int hist_parse_dec(const char *b, int n, int *pos)
  1799. {
  1800. unsigned int v = 0;
  1801. while (*pos < n && b[*pos] >= '0' && b[*pos] <= '9')
  1802. v = v * 10 + (unsigned int)(b[(*pos)++] - '0');
  1803. return v;
  1804. }
  1805. static void hist_merge_buf(const char *b, int n)
  1806. {
  1807. int pos = (int)s_len(HIST_MAGIC);
  1808. char url[HIST_URL_MAX], title[BR_TITLE_MAX];
  1809. if (n < pos || memcmp(b, HIST_MAGIC, (unsigned int)pos))
  1810. return;
  1811. while (pos < n) {
  1812. unsigned int visits, stamp, ul = 0;
  1813. int t0, t1;
  1814. visits = hist_parse_dec(b, n, &pos);
  1815. if (pos < n && b[pos] == ' ')
  1816. pos++;
  1817. stamp = hist_parse_dec(b, n, &pos);
  1818. if (pos < n && b[pos] == ' ')
  1819. pos++;
  1820. while (pos < n && b[pos] != '\t' && b[pos] != '\n') {
  1821. if (ul + 1 < sizeof(url))
  1822. url[ul++] = b[pos];
  1823. pos++;
  1824. }
  1825. url[ul] = '\0';
  1826. t0 = t1 = pos < n && b[pos] == '\t' ? pos + 1 : pos;
  1827. while (t1 < n && b[t1] != '\n')
  1828. t1++;
  1829. pos = t1 + 1;
  1830. hist_copy_title(title, b + t0, (unsigned int)(t1 - t0));
  1831. if (ul && ul + 1 < sizeof(url) && !hist_is_forgotten(url))
  1832. hist_put(url, title, visits, stamp);
  1833. }
  1834. }
  1835. static int hist_serialize(char *b, unsigned int cap)
  1836. {
  1837. unsigned int n = 0;
  1838. int i;
  1839. s_append(b, &n, HIST_MAGIC, cap);
  1840. for (i = 0; i < hist_n; i++) {
  1841. struct hist_ent *e = &hist_tab[i];
  1842. if (n + s_len(e->url) + s_len(e->title) + 26 >= cap)
  1843. break;
  1844. s_append_dec(b, &n, e->visits, cap);
  1845. b[n++] = ' ';
  1846. s_append_dec(b, &n, e->stamp, cap);
  1847. b[n++] = ' ';
  1848. s_append(b, &n, e->url, cap);
  1849. b[n++] = '\t';
  1850. s_append(b, &n, e->title, cap);
  1851. b[n++] = '\n';
  1852. }
  1853. return (int)n;
  1854. }
  1855. /* Merge /share/bhist, then write it back (and /data when asked). */
  1856. static void hist_sync(int to_data)
  1857. {
  1858. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1859. int n;
  1860. if (!b)
  1861. return;
  1862. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1863. (int)HIST_FILE_MAX);
  1864. if (n > 0)
  1865. hist_merge_buf(b, n);
  1866. n = hist_serialize(b, HIST_FILE_MAX);
  1867. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1868. hist_share_dirty = 0;
  1869. if (to_data) {
  1870. /* No /data mount: the write fails, and there is nothing to
  1871. * retry until the next visit. */
  1872. u_syscall3(SYS_WRITE_FILE, (int)DATA_HIST, (int)b, n);
  1873. hist_data_dirty = 0;
  1874. }
  1875. free(b);
  1876. }
  1877. /* Startup: the boot's shared copy, else the saved one from /data. */
  1878. static void hist_load(void)
  1879. {
  1880. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1881. int n;
  1882. if (!b)
  1883. return;
  1884. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1885. (int)HIST_FILE_MAX);
  1886. if (n <= 0) {
  1887. n = u_syscall3(SYS_READ_FILE, (int)DATA_HIST, (int)b,
  1888. (int)HIST_FILE_MAX);
  1889. if (n > 0)
  1890. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1891. }
  1892. if (n > 0)
  1893. hist_merge_buf(b, n);
  1894. free(b);
  1895. }
  1896. static void hist_visit(const char *url, const char *title)
  1897. {
  1898. struct hist_ent *e;
  1899. unsigned int i;
  1900. if (!url[0] || starts_with(url, "about:") ||
  1901. s_len(url) >= HIST_URL_MAX)
  1902. return;
  1903. for (i = 0; url[i]; i++)
  1904. if ((unsigned char)url[i] < 0x20)
  1905. return;
  1906. e = hist_put(url, title, 0, hist_next_stamp());
  1907. if (!e)
  1908. return;
  1909. e->visits++;
  1910. hist_data_dirty = 1;
  1911. hist_sync(0);
  1912. }
  1913. static void hist_forget(int i)
  1914. {
  1915. if (i < 0 || i >= hist_n)
  1916. return;
  1917. if (hist_nforgot < HIST_FORGET_MAX)
  1918. hist_forgot[hist_nforgot++] = hist_hash(hist_tab[i].url);
  1919. hist_n--;
  1920. for (; i < hist_n; i++)
  1921. hist_tab[i] = hist_tab[i + 1];
  1922. hist_data_dirty = 1;
  1923. hist_sync(0);
  1924. }
  1925. static void hist_tick(void)
  1926. {
  1927. if (hist_share_dirty || hist_data_dirty)
  1928. hist_sync(hist_data_dirty);
  1929. }
  1930. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1931. static void persist_tick(void)
  1932. {
  1933. unsigned int now = u_ticks_ms();
  1934. if ((int)(now - persist_due) < 0)
  1935. return;
  1936. persist_due = now + PERSIST_MS;
  1937. persist_cookies_flush();
  1938. if (persist_ndirty)
  1939. persist_store_flush();
  1940. hist_tick();
  1941. }
  1942. /* <link rel="modulepreload">: download the page's module graph on all
  1943. * helpers at once into the boot script cache, before any script runs. The
  1944. * engine's module loader is sequential (one blocking fetch per import), so
  1945. * without this a Vite app with a dozen chunks pays every round trip in a
  1946. * row. Failures are ignored; the loader fetches what is missing. */
  1947. #define MODULE_PRELOAD_MAX 24
  1948. static void prefetch_module_preloads(void)
  1949. {
  1950. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1951. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1952. unsigned int count = 0, next = 0, done = 0, i;
  1953. char err[64];
  1954. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1955. struct br_node *nd = &doc.nodes[i];
  1956. const char *rel, *href;
  1957. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1958. continue;
  1959. rel = br_rel(&doc, i);
  1960. href = br_href(&doc, i);
  1961. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1962. continue;
  1963. if (resolve_link(page_url, href, urls[count],
  1964. sizeof(urls[count])) != 0 ||
  1965. urls[count][0] == '/' || script_cache_has(urls[count]))
  1966. continue;
  1967. slot[count++] = 0;
  1968. }
  1969. if (!count)
  1970. return;
  1971. set_status("Loading modules...", 0, 0);
  1972. while (done < count) {
  1973. struct fetch_worker *w;
  1974. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1975. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1976. 0, 0, 0, err,
  1977. sizeof(err)) != 0) {
  1978. fetch_worker_release(w);
  1979. done++;
  1980. } else {
  1981. slot[next] = w;
  1982. }
  1983. next++;
  1984. }
  1985. worker_wait_ui();
  1986. if (cancel_fetch || pending_action) {
  1987. fetch_workers_cancel_busy();
  1988. return;
  1989. }
  1990. for (i = 0; i < next; i++) {
  1991. unsigned char *body;
  1992. int rv, tr = 0;
  1993. if (!slot[i])
  1994. continue;
  1995. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1996. if (rv == 0)
  1997. continue;
  1998. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1999. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  2000. if (body) {
  2001. rv = fetch_worker_read_body(slot[i], body,
  2002. BR_SCRIPT_MAX, image_io_buf,
  2003. BR_PAGE_COMP_MAX, &tr, err,
  2004. sizeof(err));
  2005. if (rv > 0 && !tr)
  2006. script_cache_put(urls[i], body,
  2007. (unsigned int)rv);
  2008. free(body);
  2009. }
  2010. fetch_worker_release(slot[i]);
  2011. slot[i] = 0;
  2012. done++;
  2013. }
  2014. u_sleep_ms(10);
  2015. }
  2016. }
  2017. /* Script prefetch state: one entry per <script> block. Remote bodies are
  2018. * submitted to helper workers ahead of time, but scripts still execute in
  2019. * document order. */
  2020. #define SCRIPT_INLINE 0
  2021. #define SCRIPT_LOCAL 1
  2022. #define SCRIPT_REMOTE 2
  2023. #define SCRIPT_ERROR 3
  2024. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  2025. static unsigned char script_kind[BR_MAX_SCRIPTS];
  2026. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  2027. static void script_submit_window(unsigned int *next, char *err,
  2028. unsigned int errcap)
  2029. {
  2030. while (*next < doc.nscripts) {
  2031. struct fetch_worker *w;
  2032. if (script_kind[*next] != SCRIPT_REMOTE) {
  2033. (*next)++;
  2034. continue;
  2035. }
  2036. w = fetch_worker_alloc();
  2037. if (!w)
  2038. return;
  2039. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  2040. 0, 0, 0, 0, err, errcap) != 0) {
  2041. fetch_worker_release(w);
  2042. script_kind[*next] = SCRIPT_ERROR;
  2043. (*next)++;
  2044. continue;
  2045. }
  2046. script_slot[*next] = w;
  2047. (*next)++;
  2048. }
  2049. }
  2050. /* Run the page's scripts in document order. External bodies are prefetched
  2051. * in parallel so downloading script N+1 overlaps executing script N; inline
  2052. * bodies are copied because the engine needs NUL-terminated text. */
  2053. static void run_page_scripts(void)
  2054. {
  2055. struct js_browser_host host;
  2056. unsigned int i, next = 0;
  2057. char err[64], ferr[64];
  2058. if (!doc.nscripts)
  2059. return;
  2060. host.status = js_host_status;
  2061. host.report = js_host_report;
  2062. host.navigate = js_host_navigate;
  2063. host.changed = js_host_changed;
  2064. host.rect = js_host_rect;
  2065. host.form_value = js_host_form_value;
  2066. host.form_checked = js_host_form_checked;
  2067. host.form_selected = js_host_form_selected;
  2068. host.form_set_value = js_host_form_set_value;
  2069. host.form_set_checked = js_host_form_set_checked;
  2070. host.form_set_selected = js_host_form_set_selected;
  2071. host.form_elements = js_host_form_elements;
  2072. host.form_submit = js_host_form_submit;
  2073. host.form_reset = js_host_form_reset;
  2074. host.click = js_host_click;
  2075. host.computed = js_host_computed;
  2076. host.http = js_host_http;
  2077. host.load_script = js_host_load_script;
  2078. host.storage = js_host_storage;
  2079. host.set_hash = js_host_set_hash;
  2080. host.page_url = page_url;
  2081. host.width = ui.w;
  2082. host.height = ui.h;
  2083. if (js_browser_start(&doc, &host) != 0) {
  2084. js_host_status("JavaScript: out of memory", 1);
  2085. return;
  2086. }
  2087. resize_sent_w = -1;
  2088. resize_pending = 0;
  2089. prefetch_module_preloads();
  2090. for (i = 0; i < doc.nscripts; i++) {
  2091. struct br_script *script = &doc.scripts[i];
  2092. const char *src_attr = script->src_off ?
  2093. doc.attrs + script->src_off : "";
  2094. script_slot[i] = 0;
  2095. if (!script->src_off) {
  2096. script_kind[i] = SCRIPT_INLINE;
  2097. continue;
  2098. }
  2099. if (!src_attr[0] ||
  2100. resolve_link(page_url, src_attr, script_urls[i],
  2101. sizeof(script_urls[i])) != 0) {
  2102. script_urls[i][0] = '\0';
  2103. script_kind[i] = SCRIPT_ERROR;
  2104. continue;
  2105. }
  2106. if (script_urls[i][0] == '/' ||
  2107. script_cache_has(script_urls[i]))
  2108. script_kind[i] = SCRIPT_LOCAL;
  2109. else
  2110. script_kind[i] = SCRIPT_REMOTE;
  2111. }
  2112. script_submit_window(&next, ferr, sizeof(ferr));
  2113. for (i = 0; i < doc.nscripts; i++) {
  2114. struct br_script *script = &doc.scripts[i];
  2115. /* document.currentScript for classic scripts (null for modules) */
  2116. js_browser_set_current_script(script->module ? 0 : script->node);
  2117. if (script_kind[i] == SCRIPT_INLINE) {
  2118. unsigned int off = script->off;
  2119. unsigned int len = script->len;
  2120. unsigned int k;
  2121. char *src = (char *)malloc(len + 1);
  2122. if (!src) {
  2123. js_host_status("JavaScript: out of memory", 1);
  2124. break;
  2125. }
  2126. for (k = 0; k < len; k++)
  2127. src[k] = doc.script_src[off + k];
  2128. src[len] = '\0';
  2129. if (script->module) {
  2130. /* A distinct module name per inline module
  2131. * (QuickJS registers modules by name); the
  2132. * fragment keeps relative imports resolving
  2133. * against the page. */
  2134. char mname[BR_URL_MAX + 16];
  2135. unsigned int mn = 0;
  2136. s_append(mname, &mn, page_url, sizeof(mname));
  2137. s_append(mname, &mn, "#module", sizeof(mname));
  2138. s_append_dec(mname, &mn, i, sizeof(mname));
  2139. js_browser_run_module(src, mname);
  2140. } else {
  2141. js_browser_run(src, page_url);
  2142. }
  2143. free(src);
  2144. } else if (script->src_off) {
  2145. const char *src_attr = doc.attrs + script->src_off;
  2146. if (script_kind[i] == SCRIPT_ERROR) {
  2147. script_error("Cannot load script", src_attr,
  2148. script_urls[i][0] ?
  2149. "network busy" :
  2150. "unsupported URL");
  2151. continue;
  2152. }
  2153. if (script_kind[i] == SCRIPT_LOCAL) {
  2154. unsigned char *data = 0;
  2155. unsigned int len = 0;
  2156. int rv;
  2157. set_status("Loading script...", 0, 0);
  2158. rv = fetch_script_text(script_urls[i], &data,
  2159. &len, err, sizeof(err));
  2160. if (rv == FETCH_ABORT)
  2161. break;
  2162. if (rv != 0) {
  2163. script_error("Cannot load script",
  2164. script_urls[i], err);
  2165. continue;
  2166. }
  2167. if (script->module)
  2168. js_browser_run_module(
  2169. (const char *)data,
  2170. script_urls[i]);
  2171. else
  2172. js_browser_run((const char *)data,
  2173. script_urls[i]);
  2174. free(data);
  2175. } else {
  2176. struct fetch_worker *w = script_slot[i];
  2177. unsigned char *body = 0;
  2178. int tr = 0, rv;
  2179. if (!w) {
  2180. w = fetch_worker_alloc();
  2181. if (!w)
  2182. continue;
  2183. if (fetch_worker_submit(w,
  2184. script_urls[i],
  2185. BR_SCRIPT_MAX,
  2186. 0, 0, 0, 0, err,
  2187. sizeof(err)) != 0) {
  2188. fetch_worker_release(w);
  2189. script_kind[i] = SCRIPT_ERROR;
  2190. if (i == next)
  2191. next++;
  2192. continue;
  2193. }
  2194. script_slot[i] = w;
  2195. if (i == next)
  2196. next++;
  2197. }
  2198. set_status("Loading script...", 0, 0);
  2199. rv = fetch_worker_wait(w, err, sizeof(err));
  2200. if (rv == FETCH_ABORT) {
  2201. fetch_workers_stop_all();
  2202. break;
  2203. }
  2204. /* The body gets its own buffer (scripts are up
  2205. * to 2 MB); image_io_buf takes the gzip
  2206. * stream. */
  2207. body = rv == 0 ? (unsigned char *)malloc(
  2208. BR_SCRIPT_MAX + 1) : 0;
  2209. if (body)
  2210. rv = fetch_worker_read_body(w, body,
  2211. BR_SCRIPT_MAX, image_io_buf,
  2212. BR_PAGE_COMP_MAX, &tr, err,
  2213. sizeof(err));
  2214. else {
  2215. if (rv == 0)
  2216. s_copy(err, "out of memory",
  2217. sizeof(err));
  2218. rv = -1;
  2219. }
  2220. fetch_worker_release(w);
  2221. script_slot[i] = 0;
  2222. script_submit_window(&next, ferr, sizeof(ferr));
  2223. if (rv <= 0)
  2224. script_error("Cannot load script",
  2225. script_urls[i], err);
  2226. else if (tr || (unsigned int)rv >=
  2227. BR_SCRIPT_MAX)
  2228. script_error("Cannot load script",
  2229. script_urls[i],
  2230. "script is too large");
  2231. else {
  2232. body[rv] = '\0';
  2233. script_cache_put(script_urls[i], body,
  2234. (unsigned int)rv);
  2235. if (script->module)
  2236. js_browser_run_module(
  2237. (const char *)body,
  2238. script_urls[i]);
  2239. else
  2240. js_browser_run(
  2241. (const char *)body,
  2242. script_urls[i]);
  2243. }
  2244. free(body);
  2245. }
  2246. }
  2247. if (pending_action)
  2248. break;
  2249. }
  2250. js_browser_set_current_script(0);
  2251. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  2252. * load_home() stop it before the next navigation. */
  2253. if (doc.scripts_truncated && !js_last_error)
  2254. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  2255. 1);
  2256. }
  2257. /* ---- images ---- */
  2258. /* data: images that failed to decode (key = data_img_key()), so a layout
  2259. * pass does not retry them on every frame. */
  2260. #define DATA_IMG_FAIL_MAX 32
  2261. static unsigned int data_img_fail[DATA_IMG_FAIL_MAX];
  2262. static int data_img_nfail;
  2263. static void image_reset(void)
  2264. {
  2265. int i;
  2266. for (i = 0; i < BR_MAX_IMAGES; i++) {
  2267. images[i].state = 0;
  2268. images[i].native_w = images[i].native_h = 0;
  2269. images[i].err[0] = '\0';
  2270. /* heap_clear() ran before us, so these pointers are stale: drop
  2271. * them without calling free(). */
  2272. memset(&images[i].disp, 0, sizeof(images[i].disp));
  2273. images[i].disp_pixels = 0;
  2274. images[i].disp_last = 0;
  2275. }
  2276. image_count = 0;
  2277. data_img_nfail = 0;
  2278. image_pixels = 0;
  2279. image_disp_pixels = 0;
  2280. image_disp_clock = 0;
  2281. memset(img_stat_log, 0, sizeof(img_stat_log));
  2282. img_stat_log_len = 0;
  2283. img_stat_start = 0;
  2284. img_stat_wall = 0;
  2285. img_stat_net = img_stat_open = img_stat_first = 0;
  2286. img_stat_io = img_stat_dec = img_stat_scale = 0;
  2287. img_stat_paint = img_stat_reflow = 0;
  2288. img_stat_bytes = 0;
  2289. img_stat_n = 0;
  2290. img_last_dec_ms = img_last_scale_ms = 0;
  2291. img_repaint_ms = 0;
  2292. img_repaint_pending = 0;
  2293. preload_active = 0;
  2294. preload_pending = 0;
  2295. preload_wait = 0;
  2296. preload_node = 0;
  2297. preload_loaded = 0;
  2298. }
  2299. /* Ask for a repaint, but not more often than BR_IMG_REPAINT_MS while images
  2300. * are arriving. The main loop draws once per dirty frame; without this a
  2301. * page of N images did N full layout+paint passes. */
  2302. static void image_repaint(void)
  2303. {
  2304. unsigned int now = u_ticks_ms();
  2305. if (!img_repaint_ms || (now - img_repaint_ms) >= BR_IMG_REPAINT_MS) {
  2306. img_repaint_ms = now;
  2307. img_repaint_pending = 0;
  2308. ngui_invalidate(&ui);
  2309. } else {
  2310. img_repaint_pending = 1;
  2311. }
  2312. }
  2313. static void image_disp_drop(struct br_image *bi)
  2314. {
  2315. if (bi->disp.px)
  2316. free(bi->disp.px);
  2317. if (bi->disp.alpha)
  2318. free(bi->disp.alpha);
  2319. memset(&bi->disp, 0, sizeof(bi->disp));
  2320. if (bi->disp_pixels) {
  2321. if (image_disp_pixels >= bi->disp_pixels)
  2322. image_disp_pixels -= bi->disp_pixels;
  2323. bi->disp_pixels = 0;
  2324. }
  2325. }
  2326. /* Free the least recently used display caches until need pixels fit. The
  2327. * source bitmap (bi->img) is never evicted; a later draw rescales it again. */
  2328. static int image_disp_room(unsigned int need)
  2329. {
  2330. while (image_disp_pixels + need > BR_IMG_DISP_BUDGET) {
  2331. unsigned int oldest = ~0u;
  2332. int i, victim = -1;
  2333. for (i = 0; i < image_count; i++) {
  2334. if (!images[i].disp.px)
  2335. continue;
  2336. if (images[i].disp_last < oldest) {
  2337. oldest = images[i].disp_last;
  2338. victim = i;
  2339. }
  2340. }
  2341. if (victim < 0)
  2342. return -1;
  2343. image_disp_drop(&images[victim]);
  2344. }
  2345. return 0;
  2346. }
  2347. /* Return a bitmap at exactly dw x dh, building it once from the capped source
  2348. * bitmap. Callers then draw with scale 1 and img_draw's copy fast path. */
  2349. static struct img_image *image_display_get(struct br_image *bi, int dw, int dh)
  2350. {
  2351. struct img_blit b;
  2352. unsigned int px;
  2353. if (!bi || bi->state != 1 || !bi->img.px || dw < 1 || dh < 1)
  2354. return 0;
  2355. if (dw == (int)bi->img.w && dh == (int)bi->img.h)
  2356. return &bi->img;
  2357. if (dw > 4096 || dh > 4096)
  2358. return &bi->img;
  2359. if (bi->disp.px && bi->disp.w == (unsigned int)dw &&
  2360. bi->disp.h == (unsigned int)dh) {
  2361. bi->disp_last = ++image_disp_clock;
  2362. return &bi->disp;
  2363. }
  2364. px = (unsigned int)dw * (unsigned int)dh;
  2365. if (px > BR_IMG_DISP_BUDGET || image_disp_room(px) != 0)
  2366. return &bi->img;
  2367. image_disp_drop(bi);
  2368. bi->disp.px = (unsigned short *)malloc(px * 2u);
  2369. if (!bi->disp.px)
  2370. return &bi->img;
  2371. if (bi->img.alpha) {
  2372. bi->disp.alpha = (unsigned char *)malloc(px);
  2373. if (!bi->disp.alpha) {
  2374. free(bi->disp.px);
  2375. bi->disp.px = 0;
  2376. return &bi->img;
  2377. }
  2378. }
  2379. bi->disp.w = (unsigned int)dw;
  2380. bi->disp.h = (unsigned int)dh;
  2381. bi->disp.format = bi->img.format;
  2382. bi->disp.flags = 0;
  2383. memset(&b, 0, sizeof(b));
  2384. b.dst = bi->disp.px;
  2385. b.dst_w = dw;
  2386. b.dst_h = dh;
  2387. b.clip_w = dw;
  2388. b.clip_h = dh;
  2389. b.scale = ((unsigned int)dw << 16) / bi->img.w;
  2390. b.dst_a = bi->disp.alpha;
  2391. b.flags = bi->disp.alpha ? IMG_BLIT_SAVE_ALPHA : 0;
  2392. img_draw(&bi->img, &b);
  2393. bi->disp_pixels = px;
  2394. image_disp_pixels += px;
  2395. bi->disp_last = ++image_disp_clock;
  2396. return &bi->disp;
  2397. }
  2398. /* Decode into the shared arena, then copy/scale the result into a display
  2399. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  2400. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  2401. * pixels. Transparent edges are composited over white. */
  2402. /* One decode scratch arena per page, reused across images. Allocating and
  2403. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  2404. * each small display bitmap landed in the hole the previous arena left, so
  2405. * the next arena no longer fit and the heap ratcheted up until an app
  2406. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  2407. * still released right after their one image. */
  2408. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  2409. static unsigned char *decode_arena_get(unsigned int bytes)
  2410. {
  2411. if (decode_arena && decode_arena_size >= bytes)
  2412. return decode_arena;
  2413. free(decode_arena);
  2414. decode_arena = (unsigned char *)malloc(bytes);
  2415. decode_arena_size = decode_arena ? bytes : 0;
  2416. return decode_arena;
  2417. }
  2418. static void decode_arena_put(void)
  2419. {
  2420. if (decode_arena_size > DECODE_ARENA_KEEP) {
  2421. free(decode_arena);
  2422. decode_arena = 0;
  2423. decode_arena_size = 0;
  2424. }
  2425. }
  2426. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  2427. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  2428. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  2429. static int svg_text_sniff(const unsigned char *d, unsigned int len);
  2430. static int svg_decode_image(const unsigned char *data, unsigned int len,
  2431. struct br_image *bi, int box_w, int box_h);
  2432. static int decode_image_data(const unsigned char *data, unsigned int len,
  2433. struct br_image *bi, int box_w, int box_h,
  2434. int fit_w, int fit_h)
  2435. {
  2436. struct img_info info;
  2437. struct img_options opt;
  2438. struct img_mem mem;
  2439. struct img_image decoded;
  2440. unsigned char *arena;
  2441. unsigned int est, bytes, i;
  2442. unsigned int t0;
  2443. unsigned short *px;
  2444. unsigned char *alpha = 0;
  2445. int dw, dh, r;
  2446. bi->url_hash = 0;
  2447. img_last_dec_ms = 0;
  2448. img_last_scale_ms = 0;
  2449. if (img_sniff(data, len, &info) != 0) {
  2450. if (svg_text_sniff(data, len))
  2451. return svg_decode_image(data, len, bi,
  2452. box_w > 0 && box_h > 0 ? box_w : fit_w,
  2453. box_w > 0 && box_h > 0 ? box_h : fit_h);
  2454. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  2455. return -1;
  2456. }
  2457. est = img_estimate(&info);
  2458. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  2459. s_copy(bi->err, "image too large", sizeof(bi->err));
  2460. return -1;
  2461. }
  2462. arena = decode_arena_get(est);
  2463. if (!arena) {
  2464. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2465. return -1;
  2466. }
  2467. img_mem_init(&mem, arena, est);
  2468. opt.max_pixels = BR_IMG_PIX_MAX;
  2469. opt.max_w = fit_w > 0 ? (unsigned int)fit_w :
  2470. (box_w > 0 ? (unsigned int)box_w : 0);
  2471. opt.max_h = fit_h > 0 ? (unsigned int)fit_h :
  2472. (box_h > 0 ? (unsigned int)box_h : 0);
  2473. t0 = u_ticks_ms();
  2474. r = img_decode(data, len, &opt, &mem, &decoded);
  2475. img_last_dec_ms = u_ticks_ms() - t0;
  2476. if (r != 0) {
  2477. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  2478. goto fail;
  2479. }
  2480. if (decoded.w == 0 || decoded.h == 0) {
  2481. s_copy(bi->err, "empty image", sizeof(bi->err));
  2482. goto fail;
  2483. }
  2484. /* The JPEG decoder may have reduced the IDCT output; the layout still
  2485. * needs the intrinsic dimensions from the header. */
  2486. bi->native_w = info.width ? (int)info.width : (int)decoded.w;
  2487. bi->native_h = info.height ? (int)info.height : (int)decoded.h;
  2488. dw = (int)decoded.w;
  2489. dh = (int)decoded.h;
  2490. /* An <img> with a CSS/attribute box only ever needs a bitmap that big:
  2491. * decoding 1200x800 and then box-filtering it to 1000x666, only to
  2492. * paint it at 400x267, doubled the decode-time scaling work. cap both
  2493. * axes with one scale so the aspect ratio is preserved. */
  2494. if (fit_w > 0 || fit_h > 0) {
  2495. unsigned int scw = fit_w > 0 ?
  2496. ((unsigned int)fit_w << 16) / decoded.w : ~0u;
  2497. unsigned int sch = fit_h > 0 ?
  2498. ((unsigned int)fit_h << 16) / decoded.h : ~0u;
  2499. unsigned int sc = scw < sch ? scw : sch;
  2500. if (sc < 0x10000u) {
  2501. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2502. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2503. if (dw < 1)
  2504. dw = 1;
  2505. if (dh < 1)
  2506. dh = 1;
  2507. }
  2508. }
  2509. if (box_w > 0 && box_h > 0) {
  2510. /* cover: scale so both box sides are filled, never up */
  2511. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  2512. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  2513. unsigned int sc = sw > sh ? sw : sh;
  2514. if (sc < 0x10000u) {
  2515. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2516. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2517. }
  2518. }
  2519. if (dw > BR_IMG_LAYOUT_W) {
  2520. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  2521. dw = BR_IMG_LAYOUT_W;
  2522. }
  2523. if (dh < 1)
  2524. dh = 1;
  2525. if (dw < 1)
  2526. dw = 1;
  2527. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  2528. BR_IMG_PIXEL_BUDGET) {
  2529. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  2530. goto fail;
  2531. }
  2532. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  2533. px = (unsigned short *)malloc(bytes);
  2534. if (!px) {
  2535. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2536. goto fail;
  2537. }
  2538. /* Keep the alpha plane for the scaled image so transparent logos and
  2539. * icons composite over the page instead of the browser's dark theme
  2540. * background. Very large alpha images stay flattened to bound the
  2541. * heap use. */
  2542. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  2543. alpha = (unsigned char *)malloc((unsigned int)dw *
  2544. (unsigned int)dh);
  2545. if (alpha) {
  2546. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2547. alpha[i] = 255;
  2548. }
  2549. }
  2550. /* With an alpha plane the colour under transparent pixels only shows
  2551. * through partially covered edge pixels of the downscale: use white,
  2552. * as documented above, not the dark browser theme (which left a dark
  2553. * fringe around scaled app icons). */
  2554. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2555. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  2556. {
  2557. struct img_blit b;
  2558. b.dst = px;
  2559. b.dst_w = dw;
  2560. b.dst_h = dh;
  2561. b.clip_x = 0;
  2562. b.clip_y = 0;
  2563. b.clip_w = dw;
  2564. b.clip_h = dh;
  2565. b.x = 0;
  2566. b.y = 0;
  2567. b.scale = ((unsigned int)dw << 16) / decoded.w;
  2568. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  2569. b.bg2 = b.bg;
  2570. b.dst_a = alpha;
  2571. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  2572. t0 = u_ticks_ms();
  2573. img_draw(&decoded, &b);
  2574. img_last_scale_ms = u_ticks_ms() - t0;
  2575. }
  2576. bi->img.format = decoded.format;
  2577. bi->img.w = (unsigned int)dw;
  2578. bi->img.h = (unsigned int)dh;
  2579. bi->img.px = px;
  2580. bi->img.alpha = alpha;
  2581. bi->img.flags = 0;
  2582. bi->state = 1;
  2583. image_pixels += (unsigned int)dw * (unsigned int)dh;
  2584. decode_arena_put();
  2585. return 0;
  2586. fail:
  2587. decode_arena_put();
  2588. return -1;
  2589. }
  2590. /* ---- URL / local path handling ---- */
  2591. static int is_http(const char *s)
  2592. {
  2593. return starts_with(s, "http://") || starts_with(s, "https://");
  2594. }
  2595. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  2596. static int normalize_abs(const char *in, char *out, unsigned int cap)
  2597. {
  2598. char seg[64];
  2599. unsigned int i = 0, o = 1;
  2600. int depth = 0;
  2601. int trailing;
  2602. if (!in || in[0] != '/' || cap < 2)
  2603. return -1;
  2604. trailing = 0;
  2605. {
  2606. unsigned int n = s_len(in);
  2607. if (n > 1 && in[n - 1] == '/')
  2608. trailing = 1;
  2609. }
  2610. out[0] = '/';
  2611. while (in[i]) {
  2612. unsigned int n = 0;
  2613. while (in[i] == '/')
  2614. i++;
  2615. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  2616. if (n + 1 < sizeof(seg))
  2617. seg[n++] = in[i];
  2618. i++;
  2619. }
  2620. seg[n] = '\0';
  2621. if (n == 0)
  2622. break;
  2623. if (s_eq(seg, "."))
  2624. continue;
  2625. if (s_eq(seg, "..")) {
  2626. if (depth > 0) {
  2627. while (o > 1 && out[o - 1] != '/')
  2628. o--;
  2629. if (o > 1)
  2630. o--;
  2631. depth--;
  2632. }
  2633. continue;
  2634. }
  2635. if (o > 1) {
  2636. if (o + 1 >= cap)
  2637. return -1;
  2638. out[o++] = '/';
  2639. }
  2640. if (o + n + 1 >= cap)
  2641. return -1;
  2642. {
  2643. unsigned int j;
  2644. for (j = 0; j < n; j++)
  2645. out[o++] = seg[j];
  2646. }
  2647. depth++;
  2648. }
  2649. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2650. if (o + 1 >= cap)
  2651. return -1;
  2652. out[o++] = '/';
  2653. }
  2654. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2655. if (in[i] == '?' || in[i] == '#') {
  2656. while (in[i]) {
  2657. if (o + 1 >= cap)
  2658. return -1;
  2659. out[o++] = in[i++];
  2660. }
  2661. }
  2662. out[o] = '\0';
  2663. return 0;
  2664. }
  2665. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2666. {
  2667. char joined[BR_URL_MAX];
  2668. if (!in || !in[0]) {
  2669. s_copy(out, cwd[0] ? cwd : "/", cap);
  2670. return;
  2671. }
  2672. if (in[0] == '/') {
  2673. if (normalize_abs(in, out, cap) != 0)
  2674. s_copy(out, in, cap);
  2675. return;
  2676. }
  2677. {
  2678. unsigned int n = 0;
  2679. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2680. s_append(joined, &n, "/", sizeof(joined));
  2681. s_append(joined, &n, in, sizeof(joined));
  2682. }
  2683. if (normalize_abs(joined, out, cap) != 0)
  2684. s_copy(out, joined, cap);
  2685. }
  2686. /* ---- canonical origin cache ---- *
  2687. *
  2688. * Sites commonly redirect http://host to https://host and then to
  2689. * https://www.host. Remember the final scheme/host of the last navigation so
  2690. * a bare domain typed again goes straight there instead of paying for two
  2691. * more connections and TLS handshakes. Only default-port requests are
  2692. * rewritten; explicit ports are left alone. */
  2693. #define ORIGIN_CACHE_MAX 8
  2694. #define ORIGIN_FILE "/share/borigins"
  2695. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2696. UHTTP_HOST_MAX + 2))
  2697. struct origin_cache_entry {
  2698. char host[UHTTP_HOST_MAX];
  2699. char origin[UHTTP_HOST_MAX + 16];
  2700. };
  2701. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2702. static int origin_count;
  2703. static char origin_buf[ORIGIN_BUF_SIZE];
  2704. static int default_port(const struct uhttp_url *u)
  2705. {
  2706. return u->secure ? u->port == 443 : u->port == 80;
  2707. }
  2708. static void url_origin(const struct uhttp_url *u, char *out,
  2709. unsigned int cap)
  2710. {
  2711. unsigned int n = 0;
  2712. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2713. s_append(out, &n, u->host, cap);
  2714. if (!default_port(u)) {
  2715. s_append(out, &n, ":", cap);
  2716. s_append_dec(out, &n, u->port, cap);
  2717. }
  2718. }
  2719. static void origin_cache_apply(char *url, unsigned int cap)
  2720. {
  2721. struct uhttp_url u;
  2722. char out[BR_URL_MAX];
  2723. unsigned int n = 0;
  2724. int i;
  2725. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2726. return;
  2727. for (i = 0; i < origin_count; i++) {
  2728. if (!s_eq(u.host, origins[i].host))
  2729. continue;
  2730. s_append(out, &n, origins[i].origin, sizeof(out));
  2731. s_append(out, &n, u.path, sizeof(out));
  2732. s_copy(url, out, cap);
  2733. return;
  2734. }
  2735. }
  2736. static void origin_cache_save(void)
  2737. {
  2738. unsigned int n = 0;
  2739. int i;
  2740. for (i = 0; i < origin_count; i++) {
  2741. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2742. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2743. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2744. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2745. }
  2746. if (n)
  2747. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2748. (int)origin_buf, (int)n);
  2749. }
  2750. static void origin_cache_load(void)
  2751. {
  2752. char *p;
  2753. int rn;
  2754. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2755. (int)(sizeof(origin_buf) - 1));
  2756. if (rn <= 0)
  2757. return;
  2758. origin_buf[rn] = '\0';
  2759. p = origin_buf;
  2760. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2761. char *line = p, *origin;
  2762. while (*p && *p != '\n')
  2763. p++;
  2764. if (*p)
  2765. *p++ = '\0';
  2766. if (!line[0])
  2767. continue;
  2768. origin = line;
  2769. while (*origin && *origin != ' ')
  2770. origin++;
  2771. if (!*origin)
  2772. continue;
  2773. *origin++ = '\0';
  2774. if (!line[0] || !is_http(origin))
  2775. continue;
  2776. {
  2777. struct uhttp_url uo;
  2778. if (uhttp_parse_url(origin, &uo) != 0 ||
  2779. !s_eq(uo.path, "/"))
  2780. continue;
  2781. }
  2782. s_copy(origins[origin_count].host, line,
  2783. sizeof(origins[origin_count].host));
  2784. s_copy(origins[origin_count].origin, origin,
  2785. sizeof(origins[origin_count].origin));
  2786. origin_count++;
  2787. }
  2788. }
  2789. static int host_is_www_of(const char *host, const char *base)
  2790. {
  2791. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2792. host[3] == '.' && s_eq(host + 4, base);
  2793. }
  2794. static void origin_cache_learn(const char *requested, const char *final)
  2795. {
  2796. struct uhttp_url from, to;
  2797. char origin[UHTTP_HOST_MAX + 16];
  2798. int i;
  2799. if (!is_http(requested) || !is_http(final))
  2800. return;
  2801. if (uhttp_parse_url(requested, &from) != 0 ||
  2802. uhttp_parse_url(final, &to) != 0)
  2803. return;
  2804. if (!default_port(&from))
  2805. return;
  2806. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2807. from.port == to.port)
  2808. return;
  2809. /* Only remember origin-level canonicalisation: the same path, and
  2810. * either the same host or its www./apex sibling. A path- or
  2811. * host-specific redirect (a shortener, a login page) must not poison
  2812. * every request to the typed host. */
  2813. if (!s_eq(from.path, to.path))
  2814. return;
  2815. if (!s_eq(from.host, to.host) &&
  2816. !host_is_www_of(to.host, from.host) &&
  2817. !host_is_www_of(from.host, to.host))
  2818. return;
  2819. url_origin(&to, origin, sizeof(origin));
  2820. for (i = 0; i < origin_count; i++) {
  2821. if (s_eq(origins[i].host, from.host)) {
  2822. if (!s_eq(origins[i].origin, origin)) {
  2823. s_copy(origins[i].origin, origin,
  2824. sizeof(origins[i].origin));
  2825. origin_cache_save();
  2826. }
  2827. return;
  2828. }
  2829. }
  2830. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2831. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2832. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2833. origin_cache_save();
  2834. }
  2835. static int path_dir(const char *path, char *out, unsigned int cap)
  2836. {
  2837. unsigned int i, last = 0;
  2838. for (i = 0; path[i]; i++)
  2839. if (path[i] == '/')
  2840. last = i;
  2841. if (last == 0) {
  2842. if (cap < 2)
  2843. return -1;
  2844. out[0] = '/';
  2845. out[1] = '\0';
  2846. return 0;
  2847. }
  2848. if (last + 1 >= cap)
  2849. return -1;
  2850. {
  2851. unsigned int j;
  2852. for (j = 0; j < last; j++)
  2853. out[j] = path[j];
  2854. out[last] = '\0';
  2855. }
  2856. return 0;
  2857. }
  2858. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2859. static int resolve_link(const char *base, const char *href, char *out,
  2860. unsigned int cap)
  2861. {
  2862. static char joined[BR_URL_MAX]; /* leaf: off the stack */
  2863. if (!href || !href[0] || href[0] == '#')
  2864. return -1;
  2865. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2866. starts_with(href, "data:") || starts_with(href, "tel:"))
  2867. return -1;
  2868. if (starts_with(href, "about:")) {
  2869. s_copy(out, href, cap);
  2870. return 0;
  2871. }
  2872. if (is_http(href)) {
  2873. s_copy(out, href, cap);
  2874. return 0;
  2875. }
  2876. if (starts_with(href, "//")) {
  2877. if (is_http(base)) {
  2878. unsigned int n = 0;
  2879. s_append(out, &n, starts_with(base, "https:") ?
  2880. "https:" : "http:", cap);
  2881. s_append(out, &n, href, cap);
  2882. return 0;
  2883. }
  2884. return -1;
  2885. }
  2886. if (is_http(base)) {
  2887. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2888. }
  2889. /* local page */
  2890. if (href[0] == '/') {
  2891. if (normalize_abs(href, out, cap) != 0)
  2892. return -1;
  2893. return 0;
  2894. }
  2895. {
  2896. static char dir[BR_URL_MAX];
  2897. unsigned int n = 0;
  2898. if (s_eq(base, "about:home"))
  2899. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2900. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2901. s_copy(dir, "/", sizeof(dir));
  2902. s_append(joined, &n, dir, sizeof(joined));
  2903. if (n == 0 || joined[n - 1] != '/')
  2904. s_append(joined, &n, "/", sizeof(joined));
  2905. s_append(joined, &n, href, sizeof(joined));
  2906. }
  2907. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2908. }
  2909. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2910. * rest instead of failing when a page or stylesheet is larger than the
  2911. * buffer. The stream is still walked to the end, so a normal page is
  2912. * verified; a truncated compressed input still returns whatever was decoded
  2913. * so far. */
  2914. struct trunc_buf {
  2915. unsigned char *dst;
  2916. unsigned int cap, pos;
  2917. int full;
  2918. };
  2919. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2920. {
  2921. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2922. if (len > m->cap - m->pos) {
  2923. unsigned int room = m->cap - m->pos;
  2924. if (room) {
  2925. unsigned int i;
  2926. for (i = 0; i < room; i++)
  2927. m->dst[m->pos + i] = data[i];
  2928. m->pos += room;
  2929. }
  2930. m->full = 1;
  2931. return 0;
  2932. }
  2933. {
  2934. unsigned int i;
  2935. for (i = 0; i < len; i++)
  2936. m->dst[m->pos + i] = data[i];
  2937. }
  2938. m->pos += len;
  2939. return 0;
  2940. }
  2941. static void worker_wait_ui(void);
  2942. static void inflate_ui_pump(void *ctx)
  2943. {
  2944. static unsigned int last;
  2945. unsigned int now = u_ticks_ms();
  2946. (void)ctx;
  2947. if ((int)(now - last) >= 50) {
  2948. last = now;
  2949. worker_wait_ui();
  2950. }
  2951. }
  2952. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2953. unsigned char *dst, unsigned int cap,
  2954. unsigned int *outlen, int gzip, int *truncated)
  2955. {
  2956. struct inflate_src in;
  2957. struct inflate_sink sink;
  2958. struct trunc_buf m;
  2959. unsigned int got = 0;
  2960. int r;
  2961. in.p = src;
  2962. in.len = len;
  2963. in.more = 0;
  2964. in.ctx = 0;
  2965. m.dst = dst;
  2966. m.cap = cap;
  2967. m.pos = 0;
  2968. m.full = 0;
  2969. sink.write = trunc_write;
  2970. sink.ctx = &m;
  2971. inflate_init(&image_inflate_ws, &in, &sink);
  2972. image_inflate_ws.progress = inflate_ui_pump;
  2973. image_inflate_ws.progress_ctx = 0;
  2974. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2975. inflate_zlib(&image_inflate_ws, &got);
  2976. *outlen = m.pos;
  2977. *truncated = m.full || r != 0;
  2978. if (r != 0 && m.pos == 0)
  2979. return -1;
  2980. return 0;
  2981. }
  2982. /* ---- headless fetch workers ------------------------------------------ *
  2983. *
  2984. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2985. * writes the raw response, a small metadata file and a done marker under
  2986. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2987. * or a multi-megabyte body never freezes the UI and images download in
  2988. * parallel.
  2989. */
  2990. struct fetch_meta {
  2991. int status;
  2992. int error;
  2993. int trunc;
  2994. unsigned int len;
  2995. unsigned int open_ms;
  2996. unsigned int first_ms;
  2997. unsigned int total_ms;
  2998. /* Optional decoded bitmap produced by the helper (image jobs). */
  2999. unsigned int dw, dh, nw, nh;
  3000. unsigned int alpha;
  3001. unsigned int px_len;
  3002. unsigned int dec_ms;
  3003. int dec_err;
  3004. char encoding[16];
  3005. char ctype[64];
  3006. char final[BR_URL_MAX];
  3007. };
  3008. static void draw(unsigned int *action);
  3009. static void handle_keys(unsigned int *action);
  3010. static void handle_page_click(unsigned int *action);
  3011. #define FETCH_WORKERS 4
  3012. #define FETCH_PATH_MAX 32
  3013. /* One long-lived curl __serve helper per worker. Each worker has its own
  3014. * request/body/meta/done files under /share so several downloads can be in
  3015. * flight at once; the keep-alive connection stays in the helper process, so
  3016. * tls.c's per-process state remains valid. */
  3017. struct fetch_worker {
  3018. int pid;
  3019. int slot;
  3020. int busy;
  3021. int ready;
  3022. int image_job;
  3023. unsigned int seq;
  3024. unsigned int deadline;
  3025. int retried;
  3026. unsigned int dec_w, dec_h;
  3027. int dec_retried;
  3028. char req[FETCH_PATH_MAX];
  3029. char body[FETCH_PATH_MAX];
  3030. char meta[FETCH_PATH_MAX];
  3031. char done[FETCH_PATH_MAX];
  3032. char post[FETCH_PATH_MAX];
  3033. char px[FETCH_PATH_MAX];
  3034. char prog[FETCH_PATH_MAX];
  3035. /* Optional preload job attached to this worker. */
  3036. unsigned int node;
  3037. int bg;
  3038. char url[BR_URL_MAX];
  3039. struct fetch_meta m;
  3040. };
  3041. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  3042. /* One extra helper, outside the page pool, so a download survives a
  3043. * navigation that kills the image jobs. */
  3044. static struct fetch_worker dl_worker;
  3045. static int fetch_tty = -2;
  3046. static void fetch_tty_drain(void);
  3047. static unsigned int fetch_session;
  3048. static unsigned int fetch_seq;
  3049. static struct fetch_meta fetch_meta;
  3050. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  3051. * an HTTP-level error (helper died, timeout in the browser, ...). */
  3052. static int fetch_last_error;
  3053. static unsigned int meta_uint(char **pp)
  3054. {
  3055. char *p = *pp;
  3056. unsigned int v = 0;
  3057. while (*p >= '0' && *p <= '9') {
  3058. v = v * 10 + (unsigned int)(*p - '0');
  3059. p++;
  3060. }
  3061. while (*p && *p != '\n')
  3062. p++;
  3063. if (*p == '\n')
  3064. p++;
  3065. *pp = p;
  3066. return v;
  3067. }
  3068. static void meta_str(char **pp, char *out, unsigned int cap)
  3069. {
  3070. char *p = *pp;
  3071. unsigned int n = 0;
  3072. while (*p && *p != '\n' && n + 1 < cap)
  3073. out[n++] = *p++;
  3074. out[n] = '\0';
  3075. while (*p && *p != '\n')
  3076. p++;
  3077. if (*p == '\n')
  3078. p++;
  3079. *pp = p;
  3080. }
  3081. static void worker_wait_ui(void)
  3082. {
  3083. unsigned int action = 0;
  3084. dl_poll();
  3085. if (!ngui_begin(&ui))
  3086. return;
  3087. draw(&action);
  3088. handle_keys(&action);
  3089. handle_page_click(&action);
  3090. if (action & ACT_WAIT_NAV) {
  3091. pending_action |= action & ACT_WAIT_NAV;
  3092. if ((action & ACT_NAV) && click_url[0])
  3093. s_copy(pending_url, click_url, sizeof(pending_url));
  3094. click_url[0] = '\0';
  3095. cancel_fetch = 1;
  3096. }
  3097. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  3098. ngui_invalidate(&ui);
  3099. ngui_end(&ui);
  3100. }
  3101. static void fetch_path(char *out, unsigned int cap, const char *kind,
  3102. unsigned int session, int slot)
  3103. {
  3104. unsigned int n = 0;
  3105. s_append(out, &n, "/share/bf", cap);
  3106. s_append_dec(out, &n, session, cap);
  3107. s_append(out, &n, "_", cap);
  3108. s_append_dec(out, &n, (unsigned int)slot, cap);
  3109. s_append(out, &n, kind, cap);
  3110. }
  3111. static void fetch_pool_init(void)
  3112. {
  3113. static int ready;
  3114. int i;
  3115. if (ready)
  3116. return;
  3117. ready = 1;
  3118. fetch_session = ((unsigned int)u_getpid() << 16) ^
  3119. (u_ticks_ms() & 0xFFFFu);
  3120. if (!fetch_session)
  3121. fetch_session = 1;
  3122. for (i = 0; i < FETCH_WORKERS; i++) {
  3123. struct fetch_worker *w = &fetch_workers[i];
  3124. w->pid = -1;
  3125. w->slot = i;
  3126. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  3127. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  3128. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  3129. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  3130. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  3131. fetch_path(w->px, sizeof(w->px), "px", fetch_session, i);
  3132. fetch_path(w->prog, sizeof(w->prog), "prog", fetch_session, i);
  3133. }
  3134. dl_worker.pid = -1;
  3135. dl_worker.slot = FETCH_WORKERS;
  3136. fetch_path(dl_worker.req, sizeof(dl_worker.req), "req",
  3137. fetch_session, FETCH_WORKERS);
  3138. fetch_path(dl_worker.body, sizeof(dl_worker.body), "body",
  3139. fetch_session, FETCH_WORKERS);
  3140. fetch_path(dl_worker.meta, sizeof(dl_worker.meta), "meta",
  3141. fetch_session, FETCH_WORKERS);
  3142. fetch_path(dl_worker.done, sizeof(dl_worker.done), "done",
  3143. fetch_session, FETCH_WORKERS);
  3144. fetch_path(dl_worker.post, sizeof(dl_worker.post), "post",
  3145. fetch_session, FETCH_WORKERS);
  3146. fetch_path(dl_worker.px, sizeof(dl_worker.px), "px",
  3147. fetch_session, FETCH_WORKERS);
  3148. fetch_path(dl_worker.prog, sizeof(dl_worker.prog), "prog",
  3149. fetch_session, FETCH_WORKERS);
  3150. }
  3151. static void fetch_worker_stop(struct fetch_worker *w)
  3152. {
  3153. int i;
  3154. /* An abandoned image job leaves its node loadable again. */
  3155. if (w->busy && w->image_job && w->node < doc.nnode) {
  3156. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  3157. doc.nodes[w->node].bg_img_index = -1;
  3158. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  3159. doc.nodes[w->node].img_index = -1;
  3160. }
  3161. if (w->pid > 0) {
  3162. u_kill((unsigned int)w->pid);
  3163. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  3164. u_sleep_ms(5);
  3165. /* Let the reaper close the socket before we reuse the slot. */
  3166. u_sleep_ms(10);
  3167. }
  3168. w->pid = -1;
  3169. w->busy = 0;
  3170. w->ready = 0;
  3171. w->image_job = 0;
  3172. if (w->req[0]) {
  3173. u_syscall1(SYS_UNLINK, (int)w->done);
  3174. u_syscall1(SYS_UNLINK, (int)w->meta);
  3175. u_syscall1(SYS_UNLINK, (int)w->body);
  3176. u_syscall1(SYS_UNLINK, (int)w->post);
  3177. u_syscall1(SYS_UNLINK, (int)w->req);
  3178. u_syscall1(SYS_UNLINK, (int)w->prog);
  3179. }
  3180. }
  3181. static void fetch_workers_stop_all(void)
  3182. {
  3183. int i;
  3184. for (i = 0; i < FETCH_WORKERS; i++)
  3185. fetch_worker_stop(&fetch_workers[i]);
  3186. }
  3187. /* Abandon the transfers of the current page but keep idle helpers and their
  3188. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  3189. * because its response would otherwise land in a reused /share slot. */
  3190. static void fetch_workers_cancel_busy(void)
  3191. {
  3192. int i;
  3193. for (i = 0; i < FETCH_WORKERS; i++)
  3194. if (fetch_workers[i].busy)
  3195. fetch_worker_stop(&fetch_workers[i]);
  3196. }
  3197. static void fetch_workers_prepare_nav(const char *url)
  3198. {
  3199. int i;
  3200. (void)url;
  3201. for (i = 0; i < FETCH_WORKERS; i++) {
  3202. struct fetch_worker *w = &fetch_workers[i];
  3203. if (w->pid <= 0)
  3204. continue;
  3205. /* Only an in-flight transfer must be aborted. Idle helpers
  3206. * stay warm across origins: there are just FETCH_WORKERS of
  3207. * them, and uhttp_open drops the old connection when the
  3208. * next job is for another host. Killing and respawning all
  3209. * four on every navigation churned processes and sockets
  3210. * while images were still loading. */
  3211. if (w->busy)
  3212. fetch_worker_stop(w);
  3213. }
  3214. }
  3215. /* The browser is no longer the active window and no fetch is running: give
  3216. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  3217. static void fetch_workers_stop_if_unfocused(void)
  3218. {
  3219. int i;
  3220. fetch_tty_drain();
  3221. if (ui.focused || page_loading || preload_active)
  3222. return;
  3223. for (i = 0; i < FETCH_WORKERS; i++)
  3224. if (fetch_workers[i].pid > 0) {
  3225. fetch_workers_stop_all();
  3226. return;
  3227. }
  3228. }
  3229. /* The helpers (and this process, since u_tty_create() rebinds our own
  3230. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  3231. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  3232. * a dozen TLS connections every helper hung in its next log line, so the
  3233. * following cross-origin navigation sat at "Loading..." until it timed out.
  3234. * Drain and discard it from every wait/poll loop. */
  3235. static void fetch_tty_drain(void)
  3236. {
  3237. char sink[512];
  3238. int i;
  3239. if (fetch_tty <= 0)
  3240. return;
  3241. for (i = 0; i < 16; i++)
  3242. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  3243. break;
  3244. }
  3245. static int fetch_worker_start(struct fetch_worker *w, char *err,
  3246. unsigned int errcap)
  3247. {
  3248. char arg[40];
  3249. unsigned int n = 0;
  3250. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  3251. return 0;
  3252. w->pid = -1;
  3253. fetch_pool_init();
  3254. if (fetch_tty == -2) {
  3255. int t = u_tty_create();
  3256. fetch_tty = t > 0 ? t : 0;
  3257. }
  3258. s_append(arg, &n, "__serve ", sizeof(arg));
  3259. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  3260. s_append(arg, &n, " ", sizeof(arg));
  3261. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  3262. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  3263. if (w->pid <= 0) {
  3264. w->pid = -1;
  3265. s_copy(err, "cannot start network helper", errcap);
  3266. return -1;
  3267. }
  3268. return 0;
  3269. }
  3270. static struct fetch_worker *fetch_worker_alloc(void)
  3271. {
  3272. int i;
  3273. fetch_pool_init();
  3274. for (i = 0; i < FETCH_WORKERS; i++)
  3275. if (!fetch_workers[i].busy)
  3276. return &fetch_workers[i];
  3277. return 0;
  3278. }
  3279. /* A worker for a synchronous foreground fetch (the page, a module, a
  3280. * script's fetch()/XHR). When image prefetches hold every helper, the
  3281. * newest image job (least progress) is abandoned: fetch_worker_stop()
  3282. * re-arms its node, so a later scan loads it again. Failing instead made
  3283. * cloudron.io's catalogue XHR return status 0 while its icons loaded. */
  3284. static struct fetch_worker *fetch_worker_alloc_fg(void)
  3285. {
  3286. struct fetch_worker *w = fetch_worker_alloc(), *victim = 0;
  3287. int i;
  3288. if (w)
  3289. return w;
  3290. for (i = 0; i < FETCH_WORKERS; i++) {
  3291. struct fetch_worker *c = &fetch_workers[i];
  3292. if (c->busy && c->image_job &&
  3293. (!victim || (int)(c->seq - victim->seq) > 0))
  3294. victim = c;
  3295. }
  3296. if (victim)
  3297. fetch_worker_stop(victim);
  3298. return victim;
  3299. }
  3300. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3301. unsigned int cap, const char *method,
  3302. const char *ctype, const char *post,
  3303. unsigned int post_len, unsigned int node,
  3304. int bg, unsigned int dec_w,
  3305. unsigned int dec_h, int download,
  3306. char *err, unsigned int errcap);
  3307. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  3308. unsigned int cap, const char *post,
  3309. unsigned int post_len, unsigned int node,
  3310. int bg, char *err, unsigned int errcap)
  3311. {
  3312. /* A body pointer with no bytes is still a POST: the classic request
  3313. * line would turn it into a GET. */
  3314. if (post && !post_len)
  3315. return fetch_worker_submit_req(w, url, cap, "POST",
  3316. "application/x-www-form-urlencoded", post, 0, node,
  3317. bg, 0, 0, 0, err, errcap);
  3318. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  3319. node, bg, 0, 0, 0, err, errcap);
  3320. }
  3321. /* Image job: ask the helper to decode at these display bounds as well. */
  3322. static int fetch_worker_submit_image(struct fetch_worker *w, const char *url,
  3323. unsigned int cap, unsigned int node,
  3324. int bg, unsigned int dec_w,
  3325. unsigned int dec_h, char *err,
  3326. unsigned int errcap)
  3327. {
  3328. return fetch_worker_submit_req(w, url, cap, 0, 0, 0, 0, node, bg,
  3329. dec_w, dec_h, 0, err, errcap);
  3330. }
  3331. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  3332. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  3333. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3334. unsigned int cap, const char *method,
  3335. const char *ctype, const char *post,
  3336. unsigned int post_len, unsigned int node,
  3337. int bg, unsigned int dec_w,
  3338. unsigned int dec_h, int download,
  3339. char *err, unsigned int errcap)
  3340. {
  3341. static char req[BR_URL_MAX + 256];
  3342. unsigned int n = 0;
  3343. fetch_seq++;
  3344. if (!fetch_seq)
  3345. fetch_seq = 1;
  3346. w->seq = fetch_seq;
  3347. w->ready = 0;
  3348. w->image_job = 0;
  3349. w->retried = 0;
  3350. w->m.error = 0;
  3351. w->node = node;
  3352. w->bg = bg;
  3353. w->dec_w = dec_w;
  3354. w->dec_h = dec_h;
  3355. w->dec_retried = 0;
  3356. s_copy(w->url, url, sizeof(w->url));
  3357. s_append_dec(req, &n, w->seq, sizeof(req));
  3358. s_append(req, &n, " ", sizeof(req));
  3359. s_append_dec(req, &n, cap, sizeof(req));
  3360. s_append(req, &n, " ", sizeof(req));
  3361. if (dec_w || dec_h) {
  3362. s_append(req, &n, "D ", sizeof(req));
  3363. s_append_dec(req, &n, dec_w, sizeof(req));
  3364. s_append(req, &n, " ", sizeof(req));
  3365. s_append_dec(req, &n, dec_h, sizeof(req));
  3366. s_append(req, &n, " ", sizeof(req));
  3367. } else if (method) {
  3368. unsigned int k;
  3369. s_append(req, &n, "X ", sizeof(req));
  3370. s_append(req, &n, method, sizeof(req));
  3371. s_append(req, &n, " ", sizeof(req));
  3372. s_append_dec(req, &n, post_len, sizeof(req));
  3373. s_append(req, &n, " ", sizeof(req));
  3374. if (!ctype || !ctype[0])
  3375. s_append(req, &n, "-", sizeof(req));
  3376. /* One token on the request line: drop the spaces
  3377. * ("application/json; charset=utf-8" stays valid). */
  3378. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  3379. if (ctype[k] != ' ')
  3380. req[n++] = ctype[k];
  3381. req[n] = '\0';
  3382. s_append(req, &n, " ", sizeof(req));
  3383. } else if (post_len) {
  3384. s_append(req, &n, "POST ", sizeof(req));
  3385. s_append_dec(req, &n, post_len, sizeof(req));
  3386. s_append(req, &n, " ", sizeof(req));
  3387. }
  3388. if (download)
  3389. s_append(req, &n, "DL ", sizeof(req));
  3390. s_append(req, &n, url, sizeof(req));
  3391. s_append(req, &n, "\n", sizeof(req));
  3392. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  3393. (int)post, (int)post_len) < 0) {
  3394. s_copy(err, "cannot queue form body", errcap);
  3395. return -1;
  3396. }
  3397. u_syscall1(SYS_UNLINK, (int)w->done);
  3398. u_syscall1(SYS_UNLINK, (int)w->meta);
  3399. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  3400. s_copy(err, "cannot queue network request", errcap);
  3401. return -1;
  3402. }
  3403. if (fetch_worker_start(w, err, errcap) != 0)
  3404. return -1;
  3405. w->busy = 1;
  3406. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  3407. return 0;
  3408. }
  3409. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  3410. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  3411. unsigned int errcap)
  3412. {
  3413. static char meta[BR_URL_MAX + 1024];
  3414. char *p;
  3415. int rn, mseq;
  3416. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  3417. (int)(sizeof(meta) - 1));
  3418. if (rn <= 0) {
  3419. s_copy(err, "network helper failed", errcap);
  3420. return -1;
  3421. }
  3422. meta[rn] = '\0';
  3423. p = meta;
  3424. mseq = (int)meta_uint(&p);
  3425. if (mseq != (int)w->seq) {
  3426. s_copy(err, "stale network response", errcap);
  3427. return -1;
  3428. }
  3429. w->m.status = (int)meta_uint(&p);
  3430. w->m.error = (int)meta_uint(&p);
  3431. w->m.trunc = (int)meta_uint(&p);
  3432. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  3433. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  3434. meta_str(&p, w->m.final, sizeof(w->m.final));
  3435. w->m.len = meta_uint(&p);
  3436. w->m.open_ms = 0;
  3437. w->m.first_ms = 0;
  3438. w->m.total_ms = 0;
  3439. if (*p) {
  3440. w->m.open_ms = meta_uint(&p);
  3441. w->m.first_ms = meta_uint(&p);
  3442. w->m.total_ms = meta_uint(&p);
  3443. }
  3444. w->m.dw = w->m.dh = w->m.nw = w->m.nh = 0;
  3445. w->m.alpha = w->m.px_len = w->m.dec_ms = 0;
  3446. w->m.dec_err = 0;
  3447. if (*p) {
  3448. w->m.dw = meta_uint(&p);
  3449. w->m.dh = meta_uint(&p);
  3450. w->m.nw = meta_uint(&p);
  3451. w->m.nh = meta_uint(&p);
  3452. w->m.alpha = meta_uint(&p);
  3453. w->m.px_len = meta_uint(&p);
  3454. w->m.dec_err = (int)meta_uint(&p);
  3455. w->m.dec_ms = meta_uint(&p);
  3456. }
  3457. if (w->m.error) {
  3458. s_copy(err, uhttp_error_string(w->m.error), errcap);
  3459. return -1;
  3460. }
  3461. w->ready = 1;
  3462. return 0;
  3463. }
  3464. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  3465. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  3466. unsigned int errcap)
  3467. {
  3468. static char done[24];
  3469. char *p;
  3470. int rn, mseq;
  3471. fetch_tty_drain();
  3472. if (!w->busy)
  3473. return -1;
  3474. if (w->ready)
  3475. return 1;
  3476. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  3477. (int)(sizeof(done) - 1));
  3478. if (rn > 0) {
  3479. done[rn] = '\0';
  3480. p = done;
  3481. mseq = (int)meta_uint(&p);
  3482. if (mseq == (int)w->seq) {
  3483. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  3484. fetch_worker_stop(w);
  3485. return -1;
  3486. }
  3487. return 1;
  3488. }
  3489. }
  3490. if (!u_alive((unsigned int)w->pid)) {
  3491. w->pid = -1;
  3492. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  3493. w->retried = 1;
  3494. return 0;
  3495. }
  3496. s_copy(err, "network helper stopped", errcap);
  3497. fetch_worker_stop(w);
  3498. return -1;
  3499. }
  3500. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  3501. s_copy(err, "network request timed out", errcap);
  3502. fetch_worker_stop(w);
  3503. return -1;
  3504. }
  3505. return 0;
  3506. }
  3507. /* Copy the completed body, inflating it if the server ignored our identity
  3508. * request. Mirrors the old fetch_remote body path. */
  3509. static int fetch_worker_read_body(struct fetch_worker *w,
  3510. unsigned char *plain,
  3511. unsigned int plaincap,
  3512. unsigned char *comp,
  3513. unsigned int compcap,
  3514. int *truncated, char *err,
  3515. unsigned int errcap)
  3516. {
  3517. int rv, zr, was_trunc;
  3518. if (contains_ci(w->m.encoding, "gzip") ||
  3519. contains_ci(w->m.encoding, "deflate")) {
  3520. unsigned int comp_len = 0, plen = 0;
  3521. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  3522. (int)compcap);
  3523. if (rv < 0) {
  3524. s_copy(err, "empty response", errcap);
  3525. return -1;
  3526. }
  3527. comp_len = (unsigned int)rv;
  3528. if (comp_len < w->m.len) {
  3529. s_copy(err, "compressed response is too large", errcap);
  3530. return -1;
  3531. }
  3532. if (contains_ci(w->m.encoding, "deflate"))
  3533. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3534. &plen, 0, &was_trunc);
  3535. else
  3536. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3537. &plen, 1, &was_trunc);
  3538. if (zr != 0) {
  3539. s_copy(err, "compressed response is corrupt", errcap);
  3540. return -1;
  3541. }
  3542. *truncated = w->m.trunc || was_trunc;
  3543. return (int)plen;
  3544. }
  3545. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  3546. if (rv < 0) {
  3547. s_copy(err, "empty response", errcap);
  3548. return -1;
  3549. }
  3550. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  3551. return rv;
  3552. }
  3553. static void fetch_worker_release(struct fetch_worker *w)
  3554. {
  3555. u_syscall1(SYS_UNLINK, (int)w->done);
  3556. u_syscall1(SYS_UNLINK, (int)w->meta);
  3557. u_syscall1(SYS_UNLINK, (int)w->body);
  3558. u_syscall1(SYS_UNLINK, (int)w->post);
  3559. u_syscall1(SYS_UNLINK, (int)w->px);
  3560. u_syscall1(SYS_UNLINK, (int)w->req);
  3561. u_syscall1(SYS_UNLINK, (int)w->prog);
  3562. w->busy = 0;
  3563. w->ready = 0;
  3564. w->image_job = 0;
  3565. w->dec_w = 0;
  3566. w->dec_h = 0;
  3567. w->dec_retried = 0;
  3568. }
  3569. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  3570. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  3571. unsigned int errcap)
  3572. {
  3573. for (;;) {
  3574. int rv;
  3575. if (!fetch_wait_passive)
  3576. worker_wait_ui();
  3577. if (cancel_fetch || pending_action) {
  3578. fetch_workers_cancel_busy();
  3579. return FETCH_ABORT;
  3580. }
  3581. rv = fetch_worker_poll(w, err, errcap);
  3582. if (rv != 0)
  3583. return rv == 1 ? 0 : -1;
  3584. u_sleep_ms(10);
  3585. }
  3586. }
  3587. static int fetch_remote(const char *url, unsigned int cap,
  3588. const char *post, unsigned int post_len,
  3589. unsigned char *plain, unsigned int plaincap,
  3590. unsigned char *comp, unsigned int compcap,
  3591. struct fetch_meta *m, int *truncated,
  3592. char *err, unsigned int errcap)
  3593. {
  3594. struct fetch_worker *w = fetch_worker_alloc_fg();
  3595. int rv;
  3596. fetch_last_error = 0;
  3597. if (!w) {
  3598. s_copy(err, "network busy", errcap);
  3599. return -1;
  3600. }
  3601. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  3602. err, errcap) != 0) {
  3603. fetch_worker_release(w);
  3604. return -1;
  3605. }
  3606. rv = fetch_worker_wait(w, err, errcap);
  3607. if (rv == FETCH_ABORT) {
  3608. fetch_worker_release(w);
  3609. return FETCH_ABORT;
  3610. }
  3611. if (rv != 0) {
  3612. fetch_last_error = w->m.error;
  3613. fetch_worker_release(w);
  3614. return -1;
  3615. }
  3616. *m = w->m;
  3617. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  3618. truncated, err, errcap);
  3619. fetch_worker_release(w);
  3620. if (rv >= 0 && (cancel_fetch || pending_action))
  3621. return FETCH_ABORT;
  3622. return rv;
  3623. }
  3624. static int fetch_worker_status(const struct fetch_worker *w)
  3625. {
  3626. return w->m.status;
  3627. }
  3628. /* ---- download manager ------------------------------------------------- */
  3629. static char dl_dir[DL_PATH_MAX];
  3630. static unsigned int dl_last_prog_ms;
  3631. /* 8.3-safe uppercase name: FAT's directory reader also accepts these. */
  3632. static void dl_clean(char *dst, unsigned int cap, const char *src,
  3633. unsigned int len)
  3634. {
  3635. unsigned int i, n = 0;
  3636. for (i = 0; i < len && n + 1 < cap; i++) {
  3637. unsigned char c = (unsigned char)src[i];
  3638. if (c >= 'a' && c <= 'z')
  3639. c = (unsigned char)(c - 'a' + 'A');
  3640. if (!((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
  3641. c == '-' || c == '_'))
  3642. c = '_';
  3643. dst[n++] = (char)c;
  3644. }
  3645. dst[n] = '\0';
  3646. }
  3647. static const char *dl_ctype_ext(const char *ctype, char out[4])
  3648. {
  3649. static const struct {
  3650. const char *needle;
  3651. const char *ext;
  3652. } map[] = {
  3653. { "html", "HTM" }, { "xml", "XML" }, { "json", "JSN" },
  3654. { "javascript", "JS" }, { "css", "CSS" },
  3655. { "jpeg", "JPG" }, { "png", "PNG" }, { "gif", "GIF" },
  3656. { "bmp", "BMP" }, { "webp", "WBP" }, { "svg", "SVG" },
  3657. { "tiff", "TIF" }, { "pdf", "PDF" }, { "zip", "ZIP" },
  3658. { "mpeg", "MPG" }, { "mp4", "MP4" }, { "audio", "MP3" },
  3659. { "plain", "TXT" }, { "text", "TXT" },
  3660. };
  3661. unsigned int i;
  3662. out[0] = '\0';
  3663. for (i = 0; ctype && i < sizeof(map) / sizeof(map[0]); i++)
  3664. if (contains_ci(ctype, map[i].needle)) {
  3665. s_copy(out, map[i].ext, 4);
  3666. break;
  3667. }
  3668. return out;
  3669. }
  3670. /* Derive BASE[.EXT] from the URL basename. A URL that ends in '/' (or a
  3671. * host-only URL) uses the host as the base and lets the MIME type supply
  3672. * the extension. */
  3673. static void dl_url_name(const char *url, const char *ctype, char *base,
  3674. unsigned int basecap, char *ext, unsigned int extcap)
  3675. {
  3676. const char *p = url, *host = 0, *end, *dot = 0, *slash;
  3677. char raw[96];
  3678. unsigned int n;
  3679. int from_host = 0;
  3680. slash = strstr(url, "://");
  3681. if (slash) {
  3682. host = slash + 3;
  3683. p = strrchr(host, '/');
  3684. if (!p) {
  3685. p = host;
  3686. from_host = 1;
  3687. } else {
  3688. p++;
  3689. }
  3690. } else {
  3691. slash = strrchr(url, '/');
  3692. if (slash)
  3693. p = slash + 1;
  3694. }
  3695. end = p;
  3696. while (*end && *end != '?' && *end != '#')
  3697. end++;
  3698. if (end == p && host) {
  3699. p = host;
  3700. end = p;
  3701. while (*end && *end != '/' && *end != '?' && *end != '#')
  3702. end++;
  3703. from_host = 1;
  3704. }
  3705. n = (unsigned int)(end - p);
  3706. if (n >= sizeof(raw))
  3707. n = sizeof(raw) - 1;
  3708. memcpy(raw, p, n);
  3709. raw[n] = '\0';
  3710. if (from_host) {
  3711. char *dot = strchr(raw, '.');
  3712. if (dot)
  3713. *dot = '\0';
  3714. n = (unsigned int)strlen(raw);
  3715. }
  3716. if (!from_host) {
  3717. dot = strrchr(raw, '.');
  3718. if (dot == raw)
  3719. dot = 0;
  3720. }
  3721. if (dot) {
  3722. dl_clean(ext, extcap, dot + 1,
  3723. (unsigned int)strlen(dot + 1));
  3724. if (!ext[0])
  3725. dot = 0;
  3726. }
  3727. if (!dot)
  3728. dl_ctype_ext(ctype, ext);
  3729. dl_clean(base, basecap, raw, dot ? (unsigned int)(dot - raw) : n);
  3730. if (!base[0])
  3731. s_copy(base, "DOWNLOAD", basecap);
  3732. }
  3733. static int dl_path_taken(const char *path)
  3734. {
  3735. struct sys_stat st;
  3736. return u_syscall2(SYS_FS_STAT, (int)path, (int)&st) == 0;
  3737. }
  3738. static int dl_prepare_dir(void)
  3739. {
  3740. struct sys_stat st;
  3741. const char *want;
  3742. if (u_syscall2(SYS_FS_STAT, (int)"/data", (int)&st) == 0 && st.is_dir)
  3743. want = DL_DIR_DATA;
  3744. else
  3745. want = DL_DIR_SHARE;
  3746. s_copy(dl_dir, want, sizeof(dl_dir));
  3747. if (u_syscall2(SYS_FS_STAT, (int)dl_dir, (int)&st) == 0 && st.is_dir)
  3748. return 0;
  3749. u_syscall1(SYS_MKDIR, (int)dl_dir);
  3750. if (u_syscall2(SYS_FS_STAT, (int)dl_dir, (int)&st) == 0 && st.is_dir)
  3751. return 0;
  3752. if (strcmp(want, DL_DIR_DATA) == 0) {
  3753. s_copy(dl_dir, DL_DIR_SHARE, sizeof(dl_dir));
  3754. if (u_syscall2(SYS_FS_STAT, (int)dl_dir, (int)&st) == 0 &&
  3755. st.is_dir)
  3756. return 0;
  3757. u_syscall1(SYS_MKDIR, (int)dl_dir);
  3758. if (u_syscall2(SYS_FS_STAT, (int)dl_dir, (int)&st) == 0 &&
  3759. st.is_dir)
  3760. return 0;
  3761. }
  3762. return -1;
  3763. }
  3764. /* Pick an unused 8.3 name in dl_dir; fills name and path. */
  3765. static int dl_make_path(const char *url, const char *ctype, char *name,
  3766. unsigned int namecap, char *path,
  3767. unsigned int pathcap)
  3768. {
  3769. char base[16], ext[8], cand[DL_NAME_MAX];
  3770. unsigned int k, n = 0;
  3771. dl_url_name(url, ctype, base, sizeof(base), ext, sizeof(ext));
  3772. if (s_len(base) > 8)
  3773. base[8] = '\0';
  3774. if (s_len(ext) > 3)
  3775. ext[3] = '\0';
  3776. for (k = 0; k < 100; k++) {
  3777. int keep = k < 10 ? 6 : 5;
  3778. if (k == 0) {
  3779. if (ext[0])
  3780. snprintf(cand, sizeof(cand), "%s.%s", base, ext);
  3781. else
  3782. s_copy(cand, base, sizeof(cand));
  3783. } else {
  3784. char b[9];
  3785. s_copy(b, base, sizeof(b));
  3786. if (s_len(b) > (unsigned int)keep)
  3787. b[keep] = '\0';
  3788. if (ext[0])
  3789. snprintf(cand, sizeof(cand), "%s~%u.%s", b,
  3790. k, ext);
  3791. else
  3792. snprintf(cand, sizeof(cand), "%s~%u", b, k);
  3793. }
  3794. n = 0;
  3795. s_append(path, &n, dl_dir, pathcap);
  3796. s_append(path, &n, "/", pathcap);
  3797. s_append(path, &n, cand, pathcap);
  3798. if (!dl_path_taken(path)) {
  3799. s_copy(name, cand, namecap);
  3800. return 0;
  3801. }
  3802. }
  3803. return -1;
  3804. }
  3805. static void dl_ensure_name(struct dl_ent *e)
  3806. {
  3807. char base[16], ext[8];
  3808. if (e->name[0] || !e->url[0])
  3809. return;
  3810. dl_url_name(e->url, "", base, sizeof(base), ext, sizeof(ext));
  3811. if (s_len(base) > 8)
  3812. base[8] = '\0';
  3813. if (s_len(ext) > 3)
  3814. ext[3] = '\0';
  3815. if (ext[0])
  3816. snprintf(e->name, sizeof(e->name), "%s.%s", base, ext);
  3817. else
  3818. s_copy(e->name, base, sizeof(e->name));
  3819. }
  3820. static void dl_write_list(void)
  3821. {
  3822. static char buf[6144];
  3823. unsigned int n = 0, last = 0;
  3824. int out, i;
  3825. s_append(buf, &n, "NBDL1\n", sizeof(buf));
  3826. for (out = 0; out < DL_MAX; out++) {
  3827. int best = -1;
  3828. for (i = 0; i < DL_MAX; i++) {
  3829. struct dl_ent *e = &dl_tab[i];
  3830. if (!e->used || e->stamp <= last ||
  3831. (e->state != DL_DONE && e->state != DL_FAILED))
  3832. continue;
  3833. if (best < 0 || e->stamp < dl_tab[best].stamp)
  3834. best = i;
  3835. }
  3836. if (best < 0)
  3837. break;
  3838. last = dl_tab[best].stamp;
  3839. s_append_dec(buf, &n, dl_tab[best].state, sizeof(buf));
  3840. s_append(buf, &n, "\n", sizeof(buf));
  3841. s_append_dec(buf, &n, dl_tab[best].size, sizeof(buf));
  3842. s_append(buf, &n, "\n", sizeof(buf));
  3843. s_append(buf, &n, dl_tab[best].name, sizeof(buf));
  3844. s_append(buf, &n, "\n", sizeof(buf));
  3845. s_append(buf, &n, dl_tab[best].path, sizeof(buf));
  3846. s_append(buf, &n, "\n", sizeof(buf));
  3847. }
  3848. u_syscall3(SYS_WRITE_FILE, (int)DL_SHARE_LIST, (int)buf, (int)n);
  3849. u_syscall3(SYS_WRITE_FILE, (int)DL_DATA_LIST, (int)buf, (int)n);
  3850. }
  3851. static void dl_load(void)
  3852. {
  3853. static char buf[6144];
  3854. char *p;
  3855. int rn, i = 0;
  3856. rn = u_syscall3(SYS_READ_FILE, (int)DL_SHARE_LIST, (int)buf,
  3857. (int)(sizeof(buf) - 1));
  3858. if (rn < 6 || memcmp(buf, "NBDL1\n", 6) != 0)
  3859. rn = u_syscall3(SYS_READ_FILE, (int)DL_DATA_LIST, (int)buf,
  3860. (int)(sizeof(buf) - 1));
  3861. if (rn < 6 || memcmp(buf, "NBDL1\n", 6) != 0)
  3862. return;
  3863. buf[rn] = '\0';
  3864. p = buf + 6;
  3865. while (i < DL_MAX && *p) {
  3866. unsigned int state = meta_uint(&p);
  3867. unsigned int size = meta_uint(&p);
  3868. char name[DL_NAME_MAX], path[DL_PATH_MAX];
  3869. meta_str(&p, name, sizeof(name));
  3870. meta_str(&p, path, sizeof(path));
  3871. if ((state != DL_DONE && state != DL_FAILED) || !name[0])
  3872. continue;
  3873. dl_tab[i].used = 1;
  3874. dl_tab[i].state = (unsigned char)state;
  3875. dl_tab[i].size = size;
  3876. dl_tab[i].got = size;
  3877. dl_tab[i].total = size;
  3878. dl_tab[i].stamp = dl_stamp++;
  3879. s_copy(dl_tab[i].name, name, sizeof(dl_tab[i].name));
  3880. s_copy(dl_tab[i].path, path, sizeof(dl_tab[i].path));
  3881. i++;
  3882. }
  3883. }
  3884. static struct dl_ent *dl_active_ent(void)
  3885. {
  3886. return dl_active >= 0 ? &dl_tab[dl_active] : 0;
  3887. }
  3888. static int dl_percent(void)
  3889. {
  3890. struct dl_ent *e = dl_active_ent();
  3891. if (!e)
  3892. return -1;
  3893. if (e->state == DL_SAVING || e->state == DL_DONE)
  3894. return 100;
  3895. if (!e->total)
  3896. return -1;
  3897. if (e->got >= e->total)
  3898. return 100;
  3899. return (int)((unsigned long long)e->got * 100 / e->total);
  3900. }
  3901. static int dl_history_count(void)
  3902. {
  3903. int i, n = 0;
  3904. for (i = 0; i < DL_MAX; i++)
  3905. if (dl_tab[i].used && (dl_tab[i].state == DL_DONE ||
  3906. dl_tab[i].state == DL_FAILED))
  3907. n++;
  3908. return n;
  3909. }
  3910. static void dl_start_next(void);
  3911. static void dl_fail(int idx, const char *why, int stop_helper)
  3912. {
  3913. struct dl_ent *e = &dl_tab[idx];
  3914. char msg[DL_ERR_MAX + 24];
  3915. unsigned int n = 0;
  3916. e->state = DL_FAILED;
  3917. s_copy(e->err, why && why[0] ? why : "download failed",
  3918. sizeof(e->err));
  3919. dl_ensure_name(e);
  3920. e->got = 0;
  3921. if (stop_helper)
  3922. fetch_worker_stop(&dl_worker);
  3923. dl_active = -1;
  3924. s_append(msg, &n, "Download failed: ", sizeof(msg));
  3925. s_append(msg, &n, e->err, sizeof(msg));
  3926. set_status(msg, 1, 6000);
  3927. if (!dl_panel_open)
  3928. dl_unseen++;
  3929. dl_write_list();
  3930. ngui_invalidate(&ui);
  3931. dl_start_next();
  3932. }
  3933. static int dl_commit(int idx, const unsigned char *data, unsigned int len,
  3934. const char *ctype, int release_helper)
  3935. {
  3936. struct dl_ent *e = &dl_tab[idx];
  3937. char name[DL_NAME_MAX], path[DL_PATH_MAX];
  3938. int wr;
  3939. if (dl_prepare_dir() != 0) {
  3940. dl_fail(idx, "no writable download folder", release_helper);
  3941. return -1;
  3942. }
  3943. if (dl_make_path(e->url, ctype, name, sizeof(name), path,
  3944. sizeof(path)) != 0) {
  3945. dl_fail(idx, "cannot choose a file name", release_helper);
  3946. return -1;
  3947. }
  3948. if (release_helper) {
  3949. /* Keep the helper process, but drop its request files. */
  3950. fetch_worker_release(&dl_worker);
  3951. }
  3952. wr = u_syscall3(SYS_WRITE_FILE, (int)path, (int)data, (int)len);
  3953. if (wr < 0) {
  3954. dl_fail(idx, "cannot write the file", 0);
  3955. return -1;
  3956. }
  3957. e->state = DL_DONE;
  3958. e->size = len;
  3959. e->got = len;
  3960. e->total = len;
  3961. s_copy(e->name, name, sizeof(e->name));
  3962. s_copy(e->path, path, sizeof(e->path));
  3963. dl_active = -1;
  3964. if (!dl_panel_open)
  3965. dl_unseen++;
  3966. dl_write_list();
  3967. {
  3968. char msg[DL_PATH_MAX + 16];
  3969. unsigned int n = 0;
  3970. s_append(msg, &n, "Saved ", sizeof(msg));
  3971. s_append(msg, &n, e->path, sizeof(msg));
  3972. set_status(msg, 0, 5000);
  3973. }
  3974. ngui_invalidate(&ui);
  3975. dl_start_next();
  3976. return 0;
  3977. }
  3978. static void dl_local_read(int idx)
  3979. {
  3980. struct dl_ent *e = &dl_tab[idx];
  3981. struct sys_stat st;
  3982. unsigned char *buf;
  3983. int rn;
  3984. if (u_syscall2(SYS_FS_STAT, (int)e->url, (int)&st) != 0 || st.is_dir) {
  3985. dl_fail(idx, "not a readable file", 0);
  3986. return;
  3987. }
  3988. if (st.size > DL_FILE_MAX) {
  3989. dl_fail(idx, "file is over the 4 MB limit", 0);
  3990. return;
  3991. }
  3992. buf = (unsigned char *)malloc(st.size + 512);
  3993. if (!buf) {
  3994. dl_fail(idx, "out of memory", 0);
  3995. return;
  3996. }
  3997. rn = u_syscall3(SYS_READ_FILE, (int)e->url, (int)buf,
  3998. (int)(st.size ? st.size : 1));
  3999. if (rn < 0) {
  4000. free(buf);
  4001. dl_fail(idx, "cannot read the file", 0);
  4002. return;
  4003. }
  4004. e->got = e->total = (unsigned int)rn;
  4005. e->state = DL_SAVING;
  4006. dl_commit(idx, buf, (unsigned int)rn, "", 0);
  4007. free(buf);
  4008. }
  4009. static void dl_remote_read(int idx)
  4010. {
  4011. struct dl_ent *e = &dl_tab[idx];
  4012. unsigned char *buf;
  4013. int rn;
  4014. if (dl_worker.m.status < 200 || dl_worker.m.status >= 300) {
  4015. char why[32];
  4016. unsigned int n = 0;
  4017. s_append(why, &n, "HTTP ", sizeof(why));
  4018. s_append_dec(why, &n, (unsigned int)dl_worker.m.status,
  4019. sizeof(why));
  4020. dl_fail(idx, why, 1);
  4021. return;
  4022. }
  4023. if (dl_worker.m.trunc) {
  4024. dl_fail(idx, "file is over the 4 MB limit", 1);
  4025. return;
  4026. }
  4027. e->got = e->total = dl_worker.m.len;
  4028. e->state = DL_SAVING;
  4029. if (dl_worker.m.len > DL_FILE_MAX) {
  4030. dl_fail(idx, "file is over the 4 MB limit", 1);
  4031. return;
  4032. }
  4033. buf = (unsigned char *)malloc(dl_worker.m.len + 512);
  4034. if (!buf) {
  4035. dl_fail(idx, "out of memory", 1);
  4036. return;
  4037. }
  4038. rn = dl_worker.m.len ? u_syscall3(SYS_READ_FILE,
  4039. (int)dl_worker.body, (int)buf,
  4040. (int)dl_worker.m.len) : 0;
  4041. if (rn < 0 || (unsigned int)rn < dl_worker.m.len) {
  4042. free(buf);
  4043. dl_fail(idx, "cannot read the response body", 1);
  4044. return;
  4045. }
  4046. dl_commit(idx, buf, dl_worker.m.len, dl_worker.m.ctype, 1);
  4047. free(buf);
  4048. }
  4049. static void dl_read_progress(void)
  4050. {
  4051. static char buf[96];
  4052. char *p;
  4053. unsigned int seq;
  4054. struct dl_ent *e = dl_active_ent();
  4055. int rn;
  4056. if (!e || e->url[0] == '/')
  4057. return;
  4058. rn = u_syscall3(SYS_READ_FILE, (int)dl_worker.prog, (int)buf,
  4059. (int)(sizeof(buf) - 1));
  4060. if (rn <= 0)
  4061. return;
  4062. buf[rn] = '\0';
  4063. p = buf;
  4064. seq = meta_uint(&p);
  4065. if (seq != dl_worker.seq)
  4066. return;
  4067. e->got = meta_uint(&p);
  4068. e->total = meta_uint(&p);
  4069. ngui_invalidate(&ui);
  4070. }
  4071. static void dl_start_next(void)
  4072. {
  4073. int i, pick = -1;
  4074. struct dl_ent *e;
  4075. char err[64];
  4076. if (dl_active >= 0)
  4077. return;
  4078. for (i = 0; i < DL_MAX; i++) {
  4079. if (!dl_tab[i].used || dl_tab[i].state != DL_QUEUED)
  4080. continue;
  4081. if (pick < 0 || dl_tab[i].stamp < dl_tab[pick].stamp)
  4082. pick = i;
  4083. }
  4084. if (pick < 0)
  4085. return;
  4086. dl_active = pick;
  4087. e = &dl_tab[pick];
  4088. e->state = DL_RUNNING;
  4089. e->err[0] = '\0';
  4090. e->got = e->total = 0;
  4091. dl_last_prog_ms = u_ticks_ms();
  4092. ngui_invalidate(&ui);
  4093. if (e->url[0] == '/')
  4094. return; /* dl_poll reads local files */
  4095. err[0] = '\0';
  4096. if (fetch_worker_submit_req(&dl_worker, e->url, DL_FILE_MAX,
  4097. 0, 0, 0, 0, 0, 0, 0, 0, 1,
  4098. err, sizeof(err)) != 0) {
  4099. dl_fail(pick, err[0] ? err : "cannot start the download", 1);
  4100. }
  4101. }
  4102. static void dl_poll(void)
  4103. {
  4104. struct dl_ent *e;
  4105. unsigned int now;
  4106. char err[64];
  4107. int rv;
  4108. if (dl_active < 0) {
  4109. dl_start_next();
  4110. return;
  4111. }
  4112. e = &dl_tab[dl_active];
  4113. if (e->url[0] == '/') {
  4114. dl_local_read(dl_active);
  4115. return;
  4116. }
  4117. now = u_ticks_ms();
  4118. if ((unsigned int)(now - dl_last_prog_ms) >= 100) {
  4119. dl_last_prog_ms = now;
  4120. dl_read_progress();
  4121. }
  4122. err[0] = '\0';
  4123. rv = fetch_worker_poll(&dl_worker, err, sizeof(err));
  4124. if (rv == 0)
  4125. return;
  4126. if (rv < 0) {
  4127. dl_fail(dl_active, err[0] ? err : "download failed", 1);
  4128. return;
  4129. }
  4130. dl_remote_read(dl_active);
  4131. }
  4132. static int dl_queue(const char *url)
  4133. {
  4134. int i, pick = -1;
  4135. struct dl_ent *e;
  4136. if (!url || !url[0] || s_len(url) >= DL_URL_MAX) {
  4137. set_status("Cannot download: bad URL", 1, 4000);
  4138. return -1;
  4139. }
  4140. if (!is_http(url) && url[0] != '/') {
  4141. set_status("Cannot download this URL", 1, 4000);
  4142. return -1;
  4143. }
  4144. for (i = 0; i < DL_MAX; i++)
  4145. if (!dl_tab[i].used) {
  4146. pick = i;
  4147. break;
  4148. }
  4149. if (pick < 0) {
  4150. for (i = 0; i < DL_MAX; i++)
  4151. if (dl_tab[i].state == DL_DONE ||
  4152. dl_tab[i].state == DL_FAILED) {
  4153. if (pick < 0 ||
  4154. dl_tab[i].stamp < dl_tab[pick].stamp)
  4155. pick = i;
  4156. }
  4157. if (pick < 0) {
  4158. set_status("Download list is full", 1, 4000);
  4159. return -1;
  4160. }
  4161. }
  4162. e = &dl_tab[pick];
  4163. memset(e, 0, sizeof(*e));
  4164. e->used = 1;
  4165. e->state = DL_QUEUED;
  4166. e->stamp = dl_stamp++;
  4167. s_copy(e->url, url, sizeof(e->url));
  4168. dl_ensure_name(e);
  4169. set_status("Download started", 0, 3000);
  4170. ngui_invalidate(&ui);
  4171. dl_start_next();
  4172. return 0;
  4173. }
  4174. static void dl_clear_history(void)
  4175. {
  4176. int i;
  4177. for (i = 0; i < DL_MAX; i++)
  4178. if (dl_tab[i].used && (dl_tab[i].state == DL_DONE ||
  4179. dl_tab[i].state == DL_FAILED))
  4180. dl_tab[i].used = 0;
  4181. dl_unseen = 0;
  4182. dl_write_list();
  4183. ngui_invalidate(&ui);
  4184. }
  4185. /* fetch()/XHR through a helper: one request, the status and body come back
  4186. * whatever the HTTP status (a 401 is an answer, not a network error). */
  4187. static int js_worker_http(const char *method, const char *url,
  4188. const char *ctype, const char *body,
  4189. unsigned int body_len, struct js_http_resp *r,
  4190. char *err, int errcap)
  4191. {
  4192. struct fetch_worker *w = fetch_worker_alloc_fg();
  4193. unsigned char *plain;
  4194. int rv, tr = 0;
  4195. if (!w) {
  4196. s_copy(err, "network busy", (unsigned int)errcap);
  4197. return -1;
  4198. }
  4199. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  4200. body_len, 0, 0, 0, 0, 0, err,
  4201. (unsigned int)errcap) != 0) {
  4202. fetch_worker_release(w);
  4203. return -1;
  4204. }
  4205. fetch_wait_passive++;
  4206. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  4207. fetch_wait_passive--;
  4208. if (rv != 0) {
  4209. if (rv == FETCH_ABORT)
  4210. s_copy(err, "page is navigating", (unsigned int)errcap);
  4211. fetch_worker_release(w);
  4212. return -1;
  4213. }
  4214. r->status = w->m.status;
  4215. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  4216. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  4217. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  4218. if (!plain) {
  4219. fetch_worker_release(w);
  4220. s_copy(err, "out of memory", (unsigned int)errcap);
  4221. return -1;
  4222. }
  4223. if (w->m.len == 0) {
  4224. rv = 0; /* 204, an empty 200: no body file */
  4225. } else {
  4226. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  4227. image_io_buf, BR_PAGE_COMP_MAX,
  4228. &tr, err, (unsigned int)errcap);
  4229. }
  4230. fetch_worker_release(w);
  4231. if (rv < 0) {
  4232. free(plain);
  4233. return -1;
  4234. }
  4235. plain[rv] = '\0';
  4236. r->body = (char *)plain;
  4237. r->len = (unsigned int)rv;
  4238. return 0;
  4239. }
  4240. /* ---- HTTP / file fetch ---- */
  4241. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  4242. unsigned int *outlen, int *is_local, char *ctype,
  4243. unsigned int ctcap, char *final, unsigned int finalcap,
  4244. char *err, unsigned int errcap, int *truncated,
  4245. const char *post, unsigned int post_len)
  4246. {
  4247. unsigned char *buf;
  4248. unsigned int len;
  4249. int tr = 0;
  4250. int rv;
  4251. *out = 0;
  4252. *outlen = 0;
  4253. *truncated = 0;
  4254. if (final && finalcap)
  4255. final[0] = '\0';
  4256. if (ctype && ctcap)
  4257. ctype[0] = '\0';
  4258. if (url[0] == '/') {
  4259. char pathbuf[BR_URL_MAX];
  4260. const char *open_url = url;
  4261. unsigned int i = 0;
  4262. /* A local form GET keeps ?query in the address bar but the
  4263. * file lookup uses the path alone, like a real browser. */
  4264. while (url[i] && url[i] != '?' && url[i] != '#')
  4265. i++;
  4266. if (url[i]) {
  4267. s_copy(pathbuf, url, i + 1);
  4268. open_url = pathbuf;
  4269. }
  4270. buf = (unsigned char *)malloc(cap);
  4271. if (!buf) {
  4272. s_copy(err, "out of memory", errcap);
  4273. return -1;
  4274. }
  4275. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  4276. if (rv < 0) {
  4277. free(buf);
  4278. s_copy(err, "file not found", errcap);
  4279. return -1;
  4280. }
  4281. *out = buf;
  4282. *outlen = (unsigned int)rv;
  4283. *is_local = 1;
  4284. if (ctype)
  4285. s_copy(ctype, "text/html", ctcap);
  4286. if (final)
  4287. s_copy(final, url, finalcap);
  4288. if ((unsigned int)rv == cap)
  4289. *truncated = 1;
  4290. return 0;
  4291. }
  4292. buf = (unsigned char *)malloc(cap);
  4293. if (!buf) {
  4294. s_copy(err, "out of memory", errcap);
  4295. return -1;
  4296. }
  4297. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  4298. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  4299. if (rv == FETCH_ABORT) {
  4300. free(buf);
  4301. return FETCH_ABORT;
  4302. }
  4303. if (rv < 0) {
  4304. free(buf);
  4305. return -1;
  4306. }
  4307. len = (unsigned int)rv;
  4308. if (len == 0) {
  4309. free(buf);
  4310. s_copy(err, "empty response", errcap);
  4311. return -1;
  4312. }
  4313. if (ctype)
  4314. s_copy(ctype, fetch_meta.ctype, ctcap);
  4315. if (final && fetch_meta.final[0])
  4316. s_copy(final, fetch_meta.final, finalcap);
  4317. *is_local = 0;
  4318. *out = buf;
  4319. *outlen = len;
  4320. *truncated = tr;
  4321. return 0;
  4322. }
  4323. static unsigned int css_cache_hash(const char *s);
  4324. /* Remote fonts are cached under /share for the current boot like the
  4325. * stylesheets, as the raw response (a WOFF stays compressed). */
  4326. static int font_cache_count;
  4327. static void font_cache_path(const char *url, char *out, unsigned int cap)
  4328. {
  4329. unsigned int n = 0;
  4330. s_append(out, &n, "/share/" FONT_CACHE_PREFIX, cap);
  4331. s_append_dec(out, &n, css_cache_hash(url), cap);
  4332. }
  4333. static void font_cache_init(void)
  4334. {
  4335. struct sys_dirent d;
  4336. int i;
  4337. font_cache_count = 0;
  4338. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4339. (int)&d) == 1; i++)
  4340. if (starts_with(d.name, FONT_CACHE_PREFIX))
  4341. font_cache_count++;
  4342. }
  4343. /* Read one font file (local path, boot cache or network) into a fresh
  4344. * malloc'ed buffer. Returns its length, or -1. */
  4345. static int font_fetch(const char *abs, unsigned char **out)
  4346. {
  4347. unsigned char *buf;
  4348. char path[96];
  4349. int rv;
  4350. *out = 0;
  4351. buf = (unsigned char *)malloc(UFONT_MAX_FILE + 512u);
  4352. if (!buf)
  4353. return -1;
  4354. if (abs[0] == '/') {
  4355. struct sys_stat st;
  4356. /* FAT reads may write past the length: the 512 bytes of
  4357. * slack above cover the final partial sector. */
  4358. if (u_stat(abs, &st) != 0 || st.is_dir || st.size == 0 ||
  4359. st.size > UFONT_MAX_FILE) {
  4360. free(buf);
  4361. return -1;
  4362. }
  4363. rv = u_syscall3(SYS_READ_FILE, (int)abs, (int)buf,
  4364. (int)st.size);
  4365. if (rv != (int)st.size) {
  4366. free(buf);
  4367. return -1;
  4368. }
  4369. *out = buf;
  4370. return rv;
  4371. }
  4372. if (!is_http(abs)) {
  4373. free(buf);
  4374. return -1;
  4375. }
  4376. font_cache_path(abs, path, sizeof(path));
  4377. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)buf,
  4378. (int)UFONT_MAX_FILE);
  4379. if (rv > 0 && (unsigned int)rv < UFONT_MAX_FILE) {
  4380. *out = buf;
  4381. return rv;
  4382. }
  4383. {
  4384. char err[64];
  4385. int tr = 0;
  4386. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  4387. UFONT_MAX_FILE, image_io_buf,
  4388. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err,
  4389. sizeof(err));
  4390. /* An error page is not a font: never parse or cache it. */
  4391. if (rv > 0 && !tr && fetch_meta.status >= 300) {
  4392. snprintf(err, sizeof(err), "HTTP %d", fetch_meta.status);
  4393. rv = 0;
  4394. }
  4395. if (rv <= 0 || tr) {
  4396. u_puts("[font] failed: ");
  4397. u_puts(abs);
  4398. u_puts(rv <= 0 ? " " : " truncated ");
  4399. u_puts(rv <= 0 ? err : "");
  4400. u_putc('\n');
  4401. free(buf);
  4402. return -1;
  4403. }
  4404. }
  4405. if (font_cache_count < FONT_CACHE_MAX &&
  4406. u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, rv) >= 0)
  4407. font_cache_count++;
  4408. *out = buf;
  4409. return rv;
  4410. }
  4411. /* Open one @font-face entry: fetch, unwrap WOFF, parse into the ufont
  4412. * arena. A WOFF2 or CFF (OTTO) file is reported and left unloaded. */
  4413. static struct ufont_face *font_open_entry(int id)
  4414. {
  4415. const char *url = br_font_face_url(id);
  4416. const char *base = br_font_face_base(id);
  4417. char abs[BR_URL_MAX];
  4418. unsigned char *buf, *sfnt;
  4419. unsigned int slen = 0;
  4420. struct ufont_face *f = 0;
  4421. const char *why = 0;
  4422. int n;
  4423. if (!url || !url[0] ||
  4424. resolve_link(base && base[0] ? base : page_url, url, abs,
  4425. sizeof(abs)) != 0)
  4426. return 0;
  4427. n = font_fetch(abs, &buf);
  4428. if (n <= 0)
  4429. return 0;
  4430. sfnt = buf;
  4431. slen = (unsigned int)n;
  4432. if (ufont_is_woff2(buf, slen)) {
  4433. why = "WOFF2 not supported";
  4434. } else if (ufont_is_woff(buf, slen)) {
  4435. sfnt = ufont_woff_decode(buf, slen, &slen);
  4436. if (!sfnt)
  4437. why = "bad WOFF";
  4438. }
  4439. if (!why) {
  4440. f = ufont_face_open_mem(sfnt, slen);
  4441. if (!f)
  4442. why = (slen >= 4 && sfnt[0] == 'O' && sfnt[1] == 'T' &&
  4443. sfnt[2] == 'T' && sfnt[3] == 'O') ?
  4444. "CFF outlines not supported" :
  4445. "not a TrueType font or arena full";
  4446. }
  4447. if (sfnt && sfnt != buf)
  4448. free(sfnt);
  4449. free(buf);
  4450. u_puts(f ? "[font] loaded " : "[font] skipped ");
  4451. u_puts(br_font_face_family(id));
  4452. u_puts(": ");
  4453. u_puts(abs);
  4454. if (why) {
  4455. u_puts(" (");
  4456. u_puts(why);
  4457. u_putc(')');
  4458. }
  4459. u_putc('\n');
  4460. return f;
  4461. }
  4462. /* Distance of a face from the requested weight: 0 inside its range. A
  4463. * bold request prefers heavier faces and a normal one lighter faces, as
  4464. * the CSS font-matching steps do. */
  4465. static unsigned int font_weight_dist(const struct br_font_face_info *fi,
  4466. unsigned int want)
  4467. {
  4468. if (want >= fi->wmin && want <= fi->wmax)
  4469. return 0;
  4470. if (want > fi->wmax)
  4471. return (want - fi->wmax) * 2u + (want >= 500 ? 1u : 0u);
  4472. return (fi->wmin - want) * 2u + (want < 500 ? 1u : 0u);
  4473. }
  4474. /* Load the @font-face entries a font-family declaration named: per family
  4475. * the regular face first, then bold, italic and the rest, so a full arena
  4476. * drops the least common variants. Then precompute, for every family and
  4477. * (bold, italic) combination, the loaded face CSS font matching picks;
  4478. * layout reads only that table. A family with no loaded face keeps
  4479. * font_pick 0, and its text uses the built-in set. */
  4480. static void load_font_faces(void)
  4481. {
  4482. int n = br_font_face_count(), pass, id;
  4483. memset(font_faces, 0, sizeof(font_faces));
  4484. memset(font_pick, 0, sizeof(font_pick));
  4485. if (n > BR_MAX_FACES)
  4486. n = BR_MAX_FACES;
  4487. for (pass = 0; pass < 4; pass++) {
  4488. for (id = 1; id <= n; id++) {
  4489. struct br_font_face_info fi;
  4490. int cls;
  4491. if (br_font_face_info(id, &fi) != 0 || !fi.used)
  4492. continue;
  4493. if (!fi.italic && fi.wmin <= 400 && fi.wmax >= 400)
  4494. cls = 0;
  4495. else if (!fi.italic && fi.wmin <= 700 &&
  4496. fi.wmax >= 700)
  4497. cls = 1;
  4498. else if (fi.italic && fi.wmin <= 400 &&
  4499. fi.wmax >= 400)
  4500. cls = 2;
  4501. else
  4502. cls = 3;
  4503. if (cls == pass)
  4504. font_faces[id - 1] = font_open_entry(id);
  4505. }
  4506. }
  4507. for (id = 1; id <= n; id++) {
  4508. struct br_font_face_info fam;
  4509. int combo;
  4510. if (br_font_face_info(id, &fam) != 0 || fam.family_id != id)
  4511. continue;
  4512. for (combo = 0; combo < 4; combo++) {
  4513. unsigned int want = (combo & 2) ? 700u : 400u;
  4514. int italic = combo & 1, k, best = 0;
  4515. unsigned int best_score = 0;
  4516. for (k = 1; k <= n; k++) {
  4517. struct br_font_face_info fi;
  4518. unsigned int score;
  4519. if (!font_faces[k - 1] ||
  4520. br_font_face_info(k, &fi) != 0 ||
  4521. fi.family_id != id)
  4522. continue;
  4523. score = font_weight_dist(&fi, want) +
  4524. ((fi.italic != 0) != (italic != 0) ?
  4525. 100000u : 0u);
  4526. if (!best || score < best_score) {
  4527. best = k;
  4528. best_score = score;
  4529. }
  4530. }
  4531. font_pick[id - 1][combo] = (unsigned char)best;
  4532. }
  4533. }
  4534. }
  4535. /* Remote scripts are cached under /share for the current boot, like the
  4536. * stylesheet cache, so reloads and later visits skip the network. */
  4537. static int script_cache_count;
  4538. static unsigned int script_cache_hash(const char *s)
  4539. {
  4540. unsigned int h = 2166136261u;
  4541. while (*s) {
  4542. h ^= (unsigned char)*s++;
  4543. h *= 16777619u;
  4544. }
  4545. return h;
  4546. }
  4547. static void script_cache_path(const char *url, char *out, unsigned int cap)
  4548. {
  4549. unsigned int n = 0;
  4550. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  4551. s_append_dec(out, &n, script_cache_hash(url), cap);
  4552. }
  4553. static void script_cache_clear(void)
  4554. {
  4555. struct sys_dirent d;
  4556. char path[96];
  4557. for (;;) {
  4558. int i, found = 0;
  4559. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4560. (int)&d) == 1; i++) {
  4561. unsigned int n = 0;
  4562. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  4563. continue;
  4564. s_append(path, &n, "/share/", sizeof(path));
  4565. s_append(path, &n, d.name, sizeof(path));
  4566. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  4567. return;
  4568. found = 1;
  4569. break;
  4570. }
  4571. if (!found)
  4572. break;
  4573. }
  4574. script_cache_count = 0;
  4575. }
  4576. static void script_cache_init(void)
  4577. {
  4578. struct sys_dirent d;
  4579. int i, count = 0;
  4580. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4581. (int)&d) == 1; i++)
  4582. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  4583. count++;
  4584. if (count >= SCRIPT_CACHE_MAX) {
  4585. script_cache_clear();
  4586. return;
  4587. }
  4588. script_cache_count = count;
  4589. }
  4590. static int script_cache_get(const char *url, unsigned char **out,
  4591. unsigned int *outlen)
  4592. {
  4593. char path[96];
  4594. struct sys_stat st;
  4595. unsigned char *buf;
  4596. int rn;
  4597. script_cache_path(url, path, sizeof(path));
  4598. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  4599. st.size >= SCRIPT_CACHE_FILE_MAX)
  4600. return 0;
  4601. buf = (unsigned char *)malloc(st.size + 1);
  4602. if (!buf)
  4603. return 0;
  4604. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  4605. if (rn != (int)st.size) {
  4606. free(buf);
  4607. return 0;
  4608. }
  4609. buf[st.size] = '\0';
  4610. *out = buf;
  4611. *outlen = st.size;
  4612. return 1;
  4613. }
  4614. static void script_cache_put(const char *url, const unsigned char *data,
  4615. unsigned int len)
  4616. {
  4617. char path[96];
  4618. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  4619. len >= SCRIPT_CACHE_FILE_MAX)
  4620. return;
  4621. script_cache_path(url, path, sizeof(path));
  4622. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  4623. (int)len) >= 0)
  4624. script_cache_count++;
  4625. }
  4626. static int script_cache_has(const char *url)
  4627. {
  4628. char path[96];
  4629. struct sys_stat st;
  4630. script_cache_path(url, path, sizeof(path));
  4631. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  4632. st.size < SCRIPT_CACHE_FILE_MAX;
  4633. }
  4634. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  4635. static int fetch_script_text(const char *url, unsigned char **out,
  4636. unsigned int *outlen, char *err,
  4637. unsigned int errcap)
  4638. {
  4639. unsigned char *buf;
  4640. unsigned int len;
  4641. int local, truncated = 0;
  4642. char ctype[64], final[BR_URL_MAX];
  4643. int rv;
  4644. *out = 0;
  4645. *outlen = 0;
  4646. if (url[0] != '/' && script_cache_get(url, out, outlen))
  4647. return 0;
  4648. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  4649. sizeof(ctype), final, sizeof(final), err, errcap,
  4650. &truncated, 0, 0);
  4651. if (rv != 0)
  4652. return rv;
  4653. if (truncated || len >= BR_SCRIPT_MAX) {
  4654. free(buf);
  4655. s_copy(err, "script is too large", errcap);
  4656. return -1;
  4657. }
  4658. buf[len] = '\0';
  4659. if (!local)
  4660. script_cache_put(url, buf, len);
  4661. *out = buf;
  4662. *outlen = len;
  4663. return 0;
  4664. }
  4665. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  4666. * the heap, so images must not allocate their file body from it as well. */
  4667. static int fetch_image(const char *url, unsigned int cap,
  4668. unsigned char **out, unsigned int *outlen,
  4669. char *err, unsigned int errcap)
  4670. {
  4671. unsigned int len;
  4672. int tr = 0;
  4673. int rv;
  4674. *out = 0;
  4675. *outlen = 0;
  4676. if (cap > BR_IMG_FILE_MAX)
  4677. cap = BR_IMG_FILE_MAX;
  4678. if (url[0] == '/') {
  4679. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  4680. (int)cap);
  4681. if (rv < 0) {
  4682. s_copy(err, "file not found", errcap);
  4683. return -1;
  4684. }
  4685. *out = image_file_buf;
  4686. *outlen = (unsigned int)rv;
  4687. return 0;
  4688. }
  4689. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  4690. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  4691. if (rv == FETCH_ABORT)
  4692. return FETCH_ABORT;
  4693. if (rv < 0)
  4694. return -1;
  4695. len = (unsigned int)rv;
  4696. if (len == 0) {
  4697. s_copy(err, "empty image", errcap);
  4698. return -1;
  4699. }
  4700. *out = image_file_buf;
  4701. *outlen = len;
  4702. return 0;
  4703. }
  4704. /* Remote stylesheets are immutable enough for the current boot: keep
  4705. * successful responses under /share so a reload, a second visit or a fresh
  4706. * browser launch does not fetch the same five sheets over the network again.
  4707. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  4708. static int css_cache_count;
  4709. static unsigned int css_cache_hash(const char *s)
  4710. {
  4711. unsigned int h = 2166136261u;
  4712. while (*s) {
  4713. h ^= (unsigned char)*s++;
  4714. h *= 16777619u;
  4715. }
  4716. return h;
  4717. }
  4718. static void css_cache_path(const char *url, char *out, unsigned int cap)
  4719. {
  4720. unsigned int n = 0;
  4721. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  4722. s_append_dec(out, &n, css_cache_hash(url), cap);
  4723. }
  4724. static void css_cache_clear(void)
  4725. {
  4726. struct sys_dirent d;
  4727. char path[96];
  4728. for (;;) {
  4729. int i, found = 0;
  4730. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4731. (int)&d) == 1; i++) {
  4732. unsigned int n = 0;
  4733. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  4734. continue;
  4735. s_append(path, &n, "/share/", sizeof(path));
  4736. s_append(path, &n, d.name, sizeof(path));
  4737. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  4738. return;
  4739. found = 1;
  4740. break;
  4741. }
  4742. if (!found)
  4743. break;
  4744. }
  4745. css_cache_count = 0;
  4746. }
  4747. static void css_cache_init(void)
  4748. {
  4749. struct sys_dirent d;
  4750. int i, count = 0;
  4751. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4752. (int)&d) == 1; i++)
  4753. if (starts_with(d.name, CSS_CACHE_PREFIX))
  4754. count++;
  4755. if (count >= CSS_CACHE_MAX) {
  4756. css_cache_clear();
  4757. return;
  4758. }
  4759. css_cache_count = count;
  4760. }
  4761. static int css_cache_get(const char *url, unsigned char **out,
  4762. unsigned int *outlen)
  4763. {
  4764. char path[96];
  4765. int rn;
  4766. css_cache_path(url, path, sizeof(path));
  4767. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  4768. (int)CSS_CACHE_FILE_MAX);
  4769. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  4770. return 0;
  4771. *out = image_io_buf;
  4772. *outlen = (unsigned int)rn;
  4773. return 1;
  4774. }
  4775. static void css_cache_put(const char *url, const unsigned char *data,
  4776. unsigned int len)
  4777. {
  4778. char path[96];
  4779. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  4780. len >= CSS_CACHE_FILE_MAX)
  4781. return;
  4782. css_cache_path(url, path, sizeof(path));
  4783. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  4784. (int)len) >= 0)
  4785. css_cache_count++;
  4786. }
  4787. static int css_cache_has(const char *url)
  4788. {
  4789. char path[96];
  4790. struct sys_stat st;
  4791. css_cache_path(url, path, sizeof(path));
  4792. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  4793. st.size < CSS_CACHE_FILE_MAX;
  4794. }
  4795. /* Read one stylesheet into the shared static buffer. CSS is parsed
  4796. * immediately, so it does not need the page heap; this leaves the heap for
  4797. * the 2 MB page body, the rules and the scaled image bitmaps. */
  4798. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  4799. char *err, unsigned int errcap)
  4800. {
  4801. unsigned int len;
  4802. int tr = 0;
  4803. int rv;
  4804. *out = 0;
  4805. *outlen = 0;
  4806. if (url[0] == '/') {
  4807. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  4808. (int)BR_CSS_MAX);
  4809. if (rv < 0) {
  4810. s_copy(err, "stylesheet not found", errcap);
  4811. return -1;
  4812. }
  4813. *out = image_io_buf;
  4814. *outlen = (unsigned int)rv;
  4815. return 0;
  4816. }
  4817. if (css_cache_get(url, out, outlen))
  4818. return 0;
  4819. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  4820. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  4821. &fetch_meta, &tr, err, errcap);
  4822. if (rv == FETCH_ABORT)
  4823. return FETCH_ABORT;
  4824. if (rv < 0)
  4825. return -1;
  4826. len = (unsigned int)rv;
  4827. if (len == 0) {
  4828. s_copy(err, "empty stylesheet", errcap);
  4829. return -1;
  4830. }
  4831. *out = image_io_buf;
  4832. *outlen = len;
  4833. css_cache_put(url, image_io_buf, len);
  4834. return 0;
  4835. }
  4836. static void redraw_now(void);
  4837. static char error_page[1024];
  4838. static void show_error(const char *title, const char *detail)
  4839. {
  4840. char *page = error_page;
  4841. unsigned int n = 0;
  4842. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  4843. s_append(page, &n, title, sizeof(error_page));
  4844. s_append(page, &n, "</h2><p>", sizeof(error_page));
  4845. {
  4846. const char *p = detail;
  4847. while (*p && n + 1 < sizeof(error_page)) {
  4848. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  4849. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  4850. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  4851. else page[n++] = *p;
  4852. p++;
  4853. }
  4854. }
  4855. page[n] = '\0';
  4856. s_append(page, &n, "</p><p>", sizeof(error_page));
  4857. s_append(page, &n, page_url, sizeof(error_page));
  4858. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  4859. sizeof(error_page));
  4860. br_parse(&doc, page, n);
  4861. layout_valid = 0;
  4862. preload_active = 0;
  4863. preload_pending = 0;
  4864. preload_wait = 0;
  4865. fetch_workers_cancel_busy();
  4866. s_copy(page_title, title, sizeof(page_title));
  4867. page_loading = 0;
  4868. set_status(title, 1, 0);
  4869. ngui_invalidate(&ui);
  4870. }
  4871. static int decode_direct_image(const unsigned char *data, unsigned int len,
  4872. unsigned int node)
  4873. {
  4874. if (image_count >= BR_MAX_IMAGES)
  4875. return -1;
  4876. if (decode_image_data(data, len, &images[0], 0, 0, 0, 0) != 0)
  4877. return -1;
  4878. doc.nodes[node].img_index = 0;
  4879. image_count = 1;
  4880. return 0;
  4881. }
  4882. static int ancestor_is(unsigned int node, unsigned int tag)
  4883. {
  4884. unsigned int p = doc.nodes[node].parent;
  4885. while (p) {
  4886. if (doc.nodes[p].tag == tag)
  4887. return 1;
  4888. p = doc.nodes[p].parent;
  4889. }
  4890. return 0;
  4891. }
  4892. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  4893. * parallel but parsed in document order, so the cascade is unchanged. */
  4894. static int load_stylesheets(void)
  4895. {
  4896. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  4897. static unsigned char remote[BR_MAX_SHEETS];
  4898. struct fetch_worker *slot[BR_MAX_SHEETS];
  4899. unsigned int i, n = 0, next = 0, k;
  4900. char err[64];
  4901. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  4902. struct br_node *nd = &doc.nodes[i];
  4903. const char *rel, *href;
  4904. char url[BR_URL_MAX];
  4905. int dup = 0;
  4906. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  4907. continue;
  4908. rel = br_rel(&doc, i);
  4909. if (!contains_ci(rel, "stylesheet"))
  4910. continue;
  4911. href = br_href(&doc, i);
  4912. if (!href[0])
  4913. continue;
  4914. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  4915. continue;
  4916. for (k = 0; k < n; k++)
  4917. if (s_eq(urls[k], url)) {
  4918. dup = 1;
  4919. break;
  4920. }
  4921. if (dup)
  4922. continue;
  4923. s_copy(urls[n], url, BR_URL_MAX);
  4924. remote[n] = url[0] != '/' && !css_cache_has(url);
  4925. n++;
  4926. }
  4927. for (i = 0; i < BR_MAX_SHEETS; i++)
  4928. slot[i] = 0;
  4929. /* Start as many remote sheets as there are free workers. */
  4930. for (; next < n; next++) {
  4931. struct fetch_worker *w;
  4932. if (!remote[next])
  4933. continue;
  4934. w = fetch_worker_alloc();
  4935. if (!w)
  4936. break;
  4937. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  4938. err, sizeof(err)) != 0) {
  4939. fetch_worker_release(w);
  4940. remote[next] = 0;
  4941. continue;
  4942. }
  4943. slot[next] = w;
  4944. }
  4945. for (i = 0; i < n; i++) {
  4946. unsigned char *data = 0;
  4947. unsigned int len = 0;
  4948. int rv;
  4949. if (!remote[i]) {
  4950. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  4951. if (rv == FETCH_ABORT) {
  4952. fetch_workers_stop_all();
  4953. return FETCH_ABORT;
  4954. }
  4955. if (rv != 0 || !len)
  4956. continue;
  4957. } else {
  4958. struct fetch_worker *w = slot[i];
  4959. int tr = 0;
  4960. if (!w) {
  4961. w = fetch_worker_alloc();
  4962. if (!w) {
  4963. rv = -1;
  4964. goto css_failed;
  4965. }
  4966. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  4967. 0, 0, 0, 0, err,
  4968. sizeof(err)) != 0) {
  4969. fetch_worker_release(w);
  4970. remote[i] = 0;
  4971. if (i == next)
  4972. next++;
  4973. continue;
  4974. }
  4975. slot[i] = w;
  4976. if (i == next)
  4977. next++;
  4978. }
  4979. rv = fetch_worker_wait(w, err, sizeof(err));
  4980. if (rv == FETCH_ABORT) {
  4981. fetch_workers_stop_all();
  4982. return FETCH_ABORT;
  4983. }
  4984. if (rv == 0)
  4985. rv = fetch_worker_read_body(w, image_io_buf,
  4986. BR_CSS_MAX,
  4987. image_io_buf + BR_CSS_MAX,
  4988. BR_CSS_COMP_MAX, &tr,
  4989. err, sizeof(err));
  4990. else
  4991. rv = -1;
  4992. fetch_worker_release(w);
  4993. slot[i] = 0;
  4994. /* Refill the worker window before parsing this sheet. */
  4995. for (; next < n; next++) {
  4996. struct fetch_worker *nw;
  4997. if (!remote[next])
  4998. continue;
  4999. nw = fetch_worker_alloc();
  5000. if (!nw)
  5001. break;
  5002. if (fetch_worker_submit(nw, urls[next],
  5003. BR_CSS_MAX, 0, 0, 0, 0,
  5004. err, sizeof(err)) != 0) {
  5005. fetch_worker_release(nw);
  5006. remote[next] = 0;
  5007. continue;
  5008. }
  5009. slot[next] = nw;
  5010. }
  5011. css_failed:
  5012. if (rv <= 0) {
  5013. /* One synchronous retry: a dropped sheet leaves the
  5014. * whole page unstyled (seen intermittently on
  5015. * arstechnica's CDN). */
  5016. u_puts("[css] retry ");
  5017. u_puts(urls[i]);
  5018. u_puts(": ");
  5019. u_puts(err[0] ? err : "no worker/empty body");
  5020. u_putc('\n');
  5021. err[0] = '\0';
  5022. rv = fetch_css(urls[i], &data, &len, err,
  5023. sizeof(err));
  5024. if (rv == FETCH_ABORT) {
  5025. fetch_workers_stop_all();
  5026. return FETCH_ABORT;
  5027. }
  5028. if (rv != 0 || !len) {
  5029. u_puts("[css] failed: ");
  5030. u_puts(err);
  5031. u_putc('\n');
  5032. continue;
  5033. }
  5034. } else {
  5035. len = (unsigned int)rv;
  5036. data = image_io_buf;
  5037. css_cache_put(urls[i], data, len);
  5038. }
  5039. }
  5040. if (len) {
  5041. br_set_font_base(urls[i]);
  5042. br_parse_css_text(&doc, (const char *)data, len);
  5043. }
  5044. }
  5045. br_set_font_base(page_url);
  5046. br_parse_inline_css(&doc);
  5047. load_font_faces();
  5048. br_reset_styles(&doc);
  5049. layout_valid = 0;
  5050. return 0;
  5051. }
  5052. static void preload_begin(void)
  5053. {
  5054. preload_active = 1;
  5055. preload_pending = 0;
  5056. preload_wait = 1;
  5057. preload_max_jobs = FETCH_WORKERS;
  5058. preload_node = 0;
  5059. preload_loaded = 0;
  5060. preload_scroll = 0;
  5061. img_stat_start = u_ticks_ms();
  5062. img_stat_wall = 0;
  5063. img_stat_net = img_stat_open = img_stat_first = 0;
  5064. img_stat_io = img_stat_dec = img_stat_scale = 0;
  5065. img_stat_paint = img_stat_reflow = 0;
  5066. img_stat_bytes = 0;
  5067. img_stat_n = 0;
  5068. img_stat_log_len = 0;
  5069. if (img_stat_log[0])
  5070. img_stat_log[0] = '\0';
  5071. img_repaint_ms = 0;
  5072. img_repaint_pending = 0;
  5073. }
  5074. /* Styles are computed top-down during layout, but images inside a hidden
  5075. * menu/carousel are never visited and keep img_top == 0. Without this check
  5076. * the preloader walks the DOM in node order and spends the whole image
  5077. * budget on logos and off-canvas thumbnails the reader cannot see. */
  5078. static struct br_style base_style(void);
  5079. static int node_hidden(unsigned int node)
  5080. {
  5081. unsigned int path[32], n = 0, p = node, i;
  5082. struct br_style st, parent;
  5083. while (p && n < sizeof(path) / sizeof(path[0])) {
  5084. path[n++] = p;
  5085. p = doc.nodes[p].parent;
  5086. }
  5087. /* Node 0 is the <html> element when the page starts with one: it
  5088. * is an ancestor too. Styles are cached per node, so the chain
  5089. * must start from the same base as style_for_node(); seeding it
  5090. * with a zeroed style left <body> cached with black text and no
  5091. * line-height once an image job ran (docs.cloudron.io). */
  5092. if (!p && n && n < sizeof(path) / sizeof(path[0]) &&
  5093. doc.nodes[0].type == BR_NODE_ELEM &&
  5094. doc.nodes[0].tag == BR_TAG_HTML &&
  5095. !(doc.nodes[path[n - 1]].flags & BR_NODE_DETACHED))
  5096. path[n++] = 0;
  5097. parent = base_style();
  5098. for (i = n; i > 0; i--) {
  5099. br_style_for(&doc, path[i - 1], &parent, &st);
  5100. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  5101. st.opacity_hidden)
  5102. return 1;
  5103. parent = st;
  5104. }
  5105. return 0;
  5106. }
  5107. static struct br_style base_style(void);
  5108. static int style_width_px(const struct br_style *st, int base);
  5109. static int style_height_px(const struct br_style *st, int base);
  5110. static void style_for_node(unsigned int node, struct br_style *out)
  5111. {
  5112. unsigned int p = doc.nodes[node].parent;
  5113. struct br_style parent;
  5114. /* Parent index 0 is ambiguous: it is the <html> element when the page
  5115. * starts with one (see root_style()), but also the parent field of a
  5116. * detached subtree root. */
  5117. if (p || (node != 0 && doc.nodes[0].type == BR_NODE_ELEM &&
  5118. doc.nodes[0].tag == BR_TAG_HTML &&
  5119. !(doc.nodes[node].flags & BR_NODE_DETACHED))) {
  5120. style_for_node(p, &parent);
  5121. br_style_for(&doc, node, &parent, out);
  5122. } else {
  5123. parent = base_style();
  5124. br_style_for(&doc, node, &parent, out);
  5125. }
  5126. }
  5127. /* ---- parallel image preloading ---- *
  5128. *
  5129. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  5130. * preload_step() only starts jobs and harvests completed ones; the browser
  5131. * main loop keeps drawing between calls, instead of blocking on one fetch.
  5132. */
  5133. static int preload_active_jobs(void)
  5134. {
  5135. int i, n = 0;
  5136. for (i = 0; i < FETCH_WORKERS; i++)
  5137. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  5138. n++;
  5139. return n;
  5140. }
  5141. static void preload_job_error(struct fetch_worker *w)
  5142. {
  5143. if (w->node < doc.nnode) {
  5144. if (w->bg)
  5145. doc.nodes[w->node].bg_img_index = -2;
  5146. else
  5147. doc.nodes[w->node].img_index = -2;
  5148. image_repaint();
  5149. }
  5150. }
  5151. /* Is the image's box anywhere near the visible page? A decode below the
  5152. * fold changes the layout (scroll extent) but not a single on-screen pixel,
  5153. * so it does not need a repaint. top/h come from the last layout; treat an
  5154. * unknown box as visible to stay safe. */
  5155. static int image_preload_visible(unsigned int node, int bg)
  5156. {
  5157. int top, h, scroll;
  5158. if (node >= BR_MAX_NODES || node >= doc.nnode || page_rect.h <= 0)
  5159. return 1;
  5160. if (bg) {
  5161. top = (int)block_top[node];
  5162. h = (int)block_h[node];
  5163. } else {
  5164. top = (int)img_top[node];
  5165. h = (int)img_h[node];
  5166. }
  5167. if (!top && !h)
  5168. return 1;
  5169. scroll = (int)page_scroll.offset;
  5170. if (top > scroll + page_rect.h + 160)
  5171. return 0;
  5172. if (top + h + 160 < scroll)
  5173. return 0;
  5174. return 1;
  5175. }
  5176. /* Upper bounds for the bitmap an <img> will paint. Zero means "unbounded";
  5177. * decode_image_data applies one scale to both axes so the aspect ratio is
  5178. * preserved. This is what keeps a 1200x800 photo that CSS paints at 400 px
  5179. * from being decoded and box-filtered to the 1000 px layout cap first. */
  5180. static void image_fit_size(unsigned int node, int *out_w, int *out_h)
  5181. {
  5182. struct br_style st;
  5183. struct br_node *nd;
  5184. unsigned int p;
  5185. int cw, w = 0, h = 0;
  5186. *out_w = *out_h = 0;
  5187. if (node >= doc.nnode)
  5188. return;
  5189. nd = &doc.nodes[node];
  5190. style_for_node(node, &st);
  5191. cw = page_rect.w > 24 ? page_rect.w - 24 : 0;
  5192. p = doc.nodes[node].parent;
  5193. if (p && p < BR_MAX_NODES && layout_boxes[p].valid &&
  5194. layout_boxes[p].w > 0 && layout_boxes[p].w < cw)
  5195. cw = layout_boxes[p].w;
  5196. if (st.width_kind)
  5197. w = style_width_px(&st, cw);
  5198. else if (nd->width_attr)
  5199. w = nd->width_pct ? cw * (int)nd->width_attr / 100 :
  5200. (int)nd->width_attr;
  5201. if (st.height_kind)
  5202. h = style_height_px(&st, cw);
  5203. else if (nd->height_attr)
  5204. h = nd->height_pct ? cw * (int)nd->height_attr / 100 :
  5205. (int)nd->height_attr;
  5206. if (st.max_width_kind) {
  5207. int mw = st.max_width_kind == 3 ?
  5208. cw * st.max_width_calc_pct / 100 +
  5209. st.max_width_calc_px :
  5210. st.max_width_kind == 2 ?
  5211. cw * (int)st.max_width / 100 :
  5212. (int)st.max_width;
  5213. if (mw > 0 && (w == 0 || w > mw))
  5214. w = mw;
  5215. }
  5216. if (st.max_height_kind) {
  5217. int mh = st.max_height_kind == 3 ?
  5218. cw * st.max_height_calc_pct / 100 +
  5219. st.max_height_calc_px :
  5220. st.max_height_kind == 2 ?
  5221. cw * (int)st.max_height / 100 :
  5222. (int)st.max_height;
  5223. if (mh > 0 && (h == 0 || h > mh))
  5224. h = mh;
  5225. }
  5226. if (w > BR_IMG_LAYOUT_W)
  5227. w = BR_IMG_LAYOUT_W;
  5228. if (h > 4096)
  5229. h = 4096;
  5230. if (w < 0)
  5231. w = 0;
  5232. if (h < 0)
  5233. h = 0;
  5234. *out_w = w;
  5235. *out_h = h;
  5236. }
  5237. static void preload_accept_image(unsigned int node, int bg, const char *url)
  5238. {
  5239. /* An <img> bitmap only depends on its URL, so the next <img> with the
  5240. * same source reuses it (heise repeats one comment icon 85 times).
  5241. * Backgrounds are scaled to their box and are not shared. */
  5242. images[image_count].url_hash =
  5243. !bg && url ? script_cache_hash(url) | 1u : 0;
  5244. if (bg)
  5245. doc.nodes[node].bg_img_index = (short)image_count;
  5246. else
  5247. doc.nodes[node].img_index = (short)image_count;
  5248. image_count++;
  5249. preload_loaded++;
  5250. /* A background bitmap never changes its box, so keep the (expensive)
  5251. * measured layout and only repaint the pixels. */
  5252. if (bg)
  5253. page_cache_valid = 0;
  5254. else
  5255. layout_valid = 0;
  5256. if (image_preload_visible(node, bg))
  5257. image_repaint();
  5258. }
  5259. /* Install a bitmap decoded by the fetch helper. The helper already applied
  5260. * the display bounds (and the JPEG reduced IDCT), so this is a read + copy
  5261. * on the UI thread instead of a decode. */
  5262. static int preload_store_helper(unsigned int node, int bg,
  5263. unsigned char *px, unsigned int pxlen,
  5264. unsigned int dw, unsigned int dh,
  5265. int alpha, unsigned int nw, unsigned int nh,
  5266. const char *url)
  5267. {
  5268. struct br_image *bi;
  5269. unsigned int npx;
  5270. if (image_count >= BR_MAX_IMAGES || !px || !dw || !dh ||
  5271. dw > 4096 || dh > 4096) {
  5272. free(px);
  5273. return -1;
  5274. }
  5275. npx = dw * dh;
  5276. if (image_pixels + npx > BR_IMG_PIXEL_BUDGET ||
  5277. pxlen < npx * 2u + (alpha ? npx : 0)) {
  5278. free(px);
  5279. return -1;
  5280. }
  5281. bi = &images[image_count];
  5282. bi->img.format = 0;
  5283. bi->img.w = dw;
  5284. bi->img.h = dh;
  5285. bi->img.px = (unsigned short *)px;
  5286. bi->img.alpha = alpha ? px + npx * 2u : 0;
  5287. bi->img.flags = 0;
  5288. bi->native_w = nw ? (int)nw : (int)dw;
  5289. bi->native_h = nh ? (int)nh : (int)dh;
  5290. bi->state = 1;
  5291. image_pixels += npx;
  5292. preload_accept_image(node, bg, url);
  5293. return 0;
  5294. }
  5295. static void preload_decode(unsigned int node, int bg,
  5296. const unsigned char *data, unsigned int len,
  5297. const char *url)
  5298. {
  5299. int fit_w = 0, fit_h = 0;
  5300. if (image_count >= BR_MAX_IMAGES) {
  5301. if (bg)
  5302. doc.nodes[node].bg_img_index = -2;
  5303. else
  5304. doc.nodes[node].img_index = -2;
  5305. return;
  5306. }
  5307. if (!bg)
  5308. image_fit_size(node, &fit_w, &fit_h);
  5309. if (decode_image_data(data, len, &images[image_count],
  5310. bg && node < BR_MAX_NODES &&
  5311. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  5312. bg && node < BR_MAX_NODES &&
  5313. layout_boxes[node].valid ? layout_boxes[node].h : 0,
  5314. fit_w, fit_h) == 0) {
  5315. preload_accept_image(node, bg, url);
  5316. } else {
  5317. if (bg)
  5318. doc.nodes[node].bg_img_index = -2;
  5319. else
  5320. doc.nodes[node].img_index = -2;
  5321. layout_valid = 0;
  5322. }
  5323. if (image_preload_visible(node, bg))
  5324. image_repaint();
  5325. }
  5326. /* ---- data: URLs ----
  5327. *
  5328. * `data:[<type>][;base64],<payload>` decoded to bytes from the page heap
  5329. * (the caller frees them). The payload is percent-decoded, then base64-
  5330. * decoded when the header says so. Infima's menu chevron and many icon
  5331. * fonts' fallbacks are inline SVGs written this way. */
  5332. static int b64_val(int c)
  5333. {
  5334. if (c >= 'A' && c <= 'Z') return c - 'A';
  5335. if (c >= 'a' && c <= 'z') return c - 'a' + 26;
  5336. if (c >= '0' && c <= '9') return c - '0' + 52;
  5337. if (c == '+' || c == '-') return 62;
  5338. if (c == '/' || c == '_') return 63;
  5339. return -1;
  5340. }
  5341. static int hex_val(int c)
  5342. {
  5343. if (c >= '0' && c <= '9') return c - '0';
  5344. c |= 32;
  5345. if (c >= 'a' && c <= 'f') return c - 'a' + 10;
  5346. return -1;
  5347. }
  5348. static int data_url_decode(const char *url, unsigned char **out,
  5349. unsigned int *out_len)
  5350. {
  5351. const char *comma, *p;
  5352. unsigned int n = 0, len, i;
  5353. unsigned char *buf;
  5354. int base64 = 0;
  5355. *out = 0;
  5356. *out_len = 0;
  5357. if (!starts_with(url, "data:"))
  5358. return -1;
  5359. comma = url + 5;
  5360. while (*comma && *comma != ',')
  5361. comma++;
  5362. if (!*comma)
  5363. return -1;
  5364. for (p = url + 5; p + 7 <= comma; p++)
  5365. if (!strncmp(p, ";base64", 7))
  5366. base64 = 1;
  5367. len = s_len(comma + 1);
  5368. buf = (unsigned char *)malloc(len + 1);
  5369. if (!buf)
  5370. return -1;
  5371. for (i = 0, p = comma + 1; i < len; i++) {
  5372. int c = (unsigned char)p[i];
  5373. if (c == '%' && i + 2 < len &&
  5374. hex_val(p[i + 1]) >= 0 && hex_val(p[i + 2]) >= 0) {
  5375. c = hex_val(p[i + 1]) * 16 + hex_val(p[i + 2]);
  5376. i += 2;
  5377. }
  5378. buf[n++] = (unsigned char)c;
  5379. }
  5380. if (base64) {
  5381. unsigned int acc = 0, o = 0;
  5382. int bits = 0;
  5383. for (i = 0; i < n; i++) {
  5384. int v = b64_val(buf[i]);
  5385. if (v < 0)
  5386. continue; /* padding, whitespace */
  5387. acc = (acc << 6) | (unsigned int)v;
  5388. bits += 6;
  5389. if (bits >= 8) {
  5390. bits -= 8;
  5391. buf[o++] = (unsigned char)(acc >> bits);
  5392. }
  5393. }
  5394. n = o;
  5395. }
  5396. buf[n] = 0;
  5397. *out = buf;
  5398. *out_len = n;
  5399. return 0;
  5400. }
  5401. static unsigned int data_img_key(const char *url, int w, int h)
  5402. {
  5403. return (script_cache_hash(url) ^ ((unsigned int)w * 2654435761u) ^
  5404. ((unsigned int)h * 40503u)) | 1u;
  5405. }
  5406. /* The image index of a data: URL decoded for a w x h box (an SVG is
  5407. * rasterized at that size), decoding it on first use; -1 on failure.
  5408. * Decoded bitmaps are found again through url_hash, which is distinct
  5409. * from the <img> sharing hash because it mixes in the size. */
  5410. static int data_url_image(const char *url, int w, int h)
  5411. {
  5412. unsigned int key, len;
  5413. unsigned char *data;
  5414. int i;
  5415. if (!starts_with(url, "data:") || w <= 0 || h <= 0)
  5416. return -1;
  5417. key = data_img_key(url, w, h);
  5418. for (i = 0; i < image_count; i++)
  5419. if (images[i].state == 1 && images[i].url_hash == key)
  5420. return i;
  5421. for (i = 0; i < data_img_nfail; i++)
  5422. if (data_img_fail[i] == key)
  5423. return -1;
  5424. if (image_count < BR_MAX_IMAGES &&
  5425. data_url_decode(url, &data, &len) == 0) {
  5426. int r = decode_image_data(data, len, &images[image_count],
  5427. w, h, w, h);
  5428. free(data);
  5429. if (r == 0) {
  5430. images[image_count].url_hash = key;
  5431. return image_count++;
  5432. }
  5433. }
  5434. if (data_img_nfail < DATA_IMG_FAIL_MAX)
  5435. data_img_fail[data_img_nfail++] = key;
  5436. return -1;
  5437. }
  5438. /* A local file image bypasses the helpers: count its decode so a page opened
  5439. * from /share or /data still produces the same timing breakdown. */
  5440. static void img_stat_local(int before, unsigned int bytes, unsigned int io_ms)
  5441. {
  5442. img_stat_n++;
  5443. img_stat_bytes += bytes;
  5444. img_stat_io += io_ms;
  5445. if (image_count > before) {
  5446. struct br_image *bi = &images[image_count - 1];
  5447. img_stat_dec += img_last_dec_ms;
  5448. img_stat_scale += img_last_scale_ms;
  5449. if (img_stat_log_len + 100 < sizeof(img_stat_log)) {
  5450. unsigned int n = img_stat_log_len;
  5451. s_append(img_stat_log, &n, "local ", sizeof(img_stat_log));
  5452. s_append_dec(img_stat_log, &n, bytes,
  5453. sizeof(img_stat_log));
  5454. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5455. s_append_dec(img_stat_log, &n, img_last_dec_ms,
  5456. sizeof(img_stat_log));
  5457. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5458. s_append_dec(img_stat_log, &n, img_last_scale_ms,
  5459. sizeof(img_stat_log));
  5460. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5461. s_append_dec(img_stat_log, &n,
  5462. (unsigned int)bi->native_w,
  5463. sizeof(img_stat_log));
  5464. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  5465. s_append_dec(img_stat_log, &n,
  5466. (unsigned int)bi->native_h,
  5467. sizeof(img_stat_log));
  5468. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5469. s_append_dec(img_stat_log, &n, bi->img.w,
  5470. sizeof(img_stat_log));
  5471. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  5472. s_append_dec(img_stat_log, &n, bi->img.h,
  5473. sizeof(img_stat_log));
  5474. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  5475. s_append_dec(img_stat_log, &n,
  5476. bi->img.alpha ? 1u : 0u,
  5477. sizeof(img_stat_log));
  5478. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  5479. img_stat_log_len = n;
  5480. }
  5481. }
  5482. }
  5483. /* Harvest one completed worker. Returns 1 when a job was finished. */
  5484. static int preload_finish_worker(struct fetch_worker *w)
  5485. {
  5486. char err[64];
  5487. int rv, tr = 0;
  5488. unsigned int t0, io_ms;
  5489. int before;
  5490. int used_px = 0;
  5491. rv = fetch_worker_poll(w, err, sizeof(err));
  5492. if (rv < 0) {
  5493. /* A helper from an older pack does not understand the image
  5494. * decode request; retry once without it and decode in-process. */
  5495. if (w->image_job && w->dec_w && !w->dec_retried &&
  5496. fetch_worker_submit_req(w, w->url, BR_IMG_FILE_MAX,
  5497. 0, 0, 0, 0, w->node, w->bg,
  5498. 0, 0, 0, err, sizeof(err)) == 0) {
  5499. w->image_job = 1;
  5500. w->dec_retried = 1;
  5501. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  5502. return 0;
  5503. }
  5504. preload_job_error(w);
  5505. if (img_stat_log_len + 64 < sizeof(img_stat_log)) {
  5506. unsigned int n = img_stat_log_len;
  5507. char u[48];
  5508. s_copy(u, w->url, sizeof(u));
  5509. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  5510. s_append(img_stat_log, &n, " error\n",
  5511. sizeof(img_stat_log));
  5512. img_stat_log_len = n;
  5513. }
  5514. img_stat_n++;
  5515. fetch_worker_release(w);
  5516. return 1;
  5517. }
  5518. if (rv == 0)
  5519. return 0;
  5520. t0 = u_ticks_ms();
  5521. rv = -1;
  5522. before = image_count;
  5523. if (w->m.px_len && !w->m.dec_err && w->m.dw && w->m.dh &&
  5524. w->m.px_len <= 8u * 1024u * 1024u) {
  5525. unsigned char *px = (unsigned char *)malloc(w->m.px_len);
  5526. int pr = -1;
  5527. if (px)
  5528. pr = u_syscall3(SYS_READ_FILE, (int)w->px, (int)px,
  5529. (int)w->m.px_len);
  5530. if (pr == (int)w->m.px_len) {
  5531. if (preload_store_helper(w->node, w->bg, px,
  5532. w->m.px_len, w->m.dw,
  5533. w->m.dh, (int)w->m.alpha,
  5534. w->m.nw, w->m.nh,
  5535. w->url) == 0) {
  5536. rv = (int)w->m.len;
  5537. img_last_dec_ms = w->m.dec_ms;
  5538. img_last_scale_ms = 0;
  5539. used_px = 1;
  5540. } else {
  5541. px = 0; /* the helper freed it */
  5542. }
  5543. }
  5544. if (px && !(pr == (int)w->m.px_len))
  5545. free(px);
  5546. }
  5547. io_ms = u_ticks_ms() - t0;
  5548. if (rv < 0) {
  5549. t0 = u_ticks_ms();
  5550. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  5551. image_comp_buf, BR_IMG_FILE_MAX,
  5552. &tr, err, sizeof(err));
  5553. io_ms += u_ticks_ms() - t0;
  5554. before = image_count;
  5555. if (rv >= 0)
  5556. preload_decode(w->node, w->bg, image_file_buf,
  5557. (unsigned int)rv, w->url);
  5558. else
  5559. preload_job_error(w);
  5560. }
  5561. img_stat_n++;
  5562. img_stat_net += w->m.total_ms;
  5563. img_stat_open += w->m.open_ms;
  5564. img_stat_first += w->m.first_ms;
  5565. img_stat_io += io_ms;
  5566. img_stat_bytes += rv > 0 ? (unsigned int)rv : 0;
  5567. img_stat_dec += w->m.dec_ms;
  5568. if (rv >= 0 && !used_px) {
  5569. img_stat_dec += img_last_dec_ms;
  5570. img_stat_scale += img_last_scale_ms;
  5571. }
  5572. if (img_stat_log_len + 160 < sizeof(img_stat_log)) {
  5573. unsigned int n = img_stat_log_len;
  5574. char u[48];
  5575. s_copy(u, w->url, sizeof(u));
  5576. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  5577. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5578. s_append_dec(img_stat_log, &n,
  5579. rv > 0 ? (unsigned int)rv : 0,
  5580. sizeof(img_stat_log));
  5581. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5582. s_append_dec(img_stat_log, &n, w->m.open_ms,
  5583. sizeof(img_stat_log));
  5584. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5585. s_append_dec(img_stat_log, &n, w->m.first_ms,
  5586. sizeof(img_stat_log));
  5587. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5588. s_append_dec(img_stat_log, &n, w->m.total_ms,
  5589. sizeof(img_stat_log));
  5590. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5591. s_append_dec(img_stat_log, &n, io_ms, sizeof(img_stat_log));
  5592. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5593. s_append_dec(img_stat_log, &n,
  5594. rv >= 0 ? img_last_dec_ms : 0,
  5595. sizeof(img_stat_log));
  5596. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5597. s_append_dec(img_stat_log, &n,
  5598. rv >= 0 ? img_last_scale_ms : 0,
  5599. sizeof(img_stat_log));
  5600. if (image_count > before) {
  5601. struct br_image *bi = &images[image_count - 1];
  5602. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5603. s_append_dec(img_stat_log, &n,
  5604. (unsigned int)bi->native_w,
  5605. sizeof(img_stat_log));
  5606. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  5607. s_append_dec(img_stat_log, &n,
  5608. (unsigned int)bi->native_h,
  5609. sizeof(img_stat_log));
  5610. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5611. s_append_dec(img_stat_log, &n, bi->img.w,
  5612. sizeof(img_stat_log));
  5613. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  5614. s_append_dec(img_stat_log, &n, bi->img.h,
  5615. sizeof(img_stat_log));
  5616. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  5617. s_append_dec(img_stat_log, &n,
  5618. bi->img.alpha ? 1u : 0u,
  5619. sizeof(img_stat_log));
  5620. }
  5621. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  5622. img_stat_log_len = n;
  5623. }
  5624. fetch_worker_release(w);
  5625. return 1;
  5626. }
  5627. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  5628. * the number of jobs started. */
  5629. static int preload_fill_jobs(void)
  5630. {
  5631. int started = 0;
  5632. char err[64];
  5633. while (preload_active && preload_node < doc.nnode) {
  5634. unsigned int i = preload_node;
  5635. struct br_node *nd = &doc.nodes[i];
  5636. const char *src;
  5637. char url[BR_URL_MAX];
  5638. struct fetch_worker *w;
  5639. if (preload_active_jobs() >= preload_max_jobs)
  5640. break;
  5641. if (nd->type != BR_NODE_ELEM) {
  5642. preload_node++;
  5643. continue;
  5644. }
  5645. if (nd->tag != BR_TAG_IMG) {
  5646. if (nd->bg_img_index == -1) {
  5647. struct br_style bs;
  5648. style_for_node(i, &bs);
  5649. if (bs.display != BR_DISPLAY_NONE &&
  5650. !bs.vis_hidden && bs.bg_image) {
  5651. const char *bsrc =
  5652. br_bg_image_url(bs.bg_image - 1);
  5653. /* Lazy like <img>: a background box
  5654. * below the viewport (or not laid
  5655. * out yet) waits for the next scan. */
  5656. if (bsrc[0] &&
  5657. (!layout_boxes[i].valid ||
  5658. block_top[i] >
  5659. (unsigned int)(page_scroll.offset +
  5660. page_rect.h + 160))) {
  5661. preload_pending = 1;
  5662. preload_node++;
  5663. continue;
  5664. }
  5665. if (starts_with(bsrc, "data:")) {
  5666. /* Inline image: decode now,
  5667. * no fetch helper. */
  5668. unsigned char *data;
  5669. unsigned int len;
  5670. preload_node = i + 1;
  5671. if (data_url_decode(bsrc, &data,
  5672. &len) == 0) {
  5673. preload_decode(i, 1, data,
  5674. len, 0);
  5675. free(data);
  5676. } else {
  5677. nd->bg_img_index = -2;
  5678. }
  5679. continue;
  5680. }
  5681. if (bsrc[0] &&
  5682. resolve_link(page_url, bsrc, url,
  5683. sizeof(url)) == 0) {
  5684. if (image_count +
  5685. preload_active_jobs() >=
  5686. BR_MAX_IMAGES) {
  5687. preload_node = doc.nnode;
  5688. break;
  5689. }
  5690. if (url[0] == '/') {
  5691. unsigned char *data = 0;
  5692. unsigned int len = 0;
  5693. unsigned int t0;
  5694. int before;
  5695. preload_node = i + 1;
  5696. before = image_count;
  5697. t0 = u_ticks_ms();
  5698. if (fetch_image(url,
  5699. BR_IMG_FILE_MAX,
  5700. &data, &len,
  5701. err,
  5702. sizeof(err)) == 0) {
  5703. preload_decode(i, 1, data, len, 0);
  5704. img_stat_local(before, len,
  5705. u_ticks_ms() - t0);
  5706. } else {
  5707. nd->bg_img_index = -2;
  5708. }
  5709. continue;
  5710. }
  5711. w = fetch_worker_alloc();
  5712. if (!w)
  5713. return started;
  5714. preload_node = i + 1;
  5715. if (fetch_worker_submit(w, url,
  5716. BR_IMG_FILE_MAX,
  5717. 0, 0, i, 1,
  5718. err,
  5719. sizeof(err)) != 0) {
  5720. nd->bg_img_index = -2;
  5721. fetch_worker_release(w);
  5722. continue;
  5723. }
  5724. w->image_job = 1;
  5725. w->deadline = u_ticks_ms() +
  5726. BR_IMG_JOB_TIMEOUT_MS;
  5727. /* in flight: rescans skip it */
  5728. nd->bg_img_index = -3;
  5729. started++;
  5730. continue;
  5731. }
  5732. }
  5733. nd->bg_img_index = -2;
  5734. }
  5735. preload_node++;
  5736. continue;
  5737. }
  5738. if (nd->img_index != -1) {
  5739. preload_node++;
  5740. continue;
  5741. }
  5742. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  5743. preload_node++;
  5744. continue;
  5745. }
  5746. src = br_src(&doc, i);
  5747. if (starts_with(src, "data:")) {
  5748. unsigned char *data;
  5749. unsigned int len;
  5750. preload_node = i + 1;
  5751. if (data_url_decode(src, &data, &len) == 0) {
  5752. preload_decode(i, 0, data, len, 0);
  5753. free(data);
  5754. } else {
  5755. doc.nodes[i].img_index = -2;
  5756. }
  5757. continue;
  5758. }
  5759. if (!src[0]) {
  5760. preload_node++;
  5761. continue;
  5762. }
  5763. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  5764. preload_node++;
  5765. continue;
  5766. }
  5767. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  5768. preload_node = doc.nnode;
  5769. break;
  5770. }
  5771. /* Do not stop at the first below-fold image: DOM order is
  5772. * not visual order, and a footer/ad image early in the DOM
  5773. * used to hide every later article image from the loader. */
  5774. if (img_top[i] >
  5775. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  5776. preload_pending = 1;
  5777. preload_node++;
  5778. continue;
  5779. }
  5780. {
  5781. unsigned int uh = script_cache_hash(url) | 1u;
  5782. int k;
  5783. for (k = 0; k < image_count; k++)
  5784. if (images[k].state == 1 &&
  5785. images[k].url_hash == uh)
  5786. break;
  5787. if (k < image_count) {
  5788. nd->img_index = (short)k;
  5789. layout_valid = 0;
  5790. preload_node = i + 1;
  5791. image_repaint();
  5792. continue;
  5793. }
  5794. }
  5795. if (url[0] == '/') {
  5796. unsigned char *data = 0;
  5797. unsigned int len = 0;
  5798. unsigned int t0;
  5799. int before;
  5800. preload_node = i + 1;
  5801. before = image_count;
  5802. t0 = u_ticks_ms();
  5803. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  5804. err, sizeof(err)) == 0) {
  5805. preload_decode(i, 0, data, len, url);
  5806. img_stat_local(before, len, u_ticks_ms() - t0);
  5807. } else {
  5808. nd->img_index = -2;
  5809. }
  5810. continue;
  5811. }
  5812. w = fetch_worker_alloc();
  5813. if (!w)
  5814. return started;
  5815. preload_node = i + 1;
  5816. {
  5817. char msg[64];
  5818. unsigned int n = 0;
  5819. s_append(msg, &n, "Loading images ", sizeof(msg));
  5820. s_append_dec(msg, &n,
  5821. (unsigned int)preload_loaded + 1,
  5822. sizeof(msg));
  5823. s_append(msg, &n, "...", sizeof(msg));
  5824. set_status_quiet(msg);
  5825. image_repaint();
  5826. }
  5827. {
  5828. int fit_w = 0, fit_h = 0;
  5829. image_fit_size(i, &fit_w, &fit_h);
  5830. if (!fit_w)
  5831. fit_w = BR_IMG_LAYOUT_W;
  5832. if (fetch_worker_submit_image(w, url, BR_IMG_FILE_MAX,
  5833. i, 0,
  5834. (unsigned int)fit_w,
  5835. (unsigned int)fit_h,
  5836. err, sizeof(err)) != 0) {
  5837. nd->img_index = -2;
  5838. fetch_worker_release(w);
  5839. continue;
  5840. }
  5841. }
  5842. w->image_job = 1;
  5843. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  5844. nd->img_index = -3; /* in flight: rescans skip it */
  5845. started++;
  5846. }
  5847. return started;
  5848. }
  5849. /* Report where the image batch spent its time: status bar for the headline,
  5850. * /share/IMGSTAT for the per-image breakdown (cat it from a terminal). */
  5851. static void img_stats_report(void)
  5852. {
  5853. char msg[80];
  5854. static char out[BR_IMG_STAT_LOG + 512];
  5855. unsigned int n = 0, o = 0;
  5856. if (!img_stat_n)
  5857. return;
  5858. img_stat_wall = img_stat_start ?
  5859. u_ticks_ms() - img_stat_start : 1;
  5860. if (!img_stat_wall)
  5861. img_stat_wall = 1;
  5862. /* Compact on-screen form; /share/IMGSTAT has the full breakdown. */
  5863. s_append(msg, &n, "img ", sizeof(msg));
  5864. s_append_dec(msg, &n, (unsigned int)img_stat_n, sizeof(msg));
  5865. s_append(msg, &n, " ", sizeof(msg));
  5866. s_append_dec(msg, &n, img_stat_wall, sizeof(msg));
  5867. s_append(msg, &n, "ms net ", sizeof(msg));
  5868. s_append_dec(msg, &n, img_stat_net, sizeof(msg));
  5869. s_append(msg, &n, " dec ", sizeof(msg));
  5870. s_append_dec(msg, &n, img_stat_dec, sizeof(msg));
  5871. s_append(msg, &n, " sc ", sizeof(msg));
  5872. s_append_dec(msg, &n, img_stat_scale, sizeof(msg));
  5873. s_append(msg, &n, " paint ", sizeof(msg));
  5874. s_append_dec(msg, &n, img_stat_paint, sizeof(msg));
  5875. /* Keep the page's phase breakdown and append the image summary when
  5876. * it fits; never hide a JS error or a truncation notice. */
  5877. if (!post_status_error && !contains_ci(post_status_text, "truncated")) {
  5878. unsigned int plen = s_len(post_status_text);
  5879. if (!plen) {
  5880. s_copy(post_status_text, msg, sizeof(post_status_text));
  5881. } else if (plen + s_len(msg) + 4 < sizeof(post_status_text)) {
  5882. unsigned int pn = plen;
  5883. s_append(post_status_text, &pn, " | ",
  5884. sizeof(post_status_text));
  5885. s_append(post_status_text, &pn, msg,
  5886. sizeof(post_status_text));
  5887. } else {
  5888. s_copy(post_status_text, msg, sizeof(post_status_text));
  5889. }
  5890. post_status_ttl = 12000;
  5891. }
  5892. s_append(out, &o, "browser image stats\n", sizeof(out));
  5893. s_append(out, &o, "n=", sizeof(out));
  5894. s_append_dec(out, &o, (unsigned int)img_stat_n, sizeof(out));
  5895. s_append(out, &o, " wall=", sizeof(out));
  5896. s_append_dec(out, &o, img_stat_wall, sizeof(out));
  5897. s_append(out, &o, " net=", sizeof(out));
  5898. s_append_dec(out, &o, img_stat_net, sizeof(out));
  5899. s_append(out, &o, " open=", sizeof(out));
  5900. s_append_dec(out, &o, img_stat_open, sizeof(out));
  5901. s_append(out, &o, " first=", sizeof(out));
  5902. s_append_dec(out, &o, img_stat_first, sizeof(out));
  5903. s_append(out, &o, " io=", sizeof(out));
  5904. s_append_dec(out, &o, img_stat_io, sizeof(out));
  5905. s_append(out, &o, " dec=", sizeof(out));
  5906. s_append_dec(out, &o, img_stat_dec, sizeof(out));
  5907. s_append(out, &o, " scale=", sizeof(out));
  5908. s_append_dec(out, &o, img_stat_scale, sizeof(out));
  5909. s_append(out, &o, " paint=", sizeof(out));
  5910. s_append_dec(out, &o, img_stat_paint, sizeof(out));
  5911. s_append(out, &o, " reflow=", sizeof(out));
  5912. s_append_dec(out, &o, img_stat_reflow, sizeof(out));
  5913. s_append(out, &o, " bytes=", sizeof(out));
  5914. s_append_dec(out, &o, img_stat_bytes, sizeof(out));
  5915. s_append(out, &o, "\nurl bytes open first total io dec scale native bitmap\n",
  5916. sizeof(out));
  5917. s_append(out, &o, img_stat_log, sizeof(out));
  5918. u_syscall3(SYS_WRITE_FILE, (int)"/share/IMGSTAT", (int)out,
  5919. (int)s_len(out));
  5920. }
  5921. static void preload_step(void)
  5922. {
  5923. int i;
  5924. unsigned int t0;
  5925. if (!preload_active)
  5926. return;
  5927. if (cancel_fetch || pending_action) {
  5928. preload_active = 0;
  5929. preload_pending = 0;
  5930. fetch_workers_cancel_busy();
  5931. return;
  5932. }
  5933. preload_fill_jobs();
  5934. /* Decode completed images in a short batch instead of one per pass.
  5935. * A pass used to decode one image and then sleep 10 ms, so a page of
  5936. * small icons trickled in at the decode rate. The budget keeps a
  5937. * single huge JPEG from monopolising the UI while small images
  5938. * finish together. */
  5939. t0 = u_ticks_ms();
  5940. for (i = 0; i < FETCH_WORKERS; i++) {
  5941. if (!fetch_workers[i].busy)
  5942. continue;
  5943. if (preload_finish_worker(&fetch_workers[i]) &&
  5944. u_ticks_ms() - t0 >= BR_IMG_DECODE_BUDGET_MS)
  5945. break;
  5946. }
  5947. if (preload_active && preload_node >= doc.nnode &&
  5948. preload_active_jobs() == 0) {
  5949. preload_active = 0;
  5950. if (preload_pending)
  5951. preload_scroll = page_scroll.offset;
  5952. else
  5953. preload_pending = 0;
  5954. /* Keep the now idle helpers and their connections; a later
  5955. * navigation reuses them. They exit after ten idle seconds,
  5956. * and losing window focus stops them at once. */
  5957. if (img_repaint_pending) {
  5958. img_repaint_pending = 0;
  5959. ngui_invalidate(&ui);
  5960. }
  5961. img_stats_report();
  5962. set_status(post_status_text, post_status_error, post_status_ttl);
  5963. ngui_invalidate(&ui);
  5964. }
  5965. }
  5966. /* Set by navigate() when it turned a typed bare host into https://; the next
  5967. * load_page() consumes it and may retry over http. */
  5968. static int nav_https_upgraded;
  5969. /* Errors that mean "https is not served here" rather than "the site is
  5970. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  5971. static int https_fallback_error(int e)
  5972. {
  5973. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  5974. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  5975. e == UHTTP_ERR_RESET;
  5976. }
  5977. static void history_push(const char *url)
  5978. {
  5979. if (!url || !url[0])
  5980. return;
  5981. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  5982. s_eq(history[hist_pos], url))
  5983. return;
  5984. if (hist_len > 0 && hist_pos + 1 < hist_len)
  5985. hist_len = hist_pos + 1;
  5986. if (hist_len < BR_HISTORY) {
  5987. s_copy(history[hist_len], url, BR_URL_MAX);
  5988. hist_pos = hist_len;
  5989. hist_len++;
  5990. } else {
  5991. int i;
  5992. for (i = 1; i < BR_HISTORY; i++)
  5993. s_copy(history[i - 1], history[i], BR_URL_MAX);
  5994. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  5995. hist_pos = BR_HISTORY - 1;
  5996. }
  5997. }
  5998. static void load_page(const char *url, int local, int push)
  5999. {
  6000. unsigned char *body = 0;
  6001. unsigned int len = 0;
  6002. int truncated = 0;
  6003. struct img_info image_info;
  6004. char ctype[64];
  6005. char final[BR_URL_MAX];
  6006. char err[80];
  6007. const char *detail = 0;
  6008. const char *post = pending_post_is ? pending_post : 0;
  6009. unsigned int post_len = pending_post_len;
  6010. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  6011. /* Phase timings for the status line: where a slow load spends it. */
  6012. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  6013. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  6014. int upgraded = nav_https_upgraded;
  6015. int retried = 0;
  6016. int rv;
  6017. nav_https_upgraded = 0;
  6018. final[0] = '\0';
  6019. pending_post_len = 0;
  6020. pending_post_is = 0;
  6021. cancel_fetch = 0;
  6022. preload_active = 0;
  6023. preload_pending = 0;
  6024. fetch_workers_prepare_nav(url);
  6025. js_browser_stop();
  6026. js_last_status[0] = '\0';
  6027. js_last_error = 0;
  6028. heap_clear();
  6029. image_reset();
  6030. form_reset_state();
  6031. layout_valid = 0;
  6032. page_scroll.offset = 0;
  6033. page_scroll.dragging = 0;
  6034. page_title[0] = '\0';
  6035. page_loading = 1;
  6036. page_is_local = local;
  6037. s_copy(page_url, url, sizeof(page_url));
  6038. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  6039. url_in.len = s_len(url_in.text);
  6040. url_in.cursor = url_in.len;
  6041. url_in.scroll = 0;
  6042. ngui_set_focus(&ui, 0);
  6043. if (final[0])
  6044. final[0] = '\0';
  6045. if (push)
  6046. history_push(url);
  6047. set_status("Loading...", 0, 0);
  6048. ngui_invalidate(&ui);
  6049. /* heap_clear() detaches the fonts, so attach them again before the
  6050. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  6051. if (heap_start() != 0) {
  6052. show_error("Out of memory", "Cannot allocate the page buffer");
  6053. return;
  6054. }
  6055. br_parse_plain(&doc, "", 0); /* blank while loading */
  6056. ngui_font_attach(&ui);
  6057. redraw_now();
  6058. browser_rules_alloc();
  6059. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  6060. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  6061. &truncated, post, post_len);
  6062. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  6063. fetch_last_error == UHTTP_ERR_DNS) {
  6064. /* A busy previous page can leave the receiver ring full just
  6065. * long enough to lose a DNS reply. Tear the old helpers down
  6066. * and try once more before giving up. */
  6067. retried = 1;
  6068. fetch_workers_stop_all();
  6069. u_sleep_ms(500);
  6070. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  6071. sizeof(ctype), final, sizeof(final), err,
  6072. sizeof(err), &truncated, post, post_len);
  6073. }
  6074. if (rv == FETCH_ABORT)
  6075. return;
  6076. t_fetch = u_ticks_ms() - t_start;
  6077. /* Capture the page timing before CSS/script/image fetches overwrite the
  6078. * shared fetch_meta block. */
  6079. if (rv == 0 && !local) {
  6080. page_open_ms = fetch_meta.open_ms;
  6081. page_first_ms = fetch_meta.first_ms;
  6082. page_total_ms = fetch_meta.total_ms;
  6083. }
  6084. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  6085. https_fallback_error(fetch_last_error)) {
  6086. char http_url[BR_URL_MAX];
  6087. unsigned int n = 0;
  6088. s_append(http_url, &n, "http://", sizeof(http_url));
  6089. s_append(http_url, &n, url + 8, sizeof(http_url));
  6090. /* Replace the https entry instead of adding a second one. */
  6091. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  6092. s_eq(history[hist_pos], url))
  6093. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  6094. load_page(http_url, 0, 0);
  6095. return;
  6096. }
  6097. if (rv != 0) {
  6098. detail = err;
  6099. show_error("Cannot load this page", detail);
  6100. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  6101. url_in.len = s_len(url_in.text);
  6102. url_in.cursor = url_in.len;
  6103. url_in.scroll = 0;
  6104. return;
  6105. }
  6106. if (!local)
  6107. origin_cache_learn(url, final[0] ? final : url);
  6108. page_is_local = local;
  6109. if (final[0]) {
  6110. s_copy(page_url, final, sizeof(page_url));
  6111. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  6112. url_in.len = s_len(url_in.text);
  6113. url_in.cursor = url_in.len;
  6114. url_in.scroll = 0;
  6115. }
  6116. if (contains_ci(ctype, "text/plain")) {
  6117. br_parse_plain(&doc, (const char *)body, len);
  6118. } else if (contains_ci(ctype, "image/") ||
  6119. (!contains_ci(ctype, "text/html") &&
  6120. img_sniff(body, len, &image_info) == 0)) {
  6121. unsigned int node = br_parse_image_doc(&doc, page_url);
  6122. if (node)
  6123. decode_direct_image(body, len, node);
  6124. s_copy(page_title, "Image", sizeof(page_title));
  6125. } else {
  6126. br_set_viewport(ui.w);
  6127. t_mark = u_ticks_ms();
  6128. br_parse(&doc, (const char *)body, len);
  6129. t_parse = u_ticks_ms() - t_mark;
  6130. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  6131. sizeof(page_title));
  6132. t_mark = u_ticks_ms();
  6133. if (load_stylesheets() == FETCH_ABORT)
  6134. return;
  6135. t_css = u_ticks_ms() - t_mark;
  6136. if (pending_action)
  6137. return;
  6138. }
  6139. preload_begin();
  6140. page_loading = 0;
  6141. hist_visit(page_url, page_title);
  6142. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  6143. url_in.len = s_len(url_in.text);
  6144. url_in.cursor = url_in.len;
  6145. url_in.scroll = 0;
  6146. ngui_set_focus(&ui, 0);
  6147. /* Paint the parsed page before fetching/running scripts. A slow
  6148. * remote <script src> then does not hide the page behind the loading
  6149. * screen; the fetch helper pumps this UI while it waits. */
  6150. set_status("Loading scripts...", 0, 0);
  6151. t_mark = u_ticks_ms();
  6152. redraw_now();
  6153. t_paint = u_ticks_ms() - t_mark;
  6154. /* Start one image download before the scripts. The other workers
  6155. * fetch the external script bodies in parallel, and the remaining
  6156. * images start as soon as the script phase ends. */
  6157. preload_max_jobs = 1;
  6158. preload_fill_jobs();
  6159. preload_wait = 0;
  6160. t_mark = u_ticks_ms();
  6161. run_page_scripts();
  6162. t_js = u_ticks_ms() - t_mark;
  6163. preload_max_jobs = FETCH_WORKERS;
  6164. if (pending_action)
  6165. return;
  6166. post_status_text[0] = '\0';
  6167. post_status_error = 0;
  6168. post_status_ttl = 0;
  6169. if (js_last_status[0]) {
  6170. s_copy(post_status_text, js_last_status,
  6171. sizeof(post_status_text));
  6172. post_status_error = js_last_error;
  6173. post_status_ttl = 8000;
  6174. } else if (truncated) {
  6175. s_copy(post_status_text, "Page truncated at the buffer limit",
  6176. sizeof(post_status_text));
  6177. post_status_ttl = 6000;
  6178. } else if (doc.truncated) {
  6179. s_copy(post_status_text, "Page truncated by the parser",
  6180. sizeof(post_status_text));
  6181. post_status_ttl = 6000;
  6182. } else if (page_total_ms) {
  6183. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  6184. * paint 220, js 1750" -- the phases of this load. */
  6185. unsigned int n = 0;
  6186. static const char *const names[] = {
  6187. ", parse ", ", css ", ", paint ", ", js "
  6188. };
  6189. unsigned int vals[4];
  6190. int k;
  6191. vals[0] = t_parse;
  6192. vals[1] = t_css;
  6193. vals[2] = t_paint;
  6194. vals[3] = t_js;
  6195. (void)page_first_ms;
  6196. if (starts_with(page_url, "https://"))
  6197. s_append(post_status_text, &n,
  6198. "HTTPS (not verified), ",
  6199. sizeof(post_status_text));
  6200. s_append(post_status_text, &n, "Loaded in ",
  6201. sizeof(post_status_text));
  6202. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  6203. sizeof(post_status_text));
  6204. s_append(post_status_text, &n, " ms: page ",
  6205. sizeof(post_status_text));
  6206. s_append_dec(post_status_text, &n, t_fetch,
  6207. sizeof(post_status_text));
  6208. s_append(post_status_text, &n, " (headers ",
  6209. sizeof(post_status_text));
  6210. s_append_dec(post_status_text, &n, page_open_ms,
  6211. sizeof(post_status_text));
  6212. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  6213. for (k = 0; k < 4; k++) {
  6214. s_append(post_status_text, &n, names[k],
  6215. sizeof(post_status_text));
  6216. s_append_dec(post_status_text, &n, vals[k],
  6217. sizeof(post_status_text));
  6218. }
  6219. post_status_ttl = 12000;
  6220. } else if (starts_with(page_url, "https://")) {
  6221. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  6222. sizeof(post_status_text));
  6223. post_status_ttl = 6000;
  6224. }
  6225. set_status(post_status_text, post_status_error, post_status_ttl);
  6226. ngui_invalidate(&ui);
  6227. }
  6228. static void load_home(int push)
  6229. {
  6230. pending_post_len = 0;
  6231. pending_post_is = 0;
  6232. cancel_fetch = 0;
  6233. preload_active = 0;
  6234. preload_pending = 0;
  6235. js_browser_stop();
  6236. js_last_status[0] = '\0';
  6237. js_last_error = 0;
  6238. heap_clear();
  6239. image_reset();
  6240. form_reset_state();
  6241. layout_valid = 0;
  6242. page_scroll.offset = 0;
  6243. page_scroll.dragging = 0;
  6244. page_loading = 1;
  6245. page_is_local = 0;
  6246. s_copy(page_url, "about:home", sizeof(page_url));
  6247. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  6248. url_in.len = s_len(url_in.text);
  6249. url_in.cursor = url_in.len;
  6250. url_in.scroll = 0;
  6251. ngui_set_focus(&ui, 0);
  6252. if (push)
  6253. history_push(page_url);
  6254. ngui_invalidate(&ui);
  6255. /* See load_page(): reattach the fonts before the first redraw. */
  6256. if (heap_start() != 0) {
  6257. show_error("Out of memory", "Cannot allocate the browser heap");
  6258. return;
  6259. }
  6260. br_parse_plain(&doc, "", 0);
  6261. ngui_font_attach(&ui);
  6262. redraw_now();
  6263. browser_rules_alloc();
  6264. {
  6265. static const char home[] =
  6266. "<html><head><title>NebOS Browser</title><style>"
  6267. "body { margin: 10px; color: #e4e6f0; }"
  6268. "h1 { color: #7fb0ff; }"
  6269. ".box { background-color: #262b3a; margin: 12px; "
  6270. "padding: 10px; }"
  6271. "a { color: #7fb0ff; }"
  6272. "pre { background-color: #32384a; }"
  6273. "</style></head><body>"
  6274. "<h1>NebOS Browser</h1>"
  6275. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  6276. "shared HTTP client and the image library.</p>"
  6277. "<div class=\"box\"><b>Try:</b>"
  6278. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  6279. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  6280. "<li><a href=\"/floppy1/JS.HTM\">/"
  6281. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  6282. "<li><a href=\"http://10.0.2.2:8000/\">"
  6283. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  6284. "<li><a href=\"https://example.com/\">"
  6285. "https://example.com/</a> (TLS, not verified)</li>"
  6286. "</ul></div>"
  6287. "<p>Type a URL in the bar above. Esc closes the "
  6288. "window, Ctrl+L focuses the address bar.</p>"
  6289. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  6290. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  6291. "</body></html>";
  6292. br_set_viewport(ui.w);
  6293. br_parse(&doc, home, sizeof(home) - 1);
  6294. br_parse_inline_css(&doc);
  6295. br_reset_styles(&doc);
  6296. s_copy(page_title, doc.title, sizeof(page_title));
  6297. }
  6298. post_status_text[0] = '\0';
  6299. post_status_error = 0;
  6300. post_status_ttl = 0;
  6301. page_loading = 0;
  6302. set_status("", 0, 0);
  6303. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  6304. url_in.len = s_len(url_in.text);
  6305. url_in.cursor = url_in.len;
  6306. url_in.scroll = 0;
  6307. ngui_set_focus(&ui, 0);
  6308. ngui_invalidate(&ui);
  6309. }
  6310. /* Extensions the browser opens from the local filesystem. A dotted input
  6311. * with one of these still resolves relative to the cwd. */
  6312. static int local_file_ext(const char *s)
  6313. {
  6314. static const char *const exts[] = {
  6315. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  6316. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  6317. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  6318. "cfg", "conf", 0
  6319. };
  6320. unsigned int i = 0, start = 0, len = 0, e;
  6321. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  6322. s[i] != '#') {
  6323. if (s[i] == '.') {
  6324. start = i + 1;
  6325. len = 0;
  6326. } else if (start) {
  6327. len++;
  6328. }
  6329. i++;
  6330. }
  6331. if (!len)
  6332. return 0;
  6333. for (e = 0; exts[e]; e++) {
  6334. const char *x = exts[e];
  6335. unsigned int xn = s_len(x), k;
  6336. if (xn != len)
  6337. continue;
  6338. for (k = 0; k < len; k++) {
  6339. char a = s[start + k];
  6340. if (a >= 'A' && a <= 'Z')
  6341. a = (char)(a - 'A' + 'a');
  6342. if (a != x[k])
  6343. break;
  6344. }
  6345. if (k == len)
  6346. return 1;
  6347. }
  6348. return 0;
  6349. }
  6350. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  6351. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  6352. * Enter to the first network request. */
  6353. static int looks_like_host(const char *s)
  6354. {
  6355. unsigned int i = 0;
  6356. int dot = 0;
  6357. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  6358. s[i] != ':') {
  6359. char c = s[i];
  6360. if (c == '.') {
  6361. dot = 1;
  6362. } else if (!((c >= 'a' && c <= 'z') ||
  6363. (c >= 'A' && c <= 'Z') ||
  6364. (c >= '0' && c <= '9') ||
  6365. c == '-' || c == '_')) {
  6366. return 0;
  6367. }
  6368. i++;
  6369. }
  6370. return dot && i > 0 && !local_file_ext(s);
  6371. }
  6372. static void load_remote(const char *url, int push)
  6373. {
  6374. char canon[BR_URL_MAX];
  6375. s_copy(canon, url, sizeof(canon));
  6376. origin_cache_apply(canon, sizeof(canon));
  6377. load_page(canon, 0, push);
  6378. }
  6379. static void navigate(const char *input, int push)
  6380. {
  6381. char target[BR_URL_MAX];
  6382. char *t;
  6383. if (!input)
  6384. return;
  6385. ctx_open = 0;
  6386. dl_panel_open = 0;
  6387. s_copy(target, input, sizeof(target));
  6388. t = trim(target);
  6389. if (!t[0])
  6390. return;
  6391. if (s_eq(t, "about:home")) {
  6392. load_home(push);
  6393. return;
  6394. }
  6395. if (starts_with(t, "file://")) {
  6396. make_abs_local(t + 7, target, sizeof(target));
  6397. load_page(target, 1, push);
  6398. return;
  6399. }
  6400. if (is_http(t)) {
  6401. load_remote(t, push);
  6402. return;
  6403. }
  6404. if (t[0] == '/') {
  6405. make_abs_local(t, target, sizeof(target));
  6406. load_page(target, 1, push);
  6407. return;
  6408. }
  6409. if (!looks_like_host(t)) {
  6410. struct sys_stat st;
  6411. if (u_stat(t, &st) == 0 && !st.is_dir) {
  6412. make_abs_local(t, target, sizeof(target));
  6413. load_page(target, 1, push);
  6414. return;
  6415. }
  6416. }
  6417. {
  6418. /* A typed bare host tries https first: nearly every site
  6419. * redirects http -> https anyway, and that hop costs a whole
  6420. * extra connection. load_page() falls back to http when the
  6421. * https connection itself fails. */
  6422. char with_scheme[BR_URL_MAX];
  6423. unsigned int n = 0;
  6424. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  6425. s_append(with_scheme, &n, t, sizeof(with_scheme));
  6426. nav_https_upgraded = 1;
  6427. load_remote(with_scheme, push);
  6428. }
  6429. }
  6430. /* ---- layout ---- */
  6431. static struct ufont_face *face_for(unsigned int family, int bold, int italic)
  6432. {
  6433. unsigned int id;
  6434. if (!family || family > BR_MAX_FACES)
  6435. return 0;
  6436. id = font_pick[family - 1][(bold ? 2 : 0) | (italic ? 1 : 0)];
  6437. return id ? font_faces[id - 1] : 0;
  6438. }
  6439. static struct ufont_face *style_face(const struct br_style *st)
  6440. {
  6441. return st ? face_for(st->font_face, st->bold, st->italic) : 0;
  6442. }
  6443. static struct ufont_face *run_face(const struct lay_run *r)
  6444. {
  6445. return face_for(r->font_face, r->bold, r->italic);
  6446. }
  6447. static unsigned int face_text_width(struct ngui *gui,
  6448. const struct br_style *st,
  6449. const char *s, unsigned int n)
  6450. {
  6451. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  6452. st->bold, st->italic, st->mono);
  6453. }
  6454. static int face_line_height(struct ngui *gui, const struct br_style *st)
  6455. {
  6456. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  6457. st->mono);
  6458. }
  6459. static unsigned int run_text_width(struct ngui *gui,
  6460. const struct lay_run *r,
  6461. const char *s, unsigned int n)
  6462. {
  6463. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  6464. r->bold, r->italic, r->mono);
  6465. }
  6466. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  6467. {
  6468. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  6469. r->mono);
  6470. }
  6471. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  6472. {
  6473. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  6474. }
  6475. static struct br_style base_style(void)
  6476. {
  6477. struct br_style s = { 0 };
  6478. s.color = ui.theme.text;
  6479. s.bg = ui.theme.bg;
  6480. s.has_bg = 0;
  6481. for (int i = 0; i < 4; i++) {
  6482. s.border_c[i] = 0;
  6483. s.border_w[i] = 0;
  6484. s.border_s[i] = BR_BORDER_SOLID;
  6485. }
  6486. s.font_px = 16;
  6487. s.bold = 0;
  6488. s.italic = 0;
  6489. s.mono = 0;
  6490. s.underline = 0;
  6491. s.strike = 0;
  6492. s.overline = 0;
  6493. s.align = BR_ALIGN_LEFT;
  6494. s.display = BR_DISPLAY_BLOCK;
  6495. s.no_bullet = 0;
  6496. s.list_style = BR_LIST_AUTO;
  6497. s.uppercase = 0;
  6498. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  6499. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  6500. s.width = s.max_width = s.min_width = 0;
  6501. s.height = s.min_height = s.max_height = 0;
  6502. s.box_sizing = 0;
  6503. s.ml_auto = s.mr_auto = 0;
  6504. s.line_h_pct = 0;
  6505. s.line_h_px = 0;
  6506. s.mt = s.mb = s.ml = s.mr = 0;
  6507. s.pt = s.pb = s.pl = s.pr = 0;
  6508. return s;
  6509. }
  6510. /* The style node 0's children inherit. Node 0 is the first parsed node:
  6511. * a minified page that starts `<!doctype html><html ...>` makes it the
  6512. * <html> element itself, and the layout walks only its children, so its
  6513. * own cascade (html { color; font } -- Docusaurus/Infima put the page
  6514. * colour and font there) used to be skipped and the theme defaults showed
  6515. * through. Only inherited properties are taken: the root's box (margins,
  6516. * display, background) is not a container style for its children here. */
  6517. static struct br_style root_style(void)
  6518. {
  6519. struct br_style base = base_style(), st;
  6520. if (!doc.nnode || doc.nodes[doc.root].type != BR_NODE_ELEM ||
  6521. doc.nodes[doc.root].tag != BR_TAG_HTML)
  6522. return base;
  6523. br_style_for(&doc, doc.root, &base, &st);
  6524. base.color = st.color;
  6525. base.font_px = st.font_px;
  6526. base.bold = st.bold;
  6527. base.italic = st.italic;
  6528. base.mono = st.mono;
  6529. base.font_face = st.font_face;
  6530. base.align = st.align;
  6531. base.line_h_pct = st.line_h_pct;
  6532. base.line_h_px = st.line_h_px;
  6533. base.nowrap = st.nowrap;
  6534. base.uppercase = st.uppercase;
  6535. base.cursor = st.cursor;
  6536. base.vis_hidden = st.vis_hidden;
  6537. base.fill_mode = st.fill_mode;
  6538. base.fill = st.fill;
  6539. base.stroke_mode = st.stroke_mode;
  6540. base.stroke = st.stroke;
  6541. base.stroke_w = st.stroke_w;
  6542. base.fill_evenodd = st.fill_evenodd;
  6543. return base;
  6544. }
  6545. /* Resolve a margin/padding raw value. Percentages use the containing
  6546. * block width for all four sides, as CSS specifies. */
  6547. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  6548. {
  6549. if (unit == 1)
  6550. return base * v / 10000;
  6551. if (unit == 2)
  6552. return st->font_px * v / 100;
  6553. if (unit == 3)
  6554. return (int)br_root_font_px() * v / 100;
  6555. if (unit == 4)
  6556. return 0;
  6557. return v;
  6558. }
  6559. static int mp_px(const struct br_style *st, int side, int base)
  6560. {
  6561. int raw;
  6562. switch (side) {
  6563. case 0: raw = st->mt; break;
  6564. case 1: raw = st->mr; break;
  6565. case 2: raw = st->mb; break;
  6566. case 3: raw = st->ml; break;
  6567. case 4: raw = st->pt; break;
  6568. case 5: raw = st->pr; break;
  6569. case 6: raw = st->pb; break;
  6570. default: raw = st->pl; break;
  6571. }
  6572. if (st->mp_unit[side] == 5)
  6573. return base * raw / 100 + st->mp_calc_px[side];
  6574. return css_mp_px(st, raw, st->mp_unit[side], base);
  6575. }
  6576. static int style_width_px(const struct br_style *st, int base)
  6577. {
  6578. if (st->width_kind == 1)
  6579. return st->width;
  6580. if (st->width_kind == 2)
  6581. return base * (int)st->width / 100;
  6582. if (st->width_kind == 3)
  6583. return base * st->width_calc_pct / 100 + st->width_calc_px;
  6584. return 0;
  6585. }
  6586. static int style_height_px(const struct br_style *st, int base)
  6587. {
  6588. if (st->height_kind == 1)
  6589. return st->height;
  6590. if (st->height_kind == 2)
  6591. return base * (int)st->height / 100;
  6592. if (st->height_kind == 3)
  6593. return base * st->height_calc_pct / 100 + st->height_calc_px;
  6594. return 0;
  6595. }
  6596. static int css_size(unsigned char kind, int val, int base)
  6597. {
  6598. if (kind == 1)
  6599. return val;
  6600. if (kind == 2)
  6601. return base * val / 100;
  6602. return -1;
  6603. }
  6604. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  6605. int thick, int horizontal, unsigned short color,
  6606. unsigned char style)
  6607. {
  6608. int pos;
  6609. if (len <= 0 || thick <= 0)
  6610. return;
  6611. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  6612. if (horizontal)
  6613. ngui_fill_rect(ui, (struct ngui_rect){
  6614. x, y, len, thick}, color);
  6615. else
  6616. ngui_fill_rect(ui, (struct ngui_rect){
  6617. x, y, thick, len}, color);
  6618. return;
  6619. }
  6620. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  6621. int seg = len - pos;
  6622. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  6623. seg = style == BR_BORDER_DASHED ? 4 : 2;
  6624. if (horizontal)
  6625. ngui_fill_rect(ui, (struct ngui_rect){
  6626. x + pos, y, seg, thick}, color);
  6627. else
  6628. ngui_fill_rect(ui, (struct ngui_rect){
  6629. x, y + pos, thick, seg}, color);
  6630. }
  6631. }
  6632. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  6633. const struct br_style *st)
  6634. {
  6635. int top = st->border_w[0], right = st->border_w[1];
  6636. int bottom = st->border_w[2], left = st->border_w[3];
  6637. if (r.w <= 0 || r.h <= 0)
  6638. return;
  6639. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  6640. int i;
  6641. for (i = 0; i < 4; i++)
  6642. if (st->border_w[i] && !st->border_t[i]) {
  6643. ngui_fill_rect(ui, r, st->border_c[i]);
  6644. break;
  6645. }
  6646. return;
  6647. }
  6648. if (top && !st->border_t[0])
  6649. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  6650. st->border_c[0], st->border_s[0]);
  6651. if (bottom && !st->border_t[2])
  6652. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  6653. st->border_c[2], st->border_s[2]);
  6654. if (left && !st->border_t[3])
  6655. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  6656. left, 0, st->border_c[3], st->border_s[3]);
  6657. if (right && !st->border_t[1])
  6658. draw_border_side(ui, r.x + r.w - right, r.y + top,
  6659. r.h - top - bottom, right, 0,
  6660. st->border_c[1], st->border_s[1]);
  6661. }
  6662. static void transform_origin(const struct br_style *st, int w, int h,
  6663. int *ox, int *oy)
  6664. {
  6665. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  6666. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  6667. }
  6668. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  6669. unsigned int a)
  6670. {
  6671. unsigned int dr, dg, db, sr, sg, sb;
  6672. if (a >= 255)
  6673. return s;
  6674. dr = (d >> 11) & 31;
  6675. dg = (d >> 5) & 63;
  6676. db = d & 31;
  6677. sr = (s >> 11) & 31;
  6678. sg = (s >> 5) & 63;
  6679. sb = s & 31;
  6680. dr = (dr * (255 - a) + sr * a) / 255;
  6681. dg = (dg * (255 - a) + sg * a) / 255;
  6682. db = (db * (255 - a) + sb * a) / 255;
  6683. return (unsigned short)((dr << 11) | (dg << 5) | db);
  6684. }
  6685. /* Paint a solid box through scale()/rotate() around transform-origin. This
  6686. * transforms the element's own background box; text and descendants keep
  6687. * their layout (documented approximation). */
  6688. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  6689. unsigned short color,
  6690. const struct br_style *st)
  6691. {
  6692. double sx = st->scale_x / 100.0;
  6693. double sy = st->scale_y / 100.0;
  6694. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  6695. double c = cos(th), sn = sin(th);
  6696. int ox, oy, minx, miny, maxx, maxy, x, y;
  6697. double ax, ay;
  6698. double px[4], py[4];
  6699. int cx1, cy1, cx2, cy2, i;
  6700. if (sx == 0)
  6701. sx = 0.01;
  6702. if (sy == 0)
  6703. sy = 0.01;
  6704. transform_origin(st, box.w, box.h, &ox, &oy);
  6705. ax = box.x + ox;
  6706. ay = box.y + oy;
  6707. px[0] = -ox; py[0] = -oy;
  6708. px[1] = box.w - ox; py[1] = -oy;
  6709. px[2] = box.w - ox; py[2] = box.h - oy;
  6710. px[3] = -ox; py[3] = box.h - oy;
  6711. minx = miny = 1000000;
  6712. maxx = maxy = -1000000;
  6713. for (i = 0; i < 4; i++) {
  6714. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  6715. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  6716. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  6717. if (dx < minx) minx = dx;
  6718. if (dx > maxx) maxx = dx;
  6719. if (dy < miny) miny = dy;
  6720. if (dy > maxy) maxy = dy;
  6721. }
  6722. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  6723. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  6724. cx2 = page_rect.x + page_rect.w - 12;
  6725. cy2 = page_rect.y + page_rect.h;
  6726. if (cx2 > gui->w) cx2 = gui->w;
  6727. if (cy2 > gui->h) cy2 = gui->h;
  6728. if (minx < cx1) minx = cx1;
  6729. if (miny < cy1) miny = cy1;
  6730. if (maxx > cx2 - 1) maxx = cx2 - 1;
  6731. if (maxy > cy2 - 1) maxy = cy2 - 1;
  6732. for (y = miny; y <= maxy; y++) {
  6733. for (x = minx; x <= maxx; x++) {
  6734. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  6735. double rx = dx * c + dy * sn;
  6736. double ry = -dx * sn + dy * c;
  6737. double bx = rx / sx + ox;
  6738. double by = ry / sy + oy;
  6739. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  6740. gui->px[y * gui->w + x] = color;
  6741. }
  6742. }
  6743. }
  6744. static void draw_image_transformed(struct ngui *gui,
  6745. const struct img_image *im,
  6746. int x, int y, int w, int h,
  6747. int sx100, int sy100, int rot100,
  6748. int origin_x, int origin_y,
  6749. int origin_x_kind, int origin_y_kind)
  6750. {
  6751. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  6752. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  6753. double c = cos(th), sn = sin(th);
  6754. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  6755. double ax, ay;
  6756. double bx[4], by[4];
  6757. int cx1, cy1, cx2, cy2;
  6758. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  6759. return;
  6760. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  6761. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  6762. ax = x + ox;
  6763. ay = y + oy;
  6764. bx[0] = -ox; by[0] = -oy;
  6765. bx[1] = w - ox; by[1] = -oy;
  6766. bx[2] = w - ox; by[2] = h - oy;
  6767. bx[3] = -ox; by[3] = h - oy;
  6768. minx = miny = 1000000;
  6769. maxx = maxy = -1000000;
  6770. for (i = 0; i < 4; i++) {
  6771. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  6772. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  6773. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  6774. if (dx < minx) minx = dx;
  6775. if (dx > maxx) maxx = dx;
  6776. if (dy < miny) miny = dy;
  6777. if (dy > maxy) maxy = dy;
  6778. }
  6779. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  6780. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  6781. cx2 = page_rect.x + page_rect.w - 12;
  6782. cy2 = page_rect.y + page_rect.h;
  6783. if (cx2 > gui->w) cx2 = gui->w;
  6784. if (cy2 > gui->h) cy2 = gui->h;
  6785. if (minx < cx1) minx = cx1;
  6786. if (miny < cy1) miny = cy1;
  6787. if (maxx > cx2 - 1) maxx = cx2 - 1;
  6788. if (maxy > cy2 - 1) maxy = cy2 - 1;
  6789. for (py = miny; py <= maxy; py++) {
  6790. for (px = minx; px <= maxx; px++) {
  6791. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  6792. double rx = dx * c + dy * sn;
  6793. double ry = -dx * sn + dy * c;
  6794. double fx = rx / sx + ox;
  6795. double fy = ry / sy + oy;
  6796. int ix, iy;
  6797. unsigned int si, a;
  6798. unsigned short src;
  6799. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  6800. continue;
  6801. ix = (int)(fx * (double)im->w / w);
  6802. iy = (int)(fy * (double)im->h / h);
  6803. if (ix < 0 || ix >= (int)im->w ||
  6804. iy < 0 || iy >= (int)im->h)
  6805. continue;
  6806. si = (unsigned int)iy * im->w + (unsigned int)ix;
  6807. src = im->px[si];
  6808. a = im->alpha ? im->alpha[si] : 255;
  6809. gui->px[py * gui->w + px] =
  6810. a >= 255 ? src :
  6811. blend_rgb565(gui->px[py * gui->w + px],
  6812. src, a);
  6813. }
  6814. }
  6815. }
  6816. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  6817. unsigned int node, const struct br_style *st);
  6818. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  6819. * first and every pixel outside a corner's arc is restored afterwards. */
  6820. #define BG_ROUND_MAX 64
  6821. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  6822. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  6823. unsigned int node, const struct br_style *st,
  6824. int rtl, int rtr, int rbr, int rbl)
  6825. {
  6826. struct ngui *ui = l->ui;
  6827. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  6828. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  6829. if (ui->nclip > 0)
  6830. clip = ui->clip[ui->nclip - 1];
  6831. for (c = 0; c < 4; c++) {
  6832. if (r[c] > BG_ROUND_MAX)
  6833. r[c] = BG_ROUND_MAX;
  6834. if (r[c] > box.w / 2)
  6835. r[c] = box.w / 2;
  6836. if (r[c] > box.h / 2)
  6837. r[c] = box.h / 2;
  6838. }
  6839. for (c = 0; c < 4; c++) {
  6840. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  6841. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  6842. for (dy = 0; dy < r[c]; dy++)
  6843. for (dx = 0; dx < r[c]; dx++) {
  6844. int px = ox + dx, py = oy + dy;
  6845. if (px >= clip.x && py >= clip.y &&
  6846. px < clip.x + clip.w && py < clip.y + clip.h)
  6847. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  6848. ui->px[py * ui->w + px];
  6849. }
  6850. }
  6851. draw_bg_image(l, box, node, st);
  6852. for (c = 0; c < 4; c++) {
  6853. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  6854. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  6855. /* arc centre, in corner-square coordinates */
  6856. int cx = (c == 1 || c == 2) ? 0 : r[c];
  6857. int cy = (c >= 2) ? 0 : r[c];
  6858. for (dy = 0; dy < r[c]; dy++)
  6859. for (dx = 0; dx < r[c]; dx++) {
  6860. int px = ox + dx, py = oy + dy;
  6861. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  6862. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  6863. continue;
  6864. if (px >= clip.x && py >= clip.y &&
  6865. px < clip.x + clip.w && py < clip.y + clip.h)
  6866. ui->px[py * ui->w + px] =
  6867. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  6868. }
  6869. }
  6870. }
  6871. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  6872. unsigned int node, const struct br_style *st)
  6873. {
  6874. struct br_image *bi;
  6875. struct img_blit b;
  6876. int tw, th, x, y, rep_x, rep_y, posx, posy;
  6877. unsigned int scale = 65536;
  6878. int legacy, tiles = 0, rows = 0;
  6879. int cx1, cy1, cx2, cy2;
  6880. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  6881. return;
  6882. if (doc.nodes[node].bg_img_index < 0 ||
  6883. doc.nodes[node].bg_img_index >= image_count)
  6884. return;
  6885. bi = &images[doc.nodes[node].bg_img_index];
  6886. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  6887. return;
  6888. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  6889. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  6890. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  6891. if (legacy) {
  6892. scale = ((unsigned int)box.w << 16) / bi->img.w;
  6893. tw = box.w;
  6894. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6895. x = box.x;
  6896. y = box.y;
  6897. rep_x = rep_y = 0;
  6898. } else {
  6899. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  6900. unsigned int sx = ((unsigned int)box.w << 16) /
  6901. bi->img.w;
  6902. unsigned int sy = ((unsigned int)box.h << 16) /
  6903. bi->img.h;
  6904. scale = st->bg_size_kind == 3 ?
  6905. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  6906. } else if (st->bg_size_kind == 1 ||
  6907. st->bg_size_kind == 2) {
  6908. int w = st->bg_size_w;
  6909. int h = st->bg_size_h;
  6910. if (st->bg_size_kind == 2) {
  6911. if (w)
  6912. w = box.w * w / 100;
  6913. if (h)
  6914. h = box.h * h / 100;
  6915. }
  6916. if (w)
  6917. scale = ((unsigned int)w << 16) / bi->img.w;
  6918. else if (h)
  6919. scale = ((unsigned int)h << 16) / bi->img.h;
  6920. }
  6921. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  6922. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6923. if (tw < 1)
  6924. tw = 1;
  6925. if (th < 1)
  6926. th = 1;
  6927. posx = st->bg_pos_x_kind == 1 ?
  6928. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  6929. posy = st->bg_pos_y_kind == 1 ?
  6930. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  6931. x = box.x + posx;
  6932. y = box.y + posy;
  6933. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  6934. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  6935. if (rep_x) {
  6936. int m = (x - box.x) % tw;
  6937. if (m > 0)
  6938. m -= tw;
  6939. x = box.x + m;
  6940. }
  6941. if (rep_y) {
  6942. int m = (y - box.y) % th;
  6943. if (m > 0)
  6944. m -= th;
  6945. y = box.y + m;
  6946. }
  6947. }
  6948. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  6949. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  6950. cx2 = box.x + box.w;
  6951. cy2 = box.y + box.h;
  6952. if (cx2 > page_rect.x + page_rect.w - 12)
  6953. cx2 = page_rect.x + page_rect.w - 12;
  6954. if (cy2 > page_rect.y + page_rect.h)
  6955. cy2 = page_rect.y + page_rect.h;
  6956. if (cx1 >= cx2 || cy1 >= cy2)
  6957. return;
  6958. b.dst = l->ui->px;
  6959. b.dst_w = l->ui->w;
  6960. b.dst_h = l->ui->h;
  6961. b.clip_x = cx1;
  6962. b.clip_y = cy1;
  6963. b.clip_w = cx2 - cx1;
  6964. b.clip_h = cy2 - cy1;
  6965. b.bg = ui.theme.bg;
  6966. b.bg2 = ui.theme.bg;
  6967. b.dst_a = 0;
  6968. {
  6969. struct img_image *src = image_display_get(bi, tw, th);
  6970. int row_x;
  6971. if (!src)
  6972. src = &bi->img;
  6973. b.scale = ((unsigned int)tw << 16) / src->w;
  6974. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  6975. row_x = x;
  6976. for (;;) {
  6977. for (;;) {
  6978. b.x = x;
  6979. b.y = y;
  6980. img_draw(src, &b);
  6981. if (!rep_x || ++tiles > 512)
  6982. break;
  6983. x += tw;
  6984. if (x >= box.x + box.w)
  6985. break;
  6986. }
  6987. if (!rep_y || ++rows > 64)
  6988. break;
  6989. y += th;
  6990. if (y >= box.y + box.h)
  6991. break;
  6992. x = row_x;
  6993. }
  6994. }
  6995. }
  6996. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  6997. int *out_w, int *out_h);
  6998. static void svg_paint_box(struct ngui *ui, unsigned int node,
  6999. const struct br_style *st, int x, int y, int w,
  7000. int h);
  7001. /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
  7002. * RUN_SVG an inline <svg> icon (its node in off), RUN_PBOX an empty
  7003. * ::before/::after box with a background (Infima's menu chevrons). */
  7004. #define RUN_SVG (-3)
  7005. #define RUN_PBOX (-4)
  7006. static int run_width(const struct lay_run *r)
  7007. {
  7008. if (r->img >= 0)
  7009. return r->iw;
  7010. if (r->img == -2 || r->img == RUN_SVG || r->img == RUN_PBOX)
  7011. return r->iw;
  7012. return (int)r->w;
  7013. }
  7014. static void start_line(struct lay *l, const struct br_style *st)
  7015. {
  7016. (void)st;
  7017. if (l->nruns == 0) {
  7018. l->line_y = l->y;
  7019. l->line_h = 0;
  7020. }
  7021. l->line_left = l->left;
  7022. l->line_right = l->right;
  7023. if (l->float_active && l->line_y < l->float_bottom) {
  7024. if (l->float_left > l->line_left)
  7025. l->line_left = l->float_left;
  7026. if (l->float_right < l->line_right)
  7027. l->line_right = l->float_right;
  7028. }
  7029. if (l->line_right < l->line_left + 8)
  7030. l->line_right = l->line_left + 8;
  7031. l->line_x = l->line_left;
  7032. l->run_x = l->line_left;
  7033. }
  7034. static void inline_box_add(const struct lay *l, unsigned int owner, int x,
  7035. int w)
  7036. {
  7037. int y = l->line_y;
  7038. int h = l->line_h ? l->line_h : 16;
  7039. int depth = 0;
  7040. while (owner && owner <= BR_MAX_NODES && depth++ < 16) {
  7041. unsigned int node = owner - 1;
  7042. struct br_layout_box *b = &layout_boxes[node];
  7043. if (b->valid && inline_box_pass[node] == inline_box_pass_id &&
  7044. (inline_box_flush[node] == inline_box_flush_id ||
  7045. inline_box_y[node] < y)) {
  7046. int x1 = b->x + b->w, y1 = b->y + b->h;
  7047. if (x < b->x)
  7048. b->x = x;
  7049. if (y < b->y)
  7050. b->y = y;
  7051. if (x + w > x1)
  7052. x1 = x + w;
  7053. if (y + h > y1)
  7054. y1 = y + h;
  7055. b->w = x1 - b->x;
  7056. b->h = y1 - b->y;
  7057. } else {
  7058. b->x = x;
  7059. b->y = y;
  7060. b->w = w;
  7061. b->h = h;
  7062. b->valid = 1;
  7063. }
  7064. inline_box_pass[node] = inline_box_pass_id;
  7065. inline_box_flush[node] = inline_box_flush_id;
  7066. inline_box_y[node] = y;
  7067. owner = inline_box_parent[node];
  7068. }
  7069. }
  7070. static void flush_line(struct lay *l)
  7071. {
  7072. int total, x, i, vis;
  7073. inline_box_flush_id++;
  7074. if (!l->nruns && l->line_x == l->line_left) {
  7075. l->line_h = 0;
  7076. return;
  7077. }
  7078. total = l->line_x - l->line_left;
  7079. x = l->line_left;
  7080. vis = 1;
  7081. if (l->draw) {
  7082. int lh = l->line_h ? l->line_h : 16;
  7083. vis = l->line_y + lh >= page_rect.y &&
  7084. l->line_y <= page_rect.y + page_rect.h;
  7085. }
  7086. if (l->align == BR_ALIGN_CENTER)
  7087. x += (l->line_right - l->line_left - total) / 2;
  7088. else if (l->align == BR_ALIGN_RIGHT)
  7089. x = l->line_right - total;
  7090. if (x < l->line_left)
  7091. x = l->line_left;
  7092. for (i = 0; i < l->nruns; i++) {
  7093. struct lay_run *r = &l->runs[i];
  7094. int w = run_width(r);
  7095. int ry = l->line_y + r->dy;
  7096. x += r->gap;
  7097. if (l->draw && vis) {
  7098. if (r->form) {
  7099. unsigned int node = r->form - 1;
  7100. struct form_state *fs = form_get(node, 1);
  7101. int hh = r->ih ? r->ih : 20;
  7102. int focused = form_focus == node;
  7103. int disabled = r->form_disabled;
  7104. unsigned short bg = l->ui->theme.panel_alt;
  7105. unsigned short fg = disabled ? 0x8410 : r->color;
  7106. struct ngui_rect box = {x, ry, w, hh};
  7107. if (r->form_kind == FORM_CHECKBOX ||
  7108. r->form_kind == FORM_RADIO) {
  7109. ngui_fill_rect(l->ui, box, bg);
  7110. ngui_frame(l->ui, box,
  7111. focused ? l->ui->theme.accent :
  7112. l->ui->theme.border);
  7113. if (fs && fs->checked) {
  7114. struct ngui_rect dot = {
  7115. x + 4, ry + 4,
  7116. w > 8 ? w - 8 : 1,
  7117. hh > 8 ? hh - 8 : 1
  7118. };
  7119. if (r->form_kind == FORM_RADIO)
  7120. ngui_fill_round_rect(
  7121. l->ui, dot, 4,
  7122. 4, 4, 4,
  7123. l->ui->theme.accent);
  7124. else
  7125. ngui_fill_rect(l->ui,
  7126. dot,
  7127. l->ui->theme.accent);
  7128. }
  7129. } else {
  7130. int editable =
  7131. r->form_kind == FORM_TEXT ||
  7132. r->form_kind == FORM_PASSWORD ||
  7133. r->form_kind == FORM_TEXTAREA;
  7134. int scroll = 0;
  7135. /* Editable fields draw the live value
  7136. * (r->lit is a short copy). */
  7137. static char shown[FORM_VALUE_MAX + 1];
  7138. const char *txt = r->lit;
  7139. unsigned int tl = s_len(r->lit);
  7140. if (editable && fs && fs->len) {
  7141. unsigned int k;
  7142. if (r->form_kind == FORM_PASSWORD) {
  7143. for (k = 0; k < fs->len; k++)
  7144. shown[k] = '*';
  7145. shown[k] = '\0';
  7146. txt = shown;
  7147. } else {
  7148. txt = fs->value;
  7149. }
  7150. tl = fs->len;
  7151. }
  7152. struct br_style fst;
  7153. int author, tx = x + 6, pr = 6;
  7154. style_for_node(node, &fst);
  7155. author = form_author_styled(&fst);
  7156. if (author) {
  7157. /* The page styled the control:
  7158. * its background, border, radius
  7159. * and text colour. */
  7160. form_paint_author(l->ui, box, &fst,
  7161. focused);
  7162. tx = x + fst.border_w[3] +
  7163. mp_px(&fst, 7, w);
  7164. pr = fst.border_w[1] +
  7165. mp_px(&fst, 5, w);
  7166. if (tx < x + 2 && !editable)
  7167. tx = x + 2;
  7168. if (!disabled)
  7169. fg = editable && fs &&
  7170. !fs->len ?
  7171. 0x8410 : fst.color;
  7172. if (!editable) {
  7173. int tw0 = (int)
  7174. run_text_width(l->ui,
  7175. r, txt, tl);
  7176. tx = x + (w - tw0) / 2;
  7177. }
  7178. } else {
  7179. /* The box is drawn in theme colours, so
  7180. * the text is too: the page's CSS colour
  7181. * (dark on a light page) would vanish on
  7182. * the dark field. */
  7183. if (!disabled)
  7184. fg = editable && fs && !fs->len ?
  7185. l->ui->theme.text_dim :
  7186. l->ui->theme.text;
  7187. ngui_fill_rect(l->ui, box, bg);
  7188. ngui_frame(l->ui, box,
  7189. focused ? l->ui->theme.accent :
  7190. l->ui->theme.border);
  7191. }
  7192. /* A value wider than the field shows its
  7193. * tail (where typing happens). */
  7194. if (editable && fs && fs->len &&
  7195. w > (tx - x) + pr) {
  7196. int tw = (int)run_text_width(l->ui,
  7197. r, txt, tl);
  7198. int room = w - (tx - x) - pr;
  7199. if (tw > room)
  7200. scroll = tw - room;
  7201. }
  7202. ngui_push_clip(l->ui, (struct ngui_rect){
  7203. x + 1, ry + 1,
  7204. w > 2 ? w - 2 : 1,
  7205. hh > 2 ? hh - 2 : 1 });
  7206. ngui_text_px_face(l->ui, run_face(r),
  7207. tx - scroll,
  7208. ry + (hh - r->font_px) / 2 - 1,
  7209. txt, tl, fg, r->font_px,
  7210. r->bold, r->italic, r->mono);
  7211. if (focused && fs && editable) {
  7212. int cw = 0;
  7213. if (fs->len && fs->caret)
  7214. cw = (int)run_text_width(
  7215. l->ui, r, txt,
  7216. fs->caret < fs->len ?
  7217. fs->caret : fs->len);
  7218. ngui_fill_rect(l->ui,
  7219. (struct ngui_rect){
  7220. tx + cw - scroll,
  7221. ry + 4, 1,
  7222. hh > 8 ? hh - 8 : 1
  7223. },
  7224. l->ui->theme.accent);
  7225. }
  7226. ngui_pop_clip(l->ui);
  7227. if (r->form_kind == FORM_SELECT) {
  7228. ngui_text_px(l->ui, x + w - 12,
  7229. ry + 2, "v", 1, fg,
  7230. r->font_px, 0, 0, 0);
  7231. }
  7232. }
  7233. } else if (r->img == RUN_PBOX) {
  7234. struct ngui_rect bx = { x, ry, w, r->ih };
  7235. ngui_push_clip(l->ui, bx);
  7236. if (r->pb_has_bg)
  7237. ngui_fill_rect(l->ui, bx, r->pb_bg);
  7238. if (r->pb_img >= 0 && r->pb_img < image_count &&
  7239. images[r->pb_img].state == 1) {
  7240. /* Rotate about the box centre: the
  7241. * image is centred in it here. */
  7242. draw_image_transformed(l->ui,
  7243. &images[r->pb_img].img,
  7244. x + r->pb_x, ry + r->pb_y,
  7245. r->pb_w, r->pb_h,
  7246. r->transform_scale ?
  7247. r->scale_x : 100,
  7248. r->transform_scale ?
  7249. r->scale_y : 100,
  7250. r->transform_scale ?
  7251. r->rotate_x100 : 0,
  7252. 50, 50, 1, 1);
  7253. }
  7254. ngui_pop_clip(l->ui);
  7255. } else if (r->img == RUN_SVG) {
  7256. struct br_style sst;
  7257. style_for_node(r->off, &sst);
  7258. svg_paint_box(l->ui, r->off, &sst, x, ry, w,
  7259. r->ih);
  7260. } else if (r->img == -2) {
  7261. int hh = r->ih ? r->ih : 20;
  7262. ngui_fill_rect(l->ui,
  7263. (struct ngui_rect){x, ry, w, hh},
  7264. l->ui->theme.panel_alt);
  7265. ngui_frame(l->ui,
  7266. (struct ngui_rect){x, ry, w, hh},
  7267. l->ui->theme.border);
  7268. ngui_text_px_face(l->ui, run_face(r),
  7269. x + 6, ry + 2, r->lit,
  7270. s_len(r->lit), r->color,
  7271. r->font_px, r->bold, r->italic,
  7272. r->mono);
  7273. } else if (r->img >= 0) {
  7274. struct br_image *bi = &images[r->img];
  7275. if (bi->state == 1 && r->transform_scale) {
  7276. draw_image_transformed(l->ui, &bi->img,
  7277. x, ry, r->iw, r->ih,
  7278. r->scale_x, r->scale_y,
  7279. r->rotate_x100, r->origin_x,
  7280. r->origin_y, r->origin_x_kind,
  7281. r->origin_y_kind);
  7282. } else if (bi->state == 1) {
  7283. struct img_image *src =
  7284. image_display_get(bi, r->iw, r->ih);
  7285. struct img_blit b;
  7286. if (!src)
  7287. src = &bi->img;
  7288. b.dst = l->ui->px;
  7289. b.dst_w = l->ui->w;
  7290. b.dst_h = l->ui->h;
  7291. b.clip_x = page_rect.x;
  7292. b.clip_y = page_rect.y;
  7293. b.clip_w = page_rect.w - 12;
  7294. b.clip_h = page_rect.h;
  7295. b.x = x;
  7296. b.y = ry;
  7297. b.scale = ((unsigned int)r->iw << 16) /
  7298. src->w;
  7299. b.bg = ui.theme.bg;
  7300. b.bg2 = ui.theme.bg;
  7301. b.dst_a = 0;
  7302. b.flags = src->alpha ?
  7303. IMG_BLIT_OVER_DST : 0;
  7304. img_draw(src, &b);
  7305. }
  7306. } else {
  7307. const char *s = r->has_lit ? r->lit :
  7308. doc.text + r->off;
  7309. unsigned int n = r->has_lit ? s_len(r->lit) :
  7310. r->len;
  7311. ngui_text_px_face(l->ui, run_face(r), x, ry,
  7312. s, n, r->color, r->font_px,
  7313. r->bold, r->italic, r->mono);
  7314. if (r->underline)
  7315. ngui_fill_rect(l->ui,
  7316. (struct ngui_rect){x,
  7317. ry + run_ascent(l->ui, r) + 2,
  7318. w, 1}, r->color);
  7319. if (r->strike)
  7320. ngui_fill_rect(l->ui,
  7321. (struct ngui_rect){x,
  7322. ry + run_ascent(l->ui, r) -
  7323. (r->font_px > 3 ?
  7324. r->font_px / 3 : 1),
  7325. w, 1}, r->color);
  7326. if (r->overline)
  7327. ngui_fill_rect(l->ui,
  7328. (struct ngui_rect){x, ry,
  7329. w, 1}, r->color);
  7330. }
  7331. if (r->form || r->href) {
  7332. if (nhits < HIT_MAX) {
  7333. struct hit *h = &hits[nhits];
  7334. unsigned int target = r->form ?
  7335. r->form - 1 : r->href;
  7336. int hh = (r->form || r->img >= 0 ||
  7337. r->img == RUN_SVG) ?
  7338. r->ih :
  7339. run_line_height(l->ui, r);
  7340. int merge = nhits > 0 &&
  7341. hits[nhits - 1].node == target &&
  7342. hits[nhits - 1].y == ry &&
  7343. hits[nhits - 1].h == hh &&
  7344. x <= hits[nhits - 1].x +
  7345. hits[nhits - 1].w + 2;
  7346. if (merge) {
  7347. struct hit *p = &hits[nhits - 1];
  7348. int end = x + w;
  7349. if (end > p->x + p->w)
  7350. p->w = end - p->x;
  7351. } else {
  7352. h->x = x;
  7353. h->y = ry;
  7354. h->w = w;
  7355. h->h = hh;
  7356. h->node = (unsigned short)target;
  7357. h->occl = 0;
  7358. nhits++;
  7359. }
  7360. }
  7361. }
  7362. }
  7363. if (r->box)
  7364. inline_box_add(l, r->box, x, w);
  7365. x += w;
  7366. }
  7367. l->y += l->line_h + 2;
  7368. if (l->float_active && l->y >= l->float_bottom)
  7369. l->float_active = 0;
  7370. l->nruns = 0;
  7371. l->line_x = l->left;
  7372. l->run_x = l->left;
  7373. l->line_left = l->left;
  7374. l->line_right = l->right;
  7375. l->line_h = 0;
  7376. l->space_pending = 0;
  7377. }
  7378. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  7379. const struct br_style *st, unsigned short href,
  7380. const char *lit)
  7381. {
  7382. unsigned int n = lit ? s_len(lit) : len;
  7383. const char *tp = lit ? lit : doc.text + off;
  7384. int w = (int)face_text_width(l->ui, st, tp, n);
  7385. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  7386. flush_line(l);
  7387. if (l->nruns == 0) {
  7388. l->line_y = l->y;
  7389. l->line_h = 0;
  7390. start_line(l, st);
  7391. }
  7392. {
  7393. struct lay_run *r = &l->runs[l->nruns++];
  7394. int gap = l->line_x - l->run_x;
  7395. if (gap < 0)
  7396. gap = 0;
  7397. r->box = l->box_owner;
  7398. r->gap = (unsigned short)gap;
  7399. r->off = off;
  7400. r->len = len;
  7401. r->color = st->color;
  7402. r->href = href;
  7403. r->dy = 0;
  7404. r->has_lit = 0;
  7405. r->form = 0;
  7406. r->form_kind = 0;
  7407. r->form_disabled = 0;
  7408. r->lit[0] = '\0';
  7409. if (lit && lit[0]) {
  7410. unsigned int i;
  7411. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  7412. r->lit[i] = lit[i];
  7413. r->lit[i] = '\0';
  7414. r->has_lit = 1;
  7415. }
  7416. r->img = -1;
  7417. r->iw = r->ih = 0;
  7418. r->font_px = st->font_px;
  7419. r->bold = st->bold;
  7420. r->italic = st->italic;
  7421. r->mono = st->mono;
  7422. r->font_face = st->font_face;
  7423. /* A control with its own background is a button, not body copy;
  7424. * an inherited link underline would strike through the fill. */
  7425. r->underline = st->underline && !st->has_bg;
  7426. r->strike = st->strike && !st->has_bg;
  7427. r->overline = st->overline && !st->has_bg;
  7428. r->w = (unsigned short)w;
  7429. if (r->has_lit)
  7430. r->w = (unsigned short)run_text_width(
  7431. l->ui, r, r->lit, s_len(r->lit));
  7432. w = r->w;
  7433. }
  7434. l->line_x += w;
  7435. l->run_x = l->line_x;
  7436. {
  7437. int lh = face_line_height(l->ui, st);
  7438. if (st->line_h_px)
  7439. lh = st->line_h_px;
  7440. else if (st->line_h_pct)
  7441. lh = st->font_px * st->line_h_pct / 100;
  7442. if (lh < face_line_height(l->ui, st))
  7443. lh = face_line_height(l->ui, st);
  7444. if (l->line_h < lh)
  7445. l->line_h = lh;
  7446. }
  7447. }
  7448. static void add_image_run(struct lay *l, unsigned int node,
  7449. const struct br_style *st, unsigned short href)
  7450. {
  7451. struct br_image *bi = 0;
  7452. int idx = doc.nodes[node].img_index;
  7453. int dw, dh, maxw;
  7454. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  7455. bi = &images[idx];
  7456. if (l->nruns == 0)
  7457. start_line(l, st);
  7458. if (l->space_pending &&
  7459. (l->nruns > 0 || l->line_x > l->line_left)) {
  7460. int sp = (int)face_text_width(l->ui, st, " ", 1);
  7461. if (l->line_x + sp <= l->line_right)
  7462. l->line_x += sp;
  7463. }
  7464. l->space_pending = 0;
  7465. if (!bi) {
  7466. const char *alt = br_alt(&doc, node);
  7467. struct br_style gs = *st;
  7468. char tmp[96];
  7469. unsigned int n = 0;
  7470. int w;
  7471. gs.color = BR_GRAY;
  7472. gs.underline = 0;
  7473. s_append(tmp, &n, "[", sizeof(tmp));
  7474. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  7475. s_append(tmp, &n, "]", sizeof(tmp));
  7476. w = (int)face_text_width(l->ui, &gs, tmp, n);
  7477. if (l->line_x + w > l->line_right &&
  7478. (l->nruns > 0 || l->line_x > l->line_left))
  7479. flush_line(l);
  7480. add_run(l, 0, 0, &gs, href, tmp);
  7481. if (!l->draw) {
  7482. int t = l->line_y < 0 ? 0 : l->line_y;
  7483. int hh = face_line_height(l->ui, &gs);
  7484. if (t > 65535)
  7485. t = 65535;
  7486. if (hh > 65535)
  7487. hh = 65535;
  7488. img_top[node] = (unsigned short)t;
  7489. img_h[node] = (unsigned short)hh;
  7490. }
  7491. return;
  7492. }
  7493. maxw = l->line_right - l->line_left;
  7494. if (maxw < 8)
  7495. maxw = 8;
  7496. {
  7497. int iw = bi->native_w, ih = bi->native_h;
  7498. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  7499. if (iw <= 0 || ih <= 0) {
  7500. iw = (int)bi->img.w;
  7501. ih = (int)bi->img.h;
  7502. }
  7503. dw = iw;
  7504. dh = ih;
  7505. if (doc.nodes[node].width_attr) {
  7506. int want = doc.nodes[node].width_attr;
  7507. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  7508. have_w = 1;
  7509. }
  7510. if (doc.nodes[node].height_attr) {
  7511. int want = doc.nodes[node].height_attr;
  7512. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  7513. have_h = 1;
  7514. }
  7515. if (have_w && !have_h)
  7516. dh = ih ? ih * dw / iw : 0;
  7517. if (have_h && !have_w)
  7518. dw = iw ? iw * dh / ih : 0;
  7519. if (st->width_kind) {
  7520. css_w = 1;
  7521. if (st->width_kind == 3)
  7522. dw = maxw * st->width_calc_pct / 100 +
  7523. st->width_calc_px;
  7524. else
  7525. dw = st->width_kind == 2 ?
  7526. maxw * (int)st->width / 100 :
  7527. (int)st->width;
  7528. }
  7529. /* Percentage heights resolve against the containing block's
  7530. * definite height (Docusaurus' logo: `.navbar__logo { height:
  7531. * 2rem }` holding an `img { height: 100% }`), and are auto
  7532. * when it has none; they used to use the width. */
  7533. if (st->height_kind == 1 ||
  7534. ((st->height_kind == 2 || st->height_kind == 3) &&
  7535. l->cb_h > 0)) {
  7536. css_h = 1;
  7537. if (st->height_kind == 3)
  7538. dh = l->cb_h * st->height_calc_pct / 100 +
  7539. st->height_calc_px;
  7540. else
  7541. dh = st->height_kind == 2 ?
  7542. l->cb_h * (int)st->height / 100 :
  7543. (int)st->height;
  7544. }
  7545. if (css_w && !css_h)
  7546. dh = ih ? ih * dw / iw : 0;
  7547. if (css_h && !css_w)
  7548. dw = iw ? iw * dh / ih : 0;
  7549. if (st->max_width_kind) {
  7550. int mw = st->max_width_kind == 3 ?
  7551. maxw * st->max_width_calc_pct / 100 +
  7552. st->max_width_calc_px :
  7553. st->max_width_kind == 2 ?
  7554. maxw * (int)st->max_width / 100 :
  7555. (int)st->max_width;
  7556. if (mw > 0 && dw > mw) {
  7557. dh = iw ? ih * mw / iw : 0;
  7558. dw = mw;
  7559. }
  7560. }
  7561. }
  7562. if (dw < 8)
  7563. dw = 8;
  7564. if (dh < 8)
  7565. dh = 8;
  7566. if (dw > maxw) {
  7567. dh = dw ? dh * maxw / dw : dh;
  7568. dw = maxw;
  7569. }
  7570. if (!l->draw) {
  7571. int t = l->line_y < 0 ? 0 : l->line_y;
  7572. if (t > 65535)
  7573. t = 65535;
  7574. if (dh > 65535)
  7575. dh = 65535;
  7576. img_top[node] = (unsigned short)t;
  7577. img_h[node] = (unsigned short)dh;
  7578. }
  7579. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  7580. l->line_x > l->line_left))
  7581. flush_line(l);
  7582. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  7583. flush_line(l);
  7584. if (l->nruns == 0) {
  7585. l->line_y = l->y;
  7586. l->line_h = 0;
  7587. start_line(l, st);
  7588. }
  7589. {
  7590. struct lay_run *r = &l->runs[l->nruns++];
  7591. int gap = l->line_x - l->run_x;
  7592. if (gap < 0)
  7593. gap = 0;
  7594. r->box = l->box_owner;
  7595. r->gap = (unsigned short)gap;
  7596. r->off = 0;
  7597. r->len = 0;
  7598. r->color = 0;
  7599. r->href = href;
  7600. r->form = 0;
  7601. r->form_kind = 0;
  7602. r->form_disabled = 0;
  7603. /* Inline replaced elements honour their vertical margins; this
  7604. * is how Bootstrap's negative logo margins centre the wordmark. */
  7605. {
  7606. int idy = mp_px(st, 0, l->right - l->left);
  7607. if (idy < -2048)
  7608. idy = -2048;
  7609. if (idy > 2048)
  7610. idy = 2048;
  7611. r->dy = (signed short)idy;
  7612. }
  7613. r->has_lit = 0;
  7614. r->lit[0] = '\0';
  7615. r->img = (short)idx;
  7616. r->iw = (unsigned short)dw;
  7617. r->ih = (unsigned short)dh;
  7618. r->w = (unsigned short)dw;
  7619. r->font_px = st->font_px;
  7620. r->bold = st->bold;
  7621. r->italic = st->italic;
  7622. r->mono = st->mono;
  7623. r->font_face = st->font_face;
  7624. r->transform_scale = st->transform_scale;
  7625. r->scale_x = st->scale_x;
  7626. r->scale_y = st->scale_y;
  7627. r->rotate_x100 = st->rotate_x100;
  7628. r->origin_x = st->origin_x;
  7629. r->origin_y = st->origin_y;
  7630. r->origin_x_kind = st->origin_x_kind;
  7631. r->origin_y_kind = st->origin_y_kind;
  7632. r->underline = 0;
  7633. }
  7634. if (node < BR_MAX_NODES) {
  7635. layout_boxes[node].x = l->line_x;
  7636. layout_boxes[node].y = l->line_y +
  7637. mp_px(st, 0, l->right - l->left);
  7638. layout_boxes[node].w = dw;
  7639. layout_boxes[node].h = dh;
  7640. layout_boxes[node].valid = 1;
  7641. }
  7642. l->line_x += dw;
  7643. l->run_x = l->line_x;
  7644. if (l->line_h < dh)
  7645. l->line_h = dh;
  7646. }
  7647. /* An inline (or inline-block) <svg> is a replaced element in the text
  7648. * line, like an <img>: comment bubbles and arrows sit next to their label
  7649. * instead of starting a block of their own. */
  7650. static void add_svg_run(struct lay *l, unsigned int node,
  7651. const struct br_style *st, unsigned short href)
  7652. {
  7653. struct lay_run *r;
  7654. int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
  7655. if (lw < 8)
  7656. lw = 8;
  7657. cw = st->width_kind ? style_width_px(st, lw) : lw;
  7658. if (cw < 1)
  7659. cw = 1;
  7660. svg_size(node, st, cw, &dw, &dh);
  7661. if (dw > lw)
  7662. dw = lw;
  7663. ml = mp_px(st, 3, lw);
  7664. mr = mp_px(st, 1, lw);
  7665. if (ml < 0)
  7666. ml = 0;
  7667. if (mr < 0)
  7668. mr = 0;
  7669. if (l->line_x + ml + dw > l->line_right &&
  7670. (l->nruns > 0 || l->line_x > l->line_left))
  7671. flush_line(l);
  7672. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  7673. flush_line(l);
  7674. if (l->nruns == 0) {
  7675. l->line_y = l->y;
  7676. l->line_h = 0;
  7677. start_line(l, st);
  7678. }
  7679. l->line_x += ml;
  7680. r = &l->runs[l->nruns++];
  7681. memset(r, 0, sizeof(*r));
  7682. r->box = l->box_owner;
  7683. r->gap = (unsigned short)(l->line_x > l->run_x ?
  7684. l->line_x - l->run_x : 0);
  7685. r->off = node;
  7686. r->color = st->color;
  7687. r->href = href;
  7688. r->img = RUN_SVG;
  7689. r->iw = (unsigned short)dw;
  7690. r->ih = (unsigned short)dh;
  7691. r->w = (unsigned short)dw;
  7692. r->font_px = st->font_px;
  7693. if (node < BR_MAX_NODES) {
  7694. layout_boxes[node].x = l->line_x;
  7695. layout_boxes[node].y = l->line_y;
  7696. layout_boxes[node].w = dw;
  7697. layout_boxes[node].h = dh;
  7698. layout_boxes[node].valid = 1;
  7699. }
  7700. l->line_x += dw + mr;
  7701. l->run_x = l->line_x;
  7702. if (l->line_h < dh)
  7703. l->line_h = dh;
  7704. }
  7705. static int text_width(struct lay *l, const char *s, unsigned int n,
  7706. const struct br_style *st)
  7707. {
  7708. return (int)face_text_width(l->ui, st, s, n);
  7709. }
  7710. /* Longest prefix that fits in maxw, at least one byte. */
  7711. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  7712. const struct br_style *st, int maxw)
  7713. {
  7714. unsigned int take = 0;
  7715. while (take < n) {
  7716. if (text_width(l, s, take + 1, st) > maxw)
  7717. break;
  7718. take++;
  7719. }
  7720. return take ? take : 1;
  7721. }
  7722. static void emit_word(struct lay *l, const char *s, unsigned int start,
  7723. unsigned int n, unsigned int base,
  7724. const struct br_style *st, unsigned short href)
  7725. {
  7726. int avail;
  7727. int w = text_width(l, s + start, n, st);
  7728. unsigned int off = start;
  7729. if (l->nruns == 0)
  7730. start_line(l, st);
  7731. avail = l->line_right - l->line_left;
  7732. if (st->nowrap) {
  7733. if (n)
  7734. add_run(l, base + start,
  7735. (unsigned short)n, st, href, 0);
  7736. return;
  7737. }
  7738. /* A padded/bordered one-word button can be a few pixels wider than
  7739. * the content box; keep it on one line instead of splitting it. */
  7740. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  7741. add_run(l, base + start,
  7742. (unsigned short)n, st, href, 0);
  7743. return;
  7744. }
  7745. if (l->line_x + w > l->line_right &&
  7746. (l->nruns > 0 || l->line_x > l->line_left)) {
  7747. flush_line(l);
  7748. start_line(l, st);
  7749. avail = l->line_right - l->line_left;
  7750. }
  7751. if (w <= avail) {
  7752. if (n)
  7753. add_run(l, base + start,
  7754. (unsigned short)n, st, href, 0);
  7755. return;
  7756. }
  7757. while (n > 0) {
  7758. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  7759. add_run(l, base + off,
  7760. (unsigned short)take, st, href, 0);
  7761. off += take;
  7762. n -= take;
  7763. if (n) {
  7764. flush_line(l);
  7765. start_line(l, st);
  7766. avail = l->line_right - l->line_left;
  7767. }
  7768. }
  7769. }
  7770. static void emit_text(struct lay *l, const char *s, unsigned int len,
  7771. const struct br_style *st, unsigned short href, int pre)
  7772. {
  7773. unsigned int i = 0;
  7774. unsigned int base;
  7775. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  7776. if (!s || !len)
  7777. return;
  7778. if (space_w <= 0)
  7779. space_w = 8;
  7780. if (l->nruns == 0)
  7781. start_line(l, st);
  7782. base = (unsigned int)(s - doc.text);
  7783. if (st->uppercase) {
  7784. char *p = (char *)s;
  7785. unsigned int j;
  7786. for (j = 0; j < len; j++)
  7787. if (p[j] >= 'a' && p[j] <= 'z')
  7788. p[j] = (char)(p[j] - 'a' + 'A');
  7789. }
  7790. if (pre) {
  7791. while (i < len) {
  7792. unsigned int start;
  7793. if (s[i] == '\n') {
  7794. flush_line(l);
  7795. start_line(l, st);
  7796. i++;
  7797. continue;
  7798. }
  7799. if (s[i] == ' ') {
  7800. if (l->line_x + space_w > l->line_right &&
  7801. (l->nruns > 0 || l->line_x > l->line_left)) {
  7802. flush_line(l);
  7803. start_line(l, st);
  7804. } else {
  7805. l->line_x += space_w;
  7806. }
  7807. i++;
  7808. continue;
  7809. }
  7810. start = i;
  7811. while (i < len && s[i] != ' ' && s[i] != '\n')
  7812. i++;
  7813. emit_word(l, s, start, i - start, base, st, href);
  7814. }
  7815. return;
  7816. }
  7817. while (i < len) {
  7818. unsigned int start, n;
  7819. if (s[i] == ' ') {
  7820. l->space_pending = 1;
  7821. i++;
  7822. continue;
  7823. }
  7824. start = i;
  7825. while (i < len && s[i] != ' ')
  7826. i++;
  7827. n = i - start;
  7828. if (l->space_pending &&
  7829. (l->nruns > 0 || l->line_x > l->line_left)) {
  7830. if (st->nowrap ||
  7831. l->line_x + space_w <= l->line_right)
  7832. l->line_x += space_w;
  7833. }
  7834. l->space_pending = 0;
  7835. emit_word(l, s, start, n, base, st, href);
  7836. }
  7837. }
  7838. static int list_index(unsigned int parent, unsigned int node)
  7839. {
  7840. unsigned int n = 0, i;
  7841. for (i = doc.nodes[parent].first; i && i != node;
  7842. i = doc.nodes[i].next)
  7843. if (doc.nodes[i].tag == BR_TAG_LI)
  7844. n++;
  7845. return (int)n + 1;
  7846. }
  7847. static void list_roman(char *m, unsigned int *n, int v, int upper,
  7848. unsigned int cap)
  7849. {
  7850. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  7851. 50, 40, 10, 9, 5, 4, 1 };
  7852. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  7853. "l", "xl", "x", "ix", "v", "iv", "i" };
  7854. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  7855. "L", "XL", "X", "IX", "V", "IV", "I" };
  7856. unsigned int i;
  7857. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  7858. while (v >= val[i] && *n + 1 < cap) {
  7859. const char *s = upper ? up[i] : lo[i];
  7860. while (*s && *n + 1 < cap)
  7861. m[(*n)++] = *s++;
  7862. v -= val[i];
  7863. }
  7864. }
  7865. }
  7866. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  7867. {
  7868. unsigned int n = 0;
  7869. if (style == BR_LIST_DISC) {
  7870. m[n++] = '-';
  7871. } else if (style == BR_LIST_CIRCLE) {
  7872. m[n++] = 'o';
  7873. } else if (style == BR_LIST_SQUARE) {
  7874. m[n++] = '+';
  7875. } else if (style == BR_LIST_LOWER_ALPHA ||
  7876. style == BR_LIST_UPPER_ALPHA) {
  7877. if (idx >= 1 && idx <= 26)
  7878. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  7879. 'A' : 'a') + idx - 1);
  7880. else
  7881. m[n++] = '?';
  7882. m[n++] = '.';
  7883. } else if (style == BR_LIST_LOWER_ROMAN ||
  7884. style == BR_LIST_UPPER_ROMAN) {
  7885. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  7886. if (n + 1 < cap)
  7887. m[n++] = '.';
  7888. } else {
  7889. s_append_dec(m, &n, (unsigned int)idx, cap);
  7890. if (n + 1 < cap)
  7891. m[n++] = '.';
  7892. }
  7893. m[n] = '\0';
  7894. }
  7895. /* A control the page styled itself (background, border or radius in author
  7896. * CSS -- `background:transparent;border:none` counts) is painted with that
  7897. * style, sized from its padding/height and keeps the page's text colour.
  7898. * Unstyled controls keep the ngui theme look. */
  7899. static int form_author_styled(const struct br_style *st)
  7900. {
  7901. int i;
  7902. if (st->bg_set)
  7903. return 1;
  7904. for (i = 0; i < 4; i++)
  7905. if (st->border_w[i] || st->radius[i])
  7906. return 1;
  7907. return 0;
  7908. }
  7909. /* Set by the layout when the control is stretched to its line: a flex item
  7910. * (its box width was assigned by the flex row) or a child of a flex column,
  7911. * whose default align-items: stretch makes inputs full width. */
  7912. static int form_fill_line;
  7913. static void add_form_run(struct lay *l, unsigned int node,
  7914. const struct br_style *st, unsigned short href)
  7915. {
  7916. struct form_state *fs = form_get(node, 1);
  7917. char shown[FORM_VALUE_MAX + 1];
  7918. char opt[64];
  7919. const char *text = "";
  7920. struct lay_run *r;
  7921. int kind = form_kind_of(node);
  7922. int disabled = form_disabled(node);
  7923. int author = form_author_styled(st);
  7924. int tw, w = 120, h = 20, i, line_w, pad_x, pad_y;
  7925. int ml = 0, mr = 0, mt = 0, mb = 0;
  7926. if (!fs)
  7927. return;
  7928. if (l->nruns == 0)
  7929. start_line(l, st);
  7930. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  7931. text = "";
  7932. w = 16;
  7933. h = 16;
  7934. } else if (kind == FORM_SELECT) {
  7935. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  7936. s_copy(opt, "Select", sizeof(opt));
  7937. text = opt;
  7938. w = 120;
  7939. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  7940. kind == FORM_RESET) {
  7941. if (fs->len)
  7942. text = fs->value;
  7943. else if (doc.nodes[node].tag == BR_TAG_BUTTON)
  7944. /* A <button>'s label is its content: an empty one
  7945. * (Docusaurus' sidebar caret, drawn by a CSS
  7946. * ::before icon) shows none. Only <input> buttons
  7947. * get the UA's default label. */
  7948. text = "";
  7949. else
  7950. text = kind == FORM_SUBMIT ? "Submit" :
  7951. kind == FORM_RESET ? "Reset" : "Button";
  7952. } else if (kind == FORM_PASSWORD) {
  7953. for (i = 0; i < fs->len; i++)
  7954. shown[i] = '*';
  7955. shown[fs->len] = '\0';
  7956. text = fs->len ? shown : br_placeholder(&doc, node);
  7957. } else {
  7958. if (fs->len)
  7959. text = fs->value;
  7960. else
  7961. text = br_placeholder(&doc, node);
  7962. if (kind == FORM_TEXTAREA) {
  7963. w = 180;
  7964. h = 40;
  7965. }
  7966. }
  7967. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  7968. line_w = l->line_right - l->line_left;
  7969. pad_x = mp_px(st, 7, line_w) + mp_px(st, 5, line_w) +
  7970. st->border_w[1] + st->border_w[3];
  7971. pad_y = mp_px(st, 4, line_w) + mp_px(st, 6, line_w) +
  7972. st->border_w[0] + st->border_w[2];
  7973. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  7974. /* Buttons are border-box in every UA stylesheet: an
  7975. * explicit width/height is the whole box. */
  7976. if (author || pad_x) {
  7977. w = tw + pad_x;
  7978. } else {
  7979. w = tw + 18;
  7980. if (w < 64)
  7981. w = 64;
  7982. }
  7983. if (st->width_kind)
  7984. w = style_width_px(st, line_w);
  7985. if (st->min_width_kind == 1 && w < (int)st->min_width)
  7986. w = st->min_width;
  7987. if (st->height_kind == 1)
  7988. h = st->height;
  7989. else if (author)
  7990. h = st->font_px + 6 + pad_y;
  7991. else
  7992. h = 22;
  7993. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  7994. kind == FORM_TEXTAREA) {
  7995. int fill = form_fill_line || st->display == BR_DISPLAY_BLOCK ||
  7996. st->display == BR_DISPLAY_FLEX;
  7997. int boxed = st->box_sizing ? 0 : pad_x;
  7998. if (st->width_kind)
  7999. w = style_width_px(st, line_w) + boxed;
  8000. else if (fill)
  8001. w = line_w - (l->line_x - l->line_left);
  8002. else
  8003. w = kind == FORM_TEXTAREA ? 180 : 120;
  8004. if (kind == FORM_TEXTAREA) {
  8005. const char *ra = br_find_attr(&doc, node, "rows");
  8006. int rows = 0;
  8007. int lh = st->line_h_px ? st->line_h_px :
  8008. st->font_px * 5 / 4;
  8009. while (ra && *ra >= '0' && *ra <= '9')
  8010. rows = rows * 10 + (*ra++ - '0');
  8011. if (rows < 1 || rows > 40)
  8012. rows = 2;
  8013. h = author ? rows * lh + pad_y : 40;
  8014. } else if (author) {
  8015. h = st->font_px + 8 + pad_y;
  8016. } else if (st->font_px + 8 > h) {
  8017. /* Taller fields for large text (min-height/padding
  8018. * on login pages): keep the box around the glyphs. */
  8019. h = st->font_px + 8;
  8020. }
  8021. if (st->height_kind == 1)
  8022. h = st->height + (st->box_sizing ? 0 : pad_y);
  8023. if (st->min_height_kind == 1 && h < (int)st->min_height)
  8024. h = st->min_height;
  8025. } else if (kind == FORM_SELECT) {
  8026. w = st->width_kind == 1 ? st->width : 120;
  8027. }
  8028. if (author) {
  8029. /* Inline margins (Google's `margin:11px 4px` between its
  8030. * two submit buttons). */
  8031. ml = mp_px(st, 3, line_w);
  8032. mr = mp_px(st, 1, line_w);
  8033. mt = mp_px(st, 0, line_w);
  8034. mb = mp_px(st, 2, line_w);
  8035. if (ml < 0 || ml > 64) ml = 0;
  8036. if (mr < 0 || mr > 64) mr = 0;
  8037. if (mt < 0 || mt > 64) mt = 0;
  8038. if (mb < 0 || mb > 64) mb = 0;
  8039. }
  8040. if (w > line_w - ml - mr)
  8041. w = line_w - ml - mr;
  8042. if (w < 8)
  8043. w = 8;
  8044. if (h > 400)
  8045. h = 400;
  8046. if (l->line_x + ml + w > l->line_right &&
  8047. (l->nruns > 0 || l->line_x > l->line_left))
  8048. flush_line(l);
  8049. if (l->nruns >= 96)
  8050. return;
  8051. if (l->nruns == 0) {
  8052. l->line_y = l->y;
  8053. l->line_h = 0;
  8054. start_line(l, st);
  8055. }
  8056. l->line_x += ml;
  8057. r = &l->runs[l->nruns++];
  8058. r->box = l->box_owner;
  8059. r->gap = (unsigned short)(l->line_x - l->run_x);
  8060. r->off = r->len = 0;
  8061. r->color = st->color;
  8062. r->href = href;
  8063. r->dy = (signed short)mt;
  8064. r->has_lit = 1;
  8065. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  8066. r->lit[i] = text[i];
  8067. r->lit[i] = '\0';
  8068. r->img = -2;
  8069. r->iw = (unsigned short)w;
  8070. r->ih = (unsigned short)h;
  8071. r->w = (unsigned short)w;
  8072. r->font_px = st->font_px;
  8073. r->bold = st->bold;
  8074. r->italic = st->italic;
  8075. r->mono = st->mono;
  8076. r->font_face = st->font_face;
  8077. r->underline = 0;
  8078. r->form = node + 1;
  8079. r->form_kind = (unsigned char)kind;
  8080. r->form_disabled = (unsigned char)disabled;
  8081. if (node < BR_MAX_NODES) {
  8082. layout_boxes[node].x = l->line_x;
  8083. layout_boxes[node].y = l->line_y + mt;
  8084. layout_boxes[node].w = w;
  8085. layout_boxes[node].h = h;
  8086. layout_boxes[node].valid = 1;
  8087. }
  8088. l->line_x += w;
  8089. l->run_x = l->line_x;
  8090. l->line_x += mr;
  8091. if (l->line_h < h + mt + mb)
  8092. l->line_h = h + mt + mb;
  8093. }
  8094. /* Background, border and corner radius of an author-styled control, the
  8095. * same decoration rules as a block box. */
  8096. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  8097. const struct br_style *st, int focused)
  8098. {
  8099. int rtl = css_radius(st, 0, box.w, box.h);
  8100. int rtr = css_radius(st, 1, box.w, box.h);
  8101. int rbr = css_radius(st, 2, box.w, box.h);
  8102. int rbl = css_radius(st, 3, box.w, box.h);
  8103. int bw = st->border_t[0] ? 0 : st->border_w[0];
  8104. (void)focused;
  8105. if (box.w <= 0 || box.h <= 0)
  8106. return;
  8107. if (rtl || rtr || rbr || rbl) {
  8108. if (bw > 0 && st->has_bg && st->border_c[0] != st->bg &&
  8109. box.w > bw * 2 && box.h > bw * 2) {
  8110. struct ngui_rect in = { box.x + bw, box.y + bw,
  8111. box.w - bw * 2,
  8112. box.h - bw * 2 };
  8113. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  8114. st->border_c[0]);
  8115. ngui_fill_round_rect(ui, in,
  8116. rtl > bw ? rtl - bw : 0,
  8117. rtr > bw ? rtr - bw : 0,
  8118. rbr > bw ? rbr - bw : 0,
  8119. rbl > bw ? rbl - bw : 0, st->bg);
  8120. } else if (st->has_bg) {
  8121. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  8122. st->bg);
  8123. } else if (bw > 0) {
  8124. ngui_frame_round(ui, box, rtl, rtr, rbr, rbl, bw,
  8125. st->border_c[0]);
  8126. }
  8127. return;
  8128. }
  8129. if (st->has_bg)
  8130. ngui_fill_rect(ui, box, st->bg);
  8131. if (st->border_w[0] || st->border_w[1] || st->border_w[2] ||
  8132. st->border_w[3])
  8133. draw_border_box(ui, box, st);
  8134. }
  8135. /* A poster wrapper is absolutely positioned over the media slot; the
  8136. * measured height of its picture is normally added back to the flow. When a
  8137. * loading-skeleton sibling already reserves that slot, adding both doubles
  8138. * the media height and pushes the article text a full screen down. */
  8139. static int has_skeleton_sibling(unsigned int node)
  8140. {
  8141. unsigned int p = doc.nodes[node].parent, c;
  8142. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  8143. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  8144. continue;
  8145. if (doc.nodes[c].class_off &&
  8146. contains_ci(doc.attrs + doc.nodes[c].class_off,
  8147. "skeleton"))
  8148. return 1;
  8149. }
  8150. return 0;
  8151. }
  8152. static void layout_children(struct lay *l, unsigned int parent,
  8153. const struct br_style *pst, int depth,
  8154. unsigned short link);
  8155. static void layout_flex_children(struct lay *l, unsigned int parent,
  8156. const struct br_style *pst, int depth,
  8157. unsigned short link);
  8158. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  8159. struct br_style *ps, int base);
  8160. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  8161. const struct br_style *ps, unsigned short link);
  8162. static void layout_grid_children(struct lay *l, unsigned int parent,
  8163. const struct br_style *pst, int depth,
  8164. unsigned short link);
  8165. static void layout_grid_auto(struct lay *l, unsigned int parent,
  8166. const struct br_style *pst, int depth,
  8167. unsigned short link);
  8168. static int flex_item_width(struct lay *l, unsigned int n,
  8169. const struct br_style *cs, int avail);
  8170. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  8171. const struct br_style *pst, int depth,
  8172. unsigned short link);
  8173. static void layout_table_row(struct lay *l, unsigned int row,
  8174. const struct br_style *pst, int depth,
  8175. unsigned short link);
  8176. static int table_has_rowspan(unsigned int table);
  8177. static void layout_table(struct lay *l, unsigned int table,
  8178. const struct br_style *st, int depth,
  8179. unsigned short link);
  8180. /* A flex container whose items are only inline spans is usually just a
  8181. * heading/icon pair. Our flex row positions such items without emitting
  8182. * their inline text in some deep page contexts; normal inline flow renders
  8183. * the same content correctly. */
  8184. static int layout_out_of_flow(struct lay *l, unsigned int n,
  8185. const struct br_style *cs, int depth,
  8186. unsigned short lk);
  8187. static void layout_flex_column(struct lay *l, unsigned int parent,
  8188. const struct br_style *pst, int depth,
  8189. unsigned short link);
  8190. static void emit_pseudo(struct lay *l, unsigned int node,
  8191. const struct br_style *st, int pe, unsigned short link);
  8192. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  8193. {
  8194. unsigned int c;
  8195. int items = 0;
  8196. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  8197. struct br_node *nd = &doc.nodes[c];
  8198. struct br_style cs;
  8199. if (nd->type == BR_NODE_TEXT)
  8200. continue;
  8201. br_style_for(&doc, c, pst, &cs);
  8202. if (cs.display == BR_DISPLAY_NONE)
  8203. continue;
  8204. /* `justify-content: space-between` spreads even two plain
  8205. * inline items (a "Password ... Reset password" label row)
  8206. * across the line; inline flow would set them side by side. */
  8207. if (++items >= 2 && pst->justify >= 3)
  8208. return 1;
  8209. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  8210. cs.width_kind || cs.has_bg ||
  8211. cs.border_w[0] || cs.border_w[1] ||
  8212. cs.border_w[2] || cs.border_w[3] ||
  8213. nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG)
  8214. return 1;
  8215. }
  8216. return 0;
  8217. }
  8218. static int css_radius(const struct br_style *st, int corner,
  8219. int w, int h)
  8220. {
  8221. int r = st->radius[corner];
  8222. if (r <= 0)
  8223. return 0;
  8224. if (r > w / 2)
  8225. r = w / 2;
  8226. if (r > h / 2)
  8227. r = h / 2;
  8228. return r;
  8229. }
  8230. /* ---- inline SVG ----
  8231. *
  8232. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  8233. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  8234. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  8235. * opacity and solid paint; a gradient paints the average of its stops) and
  8236. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  8237. #define SVG_CACHE_MAX 48
  8238. #define SVG_CACHE_PIXELS (640 * 1024)
  8239. #define SVG_MAX_POINTS 24576
  8240. struct svg_cache_ent {
  8241. unsigned int node;
  8242. int w, h;
  8243. unsigned short *px;
  8244. unsigned char *a;
  8245. unsigned int stamp;
  8246. };
  8247. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  8248. static unsigned int svg_cache_pixels, svg_cache_clock;
  8249. static struct svgr svg_geom;
  8250. static void *svg_geom_buf;
  8251. /* Current viewport in user units: percentage lengths resolve against it
  8252. * (the viewBox size, not the device pixels). */
  8253. static double svg_vp_w = 300, svg_vp_h = 150;
  8254. /* The layers live in the page heap: forget them before heap_reset(). */
  8255. static void svg_cache_clear(void)
  8256. {
  8257. memset(svg_cache, 0, sizeof(svg_cache));
  8258. svg_cache_pixels = 0;
  8259. svg_geom_buf = 0;
  8260. }
  8261. static int svg_name_is(const char *a, const char *b)
  8262. {
  8263. while (*a && *b) {
  8264. char x = *a, y = *b;
  8265. if (x >= 'A' && x <= 'Z')
  8266. x = (char)(x - 'A' + 'a');
  8267. if (x != y)
  8268. return 0;
  8269. a++;
  8270. b++;
  8271. }
  8272. return *a == *b;
  8273. }
  8274. static const char *svg_elem_name(unsigned int node)
  8275. {
  8276. const struct br_node *nd = &doc.nodes[node];
  8277. if (nd->name_off)
  8278. return doc.attrs + nd->name_off;
  8279. return br_tag_name(nd->tag);
  8280. }
  8281. /* A numeric attribute; a percentage resolves against `base`. */
  8282. static double svg_attr_num(unsigned int node, const char *name, double def,
  8283. double base)
  8284. {
  8285. const char *v = br_find_attr(&doc, node, name);
  8286. const char *p = v;
  8287. int ok = 0;
  8288. double x;
  8289. if (!v)
  8290. return def;
  8291. x = svgr_num(&p, &ok);
  8292. if (!ok)
  8293. return def;
  8294. if (*p == '%')
  8295. x = x * base / 100.0;
  8296. return x;
  8297. }
  8298. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  8299. static int svg_viewbox4(unsigned int node, double vb[4])
  8300. {
  8301. const char *v = br_find_attr(&doc, node, "viewbox");
  8302. const char *p = v;
  8303. int i, ok = 1;
  8304. if (!v)
  8305. return 0;
  8306. for (i = 0; i < 4 && ok; i++)
  8307. vb[i] = svgr_num(&p, &ok);
  8308. return ok && vb[2] > 0 && vb[3] > 0;
  8309. }
  8310. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  8311. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  8312. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  8313. double w, double h, double m[6])
  8314. {
  8315. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  8316. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  8317. int ax = 1, ay = 1;
  8318. if (par && contains_ci(par, "none")) {
  8319. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  8320. m[4] = -vb[0] * sx;
  8321. m[5] = -vb[1] * sy;
  8322. return;
  8323. }
  8324. if (par) {
  8325. if (contains_ci(par, "xmin"))
  8326. ax = 0;
  8327. else if (contains_ci(par, "xmax"))
  8328. ax = 2;
  8329. if (contains_ci(par, "ymin"))
  8330. ay = 0;
  8331. else if (contains_ci(par, "ymax"))
  8332. ay = 2;
  8333. }
  8334. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  8335. (sx < sy ? sx : sy);
  8336. tx = (w - vb[2] * s) * ax / 2.0;
  8337. ty = (h - vb[3] * s) * ay / 2.0;
  8338. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  8339. m[4] = tx - vb[0] * s;
  8340. m[5] = ty - vb[1] * s;
  8341. }
  8342. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  8343. * the paint attribute, then average the gradient's stops. */
  8344. static int svg_url_paint(unsigned int node, const char *attr,
  8345. unsigned short *color, unsigned int *alpha)
  8346. {
  8347. const char *v = 0, *h;
  8348. char id[64];
  8349. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  8350. for (k = 0; node && k < 32 && !v; k++) {
  8351. v = br_find_attr(&doc, node, attr);
  8352. if (!v) {
  8353. const char *style = br_find_attr(&doc, node, "style");
  8354. if (style && contains_ci(style, "url(#"))
  8355. v = strstr(style, "url(#");
  8356. }
  8357. if (v && !contains_ci(v, "url("))
  8358. v = 0;
  8359. node = doc.nodes[node].parent;
  8360. }
  8361. if (!v || !(h = strstr(v, "#")))
  8362. return 0;
  8363. h++;
  8364. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  8365. id[n++] = *h++;
  8366. id[n] = '\0';
  8367. g = br_find_id(&doc, id);
  8368. /* Follow href chains (a gradient that only references another one's
  8369. * stops), at most a few hops. */
  8370. for (k = 0; g && k < 4; k++) {
  8371. unsigned int gi = g - 1;
  8372. const char *ref;
  8373. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  8374. const char *nm, *sc, *so;
  8375. unsigned short col = 0;
  8376. double op = 1;
  8377. if (doc.nodes[c].type != BR_NODE_ELEM)
  8378. continue;
  8379. nm = svg_elem_name(c);
  8380. if (!svg_name_is(nm, "stop"))
  8381. continue;
  8382. sc = br_find_attr(&doc, c, "stop-color");
  8383. so = br_find_attr(&doc, c, "stop-opacity");
  8384. {
  8385. const char *st = br_find_attr(&doc, c, "style");
  8386. const char *q;
  8387. if (st && (q = strstr(st, "stop-color:")) != 0)
  8388. sc = q + 11;
  8389. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  8390. so = q + 13;
  8391. }
  8392. if (sc) {
  8393. unsigned int L = 0;
  8394. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  8395. L++;
  8396. if (!br_parse_color(sc, L, &col))
  8397. col = 0;
  8398. }
  8399. if (so) {
  8400. const char *p = so;
  8401. int ok = 0;
  8402. double x = svgr_num(&p, &ok);
  8403. if (ok)
  8404. op = x < 0 ? 0 : x > 1 ? 1 : x;
  8405. }
  8406. sr += (col >> 11) & 31;
  8407. sg += (col >> 5) & 63;
  8408. sb += col & 31;
  8409. sa += (unsigned int)(op * 255);
  8410. cnt++;
  8411. }
  8412. if (cnt)
  8413. break;
  8414. ref = br_find_attr(&doc, gi, "href");
  8415. if (!ref)
  8416. ref = br_find_attr(&doc, gi, "xlink:href");
  8417. if (!ref || ref[0] != '#')
  8418. break;
  8419. g = br_find_id(&doc, ref + 1);
  8420. }
  8421. if (!cnt)
  8422. return 0;
  8423. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  8424. (sb / cnt));
  8425. *alpha = sa / cnt;
  8426. return 1;
  8427. }
  8428. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  8429. unsigned short *color, unsigned int *alpha)
  8430. {
  8431. int mode = fill ? st->fill_mode : st->stroke_mode;
  8432. const char *op = br_find_attr(&doc, node,
  8433. fill ? "fill-opacity" : "stroke-opacity");
  8434. *alpha = 255;
  8435. switch (mode) {
  8436. case BR_PAINT_UNSET:
  8437. if (!fill)
  8438. return 0;
  8439. *color = 0;
  8440. break;
  8441. case BR_PAINT_COLOR:
  8442. *color = fill ? st->fill : st->stroke;
  8443. break;
  8444. case BR_PAINT_CURRENT:
  8445. *color = st->color;
  8446. break;
  8447. case BR_PAINT_URL:
  8448. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  8449. alpha))
  8450. return 0;
  8451. break;
  8452. default:
  8453. return 0;
  8454. }
  8455. if (op) {
  8456. const char *p = op;
  8457. int ok = 0;
  8458. double x = svgr_num(&p, &ok);
  8459. if (ok)
  8460. *alpha = (unsigned int)(*alpha *
  8461. (x < 0 ? 0 : x > 1 ? 1 : x));
  8462. }
  8463. return *alpha > 0;
  8464. }
  8465. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  8466. const double m[6], const struct br_style *pst,
  8467. unsigned int alpha, int depth);
  8468. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  8469. const double m[6], const struct br_style *st,
  8470. unsigned int alpha, int depth)
  8471. {
  8472. unsigned int c;
  8473. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  8474. if (doc.nodes[c].type == BR_NODE_ELEM)
  8475. svg_draw_node(L, c, m, st, alpha, depth + 1);
  8476. }
  8477. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  8478. const double pm[6], const struct br_style *pst,
  8479. unsigned int alpha, int depth)
  8480. {
  8481. struct br_style st;
  8482. const char *nm = svg_elem_name(node);
  8483. const char *tf;
  8484. double m[6];
  8485. unsigned short color;
  8486. unsigned int pa;
  8487. int shape = 0, fillable = 1;
  8488. if (depth > 24 || !nm)
  8489. return;
  8490. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  8491. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  8492. svg_name_is(nm, "lineargradient") ||
  8493. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  8494. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  8495. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  8496. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  8497. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  8498. svg_name_is(nm, "foreignobject"))
  8499. return;
  8500. br_style_for(&doc, node, pst, &st);
  8501. if (st.display == BR_DISPLAY_NONE)
  8502. return;
  8503. memcpy(m, pm, sizeof(m));
  8504. tf = br_find_attr(&doc, node, "transform");
  8505. if (tf)
  8506. svgr_transform(m, tf);
  8507. {
  8508. const char *op = br_find_attr(&doc, node, "opacity");
  8509. if (op) {
  8510. const char *p = op;
  8511. int ok = 0;
  8512. double x = svgr_num(&p, &ok);
  8513. if (ok)
  8514. alpha = (unsigned int)(alpha *
  8515. (x < 0 ? 0 :
  8516. x > 1 ? 1 : x));
  8517. }
  8518. }
  8519. if (!alpha)
  8520. return;
  8521. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  8522. svg_name_is(nm, "switch")) {
  8523. svg_draw_children(L, node, m, &st, alpha, depth);
  8524. return;
  8525. }
  8526. if (svg_name_is(nm, "svg")) {
  8527. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  8528. y = svg_attr_num(node, "y", 0, 0);
  8529. double t[6] = { 1, 0, 0, 1, 0, 0 };
  8530. t[4] = x;
  8531. t[5] = y;
  8532. svgr_mat_mul(m, m, t);
  8533. double ow = svg_vp_w, oh = svg_vp_h;
  8534. if (svg_viewbox4(node, vb)) {
  8535. double w = svg_attr_num(node, "width", vb[2], ow);
  8536. double h = svg_attr_num(node, "height", vb[3], oh);
  8537. double vm[6];
  8538. svg_viewport_matrix(node, vb, w, h, vm);
  8539. svgr_mat_mul(m, m, vm);
  8540. svg_vp_w = vb[2];
  8541. svg_vp_h = vb[3];
  8542. }
  8543. svg_draw_children(L, node, m, &st, alpha, depth);
  8544. svg_vp_w = ow;
  8545. svg_vp_h = oh;
  8546. return;
  8547. }
  8548. if (svg_name_is(nm, "use")) {
  8549. const char *ref = br_find_attr(&doc, node, "href");
  8550. unsigned int tgt;
  8551. double t[6] = { 1, 0, 0, 1, 0, 0 };
  8552. if (!ref)
  8553. ref = br_find_attr(&doc, node, "xlink:href");
  8554. if (!ref || ref[0] != '#')
  8555. return;
  8556. tgt = br_find_id(&doc, ref + 1);
  8557. if (!tgt || tgt - 1 == node)
  8558. return;
  8559. tgt--;
  8560. t[4] = svg_attr_num(node, "x", 0, 0);
  8561. t[5] = svg_attr_num(node, "y", 0, 0);
  8562. svgr_mat_mul(m, m, t);
  8563. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  8564. double vb[4];
  8565. double ow = svg_vp_w, oh = svg_vp_h;
  8566. if (svg_viewbox4(tgt, vb)) {
  8567. /* A <use> without width/height sizes the
  8568. * symbol to 100% of the viewport: Docusaurus'
  8569. * 13.5px external-link icon references a
  8570. * 24-unit symbol and showed only its corner. */
  8571. double w = svg_attr_num(node, "width",
  8572. ow > 0 ? ow : vb[2], ow);
  8573. double h = svg_attr_num(node, "height",
  8574. oh > 0 ? oh : vb[3], oh);
  8575. double vm[6];
  8576. svg_viewport_matrix(tgt, vb, w, h, vm);
  8577. svgr_mat_mul(m, m, vm);
  8578. svg_vp_w = vb[2];
  8579. svg_vp_h = vb[3];
  8580. }
  8581. svg_draw_children(L, tgt, m, &st, alpha, depth);
  8582. svg_vp_w = ow;
  8583. svg_vp_h = oh;
  8584. } else {
  8585. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  8586. }
  8587. return;
  8588. }
  8589. svgr_reset(&svg_geom, m);
  8590. if (svg_name_is(nm, "path")) {
  8591. const char *d = br_find_attr(&doc, node, "d");
  8592. if (d) {
  8593. svgr_path(&svg_geom, d);
  8594. shape = 1;
  8595. }
  8596. } else if (svg_name_is(nm, "rect")) {
  8597. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  8598. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  8599. double rx = svg_attr_num(node, "rx", -1, w);
  8600. double ry = svg_attr_num(node, "ry", -1, h);
  8601. if (rx < 0)
  8602. rx = ry < 0 ? 0 : ry;
  8603. if (ry < 0)
  8604. ry = rx;
  8605. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  8606. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  8607. shape = 1;
  8608. } else if (svg_name_is(nm, "circle")) {
  8609. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  8610. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  8611. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  8612. shape = 1;
  8613. } else if (svg_name_is(nm, "ellipse")) {
  8614. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  8615. svg_attr_num(node, "cy", 0, svg_vp_h),
  8616. svg_attr_num(node, "rx", 0, svg_vp_w),
  8617. svg_attr_num(node, "ry", 0, svg_vp_h));
  8618. shape = 1;
  8619. } else if (svg_name_is(nm, "line")) {
  8620. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  8621. svg_attr_num(node, "y1", 0, svg_vp_h));
  8622. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  8623. svg_attr_num(node, "y2", 0, svg_vp_h));
  8624. shape = 1;
  8625. fillable = 0;
  8626. } else if (svg_name_is(nm, "polyline") ||
  8627. svg_name_is(nm, "polygon")) {
  8628. const char *pts = br_find_attr(&doc, node, "points");
  8629. if (pts) {
  8630. svgr_points(&svg_geom, pts,
  8631. svg_name_is(nm, "polygon"));
  8632. shape = 1;
  8633. }
  8634. }
  8635. if (!shape)
  8636. return;
  8637. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  8638. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  8639. st.fill_evenodd);
  8640. if (svg_paint(node, &st, 0, &color, &pa)) {
  8641. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  8642. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  8643. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  8644. }
  8645. }
  8646. /* <text> elements: drawn straight onto the page every frame (the glyph
  8647. * renderer targets the ngui canvas, not a layer). x/y map through the
  8648. * accumulated transform; the font size scales with it. */
  8649. static void svg_draw_text(struct ngui *ui, unsigned int node,
  8650. const double pm[6], const struct br_style *pst,
  8651. int ox, int oy, int depth)
  8652. {
  8653. unsigned int c;
  8654. if (depth > 24)
  8655. return;
  8656. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8657. struct br_style st;
  8658. const char *nm, *tf;
  8659. double m[6];
  8660. if (doc.nodes[c].type != BR_NODE_ELEM)
  8661. continue;
  8662. nm = svg_elem_name(c);
  8663. if (!nm || svg_name_is(nm, "defs") ||
  8664. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  8665. svg_name_is(nm, "clippath"))
  8666. continue;
  8667. br_style_for(&doc, c, pst, &st);
  8668. if (st.display == BR_DISPLAY_NONE)
  8669. continue;
  8670. memcpy(m, pm, sizeof(m));
  8671. tf = br_find_attr(&doc, c, "transform");
  8672. if (tf)
  8673. svgr_transform(m, tf);
  8674. if (svg_name_is(nm, "text")) {
  8675. unsigned int t = doc.nodes[c].first;
  8676. const char *s;
  8677. unsigned int n, tw;
  8678. double x = svg_attr_num(c, "x", 0, 0),
  8679. y = svg_attr_num(c, "y", 0, 0);
  8680. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  8681. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  8682. int tx, ty, anchor;
  8683. unsigned short col;
  8684. unsigned int pa;
  8685. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  8686. continue;
  8687. if (px < 6)
  8688. px = 6;
  8689. if (px > 72)
  8690. px = 72;
  8691. if (!svg_paint(c, &st, 1, &col, &pa))
  8692. continue;
  8693. s = doc.text + doc.nodes[t].text_off;
  8694. n = doc.nodes[t].text_len;
  8695. st.font_px = (unsigned char)px;
  8696. tw = face_text_width(ui, &st, s, n);
  8697. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  8698. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  8699. ngui_text_ascent_face(ui, style_face(&st), px,
  8700. st.mono);
  8701. anchor = st.align;
  8702. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  8703. anchor = BR_ALIGN_CENTER;
  8704. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  8705. anchor = BR_ALIGN_RIGHT;
  8706. if (anchor == BR_ALIGN_CENTER)
  8707. tx -= (int)tw / 2;
  8708. else if (anchor == BR_ALIGN_RIGHT)
  8709. tx -= (int)tw;
  8710. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  8711. col, px, st.bold, st.italic,
  8712. st.mono);
  8713. } else {
  8714. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  8715. }
  8716. }
  8717. }
  8718. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  8719. {
  8720. double vb[4];
  8721. if (svg_viewbox4(node, vb)) {
  8722. svg_viewport_matrix(node, vb, w, h, m);
  8723. } else {
  8724. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  8725. }
  8726. }
  8727. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  8728. const struct br_style *st)
  8729. {
  8730. struct svg_cache_ent *e = 0;
  8731. struct svgr_layer L;
  8732. double m[6];
  8733. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  8734. svg_cache_clock++;
  8735. for (i = 0; i < SVG_CACHE_MAX; i++)
  8736. if (svg_cache[i].px && svg_cache[i].node == node &&
  8737. svg_cache[i].w == w && svg_cache[i].h == h) {
  8738. svg_cache[i].stamp = svg_cache_clock;
  8739. return &svg_cache[i];
  8740. }
  8741. if (need > SVG_CACHE_PIXELS)
  8742. return 0;
  8743. /* Evict least recently used layers until this one fits. */
  8744. for (;;) {
  8745. struct svg_cache_ent *lru = 0, *free_slot = 0;
  8746. for (i = 0; i < SVG_CACHE_MAX; i++) {
  8747. if (!svg_cache[i].px) {
  8748. if (!free_slot)
  8749. free_slot = &svg_cache[i];
  8750. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  8751. lru = &svg_cache[i];
  8752. }
  8753. }
  8754. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  8755. e = free_slot;
  8756. break;
  8757. }
  8758. if (!lru)
  8759. return 0;
  8760. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  8761. free(lru->px);
  8762. free(lru->a);
  8763. memset(lru, 0, sizeof(*lru));
  8764. }
  8765. if (!svg_geom_buf) {
  8766. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  8767. if (!svg_geom_buf)
  8768. return 0;
  8769. }
  8770. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  8771. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  8772. e->a = (unsigned char *)calloc(need, 1);
  8773. if (!e->px || !e->a) {
  8774. free(e->px);
  8775. free(e->a);
  8776. memset(e, 0, sizeof(*e));
  8777. return 0;
  8778. }
  8779. e->node = node;
  8780. e->w = w;
  8781. e->h = h;
  8782. e->stamp = svg_cache_clock;
  8783. svg_cache_pixels += need;
  8784. L.px = e->px;
  8785. L.a = e->a;
  8786. L.w = w;
  8787. L.h = h;
  8788. svg_root_matrix(node, w, h, m);
  8789. {
  8790. double vb[4];
  8791. if (svg_viewbox4(node, vb)) {
  8792. svg_vp_w = vb[2];
  8793. svg_vp_h = vb[3];
  8794. } else {
  8795. svg_vp_w = w;
  8796. svg_vp_h = h;
  8797. }
  8798. }
  8799. svg_draw_children(&L, node, m, st, 255, 0);
  8800. return e;
  8801. }
  8802. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  8803. *
  8804. * The markup is parsed into a detached subtree of the page document and
  8805. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  8806. * bitmap, which then behaves like any decoded image. currentColor is
  8807. * black (an image has no inherited text colour); <text> is not drawn. */
  8808. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  8809. {
  8810. unsigned int i = 0;
  8811. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  8812. i = 3;
  8813. while (i < len) {
  8814. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  8815. d[i] == '\r' || d[i] == '\n'))
  8816. i++;
  8817. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  8818. return 1;
  8819. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  8820. i += 4;
  8821. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  8822. i++;
  8823. i += 3;
  8824. continue;
  8825. }
  8826. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  8827. while (i < len && d[i] != '>')
  8828. i++;
  8829. i++;
  8830. continue;
  8831. }
  8832. return 0;
  8833. }
  8834. return 0;
  8835. }
  8836. static int svg_len_attr(unsigned int node, const char *name)
  8837. {
  8838. const char *v = br_find_attr(&doc, node, name);
  8839. int n = 0, any = 0;
  8840. if (!v)
  8841. return 0;
  8842. while (*v == ' ')
  8843. v++;
  8844. while (*v >= '0' && *v <= '9') {
  8845. n = n * 10 + (*v++ - '0');
  8846. any = 1;
  8847. }
  8848. if (*v == '.')
  8849. while (*++v >= '0' && *v <= '9')
  8850. ;
  8851. if (!any || *v == '%')
  8852. return 0;
  8853. return n;
  8854. }
  8855. static int svg_decode_image(const unsigned char *data, unsigned int len,
  8856. struct br_image *bi, int box_w, int box_h)
  8857. {
  8858. unsigned int holder, svg = 0, c, need, i;
  8859. struct br_style base = base_style(), st;
  8860. struct svgr_layer L;
  8861. double vb[4], m[6];
  8862. int w, h, have_vb, nat_w, nat_h;
  8863. holder = br_create_element(&doc, "div", 3);
  8864. if (!holder) {
  8865. s_copy(bi->err, "page is full", sizeof(bi->err));
  8866. return -1;
  8867. }
  8868. holder--;
  8869. br_set_inner_html(&doc, holder, (const char *)data, len);
  8870. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  8871. if (doc.nodes[c].type == BR_NODE_ELEM &&
  8872. doc.nodes[c].tag == BR_TAG_SVG) {
  8873. svg = c;
  8874. break;
  8875. }
  8876. if (!svg) {
  8877. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  8878. return -1;
  8879. }
  8880. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  8881. w = svg_len_attr(svg, "width");
  8882. h = svg_len_attr(svg, "height");
  8883. if (box_w > 0 && box_h > 0) {
  8884. w = box_w;
  8885. h = box_h;
  8886. } else if (!w && !h) {
  8887. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  8888. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  8889. } else if (!w) {
  8890. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  8891. } else if (!h) {
  8892. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  8893. }
  8894. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  8895. * so CSS scaling stays crisp. */
  8896. nat_w = w;
  8897. nat_h = h;
  8898. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  8899. w *= 2;
  8900. h *= 2;
  8901. }
  8902. if (w > BR_IMG_LAYOUT_W) {
  8903. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  8904. w = BR_IMG_LAYOUT_W;
  8905. }
  8906. if (h > 2048)
  8907. h = 2048;
  8908. if (w < 1)
  8909. w = 1;
  8910. if (h < 1)
  8911. h = 1;
  8912. need = (unsigned int)w * (unsigned int)h;
  8913. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  8914. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  8915. return -1;
  8916. }
  8917. if (!svg_geom_buf) {
  8918. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  8919. if (!svg_geom_buf) {
  8920. s_copy(bi->err, "out of memory", sizeof(bi->err));
  8921. return -1;
  8922. }
  8923. }
  8924. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  8925. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  8926. L.a = (unsigned char *)calloc(need, 1);
  8927. if (!L.px || !L.a) {
  8928. free(L.px);
  8929. free(L.a);
  8930. s_copy(bi->err, "out of memory", sizeof(bi->err));
  8931. return -1;
  8932. }
  8933. for (i = 0; i < need; i++)
  8934. L.px[i] = 0xFFFF;
  8935. L.w = w;
  8936. L.h = h;
  8937. base.color = 0x0000;
  8938. br_style_for(&doc, svg, &base, &st);
  8939. svg_root_matrix(svg, w, h, m);
  8940. if (!have_vb && nat_w > 0 && nat_h > 0) {
  8941. /* No viewBox: user units are CSS pixels of the natural size,
  8942. * so the up-to-4x raster (and a box size) must scale them.
  8943. * A 40x20 icon used to fill only the top-left quarter of its
  8944. * 160x80 bitmap and was drawn at a quarter of its size. */
  8945. m[0] = (double)w / nat_w;
  8946. m[3] = (double)h / nat_h;
  8947. }
  8948. svg_vp_w = have_vb ? vb[2] : nat_w;
  8949. svg_vp_h = have_vb ? vb[3] : nat_h;
  8950. svg_draw_children(&L, svg, m, &st, 255, 0);
  8951. bi->native_w = nat_w;
  8952. bi->native_h = nat_h;
  8953. bi->img.format = 0;
  8954. bi->img.w = (unsigned int)w;
  8955. bi->img.h = (unsigned int)h;
  8956. bi->img.px = L.px;
  8957. bi->img.alpha = L.a;
  8958. bi->img.flags = 0;
  8959. bi->state = 1;
  8960. image_pixels += need;
  8961. return 0;
  8962. }
  8963. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  8964. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  8965. int *out_w, int *out_h)
  8966. {
  8967. double vb[4];
  8968. int has_vb = svg_viewbox4(node, vb);
  8969. double aw = svg_attr_num(node, "width", -1, cw);
  8970. double ah = svg_attr_num(node, "height", -1, 0);
  8971. int w, h;
  8972. if (st->width_kind)
  8973. w = cw;
  8974. else if (aw > 0)
  8975. w = (int)(aw + 0.5);
  8976. else if (st->height_kind == 1 && has_vb)
  8977. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  8978. else if (ah > 0 && has_vb)
  8979. w = (int)(ah * vb[2] / vb[3] + 0.5);
  8980. else if (has_vb)
  8981. w = cw;
  8982. else
  8983. w = 300;
  8984. if (st->max_width_kind == 1 && w > st->max_width)
  8985. w = st->max_width;
  8986. if (w > cw && cw > 0 && !(aw > 0))
  8987. w = cw;
  8988. if (w < 1)
  8989. w = 1;
  8990. if (w > 2000)
  8991. w = 2000;
  8992. if (st->height_kind == 1)
  8993. h = st->height;
  8994. else if (ah > 0)
  8995. h = (int)(ah + 0.5);
  8996. else if (has_vb)
  8997. h = (int)(w * vb[3] / vb[2] + 0.5);
  8998. else
  8999. h = 150;
  9000. if (h < 1)
  9001. h = 1;
  9002. if (h > 1400)
  9003. h = 1400;
  9004. *out_w = w;
  9005. *out_h = h;
  9006. }
  9007. static void svg_paint_box(struct ngui *ui, unsigned int node,
  9008. const struct br_style *st, int x, int y, int w, int h)
  9009. {
  9010. struct svg_cache_ent *e;
  9011. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  9012. int cx0, cy0, cx1, cy1, px, py;
  9013. double m[6];
  9014. if (ui->nclip > 0)
  9015. clip = ui->clip[ui->nclip - 1];
  9016. cx0 = r.x > clip.x ? r.x : clip.x;
  9017. cy0 = r.y > clip.y ? r.y : clip.y;
  9018. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  9019. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  9020. if (cx0 >= cx1 || cy0 >= cy1)
  9021. return;
  9022. e = svg_layer(node, w, h, st);
  9023. if (e) {
  9024. for (py = cy0; py < cy1; py++) {
  9025. unsigned int srow = (unsigned int)(py - y) *
  9026. (unsigned int)w;
  9027. unsigned short *dst = ui->px + py * ui->w;
  9028. for (px = cx0; px < cx1; px++) {
  9029. unsigned int si = srow + (unsigned int)(px - x);
  9030. unsigned int a = e->a[si];
  9031. if (!a)
  9032. continue;
  9033. dst[px] = a >= 255 ? e->px[si] :
  9034. blend_rgb565(dst[px], e->px[si], a);
  9035. }
  9036. }
  9037. }
  9038. svg_root_matrix(node, w, h, m);
  9039. ngui_push_clip(ui, r);
  9040. svg_draw_text(ui, node, m, st, x, y, 0);
  9041. ngui_pop_clip(ui);
  9042. }
  9043. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  9044. * keep using add_image_run(); this covers the CSS `position:absolute;
  9045. * width:100%` poster pattern used by news sites. */
  9046. static void image_block_size(unsigned int node, const struct br_style *st,
  9047. int cbw, int *out_w, int *out_h)
  9048. {
  9049. struct br_node *nd = &doc.nodes[node];
  9050. int idx = nd->img_index;
  9051. int iw = 0, ih = 0, w, h, aw, ah;
  9052. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  9053. iw = (int)images[idx].img.w;
  9054. ih = (int)images[idx].img.h;
  9055. if (iw <= 0 || ih <= 0) {
  9056. iw = (int)images[idx].native_w;
  9057. ih = (int)images[idx].native_h;
  9058. }
  9059. }
  9060. if (st->width_kind)
  9061. w = style_width_px(st, cbw);
  9062. else if (nd->width_attr)
  9063. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  9064. (int)nd->width_attr;
  9065. else if (nd->height_attr && !nd->height_pct && iw && ih)
  9066. w = iw * (int)nd->height_attr / ih;
  9067. else if (iw)
  9068. w = iw;
  9069. else
  9070. w = 64;
  9071. /* max-width/min-width against the containing block: Tailwind's
  9072. * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
  9073. * 300x300 thumbnail to its 75 px avatar box. */
  9074. if (st->max_width_kind) {
  9075. int mw = st->max_width_kind == 3 ?
  9076. cbw * st->max_width_calc_pct / 100 +
  9077. st->max_width_calc_px :
  9078. st->max_width_kind == 2 ?
  9079. cbw * (int)st->max_width / 100 : (int)st->max_width;
  9080. if (mw > 0 && w > mw)
  9081. w = mw;
  9082. }
  9083. if (st->min_width_kind) {
  9084. int mn = st->min_width_kind == 3 ?
  9085. cbw * st->min_width_calc_pct / 100 +
  9086. st->min_width_calc_px :
  9087. st->min_width_kind == 2 ?
  9088. cbw * (int)st->min_width / 100 : (int)st->min_width;
  9089. if (mn > w)
  9090. w = mn;
  9091. }
  9092. if (w < 8)
  9093. w = 8;
  9094. if (cbw > 0 && w > cbw)
  9095. w = cbw;
  9096. /* Without a CSS height the attributes (or the bitmap) only give the
  9097. * aspect ratio: a width clamped by max-width scales the height too,
  9098. * instead of letterboxing the image into its attribute height. */
  9099. aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
  9100. ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
  9101. if (st->height_kind)
  9102. h = style_height_px(st, cbw);
  9103. else if (aw > 0 && ah > 0)
  9104. h = w * ah / aw;
  9105. else if (nd->height_attr)
  9106. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  9107. (int)nd->height_attr;
  9108. else
  9109. h = 64;
  9110. if (h < 8)
  9111. h = 8;
  9112. *out_w = w;
  9113. *out_h = h;
  9114. }
  9115. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  9116. int dw, int dh)
  9117. {
  9118. int idx = doc.nodes[node].img_index;
  9119. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  9120. struct img_image *src = image_display_get(&images[idx], dw, dh);
  9121. struct img_blit b;
  9122. if (!src)
  9123. src = &images[idx].img;
  9124. b.dst = l->ui->px;
  9125. b.dst_w = l->ui->w;
  9126. b.dst_h = l->ui->h;
  9127. b.clip_x = page_rect.x;
  9128. b.clip_y = page_rect.y;
  9129. b.clip_w = page_rect.w - 12;
  9130. b.clip_h = page_rect.h;
  9131. b.x = x;
  9132. b.y = y;
  9133. b.scale = ((unsigned int)dw << 16) / src->w;
  9134. b.bg = ui.theme.bg;
  9135. b.bg2 = ui.theme.bg;
  9136. b.dst_a = 0;
  9137. /* OVER_DST is only needed for an alpha source; an opaque one can
  9138. * take img_draw's 1:1 copy path. */
  9139. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  9140. img_draw(src, &b);
  9141. } else if (l->draw) {
  9142. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  9143. 0xD69A);
  9144. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  9145. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  9146. }
  9147. }
  9148. static int intrinsic_width(struct ngui *ui, unsigned int node,
  9149. const struct br_style *pst, int depth, int base);
  9150. /* ---- CSS transitions (opacity, transform translate) ----
  9151. *
  9152. * The cascade only knows the current computed value, so the paint pass
  9153. * remembers each element's last target value (pstate[]). When a later
  9154. * paint sees a different target and the element has a transition for that
  9155. * property, an animation from the value on screen to the new target starts
  9156. * and the page is repainted every pass until it ends; then `transitionend`
  9157. * is dispatched. The start state is whatever the previous paint saw: a
  9158. * script that changes a class right after display (Bootstrap adds `.in`)
  9159. * forces a reflow first (offsetWidth), and js_force_layout() is a paint
  9160. * pass, so that state is recorded like in a browser. Only the render
  9161. * pass records (render_pass); the measure pass does not. */
  9162. #define ANIM_MAX 32
  9163. #define ANIM_OP 0
  9164. #define ANIM_TX 1
  9165. #define ANIM_TY 2
  9166. struct anim {
  9167. unsigned short node;
  9168. unsigned char prop, ease;
  9169. short from, to;
  9170. unsigned int t0, dur;
  9171. unsigned int seq; /* render_seq of the last paint that saw it */
  9172. };
  9173. struct paint_state {
  9174. short tx, ty;
  9175. unsigned char op;
  9176. unsigned char seen; /* bit per ANIM_* prop */
  9177. };
  9178. static struct paint_state pstate[BR_MAX_NODES];
  9179. static struct anim anims[ANIM_MAX];
  9180. static int nanims;
  9181. static int render_pass;
  9182. static unsigned int render_seq;
  9183. static unsigned short anim_ended[ANIM_MAX];
  9184. static int nanim_ended;
  9185. static int anim_ease(int ease, int p) /* p and result 0..1024 */
  9186. {
  9187. int q = 1024 - p;
  9188. switch (ease) {
  9189. case BR_EASE_LINEAR:
  9190. return p;
  9191. case BR_EASE_IN:
  9192. return (int)((long)p * p / 1024);
  9193. case BR_EASE_OUT:
  9194. return 1024 - (int)((long)q * q / 1024 * q / 1024);
  9195. default: /* ease, ease-in-out: smoothstep */
  9196. return (int)((long)p * p / 1024 * (3072 - 2 * p) / 1024);
  9197. }
  9198. }
  9199. static int anim_find(unsigned int node, int prop)
  9200. {
  9201. int i;
  9202. for (i = 0; i < nanims; i++)
  9203. if (anims[i].node == node && anims[i].prop == prop)
  9204. return i;
  9205. return -1;
  9206. }
  9207. static int anim_now(const struct anim *a, unsigned int now)
  9208. {
  9209. unsigned int dt = now - a->t0;
  9210. int p;
  9211. if (dt >= a->dur)
  9212. return a->to;
  9213. p = anim_ease(a->ease, (int)(dt * 1024 / a->dur));
  9214. return a->from + (int)((long)(a->to - a->from) * p / 1024);
  9215. }
  9216. static int anim_has(unsigned int node)
  9217. {
  9218. int i;
  9219. for (i = 0; i < nanims; i++)
  9220. if (anims[i].node == node)
  9221. return 1;
  9222. return 0;
  9223. }
  9224. /* The value to paint for a property whose computed target is `target`. */
  9225. static int anim_value(unsigned int node, int prop, int target,
  9226. const struct br_style *st)
  9227. {
  9228. struct paint_state *ps;
  9229. unsigned int now = u_ticks_ms();
  9230. int i, prev, bit = 1 << prop;
  9231. int tr = prop == ANIM_OP ? (st->tr_mask & BR_TR_OPACITY) :
  9232. (st->tr_mask & BR_TR_TRANSFORM);
  9233. if (!render_pass || node >= BR_MAX_NODES)
  9234. return target;
  9235. ps = &pstate[node];
  9236. prev = prop == ANIM_OP ? ps->op : prop == ANIM_TX ? ps->tx : ps->ty;
  9237. i = anim_find(node, prop);
  9238. if ((ps->seen & bit) && prev != target) {
  9239. if (tr && st->tr_ms) {
  9240. int from = i >= 0 ? anim_now(&anims[i], now) : prev;
  9241. if (i < 0 && nanims < ANIM_MAX)
  9242. i = nanims++;
  9243. if (i >= 0) {
  9244. anims[i].node = (unsigned short)node;
  9245. anims[i].prop = (unsigned char)prop;
  9246. anims[i].ease = st->tr_ease;
  9247. anims[i].from = (short)from;
  9248. anims[i].to = (short)target;
  9249. anims[i].t0 = now;
  9250. anims[i].dur = st->tr_ms;
  9251. anims[i].seq = render_seq;
  9252. }
  9253. } else if (i >= 0) {
  9254. anims[i] = anims[--nanims];
  9255. i = -1;
  9256. }
  9257. }
  9258. ps->seen |= (unsigned char)bit;
  9259. if (prop == ANIM_OP)
  9260. ps->op = (unsigned char)target;
  9261. else if (prop == ANIM_TX)
  9262. ps->tx = (short)target;
  9263. else
  9264. ps->ty = (short)target;
  9265. if (i < 0)
  9266. return target;
  9267. anims[i].seq = render_seq;
  9268. if (now - anims[i].t0 >= anims[i].dur) {
  9269. if (nanim_ended < ANIM_MAX)
  9270. anim_ended[nanim_ended++] = anims[i].node;
  9271. anims[i] = anims[--nanims];
  9272. return target;
  9273. }
  9274. return anim_now(&anims[i], now);
  9275. }
  9276. /* After the frame: running animations need another paint, and finished
  9277. * ones get their `transitionend` (Bootstrap also has a timer fallback). */
  9278. static void anim_after_frame(void)
  9279. {
  9280. static unsigned int checked_seq;
  9281. int i, j, n = nanim_ended;
  9282. /* An element removed or hidden mid-transition is no longer painted;
  9283. * its animation would otherwise keep every frame re-rendering. */
  9284. if (render_seq != checked_seq) {
  9285. for (i = 0; i < nanims; )
  9286. if (anims[i].seq != render_seq)
  9287. anims[i] = anims[--nanims];
  9288. else
  9289. i++;
  9290. checked_seq = render_seq;
  9291. }
  9292. if (nanims) {
  9293. page_cache_valid = 0;
  9294. ngui_invalidate(&ui);
  9295. }
  9296. nanim_ended = 0;
  9297. if (!js_browser_active())
  9298. return;
  9299. for (i = 0; i < n; i++) {
  9300. for (j = 0; j < i; j++)
  9301. if (anim_ended[j] == anim_ended[i])
  9302. break;
  9303. if (j == i && anim_ended[i] < doc.nnode)
  9304. js_browser_event(anim_ended[i], "transitionend", 1, 0);
  9305. }
  9306. }
  9307. /* Group opacity for a translucent positioned box: the page area under it
  9308. * is saved before the box paints and blended back afterwards. */
  9309. static unsigned short *alpha_snap;
  9310. static unsigned int alpha_snap_px;
  9311. static void anim_reset(void)
  9312. {
  9313. memset(pstate, 0, sizeof(pstate));
  9314. nanims = 0;
  9315. nanim_ended = 0;
  9316. alpha_snap = 0; /* lived in the page heap that is being reset */
  9317. alpha_snap_px = 0;
  9318. }
  9319. static int alpha_begin(struct ngui_rect r)
  9320. {
  9321. unsigned int n = (unsigned int)r.w * (unsigned int)r.h;
  9322. int y;
  9323. if (r.w <= 0 || r.h <= 0)
  9324. return 0;
  9325. if (n > alpha_snap_px) {
  9326. free(alpha_snap);
  9327. alpha_snap = (unsigned short *)malloc(n * 2u);
  9328. alpha_snap_px = alpha_snap ? n : 0;
  9329. if (!alpha_snap)
  9330. return 0;
  9331. }
  9332. for (y = 0; y < r.h; y++)
  9333. memcpy(alpha_snap + y * r.w, ui.px + (r.y + y) * ui.w + r.x,
  9334. (unsigned int)r.w * 2u);
  9335. return 1;
  9336. }
  9337. static void alpha_end(struct ngui_rect r, struct ngui_rect box, int a)
  9338. {
  9339. int x, y, x0, x1, y0, y1;
  9340. x0 = box.x > r.x ? box.x : r.x;
  9341. y0 = box.y > r.y ? box.y : r.y;
  9342. x1 = box.x + box.w < r.x + r.w ? box.x + box.w : r.x + r.w;
  9343. y1 = box.y + box.h < r.y + r.h ? box.y + box.h : r.y + r.h;
  9344. for (y = y0; y < y1; y++) {
  9345. unsigned short *d = ui.px + y * ui.w;
  9346. const unsigned short *o = alpha_snap + (y - r.y) * r.w - r.x;
  9347. for (x = x0; x < x1; x++) {
  9348. unsigned int n = d[x], b = o[x];
  9349. unsigned int rr, gg, bb;
  9350. if (n == b)
  9351. continue;
  9352. rr = (((n >> 11) & 31) * a + ((b >> 11) & 31) *
  9353. (255 - a)) / 255;
  9354. gg = (((n >> 5) & 63) * a + ((b >> 5) & 63) *
  9355. (255 - a)) / 255;
  9356. bb = ((n & 31) * a + (b & 31) * (255 - a)) / 255;
  9357. d[x] = (unsigned short)(rr << 11 | gg << 5 | bb);
  9358. }
  9359. }
  9360. }
  9361. static void layout_block(struct lay *l, unsigned int node,
  9362. const struct br_style *st, int depth,
  9363. unsigned short link)
  9364. {
  9365. int old_left = l->left, old_right = l->right, old_align = l->align;
  9366. int parent_cb_h = l->cb_h;
  9367. int saved_parent_top = l->parent_top;
  9368. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  9369. int saved_cb_top = l->cb_top;
  9370. int top, l0, r0;
  9371. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  9372. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  9373. int deco_w, deco_h, content_w, content_h, box_h;
  9374. int img_dh = 0;
  9375. int definite_w = 0;
  9376. int normal_top = 0;
  9377. int rel_dx = 0, rel_dy = 0;
  9378. int clip_pushed = 0;
  9379. struct ngui_rect clip_rect;
  9380. /* A DOM level costs about two depth units (layout_block ->
  9381. * layout_children), so 48 covers a ~24-level page. Real news pages
  9382. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  9383. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  9384. return;
  9385. flow_y = l->y;
  9386. flow_left = l->left;
  9387. flow_right = l->right;
  9388. positioned = st->pos == 1 || st->pos == 2;
  9389. relative = st->pos == 3;
  9390. sticky = st->pos == 4;
  9391. shifted = relative || sticky || st->transform_set;
  9392. if (positioned) {
  9393. int def_w = st->width_kind == 1 ? st->width : -1;
  9394. if (st->pos == 2) {
  9395. int avail_w = page_rect.w - 12;
  9396. if (st->right_set && def_w >= 0)
  9397. l->left = page_rect.x + avail_w - st->right -
  9398. def_w;
  9399. else if (!st->left_set && !st->right_set)
  9400. l->left = flow_left; /* static position */
  9401. else
  9402. l->left = page_rect.x +
  9403. (st->left_set ? st->left : 0);
  9404. l->right = def_w >= 0 ? l->left + def_w :
  9405. st->width_kind == 2 ?
  9406. l->left + avail_w * (int)st->width / 100 :
  9407. page_rect.x + avail_w;
  9408. /* Placed by `bottom` (a page footer): an auto
  9409. * height is the measured one. */
  9410. if (st->bottom_set && st->height_kind)
  9411. l->y = page_rect.y + page_rect.h -
  9412. st->bottom -
  9413. style_height_px(st, page_rect.w);
  9414. else if (st->bottom_set && !st->top_set &&
  9415. block_h[node])
  9416. l->y = page_rect.y + page_rect.h -
  9417. st->bottom - (int)block_h[node] -
  9418. mp_px(st, 0, avail_w) -
  9419. mp_px(st, 2, avail_w);
  9420. else
  9421. l->y = page_rect.y +
  9422. (st->top_set ? st->top : 0);
  9423. } else {
  9424. int left = flow_left + (st->left_set ? st->left : 0);
  9425. unsigned int parent = doc.nodes[node].parent;
  9426. if (st->right_set && def_w >= 0)
  9427. left = flow_right - st->right - def_w;
  9428. l->left = left;
  9429. l->right = def_w >= 0 ? left + def_w :
  9430. flow_right +
  9431. (st->left_set ? st->left : 0);
  9432. l->y = flow_y + (st->top_set ? st->top : 0);
  9433. if (st->bottom_set && st->height_kind &&
  9434. parent < BR_MAX_NODES && block_h[parent] > 0)
  9435. l->y = flow_y + block_h[parent] - st->bottom -
  9436. style_height_px(st, old_right - old_left);
  9437. else if (st->bottom_set && !st->top_set &&
  9438. parent < BR_MAX_NODES && block_h[parent] > 0 &&
  9439. block_h[node] > 0)
  9440. l->y = flow_y + block_h[parent] - st->bottom -
  9441. (int)block_h[node] -
  9442. mp_px(st, 0, old_right - old_left) -
  9443. mp_px(st, 2, old_right - old_left);
  9444. }
  9445. /* An auto width placed by one horizontal offset is
  9446. * shrink-to-fit (CSS 2.1 10.3.7): a Bootstrap tooltip or a
  9447. * dropdown is as wide as its content, not its containing
  9448. * block. With neither offset the box keeps the containing
  9449. * width, since `inset: 0` overlays are not parsed and only
  9450. * stretch that way; an empty measure keeps it too. */
  9451. if (st->width_kind == 0 && st->left_set != st->right_set) {
  9452. int cb_l = st->pos == 2 ? page_rect.x : flow_left;
  9453. int cb_r = st->pos == 2 ? page_rect.x +
  9454. page_rect.w - 12 : flow_right;
  9455. int avail = cb_r - cb_l - (st->left_set ? st->left :
  9456. st->right);
  9457. int w = intrinsic_width(l->ui, node, st, 0,
  9458. cb_r - cb_l);
  9459. if (w > 0) {
  9460. w += mp_px(st, 7, cb_r - cb_l) +
  9461. mp_px(st, 5, cb_r - cb_l) +
  9462. mp_px(st, 3, cb_r - cb_l) +
  9463. mp_px(st, 1, cb_r - cb_l) +
  9464. st->border_w[1] + st->border_w[3];
  9465. if (st->max_width_kind == 1 &&
  9466. w > (int)st->max_width)
  9467. w = (int)st->max_width;
  9468. if (avail > 8 && w > avail)
  9469. w = avail;
  9470. if (st->right_set) {
  9471. l->right = cb_r - st->right;
  9472. l->left = l->right - w;
  9473. } else {
  9474. l->right = l->left + w;
  9475. }
  9476. }
  9477. }
  9478. /* `left: 100%` parks a box (Docusaurus' "Skip to main
  9479. * content" link) past the containing block's right edge
  9480. * until it is focused. An auto width then has no room: it
  9481. * used to collapse to 8 px and wrap one word per line into a
  9482. * tall column painted over the page. Lay it out at the
  9483. * containing block's width so it stays one line and
  9484. * overflows (off-screen) like in a real browser. */
  9485. if (def_w < 0 && l->right - l->left < 8) {
  9486. int avail = st->pos == 2 ? page_rect.w - 12 :
  9487. flow_right - flow_left;
  9488. l->right = l->left + (avail > 8 ? avail : 8);
  9489. }
  9490. old_left = l->left;
  9491. old_right = l->right;
  9492. } else if (relative) {
  9493. rel_dx = st->left_set ? st->left :
  9494. (st->right_set ? -st->right : 0);
  9495. rel_dy = st->top_set ? st->top :
  9496. (st->bottom_set ? -st->bottom : 0);
  9497. }
  9498. if (st->transform_set || (st->tr_mask & BR_TR_TRANSFORM) ||
  9499. (render_pass && anim_has(node))) {
  9500. int tx = st->tx, ty = st->ty;
  9501. /* translate(0, -25%): a percentage of the element's own
  9502. * box (the measure pass's height, the flow width). */
  9503. if (st->tx_pct)
  9504. tx = (old_right - old_left) * st->tx / 100;
  9505. if (st->ty_pct)
  9506. ty = node < BR_MAX_NODES ? block_h[node] * st->ty / 100
  9507. : 0;
  9508. if (!st->transform_set)
  9509. tx = ty = 0;
  9510. tx = anim_value(node, ANIM_TX, tx, st);
  9511. ty = anim_value(node, ANIM_TY, ty, st);
  9512. rel_dx += tx;
  9513. rel_dy += ty;
  9514. if (tx || ty)
  9515. shifted = 1;
  9516. }
  9517. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  9518. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  9519. doc.nodes[node].tag == BR_TAG_SELECT ||
  9520. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  9521. !button_has_elements(node)) {
  9522. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  9523. s_eq(br_type(&doc, node), "hidden"))
  9524. return;
  9525. /* Reached as a block-level box (a flex item): the control
  9526. * fills the box the caller assigned, and its line is flushed
  9527. * here; flex layout resets the run list for the next item, so
  9528. * a queued run would never be drawn. */
  9529. form_fill_line = 1;
  9530. add_form_run(l, node, st, link);
  9531. form_fill_line = 0;
  9532. flush_line(l);
  9533. return;
  9534. }
  9535. flush_line(l);
  9536. cbw = old_right - old_left;
  9537. if (cbw < 8)
  9538. cbw = 8;
  9539. l->y += mp_px(st, 0, cbw);
  9540. top = l->y;
  9541. ml = mp_px(st, 3, cbw);
  9542. mr = mp_px(st, 1, cbw);
  9543. bl = st->border_w[3];
  9544. br = st->border_w[1];
  9545. pl = mp_px(st, 7, cbw);
  9546. pr = mp_px(st, 5, cbw);
  9547. bt = st->border_w[0];
  9548. bb = st->border_w[2];
  9549. pt = mp_px(st, 4, cbw);
  9550. pb = mp_px(st, 6, cbw);
  9551. deco_w = bl + br + pl + pr;
  9552. deco_h = bt + bb + pt + pb;
  9553. if (st->width_kind) {
  9554. int w;
  9555. if (st->width_kind == 3)
  9556. w = cbw * st->width_calc_pct / 100 +
  9557. st->width_calc_px;
  9558. else
  9559. w = css_size(st->width_kind, st->width, cbw);
  9560. if (w < 0)
  9561. w = 0;
  9562. content_w = st->box_sizing ? w - deco_w : w;
  9563. definite_w = 1;
  9564. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  9565. doc.nodes[node].tag == BR_TAG_TD ||
  9566. doc.nodes[node].tag == BR_TAG_TH) &&
  9567. doc.nodes[node].width_attr) {
  9568. /* Legacy table/cell width attributes: percentages resolve
  9569. * against the containing block, bare numbers are pixels. */
  9570. int w = doc.nodes[node].width_pct ?
  9571. cbw * doc.nodes[node].width_attr / 100 :
  9572. doc.nodes[node].width_attr;
  9573. if (w < 0)
  9574. w = 0;
  9575. content_w = st->box_sizing ? w - deco_w : w;
  9576. definite_w = 1;
  9577. } else {
  9578. content_w = cbw - ml - mr - deco_w;
  9579. }
  9580. if (content_w < 0)
  9581. content_w = 0;
  9582. if (st->max_width_kind) {
  9583. int mw = st->max_width_kind == 3 ?
  9584. cbw * st->max_width_calc_pct / 100 +
  9585. st->max_width_calc_px :
  9586. css_size(st->max_width_kind, st->max_width, cbw);
  9587. int max_box = st->box_sizing ? mw : mw + deco_w;
  9588. /* A clamped auto width is used as the width, so auto
  9589. * margins share the rest (Google's 688 px search box). */
  9590. if (content_w + deco_w > max_box) {
  9591. content_w = max_box - deco_w;
  9592. definite_w = 1;
  9593. }
  9594. }
  9595. if (st->min_width_kind) {
  9596. int mw = st->min_width_kind == 3 ?
  9597. cbw * st->min_width_calc_pct / 100 +
  9598. st->min_width_calc_px :
  9599. css_size(st->min_width_kind, st->min_width, cbw);
  9600. int min_box = st->box_sizing ? mw : mw + deco_w;
  9601. if (content_w + deco_w < min_box) {
  9602. content_w = min_box - deco_w;
  9603. definite_w = 1;
  9604. }
  9605. }
  9606. if (content_w < 8)
  9607. content_w = 8;
  9608. if (definite_w) {
  9609. int free_w = cbw - ml - mr - deco_w - content_w;
  9610. if (free_w < 0)
  9611. free_w = 0;
  9612. if (st->ml_auto && st->mr_auto) {
  9613. ml = free_w / 2;
  9614. mr = free_w - ml;
  9615. } else if (st->ml_auto) {
  9616. ml = free_w;
  9617. } else if (st->mr_auto) {
  9618. mr = free_w;
  9619. }
  9620. }
  9621. if (doc.nodes[node].tag == BR_TAG_IMG) {
  9622. int iw, ih;
  9623. image_block_size(node, st, cbw, &iw, &ih);
  9624. content_w = iw;
  9625. img_dh = ih;
  9626. }
  9627. l0 = old_left + ml;
  9628. r0 = l0 + deco_w + content_w;
  9629. if (r0 < l0 + 8)
  9630. r0 = l0 + 8;
  9631. normal_top = top;
  9632. if (sticky) {
  9633. if (st->top_set) {
  9634. int stick = page_rect.y + st->top;
  9635. if (normal_top < stick)
  9636. rel_dy += stick - normal_top;
  9637. } else if (st->bottom_set && block_h[node]) {
  9638. int stick = page_rect.y + page_rect.h - st->bottom -
  9639. block_h[node];
  9640. if (normal_top > stick)
  9641. rel_dy += stick - normal_top;
  9642. }
  9643. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  9644. block_h[doc.nodes[node].parent]) {
  9645. unsigned int p = doc.nodes[node].parent;
  9646. int ptop = l->parent_top;
  9647. int pbottom = ptop + block_h[p];
  9648. int eh = block_h[node];
  9649. int moved_top = normal_top + rel_dy;
  9650. int moved_bottom = moved_top + eh;
  9651. if (moved_bottom > pbottom)
  9652. rel_dy -= moved_bottom - pbottom;
  9653. moved_top = normal_top + rel_dy;
  9654. if (moved_top < ptop)
  9655. rel_dy += ptop - moved_top;
  9656. }
  9657. }
  9658. if (shifted && l->draw) {
  9659. top += rel_dy;
  9660. l0 += rel_dx;
  9661. r0 += rel_dx;
  9662. }
  9663. l->parent_top = top;
  9664. if (st->pos != 0) {
  9665. /* Positioned boxes establish the containing block for their
  9666. * absolutely positioned descendants. */
  9667. l->cb_left = l0;
  9668. l->cb_right = r0;
  9669. l->cb_top = top;
  9670. }
  9671. if (l->draw && block_h[node] &&
  9672. top < page_rect.y + page_rect.h &&
  9673. top + block_h[node] > page_rect.y) {
  9674. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  9675. int rtl = css_radius(st, 0, box.w, box.h);
  9676. int rtr = css_radius(st, 1, box.w, box.h);
  9677. int rbr = css_radius(st, 2, box.w, box.h);
  9678. int rbl = css_radius(st, 3, box.w, box.h);
  9679. if (st->transform_scale) {
  9680. if (st->has_bg)
  9681. fill_transformed_rect(l->ui, box, st->bg, st);
  9682. } else if (rtl || rtr || rbr || rbl) {
  9683. if (st->has_bg) {
  9684. int bw = st->border_w[0];
  9685. if (bw > 0 && !st->border_t[0] &&
  9686. st->border_c[0] != st->bg &&
  9687. box.w > bw * 2 && box.h > bw * 2) {
  9688. struct ngui_rect inner = {
  9689. box.x + bw, box.y + bw,
  9690. box.w - bw * 2, box.h - bw * 2
  9691. };
  9692. int itl = rtl > bw ? rtl - bw : 0;
  9693. int itr = rtr > bw ? rtr - bw : 0;
  9694. int ibr = rbr > bw ? rbr - bw : 0;
  9695. int ibl = rbl > bw ? rbl - bw : 0;
  9696. ngui_fill_round_rect(l->ui, box, rtl,
  9697. rtr, rbr, rbl,
  9698. st->border_c[0]);
  9699. ngui_fill_round_rect(l->ui, inner,
  9700. itl, itr, ibr,
  9701. ibl, st->bg);
  9702. } else {
  9703. ngui_fill_round_rect(l->ui, box, rtl,
  9704. rtr, rbr, rbl,
  9705. st->bg);
  9706. }
  9707. } else if (st->border_w[0] && !st->border_t[0]) {
  9708. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  9709. rbl, st->border_w[0],
  9710. st->border_c[0]);
  9711. }
  9712. /* Rounded boxes paint their background image too
  9713. * (app icons are rounded squares), kept inside the
  9714. * corner arcs. */
  9715. if (st->bg_image)
  9716. draw_bg_image_round(l, box, node, st, rtl, rtr,
  9717. rbr, rbl);
  9718. } else {
  9719. if (st->has_bg)
  9720. ngui_fill_rect(l->ui, box, st->bg);
  9721. if (st->bg_image)
  9722. draw_bg_image(l, box, node, st);
  9723. if (st->border_w[0] || st->border_w[1] ||
  9724. st->border_w[2] || st->border_w[3])
  9725. draw_border_box(l->ui, box, st);
  9726. }
  9727. }
  9728. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  9729. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  9730. content_w, img_dh);
  9731. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  9732. l->ui && l->ui->nclip < 4) {
  9733. clip_rect.x = l0 + bl;
  9734. clip_rect.y = top + bt;
  9735. clip_rect.w = (r0 - l0) - bl - br;
  9736. clip_rect.h = (int)block_h[node] - bt - bb;
  9737. if (clip_rect.w > 0 && clip_rect.h > 0) {
  9738. ngui_push_clip(l->ui, clip_rect);
  9739. clip_pushed = 1;
  9740. }
  9741. }
  9742. l->left = l0 + bl + pl;
  9743. l->right = l->left + content_w;
  9744. if (l->right < l->left + 8)
  9745. l->right = l->left + 8;
  9746. l->align = st->align;
  9747. l->line_left = l->left;
  9748. l->line_right = l->right;
  9749. l->y = top + bt + pt;
  9750. if (doc.nodes[node].tag == BR_TAG_HR) {
  9751. if (l->draw)
  9752. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  9753. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  9754. l->y += 8;
  9755. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  9756. int vw = l->right - l->left;
  9757. int vh;
  9758. if (doc.nodes[node].width_pct)
  9759. vw = vw * doc.nodes[node].width_attr / 100;
  9760. else if (doc.nodes[node].width_attr)
  9761. vw = doc.nodes[node].width_attr;
  9762. if (vw > l->right - l->left)
  9763. vw = l->right - l->left;
  9764. if (vw < 8)
  9765. vw = 8;
  9766. vh = vw * 9 / 16;
  9767. if (vh > 240)
  9768. vh = 240;
  9769. if (vh < 80)
  9770. vh = 80;
  9771. if (l->draw) {
  9772. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  9773. vw, vh}, 0xD69A);
  9774. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  9775. vw, vh}, 0x8410);
  9776. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  9777. 0x4208);
  9778. }
  9779. l->y += vh + 4;
  9780. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  9781. int dw, dh, cw = l->right - l->left;
  9782. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  9783. if (l->draw && l->y < page_rect.y + page_rect.h &&
  9784. l->y + dh > page_rect.y)
  9785. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  9786. l->y += dh;
  9787. } else {
  9788. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  9789. !st->no_bullet) {
  9790. char *m = li_marker[node];
  9791. if (!m[0]) {
  9792. unsigned int parent = doc.nodes[node].parent;
  9793. int style = st->list_style;
  9794. int idx = parent ? list_index(parent, node) : 1;
  9795. if (style == BR_LIST_AUTO)
  9796. style = (parent &&
  9797. doc.nodes[parent].tag ==
  9798. BR_TAG_OL) ?
  9799. BR_LIST_DECIMAL : BR_LIST_DISC;
  9800. list_marker_text(m, sizeof(li_marker[node]),
  9801. style, idx);
  9802. }
  9803. if (l->draw && m[0]) {
  9804. int mw = (int)ngui_text_width_ui(l->ui, m);
  9805. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  9806. st->color);
  9807. }
  9808. }
  9809. /* This box's definite content height, for its children's
  9810. * percentage heights. */
  9811. if (doc.nodes[node].tag == BR_TAG_HTML ||
  9812. doc.nodes[node].tag == BR_TAG_BODY)
  9813. l->cb_h = layout_view_h;
  9814. else if (st->height_kind == 1)
  9815. l->cb_h = (int)st->height -
  9816. (st->box_sizing ? deco_h : 0);
  9817. else if (st->height_kind == 2 && parent_cb_h > 0)
  9818. l->cb_h = parent_cb_h * (int)st->height / 100 -
  9819. (st->box_sizing ? deco_h : 0);
  9820. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  9821. l->cb_h = content_w * (int)st->aspect_h /
  9822. (int)st->aspect_w;
  9823. else if (!st->height_kind && node < BR_MAX_NODES &&
  9824. flex_stretch_h[node] > deco_h)
  9825. l->cb_h = flex_stretch_h[node] - deco_h;
  9826. else
  9827. l->cb_h = 0;
  9828. if (l->cb_h < 0)
  9829. l->cb_h = 0;
  9830. if (doc.nodes[node].tag == BR_TAG_TR)
  9831. layout_table_row(l, node, st, depth + 1, link);
  9832. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  9833. table_has_rowspan(node))
  9834. layout_table(l, node, st, depth + 1, link);
  9835. else if (st->grid_auto)
  9836. layout_grid_auto(l, node, st, depth + 1, link);
  9837. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  9838. st->grid_gap > 0)
  9839. layout_grid_children(l, node, st, depth + 1, link);
  9840. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  9841. flex_wants_row(node, st))
  9842. layout_flex_children(l, node, st, depth + 1, link);
  9843. else if (st->display == BR_DISPLAY_FLEX && st->flex_col)
  9844. layout_flex_column(l, node, st, depth + 1, link);
  9845. else
  9846. layout_children(l, node, st, depth + 1, link);
  9847. l->cb_h = parent_cb_h;
  9848. }
  9849. flush_line(l);
  9850. if (clip_pushed)
  9851. ngui_pop_clip(l->ui);
  9852. if (l->float_active) {
  9853. if (l->y < l->float_bottom)
  9854. l->y = l->float_bottom;
  9855. l->float_active = 0;
  9856. }
  9857. if (doc.nodes[node].tag == BR_TAG_IMG) {
  9858. content_h = img_dh;
  9859. } else if (st->height_kind == 2 &&
  9860. doc.nodes[node].tag != BR_TAG_HTML &&
  9861. doc.nodes[node].tag != BR_TAG_BODY) {
  9862. /* A percentage of the containing block's definite height, or
  9863. * auto when it has none (it used to resolve against the
  9864. * width). The result is a minimum: without scrollable inner
  9865. * boxes, an app shell's height:100%; overflow:hidden column
  9866. * would otherwise clip everything past the first screen. */
  9867. int auto_h = l->y - (top + bt + pt);
  9868. content_h = parent_cb_h > 0 ?
  9869. parent_cb_h * (int)st->height / 100 -
  9870. (st->box_sizing ? deco_h : 0) : 0;
  9871. if (content_h < auto_h)
  9872. content_h = auto_h;
  9873. } else if (st->height_kind &&
  9874. !((doc.nodes[node].tag == BR_TAG_HTML ||
  9875. doc.nodes[node].tag == BR_TAG_BODY) &&
  9876. st->height_kind == 2)) {
  9877. content_h = style_height_px(st, cbw);
  9878. if (st->box_sizing)
  9879. content_h -= deco_h;
  9880. } else {
  9881. /* Percentage heights on html/body resolve against the
  9882. * viewport, but their content still defines the document
  9883. * scroll height. Treating them as auto avoids collapsing
  9884. * the measured page to the containing block width. */
  9885. content_h = l->y - (top + bt + pt);
  9886. /* aspect-ratio: the preferred height of an auto-height box
  9887. * (Tailwind aspect-video image frames); content can still
  9888. * make it taller, as with min-height: auto. */
  9889. if (st->aspect_w && st->aspect_h && content_w > 0) {
  9890. int ah = content_w * (int)st->aspect_h /
  9891. (int)st->aspect_w;
  9892. if (content_h < ah)
  9893. content_h = ah;
  9894. }
  9895. }
  9896. if (content_h < 0)
  9897. content_h = 0;
  9898. if (!st->height_kind && node < BR_MAX_NODES &&
  9899. content_h + deco_h < flex_stretch_h[node])
  9900. content_h = flex_stretch_h[node] - deco_h;
  9901. /* A fixed box pinned by both top and bottom with an auto height
  9902. * spans the viewport between them (Bootstrap's .modal-backdrop is
  9903. * an empty `position: fixed; top: 0; bottom: 0` box). */
  9904. if (!st->height_kind && st->pos == 2 && st->top_set &&
  9905. st->bottom_set) {
  9906. int fh = page_rect.h - st->top - st->bottom - deco_h;
  9907. if (content_h < fh)
  9908. content_h = fh;
  9909. }
  9910. if (st->max_height_kind) {
  9911. int mh = st->max_height_kind == 3 ?
  9912. cbw * st->max_height_calc_pct / 100 +
  9913. st->max_height_calc_px :
  9914. css_size(st->max_height_kind, st->max_height, cbw);
  9915. int max_box = st->box_sizing ? mh : mh + deco_h;
  9916. if (content_h + deco_h > max_box)
  9917. content_h = max_box - deco_h;
  9918. }
  9919. if (st->min_height_kind &&
  9920. !((doc.nodes[node].tag == BR_TAG_HTML ||
  9921. doc.nodes[node].tag == BR_TAG_BODY) &&
  9922. st->min_height_kind == 2)) {
  9923. int mh = st->min_height_kind == 3 ?
  9924. cbw * st->min_height_calc_pct / 100 +
  9925. st->min_height_calc_px :
  9926. css_size(st->min_height_kind, st->min_height, cbw);
  9927. int min_box = st->box_sizing ? mh : mh + deco_h;
  9928. if (content_h + deco_h < min_box)
  9929. content_h = min_box - deco_h;
  9930. }
  9931. if (content_h < 0)
  9932. content_h = 0;
  9933. box_h = deco_h + content_h;
  9934. if (box_h < 0)
  9935. box_h = 0;
  9936. l->y = (shifted ? normal_top : top) + box_h;
  9937. if (node < BR_MAX_NODES) {
  9938. layout_boxes[node].x = l0;
  9939. layout_boxes[node].y = top;
  9940. layout_boxes[node].w = r0 - l0;
  9941. layout_boxes[node].h = box_h;
  9942. layout_boxes[node].valid = r0 > l0;
  9943. }
  9944. l->left = old_left;
  9945. l->right = old_right;
  9946. l->align = old_align;
  9947. l->y += mp_px(st, 2, cbw);
  9948. if (!l->draw) {
  9949. if (box_h > 65535)
  9950. box_h = 65535;
  9951. block_h[node] = (unsigned short)box_h;
  9952. block_top[node] = (unsigned short)(top < 0 ? 0 :
  9953. top > 65535 ? 65535 : top);
  9954. }
  9955. if (positioned) {
  9956. l->y = flow_y;
  9957. l->left = flow_left;
  9958. l->right = flow_right;
  9959. }
  9960. l->parent_top = saved_parent_top;
  9961. l->cb_left = saved_cb_left;
  9962. l->cb_right = saved_cb_right;
  9963. l->cb_top = saved_cb_top;
  9964. }
  9965. static int text_node_blank(const struct br_node *nd)
  9966. {
  9967. const char *t = doc.text + nd->text_off;
  9968. unsigned int i;
  9969. for (i = 0; i < nd->text_len; i++)
  9970. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  9971. t[i] != '\r')
  9972. return 0;
  9973. return 1;
  9974. }
  9975. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  9976. * text/image widths in the subtree, plus padding and margins. This keeps
  9977. * Bootstrap's floated nav items on one line instead of giving each the whole
  9978. * row. */
  9979. static int text_space(char c)
  9980. {
  9981. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  9982. }
  9983. static int intrinsic_width(struct ngui *ui, unsigned int node,
  9984. const struct br_style *pst, int depth, int base)
  9985. {
  9986. unsigned int c;
  9987. int line_w = 0, max_w = 0;
  9988. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  9989. if (depth > 32)
  9990. return 0;
  9991. if (doc.npe_rules) {
  9992. struct br_style ps;
  9993. /* Icon boxes (::before/::after with a size) are inline
  9994. * content of the element. */
  9995. line_w += pseudo_box_w(node, pst, 1, &ps, base) +
  9996. pseudo_box_w(node, pst, 2, &ps, base);
  9997. }
  9998. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9999. struct br_node *nd = &doc.nodes[c];
  10000. struct br_style cs;
  10001. if (nd->type == BR_NODE_TEXT) {
  10002. const char *t = doc.text + nd->text_off;
  10003. unsigned int tn = nd->text_len;
  10004. if (doc.nodes[node].tag == BR_TAG_PRE) {
  10005. line_w += (int)face_text_width(ui, pst, t, tn);
  10006. } else {
  10007. unsigned int ti = 0;
  10008. int first = 1;
  10009. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  10010. int sp = (int)face_text_width(ui, pst, " ", 1);
  10011. while (ti < tn) {
  10012. unsigned int ts;
  10013. while (ti < tn && text_space(t[ti]))
  10014. ti++;
  10015. ts = ti;
  10016. while (ti < tn && !text_space(t[ti]))
  10017. ti++;
  10018. if (ti == ts)
  10019. break;
  10020. if (!first || lead)
  10021. line_w += sp;
  10022. lead = 0;
  10023. line_w += (int)face_text_width(ui, pst,
  10024. t + ts, ti - ts);
  10025. first = 0;
  10026. }
  10027. }
  10028. continue;
  10029. }
  10030. br_style_for(&doc, c, pst, &cs);
  10031. /* Absolute/fixed children take no room in the parent's
  10032. * shrink-to-fit width: a shown Bootstrap tooltip widened the
  10033. * floated navbar list and slid the hovered item away. */
  10034. if (cs.display == BR_DISPLAY_NONE || cs.pos == 1 ||
  10035. cs.pos == 2)
  10036. continue;
  10037. if (nd->tag == BR_TAG_BR) {
  10038. if (line_w > max_w)
  10039. max_w = line_w;
  10040. line_w = 0;
  10041. continue;
  10042. }
  10043. if (nd->tag == BR_TAG_IMG) {
  10044. /* Measure the image as layout will draw it: a CSS or
  10045. * attribute height keeps the intrinsic aspect ratio, and
  10046. * a CSS width overrides the native pixel width. Bootstrap
  10047. * sizes the Cloudron logo with height:40px only. */
  10048. int idx = nd->img_index;
  10049. int iw = 0, ih = 0;
  10050. if (idx >= 0 && idx < image_count &&
  10051. images[idx].state == 1) {
  10052. iw = (int)images[idx].native_w;
  10053. ih = (int)images[idx].native_h;
  10054. if (iw <= 0 || ih <= 0) {
  10055. iw = (int)images[idx].img.w;
  10056. ih = (int)images[idx].img.h;
  10057. }
  10058. }
  10059. if (cs.width_kind) {
  10060. int ww = style_width_px(&cs, base);
  10061. line_w += ww > 0 ? ww : 64;
  10062. } else if (nd->width_attr) {
  10063. line_w += nd->width_attr;
  10064. } else if (nd->height_attr && iw && ih) {
  10065. line_w += iw * (int)nd->height_attr / ih;
  10066. } else if (cs.height_kind && iw && ih) {
  10067. /* A percentage height needs the parent's
  10068. * definite height (the logo's 2rem box), as in
  10069. * add_image_run(); otherwise it is auto. */
  10070. int hh = cs.height_kind == 1 ?
  10071. style_height_px(&cs, base) :
  10072. cs.height_kind == 2 &&
  10073. pst->height_kind == 1 ?
  10074. (int)pst->height * (int)cs.height / 100 :
  10075. 0;
  10076. line_w += hh > 0 ? iw * hh / ih : iw;
  10077. } else if (iw) {
  10078. line_w += iw;
  10079. } else {
  10080. line_w += 64;
  10081. }
  10082. continue;
  10083. }
  10084. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  10085. nd->tag == BR_TAG_TEXTAREA) &&
  10086. !s_eq(br_type(&doc, c), "hidden")) {
  10087. /* Form controls are replaced: CSS width applies even
  10088. * when they are inline (add_form_run's sizes). */
  10089. int fw = cs.width_kind ? style_width_px(&cs, base) :
  10090. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  10091. if (s_eq(br_type(&doc, c), "checkbox") ||
  10092. s_eq(br_type(&doc, c), "radio"))
  10093. fw = 16;
  10094. line_w += (fw > 0 ? fw : 120) +
  10095. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  10096. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  10097. continue;
  10098. }
  10099. if (nd->tag == BR_TAG_SVG) {
  10100. /* A replaced element: its own size, like add_svg_run()
  10101. * (its path children have no width). */
  10102. int sw, sh, sb = cs.width_kind ?
  10103. style_width_px(&cs, base) : base;
  10104. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  10105. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  10106. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  10107. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  10108. line_w += sw;
  10109. } else {
  10110. if (line_w > max_w)
  10111. max_w = line_w;
  10112. line_w = 0;
  10113. if (sw > max_w)
  10114. max_w = sw;
  10115. }
  10116. continue;
  10117. }
  10118. {
  10119. int cw = mp_px(&cs, 7, base) +
  10120. mp_px(&cs, 5, base) +
  10121. mp_px(&cs, 3, base) +
  10122. mp_px(&cs, 1, base) +
  10123. cs.border_w[1] + cs.border_w[3];
  10124. /* width/height do not apply to non-replaced inline
  10125. * boxes. The tagesschau home label is an inline span
  10126. * with width:1px for the mobile icon-only header; using
  10127. * that width made the whole subnav collapse to a
  10128. * one-character column. */
  10129. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  10130. cw += cs.width_kind == 1 ? cs.width :
  10131. style_width_px(&cs, base);
  10132. else
  10133. cw += intrinsic_width(ui, c, &cs, depth + 1,
  10134. base);
  10135. if (flex_row || cs.float_left ||
  10136. cs.display == BR_DISPLAY_INLINE ||
  10137. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  10138. line_w += cw;
  10139. } else {
  10140. if (line_w > max_w)
  10141. max_w = line_w;
  10142. line_w = 0;
  10143. if (cw > max_w)
  10144. max_w = cw;
  10145. }
  10146. }
  10147. if (line_w > 4096 || max_w > 4096)
  10148. break;
  10149. }
  10150. return line_w > max_w ? line_w : max_w;
  10151. }
  10152. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  10153. * the main user: .row > .col-md-* with float:left and a percentage width.
  10154. * Each column is laid out with its own left/right edge and the row advances
  10155. * to the tallest column. Returns the first child not consumed. */
  10156. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  10157. const struct br_style *pst, int depth,
  10158. unsigned short link)
  10159. {
  10160. unsigned int n = first;
  10161. int row_left = l->left, row_right = l->right;
  10162. int row_top, row_bottom, xl, xr, any = 0;
  10163. int fl_left = row_left, fl_right = row_right, fl_bottom;
  10164. flush_line(l);
  10165. row_top = l->y;
  10166. row_bottom = l->y;
  10167. fl_bottom = row_top;
  10168. xl = row_left;
  10169. xr = row_right;
  10170. while (n) {
  10171. struct br_node *nd = &doc.nodes[n];
  10172. struct br_style cs;
  10173. unsigned short lk = link;
  10174. int colw, right;
  10175. if (nd->type == BR_NODE_TEXT) {
  10176. if (text_node_blank(nd)) {
  10177. n = nd->next;
  10178. continue;
  10179. }
  10180. break;
  10181. }
  10182. br_style_for(&doc, n, pst, &cs);
  10183. if (cs.display == BR_DISPLAY_NONE) {
  10184. n = nd->next;
  10185. continue;
  10186. }
  10187. /* A float blockifies its box: Bootstrap floats inline
  10188. * anchors too (the navbar brand and its text links), and
  10189. * their padding must be honoured. */
  10190. /* An absolute/fixed sibling is out of flow and does not end
  10191. * the row: Bootstrap inserts its tooltip right after the
  10192. * hovered navbar <li>, and the row used to break there. */
  10193. if (!cs.float_left && (cs.pos == 1 || cs.pos == 2)) {
  10194. int sy = l->y, sl = l->left, sr = l->right;
  10195. layout_out_of_flow(l, n, &cs, depth, lk);
  10196. l->y = sy;
  10197. l->left = sl;
  10198. l->right = sr;
  10199. n = nd->next;
  10200. continue;
  10201. }
  10202. if (!cs.float_left)
  10203. break;
  10204. if (nd->tag == BR_TAG_A && nd->href_off)
  10205. lk = (unsigned short)n;
  10206. right = cs.float_left == 2;
  10207. if (cs.width_kind == 1 || cs.width_kind == 2 ||
  10208. cs.width_kind == 3) {
  10209. /* The column is the margin box: `width` is the
  10210. * content (or, with border-box, the border) box,
  10211. * and layout_block() takes margins, padding and
  10212. * borders back out of the column. A 200px float
  10213. * with margin-right:20px used to get 180px of
  10214. * content. */
  10215. int base = row_right - row_left;
  10216. colw = cs.width_kind == 1 ? (int)cs.width :
  10217. style_width_px(&cs, base);
  10218. colw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  10219. if (!cs.box_sizing)
  10220. colw += mp_px(&cs, 7, base) +
  10221. mp_px(&cs, 5, base) +
  10222. cs.border_w[1] + cs.border_w[3];
  10223. } else {
  10224. int base = row_right - row_left;
  10225. /* Shrink-to-fit outer width: borders too (Google's
  10226. * 1px-bordered "Anmelden" pill wrapped otherwise). */
  10227. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  10228. mp_px(&cs, 7, base) +
  10229. mp_px(&cs, 5, base) +
  10230. mp_px(&cs, 3, base) +
  10231. mp_px(&cs, 1, base) +
  10232. cs.border_w[1] + cs.border_w[3];
  10233. if (colw < 8)
  10234. colw = 8;
  10235. }
  10236. if (colw < 8)
  10237. colw = 8;
  10238. if (colw > row_right - row_left)
  10239. colw = row_right - row_left;
  10240. /* The float column width is already resolved. */
  10241. cs.width_kind = 0;
  10242. cs.max_width_kind = 0;
  10243. if (right) {
  10244. if (any && xr - colw < xl) {
  10245. row_top = row_bottom;
  10246. row_bottom = row_top;
  10247. xl = row_left;
  10248. xr = row_right;
  10249. }
  10250. if (xr - colw < xl)
  10251. colw = xr - xl;
  10252. if (colw < 8)
  10253. colw = 8;
  10254. l->left = xr - colw;
  10255. if (l->left < row_left)
  10256. l->left = row_left;
  10257. l->right = xr;
  10258. xr = l->left;
  10259. if (xr < fl_right)
  10260. fl_right = xr;
  10261. } else {
  10262. if (any && xl + colw > xr) {
  10263. row_top = row_bottom;
  10264. row_bottom = row_top;
  10265. xl = row_left;
  10266. xr = row_right;
  10267. }
  10268. l->left = xl;
  10269. l->right = xl + colw;
  10270. xl += colw;
  10271. if (xl > fl_left)
  10272. fl_left = xl;
  10273. }
  10274. if (l->right < l->left + 8)
  10275. l->right = l->left + 8;
  10276. l->y = row_top;
  10277. l->line_left = l->line_x = l->left;
  10278. l->run_x = l->left;
  10279. l->line_y = l->y;
  10280. l->line_h = 0;
  10281. l->nruns = 0;
  10282. l->space_pending = 0;
  10283. l->align = cs.align;
  10284. layout_block(l, n, &cs, depth + 1, lk);
  10285. if (l->y > row_bottom)
  10286. row_bottom = l->y;
  10287. if (l->y > fl_bottom)
  10288. fl_bottom = l->y;
  10289. any = 1;
  10290. n = nd->next;
  10291. }
  10292. l->left = row_left;
  10293. l->right = row_right;
  10294. if (n && any) {
  10295. struct br_node *nd = &doc.nodes[n];
  10296. int inline_next = 0;
  10297. if (nd->type == BR_NODE_TEXT) {
  10298. inline_next = 1;
  10299. } else if (nd->type == BR_NODE_ELEM) {
  10300. struct br_style cs;
  10301. br_style_for(&doc, n, pst, &cs);
  10302. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  10303. cs.display != BR_DISPLAY_NONE &&
  10304. !br_tag_is_block(nd->tag);
  10305. }
  10306. if (inline_next) {
  10307. if (l->float_active) {
  10308. if (l->float_left > fl_left)
  10309. fl_left = l->float_left;
  10310. if (l->float_right < fl_right)
  10311. fl_right = l->float_right;
  10312. if (l->float_bottom > fl_bottom)
  10313. fl_bottom = l->float_bottom;
  10314. }
  10315. l->float_active = 1;
  10316. l->float_left = fl_left;
  10317. l->float_right = fl_right;
  10318. l->float_bottom = fl_bottom;
  10319. l->y = row_top;
  10320. } else {
  10321. l->float_active = 0;
  10322. l->y = row_bottom;
  10323. }
  10324. } else {
  10325. l->float_active = 0;
  10326. l->y = row_bottom;
  10327. }
  10328. l->line_x = l->left;
  10329. l->run_x = l->left;
  10330. l->line_left = l->left;
  10331. l->line_right = l->right;
  10332. l->line_y = l->y;
  10333. l->line_h = 0;
  10334. l->nruns = 0;
  10335. l->space_pending = 0;
  10336. return n;
  10337. }
  10338. static int flex_item_width(struct lay *l, unsigned int n,
  10339. const struct br_style *cs, int avail)
  10340. {
  10341. struct br_node *nd = &doc.nodes[n];
  10342. (void)l;
  10343. int w;
  10344. if (cs->width_kind == 2 || cs->width_kind == 3)
  10345. w = style_width_px(cs, avail);
  10346. else if (cs->width_kind == 1)
  10347. w = (int)cs->width;
  10348. else if (nd->tag == BR_TAG_IMG) {
  10349. int idx = nd->img_index;
  10350. if (idx >= 0 && idx < image_count &&
  10351. images[idx].state == 1)
  10352. w = (int)images[idx].img.w;
  10353. else if (nd->width_attr)
  10354. w = (int)nd->width_attr;
  10355. else
  10356. w = 64;
  10357. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  10358. nd->tag == BR_TAG_TEXTAREA) {
  10359. /* A control has no content to measure: its default size
  10360. * (a search field in a filter bar). */
  10361. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  10362. } else {
  10363. w = intrinsic_width(l->ui, n, cs, 0, avail);
  10364. }
  10365. /* Explicit widths are content-box sizes; the flex item's outer width
  10366. * must include padding, borders and margins. */
  10367. w += mp_px(cs, 7, avail);
  10368. w += mp_px(cs, 5, avail);
  10369. w += mp_px(cs, 3, avail);
  10370. w += mp_px(cs, 1, avail);
  10371. w += cs->border_w[1] + cs->border_w[3];
  10372. if (w < 24)
  10373. w = 24;
  10374. if (w > avail)
  10375. w = avail;
  10376. return w;
  10377. }
  10378. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  10379. int depth);
  10380. /* An inline child of a text-only inline-block: the same test minus the
  10381. * display check (an inline <span> may have padding/background in CSS, but
  10382. * the inline path paints those for spans anyway). */
  10383. static int inline_block_flows_inline(unsigned int node,
  10384. const struct br_style *cs, int depth)
  10385. {
  10386. unsigned int c;
  10387. if (depth > 3 || cs->pos)
  10388. return 0;
  10389. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  10390. const struct br_node *nd = &doc.nodes[c];
  10391. struct br_style ch;
  10392. if (nd->type != BR_NODE_ELEM)
  10393. continue;
  10394. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  10395. br_tag_is_block(nd->tag))
  10396. return 0;
  10397. br_style_for(&doc, c, cs, &ch);
  10398. if (ch.display == BR_DISPLAY_NONE)
  10399. continue;
  10400. if (ch.display != BR_DISPLAY_INLINE ||
  10401. !inline_block_flows_inline(c, &ch, depth + 1))
  10402. return 0;
  10403. }
  10404. return 1;
  10405. }
  10406. /* An inline-block that is only text in a line (a <time> in a byline, a
  10407. * label) with no box of its own -- no size, background, border or padding
  10408. * -- lays out exactly like an inline element, so it stays in the text line
  10409. * instead of ending it. Boxes with any of those keep the row path. */
  10410. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  10411. int depth)
  10412. {
  10413. unsigned int c;
  10414. int i;
  10415. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  10416. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  10417. cs->pos || depth > 3)
  10418. return 0;
  10419. for (i = 0; i < 4; i++)
  10420. if (cs->border_w[i])
  10421. return 0;
  10422. for (i = 4; i < 8; i++)
  10423. if (mp_px(cs, i, 0) > 0)
  10424. return 0;
  10425. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  10426. const struct br_node *nd = &doc.nodes[c];
  10427. struct br_style ch;
  10428. if (nd->type != BR_NODE_ELEM)
  10429. continue;
  10430. if (nd->tag == BR_TAG_SVG) {
  10431. /* An icon box (Docusaurus' admonition heading:
  10432. * `<span inline-block><svg/></span>Note`): the SVG
  10433. * is an inline replaced run, so the box can stay in
  10434. * the text line. */
  10435. br_style_for(&doc, c, cs, &ch);
  10436. if (ch.display == BR_DISPLAY_NONE ||
  10437. ch.display == BR_DISPLAY_INLINE ||
  10438. ch.display == BR_DISPLAY_INLINE_BLOCK)
  10439. continue;
  10440. return 0;
  10441. }
  10442. if (nd->tag == BR_TAG_IMG || br_tag_is_block(nd->tag))
  10443. return 0;
  10444. br_style_for(&doc, c, cs, &ch);
  10445. if (ch.display == BR_DISPLAY_NONE)
  10446. continue;
  10447. if (ch.display != BR_DISPLAY_INLINE ||
  10448. !inline_block_flows_inline(c, &ch, depth + 1))
  10449. return 0;
  10450. }
  10451. return 1;
  10452. }
  10453. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  10454. * on one line, not one full-width block each. Place intrinsic widths from
  10455. * left to right and wrap when the row is full. */
  10456. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  10457. const struct br_style *pst, int depth,
  10458. unsigned short link)
  10459. {
  10460. unsigned int n = first;
  10461. int row_left = l->left, row_right = l->right;
  10462. int avail = row_right - row_left;
  10463. int x = row_left, y = l->y, row_h = 0, any = 0;
  10464. /* Each box sets l->align from its own style; the text after the row
  10465. * must keep the container's (a centred .fa-fw icon centred the menu
  10466. * label that followed it). */
  10467. unsigned char row_align = l->align;
  10468. flush_line(l);
  10469. y = l->y;
  10470. while (n) {
  10471. struct br_node *nd = &doc.nodes[n];
  10472. struct br_style cs;
  10473. unsigned short lk = link;
  10474. int colw, h;
  10475. if (nd->type == BR_NODE_TEXT) {
  10476. if (!text_node_blank(nd))
  10477. break;
  10478. if (any)
  10479. x += 4;
  10480. n = nd->next;
  10481. continue;
  10482. }
  10483. br_style_for(&doc, n, pst, &cs);
  10484. if (cs.display == BR_DISPLAY_NONE) {
  10485. n = nd->next;
  10486. continue;
  10487. }
  10488. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  10489. break;
  10490. if (nd->tag == BR_TAG_A && nd->href_off)
  10491. lk = (unsigned short)n;
  10492. colw = flex_item_width(l, n, &cs, avail);
  10493. /* A few pixels of slack keep a single long token (boot.S)
  10494. * from wrapping at the exact content width. */
  10495. colw += 8;
  10496. if (colw > avail)
  10497. colw = avail;
  10498. cs.width_kind = 0;
  10499. cs.max_width_kind = 0;
  10500. if (any && x + colw > row_right) {
  10501. y += row_h + 2;
  10502. x = row_left;
  10503. row_h = 0;
  10504. any = 0;
  10505. }
  10506. if (any && x > row_left)
  10507. x += 4;
  10508. l->left = x;
  10509. l->right = x + colw;
  10510. if (l->right < l->left + 8)
  10511. l->right = l->left + 8;
  10512. l->y = y;
  10513. l->line_left = l->line_x = l->left;
  10514. l->run_x = l->left;
  10515. l->line_y = l->y;
  10516. l->line_h = 0;
  10517. l->nruns = 0;
  10518. l->space_pending = 0;
  10519. l->align = cs.align;
  10520. layout_block(l, n, &cs, depth + 1, lk);
  10521. h = l->y - y;
  10522. if (h > row_h)
  10523. row_h = h;
  10524. x += colw;
  10525. any = 1;
  10526. n = nd->next;
  10527. }
  10528. if (any)
  10529. y += row_h;
  10530. l->left = row_left;
  10531. l->right = row_right;
  10532. l->align = row_align;
  10533. l->y = y;
  10534. l->line_left = l->line_x = l->left;
  10535. l->run_x = l->left;
  10536. l->line_y = l->y;
  10537. l->line_h = 0;
  10538. l->nruns = 0;
  10539. l->space_pending = 0;
  10540. return n;
  10541. }
  10542. struct flex_item {
  10543. unsigned int node;
  10544. unsigned short link;
  10545. int w;
  10546. };
  10547. /* An item's min-width/max-width as outer (margin-box) widths in the flex
  10548. * row, or -1 when unset. Percentages and calc() resolve against the
  10549. * container width. */
  10550. static int flex_limit_w(const struct br_style *cs, int which_max, int avail)
  10551. {
  10552. unsigned char kind = which_max ? cs->max_width_kind :
  10553. cs->min_width_kind;
  10554. int w;
  10555. if (kind == 3)
  10556. w = which_max ?
  10557. avail * cs->max_width_calc_pct / 100 +
  10558. cs->max_width_calc_px :
  10559. avail * cs->min_width_calc_pct / 100 +
  10560. cs->min_width_calc_px;
  10561. else
  10562. w = css_size(kind, which_max ? cs->max_width : cs->min_width,
  10563. avail);
  10564. if (w < 0)
  10565. return -1;
  10566. if (!cs->box_sizing)
  10567. w += mp_px(cs, 7, avail) + mp_px(cs, 5, avail) +
  10568. cs->border_w[1] + cs->border_w[3];
  10569. return w + mp_px(cs, 3, avail) + mp_px(cs, 1, avail);
  10570. }
  10571. static int flex_clamp_w(const struct br_style *cs, int w, int avail)
  10572. {
  10573. int mx = flex_limit_w(cs, 1, avail), mn = flex_limit_w(cs, 0, avail);
  10574. if (mx >= 0 && w > mx)
  10575. w = mx;
  10576. if (mn >= 0 && w < mn)
  10577. w = mn;
  10578. return w;
  10579. }
  10580. /* Does a flex row stretch this item to the line height? Only items with
  10581. * no height of their own and align-self/align-items stretch; replaced
  10582. * content (images, icons) keeps its aspect ratio. */
  10583. static int flex_item_stretches(unsigned int node, const struct br_style *cs,
  10584. const struct br_style *pst)
  10585. {
  10586. int ai = cs->align_self ? cs->align_self - 1 : pst->align_items;
  10587. unsigned char tag = doc.nodes[node].tag;
  10588. return ai == 0 && !cs->height_kind && !cs->max_height_kind &&
  10589. tag != BR_TAG_IMG && tag != BR_TAG_SVG && tag != BR_TAG_INPUT &&
  10590. tag != BR_TAG_SELECT && tag != BR_TAG_TEXTAREA &&
  10591. tag != BR_TAG_BUTTON;
  10592. }
  10593. static void flex_set_stretch(unsigned int node, const struct br_style *cs,
  10594. int line_h, int cbw)
  10595. {
  10596. int h = line_h - mp_px(cs, 0, cbw) - mp_px(cs, 2, cbw);
  10597. if (node >= BR_MAX_NODES || h <= 0)
  10598. return;
  10599. if (h > 65535)
  10600. h = 65535;
  10601. flex_stretch_h[node] = (unsigned short)h;
  10602. if (block_h[node] < h)
  10603. block_h[node] = (unsigned short)h;
  10604. }
  10605. static void layout_flex_children(struct lay *l, unsigned int parent,
  10606. const struct br_style *pst, int depth,
  10607. unsigned short link)
  10608. {
  10609. struct flex_item it[32];
  10610. unsigned int c;
  10611. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  10612. int grow_need = 0; /* growing items at their content width */
  10613. int row_left = l->left, row_right = l->right;
  10614. int avail = row_right - row_left;
  10615. int idx, row_top;
  10616. unsigned char row_align = l->align;
  10617. int box_left = l->left, box_right = l->right, row_top0 = l->y;
  10618. int bw = 0, aw = 0, first_h = -1;
  10619. int cont_h = l->cb_h; /* the container's definite content height */
  10620. struct br_style bps, aps;
  10621. if (avail < 8 || depth > 48) {
  10622. layout_children(l, parent, pst, depth, link);
  10623. return;
  10624. }
  10625. /* If direct text is not just whitespace, normal block flow handles it
  10626. * better than pretending it is a flex item. */
  10627. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10628. struct br_node *nd = &doc.nodes[c];
  10629. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  10630. layout_children(l, parent, pst, depth, link);
  10631. return;
  10632. }
  10633. }
  10634. /* ::before/::after icon boxes are the row's first and last items
  10635. * (Docusaurus' sidebar chevron): reserve their columns. */
  10636. if (doc.npe_rules) {
  10637. bw = pseudo_box_w(parent, pst, 1, &bps, avail);
  10638. aw = pseudo_box_w(parent, pst, 2, &aps, avail);
  10639. if (bw + aw > avail - 8) {
  10640. bw = 0;
  10641. aw = 0;
  10642. }
  10643. row_left += bw;
  10644. row_right -= aw;
  10645. avail = row_right - row_left;
  10646. }
  10647. for (c = doc.nodes[parent].first;
  10648. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  10649. c = doc.nodes[c].next) {
  10650. struct br_node *nd = &doc.nodes[c];
  10651. struct br_style cs;
  10652. if (nd->type == BR_NODE_TEXT)
  10653. continue;
  10654. br_style_for(&doc, c, pst, &cs);
  10655. if (cs.display == BR_DISPLAY_NONE)
  10656. continue;
  10657. if ((cs.pos == 1 || cs.pos == 2) &&
  10658. layout_out_of_flow(l, c, &cs, depth,
  10659. (nd->tag == BR_TAG_A && nd->href_off) ?
  10660. (unsigned short)c : link))
  10661. continue; /* absolutely positioned: not an item */
  10662. it[nitem].node = c;
  10663. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  10664. (unsigned short)c : link;
  10665. it[nitem].w = 0;
  10666. if (cs.flex_grow && !cs.width_kind) {
  10667. grow_count++;
  10668. grow_need += flex_item_width(l, c, &cs, avail);
  10669. } else
  10670. fixed += flex_clamp_w(&cs,
  10671. flex_item_width(l, c, &cs, avail),
  10672. avail);
  10673. nitem++;
  10674. }
  10675. /* A narrow container (an icon row sized to its content, Google's
  10676. * mic + lens buttons) is still a row when its items fit; only a
  10677. * narrow one that would overflow or squeeze growing items falls
  10678. * back to block flow. */
  10679. if (avail < 160 && fixed + grow_need > avail) {
  10680. layout_children(l, parent, pst, depth, link);
  10681. return;
  10682. }
  10683. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  10684. /* A growing item capped by max-width (Docusaurus' doc column,
  10685. * `max-width: 75%`; its main container, `calc(100% - 300px)`)
  10686. * keeps its cap and leaves the rest of the free space to the other
  10687. * growing items. */
  10688. if (grow_count) {
  10689. int pass, capped[32] = { 0 };
  10690. for (pass = 0; pass < nitem; pass++) {
  10691. int changed = 0;
  10692. for (idx = 0; idx < nitem; idx++) {
  10693. struct br_style cs;
  10694. int lim;
  10695. if (capped[idx])
  10696. continue;
  10697. br_style_for(&doc, it[idx].node, pst, &cs);
  10698. if (!cs.flex_grow || cs.width_kind)
  10699. continue;
  10700. lim = flex_clamp_w(&cs, grow_w, avail);
  10701. if (lim == grow_w)
  10702. continue;
  10703. capped[idx] = lim + 1;
  10704. fixed += lim;
  10705. grow_count--;
  10706. changed = 1;
  10707. }
  10708. if (!changed || !grow_count)
  10709. break;
  10710. grow_w = (avail - fixed) / grow_count;
  10711. }
  10712. for (idx = 0; idx < nitem; idx++)
  10713. it[idx].w = capped[idx] ? capped[idx] - 1 : 0;
  10714. }
  10715. if (grow_w < 96 && avail >= 160)
  10716. grow_w = 96;
  10717. for (idx = 0; idx < nitem; idx++) {
  10718. struct br_style cs;
  10719. if (it[idx].w)
  10720. continue; /* capped growing item */
  10721. br_style_for(&doc, it[idx].node, pst, &cs);
  10722. if (cs.flex_grow && !cs.width_kind)
  10723. it[idx].w = grow_w;
  10724. else
  10725. it[idx].w = flex_clamp_w(&cs,
  10726. flex_item_width(l,
  10727. it[idx].node,
  10728. &cs, avail),
  10729. avail);
  10730. if (it[idx].w > avail)
  10731. it[idx].w = avail;
  10732. if (it[idx].w < 8)
  10733. it[idx].w = 8;
  10734. }
  10735. row_top = l->y;
  10736. idx = 0;
  10737. while (idx < nitem) {
  10738. int start = idx, count = 0, row_w = 0;
  10739. int free_w, x, extra = 0, row_h = 0, k;
  10740. while (idx < nitem) {
  10741. int add = it[idx].w + (count ? gap : 0);
  10742. /* CSS default is nowrap; only flex-wrap: wrap (1)
  10743. * starts a new row. */
  10744. if (count && pst->flex_wrap == 1 &&
  10745. row_w + add > avail)
  10746. break;
  10747. row_w += add;
  10748. count++;
  10749. idx++;
  10750. }
  10751. if (!count) {
  10752. count = 1;
  10753. row_w = it[start].w;
  10754. idx = start + 1;
  10755. }
  10756. free_w = avail - row_w;
  10757. if (free_w < 0)
  10758. free_w = 0;
  10759. x = row_left;
  10760. if (pst->justify == 1) {
  10761. x += free_w / 2;
  10762. } else if (pst->justify == 2) {
  10763. x += free_w;
  10764. } else if (pst->justify == 3) {
  10765. extra = count > 1 ? free_w / (count - 1) : 0;
  10766. } else if (pst->justify == 4) {
  10767. extra = count ? free_w / count : 0;
  10768. x += extra / 2;
  10769. } else if (pst->justify == 5) {
  10770. extra = count ? free_w / (count + 1) : 0;
  10771. x += extra;
  10772. }
  10773. for (k = 0; k < count; k++) {
  10774. int node = (int)it[start + k].node;
  10775. int h = block_h[node];
  10776. if (h > row_h)
  10777. row_h = h;
  10778. }
  10779. /* A single line fills a definite container height (an app
  10780. * shell's `height: 100%` sidebar + content row). */
  10781. if (pst->flex_wrap != 1 && cont_h > row_h)
  10782. row_h = cont_h;
  10783. else if (pst->height_kind == 1 && (int)pst->height > row_h)
  10784. row_h = pst->height;
  10785. for (k = 0; k < count; k++) {
  10786. struct br_style cs;
  10787. int node = (int)it[start + k].node;
  10788. int yoff = 0;
  10789. br_style_for(&doc, node, pst, &cs);
  10790. cs.width_kind = 0;
  10791. cs.max_width_kind = 0;
  10792. /* align-items: stretch. With a definite line height
  10793. * the item is laid out at it, so its own children see
  10794. * a definite height; otherwise the measure pass
  10795. * stretches it once the line is known (below). */
  10796. if (!l->draw && row_h > 0 && flex_item_stretches(node,
  10797. &cs, pst))
  10798. flex_set_stretch(node, &cs, row_h, avail);
  10799. {
  10800. int ai = cs.align_self ? cs.align_self - 1 :
  10801. pst->align_items;
  10802. if (l->draw && ai && row_h > block_h[node]) {
  10803. if (ai == 1)
  10804. yoff = (row_h -
  10805. block_h[node]) / 2;
  10806. else if (ai == 2)
  10807. yoff = row_h - block_h[node];
  10808. }
  10809. }
  10810. l->left = x;
  10811. l->right = x + it[start + k].w;
  10812. if (l->right < l->left + 8)
  10813. l->right = l->left + 8;
  10814. l->y = row_top + yoff;
  10815. /* line_left too: a stale one from the previous item
  10816. * made flush_line() see a non-empty line and push
  10817. * every later item down by an empty line's height. */
  10818. l->line_left = l->line_x = l->run_x = l->left;
  10819. l->line_right = l->right;
  10820. l->line_y = l->y;
  10821. l->line_h = 0;
  10822. l->nruns = 0;
  10823. l->space_pending = 0;
  10824. l->align = cs.align;
  10825. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  10826. {
  10827. /* Both passes: a form control item has no
  10828. * block_h of its own, so the draw pass would
  10829. * otherwise end a row of only an <input> at
  10830. * height 0 and pull the content below up. */
  10831. int h = l->y - row_top;
  10832. if (h > row_h)
  10833. row_h = h;
  10834. }
  10835. x += it[start + k].w;
  10836. if (k + 1 < count)
  10837. x += gap + extra;
  10838. }
  10839. if (!l->draw) {
  10840. for (k = 0; k < count; k++) {
  10841. struct br_style cs;
  10842. int node = (int)it[start + k].node;
  10843. br_style_for(&doc, node, pst, &cs);
  10844. if (!flex_item_stretches(node, &cs, pst))
  10845. continue;
  10846. /* To the line's bottom edge from where the
  10847. * item really starts (its top margin, or a
  10848. * line box above it). */
  10849. if (layout_boxes[node].valid)
  10850. flex_set_stretch(node, &cs,
  10851. row_top + row_h -
  10852. layout_boxes[node].y +
  10853. mp_px(&cs, 0, avail), avail);
  10854. else
  10855. flex_set_stretch(node, &cs, row_h, avail);
  10856. }
  10857. }
  10858. if (first_h < 0)
  10859. first_h = row_h;
  10860. row_top += row_h;
  10861. }
  10862. if (bw || aw) {
  10863. int pass;
  10864. for (pass = 0; pass < 2; pass++) {
  10865. const struct br_style *ps = pass ? &aps : &bps;
  10866. int a = pass ? row_right : box_left;
  10867. int b = pass ? box_right : row_left;
  10868. int h = ps->height_kind ?
  10869. style_height_px(ps, box_right - box_left) : 0;
  10870. if (!(pass ? aw : bw))
  10871. continue;
  10872. l->left = l->line_left = l->line_x = l->run_x = a;
  10873. l->right = l->line_right = b;
  10874. l->y = row_top0;
  10875. if (pst->align_items == 1 && first_h > h)
  10876. l->y += (first_h - h) / 2;
  10877. l->line_y = l->y;
  10878. l->line_h = 0;
  10879. l->nruns = 0;
  10880. l->space_pending = 0;
  10881. emit_pseudo_box(l, pst, ps, link);
  10882. flush_line(l);
  10883. /* The box sits inside the first row; it only makes
  10884. * the row taller when it is taller itself. */
  10885. if (row_top0 + h > row_top)
  10886. row_top = row_top0 + h;
  10887. }
  10888. }
  10889. l->left = box_left;
  10890. l->right = box_right;
  10891. l->align = row_align;
  10892. l->y = row_top;
  10893. l->line_left = l->line_x = l->run_x = l->left;
  10894. l->line_right = l->right;
  10895. l->line_y = l->y;
  10896. l->line_h = 0;
  10897. l->nruns = 0;
  10898. l->space_pending = 0;
  10899. }
  10900. /* flex-direction: column. Items stack in order with the gap and never
  10901. * collapse margins. In the draw pass justify-content shares out the free
  10902. * height of the container's measured box (a definite or min-height, or a
  10903. * row stretch), and align-items places each item: stretch (the default)
  10904. * fills the line, start/center/end shrink an item to its content width
  10905. * (a login form's "Log in" button, a centred logo and name). */
  10906. static void layout_flex_column(struct lay *l, unsigned int parent,
  10907. const struct br_style *pst, int depth,
  10908. unsigned short link)
  10909. {
  10910. unsigned int c;
  10911. int box_left = l->left, box_right = l->right;
  10912. int avail = box_right - box_left;
  10913. int gap = pst->grid_gap, y0 = l->y;
  10914. int n = 0, k = 0, total = 0, lead = 0, extra = 0;
  10915. unsigned char row_align = l->align;
  10916. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10917. struct br_node *nd = &doc.nodes[c];
  10918. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd))
  10919. break;
  10920. }
  10921. if (c || avail < 8 || depth > 48) {
  10922. /* Loose text: block flow, with centred lines standing in
  10923. * for align-items: center. */
  10924. struct br_style cst = *pst;
  10925. if (pst->align_items == 1) {
  10926. cst.align = BR_ALIGN_CENTER;
  10927. l->align = BR_ALIGN_CENTER;
  10928. }
  10929. layout_children(l, parent, &cst, depth, link);
  10930. return;
  10931. }
  10932. emit_pseudo(l, parent, pst, 1, link);
  10933. flush_line(l);
  10934. y0 = l->y;
  10935. if (l->draw && parent < BR_MAX_NODES && block_h[parent]) {
  10936. int inner = (int)block_h[parent] - pst->border_w[0] -
  10937. pst->border_w[2] - mp_px(pst, 4, avail) -
  10938. mp_px(pst, 6, avail) - (y0 - l->parent_top -
  10939. pst->border_w[0] - mp_px(pst, 4, avail));
  10940. int free_h;
  10941. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10942. struct br_style cs;
  10943. if (doc.nodes[c].type != BR_NODE_ELEM)
  10944. continue;
  10945. br_style_for(&doc, c, pst, &cs);
  10946. if (cs.display == BR_DISPLAY_NONE || cs.pos == 1 ||
  10947. cs.pos == 2)
  10948. continue;
  10949. total += block_h[c] + mp_px(&cs, 0, avail) +
  10950. mp_px(&cs, 2, avail);
  10951. n++;
  10952. }
  10953. if (n > 1)
  10954. total += gap * (n - 1);
  10955. free_h = inner - total;
  10956. if (n && free_h > 0) {
  10957. if (pst->justify == 1) {
  10958. lead = free_h / 2;
  10959. } else if (pst->justify == 2) {
  10960. lead = free_h;
  10961. } else if (pst->justify == 3) {
  10962. extra = n > 1 ? free_h / (n - 1) : 0;
  10963. } else if (pst->justify == 4) {
  10964. extra = free_h / n;
  10965. lead = extra / 2;
  10966. } else if (pst->justify == 5) {
  10967. extra = free_h / (n + 1);
  10968. lead = extra;
  10969. }
  10970. }
  10971. }
  10972. l->y = y0 + lead;
  10973. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10974. struct br_node *nd = &doc.nodes[c];
  10975. unsigned short lk = (nd->tag == BR_TAG_A && nd->href_off) ?
  10976. (unsigned short)c : link;
  10977. struct br_style cs;
  10978. int ai, left = box_left, right = box_right;
  10979. if (nd->type != BR_NODE_ELEM)
  10980. continue;
  10981. br_style_for(&doc, c, pst, &cs);
  10982. if (cs.display == BR_DISPLAY_NONE)
  10983. continue;
  10984. if ((cs.pos == 1 || cs.pos == 2) &&
  10985. layout_out_of_flow(l, c, &cs, depth, lk))
  10986. continue;
  10987. if (k++)
  10988. l->y += gap + extra;
  10989. ai = cs.align_self ? cs.align_self - 1 : pst->align_items;
  10990. if (ai) {
  10991. int w = flex_clamp_w(&cs, flex_item_width(l, c, &cs,
  10992. avail),
  10993. avail);
  10994. if (ai == 1)
  10995. left += (avail - w) / 2;
  10996. else if (ai == 2)
  10997. left += avail - w;
  10998. right = left + w;
  10999. cs.width_kind = 0;
  11000. cs.max_width_kind = 0;
  11001. }
  11002. l->left = l->line_left = l->line_x = l->run_x = left;
  11003. l->right = l->line_right = right;
  11004. l->line_y = l->y;
  11005. l->line_h = 0;
  11006. l->nruns = 0;
  11007. l->space_pending = 0;
  11008. l->align = cs.align;
  11009. layout_block(l, c, &cs, depth + 1, lk);
  11010. }
  11011. l->left = l->line_left = l->line_x = l->run_x = box_left;
  11012. l->right = l->line_right = box_right;
  11013. l->align = row_align;
  11014. l->line_y = l->y;
  11015. l->line_h = 0;
  11016. l->nruns = 0;
  11017. l->space_pending = 0;
  11018. emit_pseudo(l, parent, pst, 2, link);
  11019. }
  11020. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  11021. * plus the grid-area hints used by site shells (site notice/footer full
  11022. * width, column-start left, page-content right). Anything more elaborate
  11023. * falls back to normal block flow. */
  11024. static int grid_track_width(unsigned char kind, unsigned short val,
  11025. int avail, int other)
  11026. {
  11027. if (kind == 2)
  11028. return avail * (int)val / 100;
  11029. if (kind == 1)
  11030. return val;
  11031. return other;
  11032. }
  11033. static void layout_grid_children(struct lay *l, unsigned int parent,
  11034. const struct br_style *pst, int depth,
  11035. unsigned short link)
  11036. {
  11037. unsigned int n;
  11038. int row_left = l->left, row_right = l->right;
  11039. int avail = row_right - row_left;
  11040. int gap = pst->grid_gap;
  11041. int track_total = avail - gap;
  11042. int col0, col1, x0, x1;
  11043. int row_y, row_bottom, have_left = 0, have_right = 0;
  11044. unsigned int c;
  11045. if (avail < 32 || depth > 48)
  11046. return;
  11047. if (track_total < 16)
  11048. track_total = 16;
  11049. col0 = grid_track_width((unsigned char)(pst->width_kind),
  11050. pst->width, track_total, 0);
  11051. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  11052. pst->max_width, track_total, 0);
  11053. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  11054. int w0 = pst->width ? pst->width : 1;
  11055. int w1 = pst->max_width ? pst->max_width : 1;
  11056. col0 = track_total * w0 / (w0 + w1);
  11057. col1 = track_total - col0;
  11058. } else if (pst->width_kind == 3) {
  11059. col0 = track_total - col1;
  11060. if (col0 < 24)
  11061. col0 = 24;
  11062. } else if (pst->max_width_kind == 3) {
  11063. col1 = track_total - col0;
  11064. if (col1 < 24)
  11065. col1 = 24;
  11066. }
  11067. if (col0 < 24)
  11068. col0 = 24;
  11069. if (col1 < 24)
  11070. col1 = 24;
  11071. if (col0 + col1 > track_total) {
  11072. col1 = track_total - col0;
  11073. if (col1 < 24)
  11074. col1 = 24;
  11075. }
  11076. x0 = row_left;
  11077. x1 = row_left + col0 + gap;
  11078. /* Direct text makes a grid ambiguous; use block flow instead. */
  11079. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  11080. struct br_node *nd = &doc.nodes[c];
  11081. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  11082. layout_children(l, parent, pst, depth, link);
  11083. return;
  11084. }
  11085. }
  11086. row_y = row_bottom = l->y;
  11087. n = doc.nodes[parent].first;
  11088. while (n) {
  11089. struct br_node *nd = &doc.nodes[n];
  11090. struct br_style cs;
  11091. unsigned short lk = link;
  11092. int slot, x, w;
  11093. if (nd->type == BR_NODE_TEXT) {
  11094. n = nd->next;
  11095. continue;
  11096. }
  11097. br_style_for(&doc, n, pst, &cs);
  11098. if (cs.display == BR_DISPLAY_NONE) {
  11099. n = nd->next;
  11100. continue;
  11101. }
  11102. if (nd->tag == BR_TAG_A && nd->href_off)
  11103. lk = (unsigned short)n;
  11104. slot = cs.grid_slot;
  11105. if (!slot) {
  11106. if (!have_left)
  11107. slot = 2;
  11108. else if (!have_right)
  11109. slot = 3;
  11110. else
  11111. slot = 2;
  11112. }
  11113. if (slot == 1) {
  11114. if (have_left || have_right) {
  11115. row_y = row_bottom;
  11116. have_left = have_right = 0;
  11117. }
  11118. x = row_left;
  11119. w = avail;
  11120. } else if (slot == 2) {
  11121. if (have_left) {
  11122. row_y = row_bottom;
  11123. have_left = have_right = 0;
  11124. }
  11125. x = x0;
  11126. w = col0;
  11127. have_left = 1;
  11128. } else {
  11129. if (have_right) {
  11130. row_y = row_bottom;
  11131. have_left = have_right = 0;
  11132. }
  11133. x = x1;
  11134. w = col1;
  11135. have_right = 1;
  11136. }
  11137. cs.width_kind = 0;
  11138. cs.max_width_kind = 0;
  11139. l->left = x;
  11140. l->right = x + w;
  11141. if (l->right < l->left + 8)
  11142. l->right = l->left + 8;
  11143. l->y = row_y;
  11144. l->line_left = l->line_x = l->left;
  11145. l->run_x = l->left;
  11146. l->line_y = l->y;
  11147. l->line_h = 0;
  11148. l->nruns = 0;
  11149. l->space_pending = 0;
  11150. l->align = cs.align;
  11151. layout_block(l, n, &cs, depth + 1, lk);
  11152. if (l->y > row_bottom)
  11153. row_bottom = l->y;
  11154. n = nd->next;
  11155. }
  11156. l->left = row_left;
  11157. l->right = row_right;
  11158. l->y = row_bottom;
  11159. l->line_left = l->line_x = l->left;
  11160. l->run_x = l->left;
  11161. l->line_y = l->y;
  11162. l->line_h = 0;
  11163. l->nruns = 0;
  11164. l->space_pending = 0;
  11165. }
  11166. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  11167. * capped at four. Used by the project docs' card grids. A fixed
  11168. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  11169. static void layout_grid_auto(struct lay *l, unsigned int parent,
  11170. const struct br_style *pst, int depth,
  11171. unsigned short link)
  11172. {
  11173. unsigned int n, c;
  11174. int row_left = l->left, row_right = l->right;
  11175. int avail = row_right - row_left;
  11176. int gap = pst->grid_gap;
  11177. int minw = pst->width_kind == 1 ? pst->width : 200;
  11178. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  11179. if (avail < 32 || depth > 48) {
  11180. layout_children(l, parent, pst, depth, link);
  11181. return;
  11182. }
  11183. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  11184. struct br_node *nd = &doc.nodes[c];
  11185. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  11186. layout_children(l, parent, pst, depth, link);
  11187. return;
  11188. }
  11189. }
  11190. if (minw < 80)
  11191. minw = 80;
  11192. ncols = (avail + gap) / (minw + gap);
  11193. if (ncols < 1)
  11194. ncols = 1;
  11195. if (ncols > 4)
  11196. ncols = 4;
  11197. if (pst->grid_auto > BR_GRID_FIXED) {
  11198. /* grid-template-columns: repeat(N, 1fr) */
  11199. ncols = pst->grid_auto - BR_GRID_FIXED;
  11200. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  11201. ncols--;
  11202. }
  11203. colw = (avail - gap * (ncols - 1)) / ncols;
  11204. if (colw < 24)
  11205. colw = 24;
  11206. x = row_left;
  11207. n = doc.nodes[parent].first;
  11208. while (n) {
  11209. struct br_node *nd = &doc.nodes[n];
  11210. struct br_style cs;
  11211. unsigned short lk = link;
  11212. int h;
  11213. if (nd->type == BR_NODE_TEXT) {
  11214. n = nd->next;
  11215. continue;
  11216. }
  11217. br_style_for(&doc, n, pst, &cs);
  11218. if (cs.display == BR_DISPLAY_NONE) {
  11219. n = nd->next;
  11220. continue;
  11221. }
  11222. if (nd->tag == BR_TAG_A && nd->href_off)
  11223. lk = (unsigned short)n;
  11224. cs.width_kind = 0;
  11225. cs.max_width_kind = 0;
  11226. l->left = x;
  11227. l->right = x + colw;
  11228. if (l->right < l->left + 8)
  11229. l->right = l->left + 8;
  11230. l->y = y;
  11231. l->line_left = l->line_x = l->left;
  11232. l->run_x = l->left;
  11233. l->line_y = l->y;
  11234. l->line_h = 0;
  11235. l->nruns = 0;
  11236. l->space_pending = 0;
  11237. l->align = cs.align;
  11238. layout_block(l, n, &cs, depth + 1, lk);
  11239. h = l->y - y;
  11240. if (h > row_h)
  11241. row_h = h;
  11242. col++;
  11243. n = nd->next;
  11244. if (col == ncols) {
  11245. y += row_h + gap;
  11246. x = row_left;
  11247. row_h = 0;
  11248. col = 0;
  11249. } else {
  11250. x += colw + gap;
  11251. }
  11252. }
  11253. if (col)
  11254. y += row_h;
  11255. else if (y > start_y)
  11256. y -= gap;
  11257. l->left = row_left;
  11258. l->right = row_right;
  11259. l->y = y;
  11260. l->line_left = l->line_x = l->left;
  11261. l->run_x = l->left;
  11262. l->line_y = l->y;
  11263. l->line_h = 0;
  11264. l->nruns = 0;
  11265. l->space_pending = 0;
  11266. }
  11267. /* Column widths are the widest cell in each column across every row, so all
  11268. * rows line up. The table model is still deliberately basic: no colspan,
  11269. * border-collapse or percentage columns. */
  11270. static void table_columns(struct lay *l, unsigned int table,
  11271. const struct br_style *pst, int avail,
  11272. int *raw, int maxcols, int *out_cols,
  11273. int *out_total)
  11274. {
  11275. unsigned int r, c;
  11276. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  11277. int fixed[12];
  11278. for (c = 0; c < (unsigned int)maxcols; c++) {
  11279. raw[c] = 0;
  11280. fixed[c] = 0;
  11281. }
  11282. /* Intrinsic widths of single-column cells. */
  11283. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  11284. struct br_node *rn = &doc.nodes[r];
  11285. int col = 0;
  11286. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  11287. continue;
  11288. for (c = rn->first; c; c = doc.nodes[c].next) {
  11289. struct br_node *cn = &doc.nodes[c];
  11290. struct br_style cs;
  11291. int w, span;
  11292. if (cn->type != BR_NODE_ELEM ||
  11293. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  11294. continue;
  11295. span = cn->colspan ? cn->colspan : 1;
  11296. br_style_for(&doc, c, pst, &cs);
  11297. if (cs.display == BR_DISPLAY_NONE)
  11298. continue;
  11299. if (col + span > maxcols)
  11300. span = maxcols - col;
  11301. if (span < 1)
  11302. break;
  11303. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  11304. mp_px(&cs, 7, avail) +
  11305. mp_px(&cs, 5, avail) +
  11306. mp_px(&cs, 3, avail) +
  11307. mp_px(&cs, 1, avail) +
  11308. cs.border_w[0] + cs.border_w[1] +
  11309. cs.border_w[2] + cs.border_w[3];
  11310. if (w < 24)
  11311. w = 24;
  11312. if (span == 1) {
  11313. if (w > raw[col])
  11314. raw[col] = w;
  11315. }
  11316. if (col + span > cols)
  11317. cols = col + span;
  11318. col += span;
  11319. }
  11320. }
  11321. /* A colspan cell only has to be as wide as the sum of its columns. */
  11322. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  11323. struct br_node *rn = &doc.nodes[r];
  11324. int col = 0;
  11325. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  11326. continue;
  11327. for (c = rn->first; c; c = doc.nodes[c].next) {
  11328. struct br_node *cn = &doc.nodes[c];
  11329. struct br_style cs;
  11330. int span, w, sum, i;
  11331. if (cn->type != BR_NODE_ELEM ||
  11332. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  11333. continue;
  11334. span = cn->colspan ? cn->colspan : 1;
  11335. if (col + span > maxcols)
  11336. span = maxcols - col;
  11337. if (span < 1)
  11338. break;
  11339. if (span > 1) {
  11340. br_style_for(&doc, c, pst, &cs);
  11341. if (cs.display != BR_DISPLAY_NONE) {
  11342. w = intrinsic_width(l->ui, c, &cs,
  11343. 0, avail) +
  11344. mp_px(&cs, 7, avail) +
  11345. mp_px(&cs, 5, avail) +
  11346. mp_px(&cs, 3, avail) +
  11347. mp_px(&cs, 1, avail) +
  11348. cs.border_w[0] + cs.border_w[1] +
  11349. cs.border_w[2] + cs.border_w[3];
  11350. sum = 0;
  11351. for (i = 0; i < span; i++)
  11352. sum += raw[col + i];
  11353. if (w > sum)
  11354. raw[col + span - 1] += w - sum;
  11355. }
  11356. }
  11357. col += span;
  11358. }
  11359. }
  11360. /* Explicit and percentage widths override intrinsic widths. */
  11361. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  11362. struct br_node *rn = &doc.nodes[r];
  11363. int col = 0;
  11364. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  11365. continue;
  11366. for (c = rn->first; c; c = doc.nodes[c].next) {
  11367. struct br_node *cn = &doc.nodes[c];
  11368. struct br_style cs;
  11369. int span;
  11370. if (cn->type != BR_NODE_ELEM ||
  11371. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  11372. continue;
  11373. span = cn->colspan ? cn->colspan : 1;
  11374. if (col + span > maxcols)
  11375. span = maxcols - col;
  11376. if (span < 1)
  11377. break;
  11378. if (span == 1) {
  11379. br_style_for(&doc, c, pst, &cs);
  11380. if (cs.display != BR_DISPLAY_NONE) {
  11381. if (cs.width_kind == 1) {
  11382. raw[col] = cs.width;
  11383. fixed[col] = 1;
  11384. } else if (cs.width_kind == 2 ||
  11385. cs.width_kind == 3) {
  11386. raw[col] = style_width_px(&cs,
  11387. avail);
  11388. fixed[col] = 1;
  11389. }
  11390. }
  11391. }
  11392. col += span;
  11393. }
  11394. }
  11395. for (c = 0; c < (unsigned int)cols; c++) {
  11396. if (raw[c] < 8)
  11397. raw[c] = 8;
  11398. total += raw[c];
  11399. if (fixed[c])
  11400. fixed_sum += raw[c];
  11401. else {
  11402. free_raw += raw[c];
  11403. free_cols++;
  11404. }
  11405. }
  11406. if (fixed_sum > 0 && fixed_sum < avail) {
  11407. int free_avail = avail - fixed_sum;
  11408. int i;
  11409. if (free_raw > 0) {
  11410. for (i = 0; i < cols; i++)
  11411. if (!fixed[i])
  11412. raw[i] = free_avail * raw[i] /
  11413. free_raw;
  11414. } else if (free_cols > 0) {
  11415. for (i = 0; i < cols; i++)
  11416. if (!fixed[i])
  11417. raw[i] = free_avail / free_cols;
  11418. }
  11419. total = 0;
  11420. for (i = 0; i < cols; i++)
  11421. total += raw[i];
  11422. } else if (total < avail && total > 0) {
  11423. int i;
  11424. for (i = 0; i < cols; i++)
  11425. raw[i] = raw[i] * avail / total;
  11426. total = 0;
  11427. for (i = 0; i < cols; i++)
  11428. total += raw[i];
  11429. }
  11430. *out_cols = cols;
  11431. *out_total = total;
  11432. }
  11433. static void layout_table_row(struct lay *l, unsigned int row,
  11434. const struct br_style *pst, int depth,
  11435. unsigned short link)
  11436. {
  11437. unsigned int n, cell[12];
  11438. int raw[12], colstart[12], colspan[12];
  11439. int prefix[13];
  11440. int ncell = 0, total = 0, cols = 0, col = 0;
  11441. int row_left = l->left, row_right = l->right;
  11442. int avail = row_right - row_left;
  11443. int y = l->y, bottom = l->y;
  11444. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  11445. struct br_node *nd = &doc.nodes[n];
  11446. struct br_style cs;
  11447. int span;
  11448. if (nd->type == BR_NODE_TEXT) {
  11449. if (text_node_blank(nd))
  11450. continue;
  11451. layout_children(l, row, pst, depth, link);
  11452. return;
  11453. }
  11454. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  11455. layout_children(l, row, pst, depth, link);
  11456. return;
  11457. }
  11458. br_style_for(&doc, n, pst, &cs);
  11459. if (cs.display == BR_DISPLAY_NONE)
  11460. continue;
  11461. if (ncell >= 12) {
  11462. layout_children(l, row, pst, depth, link);
  11463. return;
  11464. }
  11465. span = nd->colspan ? nd->colspan : 1;
  11466. if (span > 12 - col)
  11467. span = 12 - col;
  11468. if (span < 1)
  11469. continue;
  11470. cell[ncell] = n;
  11471. colstart[ncell] = col;
  11472. colspan[ncell] = span;
  11473. col += span;
  11474. ncell++;
  11475. }
  11476. if (ncell < 1 || avail < 32) {
  11477. layout_children(l, row, pst, depth, link);
  11478. return;
  11479. }
  11480. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  11481. &total);
  11482. if (cols < 2 || total <= 0) {
  11483. int c;
  11484. total = 0;
  11485. for (c = 0; c < ncell; c++) {
  11486. struct br_style cs;
  11487. br_style_for(&doc, cell[c], pst, &cs);
  11488. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  11489. avail) +
  11490. mp_px(&cs, 7, avail) +
  11491. mp_px(&cs, 5, avail) +
  11492. mp_px(&cs, 3, avail) +
  11493. mp_px(&cs, 1, avail);
  11494. if (raw[c] < 24)
  11495. raw[c] = 24;
  11496. total += raw[c];
  11497. }
  11498. /* A one-column table still has to fill its own width; the
  11499. * intrinsic fallback above otherwise leaves the cell at its
  11500. * text width (HN's outer table and nested story table). */
  11501. if (total > 0 && total < avail) {
  11502. int c;
  11503. for (c = 0; c < ncell; c++)
  11504. raw[c] = raw[c] * avail / total;
  11505. total = avail;
  11506. }
  11507. }
  11508. prefix[0] = row_left;
  11509. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  11510. prefix[n + 1] = prefix[n] + raw[n];
  11511. for (n = 0; n < (unsigned int)ncell; n++) {
  11512. struct br_style cs;
  11513. int start = colstart[n];
  11514. int end = start + colspan[n];
  11515. int w;
  11516. if (end > cols)
  11517. end = cols;
  11518. if (start >= cols)
  11519. continue;
  11520. w = prefix[end] - prefix[start];
  11521. br_style_for(&doc, cell[n], pst, &cs);
  11522. /* The column width already reflects the cell's width property. */
  11523. cs.width_kind = 0;
  11524. cs.max_width_kind = 0;
  11525. if (w < 24)
  11526. w = 24;
  11527. if (w < 8)
  11528. w = 8;
  11529. l->left = prefix[start];
  11530. l->right = l->left + w;
  11531. l->y = y;
  11532. l->line_left = l->line_x = l->left;
  11533. l->run_x = l->left;
  11534. l->line_y = l->y;
  11535. l->line_h = 0;
  11536. l->nruns = 0;
  11537. l->space_pending = 0;
  11538. l->align = cs.align;
  11539. layout_block(l, cell[n], &cs, depth + 1, link);
  11540. if (l->y > bottom)
  11541. bottom = l->y;
  11542. }
  11543. l->left = row_left;
  11544. l->right = row_right;
  11545. l->y = bottom;
  11546. l->line_left = l->line_x = l->left;
  11547. l->run_x = l->left;
  11548. l->line_y = l->y;
  11549. l->line_h = 0;
  11550. l->nruns = 0;
  11551. l->space_pending = 0;
  11552. }
  11553. #define TBL_MAX_ROWS 32
  11554. #define TBL_MAX_COLS 12
  11555. #define TBL_MAX_CELLS 128
  11556. struct tbl_cell {
  11557. unsigned int node;
  11558. unsigned char row, col, rowspan, colspan;
  11559. int height;
  11560. };
  11561. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  11562. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  11563. static int table_active;
  11564. static int table_has_rowspan(unsigned int table)
  11565. {
  11566. unsigned int r, c;
  11567. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  11568. struct br_node *rn = &doc.nodes[r];
  11569. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  11570. continue;
  11571. for (c = rn->first; c; c = doc.nodes[c].next) {
  11572. struct br_node *cn = &doc.nodes[c];
  11573. if (cn->type == BR_NODE_ELEM &&
  11574. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  11575. cn->rowspan > 1)
  11576. return 1;
  11577. }
  11578. }
  11579. return 0;
  11580. }
  11581. static void table_cell_style(unsigned int row, unsigned int cell,
  11582. const struct br_style *st, struct br_style *out)
  11583. {
  11584. struct br_style trs;
  11585. br_style_for(&doc, row, st, &trs);
  11586. br_style_for(&doc, cell, &trs, out);
  11587. }
  11588. /* Tables that use rowspan need row heights before anything is painted. This
  11589. * path builds a small occupancy grid, measures the natural cell heights, then
  11590. * lays every cell out at its row/column position. Tables without rowspan
  11591. * keep the lighter per-row path in layout_table_row(). */
  11592. static void layout_table(struct lay *l, unsigned int table,
  11593. const struct br_style *st, int depth,
  11594. unsigned short link)
  11595. {
  11596. unsigned int rows[TBL_MAX_ROWS];
  11597. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  11598. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  11599. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  11600. int free_raw = 0, free_cols = 0;
  11601. int table_left = l->left, table_right = l->right;
  11602. int top = l->y, avail = table_right - table_left;
  11603. unsigned int r, c;
  11604. int i, rr, cc;
  11605. if (depth > 48 || table_active) {
  11606. layout_children(l, table, st, depth, link);
  11607. return;
  11608. }
  11609. table_active = 1;
  11610. for (r = doc.nodes[table].first;
  11611. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  11612. struct br_node *rn = &doc.nodes[r];
  11613. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  11614. rows[nrows++] = r;
  11615. }
  11616. if (!nrows) {
  11617. table_active = 0;
  11618. layout_children(l, table, st, depth, link);
  11619. return;
  11620. }
  11621. for (rr = 0; rr < nrows; rr++)
  11622. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  11623. tbl_at[rr][cc] = 0;
  11624. for (rr = 0; rr < nrows; rr++) {
  11625. int col = 0;
  11626. for (c = doc.nodes[rows[rr]].first; c;
  11627. c = doc.nodes[c].next) {
  11628. struct br_node *cn = &doc.nodes[c];
  11629. struct br_style cs;
  11630. int rs, csn;
  11631. if (cn->type != BR_NODE_ELEM ||
  11632. (cn->tag != BR_TAG_TD &&
  11633. cn->tag != BR_TAG_TH))
  11634. continue;
  11635. table_cell_style(rows[rr], c, st, &cs);
  11636. if (cs.display == BR_DISPLAY_NONE)
  11637. continue;
  11638. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  11639. col++;
  11640. if (col >= TBL_MAX_COLS)
  11641. break;
  11642. rs = cn->rowspan ? cn->rowspan : 1;
  11643. csn = cn->colspan ? cn->colspan : 1;
  11644. if (rr + rs > nrows)
  11645. rs = nrows - rr;
  11646. if (col + csn > TBL_MAX_COLS)
  11647. csn = TBL_MAX_COLS - col;
  11648. if (rs < 1 || csn < 1)
  11649. continue;
  11650. if (ncells >= TBL_MAX_CELLS)
  11651. break;
  11652. tbl_cells[ncells].node = c;
  11653. tbl_cells[ncells].row = (unsigned char)rr;
  11654. tbl_cells[ncells].col = (unsigned char)col;
  11655. tbl_cells[ncells].rowspan = (unsigned char)rs;
  11656. tbl_cells[ncells].colspan = (unsigned char)csn;
  11657. tbl_cells[ncells].height = 0;
  11658. for (i = rr; i < rr + rs; i++)
  11659. for (int j = col; j < col + csn; j++)
  11660. tbl_at[i][j] =
  11661. (unsigned short)(ncells + 1);
  11662. ncells++;
  11663. col += csn;
  11664. if (col > cols)
  11665. cols = col;
  11666. }
  11667. }
  11668. if (!ncells || cols < 1) {
  11669. table_active = 0;
  11670. layout_children(l, table, st, depth, link);
  11671. return;
  11672. }
  11673. for (i = 0; i < cols; i++) {
  11674. raw[i] = 0;
  11675. fixed[i] = 0;
  11676. }
  11677. /* Intrinsic widths of single-column cells. */
  11678. for (i = 0; i < ncells; i++) {
  11679. struct br_style cs;
  11680. int w;
  11681. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  11682. st, &cs);
  11683. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  11684. mp_px(&cs, 7, avail) +
  11685. mp_px(&cs, 5, avail) +
  11686. mp_px(&cs, 3, avail) +
  11687. mp_px(&cs, 1, avail) +
  11688. cs.border_w[0] + cs.border_w[1] +
  11689. cs.border_w[2] + cs.border_w[3];
  11690. if (w < 24)
  11691. w = 24;
  11692. if (tbl_cells[i].colspan == 1) {
  11693. int col = tbl_cells[i].col;
  11694. if (w > raw[col])
  11695. raw[col] = w;
  11696. }
  11697. }
  11698. /* A spanning cell only needs the sum of its columns to be large
  11699. * enough; put the deficit in the last column. */
  11700. for (i = 0; i < ncells; i++) {
  11701. struct br_style cs;
  11702. int w, sum, col, span;
  11703. if (tbl_cells[i].colspan < 2)
  11704. continue;
  11705. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  11706. st, &cs);
  11707. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  11708. mp_px(&cs, 7, avail) +
  11709. mp_px(&cs, 5, avail) +
  11710. mp_px(&cs, 3, avail) +
  11711. mp_px(&cs, 1, avail) +
  11712. cs.border_w[0] + cs.border_w[1] +
  11713. cs.border_w[2] + cs.border_w[3];
  11714. col = tbl_cells[i].col;
  11715. span = tbl_cells[i].colspan;
  11716. sum = 0;
  11717. for (int j = 0; j < span; j++)
  11718. sum += raw[col + j];
  11719. if (w > sum)
  11720. raw[col + span - 1] += w - sum;
  11721. }
  11722. /* Explicit/percentage widths, as in table_columns(). */
  11723. for (i = 0; i < ncells; i++) {
  11724. struct br_style cs;
  11725. int col;
  11726. if (tbl_cells[i].colspan != 1)
  11727. continue;
  11728. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  11729. st, &cs);
  11730. col = tbl_cells[i].col;
  11731. if (cs.width_kind == 1) {
  11732. raw[col] = cs.width;
  11733. fixed[col] = 1;
  11734. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  11735. raw[col] = style_width_px(&cs, avail);
  11736. fixed[col] = 1;
  11737. }
  11738. }
  11739. for (i = 0; i < cols; i++) {
  11740. if (raw[i] < 8)
  11741. raw[i] = 8;
  11742. total += raw[i];
  11743. if (fixed[i])
  11744. fixed_sum += raw[i];
  11745. else {
  11746. free_raw += raw[i];
  11747. free_cols++;
  11748. }
  11749. }
  11750. if (fixed_sum > 0 && fixed_sum < avail) {
  11751. int free_avail = avail - fixed_sum;
  11752. if (free_raw > 0) {
  11753. for (i = 0; i < cols; i++)
  11754. if (!fixed[i])
  11755. raw[i] = free_avail * raw[i] /
  11756. free_raw;
  11757. } else if (free_cols > 0) {
  11758. for (i = 0; i < cols; i++)
  11759. if (!fixed[i])
  11760. raw[i] = free_avail / free_cols;
  11761. }
  11762. } else if (total < avail && total > 0) {
  11763. for (i = 0; i < cols; i++)
  11764. raw[i] = raw[i] * avail / total;
  11765. }
  11766. prefix[0] = table_left;
  11767. for (i = 0; i < cols; i++)
  11768. prefix[i + 1] = prefix[i] + raw[i];
  11769. /* Measure natural cell heights with the column widths. */
  11770. for (i = 0; i < ncells; i++) {
  11771. struct br_style cs;
  11772. int col = tbl_cells[i].col;
  11773. int span = tbl_cells[i].colspan;
  11774. int w = prefix[col + span] - prefix[col];
  11775. int sl = l->left, sr = l->right, sy = l->y;
  11776. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  11777. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  11778. int sal = l->align, sdraw = l->draw;
  11779. struct ngui *sui = l->ui;
  11780. if (w < 8)
  11781. w = 8;
  11782. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  11783. st, &cs);
  11784. cs.width_kind = 0;
  11785. cs.max_width_kind = 0;
  11786. l->draw = 0;
  11787. l->ui = 0;
  11788. l->left = prefix[col];
  11789. l->right = l->left + w;
  11790. l->y = 0;
  11791. l->line_left = l->line_x = l->left;
  11792. l->run_x = l->left;
  11793. l->line_y = 0;
  11794. l->line_h = 0;
  11795. l->nruns = 0;
  11796. l->space_pending = 0;
  11797. l->align = cs.align;
  11798. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  11799. tbl_cells[i].height = block_h[tbl_cells[i].node];
  11800. l->left = sl;
  11801. l->right = sr;
  11802. l->y = sy;
  11803. l->line_x = slx;
  11804. l->run_x = srx;
  11805. l->line_y = sly;
  11806. l->line_h = slh;
  11807. l->nruns = snr;
  11808. l->space_pending = ssp;
  11809. l->align = sal;
  11810. l->draw = sdraw;
  11811. l->ui = sui;
  11812. }
  11813. for (i = 0; i < nrows; i++)
  11814. rowh[i] = 0;
  11815. for (i = 0; i < ncells; i++) {
  11816. int row = tbl_cells[i].row;
  11817. if (tbl_cells[i].rowspan == 1) {
  11818. if (tbl_cells[i].height > rowh[row])
  11819. rowh[row] = tbl_cells[i].height;
  11820. }
  11821. }
  11822. for (i = 0; i < ncells; i++) {
  11823. int row = tbl_cells[i].row;
  11824. int span = tbl_cells[i].rowspan;
  11825. int sum = 0;
  11826. if (span < 2)
  11827. continue;
  11828. for (int j = 0; j < span; j++)
  11829. sum += rowh[row + j];
  11830. if (sum < tbl_cells[i].height)
  11831. rowh[row + span - 1] +=
  11832. tbl_cells[i].height - sum;
  11833. }
  11834. for (i = 0; i < nrows; i++)
  11835. if (rowh[i] < 8)
  11836. rowh[i] = 8;
  11837. rowy[0] = top;
  11838. for (i = 1; i < nrows; i++)
  11839. rowy[i] = rowy[i - 1] + rowh[i - 1];
  11840. if (!l->draw) {
  11841. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  11842. table_active = 0;
  11843. return;
  11844. }
  11845. for (i = 0; i < ncells; i++) {
  11846. struct br_style cs;
  11847. int col = tbl_cells[i].col;
  11848. int span = tbl_cells[i].colspan;
  11849. int row = tbl_cells[i].row;
  11850. int rspan = tbl_cells[i].rowspan;
  11851. int w = prefix[col + span] - prefix[col];
  11852. int h = 0;
  11853. int sl = l->left, sr = l->right, sy = l->y;
  11854. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  11855. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  11856. int sal = l->align;
  11857. int deco;
  11858. for (int j = 0; j < rspan; j++)
  11859. h += rowh[row + j];
  11860. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  11861. cs.width_kind = 0;
  11862. cs.max_width_kind = 0;
  11863. cs.box_sizing = 0;
  11864. deco = mp_px(&cs, 4, avail) +
  11865. mp_px(&cs, 6, avail) +
  11866. cs.border_w[0] + cs.border_w[2];
  11867. cs.height_kind = 1;
  11868. cs.height = h > deco ? h - deco : 0;
  11869. /* The block painter reads block_h[] from the measure pass; make
  11870. * the table cell fill its row/rowspan, not just its content. */
  11871. if (h > 0 && h < 65536)
  11872. block_h[tbl_cells[i].node] = (unsigned short)h;
  11873. l->left = prefix[col];
  11874. l->right = l->left + w;
  11875. l->y = rowy[row];
  11876. l->line_left = l->line_x = l->left;
  11877. l->run_x = l->left;
  11878. l->line_y = l->y;
  11879. l->line_h = 0;
  11880. l->nruns = 0;
  11881. l->space_pending = 0;
  11882. l->align = cs.align;
  11883. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  11884. l->left = sl;
  11885. l->right = sr;
  11886. l->y = sy;
  11887. l->line_x = slx;
  11888. l->run_x = srx;
  11889. l->line_y = sly;
  11890. l->line_h = slh;
  11891. l->nruns = snr;
  11892. l->space_pending = ssp;
  11893. l->align = sal;
  11894. }
  11895. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  11896. table_active = 0;
  11897. }
  11898. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  11899. * flow so they sit above it, like CSS painting order. Their flow origin is
  11900. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  11901. struct br_deferred {
  11902. unsigned int node;
  11903. int flow_y, flow_left, flow_right;
  11904. int parent_top; /* the parent box top, for sticky clamping */
  11905. unsigned short link;
  11906. signed short z_index;
  11907. unsigned char z_set;
  11908. unsigned int order;
  11909. };
  11910. /* Positioned boxes painted after the flow. News front pages have one or two
  11911. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  11912. * old 16 entries the rest fell back into the flow, so a hero image landed
  11913. * below its padding-top aspect box instead of on top of it. */
  11914. #define BR_MAX_DEFERRED 256
  11915. static struct br_deferred deferred[BR_MAX_DEFERRED];
  11916. static int ndeferred;
  11917. /* Outer width of an element's empty ::before (pe 1) / ::after (pe 2) icon
  11918. * box, 0 when it has none; *ps receives the pseudo-element's style. */
  11919. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  11920. struct br_style *ps, int base)
  11921. {
  11922. char buf[8];
  11923. int w, h;
  11924. if (!doc.npe_rules ||
  11925. br_pseudo(&doc, node, pe, st, ps, buf, sizeof(buf)) ||
  11926. ps->content != BR_CONTENT_EMPTY || ps->display == BR_DISPLAY_NONE)
  11927. return 0;
  11928. w = ps->width_kind ? style_width_px(ps, base) : 0;
  11929. h = ps->height_kind ? style_height_px(ps, base) : 0;
  11930. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  11931. w = (int)ps->min_width;
  11932. if (w <= 0)
  11933. w = h;
  11934. if (w <= 0 || w > 512)
  11935. return 0;
  11936. return w + (ps->ml_auto ? 0 : mp_px(ps, 3, base)) + mp_px(ps, 1, base);
  11937. }
  11938. /* An empty ::before/::after with a size and a background: one run the
  11939. * size of the box. Only data: background images are drawn (decoded at
  11940. * the background-size); `margin-left: auto` inside a flex parent pushes
  11941. * the box to the line's right edge like the flex row would. */
  11942. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  11943. const struct br_style *ps, unsigned short link)
  11944. {
  11945. struct lay_run *r;
  11946. int lw = l->line_right - l->line_left, w, h, ml, mr, tw, th;
  11947. const char *url = ps->bg_image ? br_bg_image_url(ps->bg_image - 1) : "";
  11948. if (lw < 8)
  11949. lw = 8;
  11950. w = ps->width_kind ? style_width_px(ps, lw) : 0;
  11951. h = ps->height_kind ? style_height_px(ps, lw) : 0;
  11952. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  11953. w = (int)ps->min_width;
  11954. if (w <= 0)
  11955. w = h;
  11956. if (h <= 0)
  11957. h = w;
  11958. if (w <= 0 || w > 512 || h > 512)
  11959. return;
  11960. ml = ps->ml_auto ? 0 : mp_px(ps, 3, lw);
  11961. mr = mp_px(ps, 1, lw);
  11962. if (ml < 0)
  11963. ml = 0;
  11964. if (mr < 0)
  11965. mr = 0;
  11966. if (l->line_x + ml + w > l->line_right &&
  11967. (l->nruns > 0 || l->line_x > l->line_left))
  11968. flush_line(l);
  11969. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  11970. flush_line(l);
  11971. if (l->nruns == 0) {
  11972. l->line_y = l->y;
  11973. l->line_h = 0;
  11974. start_line(l, ps);
  11975. }
  11976. if (ps->ml_auto && parent->display == BR_DISPLAY_FLEX &&
  11977. l->line_right - w - mr > l->line_x)
  11978. l->line_x = l->line_right - w - mr;
  11979. else
  11980. l->line_x += ml;
  11981. r = &l->runs[l->nruns++];
  11982. memset(r, 0, sizeof(*r));
  11983. r->box = l->box_owner;
  11984. r->gap = (unsigned short)(l->line_x > l->run_x ?
  11985. l->line_x - l->run_x : 0);
  11986. r->img = RUN_PBOX;
  11987. r->href = link;
  11988. r->iw = (unsigned short)w;
  11989. r->ih = (unsigned short)h;
  11990. r->w = (unsigned short)w;
  11991. r->font_px = ps->font_px;
  11992. r->pb_has_bg = ps->has_bg;
  11993. r->pb_bg = ps->bg;
  11994. r->pb_img = -1;
  11995. if (ps->transform_set) {
  11996. r->transform_scale = 1;
  11997. r->scale_x = ps->scale_x;
  11998. r->scale_y = ps->scale_y;
  11999. r->rotate_x100 = ps->rotate_x100;
  12000. }
  12001. /* Background size and position, as draw_bg_image() resolves them. */
  12002. tw = w;
  12003. th = h;
  12004. if (ps->bg_size_kind == 1 || ps->bg_size_kind == 2) {
  12005. int bw = ps->bg_size_w, bh = ps->bg_size_h;
  12006. if (ps->bg_size_kind == 2) {
  12007. bw = bw ? w * bw / 100 : 0;
  12008. bh = bh ? h * bh / 100 : 0;
  12009. }
  12010. tw = bw ? bw : (bh ? bh : w);
  12011. th = bh ? bh : tw;
  12012. }
  12013. if (tw > 0 && th > 0 && tw <= 512 && th <= 512 && url[0])
  12014. r->pb_img = (short)data_url_image(url, tw, th);
  12015. r->pb_w = (short)tw;
  12016. r->pb_h = (short)th;
  12017. r->pb_x = (short)(ps->bg_pos_x_kind == 1 ?
  12018. (w - tw) * ps->bg_pos_x / 100 : ps->bg_pos_x);
  12019. r->pb_y = (short)(ps->bg_pos_y_kind == 1 ?
  12020. (h - th) * ps->bg_pos_y / 100 : ps->bg_pos_y);
  12021. l->line_x += w + mr;
  12022. l->run_x = l->line_x;
  12023. if (l->line_h < h)
  12024. l->line_h = h;
  12025. }
  12026. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  12027. * element's line. A block-level pseudo-element gets its own line; its box
  12028. * (margins, padding, background) is not drawn. */
  12029. static void emit_pseudo(struct lay *l, unsigned int node,
  12030. const struct br_style *st, int pe, unsigned short link)
  12031. {
  12032. char buf[160];
  12033. struct br_style ps;
  12034. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  12035. unsigned int i = 0;
  12036. int block, space_w;
  12037. if (!n && ps.content == BR_CONTENT_EMPTY &&
  12038. ps.display != BR_DISPLAY_NONE) {
  12039. emit_pseudo_box(l, st, &ps, link);
  12040. return;
  12041. }
  12042. if (!n)
  12043. return;
  12044. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  12045. if (block)
  12046. flush_line(l);
  12047. if (ps.uppercase)
  12048. for (i = 0; i < n; i++)
  12049. if (buf[i] >= 'a' && buf[i] <= 'z')
  12050. buf[i] = (char)(buf[i] - 'a' + 'A');
  12051. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  12052. if (space_w <= 0)
  12053. space_w = 8;
  12054. i = 0;
  12055. while (i < n) {
  12056. char word[28];
  12057. unsigned int k = 0;
  12058. int w;
  12059. if (buf[i] == ' ') {
  12060. l->space_pending = 1;
  12061. i++;
  12062. continue;
  12063. }
  12064. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  12065. word[k++] = buf[i++];
  12066. word[k] = '\0';
  12067. if (l->space_pending &&
  12068. (l->nruns > 0 || l->line_x > l->line_left) &&
  12069. l->line_x + space_w <= l->line_right)
  12070. l->line_x += space_w;
  12071. l->space_pending = 0;
  12072. w = (int)face_text_width(l->ui, &ps, word, k);
  12073. if (l->line_x + w > l->line_right &&
  12074. (l->nruns > 0 || l->line_x > l->line_left))
  12075. flush_line(l);
  12076. add_run(l, 0, 0, &ps, link, word);
  12077. }
  12078. if (block)
  12079. flush_line(l);
  12080. }
  12081. /* An out-of-flow child (absolute/fixed, or a relative/sticky box with a
  12082. * z-index): measured in place, painted from the deferred stacked pass
  12083. * against its containing block. Shared by block and flex layout, so an
  12084. * absolute icon inside a flex row (a password field's reveal button) is
  12085. * not laid out as one of the row's items. Returns 1 when it handled n. */
  12086. static int layout_out_of_flow(struct lay *l, unsigned int n,
  12087. const struct br_style *cs, int depth,
  12088. unsigned short lk)
  12089. {
  12090. if (!(cs->pos == 1 || cs->pos == 2 ||
  12091. ((cs->pos == 3 || cs->pos == 4) && cs->z_set)))
  12092. return 0;
  12093. if ((cs->pos == 3 || cs->pos == 4) && l->draw &&
  12094. ndeferred < BR_MAX_DEFERRED) {
  12095. /* Relative or sticky z-index (a sticky site
  12096. * header): measure and advance the flow without
  12097. * painting, then paint it in the deferred
  12098. * (stacked) pass, above the content after it. */
  12099. int fy = l->y, fl = l->left, fr = l->right;
  12100. int save_draw = l->draw;
  12101. l->draw = 0;
  12102. layout_block(l, n, cs, depth + 1, lk);
  12103. l->draw = save_draw;
  12104. deferred[ndeferred].node = n;
  12105. deferred[ndeferred].parent_top = l->parent_top;
  12106. deferred[ndeferred].flow_y = fy;
  12107. deferred[ndeferred].flow_left = fl;
  12108. deferred[ndeferred].flow_right = fr;
  12109. deferred[ndeferred].link = lk;
  12110. deferred[ndeferred].z_index = cs->z_index;
  12111. deferred[ndeferred].z_set = cs->z_set;
  12112. deferred[ndeferred].order = (unsigned int)ndeferred;
  12113. ndeferred++;
  12114. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  12115. deferred[ndeferred].node = n;
  12116. deferred[ndeferred].parent_top = l->parent_top;
  12117. deferred[ndeferred].flow_y =
  12118. cs->pos == 1 ? l->cb_top : l->y;
  12119. deferred[ndeferred].flow_left =
  12120. cs->pos == 1 ? l->cb_left : l->left;
  12121. deferred[ndeferred].flow_right =
  12122. cs->pos == 1 ? l->cb_right : l->right;
  12123. deferred[ndeferred].link = lk;
  12124. deferred[ndeferred].z_index = cs->z_index;
  12125. deferred[ndeferred].z_set = cs->z_set;
  12126. deferred[ndeferred].order = (unsigned int)ndeferred;
  12127. ndeferred++;
  12128. } else if (l->draw && cs->pos == 1) {
  12129. /* Deferred list full: paint in place, but still
  12130. * against the containing block, not the flow. */
  12131. int fy = l->y, fl = l->left, fr = l->right;
  12132. l->y = l->cb_top;
  12133. l->left = l->cb_left;
  12134. l->right = l->cb_right;
  12135. layout_block(l, n, cs, depth + 1, lk);
  12136. l->y = fy;
  12137. l->left = fl;
  12138. l->right = fr;
  12139. } else {
  12140. layout_block(l, n, cs, depth + 1, lk);
  12141. }
  12142. if (cs->pos == 1 && block_h[n] &&
  12143. doc.nodes[n].class_off) {
  12144. const char *cl = doc.attrs +
  12145. doc.nodes[n].class_off;
  12146. if ((contains_ci(cl, "poster-wrapper") ||
  12147. contains_ci(cl, "ts-picture")) &&
  12148. !has_skeleton_sibling(n))
  12149. l->y += block_h[n];
  12150. }
  12151. return 1;
  12152. }
  12153. /* An element laid out in the text line (an inline span, or an inline-block
  12154. * that flows like one): its runs are tagged with it, so flush_line() can
  12155. * record its box for getBoundingClientRect() and click targeting. */
  12156. static void layout_inline_box(struct lay *l, unsigned int node,
  12157. const struct br_style *cs, int depth,
  12158. unsigned short link)
  12159. {
  12160. unsigned short saved = l->box_owner;
  12161. if (node < BR_MAX_NODES) {
  12162. inline_box_parent[node] = saved;
  12163. l->box_owner = (unsigned short)(node + 1);
  12164. }
  12165. layout_children(l, node, cs, depth + 1, link);
  12166. l->box_owner = saved;
  12167. }
  12168. static void layout_children(struct lay *l, unsigned int parent,
  12169. const struct br_style *pst, int depth,
  12170. unsigned short link)
  12171. {
  12172. unsigned int n;
  12173. if (depth > 48)
  12174. return;
  12175. emit_pseudo(l, parent, pst, 1, link);
  12176. n = doc.nodes[parent].first;
  12177. while (n) {
  12178. struct br_node *nd = &doc.nodes[n];
  12179. struct br_style cs;
  12180. unsigned short lk = link;
  12181. if (nd->type == BR_NODE_TEXT) {
  12182. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  12183. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  12184. n = nd->next;
  12185. continue;
  12186. }
  12187. br_style_for(&doc, n, pst, &cs);
  12188. if (cs.display == BR_DISPLAY_NONE) {
  12189. n = nd->next;
  12190. continue;
  12191. }
  12192. if (cs.clear && l->float_active) {
  12193. flush_line(l);
  12194. if (l->y < l->float_bottom)
  12195. l->y = l->float_bottom;
  12196. l->float_active = 0;
  12197. l->line_x = l->left;
  12198. l->run_x = l->left;
  12199. l->line_left = l->left;
  12200. l->line_right = l->right;
  12201. l->line_y = l->y;
  12202. l->line_h = 0;
  12203. l->nruns = 0;
  12204. l->space_pending = 0;
  12205. }
  12206. if (nd->tag == BR_TAG_A && nd->href_off)
  12207. lk = (unsigned short)n;
  12208. if (layout_out_of_flow(l, n, &cs, depth, lk)) {
  12209. n = nd->next;
  12210. continue;
  12211. }
  12212. if (nd->tag == BR_TAG_BR) {
  12213. flush_line(l);
  12214. n = nd->next;
  12215. continue;
  12216. }
  12217. if (nd->tag == BR_TAG_HR) {
  12218. flush_line(l);
  12219. if (l->draw)
  12220. ngui_fill_rect(l->ui,
  12221. (struct ngui_rect){l->left, l->y + 2,
  12222. l->right - l->left, 1}, BR_GRAY);
  12223. l->y += 8;
  12224. n = nd->next;
  12225. continue;
  12226. }
  12227. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  12228. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  12229. !button_has_elements(n)) {
  12230. if (!(nd->tag == BR_TAG_INPUT &&
  12231. s_eq(br_type(&doc, n), "hidden"))) {
  12232. form_fill_line = pst->display ==
  12233. BR_DISPLAY_FLEX &&
  12234. pst->flex_col;
  12235. add_form_run(l, n, &cs, lk);
  12236. form_fill_line = 0;
  12237. }
  12238. n = nd->next;
  12239. continue;
  12240. }
  12241. if (nd->tag == BR_TAG_IMG) {
  12242. add_image_run(l, n, &cs, lk);
  12243. n = nd->next;
  12244. continue;
  12245. }
  12246. if (nd->tag == BR_TAG_SVG &&
  12247. (cs.display == BR_DISPLAY_INLINE ||
  12248. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  12249. !cs.float_left) {
  12250. add_svg_run(l, n, &cs, lk);
  12251. n = nd->next;
  12252. continue;
  12253. }
  12254. if (nd->tag == BR_TAG_VIDEO) {
  12255. layout_block(l, n, &cs, depth + 1, lk);
  12256. n = nd->next;
  12257. continue;
  12258. }
  12259. if (cs.float_left) {
  12260. n = layout_float_group(l, n, pst, depth, lk);
  12261. continue;
  12262. }
  12263. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  12264. inline_block_flows(n, &cs, 0)) {
  12265. layout_inline_box(l, n, &cs, depth, lk);
  12266. n = nd->next;
  12267. continue;
  12268. }
  12269. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  12270. n = layout_inline_blocks(l, n, pst, depth, link);
  12271. continue;
  12272. }
  12273. /* A flex container is block-level like any block box even when
  12274. * the element is an inline tag such as <a> (a link card with
  12275. * display:flex is common on news sites). Without the block box
  12276. * its children were laid out in the parent flow with a 0x0 box
  12277. * of their own. */
  12278. /* inline-flex around inline content only ("| mehr" link
  12279. * tails, icon+label pills) stays in the text line. */
  12280. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  12281. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  12282. !flex_wants_row(n, &cs)) {
  12283. layout_children(l, n, &cs, depth + 1, lk);
  12284. } else if (cs.display == BR_DISPLAY_BLOCK ||
  12285. cs.display == BR_DISPLAY_FLEX ||
  12286. br_tag_is_block(nd->tag))
  12287. layout_block(l, n, &cs, depth + 1, lk);
  12288. else if (cs.display == BR_DISPLAY_INLINE &&
  12289. nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH)
  12290. layout_inline_box(l, n, &cs, depth, lk);
  12291. else {
  12292. layout_children(l, n, &cs, depth + 1, lk);
  12293. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  12294. l->space_pending = 1;
  12295. }
  12296. n = nd->next;
  12297. }
  12298. emit_pseudo(l, parent, pst, 2, link);
  12299. }
  12300. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  12301. * runs and a recursive page can otherwise overflow the stack. */
  12302. static struct lay layout_state;
  12303. static int measure_page(int left, int right)
  12304. {
  12305. struct lay *l = &layout_state;
  12306. struct br_style base = base_style();
  12307. unsigned int i;
  12308. for (i = 0; i < BR_MAX_NODES; i++) {
  12309. block_h[i] = 0;
  12310. flex_stretch_h[i] = 0;
  12311. img_top[i] = 0;
  12312. block_top[i] = 0;
  12313. img_h[i] = 0;
  12314. layout_boxes[i].valid = 0;
  12315. }
  12316. memset(li_marker, 0, sizeof(li_marker));
  12317. inline_box_pass_id++;
  12318. l->box_owner = 0;
  12319. l->draw = 0;
  12320. l->ui = &ui;
  12321. l->left = left;
  12322. l->right = right;
  12323. l->y = 0;
  12324. l->line_x = left;
  12325. l->run_x = left;
  12326. l->line_left = left;
  12327. l->line_right = right;
  12328. l->line_y = 0;
  12329. l->line_h = 0;
  12330. l->align = BR_ALIGN_LEFT;
  12331. l->cb_h = layout_view_h;
  12332. l->float_active = 0;
  12333. l->parent_top = 0;
  12334. l->cb_left = left;
  12335. l->cb_right = right;
  12336. l->cb_top = 0;
  12337. l->depth = 0;
  12338. l->nruns = 0;
  12339. l->space_pending = 0;
  12340. base = root_style();
  12341. layout_children(l, doc.root, &base, 0, 0);
  12342. return l->y + 8;
  12343. }
  12344. static int deferred_cmp(const struct br_deferred *a,
  12345. const struct br_deferred *b)
  12346. {
  12347. int az = a->z_set ? a->z_index : 0;
  12348. int bz = b->z_set ? b->z_index : 0;
  12349. if (az != bz)
  12350. return az < bz ? -1 : 1;
  12351. if (a->order != b->order)
  12352. return a->order < b->order ? -1 : 1;
  12353. return 0;
  12354. }
  12355. static void sort_deferred(void)
  12356. {
  12357. int i;
  12358. for (i = 1; i < ndeferred; i++) {
  12359. struct br_deferred key = deferred[i];
  12360. int j = i;
  12361. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  12362. deferred[j] = deferred[j - 1];
  12363. j--;
  12364. }
  12365. deferred[j] = key;
  12366. }
  12367. }
  12368. static void hit_add_occluder(unsigned int node, int at)
  12369. {
  12370. const struct br_layout_box *b;
  12371. struct hit h;
  12372. int x0, y0, x1, y1;
  12373. if (node >= BR_MAX_NODES || nhits >= HIT_MAX || at > nhits)
  12374. return;
  12375. b = &layout_boxes[node];
  12376. if (!b->valid)
  12377. return;
  12378. x0 = b->x > page_rect.x ? b->x : page_rect.x;
  12379. y0 = b->y > page_rect.y ? b->y : page_rect.y;
  12380. x1 = b->x + b->w;
  12381. y1 = b->y + b->h;
  12382. if (x1 > page_rect.x + page_rect.w - 12)
  12383. x1 = page_rect.x + page_rect.w - 12;
  12384. if (y1 > page_rect.y + page_rect.h)
  12385. y1 = page_rect.y + page_rect.h;
  12386. if (x1 <= x0 || y1 <= y0)
  12387. return;
  12388. h.x = x0;
  12389. h.y = y0;
  12390. h.w = x1 - x0;
  12391. h.h = y1 - y0;
  12392. h.node = (unsigned short)node;
  12393. h.occl = 1;
  12394. memmove(&hits[at + 1], &hits[at],
  12395. (unsigned int)(nhits - at) * sizeof(hits[0]));
  12396. hits[at] = h;
  12397. nhits++;
  12398. }
  12399. static void render_page(int left, int right, int y0)
  12400. {
  12401. struct lay *l = &layout_state;
  12402. struct br_style base = base_style();
  12403. inline_box_pass_id++;
  12404. l->box_owner = 0;
  12405. l->draw = 1;
  12406. l->ui = &ui;
  12407. l->left = left;
  12408. l->right = right;
  12409. l->y = y0;
  12410. l->line_x = left;
  12411. l->run_x = left;
  12412. l->line_left = left;
  12413. l->line_right = right;
  12414. l->line_y = y0;
  12415. l->line_h = 0;
  12416. l->align = BR_ALIGN_LEFT;
  12417. l->cb_h = layout_view_h;
  12418. l->float_active = 0;
  12419. l->parent_top = 0;
  12420. l->cb_left = left;
  12421. l->cb_right = right;
  12422. l->cb_top = y0;
  12423. l->depth = 0;
  12424. l->nruns = 0;
  12425. l->space_pending = 0;
  12426. nhits = 0;
  12427. ndeferred = 0;
  12428. render_pass = 1;
  12429. render_seq++;
  12430. base = root_style();
  12431. layout_children(l, doc.root, &base, 0, 0);
  12432. sort_deferred();
  12433. {
  12434. int i;
  12435. for (i = 0; i < ndeferred; i++) {
  12436. struct br_style st;
  12437. int hide, op, blend, hit0;
  12438. br_style_for(&doc, deferred[i].node, &base, &st);
  12439. if (st.display == BR_DISPLAY_NONE)
  12440. continue;
  12441. /* A transparent or visibility:hidden positioned box
  12442. * still gets its boxes (scripts measure it) but no
  12443. * paint and no hit rectangles. A translucent one
  12444. * (a 50% modal backdrop, a fading tooltip) is
  12445. * blended over what is under it; the opacity may be
  12446. * mid-transition. */
  12447. hit0 = nhits;
  12448. op = anim_value(deferred[i].node, ANIM_OP, st.opacity,
  12449. &st);
  12450. hide = op == 0 || st.vis_hidden;
  12451. blend = !hide && op < 255 && alpha_begin(page_rect);
  12452. l->draw = !hide;
  12453. l->left = deferred[i].flow_left;
  12454. l->right = deferred[i].flow_right;
  12455. l->y = deferred[i].flow_y;
  12456. l->parent_top = deferred[i].parent_top;
  12457. l->line_left = l->line_x = l->left;
  12458. l->run_x = l->left;
  12459. l->line_y = l->y;
  12460. l->line_h = 0;
  12461. l->nruns = 0;
  12462. l->space_pending = 0;
  12463. l->align = st.align;
  12464. if (st.pos == 2 && block_h[deferred[i].node]) {
  12465. struct ngui_rect clip;
  12466. int ch = block_h[deferred[i].node] + 24;
  12467. int pr = page_rect.x + page_rect.w - 12;
  12468. int x0 = page_rect.x, x1 = pr;
  12469. int y0 = page_rect.y;
  12470. /* A box placed by `bottom` (a page footer) is
  12471. * clipped and filled where layout_block puts
  12472. * it, against the bottom edge. */
  12473. if (st.bottom_set && !st.top_set) {
  12474. ch = block_h[deferred[i].node] +
  12475. mp_px(&st, 0, pr - page_rect.x) +
  12476. mp_px(&st, 2, pr - page_rect.x);
  12477. y0 = page_rect.y + page_rect.h -
  12478. st.bottom - ch;
  12479. }
  12480. /* The background pre-fill spans the box's own
  12481. * columns, not the whole page: Docusaurus parks
  12482. * a white "Skip to main content" link at
  12483. * `left: 100%` with a z-index above the navbar,
  12484. * and a full-width fill painted over the bar. */
  12485. if (st.left_set)
  12486. x0 = page_rect.x + st.left;
  12487. else if (!st.right_set)
  12488. x0 = deferred[i].flow_left;
  12489. if (st.width_kind == 1) {
  12490. if (st.right_set && !st.left_set)
  12491. x0 = pr - st.right - st.width;
  12492. x1 = x0 + st.width;
  12493. } else if (st.right_set) {
  12494. x1 = pr - st.right;
  12495. }
  12496. if (x0 >= pr || x1 <= page_rect.x)
  12497. continue; /* entirely off-screen */
  12498. if (x0 < page_rect.x)
  12499. x0 = page_rect.x;
  12500. if (x1 > pr)
  12501. x1 = pr;
  12502. if (y0 < page_rect.y) {
  12503. ch -= page_rect.y - y0;
  12504. y0 = page_rect.y;
  12505. }
  12506. clip.x = x0;
  12507. clip.y = y0;
  12508. clip.w = x1 - x0;
  12509. if (ch > page_rect.h)
  12510. ch = page_rect.h;
  12511. if (ch <= 0)
  12512. continue;
  12513. clip.h = ch;
  12514. ngui_push_clip(&ui, clip);
  12515. if (st.has_bg && !hide)
  12516. ngui_fill_rect(&ui, clip, st.bg);
  12517. layout_block(l, deferred[i].node, &st, 0,
  12518. deferred[i].link);
  12519. ngui_pop_clip(&ui);
  12520. } else {
  12521. layout_block(l, deferred[i].node, &st, 0,
  12522. deferred[i].link);
  12523. }
  12524. if (!hide && !st.pe_none &&
  12525. (st.pos == 1 || st.pos == 2) &&
  12526. (st.has_bg || st.bg_image || st.z_set))
  12527. hit_add_occluder(deferred[i].node, hit0);
  12528. if (blend) {
  12529. const struct br_layout_box *b =
  12530. &layout_boxes[deferred[i].node];
  12531. struct ngui_rect box = page_rect;
  12532. /* The box itself; descendants may overflow
  12533. * it, so a full-page box is the safe case. */
  12534. if (deferred[i].node < BR_MAX_NODES &&
  12535. b->valid) {
  12536. box.x = b->x;
  12537. box.y = b->y;
  12538. box.w = b->w;
  12539. box.h = b->h;
  12540. }
  12541. alpha_end(page_rect, box, op);
  12542. }
  12543. }
  12544. }
  12545. render_pass = 0;
  12546. }
  12547. /* ---- UI ---- */
  12548. /* The link/control under a point, topmost first. An occluder above it
  12549. * returns 0 and its node in *occl (when given), so the caller can target
  12550. * the covering box instead of content painted underneath. */
  12551. static int find_hit_ex(int x, int y, int *occl)
  12552. {
  12553. int i;
  12554. if (occl)
  12555. *occl = -1;
  12556. for (i = nhits - 1; i >= 0; i--) {
  12557. struct hit *h = &hits[i];
  12558. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  12559. y < h->y + h->h) {
  12560. if (h->occl) {
  12561. if (occl)
  12562. *occl = (int)h->node;
  12563. return 0;
  12564. }
  12565. return (int)h->node;
  12566. }
  12567. }
  12568. return 0;
  12569. }
  12570. static int find_hit(int x, int y)
  12571. {
  12572. return find_hit_ex(x, y, 0);
  12573. }
  12574. /* ---- URL-bar autocomplete ----
  12575. *
  12576. * While the address bar has the focus a dropdown lists up to SUG_MAX
  12577. * history entries. An empty bar (a fresh focus, Ctrl+L) shows the most
  12578. * visited/recent sites; typing ranks prefix matches of the URL (with or
  12579. * without the scheme and "www.") above substring matches of the URL, then
  12580. * of the title, and adds visit count and recency. Typing at the end of the
  12581. * text also completes inline to the next '/' of the best prefix match
  12582. * ("clo" -> "cloudron.io/"), with the added part selected so the next
  12583. * keystroke replaces it; Enter on that text opens the history URL it came
  12584. * from (scheme included). Up/Down preview a row in the bar, Delete on a
  12585. * highlighted row forgets it, Esc closes the list (a second Esc leaves the
  12586. * bar), and a click on a row opens it. */
  12587. #define SUG_MAX 6
  12588. #define SUG_ROW_H 36
  12589. static int sug_idx[SUG_MAX];
  12590. static int sug_n, sug_sel = -1, sug_open;
  12591. static char sug_typed[NGUI_INPUT_MAX]; /* what the user typed */
  12592. static char sug_restore[NGUI_INPUT_MAX]; /* bar text before a preview */
  12593. static char ac_text[NGUI_INPUT_MAX]; /* bar text of the inline completion */
  12594. static char ac_url[HIST_URL_MAX]; /* the history URL it stands for */
  12595. static struct ngui_rect url_rect, sug_rect;
  12596. static int url_had_focus;
  12597. static char lc(char c)
  12598. {
  12599. return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
  12600. }
  12601. static int prefix_ci(const char *s, const char *p) /* p is lower case */
  12602. {
  12603. for (; *p; s++, p++)
  12604. if (lc(*s) != *p)
  12605. return 0;
  12606. return 1;
  12607. }
  12608. static unsigned int url_scheme_len(const char *url)
  12609. {
  12610. if (starts_with(url, "https://"))
  12611. return 8;
  12612. if (starts_with(url, "http://"))
  12613. return 7;
  12614. return 0;
  12615. }
  12616. /* Offset in `url` where the lower-case text `t` matches as a prefix: the
  12617. * whole URL, the URL without its scheme, or without scheme and "www.". */
  12618. static int hist_prefix_at(const char *url, const char *t)
  12619. {
  12620. unsigned int s = url_scheme_len(url);
  12621. if (prefix_ci(url, t))
  12622. return 0;
  12623. if (s && prefix_ci(url + s, t))
  12624. return (int)s;
  12625. if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
  12626. return (int)s + 4;
  12627. return -1;
  12628. }
  12629. static int hist_score(const struct hist_ent *e, const char *t,
  12630. unsigned int next)
  12631. {
  12632. unsigned int age = next - e->stamp;
  12633. int sc, at;
  12634. if (!t[0]) {
  12635. sc = 0;
  12636. } else if ((at = hist_prefix_at(e->url, t)) >= 0) {
  12637. /* Shorter rests first: "cloudron.io/" before its subpages. */
  12638. int rest = (int)s_len(e->url + at);
  12639. sc = 4000 - (rest > 400 ? 400 : rest);
  12640. } else if (contains_ci(e->url, t)) {
  12641. sc = 1000;
  12642. } else if (contains_ci(e->title, t)) {
  12643. sc = 600;
  12644. } else {
  12645. return -1;
  12646. }
  12647. sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
  12648. sc += age >= 500 ? 0 : (int)(500 - age);
  12649. return sc;
  12650. }
  12651. static void sug_lower(char *t, unsigned int cap)
  12652. {
  12653. unsigned int k;
  12654. for (k = 0; sug_typed[k] && k + 1 < cap; k++)
  12655. t[k] = lc(sug_typed[k]);
  12656. t[k] = '\0';
  12657. }
  12658. static void sug_refresh(void)
  12659. {
  12660. char t[NGUI_INPUT_MAX];
  12661. int sc[SUG_MAX], i, j;
  12662. unsigned int next = hist_next_stamp();
  12663. sug_lower(t, sizeof(t));
  12664. sug_n = 0;
  12665. for (i = 0; i < hist_n; i++) {
  12666. int s = hist_score(&hist_tab[i], t, next);
  12667. if (s < 0)
  12668. continue;
  12669. j = sug_n;
  12670. if (j == SUG_MAX) {
  12671. if (sc[SUG_MAX - 1] >= s)
  12672. continue;
  12673. j = SUG_MAX - 1;
  12674. }
  12675. while (j > 0 && sc[j - 1] < s) {
  12676. sc[j] = sc[j - 1];
  12677. sug_idx[j] = sug_idx[j - 1];
  12678. j--;
  12679. }
  12680. sc[j] = s;
  12681. sug_idx[j] = i;
  12682. if (sug_n < SUG_MAX)
  12683. sug_n++;
  12684. }
  12685. if (sug_sel >= sug_n)
  12686. sug_sel = -1;
  12687. }
  12688. /* Complete the typed text inline to the next '/' of the best prefix match. */
  12689. static void sug_inline(void)
  12690. {
  12691. char t[NGUI_INPUT_MAX];
  12692. const char *url, *rest;
  12693. unsigned int L, start, end, hs, tn, n = 0;
  12694. unsigned int next = hist_next_stamp();
  12695. int i, best = -1, best_sc = -1, at = 0;
  12696. sug_lower(t, sizeof(t));
  12697. L = s_len(t);
  12698. if (!L)
  12699. return;
  12700. for (i = 0; i < hist_n; i++) {
  12701. int a = hist_prefix_at(hist_tab[i].url, t), s;
  12702. if (a < 0)
  12703. continue;
  12704. s = hist_score(&hist_tab[i], t, next);
  12705. if (s > best_sc) {
  12706. best_sc = s;
  12707. best = i;
  12708. at = a;
  12709. }
  12710. }
  12711. if (best < 0)
  12712. return;
  12713. url = hist_tab[best].url;
  12714. rest = url + at;
  12715. /* Typing the scheme ("htt") completes past "https://", not to it. */
  12716. hs = at == 0 ? url_scheme_len(url) : 0;
  12717. start = L > hs ? L : hs;
  12718. end = start;
  12719. while (rest[end] && rest[end] != '/')
  12720. end++;
  12721. if (rest[end] == '/')
  12722. end++;
  12723. tn = s_len(sug_typed);
  12724. if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
  12725. return;
  12726. s_append(ac_text, &n, sug_typed, sizeof(ac_text));
  12727. for (; L < end && n + 1 < sizeof(ac_text); L++)
  12728. ac_text[n++] = rest[L];
  12729. ac_text[n] = '\0';
  12730. s_copy(ac_url, url, (unsigned int)at + end + 1);
  12731. ngui_input_set(&url_in, ac_text);
  12732. url_in.anchor = tn; /* select the completed part */
  12733. }
  12734. static void sug_close(void)
  12735. {
  12736. sug_open = 0;
  12737. sug_sel = -1;
  12738. ac_text[0] = '\0';
  12739. }
  12740. static int sug_visible(void)
  12741. {
  12742. return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
  12743. }
  12744. /* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
  12745. * start page) lists the top sites until something is typed. */
  12746. static int sug_focus_check(void)
  12747. {
  12748. int focused = ngui_focus(&ui) == ID_URL;
  12749. if (focused && !url_had_focus) {
  12750. sug_typed[0] = '\0';
  12751. sug_close();
  12752. sug_open = 1;
  12753. sug_refresh();
  12754. }
  12755. url_had_focus = focused;
  12756. return focused;
  12757. }
  12758. static void url_submit(unsigned int *action)
  12759. {
  12760. if (ac_text[0] && s_eq(url_in.text, ac_text))
  12761. s_copy(click_url, ac_url, sizeof(click_url));
  12762. *action |= ACT_NAV;
  12763. sug_close();
  12764. }
  12765. /* The bar text changed through typing or editing. */
  12766. static void sug_changed(void)
  12767. {
  12768. unsigned int pl = s_len(sug_typed);
  12769. int grew = url_in.len > pl && url_in.cursor == url_in.len &&
  12770. !memcmp(url_in.text, sug_typed, pl);
  12771. s_copy(sug_typed, url_in.text, sizeof(sug_typed));
  12772. ac_text[0] = '\0';
  12773. sug_sel = -1;
  12774. sug_open = 1;
  12775. sug_refresh();
  12776. if (grew)
  12777. sug_inline();
  12778. }
  12779. /* Keys for the list, taken off the queue before the text field sees them.
  12780. * Only a leading run is handled; the rest goes to the field. */
  12781. static void sug_keys(void)
  12782. {
  12783. int k;
  12784. while ((k = ngui_key_peek(&ui)) != 0) {
  12785. if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
  12786. ngui_key(&ui);
  12787. if (!sug_open) {
  12788. sug_open = 1;
  12789. continue;
  12790. }
  12791. if (sug_sel < 0)
  12792. s_copy(sug_restore, url_in.text,
  12793. sizeof(sug_restore));
  12794. if (k == NGUI_KEY_DOWN)
  12795. sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
  12796. else
  12797. sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
  12798. ngui_input_set(&url_in, sug_sel >= 0 ?
  12799. hist_tab[sug_idx[sug_sel]].url :
  12800. sug_restore);
  12801. } else if (k == NGUI_KEY_ESC && sug_visible()) {
  12802. ngui_key(&ui);
  12803. if (sug_sel >= 0)
  12804. ngui_input_set(&url_in, sug_restore);
  12805. else if (ac_text[0] && s_eq(url_in.text, ac_text))
  12806. ngui_input_set(&url_in, sug_typed);
  12807. sug_close();
  12808. } else if (k == NGUI_KEY_DELETE && sug_visible() &&
  12809. sug_sel >= 0) {
  12810. ngui_key(&ui);
  12811. hist_forget(sug_idx[sug_sel]);
  12812. ngui_input_set(&url_in, sug_restore);
  12813. sug_sel = -1;
  12814. sug_refresh();
  12815. } else {
  12816. break;
  12817. }
  12818. }
  12819. }
  12820. /* A press on a row of last frame's list opens it; any press on the list is
  12821. * swallowed so the page underneath does not see it. */
  12822. static void sug_click(unsigned int *action)
  12823. {
  12824. int row;
  12825. if (!(ui.pressed & 1) || !sug_rect.w ||
  12826. !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
  12827. return;
  12828. row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
  12829. if (row >= 0 && row < sug_n) {
  12830. s_copy(click_url, hist_tab[sug_idx[row]].url,
  12831. sizeof(click_url));
  12832. *action |= ACT_NAV;
  12833. sug_close();
  12834. }
  12835. ui.pressed = 0;
  12836. }
  12837. static void draw_suggest(struct ngui_rect page)
  12838. {
  12839. struct ngui_rect r;
  12840. int i, rows = sug_n, hover = -1;
  12841. r.x = url_rect.x;
  12842. r.y = url_rect.y + url_rect.h + 1;
  12843. r.w = url_rect.w < 320 ? 320 : url_rect.w;
  12844. if (r.x + r.w > ui.w - 2)
  12845. r.w = ui.w - 2 - r.x;
  12846. while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
  12847. rows--;
  12848. if (rows <= 0 || r.w < 60) {
  12849. sug_rect.w = 0;
  12850. return;
  12851. }
  12852. r.h = rows * SUG_ROW_H + 2;
  12853. sug_rect = r;
  12854. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  12855. hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
  12856. ngui_set_cursor(&ui, CURSOR_POINTER);
  12857. }
  12858. ngui_fill_rect(&ui, r, ui.theme.border);
  12859. for (i = 0; i < rows; i++) {
  12860. const struct hist_ent *e = &hist_tab[sug_idx[i]];
  12861. struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
  12862. r.w - 2, SUG_ROW_H};
  12863. struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
  12864. unsigned short bg = i == sug_sel ? ui.theme.selection :
  12865. i == hover ? ui.theme.panel_alt :
  12866. ui.theme.panel;
  12867. ngui_fill_rect(&ui, rr, bg);
  12868. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
  12869. e->title[0] ? e->title : e->url,
  12870. ui.theme.text);
  12871. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
  12872. i == sug_sel ? ui.theme.text :
  12873. ui.theme.text_dim);
  12874. }
  12875. }
  12876. static void ctx_close(void);
  12877. static void ctx_open_from_right(struct ngui_rect page);
  12878. static void ctx_press(struct ngui_rect page);
  12879. static void draw_context(void);
  12880. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  12881. {
  12882. int x = r.x + 4, y = r.y + 4, h = 22;
  12883. int compact = r.w < 560;
  12884. int go_w = r.w < 420 ? 32 : 42;
  12885. int in_x, in_w, res;
  12886. ngui_fill_rect(&ui, r, ui.theme.panel);
  12887. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  12888. ui.theme.border);
  12889. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  12890. NGUI_ICON_CHEVRON_LEFT))
  12891. *action |= ACT_BACK;
  12892. x += 32;
  12893. if (!compact) {
  12894. if (ngui_icon_button(&ui, ID_FORWARD,
  12895. (struct ngui_rect){x, y, 28, h},
  12896. NGUI_ICON_CHEVRON_RIGHT))
  12897. *action |= ACT_FORWARD;
  12898. x += 32;
  12899. }
  12900. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  12901. NGUI_ICON_REFRESH))
  12902. *action |= ACT_RELOAD;
  12903. x += 32;
  12904. if (!compact) {
  12905. if (ngui_icon_button(&ui, ID_HOME,
  12906. (struct ngui_rect){x, y, 28, h},
  12907. NGUI_ICON_HOME))
  12908. *action |= ACT_HOME;
  12909. x += 32;
  12910. }
  12911. dl_button_rect = (struct ngui_rect){x, y, 28, h};
  12912. if (ngui_icon_button(&ui, ID_DOWNLOADS, dl_button_rect,
  12913. NGUI_ICON_DOWNLOAD)) {
  12914. dl_panel_open = !dl_panel_open;
  12915. if (dl_panel_open) {
  12916. dl_unseen = 0;
  12917. ctx_close();
  12918. sug_close();
  12919. ngui_set_focus(&ui, 0);
  12920. }
  12921. ngui_invalidate(&ui);
  12922. }
  12923. if (dl_active >= 0) {
  12924. int p = dl_percent();
  12925. if (p < 0)
  12926. p = 0;
  12927. ngui_fill_rect(&ui, (struct ngui_rect){
  12928. dl_button_rect.x + 3,
  12929. dl_button_rect.y + dl_button_rect.h - 4,
  12930. dl_button_rect.w - 6, 2}, ui.theme.border);
  12931. if (p > 0)
  12932. ngui_fill_rect(&ui, (struct ngui_rect){
  12933. dl_button_rect.x + 3,
  12934. dl_button_rect.y + dl_button_rect.h - 4,
  12935. (dl_button_rect.w - 6) * p / 100, 2},
  12936. ui.theme.accent);
  12937. }
  12938. if (dl_unseen && !dl_panel_open)
  12939. ngui_fill_rect(&ui, (struct ngui_rect){
  12940. dl_button_rect.x + dl_button_rect.w - 6,
  12941. dl_button_rect.y + 2, 4, 4}, ui.theme.accent);
  12942. x += 32;
  12943. in_x = x + 2;
  12944. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  12945. if (in_w < 60)
  12946. in_w = 60;
  12947. url_rect = (struct ngui_rect){in_x, y, in_w, h};
  12948. if (sug_focus_check())
  12949. sug_keys();
  12950. res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
  12951. sug_focus_check(); /* a click into the bar focuses it here */
  12952. if (res & NGUI_INPUT_CHANGED)
  12953. sug_changed();
  12954. if (res & NGUI_INPUT_SUBMIT)
  12955. url_submit(action);
  12956. if (res & NGUI_INPUT_CANCEL)
  12957. ngui_set_focus(&ui, 0);
  12958. if (ngui_button(&ui, ID_GO,
  12959. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  12960. "Go"))
  12961. url_submit(action);
  12962. if (!sug_focus_check())
  12963. sug_close();
  12964. }
  12965. static int page_hover_node(void)
  12966. {
  12967. if (!ui.inside || ctx_open || dl_panel_open)
  12968. return 0;
  12969. if (ui.mouse_x < page_rect.x ||
  12970. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  12971. ui.mouse_y < page_rect.y ||
  12972. ui.mouse_y >= page_rect.y + page_rect.h)
  12973. return 0;
  12974. return find_hit(ui.mouse_x, ui.mouse_y);
  12975. }
  12976. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  12977. {
  12978. int x, y, w = page.w, h = page.h;
  12979. if (!src || w <= 0 || h <= 0)
  12980. return;
  12981. for (y = 0; y < h; y++) {
  12982. unsigned short *s = src + (page.y + y) * sw + page.x;
  12983. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  12984. for (x = 0; x + 1 < w; x += 2) {
  12985. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  12986. }
  12987. if (x < w)
  12988. d[x] = s[x];
  12989. }
  12990. }
  12991. static void draw_page(struct ngui_rect page)
  12992. {
  12993. int left, right, ch;
  12994. int old_panel, old_dim;
  12995. unsigned short *saved_px;
  12996. unsigned short page_bg = ui.theme.bg;
  12997. int saved_w, saved_h, use_buf;
  12998. unsigned int t0 = u_ticks_ms();
  12999. page_rect = page;
  13000. {
  13001. unsigned int root = doc.nnode > 1 ?
  13002. br_find_tag(&doc, BR_TAG_HTML) : 0;
  13003. unsigned int body = doc.nnode > 1 ?
  13004. br_find_tag(&doc, BR_TAG_BODY) : 0;
  13005. struct br_style bs;
  13006. int bg_found = 0;
  13007. if (root) {
  13008. style_for_node(root - 1, &bs);
  13009. if (bs.has_bg) {
  13010. page_bg = bs.bg;
  13011. bg_found = 1;
  13012. }
  13013. }
  13014. if (body) {
  13015. style_for_node(body - 1, &bs);
  13016. if (bs.has_bg) {
  13017. page_bg = bs.bg;
  13018. bg_found = 1;
  13019. }
  13020. }
  13021. /* No canvas colour, but the author made the text dark
  13022. * (Infima's light theme: `--ifm-background-color:
  13023. * transparent` on html, #1c1e21 text): the page expects the
  13024. * white canvas of a normal browser, and dark text on the
  13025. * dark default canvas is unreadable. */
  13026. if (!bg_found && (body || root) && bs.color != ui.theme.text) {
  13027. unsigned int c = bs.color;
  13028. unsigned int lum = ((c >> 11) & 31) * 8 * 299 +
  13029. ((c >> 5) & 63) * 4 * 587 +
  13030. (c & 31) * 8 * 114;
  13031. if (lum < 100 * 1000)
  13032. page_bg = 0xFFFF;
  13033. }
  13034. }
  13035. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  13036. page_cache_valid && layout_valid &&
  13037. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  13038. !(ui.scroll_y &&
  13039. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  13040. page_scroll.offset == page_cache_scroll &&
  13041. page_cache_nnode == doc.nnode &&
  13042. page_cache_x == page.x && page_cache_y == page.y &&
  13043. page_cache_w == page.w && page_cache_h == page.h) {
  13044. blit_page(page, page_backbuf, pagebuf_w);
  13045. if (img_stat_n)
  13046. img_stat_paint += u_ticks_ms() - t0;
  13047. return;
  13048. }
  13049. ngui_fill_rect(&ui, page, page_bg);
  13050. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  13051. const char *s = page_loading ? "Loading..." : "No page";
  13052. int w = (int)ngui_text_width_ui(&ui, s);
  13053. ngui_text(&ui, page.x + (page.w - w) / 2,
  13054. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  13055. page_scroll.content_h = 0;
  13056. page_scroll.view_h = page.h;
  13057. page_cache_valid = 0;
  13058. return;
  13059. }
  13060. if (page.w < 40 || page.h < 40) {
  13061. page_cache_valid = 0;
  13062. return;
  13063. }
  13064. saved_px = ui.px;
  13065. saved_w = ui.w;
  13066. saved_h = ui.h;
  13067. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  13068. if (use_buf) {
  13069. ui.px = page_backbuf;
  13070. ui.w = pagebuf_w;
  13071. ui.h = pagebuf_h;
  13072. ngui_fill_rect(&ui, page, page_bg);
  13073. }
  13074. /* No gutter of our own: the body's UA margin provides it. The
  13075. * right 12 px stay clear for the scrollbar, like every viewport
  13076. * width below (page_rect.w - 12). */
  13077. left = page.x;
  13078. right = page.x + page.w - 12;
  13079. if (!layout_valid || left != layout_left || right != layout_right ||
  13080. layout_nnode != doc.nnode) {
  13081. unsigned int tm = u_ticks_ms();
  13082. layout_view_h = page.h;
  13083. layout_content_h = measure_page(left, right);
  13084. if (img_stat_n)
  13085. img_stat_reflow += u_ticks_ms() - tm;
  13086. layout_valid = 1;
  13087. layout_left = left;
  13088. layout_right = right;
  13089. layout_nnode = doc.nnode;
  13090. /* Scripts that measured before any layout (offsetWidth on
  13091. * mount) get a resize event once real boxes exist, and again
  13092. * whenever the page width changes. */
  13093. if (js_browser_active() && right - left != resize_sent_w)
  13094. resize_pending = 1;
  13095. }
  13096. ch = layout_content_h;
  13097. page_scroll.content_h = ch;
  13098. page_scroll.view_h = page.h;
  13099. t0 = u_ticks_ms();
  13100. ngui_scroll_begin(&ui, page, &page_scroll);
  13101. ngui_scroll_wheel(&ui, page, &page_scroll);
  13102. render_page(left, right, page.y - page_scroll.offset);
  13103. old_panel = ui.theme.panel_alt;
  13104. old_dim = ui.theme.text_dim;
  13105. ui.theme.panel_alt = 0xC618;
  13106. ui.theme.text_dim = 0x8410;
  13107. ngui_scroll_end(&ui, page, &page_scroll);
  13108. ui.theme.panel_alt = old_panel;
  13109. ui.theme.text_dim = old_dim;
  13110. if (use_buf) {
  13111. ui.px = saved_px;
  13112. ui.w = saved_w;
  13113. ui.h = saved_h;
  13114. blit_page(page, page_backbuf, pagebuf_w);
  13115. page_cache_valid = 1;
  13116. page_cache_scroll = page_scroll.offset;
  13117. page_cache_nnode = doc.nnode;
  13118. page_cache_x = page.x;
  13119. page_cache_y = page.y;
  13120. page_cache_w = page.w;
  13121. page_cache_h = page.h;
  13122. } else {
  13123. page_cache_valid = 0;
  13124. }
  13125. if (img_stat_n)
  13126. img_stat_paint += u_ticks_ms() - t0;
  13127. }
  13128. /* Lay the page out now, into the page back buffer, so scripts read real
  13129. * boxes for nodes they just inserted. Absolute/fixed boxes only get their
  13130. * boxes in the painting pass, so this is a full render; the next frame
  13131. * repaints the screen as usual. Skipped while the page has never been
  13132. * drawn (no viewport yet) or without the back buffer.
  13133. *
  13134. * The guard is a count per main-loop pass, not a time budget: a hover or
  13135. * click handler (Bootstrap's tooltip does ~6 write/read rounds) must get
  13136. * correct geometry even on the ION, where one re-layout of cloudron.io
  13137. * takes longer than any reasonable per-window budget; only a script that
  13138. * keeps writing and reading in one pass falls back to the last layout. */
  13139. #define FORCE_LAYOUT_PER_PASS 8
  13140. static int force_layout_count;
  13141. static void js_force_layout_pass_reset(void)
  13142. {
  13143. force_layout_count = 0;
  13144. }
  13145. static void js_force_layout(void)
  13146. {
  13147. static int busy;
  13148. unsigned short *saved_px = ui.px;
  13149. int saved_w = ui.w, saved_h = ui.h;
  13150. struct ngui_rect page = page_rect;
  13151. if (busy || !page_backbuf || pagebuf_w != ui.w ||
  13152. pagebuf_h != ui.h || page.w < 40 || page.h < 40 ||
  13153. layout_right <= layout_left ||
  13154. force_layout_count >= FORCE_LAYOUT_PER_PASS)
  13155. return;
  13156. force_layout_count++;
  13157. busy = 1;
  13158. ui.px = page_backbuf;
  13159. layout_view_h = page.h;
  13160. layout_content_h = measure_page(layout_left, layout_right);
  13161. layout_valid = 1;
  13162. layout_nnode = doc.nnode;
  13163. ngui_push_clip(&ui, page);
  13164. render_page(layout_left, layout_right, page.y - page_scroll.offset);
  13165. ngui_pop_clip(&ui);
  13166. ui.px = saved_px;
  13167. ui.w = saved_w;
  13168. ui.h = saved_h;
  13169. page_cache_valid = 0;
  13170. ngui_invalidate(&ui);
  13171. busy = 0;
  13172. }
  13173. static void draw_status(struct ngui_rect r)
  13174. {
  13175. static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
  13176. unsigned int n = 0;
  13177. int hover = page_hover_node();
  13178. unsigned short color;
  13179. const char *kind;
  13180. ngui_fill_rect(&ui, r, ui.theme.panel);
  13181. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  13182. ui.theme.border);
  13183. /* Only a real link target is shown: a form control, or an element
  13184. * that is merely clickable through a script listener (google.com's
  13185. * jsaction wrapper around its search field), is not a link. */
  13186. if (hover && !br_href(&doc, (unsigned int)hover))
  13187. hover = 0;
  13188. if (hover) {
  13189. const char *href = br_href(&doc, (unsigned int)hover);
  13190. char url[BR_URL_MAX];
  13191. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  13192. s_append(msg, &n, "Link: ", sizeof(msg));
  13193. s_append(msg, &n, url, sizeof(msg));
  13194. } else {
  13195. s_copy(msg, "Link", sizeof(msg));
  13196. }
  13197. color = ui.theme.accent;
  13198. } else if (status_text[0]) {
  13199. s_copy(msg, status_text, sizeof(msg));
  13200. color = status_error ? ui.theme.error : ui.theme.text;
  13201. } else if (page_title[0]) {
  13202. s_copy(msg, page_title, sizeof(msg));
  13203. color = ui.theme.text;
  13204. } else {
  13205. s_copy(msg, "Ready", sizeof(msg));
  13206. color = ui.theme.text_dim;
  13207. }
  13208. kind = s_eq(page_url, "about:home") ? "HOME" :
  13209. page_is_local ? "FILE" :
  13210. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  13211. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  13212. {
  13213. int kw = (int)ngui_text_width_ui(&ui, kind);
  13214. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  13215. ui.theme.text_dim);
  13216. }
  13217. }
  13218. /* ---- downloads panel -------------------------------------------------- */
  13219. static int dl_order[DL_MAX], dl_order_n;
  13220. static void dl_order_build(void)
  13221. {
  13222. int i, j;
  13223. dl_order_n = 0;
  13224. for (i = 0; i < DL_MAX; i++)
  13225. if (dl_tab[i].used)
  13226. dl_order[dl_order_n++] = i;
  13227. for (i = 1; i < dl_order_n; i++) {
  13228. int key = dl_order[i];
  13229. unsigned int stamp = dl_tab[key].stamp;
  13230. for (j = i - 1; j >= 0 &&
  13231. dl_tab[dl_order[j]].stamp < stamp; j--)
  13232. dl_order[j + 1] = dl_order[j];
  13233. dl_order[j + 1] = key;
  13234. }
  13235. }
  13236. static void dl_size_text(unsigned int size, char *out, unsigned int cap)
  13237. {
  13238. if (size >= 1024u * 1024u)
  13239. snprintf(out, cap, "%u.%u MB", size / (1024u * 1024u),
  13240. (size % (1024u * 1024u)) * 10 / (1024u * 1024u));
  13241. else if (size >= 1024u)
  13242. snprintf(out, cap, "%u KB", size / 1024u);
  13243. else
  13244. snprintf(out, cap, "%u bytes", size);
  13245. }
  13246. static void dl_ent_label(const struct dl_ent *e, char *out, unsigned int cap)
  13247. {
  13248. char base[16], ext[8];
  13249. if (e->name[0]) {
  13250. s_copy(out, e->name, cap);
  13251. return;
  13252. }
  13253. dl_url_name(e->url, "", base, sizeof(base), ext, sizeof(ext));
  13254. if (ext[0])
  13255. snprintf(out, cap, "%s.%s", base, ext);
  13256. else
  13257. s_copy(out, base, cap);
  13258. }
  13259. static void dl_ent_status(const struct dl_ent *e, char *out,
  13260. unsigned int cap)
  13261. {
  13262. char size[24];
  13263. switch (e->state) {
  13264. case DL_QUEUED:
  13265. s_copy(out, "Queued", cap);
  13266. break;
  13267. case DL_RUNNING: {
  13268. int p = dl_percent();
  13269. if (p >= 0) {
  13270. snprintf(out, cap, "Downloading %d%%", p);
  13271. } else {
  13272. dl_size_text(e->got, size, sizeof(size));
  13273. snprintf(out, cap, "Downloading %s", size);
  13274. }
  13275. break;
  13276. }
  13277. case DL_SAVING:
  13278. s_copy(out, "Saving...", cap);
  13279. break;
  13280. case DL_DONE:
  13281. dl_size_text(e->size, size, sizeof(size));
  13282. snprintf(out, cap, "Saved - %s", size);
  13283. break;
  13284. default:
  13285. if (e->err[0])
  13286. snprintf(out, cap, "Failed: %s", e->err);
  13287. else
  13288. s_copy(out, "Failed", cap);
  13289. break;
  13290. }
  13291. }
  13292. static void dl_panel_layout(struct ngui_rect page)
  13293. {
  13294. int w = DL_PANEL_W, rows, avail, h, x, y;
  13295. dl_order_build();
  13296. rows = dl_order_n;
  13297. if (rows > DL_PANEL_ROWS)
  13298. rows = DL_PANEL_ROWS;
  13299. avail = (page.h - 46) / DL_ROW_H;
  13300. if (avail < 0)
  13301. avail = 0;
  13302. if (rows > avail)
  13303. rows = avail;
  13304. dl_panel_rows = rows;
  13305. if (w > page.w - 16)
  13306. w = page.w - 16;
  13307. if (w < 120)
  13308. w = 120;
  13309. h = 36 + (rows ? rows * DL_ROW_H : 28) + 6;
  13310. if (h > page.h - 8)
  13311. h = page.h - 8;
  13312. x = dl_button_rect.x + dl_button_rect.w - w;
  13313. if (x + w > page.x + page.w - 4)
  13314. x = page.x + page.w - 4 - w;
  13315. if (x < page.x + 4)
  13316. x = page.x + 4;
  13317. y = page.y + 2;
  13318. dl_panel_rect = (struct ngui_rect){x, y, w, h};
  13319. dl_clear_rect = (struct ngui_rect){x + w - 54, y + 6, 46, 20};
  13320. }
  13321. static void dl_panel_press(struct ngui_rect page)
  13322. {
  13323. if (!dl_panel_open || !ui.pressed)
  13324. return;
  13325. dl_panel_layout(page);
  13326. if (ngui_rect_contains(&dl_panel_rect, ui.press_x, ui.press_y)) {
  13327. if (ngui_rect_contains(&dl_clear_rect, ui.press_x, ui.press_y))
  13328. dl_clear_history();
  13329. ui.pressed = ui.released = 0;
  13330. return;
  13331. }
  13332. if (!ngui_rect_contains(&dl_button_rect, ui.press_x, ui.press_y)) {
  13333. dl_panel_open = 0;
  13334. ngui_invalidate(&ui);
  13335. if (ngui_rect_contains(&page, ui.press_x, ui.press_y))
  13336. ui.pressed = ui.released = 0;
  13337. }
  13338. }
  13339. static void draw_downloads(struct ngui_rect page)
  13340. {
  13341. int i;
  13342. if (!dl_panel_open)
  13343. return;
  13344. dl_panel_layout(page);
  13345. if (ui.inside && ngui_rect_contains(&dl_panel_rect, ui.mouse_x,
  13346. ui.mouse_y))
  13347. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  13348. if (dl_history_count() > 0 && ui.inside &&
  13349. ngui_rect_contains(&dl_clear_rect, ui.mouse_x, ui.mouse_y))
  13350. ngui_set_cursor(&ui, CURSOR_POINTER);
  13351. ngui_fill_rect(&ui, dl_panel_rect, ui.theme.border);
  13352. ngui_fill_rect(&ui, (struct ngui_rect){dl_panel_rect.x + 1,
  13353. dl_panel_rect.y + 1, dl_panel_rect.w - 2,
  13354. dl_panel_rect.h - 2}, ui.theme.panel);
  13355. ngui_text_styled(&ui, dl_panel_rect.x + 10, dl_panel_rect.y + 8,
  13356. "Downloads", 9, ui.theme.text, 1, 1);
  13357. if (dl_history_count() > 0) {
  13358. int cw = (int)ngui_text_width_ui(&ui, "Clear");
  13359. int hot = ui.inside && ngui_rect_contains(&dl_clear_rect,
  13360. ui.mouse_x,
  13361. ui.mouse_y);
  13362. ngui_text(&ui, dl_clear_rect.x + (dl_clear_rect.w - cw) / 2,
  13363. dl_clear_rect.y + 1, "Clear",
  13364. hot ? ui.theme.accent : ui.theme.text_dim);
  13365. }
  13366. if (dl_order_n > dl_panel_rows && dl_panel_rows > 0 &&
  13367. dl_panel_rect.w > 260) {
  13368. char more[24];
  13369. int mw;
  13370. snprintf(more, sizeof(more), "%d more", dl_order_n - dl_panel_rows);
  13371. mw = (int)ngui_text_width_ui(&ui, more);
  13372. ngui_text(&ui, dl_clear_rect.x - mw - 8, dl_clear_rect.y + 1,
  13373. more, ui.theme.text_dim);
  13374. }
  13375. if (!dl_order_n) {
  13376. ngui_text(&ui, dl_panel_rect.x + 12,
  13377. dl_panel_rect.y + 40, "No downloads yet",
  13378. ui.theme.text_dim);
  13379. return;
  13380. }
  13381. for (i = 0; i < dl_panel_rows; i++) {
  13382. struct dl_ent *e = &dl_tab[dl_order[i]];
  13383. struct ngui_rect rr = {dl_panel_rect.x + 1,
  13384. dl_panel_rect.y + 30 + i * DL_ROW_H,
  13385. dl_panel_rect.w - 2, DL_ROW_H};
  13386. char name[DL_NAME_MAX], status[96];
  13387. int hot = ui.inside &&
  13388. ngui_rect_contains(&rr, ui.mouse_x, ui.mouse_y);
  13389. enum ngui_icon icon = NGUI_ICON_DOWNLOAD;
  13390. unsigned short icon_color = ui.theme.text_dim;
  13391. dl_ent_label(e, name, sizeof(name));
  13392. dl_ent_status(e, status, sizeof(status));
  13393. if (e->state == DL_DONE) {
  13394. icon = NGUI_ICON_FILE;
  13395. icon_color = ui.theme.text_dim;
  13396. } else if (e->state == DL_FAILED) {
  13397. icon = NGUI_ICON_CLOSE;
  13398. icon_color = ui.theme.error;
  13399. } else {
  13400. icon_color = ui.theme.accent;
  13401. }
  13402. ngui_fill_rect(&ui, rr, hot ? ui.theme.panel_alt : ui.theme.panel);
  13403. ngui_icon(&ui, (struct ngui_rect){rr.x + 7, rr.y + 8, 20, 20},
  13404. icon, icon_color);
  13405. ngui_text_ellipsis(&ui, rr, rr.x + 34, rr.y + 3, name,
  13406. ui.theme.text);
  13407. ngui_text_ellipsis(&ui, rr, rr.x + 34, rr.y + 19, status,
  13408. e->state == DL_FAILED ? ui.theme.error :
  13409. ui.theme.text_dim);
  13410. if (e->state == DL_RUNNING || e->state == DL_SAVING) {
  13411. int p = dl_percent();
  13412. int bw = rr.w - 42;
  13413. ngui_fill_rect(&ui, (struct ngui_rect){rr.x + 34,
  13414. rr.y + rr.h - 6, bw, 3},
  13415. ui.theme.border);
  13416. if (p > 0)
  13417. ngui_fill_rect(&ui, (struct ngui_rect){
  13418. rr.x + 34, rr.y + rr.h - 6,
  13419. bw * p / 100, 3}, ui.theme.accent);
  13420. }
  13421. }
  13422. }
  13423. /* Mouse cursor over the page: the hovered node's CSS `cursor` (inherited);
  13424. * for `auto`, a hand over links, the I-beam over text fields, and the
  13425. * progress arrow anywhere on the page while it is still loading. The
  13426. * toolbar's URL field sets its own I-beam through ngui. */
  13427. static void page_cursor(void)
  13428. {
  13429. int hover = page_hover_node();
  13430. struct br_style st;
  13431. if (!hover) {
  13432. if (page_loading && ui.inside &&
  13433. ngui_rect_contains(&page_rect, ui.mouse_x, ui.mouse_y))
  13434. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  13435. return;
  13436. }
  13437. style_for_node((unsigned int)hover, &st);
  13438. if (st.cursor != BR_CURSOR_AUTO) {
  13439. ngui_set_cursor(&ui, (int)st.cursor - 1);
  13440. return;
  13441. }
  13442. if (br_href(&doc, (unsigned int)hover)) {
  13443. ngui_set_cursor(&ui, CURSOR_POINTER);
  13444. return;
  13445. }
  13446. if (form_is_control((unsigned int)hover)) {
  13447. int k = form_kind_of((unsigned int)hover);
  13448. if (form_disabled((unsigned int)hover))
  13449. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  13450. else if (k == FORM_TEXT || k == FORM_PASSWORD ||
  13451. k == FORM_TEXTAREA)
  13452. ngui_set_cursor(&ui, CURSOR_TEXT);
  13453. return;
  13454. }
  13455. if (page_loading)
  13456. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  13457. }
  13458. static void draw(unsigned int *action)
  13459. {
  13460. struct ngui_rect r = {0, 0, ui.w, ui.h};
  13461. struct ngui_rect toolbar, status, page;
  13462. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  13463. status = ngui_cut_bottom(&r, BR_STATUS_H);
  13464. page = r;
  13465. if (sug_visible())
  13466. sug_click(action);
  13467. ctx_open_from_right(page);
  13468. ctx_press(page);
  13469. dl_panel_press(page);
  13470. draw_toolbar(toolbar, action);
  13471. draw_page(page);
  13472. draw_status(status);
  13473. page_cursor();
  13474. if (sug_visible())
  13475. draw_suggest(page);
  13476. else
  13477. sug_rect.w = 0;
  13478. draw_downloads(page);
  13479. draw_context();
  13480. }
  13481. static void redraw_now(void)
  13482. {
  13483. unsigned int action = 0;
  13484. ngui_begin(&ui);
  13485. draw(&action);
  13486. ngui_end(&ui);
  13487. }
  13488. static void handle_keys(unsigned int *action)
  13489. {
  13490. int k, scrolled = 0;
  13491. if (form_focus >= doc.nnode)
  13492. form_focus = 0;
  13493. if (form_focus && !ngui_focus(&ui)) {
  13494. while ((k = ngui_key(&ui)) != 0)
  13495. form_key(k);
  13496. return;
  13497. }
  13498. /* Batch queued page keys: a slow full-page render must not make a
  13499. * held Page Down advance only once every few frames. */
  13500. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  13501. scrolled++;
  13502. if (scrolled)
  13503. ngui_invalidate(&ui);
  13504. if (ngui_focus(&ui))
  13505. return;
  13506. while ((k = ngui_key(&ui)) != 0) {
  13507. switch (k) {
  13508. case NGUI_KEY_ESC:
  13509. if (ctx_open) {
  13510. ctx_close();
  13511. } else if (dl_panel_open) {
  13512. dl_panel_open = 0;
  13513. ngui_invalidate(&ui);
  13514. } else {
  13515. *action |= ACT_CLOSE;
  13516. }
  13517. break;
  13518. case NGUI_KEY_TAB:
  13519. case 0x0C: /* Ctrl+L */
  13520. ngui_set_focus(&ui, ID_URL);
  13521. break;
  13522. case 0x12: /* Ctrl+R */
  13523. *action |= ACT_RELOAD;
  13524. break;
  13525. case NGUI_KEY_BACKSPACE:
  13526. *action |= ACT_BACK;
  13527. break;
  13528. case NGUI_KEY_UP:
  13529. ngui_scroll_to(&page_scroll,
  13530. page_scroll.offset - 24);
  13531. ngui_invalidate(&ui);
  13532. break;
  13533. case NGUI_KEY_DOWN:
  13534. ngui_scroll_to(&page_scroll,
  13535. page_scroll.offset + 24);
  13536. ngui_invalidate(&ui);
  13537. break;
  13538. case NGUI_KEY_HOME:
  13539. ngui_scroll_to(&page_scroll, 0);
  13540. ngui_invalidate(&ui);
  13541. break;
  13542. case NGUI_KEY_END:
  13543. ngui_scroll_to(&page_scroll,
  13544. page_scroll.content_h -
  13545. page_scroll.view_h);
  13546. ngui_invalidate(&ui);
  13547. break;
  13548. default:
  13549. break;
  13550. }
  13551. }
  13552. }
  13553. static unsigned int form_ancestor(unsigned int node)
  13554. {
  13555. unsigned int p = node;
  13556. while (p && p < doc.nnode) {
  13557. if (doc.nodes[p].tag == BR_TAG_FORM &&
  13558. doc.nodes[p].type == BR_NODE_ELEM)
  13559. return p;
  13560. p = doc.nodes[p].parent;
  13561. }
  13562. return 0;
  13563. }
  13564. static int form_descendant(unsigned int node, unsigned int form)
  13565. {
  13566. unsigned int p = node;
  13567. while (p && p < doc.nnode) {
  13568. if (p == form)
  13569. return 1;
  13570. p = doc.nodes[p].parent;
  13571. }
  13572. return 0;
  13573. }
  13574. static void form_reset_form(unsigned int form)
  13575. {
  13576. unsigned int i;
  13577. for (i = 0; i < FORM_MAX; i++)
  13578. if (form_states[i].used &&
  13579. form_descendant(form_states[i].node, form))
  13580. form_states[i].used = 0;
  13581. form_focus = 0;
  13582. }
  13583. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  13584. const char *s)
  13585. {
  13586. static const char hex[] = "0123456789ABCDEF";
  13587. while (s && *s && *n + 1 < cap) {
  13588. unsigned char c = (unsigned char)*s++;
  13589. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  13590. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  13591. c == '.' || c == '~') {
  13592. dst[(*n)++] = (char)c;
  13593. } else if (c == ' ') {
  13594. dst[(*n)++] = '+';
  13595. } else if (*n + 3 < cap) {
  13596. dst[(*n)++] = '%';
  13597. dst[(*n)++] = hex[c >> 4];
  13598. dst[(*n)++] = hex[c & 15];
  13599. }
  13600. }
  13601. dst[*n] = '\0';
  13602. }
  13603. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  13604. const char *name, const char *value, int *first)
  13605. {
  13606. if (!name || !name[0])
  13607. return;
  13608. if (!*first && *n + 1 < cap)
  13609. dst[(*n)++] = '&';
  13610. *first = 0;
  13611. form_url_append(dst, n, cap, name);
  13612. if (*n + 1 < cap)
  13613. dst[(*n)++] = '=';
  13614. form_url_append(dst, n, cap, value ? value : "");
  13615. dst[*n] = '\0';
  13616. }
  13617. static int form_submit_form(unsigned int node, int fire_event)
  13618. {
  13619. unsigned int form = form_ancestor(node);
  13620. char action[BR_URL_MAX], query[2048];
  13621. unsigned int qn = 0, i;
  13622. int first = 1, is_post = 0;
  13623. const char *a, *method;
  13624. if (!form)
  13625. return 0;
  13626. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  13627. return 0;
  13628. method = br_find_attr(&doc, form, "method");
  13629. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  13630. is_post = 1;
  13631. a = br_find_attr(&doc, form, "action");
  13632. if (a && a[0]) {
  13633. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  13634. return 0;
  13635. } else {
  13636. s_copy(action, page_url, sizeof(action));
  13637. }
  13638. query[0] = '\0';
  13639. for (i = 0; i < doc.nnode; i++) {
  13640. struct br_node *nd = &doc.nodes[i];
  13641. struct form_state *fs;
  13642. const char *name;
  13643. const char *value = "";
  13644. if (nd->type != BR_NODE_ELEM || i == form ||
  13645. !form_descendant(i, form))
  13646. continue;
  13647. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  13648. nd->tag != BR_TAG_SELECT)
  13649. continue;
  13650. if (form_disabled(i))
  13651. continue;
  13652. name = br_find_attr(&doc, i, "name");
  13653. if (!name || !name[0])
  13654. continue;
  13655. fs = form_get(i, 1);
  13656. if (!fs)
  13657. continue;
  13658. if (nd->tag == BR_TAG_SELECT) {
  13659. char opt[64];
  13660. if (!form_option_text(i, fs->selected, opt,
  13661. sizeof(opt)))
  13662. s_copy(opt, "", sizeof(opt));
  13663. value = opt;
  13664. {
  13665. unsigned int c, oi = 0;
  13666. for (c = nd->first; c;
  13667. c = doc.nodes[c].next) {
  13668. if (doc.nodes[c].type != BR_NODE_ELEM ||
  13669. doc.nodes[c].tag != BR_TAG_OPTION)
  13670. continue;
  13671. if (oi == fs->selected) {
  13672. const char *v =
  13673. br_value(&doc, c);
  13674. if (v && v[0])
  13675. value = v;
  13676. break;
  13677. }
  13678. oi++;
  13679. }
  13680. }
  13681. } else if (nd->tag == BR_TAG_INPUT) {
  13682. int kind = form_kind_of(i);
  13683. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  13684. if (!fs->checked)
  13685. continue;
  13686. value = br_value(&doc, i);
  13687. if (!value || !value[0])
  13688. value = "on";
  13689. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  13690. kind == FORM_BUTTON) {
  13691. if (i != node)
  13692. continue;
  13693. value = fs->value;
  13694. } else {
  13695. value = fs->value;
  13696. }
  13697. } else {
  13698. value = fs->value;
  13699. }
  13700. form_add_param(query, &qn, sizeof(query), name, value, &first);
  13701. }
  13702. if (is_post) {
  13703. if (action[0] == '/') {
  13704. set_status("POST forms need an HTTP action URL", 1, 4000);
  13705. ngui_invalidate(&ui);
  13706. return 0;
  13707. }
  13708. if (qn >= sizeof(pending_post))
  13709. qn = sizeof(pending_post) - 1;
  13710. if (qn)
  13711. memcpy(pending_post, query, qn);
  13712. pending_post[qn] = '\0';
  13713. pending_post_len = qn;
  13714. pending_post_is = 1;
  13715. } else {
  13716. pending_post_len = 0;
  13717. pending_post_is = 0;
  13718. if (qn) {
  13719. unsigned int an = s_len(action);
  13720. if (an + qn + 2 < sizeof(action)) {
  13721. action[an++] = strchr(action, '?') ? '&' : '?';
  13722. action[an] = '\0';
  13723. s_copy(action + an, query,
  13724. sizeof(action) - an);
  13725. }
  13726. }
  13727. }
  13728. s_copy(pending_url, action, sizeof(pending_url));
  13729. pending_action |= ACT_NAV;
  13730. cancel_fetch = 1;
  13731. ngui_invalidate(&ui);
  13732. return 1;
  13733. }
  13734. static void form_reset_event(unsigned int form)
  13735. {
  13736. if (form && !js_browser_event(form, "reset", 1, 1))
  13737. return;
  13738. if (form)
  13739. form_reset_form(form);
  13740. else
  13741. form_reset_state();
  13742. form_dirty = 0;
  13743. layout_valid = 0;
  13744. ngui_invalidate(&ui);
  13745. }
  13746. static void form_blur(void)
  13747. {
  13748. unsigned int node = form_focus;
  13749. form_focus = 0;
  13750. if (node && form_dirty) {
  13751. form_dirty = 0;
  13752. js_browser_event(node, "change", 1, 0);
  13753. }
  13754. }
  13755. static void form_click(unsigned int node)
  13756. {
  13757. struct form_state *fs;
  13758. int kind, changed = 0;
  13759. if (!form_is_control(node) || form_disabled(node))
  13760. return;
  13761. if (form_focus != node)
  13762. form_blur();
  13763. fs = form_get(node, 1);
  13764. if (!fs)
  13765. return;
  13766. kind = form_kind_of(node);
  13767. /* Focus moves on the press, before `click` is dispatched: a page
  13768. * that cancels the click (a framework's root listener) suppresses
  13769. * the activation behaviour below, never the focus (as in other
  13770. * browsers, where focus follows mousedown). */
  13771. form_focus = node;
  13772. form_dirty = 0;
  13773. if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  13774. kind == FORM_TEXTAREA)
  13775. fs->caret = fs->len;
  13776. layout_valid = 0;
  13777. ngui_invalidate(&ui);
  13778. if (!js_browser_event(node, "click", 1, 1))
  13779. return;
  13780. fs = form_get(node, 0); /* the handler may have changed the DOM */
  13781. if (!fs)
  13782. return;
  13783. if (kind == FORM_CHECKBOX) {
  13784. fs->checked = !fs->checked;
  13785. changed = 1;
  13786. } else if (kind == FORM_RADIO) {
  13787. const char *name = br_find_attr(&doc, node, "name");
  13788. unsigned int i;
  13789. fs->checked = 1;
  13790. changed = 1;
  13791. if (name) {
  13792. for (i = 0; i < FORM_MAX; i++) {
  13793. struct form_state *o = &form_states[i];
  13794. if (!o->used || o->node == node)
  13795. continue;
  13796. if (form_kind_of(o->node) == FORM_RADIO) {
  13797. const char *on = br_find_attr(&doc,
  13798. o->node,
  13799. "name");
  13800. if (on && s_eq(on, name))
  13801. o->checked = 0;
  13802. }
  13803. }
  13804. }
  13805. } else if (kind == FORM_SELECT) {
  13806. unsigned int n = form_option_count(node);
  13807. if (n) {
  13808. fs->selected = (unsigned char)
  13809. ((fs->selected + 1) % n);
  13810. changed = 1;
  13811. }
  13812. } else if (kind == FORM_SUBMIT) {
  13813. form_submit_form(node, 1);
  13814. return;
  13815. } else if (kind == FORM_RESET) {
  13816. form_reset_event(form_ancestor(node));
  13817. return;
  13818. }
  13819. if (changed) {
  13820. js_browser_event(node, "input", 1, 0);
  13821. js_browser_event(node, "change", 1, 0);
  13822. }
  13823. layout_valid = 0;
  13824. ngui_invalidate(&ui);
  13825. }
  13826. static void form_focus_next(void)
  13827. {
  13828. unsigned int start = form_focus ? form_focus + 1 : 0;
  13829. unsigned int i;
  13830. form_blur();
  13831. for (i = start; i < doc.nnode; i++) {
  13832. if (form_is_control(i) && !form_disabled(i) &&
  13833. !s_eq(br_type(&doc, i), "hidden")) {
  13834. form_focus = i;
  13835. layout_valid = 0;
  13836. ngui_invalidate(&ui);
  13837. return;
  13838. }
  13839. }
  13840. form_focus = 0;
  13841. layout_valid = 0;
  13842. ngui_invalidate(&ui);
  13843. }
  13844. static void form_key(int k)
  13845. {
  13846. struct form_state *fs;
  13847. int kind;
  13848. if (!form_focus || form_focus >= doc.nnode) {
  13849. form_focus = 0;
  13850. return;
  13851. }
  13852. fs = form_get(form_focus, 1);
  13853. if (!fs || form_disabled(form_focus))
  13854. return;
  13855. kind = form_kind_of(form_focus);
  13856. if (kind == FORM_SELECT) {
  13857. unsigned int n = form_option_count(form_focus);
  13858. int changed = 0;
  13859. if (k == NGUI_KEY_UP && n) {
  13860. fs->selected = (unsigned char)
  13861. ((fs->selected + n - 1) % n);
  13862. changed = 1;
  13863. } else if (k == NGUI_KEY_DOWN && n) {
  13864. fs->selected = (unsigned char)
  13865. ((fs->selected + 1) % n);
  13866. changed = 1;
  13867. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  13868. form_blur();
  13869. layout_valid = 0;
  13870. ngui_invalidate(&ui);
  13871. return;
  13872. } else {
  13873. return;
  13874. }
  13875. if (changed) {
  13876. js_browser_event(form_focus, "input", 1, 0);
  13877. js_browser_event(form_focus, "change", 1, 0);
  13878. }
  13879. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  13880. if (k == ' ') {
  13881. form_click(form_focus);
  13882. return;
  13883. }
  13884. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  13885. form_blur();
  13886. layout_valid = 0;
  13887. ngui_invalidate(&ui);
  13888. }
  13889. return;
  13890. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  13891. kind == FORM_RESET) {
  13892. if (k == NGUI_KEY_ESC) {
  13893. form_blur();
  13894. layout_valid = 0;
  13895. ngui_invalidate(&ui);
  13896. } else if (k == '\r' || k == '\n' || k == ' ') {
  13897. form_click(form_focus);
  13898. }
  13899. return;
  13900. } else if (k == NGUI_KEY_TAB) {
  13901. form_focus_next();
  13902. return;
  13903. } else if (k == NGUI_KEY_ESC) {
  13904. form_blur();
  13905. layout_valid = 0;
  13906. ngui_invalidate(&ui);
  13907. return;
  13908. } else if (k == '\r' || k == '\n') {
  13909. unsigned int node = form_focus;
  13910. form_blur();
  13911. if (form_ancestor(node))
  13912. form_submit_form(node, 1);
  13913. layout_valid = 0;
  13914. ngui_invalidate(&ui);
  13915. return;
  13916. } else if (k == NGUI_KEY_BACKSPACE) {
  13917. if (fs->caret) {
  13918. unsigned int i = --fs->caret;
  13919. for (; i < fs->len; i++)
  13920. fs->value[i] = fs->value[i + 1];
  13921. if (fs->len)
  13922. fs->len--;
  13923. form_dirty = 1;
  13924. js_browser_event(form_focus, "input", 1, 0);
  13925. }
  13926. } else if (k == NGUI_KEY_DELETE) {
  13927. if (fs->caret < fs->len) {
  13928. unsigned int i;
  13929. for (i = fs->caret; i < fs->len; i++)
  13930. fs->value[i] = fs->value[i + 1];
  13931. fs->len--;
  13932. form_dirty = 1;
  13933. js_browser_event(form_focus, "input", 1, 0);
  13934. }
  13935. } else if (k == NGUI_KEY_LEFT) {
  13936. if (fs->caret)
  13937. fs->caret--;
  13938. } else if (k == NGUI_KEY_RIGHT) {
  13939. if (fs->caret < fs->len)
  13940. fs->caret++;
  13941. } else if (k == NGUI_KEY_HOME) {
  13942. fs->caret = 0;
  13943. } else if (k == NGUI_KEY_END) {
  13944. fs->caret = fs->len;
  13945. } else if (k >= 32 && k < 127) {
  13946. if (fs->len < FORM_VALUE_MAX) {
  13947. unsigned int i;
  13948. for (i = fs->len; i > fs->caret; i--)
  13949. fs->value[i] = fs->value[i - 1];
  13950. fs->value[fs->caret++] = (char)k;
  13951. fs->len++;
  13952. form_dirty = 1;
  13953. js_browser_event(form_focus, "input", 1, 0);
  13954. }
  13955. } else {
  13956. return;
  13957. }
  13958. fs->value[fs->len] = '\0';
  13959. layout_valid = 0;
  13960. ngui_invalidate(&ui);
  13961. }
  13962. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  13963. * a same-document navigation: update the URL and fire hashchange. Returns
  13964. * 1 when handled. */
  13965. static int link_fragment_nav(unsigned int node)
  13966. {
  13967. const char *href = br_href(&doc, node);
  13968. char url[BR_URL_MAX];
  13969. unsigned int n = 0;
  13970. if (!href || !href[0] || !js_browser_active())
  13971. return 0;
  13972. if (href[0] == '#') {
  13973. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  13974. url[n] = page_url[n];
  13975. n++;
  13976. }
  13977. url[n] = '\0';
  13978. s_append(url, &n, href, sizeof(url));
  13979. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  13980. return 0;
  13981. }
  13982. if (!same_doc_fragment(url))
  13983. return href[0] == '#';
  13984. page_set_fragment(url, 1);
  13985. js_browser_hashchange();
  13986. return 1;
  13987. }
  13988. /* A positioned box laid out while transparent or visibility:hidden (or
  13989. * inside one): it has a box for scripts but must not catch the pointer. */
  13990. static int node_invisible(unsigned int n)
  13991. {
  13992. unsigned int guard = 0;
  13993. while (n < doc.nnode && guard++ < 64) {
  13994. struct br_style st;
  13995. style_for_node(n, &st);
  13996. if (st.opacity_hidden || st.vis_hidden)
  13997. return 1;
  13998. if (n == 0)
  13999. break;
  14000. n = doc.nodes[n].parent;
  14001. }
  14002. return 0;
  14003. }
  14004. /* The innermost laid-out box under a screen point: the smallest valid box
  14005. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  14006. * Used to deliver clicks to elements that are neither links nor controls
  14007. * (a Vue <div role="button">, a card with a click listener). */
  14008. static int node_contains(unsigned int a, unsigned int n);
  14009. static unsigned int find_box_hit(int x, int y)
  14010. {
  14011. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  14012. int root;
  14013. /* A covering positioned box (a modal) takes the point: only it and
  14014. * its descendants are candidates, not the page painted under it. */
  14015. if (find_hit_ex(x, y, &root) || root < 0)
  14016. root = -1;
  14017. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  14018. const struct br_layout_box *b = &layout_boxes[i];
  14019. unsigned int area;
  14020. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  14021. x < b->x || y < b->y || x >= b->x + b->w ||
  14022. y >= b->y + b->h)
  14023. continue;
  14024. if (root >= 0 && !node_contains((unsigned int)root, i))
  14025. continue;
  14026. area = (unsigned int)b->w * (unsigned int)b->h;
  14027. if (area <= best_area && !node_invisible(i)) {
  14028. best = i;
  14029. best_area = area;
  14030. }
  14031. }
  14032. return best;
  14033. }
  14034. /* ---- page context menu ------------------------------------------------ */
  14035. static void ctx_add(unsigned int action, const char *label, const char *url)
  14036. {
  14037. int i;
  14038. if (ctx_n >= CTX_MAX || !url || !url[0])
  14039. return;
  14040. for (i = 0; i < ctx_n; i++)
  14041. if (ctx_action[i] == action && s_eq(ctx_url[i], url))
  14042. return;
  14043. s_copy(ctx_label[ctx_n], label, sizeof(ctx_label[0]));
  14044. s_copy(ctx_url[ctx_n], url, sizeof(ctx_url[0]));
  14045. ctx_action[ctx_n] = action;
  14046. ctx_n++;
  14047. }
  14048. static unsigned int ctx_ancestor_tag(unsigned int node, unsigned char tag)
  14049. {
  14050. unsigned int guard = 0;
  14051. while (node && node < doc.nnode && guard++ < BR_MAX_NODES) {
  14052. if (doc.nodes[node].type == BR_NODE_ELEM &&
  14053. doc.nodes[node].tag == tag)
  14054. return node;
  14055. node = doc.nodes[node].parent;
  14056. }
  14057. return 0;
  14058. }
  14059. static void ctx_open_at(struct ngui_rect page, int x, int y)
  14060. {
  14061. unsigned int hit = (unsigned int)find_hit(x, y);
  14062. unsigned int box = find_box_hit(x, y);
  14063. unsigned int img = 0;
  14064. char resolved[BR_URL_MAX];
  14065. const char *href;
  14066. ctx_open = 0;
  14067. ctx_n = 0;
  14068. if (box && doc.nodes[box].tag == BR_TAG_IMG)
  14069. img = box;
  14070. else if (hit && doc.nodes[hit].tag == BR_TAG_IMG)
  14071. img = hit;
  14072. else if (hit)
  14073. img = ctx_ancestor_tag(hit, BR_TAG_IMG);
  14074. if (!img && box)
  14075. img = ctx_ancestor_tag(box, BR_TAG_IMG);
  14076. if (img && br_src(&doc, img) &&
  14077. resolve_link(page_url, br_src(&doc, img), resolved,
  14078. sizeof(resolved)) == 0)
  14079. ctx_add(CTX_SAVE_IMAGE, "Save image", resolved);
  14080. /* A CSS background image is an image too; check the element under
  14081. * the pointer and then its ancestors (a card's image behind text). */
  14082. if (!img) {
  14083. unsigned int n = box ? box : hit, guard = 0;
  14084. while (n && n < doc.nnode && guard++ < BR_MAX_NODES) {
  14085. struct br_style st;
  14086. style_for_node(n, &st);
  14087. if (st.bg_image > 0) {
  14088. const char *bg = br_bg_image_url(st.bg_image - 1);
  14089. if (bg && resolve_link(page_url, bg, resolved,
  14090. sizeof(resolved)) == 0)
  14091. ctx_add(CTX_SAVE_IMAGE, "Save image",
  14092. resolved);
  14093. break;
  14094. }
  14095. n = doc.nodes[n].parent;
  14096. }
  14097. }
  14098. href = hit ? br_href(&doc, hit) : 0;
  14099. if (!href && box)
  14100. href = br_href(&doc, box);
  14101. if (href && resolve_link(page_url, href, resolved,
  14102. sizeof(resolved)) == 0)
  14103. ctx_add(CTX_SAVE_LINK, "Save link", resolved);
  14104. if (page_url[0] && !starts_with(page_url, "about:"))
  14105. ctx_add(CTX_SAVE_PAGE, "Save page", page_url);
  14106. if (!ctx_n)
  14107. return;
  14108. ctx_w = 190;
  14109. ctx_h = ctx_n * CTX_ROW_H + 2;
  14110. ctx_x = x;
  14111. ctx_y = y;
  14112. if (ctx_x + ctx_w > page.x + page.w - 4)
  14113. ctx_x = page.x + page.w - 4 - ctx_w;
  14114. if (ctx_y + ctx_h > page.y + page.h - 4)
  14115. ctx_y = page.y + page.h - 4 - ctx_h;
  14116. if (ctx_x < page.x + 4)
  14117. ctx_x = page.x + 4;
  14118. if (ctx_y < page.y + 4)
  14119. ctx_y = page.y + 4;
  14120. ctx_open = 1;
  14121. ngui_invalidate(&ui);
  14122. }
  14123. static void ctx_close(void)
  14124. {
  14125. if (!ctx_open)
  14126. return;
  14127. ctx_open = 0;
  14128. ngui_invalidate(&ui);
  14129. }
  14130. static void ctx_open_from_right(struct ngui_rect page)
  14131. {
  14132. if (!ui.right_pressed)
  14133. return;
  14134. if (ngui_rect_contains(&page, ui.right_press_x, ui.right_press_y)) {
  14135. dl_panel_open = 0;
  14136. ngui_set_focus(&ui, 0);
  14137. sug_close();
  14138. ctx_open_at(page, ui.right_press_x, ui.right_press_y);
  14139. } else {
  14140. ctx_close();
  14141. }
  14142. }
  14143. static void ctx_press(struct ngui_rect page)
  14144. {
  14145. struct ngui_rect r;
  14146. int row;
  14147. if (!ctx_open || !ui.pressed)
  14148. return;
  14149. r = (struct ngui_rect){ctx_x, ctx_y, ctx_w, ctx_h};
  14150. if (ngui_rect_contains(&r, ui.press_x, ui.press_y)) {
  14151. row = -1;
  14152. if (ui.press_y > ctx_y &&
  14153. ui.press_y < ctx_y + 1 + ctx_n * CTX_ROW_H)
  14154. row = (ui.press_y - ctx_y - 1) / CTX_ROW_H;
  14155. if (row >= 0 && row < ctx_n)
  14156. dl_queue(ctx_url[row]);
  14157. ctx_close();
  14158. ui.pressed = ui.released = 0;
  14159. return;
  14160. }
  14161. if (ngui_rect_contains(&page, ui.press_x, ui.press_y)) {
  14162. ctx_close();
  14163. ui.pressed = ui.released = 0;
  14164. return;
  14165. }
  14166. ctx_close();
  14167. }
  14168. static void draw_context(void)
  14169. {
  14170. struct ngui_rect r;
  14171. int i, hover = -1;
  14172. if (!ctx_open)
  14173. return;
  14174. r = (struct ngui_rect){ctx_x, ctx_y, ctx_w, ctx_h};
  14175. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  14176. if (ui.mouse_y > ctx_y &&
  14177. ui.mouse_y < ctx_y + 1 + ctx_n * CTX_ROW_H)
  14178. hover = (ui.mouse_y - ctx_y - 1) / CTX_ROW_H;
  14179. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  14180. }
  14181. ngui_fill_rect(&ui, r, ui.theme.border);
  14182. for (i = 0; i < ctx_n; i++) {
  14183. struct ngui_rect rr = {ctx_x + 1,
  14184. ctx_y + 1 + i * CTX_ROW_H, ctx_w - 2, CTX_ROW_H};
  14185. ngui_fill_rect(&ui, rr, i == hover ? ui.theme.selection :
  14186. ui.theme.panel);
  14187. ngui_text(&ui, rr.x + 10,
  14188. rr.y + (rr.h - ngui_text_line_height(&ui,
  14189. ui.font_px, 0)) / 2,
  14190. ctx_label[i], ui.theme.text);
  14191. }
  14192. }
  14193. /* The element under the pointer for hover events: the innermost laid-out
  14194. * box, or the link/control hit inside it (an inline <a> has no box of its
  14195. * own but a hit rectangle). -1 when none. */
  14196. static int hover_node = -1;
  14197. static int node_contains(unsigned int a, unsigned int n)
  14198. {
  14199. unsigned int guard = 0;
  14200. while (n < doc.nnode && guard++ < BR_MAX_NODES) {
  14201. if (n == a)
  14202. return 1;
  14203. if (n == 0)
  14204. return 0;
  14205. n = doc.nodes[n].parent;
  14206. }
  14207. return 0;
  14208. }
  14209. static int hover_target(void)
  14210. {
  14211. int h, x = ui.mouse_x, y = ui.mouse_y;
  14212. unsigned int b;
  14213. if (!ui.inside || ui.buttons || sug_visible() || ctx_open ||
  14214. dl_panel_open ||
  14215. x < page_rect.x || x >= page_rect.x + page_rect.w - 12 ||
  14216. y < page_rect.y || y >= page_rect.y + page_rect.h)
  14217. return -1;
  14218. h = find_hit(x, y);
  14219. b = find_box_hit(x, y);
  14220. if (h && (!b || node_contains(b, (unsigned int)h)))
  14221. return h;
  14222. if (b)
  14223. return (int)b;
  14224. return h ? h : -1;
  14225. }
  14226. /* mouseover/mouseout (bubbling, with relatedTarget) at the old and new
  14227. * element, and mouseleave/mouseenter on every ancestor that was left or
  14228. * entered (outermost first for enter), like a browser's boundary events.
  14229. * jQuery 1.11 builds its mouseenter (Bootstrap tooltips) from mouseover
  14230. * and relatedTarget. */
  14231. static void page_hover_events(void)
  14232. {
  14233. int now, old, cx, cy, path[64], np = 0, i;
  14234. unsigned int n;
  14235. if (!js_browser_active()) {
  14236. hover_node = -1;
  14237. return;
  14238. }
  14239. now = hover_target();
  14240. if (now >= (int)doc.nnode)
  14241. now = -1;
  14242. if (now == hover_node)
  14243. return;
  14244. old = hover_node;
  14245. if (old >= (int)doc.nnode)
  14246. old = -1;
  14247. hover_node = now;
  14248. cx = ui.mouse_x - page_rect.x;
  14249. cy = ui.mouse_y - page_rect.y;
  14250. if (old >= 0) {
  14251. js_browser_mouse_event((unsigned int)old, "mouseout", 1, now,
  14252. cx, cy);
  14253. for (n = (unsigned int)old, i = 0;
  14254. n < doc.nnode && i < 64 &&
  14255. !(now >= 0 && node_contains(n, (unsigned int)now)); i++) {
  14256. js_browser_mouse_event(n, "mouseleave", 0, now, cx, cy);
  14257. if (n == 0)
  14258. break;
  14259. n = doc.nodes[n].parent;
  14260. }
  14261. }
  14262. if (now < 0 || now >= (int)doc.nnode)
  14263. return;
  14264. js_browser_mouse_event((unsigned int)now, "mouseover", 1, old, cx, cy);
  14265. for (n = (unsigned int)now;
  14266. n < doc.nnode && np < 64 &&
  14267. !(old >= 0 && node_contains(n, (unsigned int)old));) {
  14268. path[np++] = (int)n;
  14269. if (n == 0)
  14270. break;
  14271. n = doc.nodes[n].parent;
  14272. }
  14273. for (i = np - 1; i >= 0; i--)
  14274. js_browser_mouse_event((unsigned int)path[i], "mouseenter", 0,
  14275. old, cx, cy);
  14276. }
  14277. static void handle_page_click(unsigned int *action)
  14278. {
  14279. int node;
  14280. char url[BR_URL_MAX];
  14281. if (!ui.pressed)
  14282. return;
  14283. if (ui.press_x < page_rect.x ||
  14284. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  14285. ui.press_y < page_rect.y ||
  14286. ui.press_y >= page_rect.y + page_rect.h)
  14287. return;
  14288. node = find_hit(ui.press_x, ui.press_y);
  14289. if (!node) {
  14290. unsigned int box;
  14291. if (!js_browser_active())
  14292. return;
  14293. box = find_box_hit(ui.press_x, ui.press_y);
  14294. if (box) {
  14295. form_blur();
  14296. js_browser_event(box, "click", 1, 1);
  14297. }
  14298. return;
  14299. }
  14300. if (form_is_control((unsigned int)node)) {
  14301. form_click((unsigned int)node);
  14302. return;
  14303. }
  14304. form_blur();
  14305. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  14306. return;
  14307. if (link_fragment_nav((unsigned int)node))
  14308. return;
  14309. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  14310. sizeof(url)) != 0)
  14311. return;
  14312. s_copy(click_url, url, sizeof(click_url));
  14313. *action |= ACT_NAV;
  14314. }
  14315. void _start(const char *arg)
  14316. {
  14317. struct win_info wi;
  14318. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  14319. u_win_create(960, 640, "Browser", &wi) != 0 &&
  14320. u_win_create(780, 540, "Browser", &wi) != 0) {
  14321. u_puts("browser: no graphics window\n");
  14322. u_exit(1);
  14323. }
  14324. ufont_set_arena_bytes(BR_FONT_ARENA);
  14325. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  14326. url_in.placeholder = "http://...";
  14327. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  14328. ui.theme.accent);
  14329. br_set_viewport(wi.width);
  14330. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  14331. s_copy(cwd, "/", sizeof(cwd));
  14332. heap_clear();
  14333. origin_cache_load();
  14334. css_cache_init();
  14335. script_cache_init();
  14336. font_cache_init();
  14337. persist_restore();
  14338. hist_load();
  14339. dl_load();
  14340. page_scroll.offset = 0;
  14341. page_scroll.content_h = 0;
  14342. if (arg && arg[0]) {
  14343. navigate(arg, 1);
  14344. } else {
  14345. load_home(1);
  14346. /* Start ready to type: keep the home page, but leave the address
  14347. * bar empty instead of showing "about:home". */
  14348. ngui_input_set(&url_in, "");
  14349. ngui_set_focus(&ui, ID_URL);
  14350. }
  14351. for (;;) {
  14352. unsigned int action = 0;
  14353. unsigned int now;
  14354. click_url[0] = '\0';
  14355. if (pending_action) {
  14356. action |= pending_action & ACT_WAIT_NAV;
  14357. if (pending_url[0])
  14358. s_copy(click_url, pending_url, sizeof(click_url));
  14359. pending_action = 0;
  14360. pending_url[0] = '\0';
  14361. cancel_fetch = 0;
  14362. } else if (preload_active) {
  14363. if (preload_wait)
  14364. preload_wait = 0;
  14365. else
  14366. preload_step();
  14367. } else if ((preload_pending &&
  14368. page_scroll.offset != preload_scroll) ||
  14369. (preload_rescan && layout_valid)) {
  14370. preload_scroll = page_scroll.offset;
  14371. preload_rescan = 0;
  14372. preload_pending = 0;
  14373. preload_node = 0;
  14374. preload_active = 1;
  14375. }
  14376. js_force_layout_pass_reset();
  14377. js_browser_tick();
  14378. if (resize_pending && !pending_action) {
  14379. resize_pending = 0;
  14380. resize_sent_w = layout_right - layout_left;
  14381. js_browser_window_event("resize");
  14382. }
  14383. persist_tick();
  14384. dl_poll();
  14385. if (pending_action)
  14386. continue;
  14387. now = u_ticks_ms();
  14388. if (status_until && (int)(now - status_until) >= 0) {
  14389. status_text[0] = '\0';
  14390. status_until = 0;
  14391. status_error = 0;
  14392. ngui_invalidate(&ui);
  14393. }
  14394. if (!ngui_begin(&ui)) {
  14395. /* A queued navigation (e.g. Enter in the URL bar during
  14396. * a slow fetch) must be handled even when this frame
  14397. * needs no redraw. */
  14398. if (!action) {
  14399. fetch_workers_stop_if_unfocused();
  14400. u_sleep_ms(10);
  14401. continue;
  14402. }
  14403. } else {
  14404. js_force_layout_pass_reset();
  14405. draw(&action);
  14406. handle_keys(&action);
  14407. handle_page_click(&action);
  14408. page_hover_events();
  14409. anim_after_frame();
  14410. ngui_end(&ui);
  14411. }
  14412. if (action & ACT_NAV) {
  14413. if (click_url[0]) {
  14414. navigate(click_url, 1);
  14415. click_url[0] = '\0';
  14416. } else {
  14417. navigate(url_in.text, 1);
  14418. }
  14419. }
  14420. if (action & ACT_BACK) {
  14421. if (hist_pos > 0) {
  14422. hist_pos--;
  14423. if (same_doc_fragment(history[hist_pos])) {
  14424. page_set_fragment(history[hist_pos], 0);
  14425. js_browser_hashchange();
  14426. } else {
  14427. navigate(history[hist_pos], 0);
  14428. }
  14429. }
  14430. }
  14431. if (action & ACT_FORWARD) {
  14432. if (hist_pos + 1 < hist_len) {
  14433. hist_pos++;
  14434. if (same_doc_fragment(history[hist_pos])) {
  14435. page_set_fragment(history[hist_pos], 0);
  14436. js_browser_hashchange();
  14437. } else {
  14438. navigate(history[hist_pos], 0);
  14439. }
  14440. }
  14441. }
  14442. if (action & ACT_RELOAD) {
  14443. if (s_eq(page_url, "about:home"))
  14444. load_home(0);
  14445. else
  14446. navigate(page_url, 0);
  14447. }
  14448. if (action & ACT_HOME)
  14449. load_home(1);
  14450. if (action & ACT_CLOSE)
  14451. quit = 1;
  14452. if (quit)
  14453. break;
  14454. if (pending_action)
  14455. continue;
  14456. fetch_workers_stop_if_unfocused();
  14457. u_sleep_ms(10);
  14458. }
  14459. fetch_workers_stop_all();
  14460. fetch_worker_stop(&dl_worker);
  14461. u_win_close();
  14462. u_exit(0);
  14463. }