browser.c 419 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729
  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. /* A table centred by legacy markup: a <center> parent or align="center".
  9362. * CSS text-align on the parent does not centre a block table, as in
  9363. * browsers. */
  9364. static int table_centered(unsigned int node)
  9365. {
  9366. const char *al = br_find_attr(&doc, node, "align");
  9367. unsigned int p = doc.nodes[node].parent;
  9368. if (al && (al[0] == 'c' || al[0] == 'C'))
  9369. return 1;
  9370. return p < doc.nnode && doc.nodes[p].type == BR_NODE_ELEM &&
  9371. doc.nodes[p].tag == BR_TAG_CENTER;
  9372. }
  9373. static void layout_block(struct lay *l, unsigned int node,
  9374. const struct br_style *st, int depth,
  9375. unsigned short link)
  9376. {
  9377. int old_left = l->left, old_right = l->right, old_align = l->align;
  9378. int parent_cb_h = l->cb_h;
  9379. int saved_parent_top = l->parent_top;
  9380. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  9381. int saved_cb_top = l->cb_top;
  9382. int top, l0, r0;
  9383. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  9384. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  9385. int deco_w, deco_h, content_w, content_h, box_h;
  9386. int img_dh = 0;
  9387. int definite_w = 0;
  9388. int normal_top = 0;
  9389. int rel_dx = 0, rel_dy = 0;
  9390. int clip_pushed = 0;
  9391. struct ngui_rect clip_rect;
  9392. /* A DOM level costs about two depth units (layout_block ->
  9393. * layout_children), so 48 covers a ~24-level page. Real news pages
  9394. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  9395. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  9396. return;
  9397. flow_y = l->y;
  9398. flow_left = l->left;
  9399. flow_right = l->right;
  9400. positioned = st->pos == 1 || st->pos == 2;
  9401. relative = st->pos == 3;
  9402. sticky = st->pos == 4;
  9403. shifted = relative || sticky || st->transform_set;
  9404. if (positioned) {
  9405. int def_w = st->width_kind == 1 ? st->width : -1;
  9406. if (st->pos == 2) {
  9407. int avail_w = page_rect.w - 12;
  9408. if (st->right_set && def_w >= 0)
  9409. l->left = page_rect.x + avail_w - st->right -
  9410. def_w;
  9411. else if (!st->left_set && !st->right_set)
  9412. l->left = flow_left; /* static position */
  9413. else
  9414. l->left = page_rect.x +
  9415. (st->left_set ? st->left : 0);
  9416. l->right = def_w >= 0 ? l->left + def_w :
  9417. st->width_kind == 2 ?
  9418. l->left + avail_w * (int)st->width / 100 :
  9419. page_rect.x + avail_w;
  9420. /* Placed by `bottom` (a page footer): an auto
  9421. * height is the measured one. */
  9422. if (st->bottom_set && st->height_kind)
  9423. l->y = page_rect.y + page_rect.h -
  9424. st->bottom -
  9425. style_height_px(st, page_rect.w);
  9426. else if (st->bottom_set && !st->top_set &&
  9427. block_h[node])
  9428. l->y = page_rect.y + page_rect.h -
  9429. st->bottom - (int)block_h[node] -
  9430. mp_px(st, 0, avail_w) -
  9431. mp_px(st, 2, avail_w);
  9432. else
  9433. l->y = page_rect.y +
  9434. (st->top_set ? st->top : 0);
  9435. } else {
  9436. int left = flow_left + (st->left_set ? st->left : 0);
  9437. unsigned int parent = doc.nodes[node].parent;
  9438. if (st->right_set && def_w >= 0)
  9439. left = flow_right - st->right - def_w;
  9440. l->left = left;
  9441. l->right = def_w >= 0 ? left + def_w :
  9442. flow_right +
  9443. (st->left_set ? st->left : 0);
  9444. l->y = flow_y + (st->top_set ? st->top : 0);
  9445. if (st->bottom_set && st->height_kind &&
  9446. parent < BR_MAX_NODES && block_h[parent] > 0)
  9447. l->y = flow_y + block_h[parent] - st->bottom -
  9448. style_height_px(st, old_right - old_left);
  9449. else if (st->bottom_set && !st->top_set &&
  9450. parent < BR_MAX_NODES && block_h[parent] > 0 &&
  9451. block_h[node] > 0)
  9452. l->y = flow_y + block_h[parent] - st->bottom -
  9453. (int)block_h[node] -
  9454. mp_px(st, 0, old_right - old_left) -
  9455. mp_px(st, 2, old_right - old_left);
  9456. }
  9457. /* An auto width placed by one horizontal offset is
  9458. * shrink-to-fit (CSS 2.1 10.3.7): a Bootstrap tooltip or a
  9459. * dropdown is as wide as its content, not its containing
  9460. * block. With neither offset the box keeps the containing
  9461. * width, since `inset: 0` overlays are not parsed and only
  9462. * stretch that way; an empty measure keeps it too. */
  9463. if (st->width_kind == 0 && st->left_set != st->right_set) {
  9464. int cb_l = st->pos == 2 ? page_rect.x : flow_left;
  9465. int cb_r = st->pos == 2 ? page_rect.x +
  9466. page_rect.w - 12 : flow_right;
  9467. int avail = cb_r - cb_l - (st->left_set ? st->left :
  9468. st->right);
  9469. int w = intrinsic_width(l->ui, node, st, 0,
  9470. cb_r - cb_l);
  9471. if (w > 0) {
  9472. w += mp_px(st, 7, cb_r - cb_l) +
  9473. mp_px(st, 5, cb_r - cb_l) +
  9474. mp_px(st, 3, cb_r - cb_l) +
  9475. mp_px(st, 1, cb_r - cb_l) +
  9476. st->border_w[1] + st->border_w[3];
  9477. if (st->max_width_kind == 1 &&
  9478. w > (int)st->max_width)
  9479. w = (int)st->max_width;
  9480. if (avail > 8 && w > avail)
  9481. w = avail;
  9482. if (st->right_set) {
  9483. l->right = cb_r - st->right;
  9484. l->left = l->right - w;
  9485. } else {
  9486. l->right = l->left + w;
  9487. }
  9488. }
  9489. }
  9490. /* `left: 100%` parks a box (Docusaurus' "Skip to main
  9491. * content" link) past the containing block's right edge
  9492. * until it is focused. An auto width then has no room: it
  9493. * used to collapse to 8 px and wrap one word per line into a
  9494. * tall column painted over the page. Lay it out at the
  9495. * containing block's width so it stays one line and
  9496. * overflows (off-screen) like in a real browser. */
  9497. if (def_w < 0 && l->right - l->left < 8) {
  9498. int avail = st->pos == 2 ? page_rect.w - 12 :
  9499. flow_right - flow_left;
  9500. l->right = l->left + (avail > 8 ? avail : 8);
  9501. }
  9502. old_left = l->left;
  9503. old_right = l->right;
  9504. } else if (relative) {
  9505. rel_dx = st->left_set ? st->left :
  9506. (st->right_set ? -st->right : 0);
  9507. rel_dy = st->top_set ? st->top :
  9508. (st->bottom_set ? -st->bottom : 0);
  9509. }
  9510. if (st->transform_set || (st->tr_mask & BR_TR_TRANSFORM) ||
  9511. (render_pass && anim_has(node))) {
  9512. int tx = st->tx, ty = st->ty;
  9513. /* translate(0, -25%): a percentage of the element's own
  9514. * box (the measure pass's height, the flow width). */
  9515. if (st->tx_pct)
  9516. tx = (old_right - old_left) * st->tx / 100;
  9517. if (st->ty_pct)
  9518. ty = node < BR_MAX_NODES ? block_h[node] * st->ty / 100
  9519. : 0;
  9520. if (!st->transform_set)
  9521. tx = ty = 0;
  9522. tx = anim_value(node, ANIM_TX, tx, st);
  9523. ty = anim_value(node, ANIM_TY, ty, st);
  9524. rel_dx += tx;
  9525. rel_dy += ty;
  9526. if (tx || ty)
  9527. shifted = 1;
  9528. }
  9529. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  9530. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  9531. doc.nodes[node].tag == BR_TAG_SELECT ||
  9532. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  9533. !button_has_elements(node)) {
  9534. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  9535. s_eq(br_type(&doc, node), "hidden"))
  9536. return;
  9537. /* Reached as a block-level box (a flex item): the control
  9538. * fills the box the caller assigned, and its line is flushed
  9539. * here; flex layout resets the run list for the next item, so
  9540. * a queued run would never be drawn. */
  9541. form_fill_line = 1;
  9542. add_form_run(l, node, st, link);
  9543. form_fill_line = 0;
  9544. flush_line(l);
  9545. return;
  9546. }
  9547. flush_line(l);
  9548. cbw = old_right - old_left;
  9549. if (cbw < 8)
  9550. cbw = 8;
  9551. l->y += mp_px(st, 0, cbw);
  9552. top = l->y;
  9553. ml = mp_px(st, 3, cbw);
  9554. mr = mp_px(st, 1, cbw);
  9555. bl = st->border_w[3];
  9556. br = st->border_w[1];
  9557. pl = mp_px(st, 7, cbw);
  9558. pr = mp_px(st, 5, cbw);
  9559. bt = st->border_w[0];
  9560. bb = st->border_w[2];
  9561. pt = mp_px(st, 4, cbw);
  9562. pb = mp_px(st, 6, cbw);
  9563. deco_w = bl + br + pl + pr;
  9564. deco_h = bt + bb + pt + pb;
  9565. if (st->width_kind) {
  9566. int w;
  9567. if (st->width_kind == 3)
  9568. w = cbw * st->width_calc_pct / 100 +
  9569. st->width_calc_px;
  9570. else
  9571. w = css_size(st->width_kind, st->width, cbw);
  9572. if (w < 0)
  9573. w = 0;
  9574. content_w = st->box_sizing ? w - deco_w : w;
  9575. definite_w = 1;
  9576. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  9577. doc.nodes[node].tag == BR_TAG_TD ||
  9578. doc.nodes[node].tag == BR_TAG_TH) &&
  9579. doc.nodes[node].width_attr) {
  9580. /* Legacy table/cell width attributes: percentages resolve
  9581. * against the containing block, bare numbers are pixels. */
  9582. int w = doc.nodes[node].width_pct ?
  9583. cbw * doc.nodes[node].width_attr / 100 :
  9584. doc.nodes[node].width_attr;
  9585. if (w < 0)
  9586. w = 0;
  9587. content_w = st->box_sizing ? w - deco_w : w;
  9588. definite_w = 1;
  9589. } else {
  9590. content_w = cbw - ml - mr - deco_w;
  9591. }
  9592. if (content_w < 0)
  9593. content_w = 0;
  9594. if (st->max_width_kind) {
  9595. int mw = st->max_width_kind == 3 ?
  9596. cbw * st->max_width_calc_pct / 100 +
  9597. st->max_width_calc_px :
  9598. css_size(st->max_width_kind, st->max_width, cbw);
  9599. int max_box = st->box_sizing ? mw : mw + deco_w;
  9600. /* A clamped auto width is used as the width, so auto
  9601. * margins share the rest (Google's 688 px search box). */
  9602. if (content_w + deco_w > max_box) {
  9603. content_w = max_box - deco_w;
  9604. definite_w = 1;
  9605. }
  9606. }
  9607. if (st->min_width_kind) {
  9608. int mw = st->min_width_kind == 3 ?
  9609. cbw * st->min_width_calc_pct / 100 +
  9610. st->min_width_calc_px :
  9611. css_size(st->min_width_kind, st->min_width, cbw);
  9612. int min_box = st->box_sizing ? mw : mw + deco_w;
  9613. if (content_w + deco_w < min_box) {
  9614. content_w = min_box - deco_w;
  9615. definite_w = 1;
  9616. }
  9617. }
  9618. if (content_w < 8)
  9619. content_w = 8;
  9620. if (definite_w) {
  9621. int free_w = cbw - ml - mr - deco_w - content_w;
  9622. if (free_w < 0)
  9623. free_w = 0;
  9624. if (st->ml_auto && st->mr_auto) {
  9625. ml = free_w / 2;
  9626. mr = free_w - ml;
  9627. } else if (st->ml_auto) {
  9628. ml = free_w;
  9629. } else if (st->mr_auto) {
  9630. mr = free_w;
  9631. } else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  9632. table_centered(node)) {
  9633. /* <center><table width=85%> (Hacker News) and
  9634. * <table align=center> centre the table box. */
  9635. ml = free_w / 2;
  9636. mr = free_w - ml;
  9637. }
  9638. }
  9639. if (doc.nodes[node].tag == BR_TAG_IMG) {
  9640. int iw, ih;
  9641. image_block_size(node, st, cbw, &iw, &ih);
  9642. content_w = iw;
  9643. img_dh = ih;
  9644. }
  9645. l0 = old_left + ml;
  9646. r0 = l0 + deco_w + content_w;
  9647. if (r0 < l0 + 8)
  9648. r0 = l0 + 8;
  9649. normal_top = top;
  9650. if (sticky) {
  9651. if (st->top_set) {
  9652. int stick = page_rect.y + st->top;
  9653. if (normal_top < stick)
  9654. rel_dy += stick - normal_top;
  9655. } else if (st->bottom_set && block_h[node]) {
  9656. int stick = page_rect.y + page_rect.h - st->bottom -
  9657. block_h[node];
  9658. if (normal_top > stick)
  9659. rel_dy += stick - normal_top;
  9660. }
  9661. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  9662. block_h[doc.nodes[node].parent]) {
  9663. unsigned int p = doc.nodes[node].parent;
  9664. int ptop = l->parent_top;
  9665. int pbottom = ptop + block_h[p];
  9666. int eh = block_h[node];
  9667. int moved_top = normal_top + rel_dy;
  9668. int moved_bottom = moved_top + eh;
  9669. if (moved_bottom > pbottom)
  9670. rel_dy -= moved_bottom - pbottom;
  9671. moved_top = normal_top + rel_dy;
  9672. if (moved_top < ptop)
  9673. rel_dy += ptop - moved_top;
  9674. }
  9675. }
  9676. if (shifted && l->draw) {
  9677. top += rel_dy;
  9678. l0 += rel_dx;
  9679. r0 += rel_dx;
  9680. }
  9681. l->parent_top = top;
  9682. if (st->pos != 0) {
  9683. /* Positioned boxes establish the containing block for their
  9684. * absolutely positioned descendants. */
  9685. l->cb_left = l0;
  9686. l->cb_right = r0;
  9687. l->cb_top = top;
  9688. }
  9689. if (l->draw && block_h[node] &&
  9690. top < page_rect.y + page_rect.h &&
  9691. top + block_h[node] > page_rect.y) {
  9692. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  9693. int rtl = css_radius(st, 0, box.w, box.h);
  9694. int rtr = css_radius(st, 1, box.w, box.h);
  9695. int rbr = css_radius(st, 2, box.w, box.h);
  9696. int rbl = css_radius(st, 3, box.w, box.h);
  9697. if (st->transform_scale) {
  9698. if (st->has_bg)
  9699. fill_transformed_rect(l->ui, box, st->bg, st);
  9700. } else if (rtl || rtr || rbr || rbl) {
  9701. if (st->has_bg) {
  9702. int bw = st->border_w[0];
  9703. if (bw > 0 && !st->border_t[0] &&
  9704. st->border_c[0] != st->bg &&
  9705. box.w > bw * 2 && box.h > bw * 2) {
  9706. struct ngui_rect inner = {
  9707. box.x + bw, box.y + bw,
  9708. box.w - bw * 2, box.h - bw * 2
  9709. };
  9710. int itl = rtl > bw ? rtl - bw : 0;
  9711. int itr = rtr > bw ? rtr - bw : 0;
  9712. int ibr = rbr > bw ? rbr - bw : 0;
  9713. int ibl = rbl > bw ? rbl - bw : 0;
  9714. ngui_fill_round_rect(l->ui, box, rtl,
  9715. rtr, rbr, rbl,
  9716. st->border_c[0]);
  9717. ngui_fill_round_rect(l->ui, inner,
  9718. itl, itr, ibr,
  9719. ibl, st->bg);
  9720. } else {
  9721. ngui_fill_round_rect(l->ui, box, rtl,
  9722. rtr, rbr, rbl,
  9723. st->bg);
  9724. }
  9725. } else if (st->border_w[0] && !st->border_t[0]) {
  9726. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  9727. rbl, st->border_w[0],
  9728. st->border_c[0]);
  9729. }
  9730. /* Rounded boxes paint their background image too
  9731. * (app icons are rounded squares), kept inside the
  9732. * corner arcs. */
  9733. if (st->bg_image)
  9734. draw_bg_image_round(l, box, node, st, rtl, rtr,
  9735. rbr, rbl);
  9736. } else {
  9737. if (st->has_bg)
  9738. ngui_fill_rect(l->ui, box, st->bg);
  9739. if (st->bg_image)
  9740. draw_bg_image(l, box, node, st);
  9741. if (st->border_w[0] || st->border_w[1] ||
  9742. st->border_w[2] || st->border_w[3])
  9743. draw_border_box(l->ui, box, st);
  9744. }
  9745. }
  9746. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  9747. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  9748. content_w, img_dh);
  9749. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  9750. l->ui && l->ui->nclip < 4) {
  9751. clip_rect.x = l0 + bl;
  9752. clip_rect.y = top + bt;
  9753. clip_rect.w = (r0 - l0) - bl - br;
  9754. clip_rect.h = (int)block_h[node] - bt - bb;
  9755. if (clip_rect.w > 0 && clip_rect.h > 0) {
  9756. ngui_push_clip(l->ui, clip_rect);
  9757. clip_pushed = 1;
  9758. }
  9759. }
  9760. l->left = l0 + bl + pl;
  9761. l->right = l->left + content_w;
  9762. if (l->right < l->left + 8)
  9763. l->right = l->left + 8;
  9764. l->align = st->align;
  9765. l->line_left = l->left;
  9766. l->line_right = l->right;
  9767. l->y = top + bt + pt;
  9768. if (doc.nodes[node].tag == BR_TAG_HR) {
  9769. if (l->draw)
  9770. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  9771. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  9772. l->y += 8;
  9773. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  9774. int vw = l->right - l->left;
  9775. int vh;
  9776. if (doc.nodes[node].width_pct)
  9777. vw = vw * doc.nodes[node].width_attr / 100;
  9778. else if (doc.nodes[node].width_attr)
  9779. vw = doc.nodes[node].width_attr;
  9780. if (vw > l->right - l->left)
  9781. vw = l->right - l->left;
  9782. if (vw < 8)
  9783. vw = 8;
  9784. vh = vw * 9 / 16;
  9785. if (vh > 240)
  9786. vh = 240;
  9787. if (vh < 80)
  9788. vh = 80;
  9789. if (l->draw) {
  9790. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  9791. vw, vh}, 0xD69A);
  9792. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  9793. vw, vh}, 0x8410);
  9794. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  9795. 0x4208);
  9796. }
  9797. l->y += vh + 4;
  9798. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  9799. int dw, dh, cw = l->right - l->left;
  9800. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  9801. if (l->draw && l->y < page_rect.y + page_rect.h &&
  9802. l->y + dh > page_rect.y)
  9803. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  9804. l->y += dh;
  9805. } else {
  9806. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  9807. !st->no_bullet) {
  9808. char *m = li_marker[node];
  9809. if (!m[0]) {
  9810. unsigned int parent = doc.nodes[node].parent;
  9811. int style = st->list_style;
  9812. int idx = parent ? list_index(parent, node) : 1;
  9813. if (style == BR_LIST_AUTO)
  9814. style = (parent &&
  9815. doc.nodes[parent].tag ==
  9816. BR_TAG_OL) ?
  9817. BR_LIST_DECIMAL : BR_LIST_DISC;
  9818. list_marker_text(m, sizeof(li_marker[node]),
  9819. style, idx);
  9820. }
  9821. if (l->draw && m[0]) {
  9822. int mw = (int)ngui_text_width_ui(l->ui, m);
  9823. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  9824. st->color);
  9825. }
  9826. }
  9827. /* This box's definite content height, for its children's
  9828. * percentage heights. */
  9829. if (doc.nodes[node].tag == BR_TAG_HTML ||
  9830. doc.nodes[node].tag == BR_TAG_BODY)
  9831. l->cb_h = layout_view_h;
  9832. else if (st->height_kind == 1)
  9833. l->cb_h = (int)st->height -
  9834. (st->box_sizing ? deco_h : 0);
  9835. else if (st->height_kind == 2 && parent_cb_h > 0)
  9836. l->cb_h = parent_cb_h * (int)st->height / 100 -
  9837. (st->box_sizing ? deco_h : 0);
  9838. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  9839. l->cb_h = content_w * (int)st->aspect_h /
  9840. (int)st->aspect_w;
  9841. else if (!st->height_kind && node < BR_MAX_NODES &&
  9842. flex_stretch_h[node] > deco_h)
  9843. l->cb_h = flex_stretch_h[node] - deco_h;
  9844. else
  9845. l->cb_h = 0;
  9846. if (l->cb_h < 0)
  9847. l->cb_h = 0;
  9848. if (doc.nodes[node].tag == BR_TAG_TR)
  9849. layout_table_row(l, node, st, depth + 1, link);
  9850. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  9851. table_has_rowspan(node))
  9852. layout_table(l, node, st, depth + 1, link);
  9853. else if (st->grid_auto)
  9854. layout_grid_auto(l, node, st, depth + 1, link);
  9855. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  9856. st->grid_gap > 0)
  9857. layout_grid_children(l, node, st, depth + 1, link);
  9858. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  9859. flex_wants_row(node, st))
  9860. layout_flex_children(l, node, st, depth + 1, link);
  9861. else if (st->display == BR_DISPLAY_FLEX && st->flex_col)
  9862. layout_flex_column(l, node, st, depth + 1, link);
  9863. else
  9864. layout_children(l, node, st, depth + 1, link);
  9865. l->cb_h = parent_cb_h;
  9866. }
  9867. flush_line(l);
  9868. if (clip_pushed)
  9869. ngui_pop_clip(l->ui);
  9870. if (l->float_active) {
  9871. if (l->y < l->float_bottom)
  9872. l->y = l->float_bottom;
  9873. l->float_active = 0;
  9874. }
  9875. if (doc.nodes[node].tag == BR_TAG_IMG) {
  9876. content_h = img_dh;
  9877. } else if (st->height_kind == 2 &&
  9878. doc.nodes[node].tag != BR_TAG_HTML &&
  9879. doc.nodes[node].tag != BR_TAG_BODY) {
  9880. /* A percentage of the containing block's definite height, or
  9881. * auto when it has none (it used to resolve against the
  9882. * width). The result is a minimum: without scrollable inner
  9883. * boxes, an app shell's height:100%; overflow:hidden column
  9884. * would otherwise clip everything past the first screen. */
  9885. int auto_h = l->y - (top + bt + pt);
  9886. content_h = parent_cb_h > 0 ?
  9887. parent_cb_h * (int)st->height / 100 -
  9888. (st->box_sizing ? deco_h : 0) : 0;
  9889. if (content_h < auto_h)
  9890. content_h = auto_h;
  9891. } else if (st->height_kind &&
  9892. !((doc.nodes[node].tag == BR_TAG_HTML ||
  9893. doc.nodes[node].tag == BR_TAG_BODY) &&
  9894. st->height_kind == 2)) {
  9895. content_h = style_height_px(st, cbw);
  9896. if (st->box_sizing)
  9897. content_h -= deco_h;
  9898. } else {
  9899. /* Percentage heights on html/body resolve against the
  9900. * viewport, but their content still defines the document
  9901. * scroll height. Treating them as auto avoids collapsing
  9902. * the measured page to the containing block width. */
  9903. content_h = l->y - (top + bt + pt);
  9904. /* aspect-ratio: the preferred height of an auto-height box
  9905. * (Tailwind aspect-video image frames); content can still
  9906. * make it taller, as with min-height: auto. */
  9907. if (st->aspect_w && st->aspect_h && content_w > 0) {
  9908. int ah = content_w * (int)st->aspect_h /
  9909. (int)st->aspect_w;
  9910. if (content_h < ah)
  9911. content_h = ah;
  9912. }
  9913. }
  9914. if (content_h < 0)
  9915. content_h = 0;
  9916. if (!st->height_kind && node < BR_MAX_NODES &&
  9917. content_h + deco_h < flex_stretch_h[node])
  9918. content_h = flex_stretch_h[node] - deco_h;
  9919. /* A fixed box pinned by both top and bottom with an auto height
  9920. * spans the viewport between them (Bootstrap's .modal-backdrop is
  9921. * an empty `position: fixed; top: 0; bottom: 0` box). */
  9922. if (!st->height_kind && st->pos == 2 && st->top_set &&
  9923. st->bottom_set) {
  9924. int fh = page_rect.h - st->top - st->bottom - deco_h;
  9925. if (content_h < fh)
  9926. content_h = fh;
  9927. }
  9928. if (st->max_height_kind) {
  9929. int mh = st->max_height_kind == 3 ?
  9930. cbw * st->max_height_calc_pct / 100 +
  9931. st->max_height_calc_px :
  9932. css_size(st->max_height_kind, st->max_height, cbw);
  9933. int max_box = st->box_sizing ? mh : mh + deco_h;
  9934. if (content_h + deco_h > max_box)
  9935. content_h = max_box - deco_h;
  9936. }
  9937. if (st->min_height_kind &&
  9938. !((doc.nodes[node].tag == BR_TAG_HTML ||
  9939. doc.nodes[node].tag == BR_TAG_BODY) &&
  9940. st->min_height_kind == 2)) {
  9941. int mh = st->min_height_kind == 3 ?
  9942. cbw * st->min_height_calc_pct / 100 +
  9943. st->min_height_calc_px :
  9944. css_size(st->min_height_kind, st->min_height, cbw);
  9945. int min_box = st->box_sizing ? mh : mh + deco_h;
  9946. if (content_h + deco_h < min_box)
  9947. content_h = min_box - deco_h;
  9948. }
  9949. if (content_h < 0)
  9950. content_h = 0;
  9951. box_h = deco_h + content_h;
  9952. if (box_h < 0)
  9953. box_h = 0;
  9954. l->y = (shifted ? normal_top : top) + box_h;
  9955. if (node < BR_MAX_NODES) {
  9956. layout_boxes[node].x = l0;
  9957. layout_boxes[node].y = top;
  9958. layout_boxes[node].w = r0 - l0;
  9959. layout_boxes[node].h = box_h;
  9960. layout_boxes[node].valid = r0 > l0;
  9961. }
  9962. l->left = old_left;
  9963. l->right = old_right;
  9964. l->align = old_align;
  9965. l->y += mp_px(st, 2, cbw);
  9966. if (!l->draw) {
  9967. if (box_h > 65535)
  9968. box_h = 65535;
  9969. block_h[node] = (unsigned short)box_h;
  9970. block_top[node] = (unsigned short)(top < 0 ? 0 :
  9971. top > 65535 ? 65535 : top);
  9972. }
  9973. if (positioned) {
  9974. l->y = flow_y;
  9975. l->left = flow_left;
  9976. l->right = flow_right;
  9977. }
  9978. l->parent_top = saved_parent_top;
  9979. l->cb_left = saved_cb_left;
  9980. l->cb_right = saved_cb_right;
  9981. l->cb_top = saved_cb_top;
  9982. }
  9983. static int text_node_blank(const struct br_node *nd)
  9984. {
  9985. const char *t = doc.text + nd->text_off;
  9986. unsigned int i;
  9987. for (i = 0; i < nd->text_len; i++)
  9988. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  9989. t[i] != '\r')
  9990. return 0;
  9991. return 1;
  9992. }
  9993. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  9994. * text/image widths in the subtree, plus padding and margins. This keeps
  9995. * Bootstrap's floated nav items on one line instead of giving each the whole
  9996. * row. */
  9997. static int text_space(char c)
  9998. {
  9999. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  10000. }
  10001. static int intrinsic_width(struct ngui *ui, unsigned int node,
  10002. const struct br_style *pst, int depth, int base)
  10003. {
  10004. unsigned int c;
  10005. int line_w = 0, max_w = 0;
  10006. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  10007. if (depth > 32)
  10008. return 0;
  10009. if (doc.npe_rules) {
  10010. struct br_style ps;
  10011. /* Icon boxes (::before/::after with a size) are inline
  10012. * content of the element. */
  10013. line_w += pseudo_box_w(node, pst, 1, &ps, base) +
  10014. pseudo_box_w(node, pst, 2, &ps, base);
  10015. }
  10016. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  10017. struct br_node *nd = &doc.nodes[c];
  10018. struct br_style cs;
  10019. if (nd->type == BR_NODE_TEXT) {
  10020. const char *t = doc.text + nd->text_off;
  10021. unsigned int tn = nd->text_len;
  10022. if (doc.nodes[node].tag == BR_TAG_PRE) {
  10023. line_w += (int)face_text_width(ui, pst, t, tn);
  10024. } else {
  10025. unsigned int ti = 0;
  10026. int first = 1;
  10027. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  10028. int sp = (int)face_text_width(ui, pst, " ", 1);
  10029. while (ti < tn) {
  10030. unsigned int ts;
  10031. while (ti < tn && text_space(t[ti]))
  10032. ti++;
  10033. ts = ti;
  10034. while (ti < tn && !text_space(t[ti]))
  10035. ti++;
  10036. if (ti == ts)
  10037. break;
  10038. if (!first || lead)
  10039. line_w += sp;
  10040. lead = 0;
  10041. line_w += (int)face_text_width(ui, pst,
  10042. t + ts, ti - ts);
  10043. first = 0;
  10044. }
  10045. }
  10046. continue;
  10047. }
  10048. br_style_for(&doc, c, pst, &cs);
  10049. /* Absolute/fixed children take no room in the parent's
  10050. * shrink-to-fit width: a shown Bootstrap tooltip widened the
  10051. * floated navbar list and slid the hovered item away. */
  10052. if (cs.display == BR_DISPLAY_NONE || cs.pos == 1 ||
  10053. cs.pos == 2)
  10054. continue;
  10055. if (nd->tag == BR_TAG_BR) {
  10056. if (line_w > max_w)
  10057. max_w = line_w;
  10058. line_w = 0;
  10059. continue;
  10060. }
  10061. if (nd->tag == BR_TAG_IMG) {
  10062. /* Measure the image as layout will draw it: a CSS or
  10063. * attribute height keeps the intrinsic aspect ratio, and
  10064. * a CSS width overrides the native pixel width. Bootstrap
  10065. * sizes the Cloudron logo with height:40px only. */
  10066. int idx = nd->img_index;
  10067. int iw = 0, ih = 0;
  10068. if (idx >= 0 && idx < image_count &&
  10069. images[idx].state == 1) {
  10070. iw = (int)images[idx].native_w;
  10071. ih = (int)images[idx].native_h;
  10072. if (iw <= 0 || ih <= 0) {
  10073. iw = (int)images[idx].img.w;
  10074. ih = (int)images[idx].img.h;
  10075. }
  10076. }
  10077. if (cs.width_kind) {
  10078. int ww = style_width_px(&cs, base);
  10079. line_w += ww > 0 ? ww : 64;
  10080. } else if (nd->width_attr) {
  10081. line_w += nd->width_attr;
  10082. } else if (nd->height_attr && iw && ih) {
  10083. line_w += iw * (int)nd->height_attr / ih;
  10084. } else if (cs.height_kind && iw && ih) {
  10085. /* A percentage height needs the parent's
  10086. * definite height (the logo's 2rem box), as in
  10087. * add_image_run(); otherwise it is auto. */
  10088. int hh = cs.height_kind == 1 ?
  10089. style_height_px(&cs, base) :
  10090. cs.height_kind == 2 &&
  10091. pst->height_kind == 1 ?
  10092. (int)pst->height * (int)cs.height / 100 :
  10093. 0;
  10094. line_w += hh > 0 ? iw * hh / ih : iw;
  10095. } else if (iw) {
  10096. line_w += iw;
  10097. } else {
  10098. line_w += 64;
  10099. }
  10100. continue;
  10101. }
  10102. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  10103. nd->tag == BR_TAG_TEXTAREA) &&
  10104. !s_eq(br_type(&doc, c), "hidden")) {
  10105. /* Form controls are replaced: CSS width applies even
  10106. * when they are inline (add_form_run's sizes). */
  10107. int fw = cs.width_kind ? style_width_px(&cs, base) :
  10108. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  10109. if (s_eq(br_type(&doc, c), "checkbox") ||
  10110. s_eq(br_type(&doc, c), "radio"))
  10111. fw = 16;
  10112. line_w += (fw > 0 ? fw : 120) +
  10113. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  10114. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  10115. continue;
  10116. }
  10117. if (nd->tag == BR_TAG_SVG) {
  10118. /* A replaced element: its own size, like add_svg_run()
  10119. * (its path children have no width). */
  10120. int sw, sh, sb = cs.width_kind ?
  10121. style_width_px(&cs, base) : base;
  10122. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  10123. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  10124. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  10125. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  10126. line_w += sw;
  10127. } else {
  10128. if (line_w > max_w)
  10129. max_w = line_w;
  10130. line_w = 0;
  10131. if (sw > max_w)
  10132. max_w = sw;
  10133. }
  10134. continue;
  10135. }
  10136. {
  10137. int cw = mp_px(&cs, 7, base) +
  10138. mp_px(&cs, 5, base) +
  10139. mp_px(&cs, 3, base) +
  10140. mp_px(&cs, 1, base) +
  10141. cs.border_w[1] + cs.border_w[3];
  10142. /* width/height do not apply to non-replaced inline
  10143. * boxes. The tagesschau home label is an inline span
  10144. * with width:1px for the mobile icon-only header; using
  10145. * that width made the whole subnav collapse to a
  10146. * one-character column. */
  10147. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  10148. cw += cs.width_kind == 1 ? cs.width :
  10149. style_width_px(&cs, base);
  10150. else
  10151. cw += intrinsic_width(ui, c, &cs, depth + 1,
  10152. base);
  10153. if (flex_row || cs.float_left ||
  10154. cs.display == BR_DISPLAY_INLINE ||
  10155. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  10156. line_w += cw;
  10157. } else {
  10158. if (line_w > max_w)
  10159. max_w = line_w;
  10160. line_w = 0;
  10161. if (cw > max_w)
  10162. max_w = cw;
  10163. }
  10164. }
  10165. if (line_w > 4096 || max_w > 4096)
  10166. break;
  10167. }
  10168. return line_w > max_w ? line_w : max_w;
  10169. }
  10170. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  10171. * the main user: .row > .col-md-* with float:left and a percentage width.
  10172. * Each column is laid out with its own left/right edge and the row advances
  10173. * to the tallest column. Returns the first child not consumed. */
  10174. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  10175. const struct br_style *pst, int depth,
  10176. unsigned short link)
  10177. {
  10178. unsigned int n = first;
  10179. int row_left = l->left, row_right = l->right;
  10180. int row_top, row_bottom, xl, xr, any = 0;
  10181. int fl_left = row_left, fl_right = row_right, fl_bottom;
  10182. flush_line(l);
  10183. row_top = l->y;
  10184. row_bottom = l->y;
  10185. fl_bottom = row_top;
  10186. xl = row_left;
  10187. xr = row_right;
  10188. while (n) {
  10189. struct br_node *nd = &doc.nodes[n];
  10190. struct br_style cs;
  10191. unsigned short lk = link;
  10192. int colw, right;
  10193. if (nd->type == BR_NODE_TEXT) {
  10194. if (text_node_blank(nd)) {
  10195. n = nd->next;
  10196. continue;
  10197. }
  10198. break;
  10199. }
  10200. br_style_for(&doc, n, pst, &cs);
  10201. if (cs.display == BR_DISPLAY_NONE) {
  10202. n = nd->next;
  10203. continue;
  10204. }
  10205. /* A float blockifies its box: Bootstrap floats inline
  10206. * anchors too (the navbar brand and its text links), and
  10207. * their padding must be honoured. */
  10208. /* An absolute/fixed sibling is out of flow and does not end
  10209. * the row: Bootstrap inserts its tooltip right after the
  10210. * hovered navbar <li>, and the row used to break there. */
  10211. if (!cs.float_left && (cs.pos == 1 || cs.pos == 2)) {
  10212. int sy = l->y, sl = l->left, sr = l->right;
  10213. layout_out_of_flow(l, n, &cs, depth, lk);
  10214. l->y = sy;
  10215. l->left = sl;
  10216. l->right = sr;
  10217. n = nd->next;
  10218. continue;
  10219. }
  10220. if (!cs.float_left)
  10221. break;
  10222. if (nd->tag == BR_TAG_A && nd->href_off)
  10223. lk = (unsigned short)n;
  10224. right = cs.float_left == 2;
  10225. if (cs.width_kind == 1 || cs.width_kind == 2 ||
  10226. cs.width_kind == 3) {
  10227. /* The column is the margin box: `width` is the
  10228. * content (or, with border-box, the border) box,
  10229. * and layout_block() takes margins, padding and
  10230. * borders back out of the column. A 200px float
  10231. * with margin-right:20px used to get 180px of
  10232. * content. */
  10233. int base = row_right - row_left;
  10234. colw = cs.width_kind == 1 ? (int)cs.width :
  10235. style_width_px(&cs, base);
  10236. colw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  10237. if (!cs.box_sizing)
  10238. colw += mp_px(&cs, 7, base) +
  10239. mp_px(&cs, 5, base) +
  10240. cs.border_w[1] + cs.border_w[3];
  10241. } else {
  10242. int base = row_right - row_left;
  10243. /* Shrink-to-fit outer width: borders too (Google's
  10244. * 1px-bordered "Anmelden" pill wrapped otherwise). */
  10245. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  10246. mp_px(&cs, 7, base) +
  10247. mp_px(&cs, 5, base) +
  10248. mp_px(&cs, 3, base) +
  10249. mp_px(&cs, 1, base) +
  10250. cs.border_w[1] + cs.border_w[3];
  10251. if (colw < 8)
  10252. colw = 8;
  10253. }
  10254. if (colw < 8)
  10255. colw = 8;
  10256. if (colw > row_right - row_left)
  10257. colw = row_right - row_left;
  10258. /* The float column width is already resolved. */
  10259. cs.width_kind = 0;
  10260. cs.max_width_kind = 0;
  10261. if (right) {
  10262. if (any && xr - colw < xl) {
  10263. row_top = row_bottom;
  10264. row_bottom = row_top;
  10265. xl = row_left;
  10266. xr = row_right;
  10267. }
  10268. if (xr - colw < xl)
  10269. colw = xr - xl;
  10270. if (colw < 8)
  10271. colw = 8;
  10272. l->left = xr - colw;
  10273. if (l->left < row_left)
  10274. l->left = row_left;
  10275. l->right = xr;
  10276. xr = l->left;
  10277. if (xr < fl_right)
  10278. fl_right = xr;
  10279. } else {
  10280. if (any && xl + colw > xr) {
  10281. row_top = row_bottom;
  10282. row_bottom = row_top;
  10283. xl = row_left;
  10284. xr = row_right;
  10285. }
  10286. l->left = xl;
  10287. l->right = xl + colw;
  10288. xl += colw;
  10289. if (xl > fl_left)
  10290. fl_left = xl;
  10291. }
  10292. if (l->right < l->left + 8)
  10293. l->right = l->left + 8;
  10294. l->y = row_top;
  10295. l->line_left = l->line_x = l->left;
  10296. l->run_x = l->left;
  10297. l->line_y = l->y;
  10298. l->line_h = 0;
  10299. l->nruns = 0;
  10300. l->space_pending = 0;
  10301. l->align = cs.align;
  10302. layout_block(l, n, &cs, depth + 1, lk);
  10303. if (l->y > row_bottom)
  10304. row_bottom = l->y;
  10305. if (l->y > fl_bottom)
  10306. fl_bottom = l->y;
  10307. any = 1;
  10308. n = nd->next;
  10309. }
  10310. l->left = row_left;
  10311. l->right = row_right;
  10312. if (n && any) {
  10313. struct br_node *nd = &doc.nodes[n];
  10314. int inline_next = 0;
  10315. if (nd->type == BR_NODE_TEXT) {
  10316. inline_next = 1;
  10317. } else if (nd->type == BR_NODE_ELEM) {
  10318. struct br_style cs;
  10319. br_style_for(&doc, n, pst, &cs);
  10320. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  10321. cs.display != BR_DISPLAY_NONE &&
  10322. !br_tag_is_block(nd->tag);
  10323. }
  10324. if (inline_next) {
  10325. if (l->float_active) {
  10326. if (l->float_left > fl_left)
  10327. fl_left = l->float_left;
  10328. if (l->float_right < fl_right)
  10329. fl_right = l->float_right;
  10330. if (l->float_bottom > fl_bottom)
  10331. fl_bottom = l->float_bottom;
  10332. }
  10333. l->float_active = 1;
  10334. l->float_left = fl_left;
  10335. l->float_right = fl_right;
  10336. l->float_bottom = fl_bottom;
  10337. l->y = row_top;
  10338. } else {
  10339. l->float_active = 0;
  10340. l->y = row_bottom;
  10341. }
  10342. } else {
  10343. l->float_active = 0;
  10344. l->y = row_bottom;
  10345. }
  10346. l->line_x = l->left;
  10347. l->run_x = l->left;
  10348. l->line_left = l->left;
  10349. l->line_right = l->right;
  10350. l->line_y = l->y;
  10351. l->line_h = 0;
  10352. l->nruns = 0;
  10353. l->space_pending = 0;
  10354. return n;
  10355. }
  10356. static int flex_item_width(struct lay *l, unsigned int n,
  10357. const struct br_style *cs, int avail)
  10358. {
  10359. struct br_node *nd = &doc.nodes[n];
  10360. (void)l;
  10361. int w;
  10362. if (cs->width_kind == 2 || cs->width_kind == 3)
  10363. w = style_width_px(cs, avail);
  10364. else if (cs->width_kind == 1)
  10365. w = (int)cs->width;
  10366. else if (nd->tag == BR_TAG_IMG) {
  10367. int idx = nd->img_index;
  10368. if (idx >= 0 && idx < image_count &&
  10369. images[idx].state == 1)
  10370. w = (int)images[idx].img.w;
  10371. else if (nd->width_attr)
  10372. w = (int)nd->width_attr;
  10373. else
  10374. w = 64;
  10375. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  10376. nd->tag == BR_TAG_TEXTAREA) {
  10377. /* A control has no content to measure: its default size
  10378. * (a search field in a filter bar). */
  10379. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  10380. } else {
  10381. w = intrinsic_width(l->ui, n, cs, 0, avail);
  10382. }
  10383. /* Explicit widths are content-box sizes; the flex item's outer width
  10384. * must include padding, borders and margins. */
  10385. w += mp_px(cs, 7, avail);
  10386. w += mp_px(cs, 5, avail);
  10387. w += mp_px(cs, 3, avail);
  10388. w += mp_px(cs, 1, avail);
  10389. w += cs->border_w[1] + cs->border_w[3];
  10390. if (w < 24)
  10391. w = 24;
  10392. if (w > avail)
  10393. w = avail;
  10394. return w;
  10395. }
  10396. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  10397. int depth);
  10398. /* An inline child of a text-only inline-block: the same test minus the
  10399. * display check (an inline <span> may have padding/background in CSS, but
  10400. * the inline path paints those for spans anyway). */
  10401. static int inline_block_flows_inline(unsigned int node,
  10402. const struct br_style *cs, int depth)
  10403. {
  10404. unsigned int c;
  10405. if (depth > 3 || cs->pos)
  10406. return 0;
  10407. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  10408. const struct br_node *nd = &doc.nodes[c];
  10409. struct br_style ch;
  10410. if (nd->type != BR_NODE_ELEM)
  10411. continue;
  10412. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  10413. br_tag_is_block(nd->tag))
  10414. return 0;
  10415. br_style_for(&doc, c, cs, &ch);
  10416. if (ch.display == BR_DISPLAY_NONE)
  10417. continue;
  10418. if (ch.display != BR_DISPLAY_INLINE ||
  10419. !inline_block_flows_inline(c, &ch, depth + 1))
  10420. return 0;
  10421. }
  10422. return 1;
  10423. }
  10424. /* An inline-block that is only text in a line (a <time> in a byline, a
  10425. * label) with no box of its own -- no size, background, border or padding
  10426. * -- lays out exactly like an inline element, so it stays in the text line
  10427. * instead of ending it. Boxes with any of those keep the row path. */
  10428. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  10429. int depth)
  10430. {
  10431. unsigned int c;
  10432. int i;
  10433. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  10434. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  10435. cs->pos || depth > 3)
  10436. return 0;
  10437. for (i = 0; i < 4; i++)
  10438. if (cs->border_w[i])
  10439. return 0;
  10440. for (i = 4; i < 8; i++)
  10441. if (mp_px(cs, i, 0) > 0)
  10442. return 0;
  10443. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  10444. const struct br_node *nd = &doc.nodes[c];
  10445. struct br_style ch;
  10446. if (nd->type != BR_NODE_ELEM)
  10447. continue;
  10448. if (nd->tag == BR_TAG_SVG) {
  10449. /* An icon box (Docusaurus' admonition heading:
  10450. * `<span inline-block><svg/></span>Note`): the SVG
  10451. * is an inline replaced run, so the box can stay in
  10452. * the text line. */
  10453. br_style_for(&doc, c, cs, &ch);
  10454. if (ch.display == BR_DISPLAY_NONE ||
  10455. ch.display == BR_DISPLAY_INLINE ||
  10456. ch.display == BR_DISPLAY_INLINE_BLOCK)
  10457. continue;
  10458. return 0;
  10459. }
  10460. if (nd->tag == BR_TAG_IMG || br_tag_is_block(nd->tag))
  10461. return 0;
  10462. br_style_for(&doc, c, cs, &ch);
  10463. if (ch.display == BR_DISPLAY_NONE)
  10464. continue;
  10465. if (ch.display != BR_DISPLAY_INLINE ||
  10466. !inline_block_flows_inline(c, &ch, depth + 1))
  10467. return 0;
  10468. }
  10469. return 1;
  10470. }
  10471. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  10472. * on one line, not one full-width block each. Place intrinsic widths from
  10473. * left to right and wrap when the row is full. */
  10474. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  10475. const struct br_style *pst, int depth,
  10476. unsigned short link)
  10477. {
  10478. unsigned int n = first;
  10479. int row_left = l->left, row_right = l->right;
  10480. int avail = row_right - row_left;
  10481. int x = row_left, y = l->y, row_h = 0, any = 0;
  10482. /* Each box sets l->align from its own style; the text after the row
  10483. * must keep the container's (a centred .fa-fw icon centred the menu
  10484. * label that followed it). */
  10485. unsigned char row_align = l->align;
  10486. flush_line(l);
  10487. y = l->y;
  10488. while (n) {
  10489. struct br_node *nd = &doc.nodes[n];
  10490. struct br_style cs;
  10491. unsigned short lk = link;
  10492. int colw, h;
  10493. if (nd->type == BR_NODE_TEXT) {
  10494. if (!text_node_blank(nd))
  10495. break;
  10496. if (any)
  10497. x += 4;
  10498. n = nd->next;
  10499. continue;
  10500. }
  10501. br_style_for(&doc, n, pst, &cs);
  10502. if (cs.display == BR_DISPLAY_NONE) {
  10503. n = nd->next;
  10504. continue;
  10505. }
  10506. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  10507. break;
  10508. if (nd->tag == BR_TAG_A && nd->href_off)
  10509. lk = (unsigned short)n;
  10510. colw = flex_item_width(l, n, &cs, avail);
  10511. /* A few pixels of slack keep a single long token (boot.S)
  10512. * from wrapping at the exact content width. */
  10513. colw += 8;
  10514. if (colw > avail)
  10515. colw = avail;
  10516. cs.width_kind = 0;
  10517. cs.max_width_kind = 0;
  10518. if (any && x + colw > row_right) {
  10519. y += row_h + 2;
  10520. x = row_left;
  10521. row_h = 0;
  10522. any = 0;
  10523. }
  10524. if (any && x > row_left)
  10525. x += 4;
  10526. l->left = x;
  10527. l->right = x + colw;
  10528. if (l->right < l->left + 8)
  10529. l->right = l->left + 8;
  10530. l->y = y;
  10531. l->line_left = l->line_x = l->left;
  10532. l->run_x = l->left;
  10533. l->line_y = l->y;
  10534. l->line_h = 0;
  10535. l->nruns = 0;
  10536. l->space_pending = 0;
  10537. l->align = cs.align;
  10538. layout_block(l, n, &cs, depth + 1, lk);
  10539. h = l->y - y;
  10540. if (h > row_h)
  10541. row_h = h;
  10542. x += colw;
  10543. any = 1;
  10544. n = nd->next;
  10545. }
  10546. if (any)
  10547. y += row_h;
  10548. l->left = row_left;
  10549. l->right = row_right;
  10550. l->align = row_align;
  10551. l->y = y;
  10552. l->line_left = l->line_x = l->left;
  10553. l->run_x = l->left;
  10554. l->line_y = l->y;
  10555. l->line_h = 0;
  10556. l->nruns = 0;
  10557. l->space_pending = 0;
  10558. return n;
  10559. }
  10560. struct flex_item {
  10561. unsigned int node;
  10562. unsigned short link;
  10563. int w;
  10564. };
  10565. /* An item's min-width/max-width as outer (margin-box) widths in the flex
  10566. * row, or -1 when unset. Percentages and calc() resolve against the
  10567. * container width. */
  10568. static int flex_limit_w(const struct br_style *cs, int which_max, int avail)
  10569. {
  10570. unsigned char kind = which_max ? cs->max_width_kind :
  10571. cs->min_width_kind;
  10572. int w;
  10573. if (kind == 3)
  10574. w = which_max ?
  10575. avail * cs->max_width_calc_pct / 100 +
  10576. cs->max_width_calc_px :
  10577. avail * cs->min_width_calc_pct / 100 +
  10578. cs->min_width_calc_px;
  10579. else
  10580. w = css_size(kind, which_max ? cs->max_width : cs->min_width,
  10581. avail);
  10582. if (w < 0)
  10583. return -1;
  10584. if (!cs->box_sizing)
  10585. w += mp_px(cs, 7, avail) + mp_px(cs, 5, avail) +
  10586. cs->border_w[1] + cs->border_w[3];
  10587. return w + mp_px(cs, 3, avail) + mp_px(cs, 1, avail);
  10588. }
  10589. static int flex_clamp_w(const struct br_style *cs, int w, int avail)
  10590. {
  10591. int mx = flex_limit_w(cs, 1, avail), mn = flex_limit_w(cs, 0, avail);
  10592. if (mx >= 0 && w > mx)
  10593. w = mx;
  10594. if (mn >= 0 && w < mn)
  10595. w = mn;
  10596. return w;
  10597. }
  10598. /* Does a flex row stretch this item to the line height? Only items with
  10599. * no height of their own and align-self/align-items stretch; replaced
  10600. * content (images, icons) keeps its aspect ratio. */
  10601. static int flex_item_stretches(unsigned int node, const struct br_style *cs,
  10602. const struct br_style *pst)
  10603. {
  10604. int ai = cs->align_self ? cs->align_self - 1 : pst->align_items;
  10605. unsigned char tag = doc.nodes[node].tag;
  10606. return ai == 0 && !cs->height_kind && !cs->max_height_kind &&
  10607. tag != BR_TAG_IMG && tag != BR_TAG_SVG && tag != BR_TAG_INPUT &&
  10608. tag != BR_TAG_SELECT && tag != BR_TAG_TEXTAREA &&
  10609. tag != BR_TAG_BUTTON;
  10610. }
  10611. static void flex_set_stretch(unsigned int node, const struct br_style *cs,
  10612. int line_h, int cbw)
  10613. {
  10614. int h = line_h - mp_px(cs, 0, cbw) - mp_px(cs, 2, cbw);
  10615. if (node >= BR_MAX_NODES || h <= 0)
  10616. return;
  10617. if (h > 65535)
  10618. h = 65535;
  10619. flex_stretch_h[node] = (unsigned short)h;
  10620. if (block_h[node] < h)
  10621. block_h[node] = (unsigned short)h;
  10622. }
  10623. static void layout_flex_children(struct lay *l, unsigned int parent,
  10624. const struct br_style *pst, int depth,
  10625. unsigned short link)
  10626. {
  10627. struct flex_item it[32];
  10628. unsigned int c;
  10629. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  10630. int grow_need = 0; /* growing items at their content width */
  10631. int row_left = l->left, row_right = l->right;
  10632. int avail = row_right - row_left;
  10633. int idx, row_top;
  10634. unsigned char row_align = l->align;
  10635. int box_left = l->left, box_right = l->right, row_top0 = l->y;
  10636. int bw = 0, aw = 0, first_h = -1;
  10637. int cont_h = l->cb_h; /* the container's definite content height */
  10638. struct br_style bps, aps;
  10639. if (avail < 8 || depth > 48) {
  10640. layout_children(l, parent, pst, depth, link);
  10641. return;
  10642. }
  10643. /* If direct text is not just whitespace, normal block flow handles it
  10644. * better than pretending it is a flex item. */
  10645. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10646. struct br_node *nd = &doc.nodes[c];
  10647. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  10648. layout_children(l, parent, pst, depth, link);
  10649. return;
  10650. }
  10651. }
  10652. /* ::before/::after icon boxes are the row's first and last items
  10653. * (Docusaurus' sidebar chevron): reserve their columns. */
  10654. if (doc.npe_rules) {
  10655. bw = pseudo_box_w(parent, pst, 1, &bps, avail);
  10656. aw = pseudo_box_w(parent, pst, 2, &aps, avail);
  10657. if (bw + aw > avail - 8) {
  10658. bw = 0;
  10659. aw = 0;
  10660. }
  10661. row_left += bw;
  10662. row_right -= aw;
  10663. avail = row_right - row_left;
  10664. }
  10665. for (c = doc.nodes[parent].first;
  10666. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  10667. c = doc.nodes[c].next) {
  10668. struct br_node *nd = &doc.nodes[c];
  10669. struct br_style cs;
  10670. if (nd->type == BR_NODE_TEXT)
  10671. continue;
  10672. br_style_for(&doc, c, pst, &cs);
  10673. if (cs.display == BR_DISPLAY_NONE)
  10674. continue;
  10675. if ((cs.pos == 1 || cs.pos == 2) &&
  10676. layout_out_of_flow(l, c, &cs, depth,
  10677. (nd->tag == BR_TAG_A && nd->href_off) ?
  10678. (unsigned short)c : link))
  10679. continue; /* absolutely positioned: not an item */
  10680. it[nitem].node = c;
  10681. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  10682. (unsigned short)c : link;
  10683. it[nitem].w = 0;
  10684. if (cs.flex_grow && !cs.width_kind) {
  10685. grow_count++;
  10686. grow_need += flex_item_width(l, c, &cs, avail);
  10687. } else
  10688. fixed += flex_clamp_w(&cs,
  10689. flex_item_width(l, c, &cs, avail),
  10690. avail);
  10691. nitem++;
  10692. }
  10693. /* A narrow container (an icon row sized to its content, Google's
  10694. * mic + lens buttons) is still a row when its items fit; only a
  10695. * narrow one that would overflow or squeeze growing items falls
  10696. * back to block flow. */
  10697. if (avail < 160 && fixed + grow_need > avail) {
  10698. layout_children(l, parent, pst, depth, link);
  10699. return;
  10700. }
  10701. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  10702. /* A growing item capped by max-width (Docusaurus' doc column,
  10703. * `max-width: 75%`; its main container, `calc(100% - 300px)`)
  10704. * keeps its cap and leaves the rest of the free space to the other
  10705. * growing items. */
  10706. if (grow_count) {
  10707. int pass, capped[32] = { 0 };
  10708. for (pass = 0; pass < nitem; pass++) {
  10709. int changed = 0;
  10710. for (idx = 0; idx < nitem; idx++) {
  10711. struct br_style cs;
  10712. int lim;
  10713. if (capped[idx])
  10714. continue;
  10715. br_style_for(&doc, it[idx].node, pst, &cs);
  10716. if (!cs.flex_grow || cs.width_kind)
  10717. continue;
  10718. lim = flex_clamp_w(&cs, grow_w, avail);
  10719. if (lim == grow_w)
  10720. continue;
  10721. capped[idx] = lim + 1;
  10722. fixed += lim;
  10723. grow_count--;
  10724. changed = 1;
  10725. }
  10726. if (!changed || !grow_count)
  10727. break;
  10728. grow_w = (avail - fixed) / grow_count;
  10729. }
  10730. for (idx = 0; idx < nitem; idx++)
  10731. it[idx].w = capped[idx] ? capped[idx] - 1 : 0;
  10732. }
  10733. if (grow_w < 96 && avail >= 160)
  10734. grow_w = 96;
  10735. for (idx = 0; idx < nitem; idx++) {
  10736. struct br_style cs;
  10737. if (it[idx].w)
  10738. continue; /* capped growing item */
  10739. br_style_for(&doc, it[idx].node, pst, &cs);
  10740. if (cs.flex_grow && !cs.width_kind)
  10741. it[idx].w = grow_w;
  10742. else
  10743. it[idx].w = flex_clamp_w(&cs,
  10744. flex_item_width(l,
  10745. it[idx].node,
  10746. &cs, avail),
  10747. avail);
  10748. if (it[idx].w > avail)
  10749. it[idx].w = avail;
  10750. if (it[idx].w < 8)
  10751. it[idx].w = 8;
  10752. }
  10753. row_top = l->y;
  10754. idx = 0;
  10755. while (idx < nitem) {
  10756. int start = idx, count = 0, row_w = 0;
  10757. int free_w, x, extra = 0, row_h = 0, k;
  10758. while (idx < nitem) {
  10759. int add = it[idx].w + (count ? gap : 0);
  10760. /* CSS default is nowrap; only flex-wrap: wrap (1)
  10761. * starts a new row. */
  10762. if (count && pst->flex_wrap == 1 &&
  10763. row_w + add > avail)
  10764. break;
  10765. row_w += add;
  10766. count++;
  10767. idx++;
  10768. }
  10769. if (!count) {
  10770. count = 1;
  10771. row_w = it[start].w;
  10772. idx = start + 1;
  10773. }
  10774. free_w = avail - row_w;
  10775. if (free_w < 0)
  10776. free_w = 0;
  10777. x = row_left;
  10778. if (pst->justify == 1) {
  10779. x += free_w / 2;
  10780. } else if (pst->justify == 2) {
  10781. x += free_w;
  10782. } else if (pst->justify == 3) {
  10783. extra = count > 1 ? free_w / (count - 1) : 0;
  10784. } else if (pst->justify == 4) {
  10785. extra = count ? free_w / count : 0;
  10786. x += extra / 2;
  10787. } else if (pst->justify == 5) {
  10788. extra = count ? free_w / (count + 1) : 0;
  10789. x += extra;
  10790. }
  10791. for (k = 0; k < count; k++) {
  10792. int node = (int)it[start + k].node;
  10793. int h = block_h[node];
  10794. if (h > row_h)
  10795. row_h = h;
  10796. }
  10797. /* A single line fills a definite container height (an app
  10798. * shell's `height: 100%` sidebar + content row). */
  10799. if (pst->flex_wrap != 1 && cont_h > row_h)
  10800. row_h = cont_h;
  10801. else if (pst->height_kind == 1 && (int)pst->height > row_h)
  10802. row_h = pst->height;
  10803. for (k = 0; k < count; k++) {
  10804. struct br_style cs;
  10805. int node = (int)it[start + k].node;
  10806. int yoff = 0;
  10807. br_style_for(&doc, node, pst, &cs);
  10808. cs.width_kind = 0;
  10809. cs.max_width_kind = 0;
  10810. /* align-items: stretch. With a definite line height
  10811. * the item is laid out at it, so its own children see
  10812. * a definite height; otherwise the measure pass
  10813. * stretches it once the line is known (below). */
  10814. if (!l->draw && row_h > 0 && flex_item_stretches(node,
  10815. &cs, pst))
  10816. flex_set_stretch(node, &cs, row_h, avail);
  10817. {
  10818. int ai = cs.align_self ? cs.align_self - 1 :
  10819. pst->align_items;
  10820. if (l->draw && ai && row_h > block_h[node]) {
  10821. if (ai == 1)
  10822. yoff = (row_h -
  10823. block_h[node]) / 2;
  10824. else if (ai == 2)
  10825. yoff = row_h - block_h[node];
  10826. }
  10827. }
  10828. l->left = x;
  10829. l->right = x + it[start + k].w;
  10830. if (l->right < l->left + 8)
  10831. l->right = l->left + 8;
  10832. l->y = row_top + yoff;
  10833. /* line_left too: a stale one from the previous item
  10834. * made flush_line() see a non-empty line and push
  10835. * every later item down by an empty line's height. */
  10836. l->line_left = l->line_x = l->run_x = l->left;
  10837. l->line_right = l->right;
  10838. l->line_y = l->y;
  10839. l->line_h = 0;
  10840. l->nruns = 0;
  10841. l->space_pending = 0;
  10842. l->align = cs.align;
  10843. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  10844. {
  10845. /* Both passes: a form control item has no
  10846. * block_h of its own, so the draw pass would
  10847. * otherwise end a row of only an <input> at
  10848. * height 0 and pull the content below up. */
  10849. int h = l->y - row_top;
  10850. if (h > row_h)
  10851. row_h = h;
  10852. }
  10853. x += it[start + k].w;
  10854. if (k + 1 < count)
  10855. x += gap + extra;
  10856. }
  10857. if (!l->draw) {
  10858. for (k = 0; k < count; k++) {
  10859. struct br_style cs;
  10860. int node = (int)it[start + k].node;
  10861. br_style_for(&doc, node, pst, &cs);
  10862. if (!flex_item_stretches(node, &cs, pst))
  10863. continue;
  10864. /* To the line's bottom edge from where the
  10865. * item really starts (its top margin, or a
  10866. * line box above it). */
  10867. if (layout_boxes[node].valid)
  10868. flex_set_stretch(node, &cs,
  10869. row_top + row_h -
  10870. layout_boxes[node].y +
  10871. mp_px(&cs, 0, avail), avail);
  10872. else
  10873. flex_set_stretch(node, &cs, row_h, avail);
  10874. }
  10875. }
  10876. if (first_h < 0)
  10877. first_h = row_h;
  10878. row_top += row_h;
  10879. }
  10880. if (bw || aw) {
  10881. int pass;
  10882. for (pass = 0; pass < 2; pass++) {
  10883. const struct br_style *ps = pass ? &aps : &bps;
  10884. int a = pass ? row_right : box_left;
  10885. int b = pass ? box_right : row_left;
  10886. int h = ps->height_kind ?
  10887. style_height_px(ps, box_right - box_left) : 0;
  10888. if (!(pass ? aw : bw))
  10889. continue;
  10890. l->left = l->line_left = l->line_x = l->run_x = a;
  10891. l->right = l->line_right = b;
  10892. l->y = row_top0;
  10893. if (pst->align_items == 1 && first_h > h)
  10894. l->y += (first_h - h) / 2;
  10895. l->line_y = l->y;
  10896. l->line_h = 0;
  10897. l->nruns = 0;
  10898. l->space_pending = 0;
  10899. emit_pseudo_box(l, pst, ps, link);
  10900. flush_line(l);
  10901. /* The box sits inside the first row; it only makes
  10902. * the row taller when it is taller itself. */
  10903. if (row_top0 + h > row_top)
  10904. row_top = row_top0 + h;
  10905. }
  10906. }
  10907. l->left = box_left;
  10908. l->right = box_right;
  10909. l->align = row_align;
  10910. l->y = row_top;
  10911. l->line_left = l->line_x = l->run_x = l->left;
  10912. l->line_right = l->right;
  10913. l->line_y = l->y;
  10914. l->line_h = 0;
  10915. l->nruns = 0;
  10916. l->space_pending = 0;
  10917. }
  10918. /* flex-direction: column. Items stack in order with the gap and never
  10919. * collapse margins. In the draw pass justify-content shares out the free
  10920. * height of the container's measured box (a definite or min-height, or a
  10921. * row stretch), and align-items places each item: stretch (the default)
  10922. * fills the line, start/center/end shrink an item to its content width
  10923. * (a login form's "Log in" button, a centred logo and name). */
  10924. static void layout_flex_column(struct lay *l, unsigned int parent,
  10925. const struct br_style *pst, int depth,
  10926. unsigned short link)
  10927. {
  10928. unsigned int c;
  10929. int box_left = l->left, box_right = l->right;
  10930. int avail = box_right - box_left;
  10931. int gap = pst->grid_gap, y0 = l->y;
  10932. int n = 0, k = 0, total = 0, lead = 0, extra = 0;
  10933. unsigned char row_align = l->align;
  10934. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10935. struct br_node *nd = &doc.nodes[c];
  10936. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd))
  10937. break;
  10938. }
  10939. if (c || avail < 8 || depth > 48) {
  10940. /* Loose text: block flow, with centred lines standing in
  10941. * for align-items: center. */
  10942. struct br_style cst = *pst;
  10943. if (pst->align_items == 1) {
  10944. cst.align = BR_ALIGN_CENTER;
  10945. l->align = BR_ALIGN_CENTER;
  10946. }
  10947. layout_children(l, parent, &cst, depth, link);
  10948. return;
  10949. }
  10950. emit_pseudo(l, parent, pst, 1, link);
  10951. flush_line(l);
  10952. y0 = l->y;
  10953. if (l->draw && parent < BR_MAX_NODES && block_h[parent]) {
  10954. int inner = (int)block_h[parent] - pst->border_w[0] -
  10955. pst->border_w[2] - mp_px(pst, 4, avail) -
  10956. mp_px(pst, 6, avail) - (y0 - l->parent_top -
  10957. pst->border_w[0] - mp_px(pst, 4, avail));
  10958. int free_h;
  10959. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10960. struct br_style cs;
  10961. if (doc.nodes[c].type != BR_NODE_ELEM)
  10962. continue;
  10963. br_style_for(&doc, c, pst, &cs);
  10964. if (cs.display == BR_DISPLAY_NONE || cs.pos == 1 ||
  10965. cs.pos == 2)
  10966. continue;
  10967. total += block_h[c] + mp_px(&cs, 0, avail) +
  10968. mp_px(&cs, 2, avail);
  10969. n++;
  10970. }
  10971. if (n > 1)
  10972. total += gap * (n - 1);
  10973. free_h = inner - total;
  10974. if (n && free_h > 0) {
  10975. if (pst->justify == 1) {
  10976. lead = free_h / 2;
  10977. } else if (pst->justify == 2) {
  10978. lead = free_h;
  10979. } else if (pst->justify == 3) {
  10980. extra = n > 1 ? free_h / (n - 1) : 0;
  10981. } else if (pst->justify == 4) {
  10982. extra = free_h / n;
  10983. lead = extra / 2;
  10984. } else if (pst->justify == 5) {
  10985. extra = free_h / (n + 1);
  10986. lead = extra;
  10987. }
  10988. }
  10989. }
  10990. l->y = y0 + lead;
  10991. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10992. struct br_node *nd = &doc.nodes[c];
  10993. unsigned short lk = (nd->tag == BR_TAG_A && nd->href_off) ?
  10994. (unsigned short)c : link;
  10995. struct br_style cs;
  10996. int ai, left = box_left, right = box_right;
  10997. if (nd->type != BR_NODE_ELEM)
  10998. continue;
  10999. br_style_for(&doc, c, pst, &cs);
  11000. if (cs.display == BR_DISPLAY_NONE)
  11001. continue;
  11002. if ((cs.pos == 1 || cs.pos == 2) &&
  11003. layout_out_of_flow(l, c, &cs, depth, lk))
  11004. continue;
  11005. if (k++)
  11006. l->y += gap + extra;
  11007. ai = cs.align_self ? cs.align_self - 1 : pst->align_items;
  11008. if (ai) {
  11009. int w = flex_clamp_w(&cs, flex_item_width(l, c, &cs,
  11010. avail),
  11011. avail);
  11012. if (ai == 1)
  11013. left += (avail - w) / 2;
  11014. else if (ai == 2)
  11015. left += avail - w;
  11016. right = left + w;
  11017. cs.width_kind = 0;
  11018. cs.max_width_kind = 0;
  11019. }
  11020. l->left = l->line_left = l->line_x = l->run_x = left;
  11021. l->right = l->line_right = right;
  11022. l->line_y = l->y;
  11023. l->line_h = 0;
  11024. l->nruns = 0;
  11025. l->space_pending = 0;
  11026. l->align = cs.align;
  11027. layout_block(l, c, &cs, depth + 1, lk);
  11028. }
  11029. l->left = l->line_left = l->line_x = l->run_x = box_left;
  11030. l->right = l->line_right = box_right;
  11031. l->align = row_align;
  11032. l->line_y = l->y;
  11033. l->line_h = 0;
  11034. l->nruns = 0;
  11035. l->space_pending = 0;
  11036. emit_pseudo(l, parent, pst, 2, link);
  11037. }
  11038. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  11039. * plus the grid-area hints used by site shells (site notice/footer full
  11040. * width, column-start left, page-content right). Anything more elaborate
  11041. * falls back to normal block flow. */
  11042. static int grid_track_width(unsigned char kind, unsigned short val,
  11043. int avail, int other)
  11044. {
  11045. if (kind == 2)
  11046. return avail * (int)val / 100;
  11047. if (kind == 1)
  11048. return val;
  11049. return other;
  11050. }
  11051. static void layout_grid_children(struct lay *l, unsigned int parent,
  11052. const struct br_style *pst, int depth,
  11053. unsigned short link)
  11054. {
  11055. unsigned int n;
  11056. int row_left = l->left, row_right = l->right;
  11057. int avail = row_right - row_left;
  11058. int gap = pst->grid_gap;
  11059. int track_total = avail - gap;
  11060. int col0, col1, x0, x1;
  11061. int row_y, row_bottom, have_left = 0, have_right = 0;
  11062. unsigned int c;
  11063. if (avail < 32 || depth > 48)
  11064. return;
  11065. if (track_total < 16)
  11066. track_total = 16;
  11067. col0 = grid_track_width((unsigned char)(pst->width_kind),
  11068. pst->width, track_total, 0);
  11069. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  11070. pst->max_width, track_total, 0);
  11071. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  11072. int w0 = pst->width ? pst->width : 1;
  11073. int w1 = pst->max_width ? pst->max_width : 1;
  11074. col0 = track_total * w0 / (w0 + w1);
  11075. col1 = track_total - col0;
  11076. } else if (pst->width_kind == 3) {
  11077. col0 = track_total - col1;
  11078. if (col0 < 24)
  11079. col0 = 24;
  11080. } else if (pst->max_width_kind == 3) {
  11081. col1 = track_total - col0;
  11082. if (col1 < 24)
  11083. col1 = 24;
  11084. }
  11085. if (col0 < 24)
  11086. col0 = 24;
  11087. if (col1 < 24)
  11088. col1 = 24;
  11089. if (col0 + col1 > track_total) {
  11090. col1 = track_total - col0;
  11091. if (col1 < 24)
  11092. col1 = 24;
  11093. }
  11094. x0 = row_left;
  11095. x1 = row_left + col0 + gap;
  11096. /* Direct text makes a grid ambiguous; use block flow instead. */
  11097. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  11098. struct br_node *nd = &doc.nodes[c];
  11099. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  11100. layout_children(l, parent, pst, depth, link);
  11101. return;
  11102. }
  11103. }
  11104. row_y = row_bottom = l->y;
  11105. n = doc.nodes[parent].first;
  11106. while (n) {
  11107. struct br_node *nd = &doc.nodes[n];
  11108. struct br_style cs;
  11109. unsigned short lk = link;
  11110. int slot, x, w;
  11111. if (nd->type == BR_NODE_TEXT) {
  11112. n = nd->next;
  11113. continue;
  11114. }
  11115. br_style_for(&doc, n, pst, &cs);
  11116. if (cs.display == BR_DISPLAY_NONE) {
  11117. n = nd->next;
  11118. continue;
  11119. }
  11120. if (nd->tag == BR_TAG_A && nd->href_off)
  11121. lk = (unsigned short)n;
  11122. slot = cs.grid_slot;
  11123. if (!slot) {
  11124. if (!have_left)
  11125. slot = 2;
  11126. else if (!have_right)
  11127. slot = 3;
  11128. else
  11129. slot = 2;
  11130. }
  11131. if (slot == 1) {
  11132. if (have_left || have_right) {
  11133. row_y = row_bottom;
  11134. have_left = have_right = 0;
  11135. }
  11136. x = row_left;
  11137. w = avail;
  11138. } else if (slot == 2) {
  11139. if (have_left) {
  11140. row_y = row_bottom;
  11141. have_left = have_right = 0;
  11142. }
  11143. x = x0;
  11144. w = col0;
  11145. have_left = 1;
  11146. } else {
  11147. if (have_right) {
  11148. row_y = row_bottom;
  11149. have_left = have_right = 0;
  11150. }
  11151. x = x1;
  11152. w = col1;
  11153. have_right = 1;
  11154. }
  11155. cs.width_kind = 0;
  11156. cs.max_width_kind = 0;
  11157. l->left = x;
  11158. l->right = x + w;
  11159. if (l->right < l->left + 8)
  11160. l->right = l->left + 8;
  11161. l->y = row_y;
  11162. l->line_left = l->line_x = l->left;
  11163. l->run_x = l->left;
  11164. l->line_y = l->y;
  11165. l->line_h = 0;
  11166. l->nruns = 0;
  11167. l->space_pending = 0;
  11168. l->align = cs.align;
  11169. layout_block(l, n, &cs, depth + 1, lk);
  11170. if (l->y > row_bottom)
  11171. row_bottom = l->y;
  11172. n = nd->next;
  11173. }
  11174. l->left = row_left;
  11175. l->right = row_right;
  11176. l->y = row_bottom;
  11177. l->line_left = l->line_x = l->left;
  11178. l->run_x = l->left;
  11179. l->line_y = l->y;
  11180. l->line_h = 0;
  11181. l->nruns = 0;
  11182. l->space_pending = 0;
  11183. }
  11184. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  11185. * capped at four. Used by the project docs' card grids. A fixed
  11186. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  11187. static void layout_grid_auto(struct lay *l, unsigned int parent,
  11188. const struct br_style *pst, int depth,
  11189. unsigned short link)
  11190. {
  11191. unsigned int n, c;
  11192. int row_left = l->left, row_right = l->right;
  11193. int avail = row_right - row_left;
  11194. int gap = pst->grid_gap;
  11195. int minw = pst->width_kind == 1 ? pst->width : 200;
  11196. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  11197. if (avail < 32 || depth > 48) {
  11198. layout_children(l, parent, pst, depth, link);
  11199. return;
  11200. }
  11201. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  11202. struct br_node *nd = &doc.nodes[c];
  11203. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  11204. layout_children(l, parent, pst, depth, link);
  11205. return;
  11206. }
  11207. }
  11208. if (minw < 80)
  11209. minw = 80;
  11210. ncols = (avail + gap) / (minw + gap);
  11211. if (ncols < 1)
  11212. ncols = 1;
  11213. if (ncols > 4)
  11214. ncols = 4;
  11215. if (pst->grid_auto > BR_GRID_FIXED) {
  11216. /* grid-template-columns: repeat(N, 1fr) */
  11217. ncols = pst->grid_auto - BR_GRID_FIXED;
  11218. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  11219. ncols--;
  11220. }
  11221. colw = (avail - gap * (ncols - 1)) / ncols;
  11222. if (colw < 24)
  11223. colw = 24;
  11224. x = row_left;
  11225. n = doc.nodes[parent].first;
  11226. while (n) {
  11227. struct br_node *nd = &doc.nodes[n];
  11228. struct br_style cs;
  11229. unsigned short lk = link;
  11230. int h;
  11231. if (nd->type == BR_NODE_TEXT) {
  11232. n = nd->next;
  11233. continue;
  11234. }
  11235. br_style_for(&doc, n, pst, &cs);
  11236. if (cs.display == BR_DISPLAY_NONE) {
  11237. n = nd->next;
  11238. continue;
  11239. }
  11240. if (nd->tag == BR_TAG_A && nd->href_off)
  11241. lk = (unsigned short)n;
  11242. cs.width_kind = 0;
  11243. cs.max_width_kind = 0;
  11244. l->left = x;
  11245. l->right = x + colw;
  11246. if (l->right < l->left + 8)
  11247. l->right = l->left + 8;
  11248. l->y = y;
  11249. l->line_left = l->line_x = l->left;
  11250. l->run_x = l->left;
  11251. l->line_y = l->y;
  11252. l->line_h = 0;
  11253. l->nruns = 0;
  11254. l->space_pending = 0;
  11255. l->align = cs.align;
  11256. layout_block(l, n, &cs, depth + 1, lk);
  11257. h = l->y - y;
  11258. if (h > row_h)
  11259. row_h = h;
  11260. col++;
  11261. n = nd->next;
  11262. if (col == ncols) {
  11263. y += row_h + gap;
  11264. x = row_left;
  11265. row_h = 0;
  11266. col = 0;
  11267. } else {
  11268. x += colw + gap;
  11269. }
  11270. }
  11271. if (col)
  11272. y += row_h;
  11273. else if (y > start_y)
  11274. y -= gap;
  11275. l->left = row_left;
  11276. l->right = row_right;
  11277. l->y = y;
  11278. l->line_left = l->line_x = l->left;
  11279. l->run_x = l->left;
  11280. l->line_y = l->y;
  11281. l->line_h = 0;
  11282. l->nruns = 0;
  11283. l->space_pending = 0;
  11284. }
  11285. /* Column widths are the widest cell in each column across every row, so all
  11286. * rows line up. The table model is still deliberately basic: no colspan,
  11287. * border-collapse or percentage columns. */
  11288. static void table_columns_compute(struct lay *l, unsigned int table,
  11289. const struct br_style *pst, int avail,
  11290. int *raw, int maxcols, int *out_cols,
  11291. int *out_total)
  11292. {
  11293. unsigned int r, c;
  11294. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  11295. int fixed[12];
  11296. for (c = 0; c < (unsigned int)maxcols; c++) {
  11297. raw[c] = 0;
  11298. fixed[c] = 0;
  11299. }
  11300. /* Intrinsic widths of single-column cells. */
  11301. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  11302. struct br_node *rn = &doc.nodes[r];
  11303. int col = 0;
  11304. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  11305. continue;
  11306. for (c = rn->first; c; c = doc.nodes[c].next) {
  11307. struct br_node *cn = &doc.nodes[c];
  11308. struct br_style cs;
  11309. int w, span;
  11310. if (cn->type != BR_NODE_ELEM ||
  11311. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  11312. continue;
  11313. span = cn->colspan ? cn->colspan : 1;
  11314. br_style_for(&doc, c, pst, &cs);
  11315. if (cs.display == BR_DISPLAY_NONE)
  11316. continue;
  11317. if (col + span > maxcols)
  11318. span = maxcols - col;
  11319. if (span < 1)
  11320. break;
  11321. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  11322. mp_px(&cs, 7, avail) +
  11323. mp_px(&cs, 5, avail) +
  11324. mp_px(&cs, 3, avail) +
  11325. mp_px(&cs, 1, avail) +
  11326. cs.border_w[0] + cs.border_w[1] +
  11327. cs.border_w[2] + cs.border_w[3];
  11328. if (w < 24)
  11329. w = 24;
  11330. if (span == 1) {
  11331. if (w > raw[col])
  11332. raw[col] = w;
  11333. }
  11334. if (col + span > cols)
  11335. cols = col + span;
  11336. col += span;
  11337. }
  11338. }
  11339. /* A colspan cell only has to be as wide as the sum of its columns. */
  11340. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  11341. struct br_node *rn = &doc.nodes[r];
  11342. int col = 0;
  11343. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  11344. continue;
  11345. for (c = rn->first; c; c = doc.nodes[c].next) {
  11346. struct br_node *cn = &doc.nodes[c];
  11347. struct br_style cs;
  11348. int span, w, sum, i;
  11349. if (cn->type != BR_NODE_ELEM ||
  11350. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  11351. continue;
  11352. span = cn->colspan ? cn->colspan : 1;
  11353. if (col + span > maxcols)
  11354. span = maxcols - col;
  11355. if (span < 1)
  11356. break;
  11357. if (span > 1) {
  11358. br_style_for(&doc, c, pst, &cs);
  11359. if (cs.display != BR_DISPLAY_NONE) {
  11360. w = intrinsic_width(l->ui, c, &cs,
  11361. 0, avail) +
  11362. mp_px(&cs, 7, avail) +
  11363. mp_px(&cs, 5, avail) +
  11364. mp_px(&cs, 3, avail) +
  11365. mp_px(&cs, 1, avail) +
  11366. cs.border_w[0] + cs.border_w[1] +
  11367. cs.border_w[2] + cs.border_w[3];
  11368. sum = 0;
  11369. for (i = 0; i < span; i++)
  11370. sum += raw[col + i];
  11371. if (w > sum)
  11372. raw[col + span - 1] += w - sum;
  11373. }
  11374. }
  11375. col += span;
  11376. }
  11377. }
  11378. /* Explicit and percentage widths override intrinsic widths. */
  11379. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  11380. struct br_node *rn = &doc.nodes[r];
  11381. int col = 0;
  11382. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  11383. continue;
  11384. for (c = rn->first; c; c = doc.nodes[c].next) {
  11385. struct br_node *cn = &doc.nodes[c];
  11386. struct br_style cs;
  11387. int span;
  11388. if (cn->type != BR_NODE_ELEM ||
  11389. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  11390. continue;
  11391. span = cn->colspan ? cn->colspan : 1;
  11392. if (col + span > maxcols)
  11393. span = maxcols - col;
  11394. if (span < 1)
  11395. break;
  11396. if (span == 1) {
  11397. br_style_for(&doc, c, pst, &cs);
  11398. if (cs.display != BR_DISPLAY_NONE) {
  11399. if (cs.width_kind == 1) {
  11400. raw[col] = cs.width;
  11401. fixed[col] = 1;
  11402. } else if (cs.width_kind == 2 ||
  11403. cs.width_kind == 3) {
  11404. raw[col] = style_width_px(&cs,
  11405. avail);
  11406. fixed[col] = 1;
  11407. }
  11408. }
  11409. }
  11410. col += span;
  11411. }
  11412. }
  11413. for (c = 0; c < (unsigned int)cols; c++) {
  11414. if (raw[c] < 8)
  11415. raw[c] = 8;
  11416. total += raw[c];
  11417. if (fixed[c])
  11418. fixed_sum += raw[c];
  11419. else {
  11420. free_raw += raw[c];
  11421. free_cols++;
  11422. }
  11423. }
  11424. if (fixed_sum > 0 && fixed_sum < avail) {
  11425. int free_avail = avail - fixed_sum;
  11426. int i;
  11427. if (free_raw > 0) {
  11428. for (i = 0; i < cols; i++)
  11429. if (!fixed[i])
  11430. raw[i] = free_avail * raw[i] /
  11431. free_raw;
  11432. } else if (free_cols > 0) {
  11433. for (i = 0; i < cols; i++)
  11434. if (!fixed[i])
  11435. raw[i] = free_avail / free_cols;
  11436. }
  11437. total = 0;
  11438. for (i = 0; i < cols; i++)
  11439. total += raw[i];
  11440. } else if (total < avail && total > 0) {
  11441. int i;
  11442. for (i = 0; i < cols; i++)
  11443. raw[i] = raw[i] * avail / total;
  11444. total = 0;
  11445. for (i = 0; i < cols; i++)
  11446. total += raw[i];
  11447. }
  11448. *out_cols = cols;
  11449. *out_total = total;
  11450. }
  11451. /* Every row of a fallback table asks for the same column widths, and each
  11452. * computation measures the text of every cell of every row: a Hacker News
  11453. * comment page (one row per comment) spent ~1.7 s per layout pass in this
  11454. * O(rows^2) walk. The result is cached per table, width and layout pass
  11455. * (inline_box_pass_id changes with every measure/render pass, so a DOM or
  11456. * style change is never served stale widths). */
  11457. #define TCOL_CACHE 8 /* nested tables: one slot per nesting level */
  11458. static struct {
  11459. unsigned int table, pass;
  11460. int avail, maxcols, cols, total;
  11461. int raw[12];
  11462. int valid;
  11463. } tcol_cache[TCOL_CACHE];
  11464. static unsigned int tcol_next;
  11465. static void table_columns(struct lay *l, unsigned int table,
  11466. const struct br_style *pst, int avail,
  11467. int *raw, int maxcols, int *out_cols,
  11468. int *out_total)
  11469. {
  11470. int i, k;
  11471. for (k = 0; k < TCOL_CACHE && maxcols <= 12; k++) {
  11472. if (!tcol_cache[k].valid || tcol_cache[k].table != table ||
  11473. tcol_cache[k].pass != inline_box_pass_id ||
  11474. tcol_cache[k].avail != avail ||
  11475. tcol_cache[k].maxcols != maxcols)
  11476. continue;
  11477. for (i = 0; i < maxcols; i++)
  11478. raw[i] = tcol_cache[k].raw[i];
  11479. *out_cols = tcol_cache[k].cols;
  11480. *out_total = tcol_cache[k].total;
  11481. return;
  11482. }
  11483. table_columns_compute(l, table, pst, avail, raw, maxcols, out_cols,
  11484. out_total);
  11485. if (maxcols > 12)
  11486. return;
  11487. k = (int)(tcol_next++ % TCOL_CACHE);
  11488. tcol_cache[k].table = table;
  11489. tcol_cache[k].pass = inline_box_pass_id;
  11490. tcol_cache[k].avail = avail;
  11491. tcol_cache[k].maxcols = maxcols;
  11492. tcol_cache[k].cols = *out_cols;
  11493. tcol_cache[k].total = *out_total;
  11494. for (i = 0; i < maxcols; i++)
  11495. tcol_cache[k].raw[i] = raw[i];
  11496. tcol_cache[k].valid = 1;
  11497. }
  11498. static void layout_table_row(struct lay *l, unsigned int row,
  11499. const struct br_style *pst, int depth,
  11500. unsigned short link)
  11501. {
  11502. unsigned int n, cell[12];
  11503. int raw[12], colstart[12], colspan[12];
  11504. int prefix[13];
  11505. int ncell = 0, total = 0, cols = 0, col = 0;
  11506. int row_left = l->left, row_right = l->right;
  11507. int avail = row_right - row_left;
  11508. int y = l->y, bottom = l->y;
  11509. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  11510. struct br_node *nd = &doc.nodes[n];
  11511. struct br_style cs;
  11512. int span;
  11513. if (nd->type == BR_NODE_TEXT) {
  11514. if (text_node_blank(nd))
  11515. continue;
  11516. layout_children(l, row, pst, depth, link);
  11517. return;
  11518. }
  11519. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  11520. layout_children(l, row, pst, depth, link);
  11521. return;
  11522. }
  11523. br_style_for(&doc, n, pst, &cs);
  11524. if (cs.display == BR_DISPLAY_NONE)
  11525. continue;
  11526. if (ncell >= 12) {
  11527. layout_children(l, row, pst, depth, link);
  11528. return;
  11529. }
  11530. span = nd->colspan ? nd->colspan : 1;
  11531. if (span > 12 - col)
  11532. span = 12 - col;
  11533. if (span < 1)
  11534. continue;
  11535. cell[ncell] = n;
  11536. colstart[ncell] = col;
  11537. colspan[ncell] = span;
  11538. col += span;
  11539. ncell++;
  11540. }
  11541. if (ncell < 1 || avail < 32) {
  11542. layout_children(l, row, pst, depth, link);
  11543. return;
  11544. }
  11545. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  11546. &total);
  11547. if (cols < 2 || total <= 0) {
  11548. int c;
  11549. total = 0;
  11550. for (c = 0; c < ncell; c++) {
  11551. struct br_style cs;
  11552. br_style_for(&doc, cell[c], pst, &cs);
  11553. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  11554. avail) +
  11555. mp_px(&cs, 7, avail) +
  11556. mp_px(&cs, 5, avail) +
  11557. mp_px(&cs, 3, avail) +
  11558. mp_px(&cs, 1, avail);
  11559. if (raw[c] < 24)
  11560. raw[c] = 24;
  11561. total += raw[c];
  11562. }
  11563. /* A one-column table still has to fill its own width; the
  11564. * intrinsic fallback above otherwise leaves the cell at its
  11565. * text width (HN's outer table and nested story table). */
  11566. if (total > 0 && total < avail) {
  11567. int c;
  11568. for (c = 0; c < ncell; c++)
  11569. raw[c] = raw[c] * avail / total;
  11570. total = avail;
  11571. }
  11572. }
  11573. prefix[0] = row_left;
  11574. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  11575. prefix[n + 1] = prefix[n] + raw[n];
  11576. for (n = 0; n < (unsigned int)ncell; n++) {
  11577. struct br_style cs;
  11578. int start = colstart[n];
  11579. int end = start + colspan[n];
  11580. int w;
  11581. if (end > cols)
  11582. end = cols;
  11583. if (start >= cols)
  11584. continue;
  11585. w = prefix[end] - prefix[start];
  11586. br_style_for(&doc, cell[n], pst, &cs);
  11587. /* The column width already reflects the cell's width property. */
  11588. cs.width_kind = 0;
  11589. cs.max_width_kind = 0;
  11590. if (w < 24)
  11591. w = 24;
  11592. if (w < 8)
  11593. w = 8;
  11594. l->left = prefix[start];
  11595. l->right = l->left + w;
  11596. l->y = y;
  11597. l->line_left = l->line_x = l->left;
  11598. l->run_x = l->left;
  11599. l->line_y = l->y;
  11600. l->line_h = 0;
  11601. l->nruns = 0;
  11602. l->space_pending = 0;
  11603. l->align = cs.align;
  11604. layout_block(l, cell[n], &cs, depth + 1, link);
  11605. if (l->y > bottom)
  11606. bottom = l->y;
  11607. }
  11608. l->left = row_left;
  11609. l->right = row_right;
  11610. l->y = bottom;
  11611. l->line_left = l->line_x = l->left;
  11612. l->run_x = l->left;
  11613. l->line_y = l->y;
  11614. l->line_h = 0;
  11615. l->nruns = 0;
  11616. l->space_pending = 0;
  11617. }
  11618. #define TBL_MAX_ROWS 32
  11619. #define TBL_MAX_COLS 12
  11620. #define TBL_MAX_CELLS 128
  11621. struct tbl_cell {
  11622. unsigned int node;
  11623. unsigned char row, col, rowspan, colspan;
  11624. int height;
  11625. };
  11626. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  11627. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  11628. static int table_active;
  11629. static int table_has_rowspan(unsigned int table)
  11630. {
  11631. unsigned int r, c;
  11632. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  11633. struct br_node *rn = &doc.nodes[r];
  11634. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  11635. continue;
  11636. for (c = rn->first; c; c = doc.nodes[c].next) {
  11637. struct br_node *cn = &doc.nodes[c];
  11638. if (cn->type == BR_NODE_ELEM &&
  11639. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  11640. cn->rowspan > 1)
  11641. return 1;
  11642. }
  11643. }
  11644. return 0;
  11645. }
  11646. static void table_cell_style(unsigned int row, unsigned int cell,
  11647. const struct br_style *st, struct br_style *out)
  11648. {
  11649. struct br_style trs;
  11650. br_style_for(&doc, row, st, &trs);
  11651. br_style_for(&doc, cell, &trs, out);
  11652. }
  11653. /* Tables that use rowspan need row heights before anything is painted. This
  11654. * path builds a small occupancy grid, measures the natural cell heights, then
  11655. * lays every cell out at its row/column position. Tables without rowspan
  11656. * keep the lighter per-row path in layout_table_row(). */
  11657. static void layout_table(struct lay *l, unsigned int table,
  11658. const struct br_style *st, int depth,
  11659. unsigned short link)
  11660. {
  11661. unsigned int rows[TBL_MAX_ROWS];
  11662. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  11663. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  11664. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  11665. int free_raw = 0, free_cols = 0;
  11666. int table_left = l->left, table_right = l->right;
  11667. int top = l->y, avail = table_right - table_left;
  11668. unsigned int r, c;
  11669. int i, rr, cc;
  11670. if (depth > 48 || table_active) {
  11671. layout_children(l, table, st, depth, link);
  11672. return;
  11673. }
  11674. table_active = 1;
  11675. for (r = doc.nodes[table].first;
  11676. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  11677. struct br_node *rn = &doc.nodes[r];
  11678. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  11679. rows[nrows++] = r;
  11680. }
  11681. if (!nrows) {
  11682. table_active = 0;
  11683. layout_children(l, table, st, depth, link);
  11684. return;
  11685. }
  11686. for (rr = 0; rr < nrows; rr++)
  11687. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  11688. tbl_at[rr][cc] = 0;
  11689. for (rr = 0; rr < nrows; rr++) {
  11690. int col = 0;
  11691. for (c = doc.nodes[rows[rr]].first; c;
  11692. c = doc.nodes[c].next) {
  11693. struct br_node *cn = &doc.nodes[c];
  11694. struct br_style cs;
  11695. int rs, csn;
  11696. if (cn->type != BR_NODE_ELEM ||
  11697. (cn->tag != BR_TAG_TD &&
  11698. cn->tag != BR_TAG_TH))
  11699. continue;
  11700. table_cell_style(rows[rr], c, st, &cs);
  11701. if (cs.display == BR_DISPLAY_NONE)
  11702. continue;
  11703. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  11704. col++;
  11705. if (col >= TBL_MAX_COLS)
  11706. break;
  11707. rs = cn->rowspan ? cn->rowspan : 1;
  11708. csn = cn->colspan ? cn->colspan : 1;
  11709. if (rr + rs > nrows)
  11710. rs = nrows - rr;
  11711. if (col + csn > TBL_MAX_COLS)
  11712. csn = TBL_MAX_COLS - col;
  11713. if (rs < 1 || csn < 1)
  11714. continue;
  11715. if (ncells >= TBL_MAX_CELLS)
  11716. break;
  11717. tbl_cells[ncells].node = c;
  11718. tbl_cells[ncells].row = (unsigned char)rr;
  11719. tbl_cells[ncells].col = (unsigned char)col;
  11720. tbl_cells[ncells].rowspan = (unsigned char)rs;
  11721. tbl_cells[ncells].colspan = (unsigned char)csn;
  11722. tbl_cells[ncells].height = 0;
  11723. for (i = rr; i < rr + rs; i++)
  11724. for (int j = col; j < col + csn; j++)
  11725. tbl_at[i][j] =
  11726. (unsigned short)(ncells + 1);
  11727. ncells++;
  11728. col += csn;
  11729. if (col > cols)
  11730. cols = col;
  11731. }
  11732. }
  11733. if (!ncells || cols < 1) {
  11734. table_active = 0;
  11735. layout_children(l, table, st, depth, link);
  11736. return;
  11737. }
  11738. for (i = 0; i < cols; i++) {
  11739. raw[i] = 0;
  11740. fixed[i] = 0;
  11741. }
  11742. /* Intrinsic widths of single-column cells. */
  11743. for (i = 0; i < ncells; i++) {
  11744. struct br_style cs;
  11745. int w;
  11746. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  11747. st, &cs);
  11748. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  11749. mp_px(&cs, 7, avail) +
  11750. mp_px(&cs, 5, avail) +
  11751. mp_px(&cs, 3, avail) +
  11752. mp_px(&cs, 1, avail) +
  11753. cs.border_w[0] + cs.border_w[1] +
  11754. cs.border_w[2] + cs.border_w[3];
  11755. if (w < 24)
  11756. w = 24;
  11757. if (tbl_cells[i].colspan == 1) {
  11758. int col = tbl_cells[i].col;
  11759. if (w > raw[col])
  11760. raw[col] = w;
  11761. }
  11762. }
  11763. /* A spanning cell only needs the sum of its columns to be large
  11764. * enough; put the deficit in the last column. */
  11765. for (i = 0; i < ncells; i++) {
  11766. struct br_style cs;
  11767. int w, sum, col, span;
  11768. if (tbl_cells[i].colspan < 2)
  11769. continue;
  11770. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  11771. st, &cs);
  11772. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  11773. mp_px(&cs, 7, avail) +
  11774. mp_px(&cs, 5, avail) +
  11775. mp_px(&cs, 3, avail) +
  11776. mp_px(&cs, 1, avail) +
  11777. cs.border_w[0] + cs.border_w[1] +
  11778. cs.border_w[2] + cs.border_w[3];
  11779. col = tbl_cells[i].col;
  11780. span = tbl_cells[i].colspan;
  11781. sum = 0;
  11782. for (int j = 0; j < span; j++)
  11783. sum += raw[col + j];
  11784. if (w > sum)
  11785. raw[col + span - 1] += w - sum;
  11786. }
  11787. /* Explicit/percentage widths, as in table_columns(). */
  11788. for (i = 0; i < ncells; i++) {
  11789. struct br_style cs;
  11790. int col;
  11791. if (tbl_cells[i].colspan != 1)
  11792. continue;
  11793. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  11794. st, &cs);
  11795. col = tbl_cells[i].col;
  11796. if (cs.width_kind == 1) {
  11797. raw[col] = cs.width;
  11798. fixed[col] = 1;
  11799. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  11800. raw[col] = style_width_px(&cs, avail);
  11801. fixed[col] = 1;
  11802. }
  11803. }
  11804. for (i = 0; i < cols; i++) {
  11805. if (raw[i] < 8)
  11806. raw[i] = 8;
  11807. total += raw[i];
  11808. if (fixed[i])
  11809. fixed_sum += raw[i];
  11810. else {
  11811. free_raw += raw[i];
  11812. free_cols++;
  11813. }
  11814. }
  11815. if (fixed_sum > 0 && fixed_sum < avail) {
  11816. int free_avail = avail - fixed_sum;
  11817. if (free_raw > 0) {
  11818. for (i = 0; i < cols; i++)
  11819. if (!fixed[i])
  11820. raw[i] = free_avail * raw[i] /
  11821. free_raw;
  11822. } else if (free_cols > 0) {
  11823. for (i = 0; i < cols; i++)
  11824. if (!fixed[i])
  11825. raw[i] = free_avail / free_cols;
  11826. }
  11827. } else if (total < avail && total > 0) {
  11828. for (i = 0; i < cols; i++)
  11829. raw[i] = raw[i] * avail / total;
  11830. }
  11831. prefix[0] = table_left;
  11832. for (i = 0; i < cols; i++)
  11833. prefix[i + 1] = prefix[i] + raw[i];
  11834. /* Measure natural cell heights with the column widths. */
  11835. for (i = 0; i < ncells; i++) {
  11836. struct br_style cs;
  11837. int col = tbl_cells[i].col;
  11838. int span = tbl_cells[i].colspan;
  11839. int w = prefix[col + span] - prefix[col];
  11840. int sl = l->left, sr = l->right, sy = l->y;
  11841. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  11842. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  11843. int sal = l->align, sdraw = l->draw;
  11844. struct ngui *sui = l->ui;
  11845. if (w < 8)
  11846. w = 8;
  11847. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  11848. st, &cs);
  11849. cs.width_kind = 0;
  11850. cs.max_width_kind = 0;
  11851. l->draw = 0;
  11852. l->ui = 0;
  11853. l->left = prefix[col];
  11854. l->right = l->left + w;
  11855. l->y = 0;
  11856. l->line_left = l->line_x = l->left;
  11857. l->run_x = l->left;
  11858. l->line_y = 0;
  11859. l->line_h = 0;
  11860. l->nruns = 0;
  11861. l->space_pending = 0;
  11862. l->align = cs.align;
  11863. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  11864. tbl_cells[i].height = block_h[tbl_cells[i].node];
  11865. l->left = sl;
  11866. l->right = sr;
  11867. l->y = sy;
  11868. l->line_x = slx;
  11869. l->run_x = srx;
  11870. l->line_y = sly;
  11871. l->line_h = slh;
  11872. l->nruns = snr;
  11873. l->space_pending = ssp;
  11874. l->align = sal;
  11875. l->draw = sdraw;
  11876. l->ui = sui;
  11877. }
  11878. for (i = 0; i < nrows; i++)
  11879. rowh[i] = 0;
  11880. for (i = 0; i < ncells; i++) {
  11881. int row = tbl_cells[i].row;
  11882. if (tbl_cells[i].rowspan == 1) {
  11883. if (tbl_cells[i].height > rowh[row])
  11884. rowh[row] = tbl_cells[i].height;
  11885. }
  11886. }
  11887. for (i = 0; i < ncells; i++) {
  11888. int row = tbl_cells[i].row;
  11889. int span = tbl_cells[i].rowspan;
  11890. int sum = 0;
  11891. if (span < 2)
  11892. continue;
  11893. for (int j = 0; j < span; j++)
  11894. sum += rowh[row + j];
  11895. if (sum < tbl_cells[i].height)
  11896. rowh[row + span - 1] +=
  11897. tbl_cells[i].height - sum;
  11898. }
  11899. for (i = 0; i < nrows; i++)
  11900. if (rowh[i] < 8)
  11901. rowh[i] = 8;
  11902. rowy[0] = top;
  11903. for (i = 1; i < nrows; i++)
  11904. rowy[i] = rowy[i - 1] + rowh[i - 1];
  11905. if (!l->draw) {
  11906. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  11907. table_active = 0;
  11908. return;
  11909. }
  11910. for (i = 0; i < ncells; i++) {
  11911. struct br_style cs;
  11912. int col = tbl_cells[i].col;
  11913. int span = tbl_cells[i].colspan;
  11914. int row = tbl_cells[i].row;
  11915. int rspan = tbl_cells[i].rowspan;
  11916. int w = prefix[col + span] - prefix[col];
  11917. int h = 0;
  11918. int sl = l->left, sr = l->right, sy = l->y;
  11919. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  11920. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  11921. int sal = l->align;
  11922. int deco;
  11923. for (int j = 0; j < rspan; j++)
  11924. h += rowh[row + j];
  11925. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  11926. cs.width_kind = 0;
  11927. cs.max_width_kind = 0;
  11928. cs.box_sizing = 0;
  11929. deco = mp_px(&cs, 4, avail) +
  11930. mp_px(&cs, 6, avail) +
  11931. cs.border_w[0] + cs.border_w[2];
  11932. cs.height_kind = 1;
  11933. cs.height = h > deco ? h - deco : 0;
  11934. /* The block painter reads block_h[] from the measure pass; make
  11935. * the table cell fill its row/rowspan, not just its content. */
  11936. if (h > 0 && h < 65536)
  11937. block_h[tbl_cells[i].node] = (unsigned short)h;
  11938. l->left = prefix[col];
  11939. l->right = l->left + w;
  11940. l->y = rowy[row];
  11941. l->line_left = l->line_x = l->left;
  11942. l->run_x = l->left;
  11943. l->line_y = l->y;
  11944. l->line_h = 0;
  11945. l->nruns = 0;
  11946. l->space_pending = 0;
  11947. l->align = cs.align;
  11948. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  11949. l->left = sl;
  11950. l->right = sr;
  11951. l->y = sy;
  11952. l->line_x = slx;
  11953. l->run_x = srx;
  11954. l->line_y = sly;
  11955. l->line_h = slh;
  11956. l->nruns = snr;
  11957. l->space_pending = ssp;
  11958. l->align = sal;
  11959. }
  11960. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  11961. table_active = 0;
  11962. }
  11963. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  11964. * flow so they sit above it, like CSS painting order. Their flow origin is
  11965. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  11966. struct br_deferred {
  11967. unsigned int node;
  11968. int flow_y, flow_left, flow_right;
  11969. int parent_top; /* the parent box top, for sticky clamping */
  11970. unsigned short link;
  11971. signed short z_index;
  11972. unsigned char z_set;
  11973. unsigned int order;
  11974. };
  11975. /* Positioned boxes painted after the flow. News front pages have one or two
  11976. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  11977. * old 16 entries the rest fell back into the flow, so a hero image landed
  11978. * below its padding-top aspect box instead of on top of it. */
  11979. #define BR_MAX_DEFERRED 256
  11980. static struct br_deferred deferred[BR_MAX_DEFERRED];
  11981. static int ndeferred;
  11982. /* Outer width of an element's empty ::before (pe 1) / ::after (pe 2) icon
  11983. * box, 0 when it has none; *ps receives the pseudo-element's style. */
  11984. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  11985. struct br_style *ps, int base)
  11986. {
  11987. char buf[8];
  11988. int w, h;
  11989. if (!doc.npe_rules ||
  11990. br_pseudo(&doc, node, pe, st, ps, buf, sizeof(buf)) ||
  11991. ps->content != BR_CONTENT_EMPTY || ps->display == BR_DISPLAY_NONE)
  11992. return 0;
  11993. w = ps->width_kind ? style_width_px(ps, base) : 0;
  11994. h = ps->height_kind ? style_height_px(ps, base) : 0;
  11995. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  11996. w = (int)ps->min_width;
  11997. if (w <= 0)
  11998. w = h;
  11999. if (w <= 0 || w > 512)
  12000. return 0;
  12001. return w + (ps->ml_auto ? 0 : mp_px(ps, 3, base)) + mp_px(ps, 1, base);
  12002. }
  12003. /* An empty ::before/::after with a size and a background: one run the
  12004. * size of the box. Only data: background images are drawn (decoded at
  12005. * the background-size); `margin-left: auto` inside a flex parent pushes
  12006. * the box to the line's right edge like the flex row would. */
  12007. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  12008. const struct br_style *ps, unsigned short link)
  12009. {
  12010. struct lay_run *r;
  12011. int lw = l->line_right - l->line_left, w, h, ml, mr, tw, th;
  12012. const char *url = ps->bg_image ? br_bg_image_url(ps->bg_image - 1) : "";
  12013. if (lw < 8)
  12014. lw = 8;
  12015. w = ps->width_kind ? style_width_px(ps, lw) : 0;
  12016. h = ps->height_kind ? style_height_px(ps, lw) : 0;
  12017. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  12018. w = (int)ps->min_width;
  12019. if (w <= 0)
  12020. w = h;
  12021. if (h <= 0)
  12022. h = w;
  12023. if (w <= 0 || w > 512 || h > 512)
  12024. return;
  12025. ml = ps->ml_auto ? 0 : mp_px(ps, 3, lw);
  12026. mr = mp_px(ps, 1, lw);
  12027. if (ml < 0)
  12028. ml = 0;
  12029. if (mr < 0)
  12030. mr = 0;
  12031. if (l->line_x + ml + w > l->line_right &&
  12032. (l->nruns > 0 || l->line_x > l->line_left))
  12033. flush_line(l);
  12034. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  12035. flush_line(l);
  12036. if (l->nruns == 0) {
  12037. l->line_y = l->y;
  12038. l->line_h = 0;
  12039. start_line(l, ps);
  12040. }
  12041. if (ps->ml_auto && parent->display == BR_DISPLAY_FLEX &&
  12042. l->line_right - w - mr > l->line_x)
  12043. l->line_x = l->line_right - w - mr;
  12044. else
  12045. l->line_x += ml;
  12046. r = &l->runs[l->nruns++];
  12047. memset(r, 0, sizeof(*r));
  12048. r->box = l->box_owner;
  12049. r->gap = (unsigned short)(l->line_x > l->run_x ?
  12050. l->line_x - l->run_x : 0);
  12051. r->img = RUN_PBOX;
  12052. r->href = link;
  12053. r->iw = (unsigned short)w;
  12054. r->ih = (unsigned short)h;
  12055. r->w = (unsigned short)w;
  12056. r->font_px = ps->font_px;
  12057. r->pb_has_bg = ps->has_bg;
  12058. r->pb_bg = ps->bg;
  12059. r->pb_img = -1;
  12060. if (ps->transform_set) {
  12061. r->transform_scale = 1;
  12062. r->scale_x = ps->scale_x;
  12063. r->scale_y = ps->scale_y;
  12064. r->rotate_x100 = ps->rotate_x100;
  12065. }
  12066. /* Background size and position, as draw_bg_image() resolves them. */
  12067. tw = w;
  12068. th = h;
  12069. if (ps->bg_size_kind == 1 || ps->bg_size_kind == 2) {
  12070. int bw = ps->bg_size_w, bh = ps->bg_size_h;
  12071. if (ps->bg_size_kind == 2) {
  12072. bw = bw ? w * bw / 100 : 0;
  12073. bh = bh ? h * bh / 100 : 0;
  12074. }
  12075. tw = bw ? bw : (bh ? bh : w);
  12076. th = bh ? bh : tw;
  12077. }
  12078. if (tw > 0 && th > 0 && tw <= 512 && th <= 512 && url[0])
  12079. r->pb_img = (short)data_url_image(url, tw, th);
  12080. r->pb_w = (short)tw;
  12081. r->pb_h = (short)th;
  12082. r->pb_x = (short)(ps->bg_pos_x_kind == 1 ?
  12083. (w - tw) * ps->bg_pos_x / 100 : ps->bg_pos_x);
  12084. r->pb_y = (short)(ps->bg_pos_y_kind == 1 ?
  12085. (h - th) * ps->bg_pos_y / 100 : ps->bg_pos_y);
  12086. l->line_x += w + mr;
  12087. l->run_x = l->line_x;
  12088. if (l->line_h < h)
  12089. l->line_h = h;
  12090. }
  12091. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  12092. * element's line. A block-level pseudo-element gets its own line; its box
  12093. * (margins, padding, background) is not drawn. */
  12094. static void emit_pseudo(struct lay *l, unsigned int node,
  12095. const struct br_style *st, int pe, unsigned short link)
  12096. {
  12097. char buf[160];
  12098. struct br_style ps;
  12099. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  12100. unsigned int i = 0;
  12101. int block, space_w;
  12102. if (!n && ps.content == BR_CONTENT_EMPTY &&
  12103. ps.display != BR_DISPLAY_NONE) {
  12104. emit_pseudo_box(l, st, &ps, link);
  12105. return;
  12106. }
  12107. if (!n)
  12108. return;
  12109. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  12110. if (block)
  12111. flush_line(l);
  12112. if (ps.uppercase)
  12113. for (i = 0; i < n; i++)
  12114. if (buf[i] >= 'a' && buf[i] <= 'z')
  12115. buf[i] = (char)(buf[i] - 'a' + 'A');
  12116. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  12117. if (space_w <= 0)
  12118. space_w = 8;
  12119. i = 0;
  12120. while (i < n) {
  12121. char word[28];
  12122. unsigned int k = 0;
  12123. int w;
  12124. if (buf[i] == ' ') {
  12125. l->space_pending = 1;
  12126. i++;
  12127. continue;
  12128. }
  12129. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  12130. word[k++] = buf[i++];
  12131. word[k] = '\0';
  12132. if (l->space_pending &&
  12133. (l->nruns > 0 || l->line_x > l->line_left) &&
  12134. l->line_x + space_w <= l->line_right)
  12135. l->line_x += space_w;
  12136. l->space_pending = 0;
  12137. w = (int)face_text_width(l->ui, &ps, word, k);
  12138. if (l->line_x + w > l->line_right &&
  12139. (l->nruns > 0 || l->line_x > l->line_left))
  12140. flush_line(l);
  12141. add_run(l, 0, 0, &ps, link, word);
  12142. }
  12143. if (block)
  12144. flush_line(l);
  12145. }
  12146. /* An out-of-flow child (absolute/fixed, or a relative/sticky box with a
  12147. * z-index): measured in place, painted from the deferred stacked pass
  12148. * against its containing block. Shared by block and flex layout, so an
  12149. * absolute icon inside a flex row (a password field's reveal button) is
  12150. * not laid out as one of the row's items. Returns 1 when it handled n. */
  12151. static int layout_out_of_flow(struct lay *l, unsigned int n,
  12152. const struct br_style *cs, int depth,
  12153. unsigned short lk)
  12154. {
  12155. if (!(cs->pos == 1 || cs->pos == 2 ||
  12156. ((cs->pos == 3 || cs->pos == 4) && cs->z_set)))
  12157. return 0;
  12158. if ((cs->pos == 3 || cs->pos == 4) && l->draw &&
  12159. ndeferred < BR_MAX_DEFERRED) {
  12160. /* Relative or sticky z-index (a sticky site
  12161. * header): measure and advance the flow without
  12162. * painting, then paint it in the deferred
  12163. * (stacked) pass, above the content after it. */
  12164. int fy = l->y, fl = l->left, fr = l->right;
  12165. int save_draw = l->draw;
  12166. l->draw = 0;
  12167. layout_block(l, n, cs, depth + 1, lk);
  12168. l->draw = save_draw;
  12169. deferred[ndeferred].node = n;
  12170. deferred[ndeferred].parent_top = l->parent_top;
  12171. deferred[ndeferred].flow_y = fy;
  12172. deferred[ndeferred].flow_left = fl;
  12173. deferred[ndeferred].flow_right = fr;
  12174. deferred[ndeferred].link = lk;
  12175. deferred[ndeferred].z_index = cs->z_index;
  12176. deferred[ndeferred].z_set = cs->z_set;
  12177. deferred[ndeferred].order = (unsigned int)ndeferred;
  12178. ndeferred++;
  12179. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  12180. deferred[ndeferred].node = n;
  12181. deferred[ndeferred].parent_top = l->parent_top;
  12182. deferred[ndeferred].flow_y =
  12183. cs->pos == 1 ? l->cb_top : l->y;
  12184. deferred[ndeferred].flow_left =
  12185. cs->pos == 1 ? l->cb_left : l->left;
  12186. deferred[ndeferred].flow_right =
  12187. cs->pos == 1 ? l->cb_right : l->right;
  12188. deferred[ndeferred].link = lk;
  12189. deferred[ndeferred].z_index = cs->z_index;
  12190. deferred[ndeferred].z_set = cs->z_set;
  12191. deferred[ndeferred].order = (unsigned int)ndeferred;
  12192. ndeferred++;
  12193. } else if (l->draw && cs->pos == 1) {
  12194. /* Deferred list full: paint in place, but still
  12195. * against the containing block, not the flow. */
  12196. int fy = l->y, fl = l->left, fr = l->right;
  12197. l->y = l->cb_top;
  12198. l->left = l->cb_left;
  12199. l->right = l->cb_right;
  12200. layout_block(l, n, cs, depth + 1, lk);
  12201. l->y = fy;
  12202. l->left = fl;
  12203. l->right = fr;
  12204. } else {
  12205. layout_block(l, n, cs, depth + 1, lk);
  12206. }
  12207. if (cs->pos == 1 && block_h[n] &&
  12208. doc.nodes[n].class_off) {
  12209. const char *cl = doc.attrs +
  12210. doc.nodes[n].class_off;
  12211. if ((contains_ci(cl, "poster-wrapper") ||
  12212. contains_ci(cl, "ts-picture")) &&
  12213. !has_skeleton_sibling(n))
  12214. l->y += block_h[n];
  12215. }
  12216. return 1;
  12217. }
  12218. /* An element laid out in the text line (an inline span, or an inline-block
  12219. * that flows like one): its runs are tagged with it, so flush_line() can
  12220. * record its box for getBoundingClientRect() and click targeting. */
  12221. static void layout_inline_box(struct lay *l, unsigned int node,
  12222. const struct br_style *cs, int depth,
  12223. unsigned short link)
  12224. {
  12225. unsigned short saved = l->box_owner;
  12226. if (node < BR_MAX_NODES) {
  12227. inline_box_parent[node] = saved;
  12228. l->box_owner = (unsigned short)(node + 1);
  12229. }
  12230. layout_children(l, node, cs, depth + 1, link);
  12231. l->box_owner = saved;
  12232. }
  12233. static void layout_children(struct lay *l, unsigned int parent,
  12234. const struct br_style *pst, int depth,
  12235. unsigned short link)
  12236. {
  12237. unsigned int n;
  12238. if (depth > 48)
  12239. return;
  12240. emit_pseudo(l, parent, pst, 1, link);
  12241. n = doc.nodes[parent].first;
  12242. while (n) {
  12243. struct br_node *nd = &doc.nodes[n];
  12244. struct br_style cs;
  12245. unsigned short lk = link;
  12246. if (nd->type == BR_NODE_TEXT) {
  12247. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  12248. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  12249. n = nd->next;
  12250. continue;
  12251. }
  12252. br_style_for(&doc, n, pst, &cs);
  12253. if (cs.display == BR_DISPLAY_NONE) {
  12254. n = nd->next;
  12255. continue;
  12256. }
  12257. if (cs.clear && l->float_active) {
  12258. flush_line(l);
  12259. if (l->y < l->float_bottom)
  12260. l->y = l->float_bottom;
  12261. l->float_active = 0;
  12262. l->line_x = l->left;
  12263. l->run_x = l->left;
  12264. l->line_left = l->left;
  12265. l->line_right = l->right;
  12266. l->line_y = l->y;
  12267. l->line_h = 0;
  12268. l->nruns = 0;
  12269. l->space_pending = 0;
  12270. }
  12271. if (nd->tag == BR_TAG_A && nd->href_off)
  12272. lk = (unsigned short)n;
  12273. if (layout_out_of_flow(l, n, &cs, depth, lk)) {
  12274. n = nd->next;
  12275. continue;
  12276. }
  12277. if (nd->tag == BR_TAG_BR) {
  12278. flush_line(l);
  12279. n = nd->next;
  12280. continue;
  12281. }
  12282. if (nd->tag == BR_TAG_HR) {
  12283. flush_line(l);
  12284. if (l->draw)
  12285. ngui_fill_rect(l->ui,
  12286. (struct ngui_rect){l->left, l->y + 2,
  12287. l->right - l->left, 1}, BR_GRAY);
  12288. l->y += 8;
  12289. n = nd->next;
  12290. continue;
  12291. }
  12292. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  12293. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  12294. !button_has_elements(n)) {
  12295. if (!(nd->tag == BR_TAG_INPUT &&
  12296. s_eq(br_type(&doc, n), "hidden"))) {
  12297. form_fill_line = pst->display ==
  12298. BR_DISPLAY_FLEX &&
  12299. pst->flex_col;
  12300. add_form_run(l, n, &cs, lk);
  12301. form_fill_line = 0;
  12302. }
  12303. n = nd->next;
  12304. continue;
  12305. }
  12306. if (nd->tag == BR_TAG_IMG) {
  12307. add_image_run(l, n, &cs, lk);
  12308. n = nd->next;
  12309. continue;
  12310. }
  12311. if (nd->tag == BR_TAG_SVG &&
  12312. (cs.display == BR_DISPLAY_INLINE ||
  12313. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  12314. !cs.float_left) {
  12315. add_svg_run(l, n, &cs, lk);
  12316. n = nd->next;
  12317. continue;
  12318. }
  12319. if (nd->tag == BR_TAG_VIDEO) {
  12320. layout_block(l, n, &cs, depth + 1, lk);
  12321. n = nd->next;
  12322. continue;
  12323. }
  12324. if (cs.float_left) {
  12325. n = layout_float_group(l, n, pst, depth, lk);
  12326. continue;
  12327. }
  12328. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  12329. inline_block_flows(n, &cs, 0)) {
  12330. layout_inline_box(l, n, &cs, depth, lk);
  12331. n = nd->next;
  12332. continue;
  12333. }
  12334. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  12335. n = layout_inline_blocks(l, n, pst, depth, link);
  12336. continue;
  12337. }
  12338. /* A flex container is block-level like any block box even when
  12339. * the element is an inline tag such as <a> (a link card with
  12340. * display:flex is common on news sites). Without the block box
  12341. * its children were laid out in the parent flow with a 0x0 box
  12342. * of their own. */
  12343. /* inline-flex around inline content only ("| mehr" link
  12344. * tails, icon+label pills) stays in the text line. */
  12345. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  12346. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  12347. !flex_wants_row(n, &cs)) {
  12348. layout_children(l, n, &cs, depth + 1, lk);
  12349. } else if (cs.display == BR_DISPLAY_BLOCK ||
  12350. cs.display == BR_DISPLAY_FLEX ||
  12351. br_tag_is_block(nd->tag))
  12352. layout_block(l, n, &cs, depth + 1, lk);
  12353. else if (cs.display == BR_DISPLAY_INLINE &&
  12354. nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH)
  12355. layout_inline_box(l, n, &cs, depth, lk);
  12356. else {
  12357. layout_children(l, n, &cs, depth + 1, lk);
  12358. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  12359. l->space_pending = 1;
  12360. }
  12361. n = nd->next;
  12362. }
  12363. emit_pseudo(l, parent, pst, 2, link);
  12364. }
  12365. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  12366. * runs and a recursive page can otherwise overflow the stack. */
  12367. static struct lay layout_state;
  12368. static int measure_page(int left, int right)
  12369. {
  12370. struct lay *l = &layout_state;
  12371. struct br_style base = base_style();
  12372. unsigned int i;
  12373. for (i = 0; i < BR_MAX_NODES; i++) {
  12374. block_h[i] = 0;
  12375. flex_stretch_h[i] = 0;
  12376. img_top[i] = 0;
  12377. block_top[i] = 0;
  12378. img_h[i] = 0;
  12379. layout_boxes[i].valid = 0;
  12380. }
  12381. memset(li_marker, 0, sizeof(li_marker));
  12382. inline_box_pass_id++;
  12383. l->box_owner = 0;
  12384. l->draw = 0;
  12385. l->ui = &ui;
  12386. l->left = left;
  12387. l->right = right;
  12388. l->y = 0;
  12389. l->line_x = left;
  12390. l->run_x = left;
  12391. l->line_left = left;
  12392. l->line_right = right;
  12393. l->line_y = 0;
  12394. l->line_h = 0;
  12395. l->align = BR_ALIGN_LEFT;
  12396. l->cb_h = layout_view_h;
  12397. l->float_active = 0;
  12398. l->parent_top = 0;
  12399. l->cb_left = left;
  12400. l->cb_right = right;
  12401. l->cb_top = 0;
  12402. l->depth = 0;
  12403. l->nruns = 0;
  12404. l->space_pending = 0;
  12405. base = root_style();
  12406. layout_children(l, doc.root, &base, 0, 0);
  12407. return l->y + 8;
  12408. }
  12409. static int deferred_cmp(const struct br_deferred *a,
  12410. const struct br_deferred *b)
  12411. {
  12412. int az = a->z_set ? a->z_index : 0;
  12413. int bz = b->z_set ? b->z_index : 0;
  12414. if (az != bz)
  12415. return az < bz ? -1 : 1;
  12416. if (a->order != b->order)
  12417. return a->order < b->order ? -1 : 1;
  12418. return 0;
  12419. }
  12420. static void sort_deferred(void)
  12421. {
  12422. int i;
  12423. for (i = 1; i < ndeferred; i++) {
  12424. struct br_deferred key = deferred[i];
  12425. int j = i;
  12426. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  12427. deferred[j] = deferred[j - 1];
  12428. j--;
  12429. }
  12430. deferred[j] = key;
  12431. }
  12432. }
  12433. static void hit_add_occluder(unsigned int node, int at)
  12434. {
  12435. const struct br_layout_box *b;
  12436. struct hit h;
  12437. int x0, y0, x1, y1;
  12438. if (node >= BR_MAX_NODES || nhits >= HIT_MAX || at > nhits)
  12439. return;
  12440. b = &layout_boxes[node];
  12441. if (!b->valid)
  12442. return;
  12443. x0 = b->x > page_rect.x ? b->x : page_rect.x;
  12444. y0 = b->y > page_rect.y ? b->y : page_rect.y;
  12445. x1 = b->x + b->w;
  12446. y1 = b->y + b->h;
  12447. if (x1 > page_rect.x + page_rect.w - 12)
  12448. x1 = page_rect.x + page_rect.w - 12;
  12449. if (y1 > page_rect.y + page_rect.h)
  12450. y1 = page_rect.y + page_rect.h;
  12451. if (x1 <= x0 || y1 <= y0)
  12452. return;
  12453. h.x = x0;
  12454. h.y = y0;
  12455. h.w = x1 - x0;
  12456. h.h = y1 - y0;
  12457. h.node = (unsigned short)node;
  12458. h.occl = 1;
  12459. memmove(&hits[at + 1], &hits[at],
  12460. (unsigned int)(nhits - at) * sizeof(hits[0]));
  12461. hits[at] = h;
  12462. nhits++;
  12463. }
  12464. static void render_page(int left, int right, int y0)
  12465. {
  12466. struct lay *l = &layout_state;
  12467. struct br_style base = base_style();
  12468. inline_box_pass_id++;
  12469. l->box_owner = 0;
  12470. l->draw = 1;
  12471. l->ui = &ui;
  12472. l->left = left;
  12473. l->right = right;
  12474. l->y = y0;
  12475. l->line_x = left;
  12476. l->run_x = left;
  12477. l->line_left = left;
  12478. l->line_right = right;
  12479. l->line_y = y0;
  12480. l->line_h = 0;
  12481. l->align = BR_ALIGN_LEFT;
  12482. l->cb_h = layout_view_h;
  12483. l->float_active = 0;
  12484. l->parent_top = 0;
  12485. l->cb_left = left;
  12486. l->cb_right = right;
  12487. l->cb_top = y0;
  12488. l->depth = 0;
  12489. l->nruns = 0;
  12490. l->space_pending = 0;
  12491. nhits = 0;
  12492. ndeferred = 0;
  12493. render_pass = 1;
  12494. render_seq++;
  12495. base = root_style();
  12496. layout_children(l, doc.root, &base, 0, 0);
  12497. sort_deferred();
  12498. {
  12499. int i;
  12500. for (i = 0; i < ndeferred; i++) {
  12501. struct br_style st;
  12502. int hide, op, blend, hit0;
  12503. br_style_for(&doc, deferred[i].node, &base, &st);
  12504. if (st.display == BR_DISPLAY_NONE)
  12505. continue;
  12506. /* A transparent or visibility:hidden positioned box
  12507. * still gets its boxes (scripts measure it) but no
  12508. * paint and no hit rectangles. A translucent one
  12509. * (a 50% modal backdrop, a fading tooltip) is
  12510. * blended over what is under it; the opacity may be
  12511. * mid-transition. */
  12512. hit0 = nhits;
  12513. op = anim_value(deferred[i].node, ANIM_OP, st.opacity,
  12514. &st);
  12515. hide = op == 0 || st.vis_hidden;
  12516. blend = !hide && op < 255 && alpha_begin(page_rect);
  12517. l->draw = !hide;
  12518. l->left = deferred[i].flow_left;
  12519. l->right = deferred[i].flow_right;
  12520. l->y = deferred[i].flow_y;
  12521. l->parent_top = deferred[i].parent_top;
  12522. l->line_left = l->line_x = l->left;
  12523. l->run_x = l->left;
  12524. l->line_y = l->y;
  12525. l->line_h = 0;
  12526. l->nruns = 0;
  12527. l->space_pending = 0;
  12528. l->align = st.align;
  12529. if (st.pos == 2 && block_h[deferred[i].node]) {
  12530. struct ngui_rect clip;
  12531. int ch = block_h[deferred[i].node] + 24;
  12532. int pr = page_rect.x + page_rect.w - 12;
  12533. int x0 = page_rect.x, x1 = pr;
  12534. int y0 = page_rect.y;
  12535. /* A box placed by `bottom` (a page footer) is
  12536. * clipped and filled where layout_block puts
  12537. * it, against the bottom edge. */
  12538. if (st.bottom_set && !st.top_set) {
  12539. ch = block_h[deferred[i].node] +
  12540. mp_px(&st, 0, pr - page_rect.x) +
  12541. mp_px(&st, 2, pr - page_rect.x);
  12542. y0 = page_rect.y + page_rect.h -
  12543. st.bottom - ch;
  12544. }
  12545. /* The background pre-fill spans the box's own
  12546. * columns, not the whole page: Docusaurus parks
  12547. * a white "Skip to main content" link at
  12548. * `left: 100%` with a z-index above the navbar,
  12549. * and a full-width fill painted over the bar. */
  12550. if (st.left_set)
  12551. x0 = page_rect.x + st.left;
  12552. else if (!st.right_set)
  12553. x0 = deferred[i].flow_left;
  12554. if (st.width_kind == 1) {
  12555. if (st.right_set && !st.left_set)
  12556. x0 = pr - st.right - st.width;
  12557. x1 = x0 + st.width;
  12558. } else if (st.right_set) {
  12559. x1 = pr - st.right;
  12560. }
  12561. if (x0 >= pr || x1 <= page_rect.x)
  12562. continue; /* entirely off-screen */
  12563. if (x0 < page_rect.x)
  12564. x0 = page_rect.x;
  12565. if (x1 > pr)
  12566. x1 = pr;
  12567. if (y0 < page_rect.y) {
  12568. ch -= page_rect.y - y0;
  12569. y0 = page_rect.y;
  12570. }
  12571. clip.x = x0;
  12572. clip.y = y0;
  12573. clip.w = x1 - x0;
  12574. if (ch > page_rect.h)
  12575. ch = page_rect.h;
  12576. if (ch <= 0)
  12577. continue;
  12578. clip.h = ch;
  12579. ngui_push_clip(&ui, clip);
  12580. if (st.has_bg && !hide)
  12581. ngui_fill_rect(&ui, clip, st.bg);
  12582. layout_block(l, deferred[i].node, &st, 0,
  12583. deferred[i].link);
  12584. ngui_pop_clip(&ui);
  12585. } else {
  12586. layout_block(l, deferred[i].node, &st, 0,
  12587. deferred[i].link);
  12588. }
  12589. if (!hide && !st.pe_none &&
  12590. (st.pos == 1 || st.pos == 2) &&
  12591. (st.has_bg || st.bg_image || st.z_set))
  12592. hit_add_occluder(deferred[i].node, hit0);
  12593. if (blend) {
  12594. const struct br_layout_box *b =
  12595. &layout_boxes[deferred[i].node];
  12596. struct ngui_rect box = page_rect;
  12597. /* The box itself; descendants may overflow
  12598. * it, so a full-page box is the safe case. */
  12599. if (deferred[i].node < BR_MAX_NODES &&
  12600. b->valid) {
  12601. box.x = b->x;
  12602. box.y = b->y;
  12603. box.w = b->w;
  12604. box.h = b->h;
  12605. }
  12606. alpha_end(page_rect, box, op);
  12607. }
  12608. }
  12609. }
  12610. render_pass = 0;
  12611. }
  12612. /* ---- UI ---- */
  12613. /* The link/control under a point, topmost first. An occluder above it
  12614. * returns 0 and its node in *occl (when given), so the caller can target
  12615. * the covering box instead of content painted underneath. */
  12616. static int find_hit_ex(int x, int y, int *occl)
  12617. {
  12618. int i;
  12619. if (occl)
  12620. *occl = -1;
  12621. for (i = nhits - 1; i >= 0; i--) {
  12622. struct hit *h = &hits[i];
  12623. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  12624. y < h->y + h->h) {
  12625. if (h->occl) {
  12626. if (occl)
  12627. *occl = (int)h->node;
  12628. return 0;
  12629. }
  12630. return (int)h->node;
  12631. }
  12632. }
  12633. return 0;
  12634. }
  12635. static int find_hit(int x, int y)
  12636. {
  12637. return find_hit_ex(x, y, 0);
  12638. }
  12639. /* ---- URL-bar autocomplete ----
  12640. *
  12641. * While the address bar has the focus a dropdown lists up to SUG_MAX
  12642. * history entries. An empty bar (a fresh focus, Ctrl+L) shows the most
  12643. * visited/recent sites; typing ranks prefix matches of the URL (with or
  12644. * without the scheme and "www.") above substring matches of the URL, then
  12645. * of the title, and adds visit count and recency. Typing at the end of the
  12646. * text also completes inline to the next '/' of the best prefix match
  12647. * ("clo" -> "cloudron.io/"), with the added part selected so the next
  12648. * keystroke replaces it; Enter on that text opens the history URL it came
  12649. * from (scheme included). Up/Down preview a row in the bar, Delete on a
  12650. * highlighted row forgets it, Esc closes the list (a second Esc leaves the
  12651. * bar), and a click on a row opens it. */
  12652. #define SUG_MAX 6
  12653. #define SUG_ROW_H 36
  12654. static int sug_idx[SUG_MAX];
  12655. static int sug_n, sug_sel = -1, sug_open;
  12656. static char sug_typed[NGUI_INPUT_MAX]; /* what the user typed */
  12657. static char sug_restore[NGUI_INPUT_MAX]; /* bar text before a preview */
  12658. static char ac_text[NGUI_INPUT_MAX]; /* bar text of the inline completion */
  12659. static char ac_url[HIST_URL_MAX]; /* the history URL it stands for */
  12660. static struct ngui_rect url_rect, sug_rect;
  12661. static int url_had_focus;
  12662. static char lc(char c)
  12663. {
  12664. return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
  12665. }
  12666. static int prefix_ci(const char *s, const char *p) /* p is lower case */
  12667. {
  12668. for (; *p; s++, p++)
  12669. if (lc(*s) != *p)
  12670. return 0;
  12671. return 1;
  12672. }
  12673. static unsigned int url_scheme_len(const char *url)
  12674. {
  12675. if (starts_with(url, "https://"))
  12676. return 8;
  12677. if (starts_with(url, "http://"))
  12678. return 7;
  12679. return 0;
  12680. }
  12681. /* Offset in `url` where the lower-case text `t` matches as a prefix: the
  12682. * whole URL, the URL without its scheme, or without scheme and "www.". */
  12683. static int hist_prefix_at(const char *url, const char *t)
  12684. {
  12685. unsigned int s = url_scheme_len(url);
  12686. if (prefix_ci(url, t))
  12687. return 0;
  12688. if (s && prefix_ci(url + s, t))
  12689. return (int)s;
  12690. if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
  12691. return (int)s + 4;
  12692. return -1;
  12693. }
  12694. static int hist_score(const struct hist_ent *e, const char *t,
  12695. unsigned int next)
  12696. {
  12697. unsigned int age = next - e->stamp;
  12698. int sc, at;
  12699. if (!t[0]) {
  12700. sc = 0;
  12701. } else if ((at = hist_prefix_at(e->url, t)) >= 0) {
  12702. /* Shorter rests first: "cloudron.io/" before its subpages. */
  12703. int rest = (int)s_len(e->url + at);
  12704. sc = 4000 - (rest > 400 ? 400 : rest);
  12705. } else if (contains_ci(e->url, t)) {
  12706. sc = 1000;
  12707. } else if (contains_ci(e->title, t)) {
  12708. sc = 600;
  12709. } else {
  12710. return -1;
  12711. }
  12712. sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
  12713. sc += age >= 500 ? 0 : (int)(500 - age);
  12714. return sc;
  12715. }
  12716. static void sug_lower(char *t, unsigned int cap)
  12717. {
  12718. unsigned int k;
  12719. for (k = 0; sug_typed[k] && k + 1 < cap; k++)
  12720. t[k] = lc(sug_typed[k]);
  12721. t[k] = '\0';
  12722. }
  12723. static void sug_refresh(void)
  12724. {
  12725. char t[NGUI_INPUT_MAX];
  12726. int sc[SUG_MAX], i, j;
  12727. unsigned int next = hist_next_stamp();
  12728. sug_lower(t, sizeof(t));
  12729. sug_n = 0;
  12730. for (i = 0; i < hist_n; i++) {
  12731. int s = hist_score(&hist_tab[i], t, next);
  12732. if (s < 0)
  12733. continue;
  12734. j = sug_n;
  12735. if (j == SUG_MAX) {
  12736. if (sc[SUG_MAX - 1] >= s)
  12737. continue;
  12738. j = SUG_MAX - 1;
  12739. }
  12740. while (j > 0 && sc[j - 1] < s) {
  12741. sc[j] = sc[j - 1];
  12742. sug_idx[j] = sug_idx[j - 1];
  12743. j--;
  12744. }
  12745. sc[j] = s;
  12746. sug_idx[j] = i;
  12747. if (sug_n < SUG_MAX)
  12748. sug_n++;
  12749. }
  12750. if (sug_sel >= sug_n)
  12751. sug_sel = -1;
  12752. }
  12753. /* Complete the typed text inline to the next '/' of the best prefix match. */
  12754. static void sug_inline(void)
  12755. {
  12756. char t[NGUI_INPUT_MAX];
  12757. const char *url, *rest;
  12758. unsigned int L, start, end, hs, tn, n = 0;
  12759. unsigned int next = hist_next_stamp();
  12760. int i, best = -1, best_sc = -1, at = 0;
  12761. sug_lower(t, sizeof(t));
  12762. L = s_len(t);
  12763. if (!L)
  12764. return;
  12765. for (i = 0; i < hist_n; i++) {
  12766. int a = hist_prefix_at(hist_tab[i].url, t), s;
  12767. if (a < 0)
  12768. continue;
  12769. s = hist_score(&hist_tab[i], t, next);
  12770. if (s > best_sc) {
  12771. best_sc = s;
  12772. best = i;
  12773. at = a;
  12774. }
  12775. }
  12776. if (best < 0)
  12777. return;
  12778. url = hist_tab[best].url;
  12779. rest = url + at;
  12780. /* Typing the scheme ("htt") completes past "https://", not to it. */
  12781. hs = at == 0 ? url_scheme_len(url) : 0;
  12782. start = L > hs ? L : hs;
  12783. end = start;
  12784. while (rest[end] && rest[end] != '/')
  12785. end++;
  12786. if (rest[end] == '/')
  12787. end++;
  12788. tn = s_len(sug_typed);
  12789. if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
  12790. return;
  12791. s_append(ac_text, &n, sug_typed, sizeof(ac_text));
  12792. for (; L < end && n + 1 < sizeof(ac_text); L++)
  12793. ac_text[n++] = rest[L];
  12794. ac_text[n] = '\0';
  12795. s_copy(ac_url, url, (unsigned int)at + end + 1);
  12796. ngui_input_set(&url_in, ac_text);
  12797. url_in.anchor = tn; /* select the completed part */
  12798. }
  12799. static void sug_close(void)
  12800. {
  12801. sug_open = 0;
  12802. sug_sel = -1;
  12803. ac_text[0] = '\0';
  12804. }
  12805. static int sug_visible(void)
  12806. {
  12807. return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
  12808. }
  12809. /* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
  12810. * start page) lists the top sites until something is typed. */
  12811. static int sug_focus_check(void)
  12812. {
  12813. int focused = ngui_focus(&ui) == ID_URL;
  12814. if (focused && !url_had_focus) {
  12815. sug_typed[0] = '\0';
  12816. sug_close();
  12817. sug_open = 1;
  12818. sug_refresh();
  12819. }
  12820. url_had_focus = focused;
  12821. return focused;
  12822. }
  12823. static void url_submit(unsigned int *action)
  12824. {
  12825. if (ac_text[0] && s_eq(url_in.text, ac_text))
  12826. s_copy(click_url, ac_url, sizeof(click_url));
  12827. *action |= ACT_NAV;
  12828. sug_close();
  12829. }
  12830. /* The bar text changed through typing or editing. */
  12831. static void sug_changed(void)
  12832. {
  12833. unsigned int pl = s_len(sug_typed);
  12834. int grew = url_in.len > pl && url_in.cursor == url_in.len &&
  12835. !memcmp(url_in.text, sug_typed, pl);
  12836. s_copy(sug_typed, url_in.text, sizeof(sug_typed));
  12837. ac_text[0] = '\0';
  12838. sug_sel = -1;
  12839. sug_open = 1;
  12840. sug_refresh();
  12841. if (grew)
  12842. sug_inline();
  12843. }
  12844. /* Keys for the list, taken off the queue before the text field sees them.
  12845. * Only a leading run is handled; the rest goes to the field. */
  12846. static void sug_keys(void)
  12847. {
  12848. int k;
  12849. while ((k = ngui_key_peek(&ui)) != 0) {
  12850. if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
  12851. ngui_key(&ui);
  12852. if (!sug_open) {
  12853. sug_open = 1;
  12854. continue;
  12855. }
  12856. if (sug_sel < 0)
  12857. s_copy(sug_restore, url_in.text,
  12858. sizeof(sug_restore));
  12859. if (k == NGUI_KEY_DOWN)
  12860. sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
  12861. else
  12862. sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
  12863. ngui_input_set(&url_in, sug_sel >= 0 ?
  12864. hist_tab[sug_idx[sug_sel]].url :
  12865. sug_restore);
  12866. } else if (k == NGUI_KEY_ESC && sug_visible()) {
  12867. ngui_key(&ui);
  12868. if (sug_sel >= 0)
  12869. ngui_input_set(&url_in, sug_restore);
  12870. else if (ac_text[0] && s_eq(url_in.text, ac_text))
  12871. ngui_input_set(&url_in, sug_typed);
  12872. sug_close();
  12873. } else if (k == NGUI_KEY_DELETE && sug_visible() &&
  12874. sug_sel >= 0) {
  12875. ngui_key(&ui);
  12876. hist_forget(sug_idx[sug_sel]);
  12877. ngui_input_set(&url_in, sug_restore);
  12878. sug_sel = -1;
  12879. sug_refresh();
  12880. } else {
  12881. break;
  12882. }
  12883. }
  12884. }
  12885. /* A press on a row of last frame's list opens it; any press on the list is
  12886. * swallowed so the page underneath does not see it. */
  12887. static void sug_click(unsigned int *action)
  12888. {
  12889. int row;
  12890. if (!(ui.pressed & 1) || !sug_rect.w ||
  12891. !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
  12892. return;
  12893. row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
  12894. if (row >= 0 && row < sug_n) {
  12895. s_copy(click_url, hist_tab[sug_idx[row]].url,
  12896. sizeof(click_url));
  12897. *action |= ACT_NAV;
  12898. sug_close();
  12899. }
  12900. ui.pressed = 0;
  12901. }
  12902. static void draw_suggest(struct ngui_rect page)
  12903. {
  12904. struct ngui_rect r;
  12905. int i, rows = sug_n, hover = -1;
  12906. r.x = url_rect.x;
  12907. r.y = url_rect.y + url_rect.h + 1;
  12908. r.w = url_rect.w < 320 ? 320 : url_rect.w;
  12909. if (r.x + r.w > ui.w - 2)
  12910. r.w = ui.w - 2 - r.x;
  12911. while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
  12912. rows--;
  12913. if (rows <= 0 || r.w < 60) {
  12914. sug_rect.w = 0;
  12915. return;
  12916. }
  12917. r.h = rows * SUG_ROW_H + 2;
  12918. sug_rect = r;
  12919. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  12920. hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
  12921. ngui_set_cursor(&ui, CURSOR_POINTER);
  12922. }
  12923. ngui_fill_rect(&ui, r, ui.theme.border);
  12924. for (i = 0; i < rows; i++) {
  12925. const struct hist_ent *e = &hist_tab[sug_idx[i]];
  12926. struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
  12927. r.w - 2, SUG_ROW_H};
  12928. struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
  12929. unsigned short bg = i == sug_sel ? ui.theme.selection :
  12930. i == hover ? ui.theme.panel_alt :
  12931. ui.theme.panel;
  12932. ngui_fill_rect(&ui, rr, bg);
  12933. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
  12934. e->title[0] ? e->title : e->url,
  12935. ui.theme.text);
  12936. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
  12937. i == sug_sel ? ui.theme.text :
  12938. ui.theme.text_dim);
  12939. }
  12940. }
  12941. static void ctx_close(void);
  12942. static void ctx_open_from_right(struct ngui_rect page);
  12943. static void ctx_press(struct ngui_rect page);
  12944. static void draw_context(void);
  12945. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  12946. {
  12947. int x = r.x + 4, y = r.y + 4, h = 22;
  12948. int compact = r.w < 560;
  12949. int go_w = r.w < 420 ? 32 : 42;
  12950. int in_x, in_w, res;
  12951. ngui_fill_rect(&ui, r, ui.theme.panel);
  12952. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  12953. ui.theme.border);
  12954. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  12955. NGUI_ICON_CHEVRON_LEFT))
  12956. *action |= ACT_BACK;
  12957. x += 32;
  12958. if (!compact) {
  12959. if (ngui_icon_button(&ui, ID_FORWARD,
  12960. (struct ngui_rect){x, y, 28, h},
  12961. NGUI_ICON_CHEVRON_RIGHT))
  12962. *action |= ACT_FORWARD;
  12963. x += 32;
  12964. }
  12965. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  12966. NGUI_ICON_REFRESH))
  12967. *action |= ACT_RELOAD;
  12968. x += 32;
  12969. if (!compact) {
  12970. if (ngui_icon_button(&ui, ID_HOME,
  12971. (struct ngui_rect){x, y, 28, h},
  12972. NGUI_ICON_HOME))
  12973. *action |= ACT_HOME;
  12974. x += 32;
  12975. }
  12976. dl_button_rect = (struct ngui_rect){x, y, 28, h};
  12977. if (ngui_icon_button(&ui, ID_DOWNLOADS, dl_button_rect,
  12978. NGUI_ICON_DOWNLOAD)) {
  12979. dl_panel_open = !dl_panel_open;
  12980. if (dl_panel_open) {
  12981. dl_unseen = 0;
  12982. ctx_close();
  12983. sug_close();
  12984. ngui_set_focus(&ui, 0);
  12985. }
  12986. ngui_invalidate(&ui);
  12987. }
  12988. if (dl_active >= 0) {
  12989. int p = dl_percent();
  12990. if (p < 0)
  12991. p = 0;
  12992. ngui_fill_rect(&ui, (struct ngui_rect){
  12993. dl_button_rect.x + 3,
  12994. dl_button_rect.y + dl_button_rect.h - 4,
  12995. dl_button_rect.w - 6, 2}, ui.theme.border);
  12996. if (p > 0)
  12997. ngui_fill_rect(&ui, (struct ngui_rect){
  12998. dl_button_rect.x + 3,
  12999. dl_button_rect.y + dl_button_rect.h - 4,
  13000. (dl_button_rect.w - 6) * p / 100, 2},
  13001. ui.theme.accent);
  13002. }
  13003. if (dl_unseen && !dl_panel_open)
  13004. ngui_fill_rect(&ui, (struct ngui_rect){
  13005. dl_button_rect.x + dl_button_rect.w - 6,
  13006. dl_button_rect.y + 2, 4, 4}, ui.theme.accent);
  13007. x += 32;
  13008. in_x = x + 2;
  13009. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  13010. if (in_w < 60)
  13011. in_w = 60;
  13012. url_rect = (struct ngui_rect){in_x, y, in_w, h};
  13013. if (sug_focus_check())
  13014. sug_keys();
  13015. res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
  13016. sug_focus_check(); /* a click into the bar focuses it here */
  13017. if (res & NGUI_INPUT_CHANGED)
  13018. sug_changed();
  13019. if (res & NGUI_INPUT_SUBMIT)
  13020. url_submit(action);
  13021. if (res & NGUI_INPUT_CANCEL)
  13022. ngui_set_focus(&ui, 0);
  13023. if (ngui_button(&ui, ID_GO,
  13024. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  13025. "Go"))
  13026. url_submit(action);
  13027. if (!sug_focus_check())
  13028. sug_close();
  13029. }
  13030. static int page_hover_node(void)
  13031. {
  13032. if (!ui.inside || ctx_open || dl_panel_open)
  13033. return 0;
  13034. if (ui.mouse_x < page_rect.x ||
  13035. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  13036. ui.mouse_y < page_rect.y ||
  13037. ui.mouse_y >= page_rect.y + page_rect.h)
  13038. return 0;
  13039. return find_hit(ui.mouse_x, ui.mouse_y);
  13040. }
  13041. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  13042. {
  13043. int x, y, w = page.w, h = page.h;
  13044. if (!src || w <= 0 || h <= 0)
  13045. return;
  13046. for (y = 0; y < h; y++) {
  13047. unsigned short *s = src + (page.y + y) * sw + page.x;
  13048. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  13049. for (x = 0; x + 1 < w; x += 2) {
  13050. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  13051. }
  13052. if (x < w)
  13053. d[x] = s[x];
  13054. }
  13055. }
  13056. static void draw_page(struct ngui_rect page)
  13057. {
  13058. int left, right, ch;
  13059. int old_panel, old_dim;
  13060. unsigned short *saved_px;
  13061. unsigned short page_bg = ui.theme.bg;
  13062. int saved_w, saved_h, use_buf;
  13063. unsigned int t0 = u_ticks_ms();
  13064. page_rect = page;
  13065. {
  13066. unsigned int root = doc.nnode > 1 ?
  13067. br_find_tag(&doc, BR_TAG_HTML) : 0;
  13068. unsigned int body = doc.nnode > 1 ?
  13069. br_find_tag(&doc, BR_TAG_BODY) : 0;
  13070. struct br_style bs;
  13071. int bg_found = 0;
  13072. if (root) {
  13073. style_for_node(root - 1, &bs);
  13074. if (bs.has_bg) {
  13075. page_bg = bs.bg;
  13076. bg_found = 1;
  13077. }
  13078. }
  13079. if (body) {
  13080. style_for_node(body - 1, &bs);
  13081. if (bs.has_bg) {
  13082. page_bg = bs.bg;
  13083. bg_found = 1;
  13084. }
  13085. }
  13086. /* No canvas colour, but the author made the text dark
  13087. * (Infima's light theme: `--ifm-background-color:
  13088. * transparent` on html, #1c1e21 text): the page expects the
  13089. * white canvas of a normal browser, and dark text on the
  13090. * dark default canvas is unreadable. Mid-grey counts too:
  13091. * Hacker News sets #828282 body text on a white page;
  13092. * text meant for a dark background is light (> ~200). */
  13093. if (!bg_found && (body || root) && bs.color != ui.theme.text) {
  13094. unsigned int c = bs.color;
  13095. unsigned int lum = ((c >> 11) & 31) * 8 * 299 +
  13096. ((c >> 5) & 63) * 4 * 587 +
  13097. (c & 31) * 8 * 114;
  13098. if (lum < 150 * 1000)
  13099. page_bg = 0xFFFF;
  13100. }
  13101. }
  13102. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  13103. page_cache_valid && layout_valid &&
  13104. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  13105. !(ui.scroll_y &&
  13106. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  13107. page_scroll.offset == page_cache_scroll &&
  13108. page_cache_nnode == doc.nnode &&
  13109. page_cache_x == page.x && page_cache_y == page.y &&
  13110. page_cache_w == page.w && page_cache_h == page.h) {
  13111. blit_page(page, page_backbuf, pagebuf_w);
  13112. if (img_stat_n)
  13113. img_stat_paint += u_ticks_ms() - t0;
  13114. return;
  13115. }
  13116. ngui_fill_rect(&ui, page, page_bg);
  13117. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  13118. const char *s = page_loading ? "Loading..." : "No page";
  13119. int w = (int)ngui_text_width_ui(&ui, s);
  13120. ngui_text(&ui, page.x + (page.w - w) / 2,
  13121. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  13122. page_scroll.content_h = 0;
  13123. page_scroll.view_h = page.h;
  13124. page_cache_valid = 0;
  13125. return;
  13126. }
  13127. if (page.w < 40 || page.h < 40) {
  13128. page_cache_valid = 0;
  13129. return;
  13130. }
  13131. saved_px = ui.px;
  13132. saved_w = ui.w;
  13133. saved_h = ui.h;
  13134. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  13135. if (use_buf) {
  13136. ui.px = page_backbuf;
  13137. ui.w = pagebuf_w;
  13138. ui.h = pagebuf_h;
  13139. ngui_fill_rect(&ui, page, page_bg);
  13140. }
  13141. /* No gutter of our own: the body's UA margin provides it. The
  13142. * right 12 px stay clear for the scrollbar, like every viewport
  13143. * width below (page_rect.w - 12). */
  13144. left = page.x;
  13145. right = page.x + page.w - 12;
  13146. if (!layout_valid || left != layout_left || right != layout_right ||
  13147. layout_nnode != doc.nnode) {
  13148. unsigned int tm = u_ticks_ms();
  13149. layout_view_h = page.h;
  13150. layout_content_h = measure_page(left, right);
  13151. if (img_stat_n)
  13152. img_stat_reflow += u_ticks_ms() - tm;
  13153. layout_valid = 1;
  13154. layout_left = left;
  13155. layout_right = right;
  13156. layout_nnode = doc.nnode;
  13157. /* Scripts that measured before any layout (offsetWidth on
  13158. * mount) get a resize event once real boxes exist, and again
  13159. * whenever the page width changes. */
  13160. if (js_browser_active() && right - left != resize_sent_w)
  13161. resize_pending = 1;
  13162. }
  13163. ch = layout_content_h;
  13164. page_scroll.content_h = ch;
  13165. page_scroll.view_h = page.h;
  13166. t0 = u_ticks_ms();
  13167. ngui_scroll_begin(&ui, page, &page_scroll);
  13168. ngui_scroll_wheel(&ui, page, &page_scroll);
  13169. render_page(left, right, page.y - page_scroll.offset);
  13170. old_panel = ui.theme.panel_alt;
  13171. old_dim = ui.theme.text_dim;
  13172. ui.theme.panel_alt = 0xC618;
  13173. ui.theme.text_dim = 0x8410;
  13174. ngui_scroll_end(&ui, page, &page_scroll);
  13175. ui.theme.panel_alt = old_panel;
  13176. ui.theme.text_dim = old_dim;
  13177. if (use_buf) {
  13178. ui.px = saved_px;
  13179. ui.w = saved_w;
  13180. ui.h = saved_h;
  13181. blit_page(page, page_backbuf, pagebuf_w);
  13182. page_cache_valid = 1;
  13183. page_cache_scroll = page_scroll.offset;
  13184. page_cache_nnode = doc.nnode;
  13185. page_cache_x = page.x;
  13186. page_cache_y = page.y;
  13187. page_cache_w = page.w;
  13188. page_cache_h = page.h;
  13189. } else {
  13190. page_cache_valid = 0;
  13191. }
  13192. if (img_stat_n)
  13193. img_stat_paint += u_ticks_ms() - t0;
  13194. }
  13195. /* Lay the page out now, into the page back buffer, so scripts read real
  13196. * boxes for nodes they just inserted. Absolute/fixed boxes only get their
  13197. * boxes in the painting pass, so this is a full render; the next frame
  13198. * repaints the screen as usual. Skipped while the page has never been
  13199. * drawn (no viewport yet) or without the back buffer.
  13200. *
  13201. * The guard is a count per main-loop pass, not a time budget: a hover or
  13202. * click handler (Bootstrap's tooltip does ~6 write/read rounds) must get
  13203. * correct geometry even on the ION, where one re-layout of cloudron.io
  13204. * takes longer than any reasonable per-window budget; only a script that
  13205. * keeps writing and reading in one pass falls back to the last layout. */
  13206. #define FORCE_LAYOUT_PER_PASS 8
  13207. static int force_layout_count;
  13208. static void js_force_layout_pass_reset(void)
  13209. {
  13210. force_layout_count = 0;
  13211. }
  13212. static void js_force_layout(void)
  13213. {
  13214. static int busy;
  13215. unsigned short *saved_px = ui.px;
  13216. int saved_w = ui.w, saved_h = ui.h;
  13217. struct ngui_rect page = page_rect;
  13218. if (busy || !page_backbuf || pagebuf_w != ui.w ||
  13219. pagebuf_h != ui.h || page.w < 40 || page.h < 40 ||
  13220. layout_right <= layout_left ||
  13221. force_layout_count >= FORCE_LAYOUT_PER_PASS)
  13222. return;
  13223. force_layout_count++;
  13224. busy = 1;
  13225. ui.px = page_backbuf;
  13226. layout_view_h = page.h;
  13227. layout_content_h = measure_page(layout_left, layout_right);
  13228. layout_valid = 1;
  13229. layout_nnode = doc.nnode;
  13230. ngui_push_clip(&ui, page);
  13231. render_page(layout_left, layout_right, page.y - page_scroll.offset);
  13232. ngui_pop_clip(&ui);
  13233. ui.px = saved_px;
  13234. ui.w = saved_w;
  13235. ui.h = saved_h;
  13236. page_cache_valid = 0;
  13237. ngui_invalidate(&ui);
  13238. busy = 0;
  13239. }
  13240. static void draw_status(struct ngui_rect r)
  13241. {
  13242. static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
  13243. unsigned int n = 0;
  13244. int hover = page_hover_node();
  13245. unsigned short color;
  13246. const char *kind;
  13247. ngui_fill_rect(&ui, r, ui.theme.panel);
  13248. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  13249. ui.theme.border);
  13250. /* Only a real link target is shown: a form control, or an element
  13251. * that is merely clickable through a script listener (google.com's
  13252. * jsaction wrapper around its search field), is not a link. */
  13253. if (hover && !br_href(&doc, (unsigned int)hover))
  13254. hover = 0;
  13255. if (hover) {
  13256. const char *href = br_href(&doc, (unsigned int)hover);
  13257. char url[BR_URL_MAX];
  13258. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  13259. s_append(msg, &n, "Link: ", sizeof(msg));
  13260. s_append(msg, &n, url, sizeof(msg));
  13261. } else {
  13262. s_copy(msg, "Link", sizeof(msg));
  13263. }
  13264. color = ui.theme.accent;
  13265. } else if (status_text[0]) {
  13266. s_copy(msg, status_text, sizeof(msg));
  13267. color = status_error ? ui.theme.error : ui.theme.text;
  13268. } else if (page_title[0]) {
  13269. s_copy(msg, page_title, sizeof(msg));
  13270. color = ui.theme.text;
  13271. } else {
  13272. s_copy(msg, "Ready", sizeof(msg));
  13273. color = ui.theme.text_dim;
  13274. }
  13275. kind = s_eq(page_url, "about:home") ? "HOME" :
  13276. page_is_local ? "FILE" :
  13277. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  13278. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  13279. {
  13280. int kw = (int)ngui_text_width_ui(&ui, kind);
  13281. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  13282. ui.theme.text_dim);
  13283. }
  13284. }
  13285. /* ---- downloads panel -------------------------------------------------- */
  13286. static int dl_order[DL_MAX], dl_order_n;
  13287. static void dl_order_build(void)
  13288. {
  13289. int i, j;
  13290. dl_order_n = 0;
  13291. for (i = 0; i < DL_MAX; i++)
  13292. if (dl_tab[i].used)
  13293. dl_order[dl_order_n++] = i;
  13294. for (i = 1; i < dl_order_n; i++) {
  13295. int key = dl_order[i];
  13296. unsigned int stamp = dl_tab[key].stamp;
  13297. for (j = i - 1; j >= 0 &&
  13298. dl_tab[dl_order[j]].stamp < stamp; j--)
  13299. dl_order[j + 1] = dl_order[j];
  13300. dl_order[j + 1] = key;
  13301. }
  13302. }
  13303. static void dl_size_text(unsigned int size, char *out, unsigned int cap)
  13304. {
  13305. if (size >= 1024u * 1024u)
  13306. snprintf(out, cap, "%u.%u MB", size / (1024u * 1024u),
  13307. (size % (1024u * 1024u)) * 10 / (1024u * 1024u));
  13308. else if (size >= 1024u)
  13309. snprintf(out, cap, "%u KB", size / 1024u);
  13310. else
  13311. snprintf(out, cap, "%u bytes", size);
  13312. }
  13313. static void dl_ent_label(const struct dl_ent *e, char *out, unsigned int cap)
  13314. {
  13315. char base[16], ext[8];
  13316. if (e->name[0]) {
  13317. s_copy(out, e->name, cap);
  13318. return;
  13319. }
  13320. dl_url_name(e->url, "", base, sizeof(base), ext, sizeof(ext));
  13321. if (ext[0])
  13322. snprintf(out, cap, "%s.%s", base, ext);
  13323. else
  13324. s_copy(out, base, cap);
  13325. }
  13326. static void dl_ent_status(const struct dl_ent *e, char *out,
  13327. unsigned int cap)
  13328. {
  13329. char size[24];
  13330. switch (e->state) {
  13331. case DL_QUEUED:
  13332. s_copy(out, "Queued", cap);
  13333. break;
  13334. case DL_RUNNING: {
  13335. int p = dl_percent();
  13336. if (p >= 0) {
  13337. snprintf(out, cap, "Downloading %d%%", p);
  13338. } else {
  13339. dl_size_text(e->got, size, sizeof(size));
  13340. snprintf(out, cap, "Downloading %s", size);
  13341. }
  13342. break;
  13343. }
  13344. case DL_SAVING:
  13345. s_copy(out, "Saving...", cap);
  13346. break;
  13347. case DL_DONE:
  13348. dl_size_text(e->size, size, sizeof(size));
  13349. snprintf(out, cap, "Saved - %s", size);
  13350. break;
  13351. default:
  13352. if (e->err[0])
  13353. snprintf(out, cap, "Failed: %s", e->err);
  13354. else
  13355. s_copy(out, "Failed", cap);
  13356. break;
  13357. }
  13358. }
  13359. static void dl_panel_layout(struct ngui_rect page)
  13360. {
  13361. int w = DL_PANEL_W, rows, avail, h, x, y;
  13362. dl_order_build();
  13363. rows = dl_order_n;
  13364. if (rows > DL_PANEL_ROWS)
  13365. rows = DL_PANEL_ROWS;
  13366. avail = (page.h - 46) / DL_ROW_H;
  13367. if (avail < 0)
  13368. avail = 0;
  13369. if (rows > avail)
  13370. rows = avail;
  13371. dl_panel_rows = rows;
  13372. if (w > page.w - 16)
  13373. w = page.w - 16;
  13374. if (w < 120)
  13375. w = 120;
  13376. h = 36 + (rows ? rows * DL_ROW_H : 28) + 6;
  13377. if (h > page.h - 8)
  13378. h = page.h - 8;
  13379. x = dl_button_rect.x + dl_button_rect.w - w;
  13380. if (x + w > page.x + page.w - 4)
  13381. x = page.x + page.w - 4 - w;
  13382. if (x < page.x + 4)
  13383. x = page.x + 4;
  13384. y = page.y + 2;
  13385. dl_panel_rect = (struct ngui_rect){x, y, w, h};
  13386. dl_clear_rect = (struct ngui_rect){x + w - 54, y + 6, 46, 20};
  13387. }
  13388. static void dl_panel_press(struct ngui_rect page)
  13389. {
  13390. if (!dl_panel_open || !ui.pressed)
  13391. return;
  13392. dl_panel_layout(page);
  13393. if (ngui_rect_contains(&dl_panel_rect, ui.press_x, ui.press_y)) {
  13394. if (ngui_rect_contains(&dl_clear_rect, ui.press_x, ui.press_y))
  13395. dl_clear_history();
  13396. ui.pressed = ui.released = 0;
  13397. return;
  13398. }
  13399. if (!ngui_rect_contains(&dl_button_rect, ui.press_x, ui.press_y)) {
  13400. dl_panel_open = 0;
  13401. ngui_invalidate(&ui);
  13402. if (ngui_rect_contains(&page, ui.press_x, ui.press_y))
  13403. ui.pressed = ui.released = 0;
  13404. }
  13405. }
  13406. static void draw_downloads(struct ngui_rect page)
  13407. {
  13408. int i;
  13409. if (!dl_panel_open)
  13410. return;
  13411. dl_panel_layout(page);
  13412. if (ui.inside && ngui_rect_contains(&dl_panel_rect, ui.mouse_x,
  13413. ui.mouse_y))
  13414. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  13415. if (dl_history_count() > 0 && ui.inside &&
  13416. ngui_rect_contains(&dl_clear_rect, ui.mouse_x, ui.mouse_y))
  13417. ngui_set_cursor(&ui, CURSOR_POINTER);
  13418. ngui_fill_rect(&ui, dl_panel_rect, ui.theme.border);
  13419. ngui_fill_rect(&ui, (struct ngui_rect){dl_panel_rect.x + 1,
  13420. dl_panel_rect.y + 1, dl_panel_rect.w - 2,
  13421. dl_panel_rect.h - 2}, ui.theme.panel);
  13422. ngui_text_styled(&ui, dl_panel_rect.x + 10, dl_panel_rect.y + 8,
  13423. "Downloads", 9, ui.theme.text, 1, 1);
  13424. if (dl_history_count() > 0) {
  13425. int cw = (int)ngui_text_width_ui(&ui, "Clear");
  13426. int hot = ui.inside && ngui_rect_contains(&dl_clear_rect,
  13427. ui.mouse_x,
  13428. ui.mouse_y);
  13429. ngui_text(&ui, dl_clear_rect.x + (dl_clear_rect.w - cw) / 2,
  13430. dl_clear_rect.y + 1, "Clear",
  13431. hot ? ui.theme.accent : ui.theme.text_dim);
  13432. }
  13433. if (dl_order_n > dl_panel_rows && dl_panel_rows > 0 &&
  13434. dl_panel_rect.w > 260) {
  13435. char more[24];
  13436. int mw;
  13437. snprintf(more, sizeof(more), "%d more", dl_order_n - dl_panel_rows);
  13438. mw = (int)ngui_text_width_ui(&ui, more);
  13439. ngui_text(&ui, dl_clear_rect.x - mw - 8, dl_clear_rect.y + 1,
  13440. more, ui.theme.text_dim);
  13441. }
  13442. if (!dl_order_n) {
  13443. ngui_text(&ui, dl_panel_rect.x + 12,
  13444. dl_panel_rect.y + 40, "No downloads yet",
  13445. ui.theme.text_dim);
  13446. return;
  13447. }
  13448. for (i = 0; i < dl_panel_rows; i++) {
  13449. struct dl_ent *e = &dl_tab[dl_order[i]];
  13450. struct ngui_rect rr = {dl_panel_rect.x + 1,
  13451. dl_panel_rect.y + 30 + i * DL_ROW_H,
  13452. dl_panel_rect.w - 2, DL_ROW_H};
  13453. char name[DL_NAME_MAX], status[96];
  13454. int hot = ui.inside &&
  13455. ngui_rect_contains(&rr, ui.mouse_x, ui.mouse_y);
  13456. enum ngui_icon icon = NGUI_ICON_DOWNLOAD;
  13457. unsigned short icon_color = ui.theme.text_dim;
  13458. dl_ent_label(e, name, sizeof(name));
  13459. dl_ent_status(e, status, sizeof(status));
  13460. if (e->state == DL_DONE) {
  13461. icon = NGUI_ICON_FILE;
  13462. icon_color = ui.theme.text_dim;
  13463. } else if (e->state == DL_FAILED) {
  13464. icon = NGUI_ICON_CLOSE;
  13465. icon_color = ui.theme.error;
  13466. } else {
  13467. icon_color = ui.theme.accent;
  13468. }
  13469. ngui_fill_rect(&ui, rr, hot ? ui.theme.panel_alt : ui.theme.panel);
  13470. ngui_icon(&ui, (struct ngui_rect){rr.x + 7, rr.y + 8, 20, 20},
  13471. icon, icon_color);
  13472. ngui_text_ellipsis(&ui, rr, rr.x + 34, rr.y + 3, name,
  13473. ui.theme.text);
  13474. ngui_text_ellipsis(&ui, rr, rr.x + 34, rr.y + 19, status,
  13475. e->state == DL_FAILED ? ui.theme.error :
  13476. ui.theme.text_dim);
  13477. if (e->state == DL_RUNNING || e->state == DL_SAVING) {
  13478. int p = dl_percent();
  13479. int bw = rr.w - 42;
  13480. ngui_fill_rect(&ui, (struct ngui_rect){rr.x + 34,
  13481. rr.y + rr.h - 6, bw, 3},
  13482. ui.theme.border);
  13483. if (p > 0)
  13484. ngui_fill_rect(&ui, (struct ngui_rect){
  13485. rr.x + 34, rr.y + rr.h - 6,
  13486. bw * p / 100, 3}, ui.theme.accent);
  13487. }
  13488. }
  13489. }
  13490. /* Mouse cursor over the page: the hovered node's CSS `cursor` (inherited);
  13491. * for `auto`, a hand over links, the I-beam over text fields, and the
  13492. * progress arrow anywhere on the page while it is still loading. The
  13493. * toolbar's URL field sets its own I-beam through ngui. */
  13494. static void page_cursor(void)
  13495. {
  13496. int hover = page_hover_node();
  13497. struct br_style st;
  13498. if (!hover) {
  13499. if (page_loading && ui.inside &&
  13500. ngui_rect_contains(&page_rect, ui.mouse_x, ui.mouse_y))
  13501. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  13502. return;
  13503. }
  13504. style_for_node((unsigned int)hover, &st);
  13505. if (st.cursor != BR_CURSOR_AUTO) {
  13506. ngui_set_cursor(&ui, (int)st.cursor - 1);
  13507. return;
  13508. }
  13509. if (br_href(&doc, (unsigned int)hover)) {
  13510. ngui_set_cursor(&ui, CURSOR_POINTER);
  13511. return;
  13512. }
  13513. if (form_is_control((unsigned int)hover)) {
  13514. int k = form_kind_of((unsigned int)hover);
  13515. if (form_disabled((unsigned int)hover))
  13516. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  13517. else if (k == FORM_TEXT || k == FORM_PASSWORD ||
  13518. k == FORM_TEXTAREA)
  13519. ngui_set_cursor(&ui, CURSOR_TEXT);
  13520. return;
  13521. }
  13522. if (page_loading)
  13523. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  13524. }
  13525. static void draw(unsigned int *action)
  13526. {
  13527. struct ngui_rect r = {0, 0, ui.w, ui.h};
  13528. struct ngui_rect toolbar, status, page;
  13529. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  13530. status = ngui_cut_bottom(&r, BR_STATUS_H);
  13531. page = r;
  13532. if (sug_visible())
  13533. sug_click(action);
  13534. ctx_open_from_right(page);
  13535. ctx_press(page);
  13536. dl_panel_press(page);
  13537. draw_toolbar(toolbar, action);
  13538. draw_page(page);
  13539. draw_status(status);
  13540. page_cursor();
  13541. if (sug_visible())
  13542. draw_suggest(page);
  13543. else
  13544. sug_rect.w = 0;
  13545. draw_downloads(page);
  13546. draw_context();
  13547. }
  13548. static void redraw_now(void)
  13549. {
  13550. unsigned int action = 0;
  13551. ngui_begin(&ui);
  13552. draw(&action);
  13553. ngui_end(&ui);
  13554. }
  13555. static void handle_keys(unsigned int *action)
  13556. {
  13557. int k, scrolled = 0;
  13558. if (form_focus >= doc.nnode)
  13559. form_focus = 0;
  13560. if (form_focus && !ngui_focus(&ui)) {
  13561. while ((k = ngui_key(&ui)) != 0)
  13562. form_key(k);
  13563. return;
  13564. }
  13565. /* Batch queued page keys: a slow full-page render must not make a
  13566. * held Page Down advance only once every few frames. */
  13567. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  13568. scrolled++;
  13569. if (scrolled)
  13570. ngui_invalidate(&ui);
  13571. if (ngui_focus(&ui))
  13572. return;
  13573. while ((k = ngui_key(&ui)) != 0) {
  13574. switch (k) {
  13575. case NGUI_KEY_ESC:
  13576. if (ctx_open) {
  13577. ctx_close();
  13578. } else if (dl_panel_open) {
  13579. dl_panel_open = 0;
  13580. ngui_invalidate(&ui);
  13581. } else {
  13582. *action |= ACT_CLOSE;
  13583. }
  13584. break;
  13585. case NGUI_KEY_TAB:
  13586. case 0x0C: /* Ctrl+L */
  13587. ngui_set_focus(&ui, ID_URL);
  13588. break;
  13589. case 0x12: /* Ctrl+R */
  13590. *action |= ACT_RELOAD;
  13591. break;
  13592. case NGUI_KEY_BACKSPACE:
  13593. *action |= ACT_BACK;
  13594. break;
  13595. case NGUI_KEY_UP:
  13596. ngui_scroll_to(&page_scroll,
  13597. page_scroll.offset - 24);
  13598. ngui_invalidate(&ui);
  13599. break;
  13600. case NGUI_KEY_DOWN:
  13601. ngui_scroll_to(&page_scroll,
  13602. page_scroll.offset + 24);
  13603. ngui_invalidate(&ui);
  13604. break;
  13605. case NGUI_KEY_HOME:
  13606. ngui_scroll_to(&page_scroll, 0);
  13607. ngui_invalidate(&ui);
  13608. break;
  13609. case NGUI_KEY_END:
  13610. ngui_scroll_to(&page_scroll,
  13611. page_scroll.content_h -
  13612. page_scroll.view_h);
  13613. ngui_invalidate(&ui);
  13614. break;
  13615. default:
  13616. break;
  13617. }
  13618. }
  13619. }
  13620. static unsigned int form_ancestor(unsigned int node)
  13621. {
  13622. unsigned int p = node;
  13623. while (p && p < doc.nnode) {
  13624. if (doc.nodes[p].tag == BR_TAG_FORM &&
  13625. doc.nodes[p].type == BR_NODE_ELEM)
  13626. return p;
  13627. p = doc.nodes[p].parent;
  13628. }
  13629. return 0;
  13630. }
  13631. static int form_descendant(unsigned int node, unsigned int form)
  13632. {
  13633. unsigned int p = node;
  13634. while (p && p < doc.nnode) {
  13635. if (p == form)
  13636. return 1;
  13637. p = doc.nodes[p].parent;
  13638. }
  13639. return 0;
  13640. }
  13641. static void form_reset_form(unsigned int form)
  13642. {
  13643. unsigned int i;
  13644. for (i = 0; i < FORM_MAX; i++)
  13645. if (form_states[i].used &&
  13646. form_descendant(form_states[i].node, form))
  13647. form_states[i].used = 0;
  13648. form_focus = 0;
  13649. }
  13650. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  13651. const char *s)
  13652. {
  13653. static const char hex[] = "0123456789ABCDEF";
  13654. while (s && *s && *n + 1 < cap) {
  13655. unsigned char c = (unsigned char)*s++;
  13656. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  13657. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  13658. c == '.' || c == '~') {
  13659. dst[(*n)++] = (char)c;
  13660. } else if (c == ' ') {
  13661. dst[(*n)++] = '+';
  13662. } else if (*n + 3 < cap) {
  13663. dst[(*n)++] = '%';
  13664. dst[(*n)++] = hex[c >> 4];
  13665. dst[(*n)++] = hex[c & 15];
  13666. }
  13667. }
  13668. dst[*n] = '\0';
  13669. }
  13670. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  13671. const char *name, const char *value, int *first)
  13672. {
  13673. if (!name || !name[0])
  13674. return;
  13675. if (!*first && *n + 1 < cap)
  13676. dst[(*n)++] = '&';
  13677. *first = 0;
  13678. form_url_append(dst, n, cap, name);
  13679. if (*n + 1 < cap)
  13680. dst[(*n)++] = '=';
  13681. form_url_append(dst, n, cap, value ? value : "");
  13682. dst[*n] = '\0';
  13683. }
  13684. static int form_submit_form(unsigned int node, int fire_event)
  13685. {
  13686. unsigned int form = form_ancestor(node);
  13687. char action[BR_URL_MAX], query[2048];
  13688. unsigned int qn = 0, i;
  13689. int first = 1, is_post = 0;
  13690. const char *a, *method;
  13691. if (!form)
  13692. return 0;
  13693. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  13694. return 0;
  13695. method = br_find_attr(&doc, form, "method");
  13696. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  13697. is_post = 1;
  13698. a = br_find_attr(&doc, form, "action");
  13699. if (a && a[0]) {
  13700. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  13701. return 0;
  13702. } else {
  13703. s_copy(action, page_url, sizeof(action));
  13704. }
  13705. query[0] = '\0';
  13706. for (i = 0; i < doc.nnode; i++) {
  13707. struct br_node *nd = &doc.nodes[i];
  13708. struct form_state *fs;
  13709. const char *name;
  13710. const char *value = "";
  13711. if (nd->type != BR_NODE_ELEM || i == form ||
  13712. !form_descendant(i, form))
  13713. continue;
  13714. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  13715. nd->tag != BR_TAG_SELECT)
  13716. continue;
  13717. if (form_disabled(i))
  13718. continue;
  13719. name = br_find_attr(&doc, i, "name");
  13720. if (!name || !name[0])
  13721. continue;
  13722. fs = form_get(i, 1);
  13723. if (!fs)
  13724. continue;
  13725. if (nd->tag == BR_TAG_SELECT) {
  13726. char opt[64];
  13727. if (!form_option_text(i, fs->selected, opt,
  13728. sizeof(opt)))
  13729. s_copy(opt, "", sizeof(opt));
  13730. value = opt;
  13731. {
  13732. unsigned int c, oi = 0;
  13733. for (c = nd->first; c;
  13734. c = doc.nodes[c].next) {
  13735. if (doc.nodes[c].type != BR_NODE_ELEM ||
  13736. doc.nodes[c].tag != BR_TAG_OPTION)
  13737. continue;
  13738. if (oi == fs->selected) {
  13739. const char *v =
  13740. br_value(&doc, c);
  13741. if (v && v[0])
  13742. value = v;
  13743. break;
  13744. }
  13745. oi++;
  13746. }
  13747. }
  13748. } else if (nd->tag == BR_TAG_INPUT) {
  13749. int kind = form_kind_of(i);
  13750. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  13751. if (!fs->checked)
  13752. continue;
  13753. value = br_value(&doc, i);
  13754. if (!value || !value[0])
  13755. value = "on";
  13756. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  13757. kind == FORM_BUTTON) {
  13758. if (i != node)
  13759. continue;
  13760. value = fs->value;
  13761. } else {
  13762. value = fs->value;
  13763. }
  13764. } else {
  13765. value = fs->value;
  13766. }
  13767. form_add_param(query, &qn, sizeof(query), name, value, &first);
  13768. }
  13769. if (is_post) {
  13770. if (action[0] == '/') {
  13771. set_status("POST forms need an HTTP action URL", 1, 4000);
  13772. ngui_invalidate(&ui);
  13773. return 0;
  13774. }
  13775. if (qn >= sizeof(pending_post))
  13776. qn = sizeof(pending_post) - 1;
  13777. if (qn)
  13778. memcpy(pending_post, query, qn);
  13779. pending_post[qn] = '\0';
  13780. pending_post_len = qn;
  13781. pending_post_is = 1;
  13782. } else {
  13783. pending_post_len = 0;
  13784. pending_post_is = 0;
  13785. if (qn) {
  13786. unsigned int an = s_len(action);
  13787. if (an + qn + 2 < sizeof(action)) {
  13788. action[an++] = strchr(action, '?') ? '&' : '?';
  13789. action[an] = '\0';
  13790. s_copy(action + an, query,
  13791. sizeof(action) - an);
  13792. }
  13793. }
  13794. }
  13795. s_copy(pending_url, action, sizeof(pending_url));
  13796. pending_action |= ACT_NAV;
  13797. cancel_fetch = 1;
  13798. ngui_invalidate(&ui);
  13799. return 1;
  13800. }
  13801. static void form_reset_event(unsigned int form)
  13802. {
  13803. if (form && !js_browser_event(form, "reset", 1, 1))
  13804. return;
  13805. if (form)
  13806. form_reset_form(form);
  13807. else
  13808. form_reset_state();
  13809. form_dirty = 0;
  13810. layout_valid = 0;
  13811. ngui_invalidate(&ui);
  13812. }
  13813. static void form_blur(void)
  13814. {
  13815. unsigned int node = form_focus;
  13816. form_focus = 0;
  13817. if (node && form_dirty) {
  13818. form_dirty = 0;
  13819. js_browser_event(node, "change", 1, 0);
  13820. }
  13821. }
  13822. static void form_click(unsigned int node)
  13823. {
  13824. struct form_state *fs;
  13825. int kind, changed = 0;
  13826. if (!form_is_control(node) || form_disabled(node))
  13827. return;
  13828. if (form_focus != node)
  13829. form_blur();
  13830. fs = form_get(node, 1);
  13831. if (!fs)
  13832. return;
  13833. kind = form_kind_of(node);
  13834. /* Focus moves on the press, before `click` is dispatched: a page
  13835. * that cancels the click (a framework's root listener) suppresses
  13836. * the activation behaviour below, never the focus (as in other
  13837. * browsers, where focus follows mousedown). */
  13838. form_focus = node;
  13839. form_dirty = 0;
  13840. if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  13841. kind == FORM_TEXTAREA)
  13842. fs->caret = fs->len;
  13843. layout_valid = 0;
  13844. ngui_invalidate(&ui);
  13845. if (!js_browser_event(node, "click", 1, 1))
  13846. return;
  13847. fs = form_get(node, 0); /* the handler may have changed the DOM */
  13848. if (!fs)
  13849. return;
  13850. if (kind == FORM_CHECKBOX) {
  13851. fs->checked = !fs->checked;
  13852. changed = 1;
  13853. } else if (kind == FORM_RADIO) {
  13854. const char *name = br_find_attr(&doc, node, "name");
  13855. unsigned int i;
  13856. fs->checked = 1;
  13857. changed = 1;
  13858. if (name) {
  13859. for (i = 0; i < FORM_MAX; i++) {
  13860. struct form_state *o = &form_states[i];
  13861. if (!o->used || o->node == node)
  13862. continue;
  13863. if (form_kind_of(o->node) == FORM_RADIO) {
  13864. const char *on = br_find_attr(&doc,
  13865. o->node,
  13866. "name");
  13867. if (on && s_eq(on, name))
  13868. o->checked = 0;
  13869. }
  13870. }
  13871. }
  13872. } else if (kind == FORM_SELECT) {
  13873. unsigned int n = form_option_count(node);
  13874. if (n) {
  13875. fs->selected = (unsigned char)
  13876. ((fs->selected + 1) % n);
  13877. changed = 1;
  13878. }
  13879. } else if (kind == FORM_SUBMIT) {
  13880. form_submit_form(node, 1);
  13881. return;
  13882. } else if (kind == FORM_RESET) {
  13883. form_reset_event(form_ancestor(node));
  13884. return;
  13885. }
  13886. if (changed) {
  13887. js_browser_event(node, "input", 1, 0);
  13888. js_browser_event(node, "change", 1, 0);
  13889. }
  13890. layout_valid = 0;
  13891. ngui_invalidate(&ui);
  13892. }
  13893. static void form_focus_next(void)
  13894. {
  13895. unsigned int start = form_focus ? form_focus + 1 : 0;
  13896. unsigned int i;
  13897. form_blur();
  13898. for (i = start; i < doc.nnode; i++) {
  13899. if (form_is_control(i) && !form_disabled(i) &&
  13900. !s_eq(br_type(&doc, i), "hidden")) {
  13901. form_focus = i;
  13902. layout_valid = 0;
  13903. ngui_invalidate(&ui);
  13904. return;
  13905. }
  13906. }
  13907. form_focus = 0;
  13908. layout_valid = 0;
  13909. ngui_invalidate(&ui);
  13910. }
  13911. static void form_key(int k)
  13912. {
  13913. struct form_state *fs;
  13914. int kind;
  13915. if (!form_focus || form_focus >= doc.nnode) {
  13916. form_focus = 0;
  13917. return;
  13918. }
  13919. fs = form_get(form_focus, 1);
  13920. if (!fs || form_disabled(form_focus))
  13921. return;
  13922. kind = form_kind_of(form_focus);
  13923. if (kind == FORM_SELECT) {
  13924. unsigned int n = form_option_count(form_focus);
  13925. int changed = 0;
  13926. if (k == NGUI_KEY_UP && n) {
  13927. fs->selected = (unsigned char)
  13928. ((fs->selected + n - 1) % n);
  13929. changed = 1;
  13930. } else if (k == NGUI_KEY_DOWN && n) {
  13931. fs->selected = (unsigned char)
  13932. ((fs->selected + 1) % n);
  13933. changed = 1;
  13934. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  13935. form_blur();
  13936. layout_valid = 0;
  13937. ngui_invalidate(&ui);
  13938. return;
  13939. } else {
  13940. return;
  13941. }
  13942. if (changed) {
  13943. js_browser_event(form_focus, "input", 1, 0);
  13944. js_browser_event(form_focus, "change", 1, 0);
  13945. }
  13946. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  13947. if (k == ' ') {
  13948. form_click(form_focus);
  13949. return;
  13950. }
  13951. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  13952. form_blur();
  13953. layout_valid = 0;
  13954. ngui_invalidate(&ui);
  13955. }
  13956. return;
  13957. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  13958. kind == FORM_RESET) {
  13959. if (k == NGUI_KEY_ESC) {
  13960. form_blur();
  13961. layout_valid = 0;
  13962. ngui_invalidate(&ui);
  13963. } else if (k == '\r' || k == '\n' || k == ' ') {
  13964. form_click(form_focus);
  13965. }
  13966. return;
  13967. } else if (k == NGUI_KEY_TAB) {
  13968. form_focus_next();
  13969. return;
  13970. } else if (k == NGUI_KEY_ESC) {
  13971. form_blur();
  13972. layout_valid = 0;
  13973. ngui_invalidate(&ui);
  13974. return;
  13975. } else if (k == '\r' || k == '\n') {
  13976. unsigned int node = form_focus;
  13977. form_blur();
  13978. if (form_ancestor(node))
  13979. form_submit_form(node, 1);
  13980. layout_valid = 0;
  13981. ngui_invalidate(&ui);
  13982. return;
  13983. } else if (k == NGUI_KEY_BACKSPACE) {
  13984. if (fs->caret) {
  13985. unsigned int i = --fs->caret;
  13986. for (; i < fs->len; i++)
  13987. fs->value[i] = fs->value[i + 1];
  13988. if (fs->len)
  13989. fs->len--;
  13990. form_dirty = 1;
  13991. js_browser_event(form_focus, "input", 1, 0);
  13992. }
  13993. } else if (k == NGUI_KEY_DELETE) {
  13994. if (fs->caret < fs->len) {
  13995. unsigned int i;
  13996. for (i = fs->caret; i < fs->len; i++)
  13997. fs->value[i] = fs->value[i + 1];
  13998. fs->len--;
  13999. form_dirty = 1;
  14000. js_browser_event(form_focus, "input", 1, 0);
  14001. }
  14002. } else if (k == NGUI_KEY_LEFT) {
  14003. if (fs->caret)
  14004. fs->caret--;
  14005. } else if (k == NGUI_KEY_RIGHT) {
  14006. if (fs->caret < fs->len)
  14007. fs->caret++;
  14008. } else if (k == NGUI_KEY_HOME) {
  14009. fs->caret = 0;
  14010. } else if (k == NGUI_KEY_END) {
  14011. fs->caret = fs->len;
  14012. } else if (k >= 32 && k < 127) {
  14013. if (fs->len < FORM_VALUE_MAX) {
  14014. unsigned int i;
  14015. for (i = fs->len; i > fs->caret; i--)
  14016. fs->value[i] = fs->value[i - 1];
  14017. fs->value[fs->caret++] = (char)k;
  14018. fs->len++;
  14019. form_dirty = 1;
  14020. js_browser_event(form_focus, "input", 1, 0);
  14021. }
  14022. } else {
  14023. return;
  14024. }
  14025. fs->value[fs->len] = '\0';
  14026. layout_valid = 0;
  14027. ngui_invalidate(&ui);
  14028. }
  14029. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  14030. * a same-document navigation: update the URL and fire hashchange. Returns
  14031. * 1 when handled. */
  14032. static int link_fragment_nav(unsigned int node)
  14033. {
  14034. const char *href = br_href(&doc, node);
  14035. char url[BR_URL_MAX];
  14036. unsigned int n = 0;
  14037. if (!href || !href[0] || !js_browser_active())
  14038. return 0;
  14039. if (href[0] == '#') {
  14040. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  14041. url[n] = page_url[n];
  14042. n++;
  14043. }
  14044. url[n] = '\0';
  14045. s_append(url, &n, href, sizeof(url));
  14046. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  14047. return 0;
  14048. }
  14049. if (!same_doc_fragment(url))
  14050. return href[0] == '#';
  14051. page_set_fragment(url, 1);
  14052. js_browser_hashchange();
  14053. return 1;
  14054. }
  14055. /* A positioned box laid out while transparent or visibility:hidden (or
  14056. * inside one): it has a box for scripts but must not catch the pointer. */
  14057. static int node_invisible(unsigned int n)
  14058. {
  14059. unsigned int guard = 0;
  14060. while (n < doc.nnode && guard++ < 64) {
  14061. struct br_style st;
  14062. style_for_node(n, &st);
  14063. if (st.opacity_hidden || st.vis_hidden)
  14064. return 1;
  14065. if (n == 0)
  14066. break;
  14067. n = doc.nodes[n].parent;
  14068. }
  14069. return 0;
  14070. }
  14071. /* The innermost laid-out box under a screen point: the smallest valid box
  14072. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  14073. * Used to deliver clicks to elements that are neither links nor controls
  14074. * (a Vue <div role="button">, a card with a click listener). */
  14075. static int node_contains(unsigned int a, unsigned int n);
  14076. static unsigned int find_box_hit(int x, int y)
  14077. {
  14078. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  14079. int root;
  14080. /* A covering positioned box (a modal) takes the point: only it and
  14081. * its descendants are candidates, not the page painted under it. */
  14082. if (find_hit_ex(x, y, &root) || root < 0)
  14083. root = -1;
  14084. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  14085. const struct br_layout_box *b = &layout_boxes[i];
  14086. unsigned int area;
  14087. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  14088. x < b->x || y < b->y || x >= b->x + b->w ||
  14089. y >= b->y + b->h)
  14090. continue;
  14091. if (root >= 0 && !node_contains((unsigned int)root, i))
  14092. continue;
  14093. area = (unsigned int)b->w * (unsigned int)b->h;
  14094. if (area <= best_area && !node_invisible(i)) {
  14095. best = i;
  14096. best_area = area;
  14097. }
  14098. }
  14099. return best;
  14100. }
  14101. /* ---- page context menu ------------------------------------------------ */
  14102. static void ctx_add(unsigned int action, const char *label, const char *url)
  14103. {
  14104. int i;
  14105. if (ctx_n >= CTX_MAX || !url || !url[0])
  14106. return;
  14107. for (i = 0; i < ctx_n; i++)
  14108. if (ctx_action[i] == action && s_eq(ctx_url[i], url))
  14109. return;
  14110. s_copy(ctx_label[ctx_n], label, sizeof(ctx_label[0]));
  14111. s_copy(ctx_url[ctx_n], url, sizeof(ctx_url[0]));
  14112. ctx_action[ctx_n] = action;
  14113. ctx_n++;
  14114. }
  14115. static unsigned int ctx_ancestor_tag(unsigned int node, unsigned char tag)
  14116. {
  14117. unsigned int guard = 0;
  14118. while (node && node < doc.nnode && guard++ < BR_MAX_NODES) {
  14119. if (doc.nodes[node].type == BR_NODE_ELEM &&
  14120. doc.nodes[node].tag == tag)
  14121. return node;
  14122. node = doc.nodes[node].parent;
  14123. }
  14124. return 0;
  14125. }
  14126. static void ctx_open_at(struct ngui_rect page, int x, int y)
  14127. {
  14128. unsigned int hit = (unsigned int)find_hit(x, y);
  14129. unsigned int box = find_box_hit(x, y);
  14130. unsigned int img = 0;
  14131. char resolved[BR_URL_MAX];
  14132. const char *href;
  14133. ctx_open = 0;
  14134. ctx_n = 0;
  14135. if (box && doc.nodes[box].tag == BR_TAG_IMG)
  14136. img = box;
  14137. else if (hit && doc.nodes[hit].tag == BR_TAG_IMG)
  14138. img = hit;
  14139. else if (hit)
  14140. img = ctx_ancestor_tag(hit, BR_TAG_IMG);
  14141. if (!img && box)
  14142. img = ctx_ancestor_tag(box, BR_TAG_IMG);
  14143. if (img && br_src(&doc, img) &&
  14144. resolve_link(page_url, br_src(&doc, img), resolved,
  14145. sizeof(resolved)) == 0)
  14146. ctx_add(CTX_SAVE_IMAGE, "Save image", resolved);
  14147. /* A CSS background image is an image too; check the element under
  14148. * the pointer and then its ancestors (a card's image behind text). */
  14149. if (!img) {
  14150. unsigned int n = box ? box : hit, guard = 0;
  14151. while (n && n < doc.nnode && guard++ < BR_MAX_NODES) {
  14152. struct br_style st;
  14153. style_for_node(n, &st);
  14154. if (st.bg_image > 0) {
  14155. const char *bg = br_bg_image_url(st.bg_image - 1);
  14156. if (bg && resolve_link(page_url, bg, resolved,
  14157. sizeof(resolved)) == 0)
  14158. ctx_add(CTX_SAVE_IMAGE, "Save image",
  14159. resolved);
  14160. break;
  14161. }
  14162. n = doc.nodes[n].parent;
  14163. }
  14164. }
  14165. href = hit ? br_href(&doc, hit) : 0;
  14166. if (!href && box)
  14167. href = br_href(&doc, box);
  14168. if (href && resolve_link(page_url, href, resolved,
  14169. sizeof(resolved)) == 0)
  14170. ctx_add(CTX_SAVE_LINK, "Save link", resolved);
  14171. if (page_url[0] && !starts_with(page_url, "about:"))
  14172. ctx_add(CTX_SAVE_PAGE, "Save page", page_url);
  14173. if (!ctx_n)
  14174. return;
  14175. ctx_w = 190;
  14176. ctx_h = ctx_n * CTX_ROW_H + 2;
  14177. ctx_x = x;
  14178. ctx_y = y;
  14179. if (ctx_x + ctx_w > page.x + page.w - 4)
  14180. ctx_x = page.x + page.w - 4 - ctx_w;
  14181. if (ctx_y + ctx_h > page.y + page.h - 4)
  14182. ctx_y = page.y + page.h - 4 - ctx_h;
  14183. if (ctx_x < page.x + 4)
  14184. ctx_x = page.x + 4;
  14185. if (ctx_y < page.y + 4)
  14186. ctx_y = page.y + 4;
  14187. ctx_open = 1;
  14188. ngui_invalidate(&ui);
  14189. }
  14190. static void ctx_close(void)
  14191. {
  14192. if (!ctx_open)
  14193. return;
  14194. ctx_open = 0;
  14195. ngui_invalidate(&ui);
  14196. }
  14197. static void ctx_open_from_right(struct ngui_rect page)
  14198. {
  14199. if (!ui.right_pressed)
  14200. return;
  14201. if (ngui_rect_contains(&page, ui.right_press_x, ui.right_press_y)) {
  14202. dl_panel_open = 0;
  14203. ngui_set_focus(&ui, 0);
  14204. sug_close();
  14205. ctx_open_at(page, ui.right_press_x, ui.right_press_y);
  14206. } else {
  14207. ctx_close();
  14208. }
  14209. }
  14210. static void ctx_press(struct ngui_rect page)
  14211. {
  14212. struct ngui_rect r;
  14213. int row;
  14214. if (!ctx_open || !ui.pressed)
  14215. return;
  14216. r = (struct ngui_rect){ctx_x, ctx_y, ctx_w, ctx_h};
  14217. if (ngui_rect_contains(&r, ui.press_x, ui.press_y)) {
  14218. row = -1;
  14219. if (ui.press_y > ctx_y &&
  14220. ui.press_y < ctx_y + 1 + ctx_n * CTX_ROW_H)
  14221. row = (ui.press_y - ctx_y - 1) / CTX_ROW_H;
  14222. if (row >= 0 && row < ctx_n)
  14223. dl_queue(ctx_url[row]);
  14224. ctx_close();
  14225. ui.pressed = ui.released = 0;
  14226. return;
  14227. }
  14228. if (ngui_rect_contains(&page, ui.press_x, ui.press_y)) {
  14229. ctx_close();
  14230. ui.pressed = ui.released = 0;
  14231. return;
  14232. }
  14233. ctx_close();
  14234. }
  14235. static void draw_context(void)
  14236. {
  14237. struct ngui_rect r;
  14238. int i, hover = -1;
  14239. if (!ctx_open)
  14240. return;
  14241. r = (struct ngui_rect){ctx_x, ctx_y, ctx_w, ctx_h};
  14242. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  14243. if (ui.mouse_y > ctx_y &&
  14244. ui.mouse_y < ctx_y + 1 + ctx_n * CTX_ROW_H)
  14245. hover = (ui.mouse_y - ctx_y - 1) / CTX_ROW_H;
  14246. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  14247. }
  14248. ngui_fill_rect(&ui, r, ui.theme.border);
  14249. for (i = 0; i < ctx_n; i++) {
  14250. struct ngui_rect rr = {ctx_x + 1,
  14251. ctx_y + 1 + i * CTX_ROW_H, ctx_w - 2, CTX_ROW_H};
  14252. ngui_fill_rect(&ui, rr, i == hover ? ui.theme.selection :
  14253. ui.theme.panel);
  14254. ngui_text(&ui, rr.x + 10,
  14255. rr.y + (rr.h - ngui_text_line_height(&ui,
  14256. ui.font_px, 0)) / 2,
  14257. ctx_label[i], ui.theme.text);
  14258. }
  14259. }
  14260. /* The element under the pointer for hover events: the innermost laid-out
  14261. * box, or the link/control hit inside it (an inline <a> has no box of its
  14262. * own but a hit rectangle). -1 when none. */
  14263. static int hover_node = -1;
  14264. static int node_contains(unsigned int a, unsigned int n)
  14265. {
  14266. unsigned int guard = 0;
  14267. while (n < doc.nnode && guard++ < BR_MAX_NODES) {
  14268. if (n == a)
  14269. return 1;
  14270. if (n == 0)
  14271. return 0;
  14272. n = doc.nodes[n].parent;
  14273. }
  14274. return 0;
  14275. }
  14276. static int hover_target(void)
  14277. {
  14278. int h, x = ui.mouse_x, y = ui.mouse_y;
  14279. unsigned int b;
  14280. if (!ui.inside || ui.buttons || sug_visible() || ctx_open ||
  14281. dl_panel_open ||
  14282. x < page_rect.x || x >= page_rect.x + page_rect.w - 12 ||
  14283. y < page_rect.y || y >= page_rect.y + page_rect.h)
  14284. return -1;
  14285. h = find_hit(x, y);
  14286. b = find_box_hit(x, y);
  14287. if (h && (!b || node_contains(b, (unsigned int)h)))
  14288. return h;
  14289. if (b)
  14290. return (int)b;
  14291. return h ? h : -1;
  14292. }
  14293. /* mouseover/mouseout (bubbling, with relatedTarget) at the old and new
  14294. * element, and mouseleave/mouseenter on every ancestor that was left or
  14295. * entered (outermost first for enter), like a browser's boundary events.
  14296. * jQuery 1.11 builds its mouseenter (Bootstrap tooltips) from mouseover
  14297. * and relatedTarget. */
  14298. static void page_hover_events(void)
  14299. {
  14300. int now, old, cx, cy, path[64], np = 0, i;
  14301. unsigned int n;
  14302. if (!js_browser_active()) {
  14303. hover_node = -1;
  14304. return;
  14305. }
  14306. now = hover_target();
  14307. if (now >= (int)doc.nnode)
  14308. now = -1;
  14309. if (now == hover_node)
  14310. return;
  14311. old = hover_node;
  14312. if (old >= (int)doc.nnode)
  14313. old = -1;
  14314. hover_node = now;
  14315. cx = ui.mouse_x - page_rect.x;
  14316. cy = ui.mouse_y - page_rect.y;
  14317. if (old >= 0) {
  14318. js_browser_mouse_event((unsigned int)old, "mouseout", 1, now,
  14319. cx, cy);
  14320. for (n = (unsigned int)old, i = 0;
  14321. n < doc.nnode && i < 64 &&
  14322. !(now >= 0 && node_contains(n, (unsigned int)now)); i++) {
  14323. js_browser_mouse_event(n, "mouseleave", 0, now, cx, cy);
  14324. if (n == 0)
  14325. break;
  14326. n = doc.nodes[n].parent;
  14327. }
  14328. }
  14329. if (now < 0 || now >= (int)doc.nnode)
  14330. return;
  14331. js_browser_mouse_event((unsigned int)now, "mouseover", 1, old, cx, cy);
  14332. for (n = (unsigned int)now;
  14333. n < doc.nnode && np < 64 &&
  14334. !(old >= 0 && node_contains(n, (unsigned int)old));) {
  14335. path[np++] = (int)n;
  14336. if (n == 0)
  14337. break;
  14338. n = doc.nodes[n].parent;
  14339. }
  14340. for (i = np - 1; i >= 0; i--)
  14341. js_browser_mouse_event((unsigned int)path[i], "mouseenter", 0,
  14342. old, cx, cy);
  14343. }
  14344. static void handle_page_click(unsigned int *action)
  14345. {
  14346. int node;
  14347. char url[BR_URL_MAX];
  14348. if (!ui.pressed)
  14349. return;
  14350. if (ui.press_x < page_rect.x ||
  14351. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  14352. ui.press_y < page_rect.y ||
  14353. ui.press_y >= page_rect.y + page_rect.h)
  14354. return;
  14355. node = find_hit(ui.press_x, ui.press_y);
  14356. if (!node) {
  14357. unsigned int box;
  14358. if (!js_browser_active())
  14359. return;
  14360. box = find_box_hit(ui.press_x, ui.press_y);
  14361. if (box) {
  14362. form_blur();
  14363. js_browser_event(box, "click", 1, 1);
  14364. }
  14365. return;
  14366. }
  14367. if (form_is_control((unsigned int)node)) {
  14368. form_click((unsigned int)node);
  14369. return;
  14370. }
  14371. form_blur();
  14372. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  14373. return;
  14374. if (link_fragment_nav((unsigned int)node))
  14375. return;
  14376. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  14377. sizeof(url)) != 0)
  14378. return;
  14379. s_copy(click_url, url, sizeof(click_url));
  14380. *action |= ACT_NAV;
  14381. }
  14382. void _start(const char *arg)
  14383. {
  14384. struct win_info wi;
  14385. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  14386. u_win_create(960, 640, "Browser", &wi) != 0 &&
  14387. u_win_create(780, 540, "Browser", &wi) != 0) {
  14388. u_puts("browser: no graphics window\n");
  14389. u_exit(1);
  14390. }
  14391. ufont_set_arena_bytes(BR_FONT_ARENA);
  14392. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  14393. url_in.placeholder = "http://...";
  14394. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  14395. ui.theme.accent);
  14396. br_set_viewport(wi.width);
  14397. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  14398. s_copy(cwd, "/", sizeof(cwd));
  14399. heap_clear();
  14400. origin_cache_load();
  14401. css_cache_init();
  14402. script_cache_init();
  14403. font_cache_init();
  14404. persist_restore();
  14405. hist_load();
  14406. dl_load();
  14407. page_scroll.offset = 0;
  14408. page_scroll.content_h = 0;
  14409. if (arg && arg[0]) {
  14410. navigate(arg, 1);
  14411. } else {
  14412. load_home(1);
  14413. /* Start ready to type: keep the home page, but leave the address
  14414. * bar empty instead of showing "about:home". */
  14415. ngui_input_set(&url_in, "");
  14416. ngui_set_focus(&ui, ID_URL);
  14417. }
  14418. for (;;) {
  14419. unsigned int action = 0;
  14420. unsigned int now;
  14421. click_url[0] = '\0';
  14422. if (pending_action) {
  14423. action |= pending_action & ACT_WAIT_NAV;
  14424. if (pending_url[0])
  14425. s_copy(click_url, pending_url, sizeof(click_url));
  14426. pending_action = 0;
  14427. pending_url[0] = '\0';
  14428. cancel_fetch = 0;
  14429. } else if (preload_active) {
  14430. if (preload_wait)
  14431. preload_wait = 0;
  14432. else
  14433. preload_step();
  14434. } else if ((preload_pending &&
  14435. page_scroll.offset != preload_scroll) ||
  14436. (preload_rescan && layout_valid)) {
  14437. preload_scroll = page_scroll.offset;
  14438. preload_rescan = 0;
  14439. preload_pending = 0;
  14440. preload_node = 0;
  14441. preload_active = 1;
  14442. }
  14443. js_force_layout_pass_reset();
  14444. js_browser_tick();
  14445. if (resize_pending && !pending_action) {
  14446. resize_pending = 0;
  14447. resize_sent_w = layout_right - layout_left;
  14448. js_browser_window_event("resize");
  14449. }
  14450. persist_tick();
  14451. dl_poll();
  14452. if (pending_action)
  14453. continue;
  14454. now = u_ticks_ms();
  14455. if (status_until && (int)(now - status_until) >= 0) {
  14456. status_text[0] = '\0';
  14457. status_until = 0;
  14458. status_error = 0;
  14459. ngui_invalidate(&ui);
  14460. }
  14461. if (!ngui_begin(&ui)) {
  14462. /* A queued navigation (e.g. Enter in the URL bar during
  14463. * a slow fetch) must be handled even when this frame
  14464. * needs no redraw. */
  14465. if (!action) {
  14466. fetch_workers_stop_if_unfocused();
  14467. u_sleep_ms(10);
  14468. continue;
  14469. }
  14470. } else {
  14471. js_force_layout_pass_reset();
  14472. draw(&action);
  14473. handle_keys(&action);
  14474. handle_page_click(&action);
  14475. page_hover_events();
  14476. anim_after_frame();
  14477. ngui_end(&ui);
  14478. }
  14479. if (action & ACT_NAV) {
  14480. if (click_url[0]) {
  14481. navigate(click_url, 1);
  14482. click_url[0] = '\0';
  14483. } else {
  14484. navigate(url_in.text, 1);
  14485. }
  14486. }
  14487. if (action & ACT_BACK) {
  14488. if (hist_pos > 0) {
  14489. hist_pos--;
  14490. if (same_doc_fragment(history[hist_pos])) {
  14491. page_set_fragment(history[hist_pos], 0);
  14492. js_browser_hashchange();
  14493. } else {
  14494. navigate(history[hist_pos], 0);
  14495. }
  14496. }
  14497. }
  14498. if (action & ACT_FORWARD) {
  14499. if (hist_pos + 1 < hist_len) {
  14500. hist_pos++;
  14501. if (same_doc_fragment(history[hist_pos])) {
  14502. page_set_fragment(history[hist_pos], 0);
  14503. js_browser_hashchange();
  14504. } else {
  14505. navigate(history[hist_pos], 0);
  14506. }
  14507. }
  14508. }
  14509. if (action & ACT_RELOAD) {
  14510. if (s_eq(page_url, "about:home"))
  14511. load_home(0);
  14512. else
  14513. navigate(page_url, 0);
  14514. }
  14515. if (action & ACT_HOME)
  14516. load_home(1);
  14517. if (action & ACT_CLOSE)
  14518. quit = 1;
  14519. if (quit)
  14520. break;
  14521. if (pending_action)
  14522. continue;
  14523. fetch_workers_stop_if_unfocused();
  14524. u_sleep_ms(10);
  14525. }
  14526. fetch_workers_stop_all();
  14527. fetch_worker_stop(&dl_worker);
  14528. u_win_close();
  14529. u_exit(0);
  14530. }