browser.c 417 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679
  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(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. static void layout_table_row(struct lay *l, unsigned int row,
  11452. const struct br_style *pst, int depth,
  11453. unsigned short link)
  11454. {
  11455. unsigned int n, cell[12];
  11456. int raw[12], colstart[12], colspan[12];
  11457. int prefix[13];
  11458. int ncell = 0, total = 0, cols = 0, col = 0;
  11459. int row_left = l->left, row_right = l->right;
  11460. int avail = row_right - row_left;
  11461. int y = l->y, bottom = l->y;
  11462. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  11463. struct br_node *nd = &doc.nodes[n];
  11464. struct br_style cs;
  11465. int span;
  11466. if (nd->type == BR_NODE_TEXT) {
  11467. if (text_node_blank(nd))
  11468. continue;
  11469. layout_children(l, row, pst, depth, link);
  11470. return;
  11471. }
  11472. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  11473. layout_children(l, row, pst, depth, link);
  11474. return;
  11475. }
  11476. br_style_for(&doc, n, pst, &cs);
  11477. if (cs.display == BR_DISPLAY_NONE)
  11478. continue;
  11479. if (ncell >= 12) {
  11480. layout_children(l, row, pst, depth, link);
  11481. return;
  11482. }
  11483. span = nd->colspan ? nd->colspan : 1;
  11484. if (span > 12 - col)
  11485. span = 12 - col;
  11486. if (span < 1)
  11487. continue;
  11488. cell[ncell] = n;
  11489. colstart[ncell] = col;
  11490. colspan[ncell] = span;
  11491. col += span;
  11492. ncell++;
  11493. }
  11494. if (ncell < 1 || avail < 32) {
  11495. layout_children(l, row, pst, depth, link);
  11496. return;
  11497. }
  11498. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  11499. &total);
  11500. if (cols < 2 || total <= 0) {
  11501. int c;
  11502. total = 0;
  11503. for (c = 0; c < ncell; c++) {
  11504. struct br_style cs;
  11505. br_style_for(&doc, cell[c], pst, &cs);
  11506. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  11507. avail) +
  11508. mp_px(&cs, 7, avail) +
  11509. mp_px(&cs, 5, avail) +
  11510. mp_px(&cs, 3, avail) +
  11511. mp_px(&cs, 1, avail);
  11512. if (raw[c] < 24)
  11513. raw[c] = 24;
  11514. total += raw[c];
  11515. }
  11516. /* A one-column table still has to fill its own width; the
  11517. * intrinsic fallback above otherwise leaves the cell at its
  11518. * text width (HN's outer table and nested story table). */
  11519. if (total > 0 && total < avail) {
  11520. int c;
  11521. for (c = 0; c < ncell; c++)
  11522. raw[c] = raw[c] * avail / total;
  11523. total = avail;
  11524. }
  11525. }
  11526. prefix[0] = row_left;
  11527. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  11528. prefix[n + 1] = prefix[n] + raw[n];
  11529. for (n = 0; n < (unsigned int)ncell; n++) {
  11530. struct br_style cs;
  11531. int start = colstart[n];
  11532. int end = start + colspan[n];
  11533. int w;
  11534. if (end > cols)
  11535. end = cols;
  11536. if (start >= cols)
  11537. continue;
  11538. w = prefix[end] - prefix[start];
  11539. br_style_for(&doc, cell[n], pst, &cs);
  11540. /* The column width already reflects the cell's width property. */
  11541. cs.width_kind = 0;
  11542. cs.max_width_kind = 0;
  11543. if (w < 24)
  11544. w = 24;
  11545. if (w < 8)
  11546. w = 8;
  11547. l->left = prefix[start];
  11548. l->right = l->left + w;
  11549. l->y = y;
  11550. l->line_left = l->line_x = l->left;
  11551. l->run_x = l->left;
  11552. l->line_y = l->y;
  11553. l->line_h = 0;
  11554. l->nruns = 0;
  11555. l->space_pending = 0;
  11556. l->align = cs.align;
  11557. layout_block(l, cell[n], &cs, depth + 1, link);
  11558. if (l->y > bottom)
  11559. bottom = l->y;
  11560. }
  11561. l->left = row_left;
  11562. l->right = row_right;
  11563. l->y = bottom;
  11564. l->line_left = l->line_x = l->left;
  11565. l->run_x = l->left;
  11566. l->line_y = l->y;
  11567. l->line_h = 0;
  11568. l->nruns = 0;
  11569. l->space_pending = 0;
  11570. }
  11571. #define TBL_MAX_ROWS 32
  11572. #define TBL_MAX_COLS 12
  11573. #define TBL_MAX_CELLS 128
  11574. struct tbl_cell {
  11575. unsigned int node;
  11576. unsigned char row, col, rowspan, colspan;
  11577. int height;
  11578. };
  11579. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  11580. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  11581. static int table_active;
  11582. static int table_has_rowspan(unsigned int table)
  11583. {
  11584. unsigned int r, c;
  11585. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  11586. struct br_node *rn = &doc.nodes[r];
  11587. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  11588. continue;
  11589. for (c = rn->first; c; c = doc.nodes[c].next) {
  11590. struct br_node *cn = &doc.nodes[c];
  11591. if (cn->type == BR_NODE_ELEM &&
  11592. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  11593. cn->rowspan > 1)
  11594. return 1;
  11595. }
  11596. }
  11597. return 0;
  11598. }
  11599. static void table_cell_style(unsigned int row, unsigned int cell,
  11600. const struct br_style *st, struct br_style *out)
  11601. {
  11602. struct br_style trs;
  11603. br_style_for(&doc, row, st, &trs);
  11604. br_style_for(&doc, cell, &trs, out);
  11605. }
  11606. /* Tables that use rowspan need row heights before anything is painted. This
  11607. * path builds a small occupancy grid, measures the natural cell heights, then
  11608. * lays every cell out at its row/column position. Tables without rowspan
  11609. * keep the lighter per-row path in layout_table_row(). */
  11610. static void layout_table(struct lay *l, unsigned int table,
  11611. const struct br_style *st, int depth,
  11612. unsigned short link)
  11613. {
  11614. unsigned int rows[TBL_MAX_ROWS];
  11615. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  11616. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  11617. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  11618. int free_raw = 0, free_cols = 0;
  11619. int table_left = l->left, table_right = l->right;
  11620. int top = l->y, avail = table_right - table_left;
  11621. unsigned int r, c;
  11622. int i, rr, cc;
  11623. if (depth > 48 || table_active) {
  11624. layout_children(l, table, st, depth, link);
  11625. return;
  11626. }
  11627. table_active = 1;
  11628. for (r = doc.nodes[table].first;
  11629. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  11630. struct br_node *rn = &doc.nodes[r];
  11631. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  11632. rows[nrows++] = r;
  11633. }
  11634. if (!nrows) {
  11635. table_active = 0;
  11636. layout_children(l, table, st, depth, link);
  11637. return;
  11638. }
  11639. for (rr = 0; rr < nrows; rr++)
  11640. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  11641. tbl_at[rr][cc] = 0;
  11642. for (rr = 0; rr < nrows; rr++) {
  11643. int col = 0;
  11644. for (c = doc.nodes[rows[rr]].first; c;
  11645. c = doc.nodes[c].next) {
  11646. struct br_node *cn = &doc.nodes[c];
  11647. struct br_style cs;
  11648. int rs, csn;
  11649. if (cn->type != BR_NODE_ELEM ||
  11650. (cn->tag != BR_TAG_TD &&
  11651. cn->tag != BR_TAG_TH))
  11652. continue;
  11653. table_cell_style(rows[rr], c, st, &cs);
  11654. if (cs.display == BR_DISPLAY_NONE)
  11655. continue;
  11656. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  11657. col++;
  11658. if (col >= TBL_MAX_COLS)
  11659. break;
  11660. rs = cn->rowspan ? cn->rowspan : 1;
  11661. csn = cn->colspan ? cn->colspan : 1;
  11662. if (rr + rs > nrows)
  11663. rs = nrows - rr;
  11664. if (col + csn > TBL_MAX_COLS)
  11665. csn = TBL_MAX_COLS - col;
  11666. if (rs < 1 || csn < 1)
  11667. continue;
  11668. if (ncells >= TBL_MAX_CELLS)
  11669. break;
  11670. tbl_cells[ncells].node = c;
  11671. tbl_cells[ncells].row = (unsigned char)rr;
  11672. tbl_cells[ncells].col = (unsigned char)col;
  11673. tbl_cells[ncells].rowspan = (unsigned char)rs;
  11674. tbl_cells[ncells].colspan = (unsigned char)csn;
  11675. tbl_cells[ncells].height = 0;
  11676. for (i = rr; i < rr + rs; i++)
  11677. for (int j = col; j < col + csn; j++)
  11678. tbl_at[i][j] =
  11679. (unsigned short)(ncells + 1);
  11680. ncells++;
  11681. col += csn;
  11682. if (col > cols)
  11683. cols = col;
  11684. }
  11685. }
  11686. if (!ncells || cols < 1) {
  11687. table_active = 0;
  11688. layout_children(l, table, st, depth, link);
  11689. return;
  11690. }
  11691. for (i = 0; i < cols; i++) {
  11692. raw[i] = 0;
  11693. fixed[i] = 0;
  11694. }
  11695. /* Intrinsic widths of single-column cells. */
  11696. for (i = 0; i < ncells; i++) {
  11697. struct br_style cs;
  11698. int w;
  11699. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  11700. st, &cs);
  11701. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  11702. mp_px(&cs, 7, avail) +
  11703. mp_px(&cs, 5, avail) +
  11704. mp_px(&cs, 3, avail) +
  11705. mp_px(&cs, 1, avail) +
  11706. cs.border_w[0] + cs.border_w[1] +
  11707. cs.border_w[2] + cs.border_w[3];
  11708. if (w < 24)
  11709. w = 24;
  11710. if (tbl_cells[i].colspan == 1) {
  11711. int col = tbl_cells[i].col;
  11712. if (w > raw[col])
  11713. raw[col] = w;
  11714. }
  11715. }
  11716. /* A spanning cell only needs the sum of its columns to be large
  11717. * enough; put the deficit in the last column. */
  11718. for (i = 0; i < ncells; i++) {
  11719. struct br_style cs;
  11720. int w, sum, col, span;
  11721. if (tbl_cells[i].colspan < 2)
  11722. continue;
  11723. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  11724. st, &cs);
  11725. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  11726. mp_px(&cs, 7, avail) +
  11727. mp_px(&cs, 5, avail) +
  11728. mp_px(&cs, 3, avail) +
  11729. mp_px(&cs, 1, avail) +
  11730. cs.border_w[0] + cs.border_w[1] +
  11731. cs.border_w[2] + cs.border_w[3];
  11732. col = tbl_cells[i].col;
  11733. span = tbl_cells[i].colspan;
  11734. sum = 0;
  11735. for (int j = 0; j < span; j++)
  11736. sum += raw[col + j];
  11737. if (w > sum)
  11738. raw[col + span - 1] += w - sum;
  11739. }
  11740. /* Explicit/percentage widths, as in table_columns(). */
  11741. for (i = 0; i < ncells; i++) {
  11742. struct br_style cs;
  11743. int col;
  11744. if (tbl_cells[i].colspan != 1)
  11745. continue;
  11746. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  11747. st, &cs);
  11748. col = tbl_cells[i].col;
  11749. if (cs.width_kind == 1) {
  11750. raw[col] = cs.width;
  11751. fixed[col] = 1;
  11752. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  11753. raw[col] = style_width_px(&cs, avail);
  11754. fixed[col] = 1;
  11755. }
  11756. }
  11757. for (i = 0; i < cols; i++) {
  11758. if (raw[i] < 8)
  11759. raw[i] = 8;
  11760. total += raw[i];
  11761. if (fixed[i])
  11762. fixed_sum += raw[i];
  11763. else {
  11764. free_raw += raw[i];
  11765. free_cols++;
  11766. }
  11767. }
  11768. if (fixed_sum > 0 && fixed_sum < avail) {
  11769. int free_avail = avail - fixed_sum;
  11770. if (free_raw > 0) {
  11771. for (i = 0; i < cols; i++)
  11772. if (!fixed[i])
  11773. raw[i] = free_avail * raw[i] /
  11774. free_raw;
  11775. } else if (free_cols > 0) {
  11776. for (i = 0; i < cols; i++)
  11777. if (!fixed[i])
  11778. raw[i] = free_avail / free_cols;
  11779. }
  11780. } else if (total < avail && total > 0) {
  11781. for (i = 0; i < cols; i++)
  11782. raw[i] = raw[i] * avail / total;
  11783. }
  11784. prefix[0] = table_left;
  11785. for (i = 0; i < cols; i++)
  11786. prefix[i + 1] = prefix[i] + raw[i];
  11787. /* Measure natural cell heights with the column widths. */
  11788. for (i = 0; i < ncells; i++) {
  11789. struct br_style cs;
  11790. int col = tbl_cells[i].col;
  11791. int span = tbl_cells[i].colspan;
  11792. int w = prefix[col + span] - prefix[col];
  11793. int sl = l->left, sr = l->right, sy = l->y;
  11794. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  11795. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  11796. int sal = l->align, sdraw = l->draw;
  11797. struct ngui *sui = l->ui;
  11798. if (w < 8)
  11799. w = 8;
  11800. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  11801. st, &cs);
  11802. cs.width_kind = 0;
  11803. cs.max_width_kind = 0;
  11804. l->draw = 0;
  11805. l->ui = 0;
  11806. l->left = prefix[col];
  11807. l->right = l->left + w;
  11808. l->y = 0;
  11809. l->line_left = l->line_x = l->left;
  11810. l->run_x = l->left;
  11811. l->line_y = 0;
  11812. l->line_h = 0;
  11813. l->nruns = 0;
  11814. l->space_pending = 0;
  11815. l->align = cs.align;
  11816. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  11817. tbl_cells[i].height = block_h[tbl_cells[i].node];
  11818. l->left = sl;
  11819. l->right = sr;
  11820. l->y = sy;
  11821. l->line_x = slx;
  11822. l->run_x = srx;
  11823. l->line_y = sly;
  11824. l->line_h = slh;
  11825. l->nruns = snr;
  11826. l->space_pending = ssp;
  11827. l->align = sal;
  11828. l->draw = sdraw;
  11829. l->ui = sui;
  11830. }
  11831. for (i = 0; i < nrows; i++)
  11832. rowh[i] = 0;
  11833. for (i = 0; i < ncells; i++) {
  11834. int row = tbl_cells[i].row;
  11835. if (tbl_cells[i].rowspan == 1) {
  11836. if (tbl_cells[i].height > rowh[row])
  11837. rowh[row] = tbl_cells[i].height;
  11838. }
  11839. }
  11840. for (i = 0; i < ncells; i++) {
  11841. int row = tbl_cells[i].row;
  11842. int span = tbl_cells[i].rowspan;
  11843. int sum = 0;
  11844. if (span < 2)
  11845. continue;
  11846. for (int j = 0; j < span; j++)
  11847. sum += rowh[row + j];
  11848. if (sum < tbl_cells[i].height)
  11849. rowh[row + span - 1] +=
  11850. tbl_cells[i].height - sum;
  11851. }
  11852. for (i = 0; i < nrows; i++)
  11853. if (rowh[i] < 8)
  11854. rowh[i] = 8;
  11855. rowy[0] = top;
  11856. for (i = 1; i < nrows; i++)
  11857. rowy[i] = rowy[i - 1] + rowh[i - 1];
  11858. if (!l->draw) {
  11859. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  11860. table_active = 0;
  11861. return;
  11862. }
  11863. for (i = 0; i < ncells; i++) {
  11864. struct br_style cs;
  11865. int col = tbl_cells[i].col;
  11866. int span = tbl_cells[i].colspan;
  11867. int row = tbl_cells[i].row;
  11868. int rspan = tbl_cells[i].rowspan;
  11869. int w = prefix[col + span] - prefix[col];
  11870. int h = 0;
  11871. int sl = l->left, sr = l->right, sy = l->y;
  11872. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  11873. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  11874. int sal = l->align;
  11875. int deco;
  11876. for (int j = 0; j < rspan; j++)
  11877. h += rowh[row + j];
  11878. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  11879. cs.width_kind = 0;
  11880. cs.max_width_kind = 0;
  11881. cs.box_sizing = 0;
  11882. deco = mp_px(&cs, 4, avail) +
  11883. mp_px(&cs, 6, avail) +
  11884. cs.border_w[0] + cs.border_w[2];
  11885. cs.height_kind = 1;
  11886. cs.height = h > deco ? h - deco : 0;
  11887. /* The block painter reads block_h[] from the measure pass; make
  11888. * the table cell fill its row/rowspan, not just its content. */
  11889. if (h > 0 && h < 65536)
  11890. block_h[tbl_cells[i].node] = (unsigned short)h;
  11891. l->left = prefix[col];
  11892. l->right = l->left + w;
  11893. l->y = rowy[row];
  11894. l->line_left = l->line_x = l->left;
  11895. l->run_x = l->left;
  11896. l->line_y = l->y;
  11897. l->line_h = 0;
  11898. l->nruns = 0;
  11899. l->space_pending = 0;
  11900. l->align = cs.align;
  11901. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  11902. l->left = sl;
  11903. l->right = sr;
  11904. l->y = sy;
  11905. l->line_x = slx;
  11906. l->run_x = srx;
  11907. l->line_y = sly;
  11908. l->line_h = slh;
  11909. l->nruns = snr;
  11910. l->space_pending = ssp;
  11911. l->align = sal;
  11912. }
  11913. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  11914. table_active = 0;
  11915. }
  11916. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  11917. * flow so they sit above it, like CSS painting order. Their flow origin is
  11918. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  11919. struct br_deferred {
  11920. unsigned int node;
  11921. int flow_y, flow_left, flow_right;
  11922. int parent_top; /* the parent box top, for sticky clamping */
  11923. unsigned short link;
  11924. signed short z_index;
  11925. unsigned char z_set;
  11926. unsigned int order;
  11927. };
  11928. /* Positioned boxes painted after the flow. News front pages have one or two
  11929. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  11930. * old 16 entries the rest fell back into the flow, so a hero image landed
  11931. * below its padding-top aspect box instead of on top of it. */
  11932. #define BR_MAX_DEFERRED 256
  11933. static struct br_deferred deferred[BR_MAX_DEFERRED];
  11934. static int ndeferred;
  11935. /* Outer width of an element's empty ::before (pe 1) / ::after (pe 2) icon
  11936. * box, 0 when it has none; *ps receives the pseudo-element's style. */
  11937. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  11938. struct br_style *ps, int base)
  11939. {
  11940. char buf[8];
  11941. int w, h;
  11942. if (!doc.npe_rules ||
  11943. br_pseudo(&doc, node, pe, st, ps, buf, sizeof(buf)) ||
  11944. ps->content != BR_CONTENT_EMPTY || ps->display == BR_DISPLAY_NONE)
  11945. return 0;
  11946. w = ps->width_kind ? style_width_px(ps, base) : 0;
  11947. h = ps->height_kind ? style_height_px(ps, base) : 0;
  11948. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  11949. w = (int)ps->min_width;
  11950. if (w <= 0)
  11951. w = h;
  11952. if (w <= 0 || w > 512)
  11953. return 0;
  11954. return w + (ps->ml_auto ? 0 : mp_px(ps, 3, base)) + mp_px(ps, 1, base);
  11955. }
  11956. /* An empty ::before/::after with a size and a background: one run the
  11957. * size of the box. Only data: background images are drawn (decoded at
  11958. * the background-size); `margin-left: auto` inside a flex parent pushes
  11959. * the box to the line's right edge like the flex row would. */
  11960. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  11961. const struct br_style *ps, unsigned short link)
  11962. {
  11963. struct lay_run *r;
  11964. int lw = l->line_right - l->line_left, w, h, ml, mr, tw, th;
  11965. const char *url = ps->bg_image ? br_bg_image_url(ps->bg_image - 1) : "";
  11966. if (lw < 8)
  11967. lw = 8;
  11968. w = ps->width_kind ? style_width_px(ps, lw) : 0;
  11969. h = ps->height_kind ? style_height_px(ps, lw) : 0;
  11970. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  11971. w = (int)ps->min_width;
  11972. if (w <= 0)
  11973. w = h;
  11974. if (h <= 0)
  11975. h = w;
  11976. if (w <= 0 || w > 512 || h > 512)
  11977. return;
  11978. ml = ps->ml_auto ? 0 : mp_px(ps, 3, lw);
  11979. mr = mp_px(ps, 1, lw);
  11980. if (ml < 0)
  11981. ml = 0;
  11982. if (mr < 0)
  11983. mr = 0;
  11984. if (l->line_x + ml + w > l->line_right &&
  11985. (l->nruns > 0 || l->line_x > l->line_left))
  11986. flush_line(l);
  11987. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  11988. flush_line(l);
  11989. if (l->nruns == 0) {
  11990. l->line_y = l->y;
  11991. l->line_h = 0;
  11992. start_line(l, ps);
  11993. }
  11994. if (ps->ml_auto && parent->display == BR_DISPLAY_FLEX &&
  11995. l->line_right - w - mr > l->line_x)
  11996. l->line_x = l->line_right - w - mr;
  11997. else
  11998. l->line_x += ml;
  11999. r = &l->runs[l->nruns++];
  12000. memset(r, 0, sizeof(*r));
  12001. r->box = l->box_owner;
  12002. r->gap = (unsigned short)(l->line_x > l->run_x ?
  12003. l->line_x - l->run_x : 0);
  12004. r->img = RUN_PBOX;
  12005. r->href = link;
  12006. r->iw = (unsigned short)w;
  12007. r->ih = (unsigned short)h;
  12008. r->w = (unsigned short)w;
  12009. r->font_px = ps->font_px;
  12010. r->pb_has_bg = ps->has_bg;
  12011. r->pb_bg = ps->bg;
  12012. r->pb_img = -1;
  12013. if (ps->transform_set) {
  12014. r->transform_scale = 1;
  12015. r->scale_x = ps->scale_x;
  12016. r->scale_y = ps->scale_y;
  12017. r->rotate_x100 = ps->rotate_x100;
  12018. }
  12019. /* Background size and position, as draw_bg_image() resolves them. */
  12020. tw = w;
  12021. th = h;
  12022. if (ps->bg_size_kind == 1 || ps->bg_size_kind == 2) {
  12023. int bw = ps->bg_size_w, bh = ps->bg_size_h;
  12024. if (ps->bg_size_kind == 2) {
  12025. bw = bw ? w * bw / 100 : 0;
  12026. bh = bh ? h * bh / 100 : 0;
  12027. }
  12028. tw = bw ? bw : (bh ? bh : w);
  12029. th = bh ? bh : tw;
  12030. }
  12031. if (tw > 0 && th > 0 && tw <= 512 && th <= 512 && url[0])
  12032. r->pb_img = (short)data_url_image(url, tw, th);
  12033. r->pb_w = (short)tw;
  12034. r->pb_h = (short)th;
  12035. r->pb_x = (short)(ps->bg_pos_x_kind == 1 ?
  12036. (w - tw) * ps->bg_pos_x / 100 : ps->bg_pos_x);
  12037. r->pb_y = (short)(ps->bg_pos_y_kind == 1 ?
  12038. (h - th) * ps->bg_pos_y / 100 : ps->bg_pos_y);
  12039. l->line_x += w + mr;
  12040. l->run_x = l->line_x;
  12041. if (l->line_h < h)
  12042. l->line_h = h;
  12043. }
  12044. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  12045. * element's line. A block-level pseudo-element gets its own line; its box
  12046. * (margins, padding, background) is not drawn. */
  12047. static void emit_pseudo(struct lay *l, unsigned int node,
  12048. const struct br_style *st, int pe, unsigned short link)
  12049. {
  12050. char buf[160];
  12051. struct br_style ps;
  12052. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  12053. unsigned int i = 0;
  12054. int block, space_w;
  12055. if (!n && ps.content == BR_CONTENT_EMPTY &&
  12056. ps.display != BR_DISPLAY_NONE) {
  12057. emit_pseudo_box(l, st, &ps, link);
  12058. return;
  12059. }
  12060. if (!n)
  12061. return;
  12062. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  12063. if (block)
  12064. flush_line(l);
  12065. if (ps.uppercase)
  12066. for (i = 0; i < n; i++)
  12067. if (buf[i] >= 'a' && buf[i] <= 'z')
  12068. buf[i] = (char)(buf[i] - 'a' + 'A');
  12069. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  12070. if (space_w <= 0)
  12071. space_w = 8;
  12072. i = 0;
  12073. while (i < n) {
  12074. char word[28];
  12075. unsigned int k = 0;
  12076. int w;
  12077. if (buf[i] == ' ') {
  12078. l->space_pending = 1;
  12079. i++;
  12080. continue;
  12081. }
  12082. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  12083. word[k++] = buf[i++];
  12084. word[k] = '\0';
  12085. if (l->space_pending &&
  12086. (l->nruns > 0 || l->line_x > l->line_left) &&
  12087. l->line_x + space_w <= l->line_right)
  12088. l->line_x += space_w;
  12089. l->space_pending = 0;
  12090. w = (int)face_text_width(l->ui, &ps, word, k);
  12091. if (l->line_x + w > l->line_right &&
  12092. (l->nruns > 0 || l->line_x > l->line_left))
  12093. flush_line(l);
  12094. add_run(l, 0, 0, &ps, link, word);
  12095. }
  12096. if (block)
  12097. flush_line(l);
  12098. }
  12099. /* An out-of-flow child (absolute/fixed, or a relative/sticky box with a
  12100. * z-index): measured in place, painted from the deferred stacked pass
  12101. * against its containing block. Shared by block and flex layout, so an
  12102. * absolute icon inside a flex row (a password field's reveal button) is
  12103. * not laid out as one of the row's items. Returns 1 when it handled n. */
  12104. static int layout_out_of_flow(struct lay *l, unsigned int n,
  12105. const struct br_style *cs, int depth,
  12106. unsigned short lk)
  12107. {
  12108. if (!(cs->pos == 1 || cs->pos == 2 ||
  12109. ((cs->pos == 3 || cs->pos == 4) && cs->z_set)))
  12110. return 0;
  12111. if ((cs->pos == 3 || cs->pos == 4) && l->draw &&
  12112. ndeferred < BR_MAX_DEFERRED) {
  12113. /* Relative or sticky z-index (a sticky site
  12114. * header): measure and advance the flow without
  12115. * painting, then paint it in the deferred
  12116. * (stacked) pass, above the content after it. */
  12117. int fy = l->y, fl = l->left, fr = l->right;
  12118. int save_draw = l->draw;
  12119. l->draw = 0;
  12120. layout_block(l, n, cs, depth + 1, lk);
  12121. l->draw = save_draw;
  12122. deferred[ndeferred].node = n;
  12123. deferred[ndeferred].parent_top = l->parent_top;
  12124. deferred[ndeferred].flow_y = fy;
  12125. deferred[ndeferred].flow_left = fl;
  12126. deferred[ndeferred].flow_right = fr;
  12127. deferred[ndeferred].link = lk;
  12128. deferred[ndeferred].z_index = cs->z_index;
  12129. deferred[ndeferred].z_set = cs->z_set;
  12130. deferred[ndeferred].order = (unsigned int)ndeferred;
  12131. ndeferred++;
  12132. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  12133. deferred[ndeferred].node = n;
  12134. deferred[ndeferred].parent_top = l->parent_top;
  12135. deferred[ndeferred].flow_y =
  12136. cs->pos == 1 ? l->cb_top : l->y;
  12137. deferred[ndeferred].flow_left =
  12138. cs->pos == 1 ? l->cb_left : l->left;
  12139. deferred[ndeferred].flow_right =
  12140. cs->pos == 1 ? l->cb_right : l->right;
  12141. deferred[ndeferred].link = lk;
  12142. deferred[ndeferred].z_index = cs->z_index;
  12143. deferred[ndeferred].z_set = cs->z_set;
  12144. deferred[ndeferred].order = (unsigned int)ndeferred;
  12145. ndeferred++;
  12146. } else if (l->draw && cs->pos == 1) {
  12147. /* Deferred list full: paint in place, but still
  12148. * against the containing block, not the flow. */
  12149. int fy = l->y, fl = l->left, fr = l->right;
  12150. l->y = l->cb_top;
  12151. l->left = l->cb_left;
  12152. l->right = l->cb_right;
  12153. layout_block(l, n, cs, depth + 1, lk);
  12154. l->y = fy;
  12155. l->left = fl;
  12156. l->right = fr;
  12157. } else {
  12158. layout_block(l, n, cs, depth + 1, lk);
  12159. }
  12160. if (cs->pos == 1 && block_h[n] &&
  12161. doc.nodes[n].class_off) {
  12162. const char *cl = doc.attrs +
  12163. doc.nodes[n].class_off;
  12164. if ((contains_ci(cl, "poster-wrapper") ||
  12165. contains_ci(cl, "ts-picture")) &&
  12166. !has_skeleton_sibling(n))
  12167. l->y += block_h[n];
  12168. }
  12169. return 1;
  12170. }
  12171. /* An element laid out in the text line (an inline span, or an inline-block
  12172. * that flows like one): its runs are tagged with it, so flush_line() can
  12173. * record its box for getBoundingClientRect() and click targeting. */
  12174. static void layout_inline_box(struct lay *l, unsigned int node,
  12175. const struct br_style *cs, int depth,
  12176. unsigned short link)
  12177. {
  12178. unsigned short saved = l->box_owner;
  12179. if (node < BR_MAX_NODES) {
  12180. inline_box_parent[node] = saved;
  12181. l->box_owner = (unsigned short)(node + 1);
  12182. }
  12183. layout_children(l, node, cs, depth + 1, link);
  12184. l->box_owner = saved;
  12185. }
  12186. static void layout_children(struct lay *l, unsigned int parent,
  12187. const struct br_style *pst, int depth,
  12188. unsigned short link)
  12189. {
  12190. unsigned int n;
  12191. if (depth > 48)
  12192. return;
  12193. emit_pseudo(l, parent, pst, 1, link);
  12194. n = doc.nodes[parent].first;
  12195. while (n) {
  12196. struct br_node *nd = &doc.nodes[n];
  12197. struct br_style cs;
  12198. unsigned short lk = link;
  12199. if (nd->type == BR_NODE_TEXT) {
  12200. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  12201. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  12202. n = nd->next;
  12203. continue;
  12204. }
  12205. br_style_for(&doc, n, pst, &cs);
  12206. if (cs.display == BR_DISPLAY_NONE) {
  12207. n = nd->next;
  12208. continue;
  12209. }
  12210. if (cs.clear && l->float_active) {
  12211. flush_line(l);
  12212. if (l->y < l->float_bottom)
  12213. l->y = l->float_bottom;
  12214. l->float_active = 0;
  12215. l->line_x = l->left;
  12216. l->run_x = l->left;
  12217. l->line_left = l->left;
  12218. l->line_right = l->right;
  12219. l->line_y = l->y;
  12220. l->line_h = 0;
  12221. l->nruns = 0;
  12222. l->space_pending = 0;
  12223. }
  12224. if (nd->tag == BR_TAG_A && nd->href_off)
  12225. lk = (unsigned short)n;
  12226. if (layout_out_of_flow(l, n, &cs, depth, lk)) {
  12227. n = nd->next;
  12228. continue;
  12229. }
  12230. if (nd->tag == BR_TAG_BR) {
  12231. flush_line(l);
  12232. n = nd->next;
  12233. continue;
  12234. }
  12235. if (nd->tag == BR_TAG_HR) {
  12236. flush_line(l);
  12237. if (l->draw)
  12238. ngui_fill_rect(l->ui,
  12239. (struct ngui_rect){l->left, l->y + 2,
  12240. l->right - l->left, 1}, BR_GRAY);
  12241. l->y += 8;
  12242. n = nd->next;
  12243. continue;
  12244. }
  12245. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  12246. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  12247. !button_has_elements(n)) {
  12248. if (!(nd->tag == BR_TAG_INPUT &&
  12249. s_eq(br_type(&doc, n), "hidden"))) {
  12250. form_fill_line = pst->display ==
  12251. BR_DISPLAY_FLEX &&
  12252. pst->flex_col;
  12253. add_form_run(l, n, &cs, lk);
  12254. form_fill_line = 0;
  12255. }
  12256. n = nd->next;
  12257. continue;
  12258. }
  12259. if (nd->tag == BR_TAG_IMG) {
  12260. add_image_run(l, n, &cs, lk);
  12261. n = nd->next;
  12262. continue;
  12263. }
  12264. if (nd->tag == BR_TAG_SVG &&
  12265. (cs.display == BR_DISPLAY_INLINE ||
  12266. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  12267. !cs.float_left) {
  12268. add_svg_run(l, n, &cs, lk);
  12269. n = nd->next;
  12270. continue;
  12271. }
  12272. if (nd->tag == BR_TAG_VIDEO) {
  12273. layout_block(l, n, &cs, depth + 1, lk);
  12274. n = nd->next;
  12275. continue;
  12276. }
  12277. if (cs.float_left) {
  12278. n = layout_float_group(l, n, pst, depth, lk);
  12279. continue;
  12280. }
  12281. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  12282. inline_block_flows(n, &cs, 0)) {
  12283. layout_inline_box(l, n, &cs, depth, lk);
  12284. n = nd->next;
  12285. continue;
  12286. }
  12287. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  12288. n = layout_inline_blocks(l, n, pst, depth, link);
  12289. continue;
  12290. }
  12291. /* A flex container is block-level like any block box even when
  12292. * the element is an inline tag such as <a> (a link card with
  12293. * display:flex is common on news sites). Without the block box
  12294. * its children were laid out in the parent flow with a 0x0 box
  12295. * of their own. */
  12296. /* inline-flex around inline content only ("| mehr" link
  12297. * tails, icon+label pills) stays in the text line. */
  12298. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  12299. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  12300. !flex_wants_row(n, &cs)) {
  12301. layout_children(l, n, &cs, depth + 1, lk);
  12302. } else if (cs.display == BR_DISPLAY_BLOCK ||
  12303. cs.display == BR_DISPLAY_FLEX ||
  12304. br_tag_is_block(nd->tag))
  12305. layout_block(l, n, &cs, depth + 1, lk);
  12306. else if (cs.display == BR_DISPLAY_INLINE &&
  12307. nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH)
  12308. layout_inline_box(l, n, &cs, depth, lk);
  12309. else {
  12310. layout_children(l, n, &cs, depth + 1, lk);
  12311. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  12312. l->space_pending = 1;
  12313. }
  12314. n = nd->next;
  12315. }
  12316. emit_pseudo(l, parent, pst, 2, link);
  12317. }
  12318. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  12319. * runs and a recursive page can otherwise overflow the stack. */
  12320. static struct lay layout_state;
  12321. static int measure_page(int left, int right)
  12322. {
  12323. struct lay *l = &layout_state;
  12324. struct br_style base = base_style();
  12325. unsigned int i;
  12326. for (i = 0; i < BR_MAX_NODES; i++) {
  12327. block_h[i] = 0;
  12328. flex_stretch_h[i] = 0;
  12329. img_top[i] = 0;
  12330. block_top[i] = 0;
  12331. img_h[i] = 0;
  12332. layout_boxes[i].valid = 0;
  12333. }
  12334. memset(li_marker, 0, sizeof(li_marker));
  12335. inline_box_pass_id++;
  12336. l->box_owner = 0;
  12337. l->draw = 0;
  12338. l->ui = &ui;
  12339. l->left = left;
  12340. l->right = right;
  12341. l->y = 0;
  12342. l->line_x = left;
  12343. l->run_x = left;
  12344. l->line_left = left;
  12345. l->line_right = right;
  12346. l->line_y = 0;
  12347. l->line_h = 0;
  12348. l->align = BR_ALIGN_LEFT;
  12349. l->cb_h = layout_view_h;
  12350. l->float_active = 0;
  12351. l->parent_top = 0;
  12352. l->cb_left = left;
  12353. l->cb_right = right;
  12354. l->cb_top = 0;
  12355. l->depth = 0;
  12356. l->nruns = 0;
  12357. l->space_pending = 0;
  12358. base = root_style();
  12359. layout_children(l, doc.root, &base, 0, 0);
  12360. return l->y + 8;
  12361. }
  12362. static int deferred_cmp(const struct br_deferred *a,
  12363. const struct br_deferred *b)
  12364. {
  12365. int az = a->z_set ? a->z_index : 0;
  12366. int bz = b->z_set ? b->z_index : 0;
  12367. if (az != bz)
  12368. return az < bz ? -1 : 1;
  12369. if (a->order != b->order)
  12370. return a->order < b->order ? -1 : 1;
  12371. return 0;
  12372. }
  12373. static void sort_deferred(void)
  12374. {
  12375. int i;
  12376. for (i = 1; i < ndeferred; i++) {
  12377. struct br_deferred key = deferred[i];
  12378. int j = i;
  12379. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  12380. deferred[j] = deferred[j - 1];
  12381. j--;
  12382. }
  12383. deferred[j] = key;
  12384. }
  12385. }
  12386. static void hit_add_occluder(unsigned int node, int at)
  12387. {
  12388. const struct br_layout_box *b;
  12389. struct hit h;
  12390. int x0, y0, x1, y1;
  12391. if (node >= BR_MAX_NODES || nhits >= HIT_MAX || at > nhits)
  12392. return;
  12393. b = &layout_boxes[node];
  12394. if (!b->valid)
  12395. return;
  12396. x0 = b->x > page_rect.x ? b->x : page_rect.x;
  12397. y0 = b->y > page_rect.y ? b->y : page_rect.y;
  12398. x1 = b->x + b->w;
  12399. y1 = b->y + b->h;
  12400. if (x1 > page_rect.x + page_rect.w - 12)
  12401. x1 = page_rect.x + page_rect.w - 12;
  12402. if (y1 > page_rect.y + page_rect.h)
  12403. y1 = page_rect.y + page_rect.h;
  12404. if (x1 <= x0 || y1 <= y0)
  12405. return;
  12406. h.x = x0;
  12407. h.y = y0;
  12408. h.w = x1 - x0;
  12409. h.h = y1 - y0;
  12410. h.node = (unsigned short)node;
  12411. h.occl = 1;
  12412. memmove(&hits[at + 1], &hits[at],
  12413. (unsigned int)(nhits - at) * sizeof(hits[0]));
  12414. hits[at] = h;
  12415. nhits++;
  12416. }
  12417. static void render_page(int left, int right, int y0)
  12418. {
  12419. struct lay *l = &layout_state;
  12420. struct br_style base = base_style();
  12421. inline_box_pass_id++;
  12422. l->box_owner = 0;
  12423. l->draw = 1;
  12424. l->ui = &ui;
  12425. l->left = left;
  12426. l->right = right;
  12427. l->y = y0;
  12428. l->line_x = left;
  12429. l->run_x = left;
  12430. l->line_left = left;
  12431. l->line_right = right;
  12432. l->line_y = y0;
  12433. l->line_h = 0;
  12434. l->align = BR_ALIGN_LEFT;
  12435. l->cb_h = layout_view_h;
  12436. l->float_active = 0;
  12437. l->parent_top = 0;
  12438. l->cb_left = left;
  12439. l->cb_right = right;
  12440. l->cb_top = y0;
  12441. l->depth = 0;
  12442. l->nruns = 0;
  12443. l->space_pending = 0;
  12444. nhits = 0;
  12445. ndeferred = 0;
  12446. render_pass = 1;
  12447. render_seq++;
  12448. base = root_style();
  12449. layout_children(l, doc.root, &base, 0, 0);
  12450. sort_deferred();
  12451. {
  12452. int i;
  12453. for (i = 0; i < ndeferred; i++) {
  12454. struct br_style st;
  12455. int hide, op, blend, hit0;
  12456. br_style_for(&doc, deferred[i].node, &base, &st);
  12457. if (st.display == BR_DISPLAY_NONE)
  12458. continue;
  12459. /* A transparent or visibility:hidden positioned box
  12460. * still gets its boxes (scripts measure it) but no
  12461. * paint and no hit rectangles. A translucent one
  12462. * (a 50% modal backdrop, a fading tooltip) is
  12463. * blended over what is under it; the opacity may be
  12464. * mid-transition. */
  12465. hit0 = nhits;
  12466. op = anim_value(deferred[i].node, ANIM_OP, st.opacity,
  12467. &st);
  12468. hide = op == 0 || st.vis_hidden;
  12469. blend = !hide && op < 255 && alpha_begin(page_rect);
  12470. l->draw = !hide;
  12471. l->left = deferred[i].flow_left;
  12472. l->right = deferred[i].flow_right;
  12473. l->y = deferred[i].flow_y;
  12474. l->parent_top = deferred[i].parent_top;
  12475. l->line_left = l->line_x = l->left;
  12476. l->run_x = l->left;
  12477. l->line_y = l->y;
  12478. l->line_h = 0;
  12479. l->nruns = 0;
  12480. l->space_pending = 0;
  12481. l->align = st.align;
  12482. if (st.pos == 2 && block_h[deferred[i].node]) {
  12483. struct ngui_rect clip;
  12484. int ch = block_h[deferred[i].node] + 24;
  12485. int pr = page_rect.x + page_rect.w - 12;
  12486. int x0 = page_rect.x, x1 = pr;
  12487. int y0 = page_rect.y;
  12488. /* A box placed by `bottom` (a page footer) is
  12489. * clipped and filled where layout_block puts
  12490. * it, against the bottom edge. */
  12491. if (st.bottom_set && !st.top_set) {
  12492. ch = block_h[deferred[i].node] +
  12493. mp_px(&st, 0, pr - page_rect.x) +
  12494. mp_px(&st, 2, pr - page_rect.x);
  12495. y0 = page_rect.y + page_rect.h -
  12496. st.bottom - ch;
  12497. }
  12498. /* The background pre-fill spans the box's own
  12499. * columns, not the whole page: Docusaurus parks
  12500. * a white "Skip to main content" link at
  12501. * `left: 100%` with a z-index above the navbar,
  12502. * and a full-width fill painted over the bar. */
  12503. if (st.left_set)
  12504. x0 = page_rect.x + st.left;
  12505. else if (!st.right_set)
  12506. x0 = deferred[i].flow_left;
  12507. if (st.width_kind == 1) {
  12508. if (st.right_set && !st.left_set)
  12509. x0 = pr - st.right - st.width;
  12510. x1 = x0 + st.width;
  12511. } else if (st.right_set) {
  12512. x1 = pr - st.right;
  12513. }
  12514. if (x0 >= pr || x1 <= page_rect.x)
  12515. continue; /* entirely off-screen */
  12516. if (x0 < page_rect.x)
  12517. x0 = page_rect.x;
  12518. if (x1 > pr)
  12519. x1 = pr;
  12520. if (y0 < page_rect.y) {
  12521. ch -= page_rect.y - y0;
  12522. y0 = page_rect.y;
  12523. }
  12524. clip.x = x0;
  12525. clip.y = y0;
  12526. clip.w = x1 - x0;
  12527. if (ch > page_rect.h)
  12528. ch = page_rect.h;
  12529. if (ch <= 0)
  12530. continue;
  12531. clip.h = ch;
  12532. ngui_push_clip(&ui, clip);
  12533. if (st.has_bg && !hide)
  12534. ngui_fill_rect(&ui, clip, st.bg);
  12535. layout_block(l, deferred[i].node, &st, 0,
  12536. deferred[i].link);
  12537. ngui_pop_clip(&ui);
  12538. } else {
  12539. layout_block(l, deferred[i].node, &st, 0,
  12540. deferred[i].link);
  12541. }
  12542. if (!hide && !st.pe_none &&
  12543. (st.pos == 1 || st.pos == 2) &&
  12544. (st.has_bg || st.bg_image || st.z_set))
  12545. hit_add_occluder(deferred[i].node, hit0);
  12546. if (blend) {
  12547. const struct br_layout_box *b =
  12548. &layout_boxes[deferred[i].node];
  12549. struct ngui_rect box = page_rect;
  12550. /* The box itself; descendants may overflow
  12551. * it, so a full-page box is the safe case. */
  12552. if (deferred[i].node < BR_MAX_NODES &&
  12553. b->valid) {
  12554. box.x = b->x;
  12555. box.y = b->y;
  12556. box.w = b->w;
  12557. box.h = b->h;
  12558. }
  12559. alpha_end(page_rect, box, op);
  12560. }
  12561. }
  12562. }
  12563. render_pass = 0;
  12564. }
  12565. /* ---- UI ---- */
  12566. /* The link/control under a point, topmost first. An occluder above it
  12567. * returns 0 and its node in *occl (when given), so the caller can target
  12568. * the covering box instead of content painted underneath. */
  12569. static int find_hit_ex(int x, int y, int *occl)
  12570. {
  12571. int i;
  12572. if (occl)
  12573. *occl = -1;
  12574. for (i = nhits - 1; i >= 0; i--) {
  12575. struct hit *h = &hits[i];
  12576. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  12577. y < h->y + h->h) {
  12578. if (h->occl) {
  12579. if (occl)
  12580. *occl = (int)h->node;
  12581. return 0;
  12582. }
  12583. return (int)h->node;
  12584. }
  12585. }
  12586. return 0;
  12587. }
  12588. static int find_hit(int x, int y)
  12589. {
  12590. return find_hit_ex(x, y, 0);
  12591. }
  12592. /* ---- URL-bar autocomplete ----
  12593. *
  12594. * While the address bar has the focus a dropdown lists up to SUG_MAX
  12595. * history entries. An empty bar (a fresh focus, Ctrl+L) shows the most
  12596. * visited/recent sites; typing ranks prefix matches of the URL (with or
  12597. * without the scheme and "www.") above substring matches of the URL, then
  12598. * of the title, and adds visit count and recency. Typing at the end of the
  12599. * text also completes inline to the next '/' of the best prefix match
  12600. * ("clo" -> "cloudron.io/"), with the added part selected so the next
  12601. * keystroke replaces it; Enter on that text opens the history URL it came
  12602. * from (scheme included). Up/Down preview a row in the bar, Delete on a
  12603. * highlighted row forgets it, Esc closes the list (a second Esc leaves the
  12604. * bar), and a click on a row opens it. */
  12605. #define SUG_MAX 6
  12606. #define SUG_ROW_H 36
  12607. static int sug_idx[SUG_MAX];
  12608. static int sug_n, sug_sel = -1, sug_open;
  12609. static char sug_typed[NGUI_INPUT_MAX]; /* what the user typed */
  12610. static char sug_restore[NGUI_INPUT_MAX]; /* bar text before a preview */
  12611. static char ac_text[NGUI_INPUT_MAX]; /* bar text of the inline completion */
  12612. static char ac_url[HIST_URL_MAX]; /* the history URL it stands for */
  12613. static struct ngui_rect url_rect, sug_rect;
  12614. static int url_had_focus;
  12615. static char lc(char c)
  12616. {
  12617. return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
  12618. }
  12619. static int prefix_ci(const char *s, const char *p) /* p is lower case */
  12620. {
  12621. for (; *p; s++, p++)
  12622. if (lc(*s) != *p)
  12623. return 0;
  12624. return 1;
  12625. }
  12626. static unsigned int url_scheme_len(const char *url)
  12627. {
  12628. if (starts_with(url, "https://"))
  12629. return 8;
  12630. if (starts_with(url, "http://"))
  12631. return 7;
  12632. return 0;
  12633. }
  12634. /* Offset in `url` where the lower-case text `t` matches as a prefix: the
  12635. * whole URL, the URL without its scheme, or without scheme and "www.". */
  12636. static int hist_prefix_at(const char *url, const char *t)
  12637. {
  12638. unsigned int s = url_scheme_len(url);
  12639. if (prefix_ci(url, t))
  12640. return 0;
  12641. if (s && prefix_ci(url + s, t))
  12642. return (int)s;
  12643. if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
  12644. return (int)s + 4;
  12645. return -1;
  12646. }
  12647. static int hist_score(const struct hist_ent *e, const char *t,
  12648. unsigned int next)
  12649. {
  12650. unsigned int age = next - e->stamp;
  12651. int sc, at;
  12652. if (!t[0]) {
  12653. sc = 0;
  12654. } else if ((at = hist_prefix_at(e->url, t)) >= 0) {
  12655. /* Shorter rests first: "cloudron.io/" before its subpages. */
  12656. int rest = (int)s_len(e->url + at);
  12657. sc = 4000 - (rest > 400 ? 400 : rest);
  12658. } else if (contains_ci(e->url, t)) {
  12659. sc = 1000;
  12660. } else if (contains_ci(e->title, t)) {
  12661. sc = 600;
  12662. } else {
  12663. return -1;
  12664. }
  12665. sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
  12666. sc += age >= 500 ? 0 : (int)(500 - age);
  12667. return sc;
  12668. }
  12669. static void sug_lower(char *t, unsigned int cap)
  12670. {
  12671. unsigned int k;
  12672. for (k = 0; sug_typed[k] && k + 1 < cap; k++)
  12673. t[k] = lc(sug_typed[k]);
  12674. t[k] = '\0';
  12675. }
  12676. static void sug_refresh(void)
  12677. {
  12678. char t[NGUI_INPUT_MAX];
  12679. int sc[SUG_MAX], i, j;
  12680. unsigned int next = hist_next_stamp();
  12681. sug_lower(t, sizeof(t));
  12682. sug_n = 0;
  12683. for (i = 0; i < hist_n; i++) {
  12684. int s = hist_score(&hist_tab[i], t, next);
  12685. if (s < 0)
  12686. continue;
  12687. j = sug_n;
  12688. if (j == SUG_MAX) {
  12689. if (sc[SUG_MAX - 1] >= s)
  12690. continue;
  12691. j = SUG_MAX - 1;
  12692. }
  12693. while (j > 0 && sc[j - 1] < s) {
  12694. sc[j] = sc[j - 1];
  12695. sug_idx[j] = sug_idx[j - 1];
  12696. j--;
  12697. }
  12698. sc[j] = s;
  12699. sug_idx[j] = i;
  12700. if (sug_n < SUG_MAX)
  12701. sug_n++;
  12702. }
  12703. if (sug_sel >= sug_n)
  12704. sug_sel = -1;
  12705. }
  12706. /* Complete the typed text inline to the next '/' of the best prefix match. */
  12707. static void sug_inline(void)
  12708. {
  12709. char t[NGUI_INPUT_MAX];
  12710. const char *url, *rest;
  12711. unsigned int L, start, end, hs, tn, n = 0;
  12712. unsigned int next = hist_next_stamp();
  12713. int i, best = -1, best_sc = -1, at = 0;
  12714. sug_lower(t, sizeof(t));
  12715. L = s_len(t);
  12716. if (!L)
  12717. return;
  12718. for (i = 0; i < hist_n; i++) {
  12719. int a = hist_prefix_at(hist_tab[i].url, t), s;
  12720. if (a < 0)
  12721. continue;
  12722. s = hist_score(&hist_tab[i], t, next);
  12723. if (s > best_sc) {
  12724. best_sc = s;
  12725. best = i;
  12726. at = a;
  12727. }
  12728. }
  12729. if (best < 0)
  12730. return;
  12731. url = hist_tab[best].url;
  12732. rest = url + at;
  12733. /* Typing the scheme ("htt") completes past "https://", not to it. */
  12734. hs = at == 0 ? url_scheme_len(url) : 0;
  12735. start = L > hs ? L : hs;
  12736. end = start;
  12737. while (rest[end] && rest[end] != '/')
  12738. end++;
  12739. if (rest[end] == '/')
  12740. end++;
  12741. tn = s_len(sug_typed);
  12742. if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
  12743. return;
  12744. s_append(ac_text, &n, sug_typed, sizeof(ac_text));
  12745. for (; L < end && n + 1 < sizeof(ac_text); L++)
  12746. ac_text[n++] = rest[L];
  12747. ac_text[n] = '\0';
  12748. s_copy(ac_url, url, (unsigned int)at + end + 1);
  12749. ngui_input_set(&url_in, ac_text);
  12750. url_in.anchor = tn; /* select the completed part */
  12751. }
  12752. static void sug_close(void)
  12753. {
  12754. sug_open = 0;
  12755. sug_sel = -1;
  12756. ac_text[0] = '\0';
  12757. }
  12758. static int sug_visible(void)
  12759. {
  12760. return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
  12761. }
  12762. /* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
  12763. * start page) lists the top sites until something is typed. */
  12764. static int sug_focus_check(void)
  12765. {
  12766. int focused = ngui_focus(&ui) == ID_URL;
  12767. if (focused && !url_had_focus) {
  12768. sug_typed[0] = '\0';
  12769. sug_close();
  12770. sug_open = 1;
  12771. sug_refresh();
  12772. }
  12773. url_had_focus = focused;
  12774. return focused;
  12775. }
  12776. static void url_submit(unsigned int *action)
  12777. {
  12778. if (ac_text[0] && s_eq(url_in.text, ac_text))
  12779. s_copy(click_url, ac_url, sizeof(click_url));
  12780. *action |= ACT_NAV;
  12781. sug_close();
  12782. }
  12783. /* The bar text changed through typing or editing. */
  12784. static void sug_changed(void)
  12785. {
  12786. unsigned int pl = s_len(sug_typed);
  12787. int grew = url_in.len > pl && url_in.cursor == url_in.len &&
  12788. !memcmp(url_in.text, sug_typed, pl);
  12789. s_copy(sug_typed, url_in.text, sizeof(sug_typed));
  12790. ac_text[0] = '\0';
  12791. sug_sel = -1;
  12792. sug_open = 1;
  12793. sug_refresh();
  12794. if (grew)
  12795. sug_inline();
  12796. }
  12797. /* Keys for the list, taken off the queue before the text field sees them.
  12798. * Only a leading run is handled; the rest goes to the field. */
  12799. static void sug_keys(void)
  12800. {
  12801. int k;
  12802. while ((k = ngui_key_peek(&ui)) != 0) {
  12803. if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
  12804. ngui_key(&ui);
  12805. if (!sug_open) {
  12806. sug_open = 1;
  12807. continue;
  12808. }
  12809. if (sug_sel < 0)
  12810. s_copy(sug_restore, url_in.text,
  12811. sizeof(sug_restore));
  12812. if (k == NGUI_KEY_DOWN)
  12813. sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
  12814. else
  12815. sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
  12816. ngui_input_set(&url_in, sug_sel >= 0 ?
  12817. hist_tab[sug_idx[sug_sel]].url :
  12818. sug_restore);
  12819. } else if (k == NGUI_KEY_ESC && sug_visible()) {
  12820. ngui_key(&ui);
  12821. if (sug_sel >= 0)
  12822. ngui_input_set(&url_in, sug_restore);
  12823. else if (ac_text[0] && s_eq(url_in.text, ac_text))
  12824. ngui_input_set(&url_in, sug_typed);
  12825. sug_close();
  12826. } else if (k == NGUI_KEY_DELETE && sug_visible() &&
  12827. sug_sel >= 0) {
  12828. ngui_key(&ui);
  12829. hist_forget(sug_idx[sug_sel]);
  12830. ngui_input_set(&url_in, sug_restore);
  12831. sug_sel = -1;
  12832. sug_refresh();
  12833. } else {
  12834. break;
  12835. }
  12836. }
  12837. }
  12838. /* A press on a row of last frame's list opens it; any press on the list is
  12839. * swallowed so the page underneath does not see it. */
  12840. static void sug_click(unsigned int *action)
  12841. {
  12842. int row;
  12843. if (!(ui.pressed & 1) || !sug_rect.w ||
  12844. !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
  12845. return;
  12846. row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
  12847. if (row >= 0 && row < sug_n) {
  12848. s_copy(click_url, hist_tab[sug_idx[row]].url,
  12849. sizeof(click_url));
  12850. *action |= ACT_NAV;
  12851. sug_close();
  12852. }
  12853. ui.pressed = 0;
  12854. }
  12855. static void draw_suggest(struct ngui_rect page)
  12856. {
  12857. struct ngui_rect r;
  12858. int i, rows = sug_n, hover = -1;
  12859. r.x = url_rect.x;
  12860. r.y = url_rect.y + url_rect.h + 1;
  12861. r.w = url_rect.w < 320 ? 320 : url_rect.w;
  12862. if (r.x + r.w > ui.w - 2)
  12863. r.w = ui.w - 2 - r.x;
  12864. while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
  12865. rows--;
  12866. if (rows <= 0 || r.w < 60) {
  12867. sug_rect.w = 0;
  12868. return;
  12869. }
  12870. r.h = rows * SUG_ROW_H + 2;
  12871. sug_rect = r;
  12872. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  12873. hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
  12874. ngui_set_cursor(&ui, CURSOR_POINTER);
  12875. }
  12876. ngui_fill_rect(&ui, r, ui.theme.border);
  12877. for (i = 0; i < rows; i++) {
  12878. const struct hist_ent *e = &hist_tab[sug_idx[i]];
  12879. struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
  12880. r.w - 2, SUG_ROW_H};
  12881. struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
  12882. unsigned short bg = i == sug_sel ? ui.theme.selection :
  12883. i == hover ? ui.theme.panel_alt :
  12884. ui.theme.panel;
  12885. ngui_fill_rect(&ui, rr, bg);
  12886. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
  12887. e->title[0] ? e->title : e->url,
  12888. ui.theme.text);
  12889. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
  12890. i == sug_sel ? ui.theme.text :
  12891. ui.theme.text_dim);
  12892. }
  12893. }
  12894. static void ctx_close(void);
  12895. static void ctx_open_from_right(struct ngui_rect page);
  12896. static void ctx_press(struct ngui_rect page);
  12897. static void draw_context(void);
  12898. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  12899. {
  12900. int x = r.x + 4, y = r.y + 4, h = 22;
  12901. int compact = r.w < 560;
  12902. int go_w = r.w < 420 ? 32 : 42;
  12903. int in_x, in_w, res;
  12904. ngui_fill_rect(&ui, r, ui.theme.panel);
  12905. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  12906. ui.theme.border);
  12907. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  12908. NGUI_ICON_CHEVRON_LEFT))
  12909. *action |= ACT_BACK;
  12910. x += 32;
  12911. if (!compact) {
  12912. if (ngui_icon_button(&ui, ID_FORWARD,
  12913. (struct ngui_rect){x, y, 28, h},
  12914. NGUI_ICON_CHEVRON_RIGHT))
  12915. *action |= ACT_FORWARD;
  12916. x += 32;
  12917. }
  12918. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  12919. NGUI_ICON_REFRESH))
  12920. *action |= ACT_RELOAD;
  12921. x += 32;
  12922. if (!compact) {
  12923. if (ngui_icon_button(&ui, ID_HOME,
  12924. (struct ngui_rect){x, y, 28, h},
  12925. NGUI_ICON_HOME))
  12926. *action |= ACT_HOME;
  12927. x += 32;
  12928. }
  12929. dl_button_rect = (struct ngui_rect){x, y, 28, h};
  12930. if (ngui_icon_button(&ui, ID_DOWNLOADS, dl_button_rect,
  12931. NGUI_ICON_DOWNLOAD)) {
  12932. dl_panel_open = !dl_panel_open;
  12933. if (dl_panel_open) {
  12934. dl_unseen = 0;
  12935. ctx_close();
  12936. sug_close();
  12937. ngui_set_focus(&ui, 0);
  12938. }
  12939. ngui_invalidate(&ui);
  12940. }
  12941. if (dl_active >= 0) {
  12942. int p = dl_percent();
  12943. if (p < 0)
  12944. p = 0;
  12945. ngui_fill_rect(&ui, (struct ngui_rect){
  12946. dl_button_rect.x + 3,
  12947. dl_button_rect.y + dl_button_rect.h - 4,
  12948. dl_button_rect.w - 6, 2}, ui.theme.border);
  12949. if (p > 0)
  12950. ngui_fill_rect(&ui, (struct ngui_rect){
  12951. dl_button_rect.x + 3,
  12952. dl_button_rect.y + dl_button_rect.h - 4,
  12953. (dl_button_rect.w - 6) * p / 100, 2},
  12954. ui.theme.accent);
  12955. }
  12956. if (dl_unseen && !dl_panel_open)
  12957. ngui_fill_rect(&ui, (struct ngui_rect){
  12958. dl_button_rect.x + dl_button_rect.w - 6,
  12959. dl_button_rect.y + 2, 4, 4}, ui.theme.accent);
  12960. x += 32;
  12961. in_x = x + 2;
  12962. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  12963. if (in_w < 60)
  12964. in_w = 60;
  12965. url_rect = (struct ngui_rect){in_x, y, in_w, h};
  12966. if (sug_focus_check())
  12967. sug_keys();
  12968. res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
  12969. sug_focus_check(); /* a click into the bar focuses it here */
  12970. if (res & NGUI_INPUT_CHANGED)
  12971. sug_changed();
  12972. if (res & NGUI_INPUT_SUBMIT)
  12973. url_submit(action);
  12974. if (res & NGUI_INPUT_CANCEL)
  12975. ngui_set_focus(&ui, 0);
  12976. if (ngui_button(&ui, ID_GO,
  12977. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  12978. "Go"))
  12979. url_submit(action);
  12980. if (!sug_focus_check())
  12981. sug_close();
  12982. }
  12983. static int page_hover_node(void)
  12984. {
  12985. if (!ui.inside || ctx_open || dl_panel_open)
  12986. return 0;
  12987. if (ui.mouse_x < page_rect.x ||
  12988. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  12989. ui.mouse_y < page_rect.y ||
  12990. ui.mouse_y >= page_rect.y + page_rect.h)
  12991. return 0;
  12992. return find_hit(ui.mouse_x, ui.mouse_y);
  12993. }
  12994. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  12995. {
  12996. int x, y, w = page.w, h = page.h;
  12997. if (!src || w <= 0 || h <= 0)
  12998. return;
  12999. for (y = 0; y < h; y++) {
  13000. unsigned short *s = src + (page.y + y) * sw + page.x;
  13001. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  13002. for (x = 0; x + 1 < w; x += 2) {
  13003. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  13004. }
  13005. if (x < w)
  13006. d[x] = s[x];
  13007. }
  13008. }
  13009. static void draw_page(struct ngui_rect page)
  13010. {
  13011. int left, right, ch;
  13012. int old_panel, old_dim;
  13013. unsigned short *saved_px;
  13014. unsigned short page_bg = ui.theme.bg;
  13015. int saved_w, saved_h, use_buf;
  13016. unsigned int t0 = u_ticks_ms();
  13017. page_rect = page;
  13018. {
  13019. unsigned int root = doc.nnode > 1 ?
  13020. br_find_tag(&doc, BR_TAG_HTML) : 0;
  13021. unsigned int body = doc.nnode > 1 ?
  13022. br_find_tag(&doc, BR_TAG_BODY) : 0;
  13023. struct br_style bs;
  13024. int bg_found = 0;
  13025. if (root) {
  13026. style_for_node(root - 1, &bs);
  13027. if (bs.has_bg) {
  13028. page_bg = bs.bg;
  13029. bg_found = 1;
  13030. }
  13031. }
  13032. if (body) {
  13033. style_for_node(body - 1, &bs);
  13034. if (bs.has_bg) {
  13035. page_bg = bs.bg;
  13036. bg_found = 1;
  13037. }
  13038. }
  13039. /* No canvas colour, but the author made the text dark
  13040. * (Infima's light theme: `--ifm-background-color:
  13041. * transparent` on html, #1c1e21 text): the page expects the
  13042. * white canvas of a normal browser, and dark text on the
  13043. * dark default canvas is unreadable. Mid-grey counts too:
  13044. * Hacker News sets #828282 body text on a white page;
  13045. * text meant for a dark background is light (> ~200). */
  13046. if (!bg_found && (body || root) && bs.color != ui.theme.text) {
  13047. unsigned int c = bs.color;
  13048. unsigned int lum = ((c >> 11) & 31) * 8 * 299 +
  13049. ((c >> 5) & 63) * 4 * 587 +
  13050. (c & 31) * 8 * 114;
  13051. if (lum < 150 * 1000)
  13052. page_bg = 0xFFFF;
  13053. }
  13054. }
  13055. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  13056. page_cache_valid && layout_valid &&
  13057. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  13058. !(ui.scroll_y &&
  13059. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  13060. page_scroll.offset == page_cache_scroll &&
  13061. page_cache_nnode == doc.nnode &&
  13062. page_cache_x == page.x && page_cache_y == page.y &&
  13063. page_cache_w == page.w && page_cache_h == page.h) {
  13064. blit_page(page, page_backbuf, pagebuf_w);
  13065. if (img_stat_n)
  13066. img_stat_paint += u_ticks_ms() - t0;
  13067. return;
  13068. }
  13069. ngui_fill_rect(&ui, page, page_bg);
  13070. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  13071. const char *s = page_loading ? "Loading..." : "No page";
  13072. int w = (int)ngui_text_width_ui(&ui, s);
  13073. ngui_text(&ui, page.x + (page.w - w) / 2,
  13074. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  13075. page_scroll.content_h = 0;
  13076. page_scroll.view_h = page.h;
  13077. page_cache_valid = 0;
  13078. return;
  13079. }
  13080. if (page.w < 40 || page.h < 40) {
  13081. page_cache_valid = 0;
  13082. return;
  13083. }
  13084. saved_px = ui.px;
  13085. saved_w = ui.w;
  13086. saved_h = ui.h;
  13087. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  13088. if (use_buf) {
  13089. ui.px = page_backbuf;
  13090. ui.w = pagebuf_w;
  13091. ui.h = pagebuf_h;
  13092. ngui_fill_rect(&ui, page, page_bg);
  13093. }
  13094. /* No gutter of our own: the body's UA margin provides it. The
  13095. * right 12 px stay clear for the scrollbar, like every viewport
  13096. * width below (page_rect.w - 12). */
  13097. left = page.x;
  13098. right = page.x + page.w - 12;
  13099. if (!layout_valid || left != layout_left || right != layout_right ||
  13100. layout_nnode != doc.nnode) {
  13101. unsigned int tm = u_ticks_ms();
  13102. layout_view_h = page.h;
  13103. layout_content_h = measure_page(left, right);
  13104. if (img_stat_n)
  13105. img_stat_reflow += u_ticks_ms() - tm;
  13106. layout_valid = 1;
  13107. layout_left = left;
  13108. layout_right = right;
  13109. layout_nnode = doc.nnode;
  13110. /* Scripts that measured before any layout (offsetWidth on
  13111. * mount) get a resize event once real boxes exist, and again
  13112. * whenever the page width changes. */
  13113. if (js_browser_active() && right - left != resize_sent_w)
  13114. resize_pending = 1;
  13115. }
  13116. ch = layout_content_h;
  13117. page_scroll.content_h = ch;
  13118. page_scroll.view_h = page.h;
  13119. t0 = u_ticks_ms();
  13120. ngui_scroll_begin(&ui, page, &page_scroll);
  13121. ngui_scroll_wheel(&ui, page, &page_scroll);
  13122. render_page(left, right, page.y - page_scroll.offset);
  13123. old_panel = ui.theme.panel_alt;
  13124. old_dim = ui.theme.text_dim;
  13125. ui.theme.panel_alt = 0xC618;
  13126. ui.theme.text_dim = 0x8410;
  13127. ngui_scroll_end(&ui, page, &page_scroll);
  13128. ui.theme.panel_alt = old_panel;
  13129. ui.theme.text_dim = old_dim;
  13130. if (use_buf) {
  13131. ui.px = saved_px;
  13132. ui.w = saved_w;
  13133. ui.h = saved_h;
  13134. blit_page(page, page_backbuf, pagebuf_w);
  13135. page_cache_valid = 1;
  13136. page_cache_scroll = page_scroll.offset;
  13137. page_cache_nnode = doc.nnode;
  13138. page_cache_x = page.x;
  13139. page_cache_y = page.y;
  13140. page_cache_w = page.w;
  13141. page_cache_h = page.h;
  13142. } else {
  13143. page_cache_valid = 0;
  13144. }
  13145. if (img_stat_n)
  13146. img_stat_paint += u_ticks_ms() - t0;
  13147. }
  13148. /* Lay the page out now, into the page back buffer, so scripts read real
  13149. * boxes for nodes they just inserted. Absolute/fixed boxes only get their
  13150. * boxes in the painting pass, so this is a full render; the next frame
  13151. * repaints the screen as usual. Skipped while the page has never been
  13152. * drawn (no viewport yet) or without the back buffer.
  13153. *
  13154. * The guard is a count per main-loop pass, not a time budget: a hover or
  13155. * click handler (Bootstrap's tooltip does ~6 write/read rounds) must get
  13156. * correct geometry even on the ION, where one re-layout of cloudron.io
  13157. * takes longer than any reasonable per-window budget; only a script that
  13158. * keeps writing and reading in one pass falls back to the last layout. */
  13159. #define FORCE_LAYOUT_PER_PASS 8
  13160. static int force_layout_count;
  13161. static void js_force_layout_pass_reset(void)
  13162. {
  13163. force_layout_count = 0;
  13164. }
  13165. static void js_force_layout(void)
  13166. {
  13167. static int busy;
  13168. unsigned short *saved_px = ui.px;
  13169. int saved_w = ui.w, saved_h = ui.h;
  13170. struct ngui_rect page = page_rect;
  13171. if (busy || !page_backbuf || pagebuf_w != ui.w ||
  13172. pagebuf_h != ui.h || page.w < 40 || page.h < 40 ||
  13173. layout_right <= layout_left ||
  13174. force_layout_count >= FORCE_LAYOUT_PER_PASS)
  13175. return;
  13176. force_layout_count++;
  13177. busy = 1;
  13178. ui.px = page_backbuf;
  13179. layout_view_h = page.h;
  13180. layout_content_h = measure_page(layout_left, layout_right);
  13181. layout_valid = 1;
  13182. layout_nnode = doc.nnode;
  13183. ngui_push_clip(&ui, page);
  13184. render_page(layout_left, layout_right, page.y - page_scroll.offset);
  13185. ngui_pop_clip(&ui);
  13186. ui.px = saved_px;
  13187. ui.w = saved_w;
  13188. ui.h = saved_h;
  13189. page_cache_valid = 0;
  13190. ngui_invalidate(&ui);
  13191. busy = 0;
  13192. }
  13193. static void draw_status(struct ngui_rect r)
  13194. {
  13195. static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
  13196. unsigned int n = 0;
  13197. int hover = page_hover_node();
  13198. unsigned short color;
  13199. const char *kind;
  13200. ngui_fill_rect(&ui, r, ui.theme.panel);
  13201. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  13202. ui.theme.border);
  13203. /* Only a real link target is shown: a form control, or an element
  13204. * that is merely clickable through a script listener (google.com's
  13205. * jsaction wrapper around its search field), is not a link. */
  13206. if (hover && !br_href(&doc, (unsigned int)hover))
  13207. hover = 0;
  13208. if (hover) {
  13209. const char *href = br_href(&doc, (unsigned int)hover);
  13210. char url[BR_URL_MAX];
  13211. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  13212. s_append(msg, &n, "Link: ", sizeof(msg));
  13213. s_append(msg, &n, url, sizeof(msg));
  13214. } else {
  13215. s_copy(msg, "Link", sizeof(msg));
  13216. }
  13217. color = ui.theme.accent;
  13218. } else if (status_text[0]) {
  13219. s_copy(msg, status_text, sizeof(msg));
  13220. color = status_error ? ui.theme.error : ui.theme.text;
  13221. } else if (page_title[0]) {
  13222. s_copy(msg, page_title, sizeof(msg));
  13223. color = ui.theme.text;
  13224. } else {
  13225. s_copy(msg, "Ready", sizeof(msg));
  13226. color = ui.theme.text_dim;
  13227. }
  13228. kind = s_eq(page_url, "about:home") ? "HOME" :
  13229. page_is_local ? "FILE" :
  13230. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  13231. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  13232. {
  13233. int kw = (int)ngui_text_width_ui(&ui, kind);
  13234. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  13235. ui.theme.text_dim);
  13236. }
  13237. }
  13238. /* ---- downloads panel -------------------------------------------------- */
  13239. static int dl_order[DL_MAX], dl_order_n;
  13240. static void dl_order_build(void)
  13241. {
  13242. int i, j;
  13243. dl_order_n = 0;
  13244. for (i = 0; i < DL_MAX; i++)
  13245. if (dl_tab[i].used)
  13246. dl_order[dl_order_n++] = i;
  13247. for (i = 1; i < dl_order_n; i++) {
  13248. int key = dl_order[i];
  13249. unsigned int stamp = dl_tab[key].stamp;
  13250. for (j = i - 1; j >= 0 &&
  13251. dl_tab[dl_order[j]].stamp < stamp; j--)
  13252. dl_order[j + 1] = dl_order[j];
  13253. dl_order[j + 1] = key;
  13254. }
  13255. }
  13256. static void dl_size_text(unsigned int size, char *out, unsigned int cap)
  13257. {
  13258. if (size >= 1024u * 1024u)
  13259. snprintf(out, cap, "%u.%u MB", size / (1024u * 1024u),
  13260. (size % (1024u * 1024u)) * 10 / (1024u * 1024u));
  13261. else if (size >= 1024u)
  13262. snprintf(out, cap, "%u KB", size / 1024u);
  13263. else
  13264. snprintf(out, cap, "%u bytes", size);
  13265. }
  13266. static void dl_ent_label(const struct dl_ent *e, char *out, unsigned int cap)
  13267. {
  13268. char base[16], ext[8];
  13269. if (e->name[0]) {
  13270. s_copy(out, e->name, cap);
  13271. return;
  13272. }
  13273. dl_url_name(e->url, "", base, sizeof(base), ext, sizeof(ext));
  13274. if (ext[0])
  13275. snprintf(out, cap, "%s.%s", base, ext);
  13276. else
  13277. s_copy(out, base, cap);
  13278. }
  13279. static void dl_ent_status(const struct dl_ent *e, char *out,
  13280. unsigned int cap)
  13281. {
  13282. char size[24];
  13283. switch (e->state) {
  13284. case DL_QUEUED:
  13285. s_copy(out, "Queued", cap);
  13286. break;
  13287. case DL_RUNNING: {
  13288. int p = dl_percent();
  13289. if (p >= 0) {
  13290. snprintf(out, cap, "Downloading %d%%", p);
  13291. } else {
  13292. dl_size_text(e->got, size, sizeof(size));
  13293. snprintf(out, cap, "Downloading %s", size);
  13294. }
  13295. break;
  13296. }
  13297. case DL_SAVING:
  13298. s_copy(out, "Saving...", cap);
  13299. break;
  13300. case DL_DONE:
  13301. dl_size_text(e->size, size, sizeof(size));
  13302. snprintf(out, cap, "Saved - %s", size);
  13303. break;
  13304. default:
  13305. if (e->err[0])
  13306. snprintf(out, cap, "Failed: %s", e->err);
  13307. else
  13308. s_copy(out, "Failed", cap);
  13309. break;
  13310. }
  13311. }
  13312. static void dl_panel_layout(struct ngui_rect page)
  13313. {
  13314. int w = DL_PANEL_W, rows, avail, h, x, y;
  13315. dl_order_build();
  13316. rows = dl_order_n;
  13317. if (rows > DL_PANEL_ROWS)
  13318. rows = DL_PANEL_ROWS;
  13319. avail = (page.h - 46) / DL_ROW_H;
  13320. if (avail < 0)
  13321. avail = 0;
  13322. if (rows > avail)
  13323. rows = avail;
  13324. dl_panel_rows = rows;
  13325. if (w > page.w - 16)
  13326. w = page.w - 16;
  13327. if (w < 120)
  13328. w = 120;
  13329. h = 36 + (rows ? rows * DL_ROW_H : 28) + 6;
  13330. if (h > page.h - 8)
  13331. h = page.h - 8;
  13332. x = dl_button_rect.x + dl_button_rect.w - w;
  13333. if (x + w > page.x + page.w - 4)
  13334. x = page.x + page.w - 4 - w;
  13335. if (x < page.x + 4)
  13336. x = page.x + 4;
  13337. y = page.y + 2;
  13338. dl_panel_rect = (struct ngui_rect){x, y, w, h};
  13339. dl_clear_rect = (struct ngui_rect){x + w - 54, y + 6, 46, 20};
  13340. }
  13341. static void dl_panel_press(struct ngui_rect page)
  13342. {
  13343. if (!dl_panel_open || !ui.pressed)
  13344. return;
  13345. dl_panel_layout(page);
  13346. if (ngui_rect_contains(&dl_panel_rect, ui.press_x, ui.press_y)) {
  13347. if (ngui_rect_contains(&dl_clear_rect, ui.press_x, ui.press_y))
  13348. dl_clear_history();
  13349. ui.pressed = ui.released = 0;
  13350. return;
  13351. }
  13352. if (!ngui_rect_contains(&dl_button_rect, ui.press_x, ui.press_y)) {
  13353. dl_panel_open = 0;
  13354. ngui_invalidate(&ui);
  13355. if (ngui_rect_contains(&page, ui.press_x, ui.press_y))
  13356. ui.pressed = ui.released = 0;
  13357. }
  13358. }
  13359. static void draw_downloads(struct ngui_rect page)
  13360. {
  13361. int i;
  13362. if (!dl_panel_open)
  13363. return;
  13364. dl_panel_layout(page);
  13365. if (ui.inside && ngui_rect_contains(&dl_panel_rect, ui.mouse_x,
  13366. ui.mouse_y))
  13367. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  13368. if (dl_history_count() > 0 && ui.inside &&
  13369. ngui_rect_contains(&dl_clear_rect, ui.mouse_x, ui.mouse_y))
  13370. ngui_set_cursor(&ui, CURSOR_POINTER);
  13371. ngui_fill_rect(&ui, dl_panel_rect, ui.theme.border);
  13372. ngui_fill_rect(&ui, (struct ngui_rect){dl_panel_rect.x + 1,
  13373. dl_panel_rect.y + 1, dl_panel_rect.w - 2,
  13374. dl_panel_rect.h - 2}, ui.theme.panel);
  13375. ngui_text_styled(&ui, dl_panel_rect.x + 10, dl_panel_rect.y + 8,
  13376. "Downloads", 9, ui.theme.text, 1, 1);
  13377. if (dl_history_count() > 0) {
  13378. int cw = (int)ngui_text_width_ui(&ui, "Clear");
  13379. int hot = ui.inside && ngui_rect_contains(&dl_clear_rect,
  13380. ui.mouse_x,
  13381. ui.mouse_y);
  13382. ngui_text(&ui, dl_clear_rect.x + (dl_clear_rect.w - cw) / 2,
  13383. dl_clear_rect.y + 1, "Clear",
  13384. hot ? ui.theme.accent : ui.theme.text_dim);
  13385. }
  13386. if (dl_order_n > dl_panel_rows && dl_panel_rows > 0 &&
  13387. dl_panel_rect.w > 260) {
  13388. char more[24];
  13389. int mw;
  13390. snprintf(more, sizeof(more), "%d more", dl_order_n - dl_panel_rows);
  13391. mw = (int)ngui_text_width_ui(&ui, more);
  13392. ngui_text(&ui, dl_clear_rect.x - mw - 8, dl_clear_rect.y + 1,
  13393. more, ui.theme.text_dim);
  13394. }
  13395. if (!dl_order_n) {
  13396. ngui_text(&ui, dl_panel_rect.x + 12,
  13397. dl_panel_rect.y + 40, "No downloads yet",
  13398. ui.theme.text_dim);
  13399. return;
  13400. }
  13401. for (i = 0; i < dl_panel_rows; i++) {
  13402. struct dl_ent *e = &dl_tab[dl_order[i]];
  13403. struct ngui_rect rr = {dl_panel_rect.x + 1,
  13404. dl_panel_rect.y + 30 + i * DL_ROW_H,
  13405. dl_panel_rect.w - 2, DL_ROW_H};
  13406. char name[DL_NAME_MAX], status[96];
  13407. int hot = ui.inside &&
  13408. ngui_rect_contains(&rr, ui.mouse_x, ui.mouse_y);
  13409. enum ngui_icon icon = NGUI_ICON_DOWNLOAD;
  13410. unsigned short icon_color = ui.theme.text_dim;
  13411. dl_ent_label(e, name, sizeof(name));
  13412. dl_ent_status(e, status, sizeof(status));
  13413. if (e->state == DL_DONE) {
  13414. icon = NGUI_ICON_FILE;
  13415. icon_color = ui.theme.text_dim;
  13416. } else if (e->state == DL_FAILED) {
  13417. icon = NGUI_ICON_CLOSE;
  13418. icon_color = ui.theme.error;
  13419. } else {
  13420. icon_color = ui.theme.accent;
  13421. }
  13422. ngui_fill_rect(&ui, rr, hot ? ui.theme.panel_alt : ui.theme.panel);
  13423. ngui_icon(&ui, (struct ngui_rect){rr.x + 7, rr.y + 8, 20, 20},
  13424. icon, icon_color);
  13425. ngui_text_ellipsis(&ui, rr, rr.x + 34, rr.y + 3, name,
  13426. ui.theme.text);
  13427. ngui_text_ellipsis(&ui, rr, rr.x + 34, rr.y + 19, status,
  13428. e->state == DL_FAILED ? ui.theme.error :
  13429. ui.theme.text_dim);
  13430. if (e->state == DL_RUNNING || e->state == DL_SAVING) {
  13431. int p = dl_percent();
  13432. int bw = rr.w - 42;
  13433. ngui_fill_rect(&ui, (struct ngui_rect){rr.x + 34,
  13434. rr.y + rr.h - 6, bw, 3},
  13435. ui.theme.border);
  13436. if (p > 0)
  13437. ngui_fill_rect(&ui, (struct ngui_rect){
  13438. rr.x + 34, rr.y + rr.h - 6,
  13439. bw * p / 100, 3}, ui.theme.accent);
  13440. }
  13441. }
  13442. }
  13443. /* Mouse cursor over the page: the hovered node's CSS `cursor` (inherited);
  13444. * for `auto`, a hand over links, the I-beam over text fields, and the
  13445. * progress arrow anywhere on the page while it is still loading. The
  13446. * toolbar's URL field sets its own I-beam through ngui. */
  13447. static void page_cursor(void)
  13448. {
  13449. int hover = page_hover_node();
  13450. struct br_style st;
  13451. if (!hover) {
  13452. if (page_loading && ui.inside &&
  13453. ngui_rect_contains(&page_rect, ui.mouse_x, ui.mouse_y))
  13454. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  13455. return;
  13456. }
  13457. style_for_node((unsigned int)hover, &st);
  13458. if (st.cursor != BR_CURSOR_AUTO) {
  13459. ngui_set_cursor(&ui, (int)st.cursor - 1);
  13460. return;
  13461. }
  13462. if (br_href(&doc, (unsigned int)hover)) {
  13463. ngui_set_cursor(&ui, CURSOR_POINTER);
  13464. return;
  13465. }
  13466. if (form_is_control((unsigned int)hover)) {
  13467. int k = form_kind_of((unsigned int)hover);
  13468. if (form_disabled((unsigned int)hover))
  13469. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  13470. else if (k == FORM_TEXT || k == FORM_PASSWORD ||
  13471. k == FORM_TEXTAREA)
  13472. ngui_set_cursor(&ui, CURSOR_TEXT);
  13473. return;
  13474. }
  13475. if (page_loading)
  13476. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  13477. }
  13478. static void draw(unsigned int *action)
  13479. {
  13480. struct ngui_rect r = {0, 0, ui.w, ui.h};
  13481. struct ngui_rect toolbar, status, page;
  13482. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  13483. status = ngui_cut_bottom(&r, BR_STATUS_H);
  13484. page = r;
  13485. if (sug_visible())
  13486. sug_click(action);
  13487. ctx_open_from_right(page);
  13488. ctx_press(page);
  13489. dl_panel_press(page);
  13490. draw_toolbar(toolbar, action);
  13491. draw_page(page);
  13492. draw_status(status);
  13493. page_cursor();
  13494. if (sug_visible())
  13495. draw_suggest(page);
  13496. else
  13497. sug_rect.w = 0;
  13498. draw_downloads(page);
  13499. draw_context();
  13500. }
  13501. static void redraw_now(void)
  13502. {
  13503. unsigned int action = 0;
  13504. ngui_begin(&ui);
  13505. draw(&action);
  13506. ngui_end(&ui);
  13507. }
  13508. static void handle_keys(unsigned int *action)
  13509. {
  13510. int k, scrolled = 0;
  13511. if (form_focus >= doc.nnode)
  13512. form_focus = 0;
  13513. if (form_focus && !ngui_focus(&ui)) {
  13514. while ((k = ngui_key(&ui)) != 0)
  13515. form_key(k);
  13516. return;
  13517. }
  13518. /* Batch queued page keys: a slow full-page render must not make a
  13519. * held Page Down advance only once every few frames. */
  13520. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  13521. scrolled++;
  13522. if (scrolled)
  13523. ngui_invalidate(&ui);
  13524. if (ngui_focus(&ui))
  13525. return;
  13526. while ((k = ngui_key(&ui)) != 0) {
  13527. switch (k) {
  13528. case NGUI_KEY_ESC:
  13529. if (ctx_open) {
  13530. ctx_close();
  13531. } else if (dl_panel_open) {
  13532. dl_panel_open = 0;
  13533. ngui_invalidate(&ui);
  13534. } else {
  13535. *action |= ACT_CLOSE;
  13536. }
  13537. break;
  13538. case NGUI_KEY_TAB:
  13539. case 0x0C: /* Ctrl+L */
  13540. ngui_set_focus(&ui, ID_URL);
  13541. break;
  13542. case 0x12: /* Ctrl+R */
  13543. *action |= ACT_RELOAD;
  13544. break;
  13545. case NGUI_KEY_BACKSPACE:
  13546. *action |= ACT_BACK;
  13547. break;
  13548. case NGUI_KEY_UP:
  13549. ngui_scroll_to(&page_scroll,
  13550. page_scroll.offset - 24);
  13551. ngui_invalidate(&ui);
  13552. break;
  13553. case NGUI_KEY_DOWN:
  13554. ngui_scroll_to(&page_scroll,
  13555. page_scroll.offset + 24);
  13556. ngui_invalidate(&ui);
  13557. break;
  13558. case NGUI_KEY_HOME:
  13559. ngui_scroll_to(&page_scroll, 0);
  13560. ngui_invalidate(&ui);
  13561. break;
  13562. case NGUI_KEY_END:
  13563. ngui_scroll_to(&page_scroll,
  13564. page_scroll.content_h -
  13565. page_scroll.view_h);
  13566. ngui_invalidate(&ui);
  13567. break;
  13568. default:
  13569. break;
  13570. }
  13571. }
  13572. }
  13573. static unsigned int form_ancestor(unsigned int node)
  13574. {
  13575. unsigned int p = node;
  13576. while (p && p < doc.nnode) {
  13577. if (doc.nodes[p].tag == BR_TAG_FORM &&
  13578. doc.nodes[p].type == BR_NODE_ELEM)
  13579. return p;
  13580. p = doc.nodes[p].parent;
  13581. }
  13582. return 0;
  13583. }
  13584. static int form_descendant(unsigned int node, unsigned int form)
  13585. {
  13586. unsigned int p = node;
  13587. while (p && p < doc.nnode) {
  13588. if (p == form)
  13589. return 1;
  13590. p = doc.nodes[p].parent;
  13591. }
  13592. return 0;
  13593. }
  13594. static void form_reset_form(unsigned int form)
  13595. {
  13596. unsigned int i;
  13597. for (i = 0; i < FORM_MAX; i++)
  13598. if (form_states[i].used &&
  13599. form_descendant(form_states[i].node, form))
  13600. form_states[i].used = 0;
  13601. form_focus = 0;
  13602. }
  13603. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  13604. const char *s)
  13605. {
  13606. static const char hex[] = "0123456789ABCDEF";
  13607. while (s && *s && *n + 1 < cap) {
  13608. unsigned char c = (unsigned char)*s++;
  13609. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  13610. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  13611. c == '.' || c == '~') {
  13612. dst[(*n)++] = (char)c;
  13613. } else if (c == ' ') {
  13614. dst[(*n)++] = '+';
  13615. } else if (*n + 3 < cap) {
  13616. dst[(*n)++] = '%';
  13617. dst[(*n)++] = hex[c >> 4];
  13618. dst[(*n)++] = hex[c & 15];
  13619. }
  13620. }
  13621. dst[*n] = '\0';
  13622. }
  13623. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  13624. const char *name, const char *value, int *first)
  13625. {
  13626. if (!name || !name[0])
  13627. return;
  13628. if (!*first && *n + 1 < cap)
  13629. dst[(*n)++] = '&';
  13630. *first = 0;
  13631. form_url_append(dst, n, cap, name);
  13632. if (*n + 1 < cap)
  13633. dst[(*n)++] = '=';
  13634. form_url_append(dst, n, cap, value ? value : "");
  13635. dst[*n] = '\0';
  13636. }
  13637. static int form_submit_form(unsigned int node, int fire_event)
  13638. {
  13639. unsigned int form = form_ancestor(node);
  13640. char action[BR_URL_MAX], query[2048];
  13641. unsigned int qn = 0, i;
  13642. int first = 1, is_post = 0;
  13643. const char *a, *method;
  13644. if (!form)
  13645. return 0;
  13646. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  13647. return 0;
  13648. method = br_find_attr(&doc, form, "method");
  13649. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  13650. is_post = 1;
  13651. a = br_find_attr(&doc, form, "action");
  13652. if (a && a[0]) {
  13653. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  13654. return 0;
  13655. } else {
  13656. s_copy(action, page_url, sizeof(action));
  13657. }
  13658. query[0] = '\0';
  13659. for (i = 0; i < doc.nnode; i++) {
  13660. struct br_node *nd = &doc.nodes[i];
  13661. struct form_state *fs;
  13662. const char *name;
  13663. const char *value = "";
  13664. if (nd->type != BR_NODE_ELEM || i == form ||
  13665. !form_descendant(i, form))
  13666. continue;
  13667. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  13668. nd->tag != BR_TAG_SELECT)
  13669. continue;
  13670. if (form_disabled(i))
  13671. continue;
  13672. name = br_find_attr(&doc, i, "name");
  13673. if (!name || !name[0])
  13674. continue;
  13675. fs = form_get(i, 1);
  13676. if (!fs)
  13677. continue;
  13678. if (nd->tag == BR_TAG_SELECT) {
  13679. char opt[64];
  13680. if (!form_option_text(i, fs->selected, opt,
  13681. sizeof(opt)))
  13682. s_copy(opt, "", sizeof(opt));
  13683. value = opt;
  13684. {
  13685. unsigned int c, oi = 0;
  13686. for (c = nd->first; c;
  13687. c = doc.nodes[c].next) {
  13688. if (doc.nodes[c].type != BR_NODE_ELEM ||
  13689. doc.nodes[c].tag != BR_TAG_OPTION)
  13690. continue;
  13691. if (oi == fs->selected) {
  13692. const char *v =
  13693. br_value(&doc, c);
  13694. if (v && v[0])
  13695. value = v;
  13696. break;
  13697. }
  13698. oi++;
  13699. }
  13700. }
  13701. } else if (nd->tag == BR_TAG_INPUT) {
  13702. int kind = form_kind_of(i);
  13703. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  13704. if (!fs->checked)
  13705. continue;
  13706. value = br_value(&doc, i);
  13707. if (!value || !value[0])
  13708. value = "on";
  13709. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  13710. kind == FORM_BUTTON) {
  13711. if (i != node)
  13712. continue;
  13713. value = fs->value;
  13714. } else {
  13715. value = fs->value;
  13716. }
  13717. } else {
  13718. value = fs->value;
  13719. }
  13720. form_add_param(query, &qn, sizeof(query), name, value, &first);
  13721. }
  13722. if (is_post) {
  13723. if (action[0] == '/') {
  13724. set_status("POST forms need an HTTP action URL", 1, 4000);
  13725. ngui_invalidate(&ui);
  13726. return 0;
  13727. }
  13728. if (qn >= sizeof(pending_post))
  13729. qn = sizeof(pending_post) - 1;
  13730. if (qn)
  13731. memcpy(pending_post, query, qn);
  13732. pending_post[qn] = '\0';
  13733. pending_post_len = qn;
  13734. pending_post_is = 1;
  13735. } else {
  13736. pending_post_len = 0;
  13737. pending_post_is = 0;
  13738. if (qn) {
  13739. unsigned int an = s_len(action);
  13740. if (an + qn + 2 < sizeof(action)) {
  13741. action[an++] = strchr(action, '?') ? '&' : '?';
  13742. action[an] = '\0';
  13743. s_copy(action + an, query,
  13744. sizeof(action) - an);
  13745. }
  13746. }
  13747. }
  13748. s_copy(pending_url, action, sizeof(pending_url));
  13749. pending_action |= ACT_NAV;
  13750. cancel_fetch = 1;
  13751. ngui_invalidate(&ui);
  13752. return 1;
  13753. }
  13754. static void form_reset_event(unsigned int form)
  13755. {
  13756. if (form && !js_browser_event(form, "reset", 1, 1))
  13757. return;
  13758. if (form)
  13759. form_reset_form(form);
  13760. else
  13761. form_reset_state();
  13762. form_dirty = 0;
  13763. layout_valid = 0;
  13764. ngui_invalidate(&ui);
  13765. }
  13766. static void form_blur(void)
  13767. {
  13768. unsigned int node = form_focus;
  13769. form_focus = 0;
  13770. if (node && form_dirty) {
  13771. form_dirty = 0;
  13772. js_browser_event(node, "change", 1, 0);
  13773. }
  13774. }
  13775. static void form_click(unsigned int node)
  13776. {
  13777. struct form_state *fs;
  13778. int kind, changed = 0;
  13779. if (!form_is_control(node) || form_disabled(node))
  13780. return;
  13781. if (form_focus != node)
  13782. form_blur();
  13783. fs = form_get(node, 1);
  13784. if (!fs)
  13785. return;
  13786. kind = form_kind_of(node);
  13787. /* Focus moves on the press, before `click` is dispatched: a page
  13788. * that cancels the click (a framework's root listener) suppresses
  13789. * the activation behaviour below, never the focus (as in other
  13790. * browsers, where focus follows mousedown). */
  13791. form_focus = node;
  13792. form_dirty = 0;
  13793. if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  13794. kind == FORM_TEXTAREA)
  13795. fs->caret = fs->len;
  13796. layout_valid = 0;
  13797. ngui_invalidate(&ui);
  13798. if (!js_browser_event(node, "click", 1, 1))
  13799. return;
  13800. fs = form_get(node, 0); /* the handler may have changed the DOM */
  13801. if (!fs)
  13802. return;
  13803. if (kind == FORM_CHECKBOX) {
  13804. fs->checked = !fs->checked;
  13805. changed = 1;
  13806. } else if (kind == FORM_RADIO) {
  13807. const char *name = br_find_attr(&doc, node, "name");
  13808. unsigned int i;
  13809. fs->checked = 1;
  13810. changed = 1;
  13811. if (name) {
  13812. for (i = 0; i < FORM_MAX; i++) {
  13813. struct form_state *o = &form_states[i];
  13814. if (!o->used || o->node == node)
  13815. continue;
  13816. if (form_kind_of(o->node) == FORM_RADIO) {
  13817. const char *on = br_find_attr(&doc,
  13818. o->node,
  13819. "name");
  13820. if (on && s_eq(on, name))
  13821. o->checked = 0;
  13822. }
  13823. }
  13824. }
  13825. } else if (kind == FORM_SELECT) {
  13826. unsigned int n = form_option_count(node);
  13827. if (n) {
  13828. fs->selected = (unsigned char)
  13829. ((fs->selected + 1) % n);
  13830. changed = 1;
  13831. }
  13832. } else if (kind == FORM_SUBMIT) {
  13833. form_submit_form(node, 1);
  13834. return;
  13835. } else if (kind == FORM_RESET) {
  13836. form_reset_event(form_ancestor(node));
  13837. return;
  13838. }
  13839. if (changed) {
  13840. js_browser_event(node, "input", 1, 0);
  13841. js_browser_event(node, "change", 1, 0);
  13842. }
  13843. layout_valid = 0;
  13844. ngui_invalidate(&ui);
  13845. }
  13846. static void form_focus_next(void)
  13847. {
  13848. unsigned int start = form_focus ? form_focus + 1 : 0;
  13849. unsigned int i;
  13850. form_blur();
  13851. for (i = start; i < doc.nnode; i++) {
  13852. if (form_is_control(i) && !form_disabled(i) &&
  13853. !s_eq(br_type(&doc, i), "hidden")) {
  13854. form_focus = i;
  13855. layout_valid = 0;
  13856. ngui_invalidate(&ui);
  13857. return;
  13858. }
  13859. }
  13860. form_focus = 0;
  13861. layout_valid = 0;
  13862. ngui_invalidate(&ui);
  13863. }
  13864. static void form_key(int k)
  13865. {
  13866. struct form_state *fs;
  13867. int kind;
  13868. if (!form_focus || form_focus >= doc.nnode) {
  13869. form_focus = 0;
  13870. return;
  13871. }
  13872. fs = form_get(form_focus, 1);
  13873. if (!fs || form_disabled(form_focus))
  13874. return;
  13875. kind = form_kind_of(form_focus);
  13876. if (kind == FORM_SELECT) {
  13877. unsigned int n = form_option_count(form_focus);
  13878. int changed = 0;
  13879. if (k == NGUI_KEY_UP && n) {
  13880. fs->selected = (unsigned char)
  13881. ((fs->selected + n - 1) % n);
  13882. changed = 1;
  13883. } else if (k == NGUI_KEY_DOWN && n) {
  13884. fs->selected = (unsigned char)
  13885. ((fs->selected + 1) % n);
  13886. changed = 1;
  13887. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  13888. form_blur();
  13889. layout_valid = 0;
  13890. ngui_invalidate(&ui);
  13891. return;
  13892. } else {
  13893. return;
  13894. }
  13895. if (changed) {
  13896. js_browser_event(form_focus, "input", 1, 0);
  13897. js_browser_event(form_focus, "change", 1, 0);
  13898. }
  13899. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  13900. if (k == ' ') {
  13901. form_click(form_focus);
  13902. return;
  13903. }
  13904. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  13905. form_blur();
  13906. layout_valid = 0;
  13907. ngui_invalidate(&ui);
  13908. }
  13909. return;
  13910. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  13911. kind == FORM_RESET) {
  13912. if (k == NGUI_KEY_ESC) {
  13913. form_blur();
  13914. layout_valid = 0;
  13915. ngui_invalidate(&ui);
  13916. } else if (k == '\r' || k == '\n' || k == ' ') {
  13917. form_click(form_focus);
  13918. }
  13919. return;
  13920. } else if (k == NGUI_KEY_TAB) {
  13921. form_focus_next();
  13922. return;
  13923. } else if (k == NGUI_KEY_ESC) {
  13924. form_blur();
  13925. layout_valid = 0;
  13926. ngui_invalidate(&ui);
  13927. return;
  13928. } else if (k == '\r' || k == '\n') {
  13929. unsigned int node = form_focus;
  13930. form_blur();
  13931. if (form_ancestor(node))
  13932. form_submit_form(node, 1);
  13933. layout_valid = 0;
  13934. ngui_invalidate(&ui);
  13935. return;
  13936. } else if (k == NGUI_KEY_BACKSPACE) {
  13937. if (fs->caret) {
  13938. unsigned int i = --fs->caret;
  13939. for (; i < fs->len; i++)
  13940. fs->value[i] = fs->value[i + 1];
  13941. if (fs->len)
  13942. fs->len--;
  13943. form_dirty = 1;
  13944. js_browser_event(form_focus, "input", 1, 0);
  13945. }
  13946. } else if (k == NGUI_KEY_DELETE) {
  13947. if (fs->caret < fs->len) {
  13948. unsigned int i;
  13949. for (i = fs->caret; i < fs->len; i++)
  13950. fs->value[i] = fs->value[i + 1];
  13951. fs->len--;
  13952. form_dirty = 1;
  13953. js_browser_event(form_focus, "input", 1, 0);
  13954. }
  13955. } else if (k == NGUI_KEY_LEFT) {
  13956. if (fs->caret)
  13957. fs->caret--;
  13958. } else if (k == NGUI_KEY_RIGHT) {
  13959. if (fs->caret < fs->len)
  13960. fs->caret++;
  13961. } else if (k == NGUI_KEY_HOME) {
  13962. fs->caret = 0;
  13963. } else if (k == NGUI_KEY_END) {
  13964. fs->caret = fs->len;
  13965. } else if (k >= 32 && k < 127) {
  13966. if (fs->len < FORM_VALUE_MAX) {
  13967. unsigned int i;
  13968. for (i = fs->len; i > fs->caret; i--)
  13969. fs->value[i] = fs->value[i - 1];
  13970. fs->value[fs->caret++] = (char)k;
  13971. fs->len++;
  13972. form_dirty = 1;
  13973. js_browser_event(form_focus, "input", 1, 0);
  13974. }
  13975. } else {
  13976. return;
  13977. }
  13978. fs->value[fs->len] = '\0';
  13979. layout_valid = 0;
  13980. ngui_invalidate(&ui);
  13981. }
  13982. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  13983. * a same-document navigation: update the URL and fire hashchange. Returns
  13984. * 1 when handled. */
  13985. static int link_fragment_nav(unsigned int node)
  13986. {
  13987. const char *href = br_href(&doc, node);
  13988. char url[BR_URL_MAX];
  13989. unsigned int n = 0;
  13990. if (!href || !href[0] || !js_browser_active())
  13991. return 0;
  13992. if (href[0] == '#') {
  13993. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  13994. url[n] = page_url[n];
  13995. n++;
  13996. }
  13997. url[n] = '\0';
  13998. s_append(url, &n, href, sizeof(url));
  13999. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  14000. return 0;
  14001. }
  14002. if (!same_doc_fragment(url))
  14003. return href[0] == '#';
  14004. page_set_fragment(url, 1);
  14005. js_browser_hashchange();
  14006. return 1;
  14007. }
  14008. /* A positioned box laid out while transparent or visibility:hidden (or
  14009. * inside one): it has a box for scripts but must not catch the pointer. */
  14010. static int node_invisible(unsigned int n)
  14011. {
  14012. unsigned int guard = 0;
  14013. while (n < doc.nnode && guard++ < 64) {
  14014. struct br_style st;
  14015. style_for_node(n, &st);
  14016. if (st.opacity_hidden || st.vis_hidden)
  14017. return 1;
  14018. if (n == 0)
  14019. break;
  14020. n = doc.nodes[n].parent;
  14021. }
  14022. return 0;
  14023. }
  14024. /* The innermost laid-out box under a screen point: the smallest valid box
  14025. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  14026. * Used to deliver clicks to elements that are neither links nor controls
  14027. * (a Vue <div role="button">, a card with a click listener). */
  14028. static int node_contains(unsigned int a, unsigned int n);
  14029. static unsigned int find_box_hit(int x, int y)
  14030. {
  14031. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  14032. int root;
  14033. /* A covering positioned box (a modal) takes the point: only it and
  14034. * its descendants are candidates, not the page painted under it. */
  14035. if (find_hit_ex(x, y, &root) || root < 0)
  14036. root = -1;
  14037. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  14038. const struct br_layout_box *b = &layout_boxes[i];
  14039. unsigned int area;
  14040. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  14041. x < b->x || y < b->y || x >= b->x + b->w ||
  14042. y >= b->y + b->h)
  14043. continue;
  14044. if (root >= 0 && !node_contains((unsigned int)root, i))
  14045. continue;
  14046. area = (unsigned int)b->w * (unsigned int)b->h;
  14047. if (area <= best_area && !node_invisible(i)) {
  14048. best = i;
  14049. best_area = area;
  14050. }
  14051. }
  14052. return best;
  14053. }
  14054. /* ---- page context menu ------------------------------------------------ */
  14055. static void ctx_add(unsigned int action, const char *label, const char *url)
  14056. {
  14057. int i;
  14058. if (ctx_n >= CTX_MAX || !url || !url[0])
  14059. return;
  14060. for (i = 0; i < ctx_n; i++)
  14061. if (ctx_action[i] == action && s_eq(ctx_url[i], url))
  14062. return;
  14063. s_copy(ctx_label[ctx_n], label, sizeof(ctx_label[0]));
  14064. s_copy(ctx_url[ctx_n], url, sizeof(ctx_url[0]));
  14065. ctx_action[ctx_n] = action;
  14066. ctx_n++;
  14067. }
  14068. static unsigned int ctx_ancestor_tag(unsigned int node, unsigned char tag)
  14069. {
  14070. unsigned int guard = 0;
  14071. while (node && node < doc.nnode && guard++ < BR_MAX_NODES) {
  14072. if (doc.nodes[node].type == BR_NODE_ELEM &&
  14073. doc.nodes[node].tag == tag)
  14074. return node;
  14075. node = doc.nodes[node].parent;
  14076. }
  14077. return 0;
  14078. }
  14079. static void ctx_open_at(struct ngui_rect page, int x, int y)
  14080. {
  14081. unsigned int hit = (unsigned int)find_hit(x, y);
  14082. unsigned int box = find_box_hit(x, y);
  14083. unsigned int img = 0;
  14084. char resolved[BR_URL_MAX];
  14085. const char *href;
  14086. ctx_open = 0;
  14087. ctx_n = 0;
  14088. if (box && doc.nodes[box].tag == BR_TAG_IMG)
  14089. img = box;
  14090. else if (hit && doc.nodes[hit].tag == BR_TAG_IMG)
  14091. img = hit;
  14092. else if (hit)
  14093. img = ctx_ancestor_tag(hit, BR_TAG_IMG);
  14094. if (!img && box)
  14095. img = ctx_ancestor_tag(box, BR_TAG_IMG);
  14096. if (img && br_src(&doc, img) &&
  14097. resolve_link(page_url, br_src(&doc, img), resolved,
  14098. sizeof(resolved)) == 0)
  14099. ctx_add(CTX_SAVE_IMAGE, "Save image", resolved);
  14100. /* A CSS background image is an image too; check the element under
  14101. * the pointer and then its ancestors (a card's image behind text). */
  14102. if (!img) {
  14103. unsigned int n = box ? box : hit, guard = 0;
  14104. while (n && n < doc.nnode && guard++ < BR_MAX_NODES) {
  14105. struct br_style st;
  14106. style_for_node(n, &st);
  14107. if (st.bg_image > 0) {
  14108. const char *bg = br_bg_image_url(st.bg_image - 1);
  14109. if (bg && resolve_link(page_url, bg, resolved,
  14110. sizeof(resolved)) == 0)
  14111. ctx_add(CTX_SAVE_IMAGE, "Save image",
  14112. resolved);
  14113. break;
  14114. }
  14115. n = doc.nodes[n].parent;
  14116. }
  14117. }
  14118. href = hit ? br_href(&doc, hit) : 0;
  14119. if (!href && box)
  14120. href = br_href(&doc, box);
  14121. if (href && resolve_link(page_url, href, resolved,
  14122. sizeof(resolved)) == 0)
  14123. ctx_add(CTX_SAVE_LINK, "Save link", resolved);
  14124. if (page_url[0] && !starts_with(page_url, "about:"))
  14125. ctx_add(CTX_SAVE_PAGE, "Save page", page_url);
  14126. if (!ctx_n)
  14127. return;
  14128. ctx_w = 190;
  14129. ctx_h = ctx_n * CTX_ROW_H + 2;
  14130. ctx_x = x;
  14131. ctx_y = y;
  14132. if (ctx_x + ctx_w > page.x + page.w - 4)
  14133. ctx_x = page.x + page.w - 4 - ctx_w;
  14134. if (ctx_y + ctx_h > page.y + page.h - 4)
  14135. ctx_y = page.y + page.h - 4 - ctx_h;
  14136. if (ctx_x < page.x + 4)
  14137. ctx_x = page.x + 4;
  14138. if (ctx_y < page.y + 4)
  14139. ctx_y = page.y + 4;
  14140. ctx_open = 1;
  14141. ngui_invalidate(&ui);
  14142. }
  14143. static void ctx_close(void)
  14144. {
  14145. if (!ctx_open)
  14146. return;
  14147. ctx_open = 0;
  14148. ngui_invalidate(&ui);
  14149. }
  14150. static void ctx_open_from_right(struct ngui_rect page)
  14151. {
  14152. if (!ui.right_pressed)
  14153. return;
  14154. if (ngui_rect_contains(&page, ui.right_press_x, ui.right_press_y)) {
  14155. dl_panel_open = 0;
  14156. ngui_set_focus(&ui, 0);
  14157. sug_close();
  14158. ctx_open_at(page, ui.right_press_x, ui.right_press_y);
  14159. } else {
  14160. ctx_close();
  14161. }
  14162. }
  14163. static void ctx_press(struct ngui_rect page)
  14164. {
  14165. struct ngui_rect r;
  14166. int row;
  14167. if (!ctx_open || !ui.pressed)
  14168. return;
  14169. r = (struct ngui_rect){ctx_x, ctx_y, ctx_w, ctx_h};
  14170. if (ngui_rect_contains(&r, ui.press_x, ui.press_y)) {
  14171. row = -1;
  14172. if (ui.press_y > ctx_y &&
  14173. ui.press_y < ctx_y + 1 + ctx_n * CTX_ROW_H)
  14174. row = (ui.press_y - ctx_y - 1) / CTX_ROW_H;
  14175. if (row >= 0 && row < ctx_n)
  14176. dl_queue(ctx_url[row]);
  14177. ctx_close();
  14178. ui.pressed = ui.released = 0;
  14179. return;
  14180. }
  14181. if (ngui_rect_contains(&page, ui.press_x, ui.press_y)) {
  14182. ctx_close();
  14183. ui.pressed = ui.released = 0;
  14184. return;
  14185. }
  14186. ctx_close();
  14187. }
  14188. static void draw_context(void)
  14189. {
  14190. struct ngui_rect r;
  14191. int i, hover = -1;
  14192. if (!ctx_open)
  14193. return;
  14194. r = (struct ngui_rect){ctx_x, ctx_y, ctx_w, ctx_h};
  14195. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  14196. if (ui.mouse_y > ctx_y &&
  14197. ui.mouse_y < ctx_y + 1 + ctx_n * CTX_ROW_H)
  14198. hover = (ui.mouse_y - ctx_y - 1) / CTX_ROW_H;
  14199. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  14200. }
  14201. ngui_fill_rect(&ui, r, ui.theme.border);
  14202. for (i = 0; i < ctx_n; i++) {
  14203. struct ngui_rect rr = {ctx_x + 1,
  14204. ctx_y + 1 + i * CTX_ROW_H, ctx_w - 2, CTX_ROW_H};
  14205. ngui_fill_rect(&ui, rr, i == hover ? ui.theme.selection :
  14206. ui.theme.panel);
  14207. ngui_text(&ui, rr.x + 10,
  14208. rr.y + (rr.h - ngui_text_line_height(&ui,
  14209. ui.font_px, 0)) / 2,
  14210. ctx_label[i], ui.theme.text);
  14211. }
  14212. }
  14213. /* The element under the pointer for hover events: the innermost laid-out
  14214. * box, or the link/control hit inside it (an inline <a> has no box of its
  14215. * own but a hit rectangle). -1 when none. */
  14216. static int hover_node = -1;
  14217. static int node_contains(unsigned int a, unsigned int n)
  14218. {
  14219. unsigned int guard = 0;
  14220. while (n < doc.nnode && guard++ < BR_MAX_NODES) {
  14221. if (n == a)
  14222. return 1;
  14223. if (n == 0)
  14224. return 0;
  14225. n = doc.nodes[n].parent;
  14226. }
  14227. return 0;
  14228. }
  14229. static int hover_target(void)
  14230. {
  14231. int h, x = ui.mouse_x, y = ui.mouse_y;
  14232. unsigned int b;
  14233. if (!ui.inside || ui.buttons || sug_visible() || ctx_open ||
  14234. dl_panel_open ||
  14235. x < page_rect.x || x >= page_rect.x + page_rect.w - 12 ||
  14236. y < page_rect.y || y >= page_rect.y + page_rect.h)
  14237. return -1;
  14238. h = find_hit(x, y);
  14239. b = find_box_hit(x, y);
  14240. if (h && (!b || node_contains(b, (unsigned int)h)))
  14241. return h;
  14242. if (b)
  14243. return (int)b;
  14244. return h ? h : -1;
  14245. }
  14246. /* mouseover/mouseout (bubbling, with relatedTarget) at the old and new
  14247. * element, and mouseleave/mouseenter on every ancestor that was left or
  14248. * entered (outermost first for enter), like a browser's boundary events.
  14249. * jQuery 1.11 builds its mouseenter (Bootstrap tooltips) from mouseover
  14250. * and relatedTarget. */
  14251. static void page_hover_events(void)
  14252. {
  14253. int now, old, cx, cy, path[64], np = 0, i;
  14254. unsigned int n;
  14255. if (!js_browser_active()) {
  14256. hover_node = -1;
  14257. return;
  14258. }
  14259. now = hover_target();
  14260. if (now >= (int)doc.nnode)
  14261. now = -1;
  14262. if (now == hover_node)
  14263. return;
  14264. old = hover_node;
  14265. if (old >= (int)doc.nnode)
  14266. old = -1;
  14267. hover_node = now;
  14268. cx = ui.mouse_x - page_rect.x;
  14269. cy = ui.mouse_y - page_rect.y;
  14270. if (old >= 0) {
  14271. js_browser_mouse_event((unsigned int)old, "mouseout", 1, now,
  14272. cx, cy);
  14273. for (n = (unsigned int)old, i = 0;
  14274. n < doc.nnode && i < 64 &&
  14275. !(now >= 0 && node_contains(n, (unsigned int)now)); i++) {
  14276. js_browser_mouse_event(n, "mouseleave", 0, now, cx, cy);
  14277. if (n == 0)
  14278. break;
  14279. n = doc.nodes[n].parent;
  14280. }
  14281. }
  14282. if (now < 0 || now >= (int)doc.nnode)
  14283. return;
  14284. js_browser_mouse_event((unsigned int)now, "mouseover", 1, old, cx, cy);
  14285. for (n = (unsigned int)now;
  14286. n < doc.nnode && np < 64 &&
  14287. !(old >= 0 && node_contains(n, (unsigned int)old));) {
  14288. path[np++] = (int)n;
  14289. if (n == 0)
  14290. break;
  14291. n = doc.nodes[n].parent;
  14292. }
  14293. for (i = np - 1; i >= 0; i--)
  14294. js_browser_mouse_event((unsigned int)path[i], "mouseenter", 0,
  14295. old, cx, cy);
  14296. }
  14297. static void handle_page_click(unsigned int *action)
  14298. {
  14299. int node;
  14300. char url[BR_URL_MAX];
  14301. if (!ui.pressed)
  14302. return;
  14303. if (ui.press_x < page_rect.x ||
  14304. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  14305. ui.press_y < page_rect.y ||
  14306. ui.press_y >= page_rect.y + page_rect.h)
  14307. return;
  14308. node = find_hit(ui.press_x, ui.press_y);
  14309. if (!node) {
  14310. unsigned int box;
  14311. if (!js_browser_active())
  14312. return;
  14313. box = find_box_hit(ui.press_x, ui.press_y);
  14314. if (box) {
  14315. form_blur();
  14316. js_browser_event(box, "click", 1, 1);
  14317. }
  14318. return;
  14319. }
  14320. if (form_is_control((unsigned int)node)) {
  14321. form_click((unsigned int)node);
  14322. return;
  14323. }
  14324. form_blur();
  14325. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  14326. return;
  14327. if (link_fragment_nav((unsigned int)node))
  14328. return;
  14329. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  14330. sizeof(url)) != 0)
  14331. return;
  14332. s_copy(click_url, url, sizeof(click_url));
  14333. *action |= ACT_NAV;
  14334. }
  14335. void _start(const char *arg)
  14336. {
  14337. struct win_info wi;
  14338. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  14339. u_win_create(960, 640, "Browser", &wi) != 0 &&
  14340. u_win_create(780, 540, "Browser", &wi) != 0) {
  14341. u_puts("browser: no graphics window\n");
  14342. u_exit(1);
  14343. }
  14344. ufont_set_arena_bytes(BR_FONT_ARENA);
  14345. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  14346. url_in.placeholder = "http://...";
  14347. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  14348. ui.theme.accent);
  14349. br_set_viewport(wi.width);
  14350. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  14351. s_copy(cwd, "/", sizeof(cwd));
  14352. heap_clear();
  14353. origin_cache_load();
  14354. css_cache_init();
  14355. script_cache_init();
  14356. font_cache_init();
  14357. persist_restore();
  14358. hist_load();
  14359. dl_load();
  14360. page_scroll.offset = 0;
  14361. page_scroll.content_h = 0;
  14362. if (arg && arg[0]) {
  14363. navigate(arg, 1);
  14364. } else {
  14365. load_home(1);
  14366. /* Start ready to type: keep the home page, but leave the address
  14367. * bar empty instead of showing "about:home". */
  14368. ngui_input_set(&url_in, "");
  14369. ngui_set_focus(&ui, ID_URL);
  14370. }
  14371. for (;;) {
  14372. unsigned int action = 0;
  14373. unsigned int now;
  14374. click_url[0] = '\0';
  14375. if (pending_action) {
  14376. action |= pending_action & ACT_WAIT_NAV;
  14377. if (pending_url[0])
  14378. s_copy(click_url, pending_url, sizeof(click_url));
  14379. pending_action = 0;
  14380. pending_url[0] = '\0';
  14381. cancel_fetch = 0;
  14382. } else if (preload_active) {
  14383. if (preload_wait)
  14384. preload_wait = 0;
  14385. else
  14386. preload_step();
  14387. } else if ((preload_pending &&
  14388. page_scroll.offset != preload_scroll) ||
  14389. (preload_rescan && layout_valid)) {
  14390. preload_scroll = page_scroll.offset;
  14391. preload_rescan = 0;
  14392. preload_pending = 0;
  14393. preload_node = 0;
  14394. preload_active = 1;
  14395. }
  14396. js_force_layout_pass_reset();
  14397. js_browser_tick();
  14398. if (resize_pending && !pending_action) {
  14399. resize_pending = 0;
  14400. resize_sent_w = layout_right - layout_left;
  14401. js_browser_window_event("resize");
  14402. }
  14403. persist_tick();
  14404. dl_poll();
  14405. if (pending_action)
  14406. continue;
  14407. now = u_ticks_ms();
  14408. if (status_until && (int)(now - status_until) >= 0) {
  14409. status_text[0] = '\0';
  14410. status_until = 0;
  14411. status_error = 0;
  14412. ngui_invalidate(&ui);
  14413. }
  14414. if (!ngui_begin(&ui)) {
  14415. /* A queued navigation (e.g. Enter in the URL bar during
  14416. * a slow fetch) must be handled even when this frame
  14417. * needs no redraw. */
  14418. if (!action) {
  14419. fetch_workers_stop_if_unfocused();
  14420. u_sleep_ms(10);
  14421. continue;
  14422. }
  14423. } else {
  14424. js_force_layout_pass_reset();
  14425. draw(&action);
  14426. handle_keys(&action);
  14427. handle_page_click(&action);
  14428. page_hover_events();
  14429. anim_after_frame();
  14430. ngui_end(&ui);
  14431. }
  14432. if (action & ACT_NAV) {
  14433. if (click_url[0]) {
  14434. navigate(click_url, 1);
  14435. click_url[0] = '\0';
  14436. } else {
  14437. navigate(url_in.text, 1);
  14438. }
  14439. }
  14440. if (action & ACT_BACK) {
  14441. if (hist_pos > 0) {
  14442. hist_pos--;
  14443. if (same_doc_fragment(history[hist_pos])) {
  14444. page_set_fragment(history[hist_pos], 0);
  14445. js_browser_hashchange();
  14446. } else {
  14447. navigate(history[hist_pos], 0);
  14448. }
  14449. }
  14450. }
  14451. if (action & ACT_FORWARD) {
  14452. if (hist_pos + 1 < hist_len) {
  14453. hist_pos++;
  14454. if (same_doc_fragment(history[hist_pos])) {
  14455. page_set_fragment(history[hist_pos], 0);
  14456. js_browser_hashchange();
  14457. } else {
  14458. navigate(history[hist_pos], 0);
  14459. }
  14460. }
  14461. }
  14462. if (action & ACT_RELOAD) {
  14463. if (s_eq(page_url, "about:home"))
  14464. load_home(0);
  14465. else
  14466. navigate(page_url, 0);
  14467. }
  14468. if (action & ACT_HOME)
  14469. load_home(1);
  14470. if (action & ACT_CLOSE)
  14471. quit = 1;
  14472. if (quit)
  14473. break;
  14474. if (pending_action)
  14475. continue;
  14476. fetch_workers_stop_if_unfocused();
  14477. u_sleep_ms(10);
  14478. }
  14479. fetch_workers_stop_all();
  14480. fetch_worker_stop(&dl_worker);
  14481. u_win_close();
  14482. u_exit(0);
  14483. }