browser.c 422 KB

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