browser.c 351 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286
  1. /* browser: a small HTML/CSS browser built on ngui, the image library and the
  2. * shared uhttp client.
  3. *
  4. * Page scripts run on the vendored QuickJS engine (modern ECMAScript) through
  5. * the DOM layer in js_browser.c; forms render and submit natively. External CSS is loaded over uhttp, and images are
  6. * decoded with img.c and drawn inline. Page-scoped buffers (page body,
  7. * rules and image bitmaps) come from the ring-3 libc heap; each image gets an
  8. * exact-size decode arena that is freed as soon as the scaled bitmap exists.
  9. * The DOM and the image/CSS I/O scratch use fixed static arenas.
  10. */
  11. #include <stdlib.h>
  12. #include <stdio.h>
  13. #include <string.h>
  14. #include <math.h>
  15. #include <ucmd_heap.h>
  16. #include "ucmd_lib.h"
  17. #include "ngui.h"
  18. #include "browser_html.h"
  19. #include "js_browser.h"
  20. #include "uhttp.h"
  21. #include "uhttp_cookie.h"
  22. #include "img.h"
  23. #include "inflate.h"
  24. #include "ufont.h"
  25. #include "svg_raster.h"
  26. static void svg_cache_clear(void);
  27. static unsigned char *decode_arena; /* see decode_arena_get() */
  28. static unsigned int decode_arena_size;
  29. /* Start wide enough for the desktop nav; smaller screens fall back to
  30. * 960x640 and 780x540, which still fit a 1024x768 panel. */
  31. #define BR_W 1100
  32. #define BR_H 700
  33. #define BR_TOOLBAR_H 30
  34. #define BR_STATUS_H 18
  35. #define BR_PAGE_MAX (2u * 1024u * 1024u)
  36. #define BR_IMG_FILE_MAX (1024u * 1024u)
  37. #define BR_IMG_PIX_MAX (8u * 1024u * 1024u)
  38. #define BR_MAX_IMAGES 256
  39. /* Decoded display bitmaps share the page heap: cap their total pixels
  40. * (RGB565 plus an optional alpha plane) instead of their count. */
  41. #define BR_IMG_PIXEL_BUDGET (4u * 1024u * 1024u)
  42. #define BR_IMG_DISP_BUDGET (6u * 1024u * 1024u)
  43. #define BR_IMG_ARENA_MAX (24u * 1024u * 1024u)
  44. #define BR_IMG_LAYOUT_W 1000
  45. /* Decode completed image jobs for at most this long per main-loop pass, then
  46. * return to input/painting. One image per pass plus a 10 ms sleep made a
  47. * page of small icons trickle in. */
  48. #define BR_IMG_DECODE_BUDGET_MS 40u
  49. /* Coalesce image-driven repaints: each decode invalidates the page, and a
  50. * full repaint per image made loading superlinear on image-heavy pages. */
  51. #define BR_IMG_REPAINT_MS 100u
  52. #define BR_IMG_STAT_LOG 3584
  53. /* An image job may hold a fetch helper this long. The page/script
  54. * deadline (UHTTP_TOTAL_TIMEOUT_MS) is minutes; one unreachable image host
  55. * must not starve the other images of all four helpers that long. */
  56. #define BR_IMG_JOB_TIMEOUT_MS 30000u
  57. #define BR_CSS_MAX (832u * 1024u)
  58. #define BR_CSS_COMP_MAX (192u * 1024u)
  59. /* Scripts and ES modules: Vite bundles reach ~1.7 MB (the Cloudron
  60. * dashboard's main chunk); the helper's FETCH_MAX is the same 2 MB. */
  61. #define BR_SCRIPT_MAX (2u * 1024u * 1024u)
  62. #define FETCH_ABORT (-2)
  63. /* Session cache for remote stylesheets (per launch; cleared at startup). */
  64. #define CSS_CACHE_MAX 16
  65. #define CSS_CACHE_FILE_MAX (256u * 1024u)
  66. #define CSS_CACHE_PREFIX "bcss-"
  67. #define SCRIPT_CACHE_MAX 24
  68. #define SCRIPT_CACHE_FILE_MAX BR_SCRIPT_MAX
  69. #define SCRIPT_CACHE_PREFIX "bjs-"
  70. #define BR_MAX_SHEETS 6
  71. #define BR_HISTORY 16
  72. #define BR_URL_MAX 4096 /* = UHTTP_PATH_MAX: google.com's JS URL is ~3.7 KB */
  73. #define BR_STATUS_MAX 200
  74. #define BR_IMG_RGB565(r, g, b) \
  75. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  76. #define BR_GRAY 0x8410
  77. enum {
  78. ID_URL = 1,
  79. ID_GO,
  80. ID_BACK,
  81. ID_FORWARD,
  82. ID_RELOAD,
  83. ID_HOME
  84. };
  85. #define ACT_NAV (1u << 0)
  86. #define ACT_BACK (1u << 1)
  87. #define ACT_FORWARD (1u << 2)
  88. #define ACT_RELOAD (1u << 3)
  89. #define ACT_HOME (1u << 4)
  90. #define ACT_CLOSE (1u << 5)
  91. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  92. ACT_HOME | ACT_CLOSE)
  93. struct br_image {
  94. int state; /* 0 empty, 1 ready */
  95. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  96. int native_w, native_h;
  97. unsigned int url_hash; /* <img> source, 0 = not shareable */
  98. char err[32];
  99. /* Display-size cache: the box an image is actually painted in. The
  100. * source bitmap above is deliberately capped at BR_IMG_LAYOUT_W so a
  101. * window resize can re-scale it; the cached copy is exactly dw x dh,
  102. * so every repaint is a 1:1 blit instead of a per-pixel resample. */
  103. struct img_image disp;
  104. unsigned int disp_pixels;
  105. unsigned int disp_last;
  106. };
  107. static struct ngui ui;
  108. static struct ngui_input url_in;
  109. static struct ngui_scroll page_scroll;
  110. static struct br_doc doc;
  111. static struct br_image images[BR_MAX_IMAGES];
  112. static int image_count;
  113. static unsigned int image_pixels;
  114. static unsigned int image_disp_pixels;
  115. static unsigned int image_disp_clock;
  116. /* Per-image pipeline timing for the status line and /share/IMGSTAT. The
  117. * numbers are what decides whether the next work is network, decode or
  118. * display; keep them cheap (one tick read per phase). */
  119. static unsigned int img_stat_start;
  120. static unsigned int img_stat_wall;
  121. static unsigned int img_stat_net;
  122. static unsigned int img_stat_open;
  123. static unsigned int img_stat_first;
  124. static unsigned int img_stat_io;
  125. static unsigned int img_stat_dec;
  126. static unsigned int img_stat_scale;
  127. static unsigned int img_stat_paint;
  128. static unsigned int img_stat_reflow;
  129. static unsigned int img_stat_bytes;
  130. static int img_stat_n;
  131. static unsigned int img_last_dec_ms;
  132. static unsigned int img_last_scale_ms;
  133. static char img_stat_log[BR_IMG_STAT_LOG];
  134. static unsigned int img_stat_log_len;
  135. static unsigned int img_repaint_ms;
  136. static int img_repaint_pending;
  137. /* Painted border boxes, in page/screen coordinates (layout starts at
  138. * page_rect.y + 4 - scroll). getBoundingClientRect() subtracts page_rect. */
  139. struct br_layout_box {
  140. int x, y;
  141. int w, h;
  142. unsigned char valid;
  143. };
  144. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  145. /* Images are loaded one per main-loop iteration so the parsed page stays
  146. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  147. static int preload_active;
  148. static int preload_max_jobs;
  149. static int preload_pending;
  150. static int preload_wait;
  151. static unsigned int preload_node;
  152. static int preload_loaded;
  153. static int preload_scroll;
  154. static int preload_rescan;
  155. static char post_status_text[BR_STATUS_MAX];
  156. static int post_status_error;
  157. static unsigned int post_status_ttl;
  158. /* Content-relative position/height of each <img>, recorded by the measure
  159. * pass so image loading can be deferred until it is near the viewport. */
  160. static unsigned short img_top[BR_MAX_NODES];
  161. static unsigned short img_h[BR_MAX_NODES];
  162. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  163. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  164. * body. Decode arenas are allocated per image instead of living here. */
  165. static unsigned char *image_io_buf;
  166. static struct ufont_face *font_faces[BR_MAX_FACES];
  167. #define image_file_buf (image_io_buf)
  168. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  169. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  170. static struct inflate image_inflate_ws;
  171. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  172. #error "CSS scratch must fit in image_io_buf"
  173. #endif
  174. static char page_url[BR_URL_MAX];
  175. static char page_title[BR_TITLE_MAX];
  176. static char cwd[64];
  177. static int page_is_local;
  178. static int page_loading;
  179. static char status_text[BR_STATUS_MAX];
  180. static unsigned int status_until;
  181. static int status_error;
  182. static char history[BR_HISTORY][BR_URL_MAX];
  183. static int hist_len, hist_pos;
  184. static char click_url[BR_URL_MAX];
  185. static char pending_url[BR_URL_MAX];
  186. #define BR_POST_MAX 4096
  187. static char pending_post[BR_POST_MAX];
  188. static unsigned int pending_post_len;
  189. /* The pending navigation is a POST even when its body is empty (a form
  190. * without fields, e.g. the OIDC consent auto-submit). */
  191. static int pending_post_is;
  192. /* window "resize" bookkeeping: the page width the last event was for. */
  193. static int resize_sent_w = -1;
  194. static int resize_pending;
  195. static unsigned int pending_action;
  196. static int cancel_fetch;
  197. static int quit;
  198. static struct ngui_rect page_rect;
  199. static unsigned short *page_backbuf;
  200. static int pagebuf_w, pagebuf_h;
  201. static int page_cache_valid;
  202. static int page_cache_scroll;
  203. static unsigned int page_cache_nnode;
  204. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  205. static int layout_valid, layout_left, layout_right;
  206. /* Height of the page viewport: what html/body height:100% resolves to. */
  207. static int layout_view_h;
  208. static unsigned int layout_nnode;
  209. static int layout_content_h;
  210. /* layout output */
  211. struct lay_run {
  212. unsigned int off;
  213. unsigned short len;
  214. unsigned short gap;
  215. unsigned short color;
  216. unsigned short href;
  217. char lit[28];
  218. short img;
  219. signed short dy; /* inline image vertical offset */
  220. unsigned short iw, ih;
  221. unsigned short w;
  222. unsigned char font_px, bold, italic, mono, underline, strike;
  223. unsigned char overline, font_face;
  224. unsigned char transform_scale;
  225. unsigned char origin_x_kind, origin_y_kind;
  226. signed short scale_x, scale_y, rotate_x100;
  227. signed short origin_x, origin_y;
  228. unsigned char has_lit;
  229. unsigned int form; /* node + 1, 0 = not a control */
  230. unsigned char form_kind;
  231. unsigned char form_disabled;
  232. /* RUN_PBOX: background colour, background image and its placement
  233. * inside the iw x ih box (relative offsets, drawn size). */
  234. unsigned char pb_has_bg;
  235. unsigned short pb_bg;
  236. short pb_img;
  237. short pb_x, pb_y, pb_w, pb_h;
  238. };
  239. struct lay {
  240. int draw;
  241. struct ngui *ui;
  242. int left, right;
  243. int y;
  244. int line_x, line_y, line_h;
  245. int line_left, line_right;
  246. int parent_top;
  247. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  248. int cb_h; /* definite content height of the containing block for
  249. * percentage heights; 0 = indefinite (auto) */
  250. int run_x;
  251. int align;
  252. int depth;
  253. int space_pending;
  254. unsigned char float_active;
  255. int float_left, float_right, float_bottom;
  256. struct lay_run runs[96];
  257. int nruns;
  258. };
  259. struct hit {
  260. int x, y, w, h;
  261. unsigned short node;
  262. };
  263. /* Live form state; the DOM attributes stay the initial/default value. */
  264. #define FORM_MAX 64
  265. #define FORM_VALUE_MAX 63
  266. enum {
  267. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  268. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  269. };
  270. struct form_state {
  271. unsigned int node;
  272. char value[FORM_VALUE_MAX + 1];
  273. unsigned char len, caret, checked, selected, used;
  274. };
  275. static struct form_state form_states[FORM_MAX];
  276. static unsigned int form_focus;
  277. static unsigned int form_dirty;
  278. static int form_descendant(unsigned int node, unsigned int form);
  279. static int form_submit_form(unsigned int node, int fire_event);
  280. static int link_fragment_nav(unsigned int node);
  281. static void history_push(const char *url);
  282. static void form_reset_event(unsigned int form);
  283. static unsigned int s_len(const char *s);
  284. static int s_eq(const char *a, const char *b);
  285. static void form_key(int k);
  286. static void form_click(unsigned int node);
  287. static void style_for_node(unsigned int node, struct br_style *out);
  288. static int form_author_styled(const struct br_style *st);
  289. static int css_radius(const struct br_style *st, int corner, int w, int h);
  290. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  291. const struct br_style *st, int focused);
  292. static int form_disabled(unsigned int node)
  293. {
  294. struct br_node *n = &doc.nodes[node];
  295. if (n->attr_flags & BR_ATTR_DISABLED)
  296. return 1;
  297. return br_find_attr(&doc, node, "disabled") != 0;
  298. }
  299. static int form_kind_of(unsigned int node)
  300. {
  301. const char *type = br_type(&doc, node);
  302. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  303. return FORM_TEXTAREA;
  304. if (doc.nodes[node].tag == BR_TAG_SELECT)
  305. return FORM_SELECT;
  306. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  307. if (s_eq(type, "reset"))
  308. return FORM_RESET;
  309. if (s_eq(type, "button"))
  310. return FORM_BUTTON;
  311. return FORM_SUBMIT;
  312. }
  313. if (s_eq(type, "password"))
  314. return FORM_PASSWORD;
  315. if (s_eq(type, "checkbox"))
  316. return FORM_CHECKBOX;
  317. if (s_eq(type, "radio"))
  318. return FORM_RADIO;
  319. if (s_eq(type, "submit"))
  320. return FORM_SUBMIT;
  321. if (s_eq(type, "reset"))
  322. return FORM_RESET;
  323. if (s_eq(type, "button"))
  324. return FORM_BUTTON;
  325. return FORM_TEXT;
  326. }
  327. static unsigned int form_option_count(unsigned int node)
  328. {
  329. unsigned int c, n = 0;
  330. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  331. if (doc.nodes[c].type == BR_NODE_ELEM &&
  332. doc.nodes[c].tag == BR_TAG_OPTION)
  333. n++;
  334. return n;
  335. }
  336. static unsigned int form_option_selected(unsigned int node)
  337. {
  338. unsigned int c, i = 0;
  339. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  340. if (doc.nodes[c].type != BR_NODE_ELEM ||
  341. doc.nodes[c].tag != BR_TAG_OPTION)
  342. continue;
  343. if (br_find_attr(&doc, c, "selected"))
  344. return i;
  345. i++;
  346. }
  347. return 0;
  348. }
  349. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  350. char *out, unsigned int cap)
  351. {
  352. unsigned int c, i = 0;
  353. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  354. if (doc.nodes[c].type != BR_NODE_ELEM ||
  355. doc.nodes[c].tag != BR_TAG_OPTION)
  356. continue;
  357. if (i == idx)
  358. return br_text_content(&doc, c, out, cap);
  359. i++;
  360. }
  361. return 0;
  362. }
  363. static struct form_state *form_get(unsigned int node, int create)
  364. {
  365. struct form_state *slot = 0;
  366. unsigned int i;
  367. for (i = 0; i < FORM_MAX; i++) {
  368. if (form_states[i].used) {
  369. if (form_states[i].node == node)
  370. return &form_states[i];
  371. } else if (!slot) {
  372. slot = &form_states[i];
  373. }
  374. }
  375. if (!create || !slot)
  376. return 0;
  377. slot->node = node;
  378. slot->len = 0;
  379. slot->caret = 0;
  380. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  381. slot->selected = form_option_selected(node);
  382. slot->used = 1;
  383. {
  384. unsigned int n = 0;
  385. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  386. n = br_text_content(&doc, node, slot->value,
  387. FORM_VALUE_MAX + 1);
  388. } else {
  389. const char *v = br_value(&doc, node);
  390. if (v) {
  391. n = s_len(v);
  392. if (n > FORM_VALUE_MAX)
  393. n = FORM_VALUE_MAX;
  394. for (unsigned int j = 0; j < n; j++)
  395. slot->value[j] = v[j];
  396. }
  397. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  398. n = br_text_content(&doc, node, slot->value,
  399. FORM_VALUE_MAX + 1);
  400. }
  401. if (n > FORM_VALUE_MAX)
  402. n = FORM_VALUE_MAX;
  403. slot->value[n] = '\0';
  404. slot->len = (unsigned char)n;
  405. slot->caret = (unsigned char)n;
  406. }
  407. return slot;
  408. }
  409. static void form_reset_state(void)
  410. {
  411. unsigned int i;
  412. for (i = 0; i < FORM_MAX; i++)
  413. form_states[i].used = 0;
  414. form_focus = 0;
  415. }
  416. /* A <button> with element content (an icon <svg>/<img>, a <span> label)
  417. * is laid out like a normal element so that content shows; only a text or
  418. * empty button is drawn as a native control. Clicks still reach it
  419. * through the box hit test. */
  420. static int button_has_elements(unsigned int node)
  421. {
  422. unsigned int c;
  423. if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
  424. return 0;
  425. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  426. if (doc.nodes[c].type == BR_NODE_ELEM)
  427. return 1;
  428. /* An empty button whose icon is a ::before/::after box (Docusaurus'
  429. * sidebar caret) is laid out as an element so the box is drawn. */
  430. if (!doc.nodes[node].first && doc.npe_rules) {
  431. struct br_style st, ps;
  432. char buf[8];
  433. int pe;
  434. style_for_node(node, &st);
  435. for (pe = 1; pe <= 2; pe++)
  436. if (!br_pseudo(&doc, node, pe, &st, &ps, buf,
  437. sizeof(buf)) &&
  438. ps.content == BR_CONTENT_EMPTY &&
  439. ps.display != BR_DISPLAY_NONE)
  440. return 1;
  441. }
  442. return 0;
  443. }
  444. static int form_is_control(unsigned int node)
  445. {
  446. unsigned int tag;
  447. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  448. return 0;
  449. tag = doc.nodes[node].tag;
  450. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  451. tag == BR_TAG_SELECT ||
  452. (tag == BR_TAG_BUTTON && !button_has_elements(node));
  453. }
  454. #define HIT_MAX 96
  455. static struct hit hits[HIT_MAX];
  456. static int nhits;
  457. static unsigned short block_h[BR_MAX_NODES];
  458. /* Measure-pass top of each block, in the same document coordinates as
  459. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  460. * paint, so it cannot drive the lazy background loader). */
  461. static unsigned short block_top[BR_MAX_NODES];
  462. static char li_marker[BR_MAX_NODES][12];
  463. /* one connection object; the browser fetches one resource at a time */
  464. /* ---- tiny strings ---- */
  465. static unsigned int s_len(const char *s)
  466. {
  467. unsigned int n = 0;
  468. while (s && s[n])
  469. n++;
  470. return n;
  471. }
  472. static void s_copy(char *d, const char *s, unsigned int cap)
  473. {
  474. unsigned int i = 0;
  475. if (!cap)
  476. return;
  477. while (s && s[i] && i + 1 < cap) {
  478. d[i] = s[i];
  479. i++;
  480. }
  481. d[i] = '\0';
  482. }
  483. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  484. {
  485. while (s && *s && *n + 1 < cap)
  486. d[(*n)++] = *s++;
  487. d[*n] = '\0';
  488. }
  489. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  490. unsigned int cap)
  491. {
  492. char tmp[12];
  493. unsigned int i = 0, j;
  494. do {
  495. tmp[i++] = (char)('0' + v % 10);
  496. v /= 10;
  497. } while (v && i < sizeof(tmp));
  498. for (j = 0; j < i && *n + 1 < cap; j++)
  499. d[(*n)++] = tmp[i - 1 - j];
  500. d[*n] = '\0';
  501. }
  502. static int s_eq(const char *a, const char *b)
  503. {
  504. while (*a && *b) {
  505. if (*a != *b)
  506. return 0;
  507. a++;
  508. b++;
  509. }
  510. return *a == *b;
  511. }
  512. static int starts_with(const char *s, const char *p)
  513. {
  514. unsigned int i = 0;
  515. while (p[i]) {
  516. if (s[i] != p[i])
  517. return 0;
  518. i++;
  519. }
  520. return 1;
  521. }
  522. static int contains_ci(const char *s, const char *p)
  523. {
  524. unsigned int i, j;
  525. for (i = 0; s[i]; i++) {
  526. for (j = 0; p[j]; j++) {
  527. char a = s[i + j];
  528. if (a >= 'A' && a <= 'Z')
  529. a = (char)(a - 'A' + 'a');
  530. if (a != p[j])
  531. break;
  532. }
  533. if (!p[j])
  534. return 1;
  535. }
  536. return 0;
  537. }
  538. static char *trim(char *s)
  539. {
  540. unsigned int n;
  541. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  542. s++;
  543. n = s_len(s);
  544. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  545. s[n - 1] == '\r' || s[n - 1] == '\n'))
  546. s[--n] = '\0';
  547. return s;
  548. }
  549. /* ---- per-process heap ---- */
  550. static int heap_start(void)
  551. {
  552. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  553. if (!image_io_buf)
  554. return -1;
  555. page_backbuf = (unsigned short *)malloc(
  556. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  557. pagebuf_w = page_backbuf ? ui.w : 0;
  558. pagebuf_h = page_backbuf ? ui.h : 0;
  559. page_cache_valid = 0;
  560. return 0;
  561. }
  562. static void heap_clear(void)
  563. {
  564. memset(font_faces, 0, sizeof(font_faces));
  565. ngui_font_detach(&ui);
  566. svg_cache_clear();
  567. decode_arena = 0; /* lives in the page heap too */
  568. decode_arena_size = 0;
  569. heap_reset();
  570. /* The document arenas live in that heap; drop the stale pointers so
  571. * the next br_parse_plain() allocates fresh ones. */
  572. doc.nodes = 0;
  573. doc.text = 0;
  574. doc.attrs = 0;
  575. image_io_buf = 0;
  576. page_backbuf = 0;
  577. pagebuf_w = pagebuf_h = 0;
  578. page_cache_valid = 0;
  579. }
  580. static void browser_rules_alloc(void)
  581. {
  582. struct br_rule *rules;
  583. rules = (struct br_rule *)malloc(
  584. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  585. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  586. }
  587. /* ---- status ---- */
  588. static void set_status(const char *s, int err, unsigned int ttl_ms)
  589. {
  590. s_copy(status_text, s, sizeof(status_text));
  591. status_error = err;
  592. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  593. ngui_invalidate(&ui);
  594. }
  595. /* Update the status text without forcing a frame; the throttled image
  596. * repaint picks it up. Starting one helper per image used to invalidate the
  597. * whole page before every decode. */
  598. static void set_status_quiet(const char *s)
  599. {
  600. s_copy(status_text, s, sizeof(status_text));
  601. status_error = 0;
  602. status_until = 0;
  603. }
  604. /* ---- JavaScript ---- */
  605. static int resolve_link(const char *base, const char *href, char *out,
  606. unsigned int cap);
  607. static char js_last_status[BR_STATUS_MAX];
  608. static int js_last_error;
  609. static void js_host_status(const char *msg, int error)
  610. {
  611. s_copy(js_last_status, msg, sizeof(js_last_status));
  612. js_last_error = error;
  613. set_status(msg, error, 6000);
  614. }
  615. static void js_host_report(const char *msg)
  616. {
  617. u_puts("[js] ");
  618. u_puts(msg);
  619. u_putc('\n');
  620. s_copy(js_last_status, msg, sizeof(js_last_status));
  621. js_last_error = 1;
  622. set_status(msg, 1, 8000);
  623. }
  624. static void js_host_navigate(const char *url)
  625. {
  626. char resolved[BR_URL_MAX];
  627. if (!url || !url[0])
  628. return;
  629. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  630. return;
  631. s_copy(pending_url, resolved, sizeof(pending_url));
  632. pending_action |= ACT_NAV;
  633. cancel_fetch = 1;
  634. }
  635. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  636. * back/forward between fragments): the page URL, address bar and history
  637. * follow, nothing is reloaded. `push` adds a history entry. */
  638. static int page_set_fragment(const char *url, int push)
  639. {
  640. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  641. return -1;
  642. s_copy(page_url, url, sizeof(page_url));
  643. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  644. url_in.len = s_len(url_in.text);
  645. url_in.cursor = url_in.len;
  646. url_in.scroll = 0;
  647. if (push)
  648. history_push(page_url);
  649. ngui_invalidate(&ui);
  650. return 0;
  651. }
  652. static int js_host_set_hash(const char *url)
  653. {
  654. return page_set_fragment(url, 1);
  655. }
  656. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  657. * the page, so a hash router can react). */
  658. static int same_doc_fragment(const char *url)
  659. {
  660. unsigned int a = 0, b = 0;
  661. if (!js_browser_active() || !url)
  662. return 0;
  663. while (url[a] && url[a] != '#')
  664. a++;
  665. while (page_url[b] && page_url[b] != '#')
  666. b++;
  667. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  668. !s_eq(url, page_url);
  669. }
  670. static void js_host_changed(void)
  671. {
  672. /* Class/style/attribute mutations change computed styles, not just the
  673. * text: drop the per-node style cache before the next layout. */
  674. br_reset_styles(&doc);
  675. layout_valid = 0;
  676. /* Script-built content (Angular's ng-repeat cards) brings new images
  677. * and inline background styles: rescan once the main loop is idle. */
  678. preload_rescan = 1;
  679. ngui_invalidate(&ui);
  680. }
  681. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  682. {
  683. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  684. return 0;
  685. *x = layout_boxes[node].x - page_rect.x;
  686. *y = layout_boxes[node].y - page_rect.y;
  687. *w = layout_boxes[node].w;
  688. *h = layout_boxes[node].h;
  689. return 1;
  690. }
  691. static void form_copy_out(const char *s, char *buf, int cap)
  692. {
  693. int i = 0;
  694. if (!buf || cap <= 0)
  695. return;
  696. while (s && s[i] && i + 1 < cap) {
  697. buf[i] = s[i];
  698. i++;
  699. }
  700. buf[i] = '\0';
  701. }
  702. static int js_host_form_value(unsigned int node, char *buf, int cap)
  703. {
  704. struct form_state *fs;
  705. int kind;
  706. if (!form_is_control(node))
  707. return 0;
  708. kind = form_kind_of(node);
  709. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  710. return 0;
  711. if (kind == FORM_SELECT) {
  712. char opt[64] = "";
  713. unsigned int c, i = 0;
  714. fs = form_get(node, 1);
  715. if (!fs)
  716. return 0;
  717. form_option_text(node, fs->selected, opt, sizeof(opt));
  718. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  719. if (doc.nodes[c].type != BR_NODE_ELEM ||
  720. doc.nodes[c].tag != BR_TAG_OPTION)
  721. continue;
  722. if (i == fs->selected) {
  723. const char *v = br_value(&doc, c);
  724. if (v && v[0])
  725. form_copy_out(v, buf, cap);
  726. else
  727. form_copy_out(opt, buf, cap);
  728. return 1;
  729. }
  730. i++;
  731. }
  732. form_copy_out(opt, buf, cap);
  733. return 1;
  734. }
  735. fs = form_get(node, 1);
  736. if (!fs)
  737. return 0;
  738. form_copy_out(fs->value, buf, cap);
  739. return 1;
  740. }
  741. static int js_host_form_checked(unsigned int node)
  742. {
  743. struct form_state *fs;
  744. int kind;
  745. if (!form_is_control(node))
  746. return -1;
  747. kind = form_kind_of(node);
  748. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  749. return -1;
  750. fs = form_get(node, 1);
  751. return fs ? fs->checked : 0;
  752. }
  753. static int js_host_form_selected(unsigned int node)
  754. {
  755. struct form_state *fs;
  756. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  757. return -1;
  758. fs = form_get(node, 1);
  759. return fs ? fs->selected : 0;
  760. }
  761. static int js_host_form_set_value(unsigned int node, const char *value)
  762. {
  763. struct form_state *fs;
  764. unsigned int n;
  765. if (!form_is_control(node))
  766. return 0;
  767. fs = form_get(node, 1);
  768. if (!fs)
  769. return 0;
  770. n = s_len(value ? value : "");
  771. if (n > FORM_VALUE_MAX)
  772. n = FORM_VALUE_MAX;
  773. for (unsigned int i = 0; i < n; i++)
  774. fs->value[i] = value[i];
  775. fs->value[n] = '\0';
  776. fs->len = (unsigned char)n;
  777. fs->caret = (unsigned char)n;
  778. layout_valid = 0;
  779. ngui_invalidate(&ui);
  780. return 1;
  781. }
  782. static int js_host_form_set_checked(unsigned int node, int checked)
  783. {
  784. struct form_state *fs;
  785. int kind;
  786. if (!form_is_control(node))
  787. return 0;
  788. kind = form_kind_of(node);
  789. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  790. return 0;
  791. fs = form_get(node, 1);
  792. if (!fs)
  793. return 0;
  794. fs->checked = (unsigned char)(checked != 0);
  795. layout_valid = 0;
  796. ngui_invalidate(&ui);
  797. return 1;
  798. }
  799. static int js_host_form_set_selected(unsigned int node, int index)
  800. {
  801. struct form_state *fs;
  802. unsigned int n;
  803. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  804. return 0;
  805. fs = form_get(node, 1);
  806. if (!fs)
  807. return 0;
  808. n = form_option_count(node);
  809. if (index < 0)
  810. index = 0;
  811. if (n && (unsigned int)index >= n)
  812. index = (int)n - 1;
  813. fs->selected = (unsigned char)index;
  814. layout_valid = 0;
  815. ngui_invalidate(&ui);
  816. return 1;
  817. }
  818. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  819. {
  820. unsigned int i;
  821. int n = 0;
  822. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  823. doc.nodes[form].tag != BR_TAG_FORM)
  824. return 0;
  825. for (i = 0; i < doc.nnode && n < cap; i++) {
  826. struct br_node *nd = &doc.nodes[i];
  827. if (i == form || nd->type != BR_NODE_ELEM)
  828. continue;
  829. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  830. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  831. continue;
  832. if (!form_descendant(i, form))
  833. continue;
  834. out[n++] = i;
  835. }
  836. return n;
  837. }
  838. static int js_host_form_submit(unsigned int form)
  839. {
  840. form_submit_form(form, 0);
  841. return 1;
  842. }
  843. static int js_host_form_reset(unsigned int form)
  844. {
  845. form_reset_event(form);
  846. return 1;
  847. }
  848. static void css_computed_name(const char *p, char *out, int cap)
  849. {
  850. int n = 0;
  851. for (; p && *p && n + 2 < cap; p++) {
  852. char c = *p;
  853. if (c >= 'A' && c <= 'Z') {
  854. out[n++] = '-';
  855. c = (char)(c - 'A' + 'a');
  856. } else if (c == '_') {
  857. c = '-';
  858. } else if (c >= 'a' && c <= 'z') {
  859. /* keep */
  860. }
  861. out[n++] = c;
  862. }
  863. out[n] = '\0';
  864. if (!strcmp(out, "css-float"))
  865. strcpy(out, "float");
  866. }
  867. static void css_rgb(unsigned short c, char *buf, int cap)
  868. {
  869. int r = ((c >> 11) & 31) * 255 / 31;
  870. int g = ((c >> 5) & 63) * 255 / 63;
  871. int b = (c & 31) * 255 / 31;
  872. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  873. }
  874. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  875. int font_px)
  876. {
  877. if (unit == 4) {
  878. snprintf(buf, cap, "auto");
  879. } else if (unit == 0) {
  880. snprintf(buf, cap, "%dpx", raw);
  881. } else if (unit == 1) {
  882. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  883. } else if (unit == 2) {
  884. /* Chrome's getComputedStyle() reports used pixel values. */
  885. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  886. } else if (unit == 3) {
  887. snprintf(buf, cap, "%dpx",
  888. (int)br_root_font_px() * raw / 100);
  889. } else {
  890. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  891. raw / 100, raw % 100, px);
  892. }
  893. }
  894. static int js_host_computed(unsigned int node, const char *property,
  895. char *buf, int cap)
  896. {
  897. struct br_style st;
  898. char name[40];
  899. /* Node 0 is a real element when the page starts with <html>. */
  900. if (!buf || cap <= 0 || node >= doc.nnode ||
  901. (node == 0 && doc.nodes[0].type != BR_NODE_ELEM))
  902. return 0;
  903. buf[0] = '\0';
  904. css_computed_name(property, name, sizeof(name));
  905. style_for_node(node, &st);
  906. if (!strcmp(name, "display")) {
  907. const char *v = "inline";
  908. if (st.display == BR_DISPLAY_BLOCK)
  909. v = "block";
  910. else if (st.display == BR_DISPLAY_NONE)
  911. v = "none";
  912. else if (st.display == BR_DISPLAY_FLEX)
  913. v = "flex";
  914. else if (st.display == BR_DISPLAY_GRID)
  915. v = "grid";
  916. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  917. v = "inline-block";
  918. snprintf(buf, cap, "%s", v);
  919. } else if (!strcmp(name, "position")) {
  920. static const char *pos[] = {
  921. "static", "absolute", "fixed", "relative", "sticky"
  922. };
  923. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  924. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  925. int is_w = name[0] == 'w';
  926. int kind = is_w ? st.width_kind : st.height_kind;
  927. int val = is_w ? st.width : st.height;
  928. if (kind == 3) {
  929. if (is_w)
  930. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  931. st.width_calc_pct / 100,
  932. st.width_calc_pct % 100,
  933. st.width_calc_px);
  934. else
  935. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  936. st.height_calc_pct / 100,
  937. st.height_calc_pct % 100,
  938. st.height_calc_px);
  939. } else if (kind == 1) {
  940. snprintf(buf, cap, "%dpx", val);
  941. } else if (kind == 2) {
  942. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  943. } else {
  944. snprintf(buf, cap, "auto");
  945. }
  946. } else if (!strcmp(name, "color") ||
  947. !strcmp(name, "background-color")) {
  948. if (!strcmp(name, "background-color") && !st.has_bg)
  949. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  950. else
  951. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  952. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  953. int is_fill = name[0] == 'f';
  954. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  955. if (mode == BR_PAINT_COLOR)
  956. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  957. else if (mode == BR_PAINT_CURRENT)
  958. css_rgb(st.color, buf, cap);
  959. else if (mode == BR_PAINT_UNSET && is_fill)
  960. snprintf(buf, cap, "rgb(0, 0, 0)");
  961. else if (mode == BR_PAINT_URL)
  962. snprintf(buf, cap, "url()");
  963. else
  964. snprintf(buf, cap, "none");
  965. } else if (!strcmp(name, "font-size")) {
  966. snprintf(buf, cap, "%dpx", st.font_px);
  967. } else if (!strcmp(name, "font-weight")) {
  968. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  969. } else if (!strcmp(name, "font-style")) {
  970. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  971. } else if (!strcmp(name, "font-family")) {
  972. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  973. br_font_face_family(st.font_face)[0])
  974. snprintf(buf, cap, "%s",
  975. br_font_face_family(st.font_face));
  976. else
  977. snprintf(buf, cap, "%s",
  978. st.mono ? "monospace" : "sans-serif");
  979. } else if (!strcmp(name, "text-align")) {
  980. static const char *al[] = { "left", "center", "right", "justify" };
  981. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  982. } else if (!strcmp(name, "float")) {
  983. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  984. st.float_left == 2 ? "right" : "none");
  985. } else if (!strcmp(name, "clear")) {
  986. static const char *cl[] = { "none", "left", "right", "both" };
  987. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  988. } else if (!strcmp(name, "opacity")) {
  989. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  990. } else if (!strcmp(name, "visibility")) {
  991. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  992. } else if (!strcmp(name, "overflow")) {
  993. snprintf(buf, cap, "%s",
  994. st.overflow_hidden ? "hidden" : "visible");
  995. } else if (!strcmp(name, "white-space")) {
  996. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  997. } else if (!strcmp(name, "text-transform")) {
  998. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  999. } else if (!strcmp(name, "box-sizing")) {
  1000. snprintf(buf, cap, "%s",
  1001. st.box_sizing ? "border-box" : "content-box");
  1002. } else if (!strcmp(name, "line-height")) {
  1003. if (st.line_h_px)
  1004. snprintf(buf, cap, "%dpx", st.line_h_px);
  1005. else if (st.line_h_pct)
  1006. snprintf(buf, cap, "%d%%", st.line_h_pct);
  1007. else
  1008. snprintf(buf, cap, "normal");
  1009. } else if (!strcmp(name, "z-index")) {
  1010. if (st.z_set)
  1011. snprintf(buf, cap, "%d", st.z_index);
  1012. else
  1013. snprintf(buf, cap, "auto");
  1014. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  1015. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  1016. int set = name[0] == 't' ? st.top_set :
  1017. name[0] == 'l' ? st.left_set :
  1018. name[0] == 'r' ? st.right_set : st.bottom_set;
  1019. int v = name[0] == 't' ? st.top :
  1020. name[0] == 'l' ? st.left :
  1021. name[0] == 'r' ? st.right : st.bottom;
  1022. if (set)
  1023. snprintf(buf, cap, "%dpx", v);
  1024. else
  1025. snprintf(buf, cap, "auto");
  1026. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  1027. !strcmp(name, "margin-bottom") ||
  1028. !strcmp(name, "margin-left") ||
  1029. !strcmp(name, "padding-top") ||
  1030. !strcmp(name, "padding-right") ||
  1031. !strcmp(name, "padding-bottom") ||
  1032. !strcmp(name, "padding-left")) {
  1033. int is_pad = name[0] == 'p';
  1034. int side = name[strlen(name) - 1] == 'p' ? 0 :
  1035. name[strlen(name) - 1] == 't' ? 1 :
  1036. name[strlen(name) - 1] == 'm' ? 2 : 3;
  1037. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  1038. if (!strcmp(name, "margin-right") ||
  1039. !strcmp(name, "padding-right"))
  1040. side = 1;
  1041. else if (!strcmp(name, "margin-bottom") ||
  1042. !strcmp(name, "padding-bottom"))
  1043. side = 2;
  1044. else if (!strcmp(name, "margin-left") ||
  1045. !strcmp(name, "padding-left"))
  1046. side = 3;
  1047. else
  1048. side = 0;
  1049. side += is_pad ? 4 : 0;
  1050. css_mp_value(buf, cap,
  1051. side == 0 ? st.mt : side == 1 ? st.mr :
  1052. side == 2 ? st.mb : side == 3 ? st.ml :
  1053. side == 4 ? st.pt : side == 5 ? st.pr :
  1054. side == 6 ? st.pb : st.pl,
  1055. st.mp_unit[side], st.mp_calc_px[side],
  1056. st.font_px);
  1057. } else if (!strcmp(name, "border-top-width") ||
  1058. !strcmp(name, "border-right-width") ||
  1059. !strcmp(name, "border-bottom-width") ||
  1060. !strcmp(name, "border-left-width")) {
  1061. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1062. name[7] == 'b' ? 2 : 3;
  1063. snprintf(buf, cap, "%dpx", st.border_w[side]);
  1064. } else if (!strcmp(name, "border-top-color") ||
  1065. !strcmp(name, "border-right-color") ||
  1066. !strcmp(name, "border-bottom-color") ||
  1067. !strcmp(name, "border-left-color")) {
  1068. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1069. name[7] == 'b' ? 2 : 3;
  1070. if (st.border_w[side] && !st.border_t[side])
  1071. css_rgb(st.border_c[side], buf, cap);
  1072. else
  1073. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1074. } else if (!strcmp(name, "background-image")) {
  1075. if (st.bg_image)
  1076. snprintf(buf, cap, "url(\"%s\")",
  1077. br_bg_image_url(st.bg_image - 1));
  1078. else
  1079. snprintf(buf, cap, "none");
  1080. } else if (!strcmp(name, "background-repeat")) {
  1081. static const char *rp[] = {
  1082. "repeat", "no-repeat", "repeat-x", "repeat-y"
  1083. };
  1084. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  1085. st.bg_repeat : 0]);
  1086. } else if (!strcmp(name, "background-position")) {
  1087. if (st.bg_pos_x_kind == 1)
  1088. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  1089. st.bg_pos_y);
  1090. else
  1091. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1092. st.bg_pos_y);
  1093. } else if (!strcmp(name, "background-size")) {
  1094. if (st.bg_size_kind == 3)
  1095. snprintf(buf, cap, "cover");
  1096. else if (st.bg_size_kind == 4)
  1097. snprintf(buf, cap, "contain");
  1098. else if (st.bg_size_kind == 1)
  1099. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1100. st.bg_size_h);
  1101. else if (st.bg_size_kind == 2)
  1102. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1103. st.bg_size_h);
  1104. else
  1105. snprintf(buf, cap, "auto");
  1106. } else if (!strcmp(name, "transform")) {
  1107. char tmp[128];
  1108. unsigned int n = 0;
  1109. if (!st.transform_set) {
  1110. snprintf(buf, cap, "none");
  1111. } else {
  1112. tmp[0] = '\0';
  1113. if (st.tx || st.ty) {
  1114. snprintf(tmp + n, sizeof(tmp) - n,
  1115. "translate(%dpx, %dpx)", st.tx, st.ty);
  1116. n = (unsigned int)strlen(tmp);
  1117. }
  1118. if (st.transform_scale) {
  1119. snprintf(tmp + n, sizeof(tmp) - n,
  1120. "%sscale(%d.%02d, %d.%02d)",
  1121. n ? " " : "", st.scale_x / 100,
  1122. st.scale_x % 100, st.scale_y / 100,
  1123. st.scale_y % 100);
  1124. n = (unsigned int)strlen(tmp);
  1125. if (st.rotate_x100) {
  1126. snprintf(tmp + n, sizeof(tmp) - n,
  1127. " rotate(%d.%02ddeg)",
  1128. st.rotate_x100 / 100,
  1129. st.rotate_x100 % 100);
  1130. }
  1131. } else if (st.rotate_x100) {
  1132. snprintf(tmp + n, sizeof(tmp) - n,
  1133. "%srotate(%d.%02ddeg)",
  1134. n ? " " : "", st.rotate_x100 / 100,
  1135. st.rotate_x100 % 100);
  1136. }
  1137. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1138. }
  1139. } else {
  1140. return 0;
  1141. }
  1142. return buf[0] != '\0';
  1143. }
  1144. static int js_host_click(unsigned int node)
  1145. {
  1146. char url[BR_URL_MAX];
  1147. const char *href;
  1148. if (node >= doc.nnode)
  1149. return 0;
  1150. if (form_is_control(node)) {
  1151. form_click(node); /* dispatches its own click event */
  1152. return 1;
  1153. }
  1154. /* element.click() fires a bubbling, cancelable click before the
  1155. * default action, like a real click (delegated list handlers). */
  1156. if (!js_browser_event(node, "click", 1, 1))
  1157. return 1;
  1158. if (link_fragment_nav(node))
  1159. return 1;
  1160. href = br_href(&doc, node);
  1161. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1162. return 0;
  1163. s_copy(pending_url, url, sizeof(pending_url));
  1164. pending_action |= ACT_NAV;
  1165. cancel_fetch = 1;
  1166. ngui_invalidate(&ui);
  1167. return 1;
  1168. }
  1169. static int fetch_script_text(const char *url, unsigned char **out,
  1170. unsigned int *outlen, char *err,
  1171. unsigned int errcap);
  1172. struct fetch_worker;
  1173. static struct fetch_worker *fetch_worker_alloc(void);
  1174. static void fetch_worker_release(struct fetch_worker *w);
  1175. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1176. unsigned int cap, const char *post,
  1177. unsigned int post_len, unsigned int node,
  1178. int bg, char *err, unsigned int errcap);
  1179. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1180. unsigned int errcap);
  1181. static int fetch_worker_read_body(struct fetch_worker *w,
  1182. unsigned char *plain,
  1183. unsigned int plaincap,
  1184. unsigned char *comp,
  1185. unsigned int compcap,
  1186. int *truncated, char *err,
  1187. unsigned int errcap);
  1188. static void fetch_workers_stop_all(void);
  1189. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1190. unsigned int cap, const char *method,
  1191. const char *ctype, const char *post,
  1192. unsigned int post_len, unsigned int node,
  1193. int bg, unsigned int dec_w,
  1194. unsigned int dec_h, char *err,
  1195. unsigned int errcap);
  1196. static int script_cache_has(const char *url);
  1197. static void script_cache_put(const char *url, const unsigned char *data,
  1198. unsigned int len);
  1199. static unsigned int script_cache_hash(const char *s);
  1200. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1201. unsigned int errcap);
  1202. static void fetch_workers_cancel_busy(void);
  1203. static void worker_wait_ui(void);
  1204. static int fetch_worker_status(const struct fetch_worker *w);
  1205. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1206. * module load: the wait must not pump input, or a click would dispatch DOM
  1207. * events into the middle of the running script. */
  1208. static int fetch_wait_passive;
  1209. static void script_error(const char *what, const char *url, const char *why)
  1210. {
  1211. char msg[192];
  1212. unsigned int n = 0;
  1213. s_append(msg, &n, what, sizeof(msg));
  1214. if (url && url[0]) {
  1215. s_append(msg, &n, " ", sizeof(msg));
  1216. s_append(msg, &n, url, sizeof(msg));
  1217. }
  1218. if (why && why[0]) {
  1219. s_append(msg, &n, ": ", sizeof(msg));
  1220. s_append(msg, &n, why, sizeof(msg));
  1221. }
  1222. js_host_report(msg);
  1223. }
  1224. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1225. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1226. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1227. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1228. #define JS_HTTP_POST_MAX (16u * 1024u)
  1229. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1230. static int js_worker_http(const char *method, const char *url,
  1231. const char *ctype, const char *body,
  1232. unsigned int body_len, struct js_http_resp *r,
  1233. char *err, int errcap);
  1234. static int js_host_http(const char *method, const char *url,
  1235. const char *ctype, const char *body,
  1236. unsigned int body_len, struct js_http_resp *r,
  1237. char *err, int errcap)
  1238. {
  1239. if (pending_action) {
  1240. s_copy(err, "page is navigating", (unsigned int)errcap);
  1241. return -1;
  1242. }
  1243. if (url[0] == '/') {
  1244. /* Local file: GET only. */
  1245. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1246. int rv;
  1247. if (!buf) {
  1248. s_copy(err, "out of memory", (unsigned int)errcap);
  1249. return -1;
  1250. }
  1251. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1252. (int)JS_HTTP_MAX);
  1253. r->status = rv < 0 ? 404 : 200;
  1254. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1255. buf[r->len] = '\0';
  1256. r->body = (char *)buf;
  1257. s_copy(r->url, url, sizeof(r->url));
  1258. if (contains_ci(url, ".json"))
  1259. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1260. return 0;
  1261. }
  1262. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1263. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1264. return -1;
  1265. }
  1266. if (body_len > JS_HTTP_POST_MAX) {
  1267. s_copy(err, "request body too large", (unsigned int)errcap);
  1268. return -1;
  1269. }
  1270. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1271. errcap);
  1272. }
  1273. /* Module source for the engine's loader: the boot script cache first, then
  1274. * one blocking fetch with input pumping disabled (the loader runs inside
  1275. * JavaScript). */
  1276. static char *js_host_load_script(const char *url, unsigned int *len)
  1277. {
  1278. unsigned char *data = 0;
  1279. char err[64];
  1280. int rv;
  1281. fetch_wait_passive++;
  1282. set_status("Loading module...", 0, 0);
  1283. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1284. fetch_wait_passive--;
  1285. if (rv != 0) {
  1286. script_error("Cannot load module", url,
  1287. rv == FETCH_ABORT ? "navigation" : err);
  1288. return 0;
  1289. }
  1290. return (char *)data;
  1291. }
  1292. /* Web Storage lives in /share, outside the page heap that every navigation
  1293. * resets: localStorage per origin for the boot, sessionStorage per origin
  1294. * and browser window. */
  1295. #define JS_ORIGIN_MAX 160
  1296. /* scheme://host[:port] of the page (a local page's whole path). */
  1297. static void js_page_origin(char *origin, unsigned int cap)
  1298. {
  1299. unsigned int i = 0, slashes = 0;
  1300. while (page_url[i] && i + 1 < cap) {
  1301. if (page_url[i] == '/' && ++slashes == 3)
  1302. break;
  1303. origin[i] = page_url[i];
  1304. i++;
  1305. }
  1306. origin[i] = '\0';
  1307. }
  1308. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1309. {
  1310. unsigned int n = 0;
  1311. s_append(out, &n, "/share/bls", cap);
  1312. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1313. }
  1314. static void js_storage_path(int kind, char *out, unsigned int cap)
  1315. {
  1316. char origin[JS_ORIGIN_MAX];
  1317. unsigned int n = 0;
  1318. js_page_origin(origin, sizeof(origin));
  1319. if (!kind) {
  1320. js_origin_path(origin, out, cap);
  1321. return;
  1322. }
  1323. s_append(out, &n, "/share/bss", cap);
  1324. if (kind) {
  1325. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1326. s_append(out, &n, "-", cap);
  1327. }
  1328. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1329. }
  1330. static void persist_mark_origin(const char *origin);
  1331. static int persist_store_lookup(const char *origin, char *out, int cap);
  1332. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1333. {
  1334. char path[48], origin[JS_ORIGIN_MAX];
  1335. int rv;
  1336. js_storage_path(kind, path, sizeof(path));
  1337. if (set) {
  1338. if (kind) {
  1339. if (!set[0] || !strcmp(set, "{}")) {
  1340. u_syscall1(SYS_UNLINK, (int)path);
  1341. return 0;
  1342. }
  1343. } else {
  1344. /* localStorage keeps an explicit "{}" rather than no
  1345. * file: a missing /share file means "not loaded from
  1346. * /data yet", and a cleared store must not come back
  1347. * from the disk copy before it is flushed. */
  1348. if (!set[0])
  1349. set = "{}";
  1350. js_page_origin(origin, sizeof(origin));
  1351. persist_mark_origin(origin);
  1352. }
  1353. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1354. (int)strlen(set)) < 0 ? -1 : 0;
  1355. }
  1356. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1357. if (rv < 0 && !kind) {
  1358. /* First use this boot: the persistent copy on /data. */
  1359. js_page_origin(origin, sizeof(origin));
  1360. rv = persist_store_lookup(origin, out, cap);
  1361. if (rv >= 0)
  1362. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1363. }
  1364. if (rv < 0)
  1365. return -1;
  1366. out[rv] = '\0';
  1367. return rv;
  1368. }
  1369. /* ---- persistence on /data ----
  1370. *
  1371. * /share is the working copy (RAM, shared by every helper and window); the
  1372. * installed disk's /data volume keeps the cookie jar and localStorage
  1373. * across reboots when it is mounted. The browser owns the disk copies: at
  1374. * start it restores the jar into /share, and its main loop writes back
  1375. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1376. * setItem updates costs one FAT write. The helpers only touch /share (they
  1377. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1378. * /data mount every disk access simply fails. Both files are plaintext
  1379. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1380. #define PERSIST_MS 3000u
  1381. #define SHARE_COOKIES "/share/bcookies"
  1382. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1383. #define DATA_STORE "/data/BSTORE.DAT"
  1384. #define DATA_STORE_MAGIC "NBLS1\n"
  1385. #define DATA_STORE_MAX (192u * 1024u)
  1386. #define PERSIST_DIRTY_MAX 8
  1387. static unsigned int persist_due;
  1388. static unsigned int cookie_sum_saved;
  1389. static int cookie_sum_valid;
  1390. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1391. static int persist_ndirty;
  1392. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1393. {
  1394. unsigned int h = 2166136261u, i;
  1395. for (i = 0; i < n; i++)
  1396. h = (h ^ p[i]) * 16777619u;
  1397. return h;
  1398. }
  1399. /* Called once at startup, before any helper runs. */
  1400. static void persist_restore(void)
  1401. {
  1402. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1403. int n;
  1404. if (!jar)
  1405. return;
  1406. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1407. (int)sizeof(struct uhttp_jar));
  1408. if (n != (int)sizeof(struct uhttp_jar)) {
  1409. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1410. (int)sizeof(struct uhttp_jar));
  1411. if (n == (int)sizeof(struct uhttp_jar)) {
  1412. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1413. (int)jar, n);
  1414. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1415. cookie_sum_valid = 1;
  1416. }
  1417. }
  1418. free(jar);
  1419. persist_due = u_ticks_ms() + PERSIST_MS;
  1420. }
  1421. static void persist_mark_origin(const char *origin)
  1422. {
  1423. int i;
  1424. for (i = 0; i < persist_ndirty; i++)
  1425. if (s_eq(persist_dirty[i], origin))
  1426. return;
  1427. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1428. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1429. }
  1430. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1431. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1432. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1433. unsigned int *o_off, unsigned int *o_len,
  1434. unsigned int *d_off, unsigned int *d_len,
  1435. unsigned int *rec_end)
  1436. {
  1437. unsigned int p = *pos, v = 0;
  1438. if (p >= len)
  1439. return 0;
  1440. *o_off = p;
  1441. while (p < len && buf[p] != '\n')
  1442. p++;
  1443. if (p >= len)
  1444. return 0;
  1445. *o_len = p - *o_off;
  1446. p++;
  1447. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1448. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1449. if (p >= len || buf[p] != '\n')
  1450. return 0;
  1451. p++;
  1452. if (v > len - p)
  1453. return 0;
  1454. *d_off = p;
  1455. *d_len = v;
  1456. p += v;
  1457. if (p < len && buf[p] == '\n')
  1458. p++;
  1459. *rec_end = p;
  1460. *pos = p;
  1461. return 1;
  1462. }
  1463. static int store_load(char **out)
  1464. {
  1465. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1466. int n;
  1467. *out = buf;
  1468. if (!buf)
  1469. return -1;
  1470. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1471. (int)DATA_STORE_MAX);
  1472. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1473. !starts_with(buf, DATA_STORE_MAGIC))
  1474. return 0;
  1475. return n;
  1476. }
  1477. static int persist_store_lookup(const char *origin, char *out, int cap)
  1478. {
  1479. char *buf;
  1480. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1481. unsigned int olen = s_len(origin);
  1482. int n = store_load(&buf), rv = -1;
  1483. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1484. &dl, &e)) {
  1485. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1486. if ((int)dl < cap) {
  1487. memcpy(out, buf + d, dl);
  1488. out[dl] = '\0';
  1489. rv = (int)dl;
  1490. }
  1491. break;
  1492. }
  1493. }
  1494. free(buf);
  1495. return rv;
  1496. }
  1497. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1498. static void persist_store_flush(void)
  1499. {
  1500. char *old, *nb, path[48];
  1501. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1502. int n = store_load(&old), i, w;
  1503. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1504. if (n < 0 || !nb) {
  1505. free(old);
  1506. free(nb);
  1507. return;
  1508. }
  1509. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1510. /* Untouched origins first, in their old order. */
  1511. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1512. &dl, &e)) {
  1513. int dirty = 0;
  1514. for (i = 0; i < persist_ndirty; i++)
  1515. if (s_len(persist_dirty[i]) == ol &&
  1516. !memcmp(persist_dirty[i], old + oo, ol))
  1517. dirty = 1;
  1518. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1519. continue;
  1520. memcpy(nb + nn, old + oo, e - oo);
  1521. nn += e - oo;
  1522. }
  1523. /* Then the changed ones (an emptied store is dropped). */
  1524. for (i = 0; i < persist_ndirty; i++) {
  1525. char num[12];
  1526. unsigned int k = 0;
  1527. js_origin_path(persist_dirty[i], path, sizeof(path));
  1528. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1529. (int)DATA_STORE_MAX);
  1530. if (w <= 2) /* missing or "{}" */
  1531. continue;
  1532. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1533. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1534. DATA_STORE_MAX) {
  1535. set_status("Saved site data is full; a site's "
  1536. "localStorage was not saved", 1, 6000);
  1537. continue;
  1538. }
  1539. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1540. nb[nn++] = '\n';
  1541. s_append(nb, &nn, num, DATA_STORE_MAX);
  1542. nb[nn++] = '\n';
  1543. memcpy(nb + nn, old, (unsigned int)w);
  1544. nn += (unsigned int)w;
  1545. nb[nn++] = '\n';
  1546. }
  1547. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1548. persist_ndirty = 0;
  1549. free(old);
  1550. free(nb);
  1551. }
  1552. static void persist_cookies_flush(void)
  1553. {
  1554. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1555. unsigned int sum;
  1556. int n;
  1557. if (!jar)
  1558. return;
  1559. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1560. (int)sizeof(struct uhttp_jar));
  1561. if (n == (int)sizeof(struct uhttp_jar)) {
  1562. sum = persist_sum(jar, (unsigned int)n);
  1563. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1564. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1565. (int)jar, n) >= 0) {
  1566. cookie_sum_saved = sum;
  1567. cookie_sum_valid = 1;
  1568. }
  1569. }
  1570. }
  1571. free(jar);
  1572. }
  1573. /* ---- visit history (URL-bar autocomplete) ----
  1574. *
  1575. * Every page that finishes loading is recorded with its title, a visit
  1576. * count and a stamp: a counter that only grows and travels with the file,
  1577. * so it orders visits across windows and boots without a wall clock. The
  1578. * table lives in BSS, because the page heap is reset on every navigation.
  1579. * The boot's browser windows share it through /share/bhist (rewritten on
  1580. * every visit) and it is persisted to /data/BHIST.DAT from persist_tick()
  1581. * at most every PERSIST_MS, like the cookie jar. A save re-reads
  1582. * /share/bhist and merges it first, so two windows add to one history
  1583. * instead of overwriting each other. File format: "NBHIST1\n", then
  1584. * "<visits> <stamp> <url>\t<title>\n" per entry. Plaintext, like the
  1585. * other browser state on /data. */
  1586. #define HIST_MAX 128
  1587. #define HIST_URL_MAX 512
  1588. #define HIST_FILE_MAX (HIST_MAX * (HIST_URL_MAX + BR_TITLE_MAX + 24) + 16)
  1589. #define HIST_MAGIC "NBHIST1\n"
  1590. #define SHARE_HIST "/share/bhist"
  1591. #define DATA_HIST "/data/BHIST.DAT"
  1592. #define HIST_FORGET_MAX 16
  1593. struct hist_ent {
  1594. unsigned int visits;
  1595. unsigned int stamp;
  1596. char url[HIST_URL_MAX];
  1597. char title[BR_TITLE_MAX];
  1598. };
  1599. static struct hist_ent hist_tab[HIST_MAX];
  1600. static int hist_n;
  1601. static int hist_share_dirty, hist_data_dirty;
  1602. /* URLs removed in this process: a merge must not bring them back. */
  1603. static unsigned int hist_forgot[HIST_FORGET_MAX];
  1604. static int hist_nforgot;
  1605. static unsigned int hist_hash(const char *s)
  1606. {
  1607. return persist_sum((const unsigned char *)s, s_len(s));
  1608. }
  1609. static int hist_is_forgotten(const char *url)
  1610. {
  1611. unsigned int h = hist_hash(url);
  1612. int i;
  1613. for (i = 0; i < hist_nforgot; i++)
  1614. if (hist_forgot[i] == h)
  1615. return 1;
  1616. return 0;
  1617. }
  1618. static int hist_find(const char *url)
  1619. {
  1620. int i;
  1621. for (i = 0; i < hist_n; i++)
  1622. if (s_eq(hist_tab[i].url, url))
  1623. return i;
  1624. return -1;
  1625. }
  1626. static unsigned int hist_next_stamp(void)
  1627. {
  1628. unsigned int m = 0;
  1629. int i;
  1630. for (i = 0; i < hist_n; i++)
  1631. if (hist_tab[i].stamp > m)
  1632. m = hist_tab[i].stamp;
  1633. return m + 1;
  1634. }
  1635. /* Copy a title, turning tabs/newlines (the file separators) into spaces. */
  1636. static void hist_copy_title(char *d, const char *s, unsigned int n)
  1637. {
  1638. unsigned int i;
  1639. for (i = 0; i + 1 < BR_TITLE_MAX && i < n && s[i]; i++)
  1640. d[i] = (unsigned char)s[i] < 0x20 ? ' ' : s[i];
  1641. d[i] = '\0';
  1642. }
  1643. /* Insert or update an entry; the newer stamp wins the title, the larger
  1644. * visit count is kept. A full table evicts the least recent entry, unless
  1645. * the new one is older still. Returns NULL when nothing was stored. */
  1646. static struct hist_ent *hist_put(const char *url, const char *title,
  1647. unsigned int visits, unsigned int stamp)
  1648. {
  1649. struct hist_ent *e;
  1650. int i = hist_find(url);
  1651. if (i < 0) {
  1652. if (hist_n < HIST_MAX) {
  1653. i = hist_n++;
  1654. } else {
  1655. int j;
  1656. i = 0;
  1657. for (j = 1; j < hist_n; j++)
  1658. if (hist_tab[j].stamp < hist_tab[i].stamp)
  1659. i = j;
  1660. if (hist_tab[i].stamp >= stamp)
  1661. return 0;
  1662. }
  1663. e = &hist_tab[i];
  1664. e->visits = 0;
  1665. e->stamp = 0;
  1666. e->title[0] = '\0';
  1667. s_copy(e->url, url, sizeof(e->url));
  1668. }
  1669. e = &hist_tab[i];
  1670. if (visits > e->visits)
  1671. e->visits = visits;
  1672. if (stamp >= e->stamp) {
  1673. e->stamp = stamp;
  1674. if (title && title[0])
  1675. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1676. } else if (!e->title[0] && title) {
  1677. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1678. }
  1679. return e;
  1680. }
  1681. static unsigned int hist_parse_dec(const char *b, int n, int *pos)
  1682. {
  1683. unsigned int v = 0;
  1684. while (*pos < n && b[*pos] >= '0' && b[*pos] <= '9')
  1685. v = v * 10 + (unsigned int)(b[(*pos)++] - '0');
  1686. return v;
  1687. }
  1688. static void hist_merge_buf(const char *b, int n)
  1689. {
  1690. int pos = (int)s_len(HIST_MAGIC);
  1691. char url[HIST_URL_MAX], title[BR_TITLE_MAX];
  1692. if (n < pos || memcmp(b, HIST_MAGIC, (unsigned int)pos))
  1693. return;
  1694. while (pos < n) {
  1695. unsigned int visits, stamp, ul = 0;
  1696. int t0, t1;
  1697. visits = hist_parse_dec(b, n, &pos);
  1698. if (pos < n && b[pos] == ' ')
  1699. pos++;
  1700. stamp = hist_parse_dec(b, n, &pos);
  1701. if (pos < n && b[pos] == ' ')
  1702. pos++;
  1703. while (pos < n && b[pos] != '\t' && b[pos] != '\n') {
  1704. if (ul + 1 < sizeof(url))
  1705. url[ul++] = b[pos];
  1706. pos++;
  1707. }
  1708. url[ul] = '\0';
  1709. t0 = t1 = pos < n && b[pos] == '\t' ? pos + 1 : pos;
  1710. while (t1 < n && b[t1] != '\n')
  1711. t1++;
  1712. pos = t1 + 1;
  1713. hist_copy_title(title, b + t0, (unsigned int)(t1 - t0));
  1714. if (ul && ul + 1 < sizeof(url) && !hist_is_forgotten(url))
  1715. hist_put(url, title, visits, stamp);
  1716. }
  1717. }
  1718. static int hist_serialize(char *b, unsigned int cap)
  1719. {
  1720. unsigned int n = 0;
  1721. int i;
  1722. s_append(b, &n, HIST_MAGIC, cap);
  1723. for (i = 0; i < hist_n; i++) {
  1724. struct hist_ent *e = &hist_tab[i];
  1725. if (n + s_len(e->url) + s_len(e->title) + 26 >= cap)
  1726. break;
  1727. s_append_dec(b, &n, e->visits, cap);
  1728. b[n++] = ' ';
  1729. s_append_dec(b, &n, e->stamp, cap);
  1730. b[n++] = ' ';
  1731. s_append(b, &n, e->url, cap);
  1732. b[n++] = '\t';
  1733. s_append(b, &n, e->title, cap);
  1734. b[n++] = '\n';
  1735. }
  1736. return (int)n;
  1737. }
  1738. /* Merge /share/bhist, then write it back (and /data when asked). */
  1739. static void hist_sync(int to_data)
  1740. {
  1741. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1742. int n;
  1743. if (!b)
  1744. return;
  1745. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1746. (int)HIST_FILE_MAX);
  1747. if (n > 0)
  1748. hist_merge_buf(b, n);
  1749. n = hist_serialize(b, HIST_FILE_MAX);
  1750. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1751. hist_share_dirty = 0;
  1752. if (to_data) {
  1753. /* No /data mount: the write fails, and there is nothing to
  1754. * retry until the next visit. */
  1755. u_syscall3(SYS_WRITE_FILE, (int)DATA_HIST, (int)b, n);
  1756. hist_data_dirty = 0;
  1757. }
  1758. free(b);
  1759. }
  1760. /* Startup: the boot's shared copy, else the saved one from /data. */
  1761. static void hist_load(void)
  1762. {
  1763. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1764. int n;
  1765. if (!b)
  1766. return;
  1767. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1768. (int)HIST_FILE_MAX);
  1769. if (n <= 0) {
  1770. n = u_syscall3(SYS_READ_FILE, (int)DATA_HIST, (int)b,
  1771. (int)HIST_FILE_MAX);
  1772. if (n > 0)
  1773. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1774. }
  1775. if (n > 0)
  1776. hist_merge_buf(b, n);
  1777. free(b);
  1778. }
  1779. static void hist_visit(const char *url, const char *title)
  1780. {
  1781. struct hist_ent *e;
  1782. unsigned int i;
  1783. if (!url[0] || starts_with(url, "about:") ||
  1784. s_len(url) >= HIST_URL_MAX)
  1785. return;
  1786. for (i = 0; url[i]; i++)
  1787. if ((unsigned char)url[i] < 0x20)
  1788. return;
  1789. e = hist_put(url, title, 0, hist_next_stamp());
  1790. if (!e)
  1791. return;
  1792. e->visits++;
  1793. hist_data_dirty = 1;
  1794. hist_sync(0);
  1795. }
  1796. static void hist_forget(int i)
  1797. {
  1798. if (i < 0 || i >= hist_n)
  1799. return;
  1800. if (hist_nforgot < HIST_FORGET_MAX)
  1801. hist_forgot[hist_nforgot++] = hist_hash(hist_tab[i].url);
  1802. hist_n--;
  1803. for (; i < hist_n; i++)
  1804. hist_tab[i] = hist_tab[i + 1];
  1805. hist_data_dirty = 1;
  1806. hist_sync(0);
  1807. }
  1808. static void hist_tick(void)
  1809. {
  1810. if (hist_share_dirty || hist_data_dirty)
  1811. hist_sync(hist_data_dirty);
  1812. }
  1813. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1814. static void persist_tick(void)
  1815. {
  1816. unsigned int now = u_ticks_ms();
  1817. if ((int)(now - persist_due) < 0)
  1818. return;
  1819. persist_due = now + PERSIST_MS;
  1820. persist_cookies_flush();
  1821. if (persist_ndirty)
  1822. persist_store_flush();
  1823. hist_tick();
  1824. }
  1825. /* <link rel="modulepreload">: download the page's module graph on all
  1826. * helpers at once into the boot script cache, before any script runs. The
  1827. * engine's module loader is sequential (one blocking fetch per import), so
  1828. * without this a Vite app with a dozen chunks pays every round trip in a
  1829. * row. Failures are ignored; the loader fetches what is missing. */
  1830. #define MODULE_PRELOAD_MAX 24
  1831. static void prefetch_module_preloads(void)
  1832. {
  1833. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1834. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1835. unsigned int count = 0, next = 0, done = 0, i;
  1836. char err[64];
  1837. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1838. struct br_node *nd = &doc.nodes[i];
  1839. const char *rel, *href;
  1840. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1841. continue;
  1842. rel = br_rel(&doc, i);
  1843. href = br_href(&doc, i);
  1844. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1845. continue;
  1846. if (resolve_link(page_url, href, urls[count],
  1847. sizeof(urls[count])) != 0 ||
  1848. urls[count][0] == '/' || script_cache_has(urls[count]))
  1849. continue;
  1850. slot[count++] = 0;
  1851. }
  1852. if (!count)
  1853. return;
  1854. set_status("Loading modules...", 0, 0);
  1855. while (done < count) {
  1856. struct fetch_worker *w;
  1857. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1858. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1859. 0, 0, 0, err,
  1860. sizeof(err)) != 0) {
  1861. fetch_worker_release(w);
  1862. done++;
  1863. } else {
  1864. slot[next] = w;
  1865. }
  1866. next++;
  1867. }
  1868. worker_wait_ui();
  1869. if (cancel_fetch || pending_action) {
  1870. fetch_workers_cancel_busy();
  1871. return;
  1872. }
  1873. for (i = 0; i < next; i++) {
  1874. unsigned char *body;
  1875. int rv, tr = 0;
  1876. if (!slot[i])
  1877. continue;
  1878. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1879. if (rv == 0)
  1880. continue;
  1881. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1882. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1883. if (body) {
  1884. rv = fetch_worker_read_body(slot[i], body,
  1885. BR_SCRIPT_MAX, image_io_buf,
  1886. BR_PAGE_COMP_MAX, &tr, err,
  1887. sizeof(err));
  1888. if (rv > 0 && !tr)
  1889. script_cache_put(urls[i], body,
  1890. (unsigned int)rv);
  1891. free(body);
  1892. }
  1893. fetch_worker_release(slot[i]);
  1894. slot[i] = 0;
  1895. done++;
  1896. }
  1897. u_sleep_ms(10);
  1898. }
  1899. }
  1900. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1901. * submitted to helper workers ahead of time, but scripts still execute in
  1902. * document order. */
  1903. #define SCRIPT_INLINE 0
  1904. #define SCRIPT_LOCAL 1
  1905. #define SCRIPT_REMOTE 2
  1906. #define SCRIPT_ERROR 3
  1907. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1908. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1909. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1910. static void script_submit_window(unsigned int *next, char *err,
  1911. unsigned int errcap)
  1912. {
  1913. while (*next < doc.nscripts) {
  1914. struct fetch_worker *w;
  1915. if (script_kind[*next] != SCRIPT_REMOTE) {
  1916. (*next)++;
  1917. continue;
  1918. }
  1919. w = fetch_worker_alloc();
  1920. if (!w)
  1921. return;
  1922. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1923. 0, 0, 0, 0, err, errcap) != 0) {
  1924. fetch_worker_release(w);
  1925. script_kind[*next] = SCRIPT_ERROR;
  1926. (*next)++;
  1927. continue;
  1928. }
  1929. script_slot[*next] = w;
  1930. (*next)++;
  1931. }
  1932. }
  1933. /* Run the page's scripts in document order. External bodies are prefetched
  1934. * in parallel so downloading script N+1 overlaps executing script N; inline
  1935. * bodies are copied because the engine needs NUL-terminated text. */
  1936. static void run_page_scripts(void)
  1937. {
  1938. struct js_browser_host host;
  1939. unsigned int i, next = 0;
  1940. char err[64], ferr[64];
  1941. if (!doc.nscripts)
  1942. return;
  1943. host.status = js_host_status;
  1944. host.report = js_host_report;
  1945. host.navigate = js_host_navigate;
  1946. host.changed = js_host_changed;
  1947. host.rect = js_host_rect;
  1948. host.form_value = js_host_form_value;
  1949. host.form_checked = js_host_form_checked;
  1950. host.form_selected = js_host_form_selected;
  1951. host.form_set_value = js_host_form_set_value;
  1952. host.form_set_checked = js_host_form_set_checked;
  1953. host.form_set_selected = js_host_form_set_selected;
  1954. host.form_elements = js_host_form_elements;
  1955. host.form_submit = js_host_form_submit;
  1956. host.form_reset = js_host_form_reset;
  1957. host.click = js_host_click;
  1958. host.computed = js_host_computed;
  1959. host.http = js_host_http;
  1960. host.load_script = js_host_load_script;
  1961. host.storage = js_host_storage;
  1962. host.set_hash = js_host_set_hash;
  1963. host.page_url = page_url;
  1964. host.width = ui.w;
  1965. host.height = ui.h;
  1966. if (js_browser_start(&doc, &host) != 0) {
  1967. js_host_status("JavaScript: out of memory", 1);
  1968. return;
  1969. }
  1970. resize_sent_w = -1;
  1971. resize_pending = 0;
  1972. prefetch_module_preloads();
  1973. for (i = 0; i < doc.nscripts; i++) {
  1974. struct br_script *script = &doc.scripts[i];
  1975. const char *src_attr = script->src_off ?
  1976. doc.attrs + script->src_off : "";
  1977. script_slot[i] = 0;
  1978. if (!script->src_off) {
  1979. script_kind[i] = SCRIPT_INLINE;
  1980. continue;
  1981. }
  1982. if (!src_attr[0] ||
  1983. resolve_link(page_url, src_attr, script_urls[i],
  1984. sizeof(script_urls[i])) != 0) {
  1985. script_urls[i][0] = '\0';
  1986. script_kind[i] = SCRIPT_ERROR;
  1987. continue;
  1988. }
  1989. if (script_urls[i][0] == '/' ||
  1990. script_cache_has(script_urls[i]))
  1991. script_kind[i] = SCRIPT_LOCAL;
  1992. else
  1993. script_kind[i] = SCRIPT_REMOTE;
  1994. }
  1995. script_submit_window(&next, ferr, sizeof(ferr));
  1996. for (i = 0; i < doc.nscripts; i++) {
  1997. struct br_script *script = &doc.scripts[i];
  1998. /* document.currentScript for classic scripts (null for modules) */
  1999. js_browser_set_current_script(script->module ? 0 : script->node);
  2000. if (script_kind[i] == SCRIPT_INLINE) {
  2001. unsigned int off = script->off;
  2002. unsigned int len = script->len;
  2003. unsigned int k;
  2004. char *src = (char *)malloc(len + 1);
  2005. if (!src) {
  2006. js_host_status("JavaScript: out of memory", 1);
  2007. break;
  2008. }
  2009. for (k = 0; k < len; k++)
  2010. src[k] = doc.script_src[off + k];
  2011. src[len] = '\0';
  2012. if (script->module) {
  2013. /* A distinct module name per inline module
  2014. * (QuickJS registers modules by name); the
  2015. * fragment keeps relative imports resolving
  2016. * against the page. */
  2017. char mname[BR_URL_MAX + 16];
  2018. unsigned int mn = 0;
  2019. s_append(mname, &mn, page_url, sizeof(mname));
  2020. s_append(mname, &mn, "#module", sizeof(mname));
  2021. s_append_dec(mname, &mn, i, sizeof(mname));
  2022. js_browser_run_module(src, mname);
  2023. } else {
  2024. js_browser_run(src, page_url);
  2025. }
  2026. free(src);
  2027. } else if (script->src_off) {
  2028. const char *src_attr = doc.attrs + script->src_off;
  2029. if (script_kind[i] == SCRIPT_ERROR) {
  2030. script_error("Cannot load script", src_attr,
  2031. script_urls[i][0] ?
  2032. "network busy" :
  2033. "unsupported URL");
  2034. continue;
  2035. }
  2036. if (script_kind[i] == SCRIPT_LOCAL) {
  2037. unsigned char *data = 0;
  2038. unsigned int len = 0;
  2039. int rv;
  2040. set_status("Loading script...", 0, 0);
  2041. rv = fetch_script_text(script_urls[i], &data,
  2042. &len, err, sizeof(err));
  2043. if (rv == FETCH_ABORT)
  2044. break;
  2045. if (rv != 0) {
  2046. script_error("Cannot load script",
  2047. script_urls[i], err);
  2048. continue;
  2049. }
  2050. if (script->module)
  2051. js_browser_run_module(
  2052. (const char *)data,
  2053. script_urls[i]);
  2054. else
  2055. js_browser_run((const char *)data,
  2056. script_urls[i]);
  2057. free(data);
  2058. } else {
  2059. struct fetch_worker *w = script_slot[i];
  2060. unsigned char *body = 0;
  2061. int tr = 0, rv;
  2062. if (!w) {
  2063. w = fetch_worker_alloc();
  2064. if (!w)
  2065. continue;
  2066. if (fetch_worker_submit(w,
  2067. script_urls[i],
  2068. BR_SCRIPT_MAX,
  2069. 0, 0, 0, 0, err,
  2070. sizeof(err)) != 0) {
  2071. fetch_worker_release(w);
  2072. script_kind[i] = SCRIPT_ERROR;
  2073. if (i == next)
  2074. next++;
  2075. continue;
  2076. }
  2077. script_slot[i] = w;
  2078. if (i == next)
  2079. next++;
  2080. }
  2081. set_status("Loading script...", 0, 0);
  2082. rv = fetch_worker_wait(w, err, sizeof(err));
  2083. if (rv == FETCH_ABORT) {
  2084. fetch_workers_stop_all();
  2085. break;
  2086. }
  2087. /* The body gets its own buffer (scripts are up
  2088. * to 2 MB); image_io_buf takes the gzip
  2089. * stream. */
  2090. body = rv == 0 ? (unsigned char *)malloc(
  2091. BR_SCRIPT_MAX + 1) : 0;
  2092. if (body)
  2093. rv = fetch_worker_read_body(w, body,
  2094. BR_SCRIPT_MAX, image_io_buf,
  2095. BR_PAGE_COMP_MAX, &tr, err,
  2096. sizeof(err));
  2097. else {
  2098. if (rv == 0)
  2099. s_copy(err, "out of memory",
  2100. sizeof(err));
  2101. rv = -1;
  2102. }
  2103. fetch_worker_release(w);
  2104. script_slot[i] = 0;
  2105. script_submit_window(&next, ferr, sizeof(ferr));
  2106. if (rv <= 0)
  2107. script_error("Cannot load script",
  2108. script_urls[i], err);
  2109. else if (tr || (unsigned int)rv >=
  2110. BR_SCRIPT_MAX)
  2111. script_error("Cannot load script",
  2112. script_urls[i],
  2113. "script is too large");
  2114. else {
  2115. body[rv] = '\0';
  2116. script_cache_put(script_urls[i], body,
  2117. (unsigned int)rv);
  2118. if (script->module)
  2119. js_browser_run_module(
  2120. (const char *)body,
  2121. script_urls[i]);
  2122. else
  2123. js_browser_run(
  2124. (const char *)body,
  2125. script_urls[i]);
  2126. }
  2127. free(body);
  2128. }
  2129. }
  2130. if (pending_action)
  2131. break;
  2132. }
  2133. js_browser_set_current_script(0);
  2134. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  2135. * load_home() stop it before the next navigation. */
  2136. if (doc.scripts_truncated && !js_last_error)
  2137. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  2138. 1);
  2139. }
  2140. /* ---- images ---- */
  2141. /* data: images that failed to decode (key = data_img_key()), so a layout
  2142. * pass does not retry them on every frame. */
  2143. #define DATA_IMG_FAIL_MAX 32
  2144. static unsigned int data_img_fail[DATA_IMG_FAIL_MAX];
  2145. static int data_img_nfail;
  2146. static void image_reset(void)
  2147. {
  2148. int i;
  2149. for (i = 0; i < BR_MAX_IMAGES; i++) {
  2150. images[i].state = 0;
  2151. images[i].native_w = images[i].native_h = 0;
  2152. images[i].err[0] = '\0';
  2153. /* heap_clear() ran before us, so these pointers are stale: drop
  2154. * them without calling free(). */
  2155. memset(&images[i].disp, 0, sizeof(images[i].disp));
  2156. images[i].disp_pixels = 0;
  2157. images[i].disp_last = 0;
  2158. }
  2159. image_count = 0;
  2160. data_img_nfail = 0;
  2161. image_pixels = 0;
  2162. image_disp_pixels = 0;
  2163. image_disp_clock = 0;
  2164. memset(img_stat_log, 0, sizeof(img_stat_log));
  2165. img_stat_log_len = 0;
  2166. img_stat_start = 0;
  2167. img_stat_wall = 0;
  2168. img_stat_net = img_stat_open = img_stat_first = 0;
  2169. img_stat_io = img_stat_dec = img_stat_scale = 0;
  2170. img_stat_paint = img_stat_reflow = 0;
  2171. img_stat_bytes = 0;
  2172. img_stat_n = 0;
  2173. img_last_dec_ms = img_last_scale_ms = 0;
  2174. img_repaint_ms = 0;
  2175. img_repaint_pending = 0;
  2176. preload_active = 0;
  2177. preload_pending = 0;
  2178. preload_wait = 0;
  2179. preload_node = 0;
  2180. preload_loaded = 0;
  2181. }
  2182. /* Ask for a repaint, but not more often than BR_IMG_REPAINT_MS while images
  2183. * are arriving. The main loop draws once per dirty frame; without this a
  2184. * page of N images did N full layout+paint passes. */
  2185. static void image_repaint(void)
  2186. {
  2187. unsigned int now = u_ticks_ms();
  2188. if (!img_repaint_ms || (now - img_repaint_ms) >= BR_IMG_REPAINT_MS) {
  2189. img_repaint_ms = now;
  2190. img_repaint_pending = 0;
  2191. ngui_invalidate(&ui);
  2192. } else {
  2193. img_repaint_pending = 1;
  2194. }
  2195. }
  2196. static void image_disp_drop(struct br_image *bi)
  2197. {
  2198. if (bi->disp.px)
  2199. free(bi->disp.px);
  2200. if (bi->disp.alpha)
  2201. free(bi->disp.alpha);
  2202. memset(&bi->disp, 0, sizeof(bi->disp));
  2203. if (bi->disp_pixels) {
  2204. if (image_disp_pixels >= bi->disp_pixels)
  2205. image_disp_pixels -= bi->disp_pixels;
  2206. bi->disp_pixels = 0;
  2207. }
  2208. }
  2209. /* Free the least recently used display caches until need pixels fit. The
  2210. * source bitmap (bi->img) is never evicted; a later draw rescales it again. */
  2211. static int image_disp_room(unsigned int need)
  2212. {
  2213. while (image_disp_pixels + need > BR_IMG_DISP_BUDGET) {
  2214. unsigned int oldest = ~0u;
  2215. int i, victim = -1;
  2216. for (i = 0; i < image_count; i++) {
  2217. if (!images[i].disp.px)
  2218. continue;
  2219. if (images[i].disp_last < oldest) {
  2220. oldest = images[i].disp_last;
  2221. victim = i;
  2222. }
  2223. }
  2224. if (victim < 0)
  2225. return -1;
  2226. image_disp_drop(&images[victim]);
  2227. }
  2228. return 0;
  2229. }
  2230. /* Return a bitmap at exactly dw x dh, building it once from the capped source
  2231. * bitmap. Callers then draw with scale 1 and img_draw's copy fast path. */
  2232. static struct img_image *image_display_get(struct br_image *bi, int dw, int dh)
  2233. {
  2234. struct img_blit b;
  2235. unsigned int px;
  2236. if (!bi || bi->state != 1 || !bi->img.px || dw < 1 || dh < 1)
  2237. return 0;
  2238. if (dw == (int)bi->img.w && dh == (int)bi->img.h)
  2239. return &bi->img;
  2240. if (dw > 4096 || dh > 4096)
  2241. return &bi->img;
  2242. if (bi->disp.px && bi->disp.w == (unsigned int)dw &&
  2243. bi->disp.h == (unsigned int)dh) {
  2244. bi->disp_last = ++image_disp_clock;
  2245. return &bi->disp;
  2246. }
  2247. px = (unsigned int)dw * (unsigned int)dh;
  2248. if (px > BR_IMG_DISP_BUDGET || image_disp_room(px) != 0)
  2249. return &bi->img;
  2250. image_disp_drop(bi);
  2251. bi->disp.px = (unsigned short *)malloc(px * 2u);
  2252. if (!bi->disp.px)
  2253. return &bi->img;
  2254. if (bi->img.alpha) {
  2255. bi->disp.alpha = (unsigned char *)malloc(px);
  2256. if (!bi->disp.alpha) {
  2257. free(bi->disp.px);
  2258. bi->disp.px = 0;
  2259. return &bi->img;
  2260. }
  2261. }
  2262. bi->disp.w = (unsigned int)dw;
  2263. bi->disp.h = (unsigned int)dh;
  2264. bi->disp.format = bi->img.format;
  2265. bi->disp.flags = 0;
  2266. memset(&b, 0, sizeof(b));
  2267. b.dst = bi->disp.px;
  2268. b.dst_w = dw;
  2269. b.dst_h = dh;
  2270. b.clip_w = dw;
  2271. b.clip_h = dh;
  2272. b.scale = ((unsigned int)dw << 16) / bi->img.w;
  2273. b.dst_a = bi->disp.alpha;
  2274. b.flags = bi->disp.alpha ? IMG_BLIT_SAVE_ALPHA : 0;
  2275. img_draw(&bi->img, &b);
  2276. bi->disp_pixels = px;
  2277. image_disp_pixels += px;
  2278. bi->disp_last = ++image_disp_clock;
  2279. return &bi->disp;
  2280. }
  2281. /* Decode into the shared arena, then copy/scale the result into a display
  2282. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  2283. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  2284. * pixels. Transparent edges are composited over white. */
  2285. /* One decode scratch arena per page, reused across images. Allocating and
  2286. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  2287. * each small display bitmap landed in the hole the previous arena left, so
  2288. * the next arena no longer fit and the heap ratcheted up until an app
  2289. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  2290. * still released right after their one image. */
  2291. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  2292. static unsigned char *decode_arena_get(unsigned int bytes)
  2293. {
  2294. if (decode_arena && decode_arena_size >= bytes)
  2295. return decode_arena;
  2296. free(decode_arena);
  2297. decode_arena = (unsigned char *)malloc(bytes);
  2298. decode_arena_size = decode_arena ? bytes : 0;
  2299. return decode_arena;
  2300. }
  2301. static void decode_arena_put(void)
  2302. {
  2303. if (decode_arena_size > DECODE_ARENA_KEEP) {
  2304. free(decode_arena);
  2305. decode_arena = 0;
  2306. decode_arena_size = 0;
  2307. }
  2308. }
  2309. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  2310. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  2311. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  2312. static int svg_text_sniff(const unsigned char *d, unsigned int len);
  2313. static int svg_decode_image(const unsigned char *data, unsigned int len,
  2314. struct br_image *bi, int box_w, int box_h);
  2315. static int decode_image_data(const unsigned char *data, unsigned int len,
  2316. struct br_image *bi, int box_w, int box_h,
  2317. int fit_w, int fit_h)
  2318. {
  2319. struct img_info info;
  2320. struct img_options opt;
  2321. struct img_mem mem;
  2322. struct img_image decoded;
  2323. unsigned char *arena;
  2324. unsigned int est, bytes, i;
  2325. unsigned int t0;
  2326. unsigned short *px;
  2327. unsigned char *alpha = 0;
  2328. int dw, dh, r;
  2329. bi->url_hash = 0;
  2330. img_last_dec_ms = 0;
  2331. img_last_scale_ms = 0;
  2332. if (img_sniff(data, len, &info) != 0) {
  2333. if (svg_text_sniff(data, len))
  2334. return svg_decode_image(data, len, bi,
  2335. box_w > 0 && box_h > 0 ? box_w : fit_w,
  2336. box_w > 0 && box_h > 0 ? box_h : fit_h);
  2337. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  2338. return -1;
  2339. }
  2340. est = img_estimate(&info);
  2341. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  2342. s_copy(bi->err, "image too large", sizeof(bi->err));
  2343. return -1;
  2344. }
  2345. arena = decode_arena_get(est);
  2346. if (!arena) {
  2347. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2348. return -1;
  2349. }
  2350. img_mem_init(&mem, arena, est);
  2351. opt.max_pixels = BR_IMG_PIX_MAX;
  2352. opt.max_w = fit_w > 0 ? (unsigned int)fit_w :
  2353. (box_w > 0 ? (unsigned int)box_w : 0);
  2354. opt.max_h = fit_h > 0 ? (unsigned int)fit_h :
  2355. (box_h > 0 ? (unsigned int)box_h : 0);
  2356. t0 = u_ticks_ms();
  2357. r = img_decode(data, len, &opt, &mem, &decoded);
  2358. img_last_dec_ms = u_ticks_ms() - t0;
  2359. if (r != 0) {
  2360. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  2361. goto fail;
  2362. }
  2363. if (decoded.w == 0 || decoded.h == 0) {
  2364. s_copy(bi->err, "empty image", sizeof(bi->err));
  2365. goto fail;
  2366. }
  2367. /* The JPEG decoder may have reduced the IDCT output; the layout still
  2368. * needs the intrinsic dimensions from the header. */
  2369. bi->native_w = info.width ? (int)info.width : (int)decoded.w;
  2370. bi->native_h = info.height ? (int)info.height : (int)decoded.h;
  2371. dw = (int)decoded.w;
  2372. dh = (int)decoded.h;
  2373. /* An <img> with a CSS/attribute box only ever needs a bitmap that big:
  2374. * decoding 1200x800 and then box-filtering it to 1000x666, only to
  2375. * paint it at 400x267, doubled the decode-time scaling work. cap both
  2376. * axes with one scale so the aspect ratio is preserved. */
  2377. if (fit_w > 0 || fit_h > 0) {
  2378. unsigned int scw = fit_w > 0 ?
  2379. ((unsigned int)fit_w << 16) / decoded.w : ~0u;
  2380. unsigned int sch = fit_h > 0 ?
  2381. ((unsigned int)fit_h << 16) / decoded.h : ~0u;
  2382. unsigned int sc = scw < sch ? scw : sch;
  2383. if (sc < 0x10000u) {
  2384. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2385. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2386. if (dw < 1)
  2387. dw = 1;
  2388. if (dh < 1)
  2389. dh = 1;
  2390. }
  2391. }
  2392. if (box_w > 0 && box_h > 0) {
  2393. /* cover: scale so both box sides are filled, never up */
  2394. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  2395. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  2396. unsigned int sc = sw > sh ? sw : sh;
  2397. if (sc < 0x10000u) {
  2398. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2399. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2400. }
  2401. }
  2402. if (dw > BR_IMG_LAYOUT_W) {
  2403. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  2404. dw = BR_IMG_LAYOUT_W;
  2405. }
  2406. if (dh < 1)
  2407. dh = 1;
  2408. if (dw < 1)
  2409. dw = 1;
  2410. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  2411. BR_IMG_PIXEL_BUDGET) {
  2412. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  2413. goto fail;
  2414. }
  2415. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  2416. px = (unsigned short *)malloc(bytes);
  2417. if (!px) {
  2418. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2419. goto fail;
  2420. }
  2421. /* Keep the alpha plane for the scaled image so transparent logos and
  2422. * icons composite over the page instead of the browser's dark theme
  2423. * background. Very large alpha images stay flattened to bound the
  2424. * heap use. */
  2425. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  2426. alpha = (unsigned char *)malloc((unsigned int)dw *
  2427. (unsigned int)dh);
  2428. if (alpha) {
  2429. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2430. alpha[i] = 255;
  2431. }
  2432. }
  2433. /* With an alpha plane the colour under transparent pixels only shows
  2434. * through partially covered edge pixels of the downscale: use white,
  2435. * as documented above, not the dark browser theme (which left a dark
  2436. * fringe around scaled app icons). */
  2437. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2438. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  2439. {
  2440. struct img_blit b;
  2441. b.dst = px;
  2442. b.dst_w = dw;
  2443. b.dst_h = dh;
  2444. b.clip_x = 0;
  2445. b.clip_y = 0;
  2446. b.clip_w = dw;
  2447. b.clip_h = dh;
  2448. b.x = 0;
  2449. b.y = 0;
  2450. b.scale = ((unsigned int)dw << 16) / decoded.w;
  2451. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  2452. b.bg2 = b.bg;
  2453. b.dst_a = alpha;
  2454. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  2455. t0 = u_ticks_ms();
  2456. img_draw(&decoded, &b);
  2457. img_last_scale_ms = u_ticks_ms() - t0;
  2458. }
  2459. bi->img.format = decoded.format;
  2460. bi->img.w = (unsigned int)dw;
  2461. bi->img.h = (unsigned int)dh;
  2462. bi->img.px = px;
  2463. bi->img.alpha = alpha;
  2464. bi->img.flags = 0;
  2465. bi->state = 1;
  2466. image_pixels += (unsigned int)dw * (unsigned int)dh;
  2467. decode_arena_put();
  2468. return 0;
  2469. fail:
  2470. decode_arena_put();
  2471. return -1;
  2472. }
  2473. /* ---- URL / local path handling ---- */
  2474. static int is_http(const char *s)
  2475. {
  2476. return starts_with(s, "http://") || starts_with(s, "https://");
  2477. }
  2478. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  2479. static int normalize_abs(const char *in, char *out, unsigned int cap)
  2480. {
  2481. char seg[64];
  2482. unsigned int i = 0, o = 1;
  2483. int depth = 0;
  2484. int trailing;
  2485. if (!in || in[0] != '/' || cap < 2)
  2486. return -1;
  2487. trailing = 0;
  2488. {
  2489. unsigned int n = s_len(in);
  2490. if (n > 1 && in[n - 1] == '/')
  2491. trailing = 1;
  2492. }
  2493. out[0] = '/';
  2494. while (in[i]) {
  2495. unsigned int n = 0;
  2496. while (in[i] == '/')
  2497. i++;
  2498. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  2499. if (n + 1 < sizeof(seg))
  2500. seg[n++] = in[i];
  2501. i++;
  2502. }
  2503. seg[n] = '\0';
  2504. if (n == 0)
  2505. break;
  2506. if (s_eq(seg, "."))
  2507. continue;
  2508. if (s_eq(seg, "..")) {
  2509. if (depth > 0) {
  2510. while (o > 1 && out[o - 1] != '/')
  2511. o--;
  2512. if (o > 1)
  2513. o--;
  2514. depth--;
  2515. }
  2516. continue;
  2517. }
  2518. if (o > 1) {
  2519. if (o + 1 >= cap)
  2520. return -1;
  2521. out[o++] = '/';
  2522. }
  2523. if (o + n + 1 >= cap)
  2524. return -1;
  2525. {
  2526. unsigned int j;
  2527. for (j = 0; j < n; j++)
  2528. out[o++] = seg[j];
  2529. }
  2530. depth++;
  2531. }
  2532. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2533. if (o + 1 >= cap)
  2534. return -1;
  2535. out[o++] = '/';
  2536. }
  2537. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2538. if (in[i] == '?' || in[i] == '#') {
  2539. while (in[i]) {
  2540. if (o + 1 >= cap)
  2541. return -1;
  2542. out[o++] = in[i++];
  2543. }
  2544. }
  2545. out[o] = '\0';
  2546. return 0;
  2547. }
  2548. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2549. {
  2550. char joined[BR_URL_MAX];
  2551. if (!in || !in[0]) {
  2552. s_copy(out, cwd[0] ? cwd : "/", cap);
  2553. return;
  2554. }
  2555. if (in[0] == '/') {
  2556. if (normalize_abs(in, out, cap) != 0)
  2557. s_copy(out, in, cap);
  2558. return;
  2559. }
  2560. {
  2561. unsigned int n = 0;
  2562. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2563. s_append(joined, &n, "/", sizeof(joined));
  2564. s_append(joined, &n, in, sizeof(joined));
  2565. }
  2566. if (normalize_abs(joined, out, cap) != 0)
  2567. s_copy(out, joined, cap);
  2568. }
  2569. /* ---- canonical origin cache ---- *
  2570. *
  2571. * Sites commonly redirect http://host to https://host and then to
  2572. * https://www.host. Remember the final scheme/host of the last navigation so
  2573. * a bare domain typed again goes straight there instead of paying for two
  2574. * more connections and TLS handshakes. Only default-port requests are
  2575. * rewritten; explicit ports are left alone. */
  2576. #define ORIGIN_CACHE_MAX 8
  2577. #define ORIGIN_FILE "/share/borigins"
  2578. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2579. UHTTP_HOST_MAX + 2))
  2580. struct origin_cache_entry {
  2581. char host[UHTTP_HOST_MAX];
  2582. char origin[UHTTP_HOST_MAX + 16];
  2583. };
  2584. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2585. static int origin_count;
  2586. static char origin_buf[ORIGIN_BUF_SIZE];
  2587. static int default_port(const struct uhttp_url *u)
  2588. {
  2589. return u->secure ? u->port == 443 : u->port == 80;
  2590. }
  2591. static void url_origin(const struct uhttp_url *u, char *out,
  2592. unsigned int cap)
  2593. {
  2594. unsigned int n = 0;
  2595. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2596. s_append(out, &n, u->host, cap);
  2597. if (!default_port(u)) {
  2598. s_append(out, &n, ":", cap);
  2599. s_append_dec(out, &n, u->port, cap);
  2600. }
  2601. }
  2602. static void origin_cache_apply(char *url, unsigned int cap)
  2603. {
  2604. struct uhttp_url u;
  2605. char out[BR_URL_MAX];
  2606. unsigned int n = 0;
  2607. int i;
  2608. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2609. return;
  2610. for (i = 0; i < origin_count; i++) {
  2611. if (!s_eq(u.host, origins[i].host))
  2612. continue;
  2613. s_append(out, &n, origins[i].origin, sizeof(out));
  2614. s_append(out, &n, u.path, sizeof(out));
  2615. s_copy(url, out, cap);
  2616. return;
  2617. }
  2618. }
  2619. static void origin_cache_save(void)
  2620. {
  2621. unsigned int n = 0;
  2622. int i;
  2623. for (i = 0; i < origin_count; i++) {
  2624. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2625. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2626. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2627. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2628. }
  2629. if (n)
  2630. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2631. (int)origin_buf, (int)n);
  2632. }
  2633. static void origin_cache_load(void)
  2634. {
  2635. char *p;
  2636. int rn;
  2637. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2638. (int)(sizeof(origin_buf) - 1));
  2639. if (rn <= 0)
  2640. return;
  2641. origin_buf[rn] = '\0';
  2642. p = origin_buf;
  2643. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2644. char *line = p, *origin;
  2645. while (*p && *p != '\n')
  2646. p++;
  2647. if (*p)
  2648. *p++ = '\0';
  2649. if (!line[0])
  2650. continue;
  2651. origin = line;
  2652. while (*origin && *origin != ' ')
  2653. origin++;
  2654. if (!*origin)
  2655. continue;
  2656. *origin++ = '\0';
  2657. if (!line[0] || !is_http(origin))
  2658. continue;
  2659. {
  2660. struct uhttp_url uo;
  2661. if (uhttp_parse_url(origin, &uo) != 0 ||
  2662. !s_eq(uo.path, "/"))
  2663. continue;
  2664. }
  2665. s_copy(origins[origin_count].host, line,
  2666. sizeof(origins[origin_count].host));
  2667. s_copy(origins[origin_count].origin, origin,
  2668. sizeof(origins[origin_count].origin));
  2669. origin_count++;
  2670. }
  2671. }
  2672. static int host_is_www_of(const char *host, const char *base)
  2673. {
  2674. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2675. host[3] == '.' && s_eq(host + 4, base);
  2676. }
  2677. static void origin_cache_learn(const char *requested, const char *final)
  2678. {
  2679. struct uhttp_url from, to;
  2680. char origin[UHTTP_HOST_MAX + 16];
  2681. int i;
  2682. if (!is_http(requested) || !is_http(final))
  2683. return;
  2684. if (uhttp_parse_url(requested, &from) != 0 ||
  2685. uhttp_parse_url(final, &to) != 0)
  2686. return;
  2687. if (!default_port(&from))
  2688. return;
  2689. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2690. from.port == to.port)
  2691. return;
  2692. /* Only remember origin-level canonicalisation: the same path, and
  2693. * either the same host or its www./apex sibling. A path- or
  2694. * host-specific redirect (a shortener, a login page) must not poison
  2695. * every request to the typed host. */
  2696. if (!s_eq(from.path, to.path))
  2697. return;
  2698. if (!s_eq(from.host, to.host) &&
  2699. !host_is_www_of(to.host, from.host) &&
  2700. !host_is_www_of(from.host, to.host))
  2701. return;
  2702. url_origin(&to, origin, sizeof(origin));
  2703. for (i = 0; i < origin_count; i++) {
  2704. if (s_eq(origins[i].host, from.host)) {
  2705. if (!s_eq(origins[i].origin, origin)) {
  2706. s_copy(origins[i].origin, origin,
  2707. sizeof(origins[i].origin));
  2708. origin_cache_save();
  2709. }
  2710. return;
  2711. }
  2712. }
  2713. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2714. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2715. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2716. origin_cache_save();
  2717. }
  2718. static int path_dir(const char *path, char *out, unsigned int cap)
  2719. {
  2720. unsigned int i, last = 0;
  2721. for (i = 0; path[i]; i++)
  2722. if (path[i] == '/')
  2723. last = i;
  2724. if (last == 0) {
  2725. if (cap < 2)
  2726. return -1;
  2727. out[0] = '/';
  2728. out[1] = '\0';
  2729. return 0;
  2730. }
  2731. if (last + 1 >= cap)
  2732. return -1;
  2733. {
  2734. unsigned int j;
  2735. for (j = 0; j < last; j++)
  2736. out[j] = path[j];
  2737. out[last] = '\0';
  2738. }
  2739. return 0;
  2740. }
  2741. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2742. static int resolve_link(const char *base, const char *href, char *out,
  2743. unsigned int cap)
  2744. {
  2745. static char joined[BR_URL_MAX]; /* leaf: off the stack */
  2746. if (!href || !href[0] || href[0] == '#')
  2747. return -1;
  2748. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2749. starts_with(href, "data:") || starts_with(href, "tel:"))
  2750. return -1;
  2751. if (starts_with(href, "about:")) {
  2752. s_copy(out, href, cap);
  2753. return 0;
  2754. }
  2755. if (is_http(href)) {
  2756. s_copy(out, href, cap);
  2757. return 0;
  2758. }
  2759. if (starts_with(href, "//")) {
  2760. if (is_http(base)) {
  2761. unsigned int n = 0;
  2762. s_append(out, &n, starts_with(base, "https:") ?
  2763. "https:" : "http:", cap);
  2764. s_append(out, &n, href, cap);
  2765. return 0;
  2766. }
  2767. return -1;
  2768. }
  2769. if (is_http(base)) {
  2770. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2771. }
  2772. /* local page */
  2773. if (href[0] == '/') {
  2774. if (normalize_abs(href, out, cap) != 0)
  2775. return -1;
  2776. return 0;
  2777. }
  2778. {
  2779. static char dir[BR_URL_MAX];
  2780. unsigned int n = 0;
  2781. if (s_eq(base, "about:home"))
  2782. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2783. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2784. s_copy(dir, "/", sizeof(dir));
  2785. s_append(joined, &n, dir, sizeof(joined));
  2786. if (n == 0 || joined[n - 1] != '/')
  2787. s_append(joined, &n, "/", sizeof(joined));
  2788. s_append(joined, &n, href, sizeof(joined));
  2789. }
  2790. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2791. }
  2792. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2793. * rest instead of failing when a page or stylesheet is larger than the
  2794. * buffer. The stream is still walked to the end, so a normal page is
  2795. * verified; a truncated compressed input still returns whatever was decoded
  2796. * so far. */
  2797. struct trunc_buf {
  2798. unsigned char *dst;
  2799. unsigned int cap, pos;
  2800. int full;
  2801. };
  2802. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2803. {
  2804. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2805. if (len > m->cap - m->pos) {
  2806. unsigned int room = m->cap - m->pos;
  2807. if (room) {
  2808. unsigned int i;
  2809. for (i = 0; i < room; i++)
  2810. m->dst[m->pos + i] = data[i];
  2811. m->pos += room;
  2812. }
  2813. m->full = 1;
  2814. return 0;
  2815. }
  2816. {
  2817. unsigned int i;
  2818. for (i = 0; i < len; i++)
  2819. m->dst[m->pos + i] = data[i];
  2820. }
  2821. m->pos += len;
  2822. return 0;
  2823. }
  2824. static void worker_wait_ui(void);
  2825. static void inflate_ui_pump(void *ctx)
  2826. {
  2827. static unsigned int last;
  2828. unsigned int now = u_ticks_ms();
  2829. (void)ctx;
  2830. if ((int)(now - last) >= 50) {
  2831. last = now;
  2832. worker_wait_ui();
  2833. }
  2834. }
  2835. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2836. unsigned char *dst, unsigned int cap,
  2837. unsigned int *outlen, int gzip, int *truncated)
  2838. {
  2839. struct inflate_src in;
  2840. struct inflate_sink sink;
  2841. struct trunc_buf m;
  2842. unsigned int got = 0;
  2843. int r;
  2844. in.p = src;
  2845. in.len = len;
  2846. in.more = 0;
  2847. in.ctx = 0;
  2848. m.dst = dst;
  2849. m.cap = cap;
  2850. m.pos = 0;
  2851. m.full = 0;
  2852. sink.write = trunc_write;
  2853. sink.ctx = &m;
  2854. inflate_init(&image_inflate_ws, &in, &sink);
  2855. image_inflate_ws.progress = inflate_ui_pump;
  2856. image_inflate_ws.progress_ctx = 0;
  2857. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2858. inflate_zlib(&image_inflate_ws, &got);
  2859. *outlen = m.pos;
  2860. *truncated = m.full || r != 0;
  2861. if (r != 0 && m.pos == 0)
  2862. return -1;
  2863. return 0;
  2864. }
  2865. /* ---- headless fetch workers ------------------------------------------ *
  2866. *
  2867. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2868. * writes the raw response, a small metadata file and a done marker under
  2869. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2870. * or a multi-megabyte body never freezes the UI and images download in
  2871. * parallel.
  2872. */
  2873. struct fetch_meta {
  2874. int status;
  2875. int error;
  2876. int trunc;
  2877. unsigned int len;
  2878. unsigned int open_ms;
  2879. unsigned int first_ms;
  2880. unsigned int total_ms;
  2881. /* Optional decoded bitmap produced by the helper (image jobs). */
  2882. unsigned int dw, dh, nw, nh;
  2883. unsigned int alpha;
  2884. unsigned int px_len;
  2885. unsigned int dec_ms;
  2886. int dec_err;
  2887. char encoding[16];
  2888. char ctype[64];
  2889. char final[BR_URL_MAX];
  2890. };
  2891. static void draw(unsigned int *action);
  2892. static void handle_keys(unsigned int *action);
  2893. static void handle_page_click(unsigned int *action);
  2894. #define FETCH_WORKERS 4
  2895. #define FETCH_PATH_MAX 32
  2896. /* One long-lived curl __serve helper per worker. Each worker has its own
  2897. * request/body/meta/done files under /share so several downloads can be in
  2898. * flight at once; the keep-alive connection stays in the helper process, so
  2899. * tls.c's per-process state remains valid. */
  2900. struct fetch_worker {
  2901. int pid;
  2902. int slot;
  2903. int busy;
  2904. int ready;
  2905. int image_job;
  2906. unsigned int seq;
  2907. unsigned int deadline;
  2908. int retried;
  2909. unsigned int dec_w, dec_h;
  2910. int dec_retried;
  2911. char req[FETCH_PATH_MAX];
  2912. char body[FETCH_PATH_MAX];
  2913. char meta[FETCH_PATH_MAX];
  2914. char done[FETCH_PATH_MAX];
  2915. char post[FETCH_PATH_MAX];
  2916. char px[FETCH_PATH_MAX];
  2917. /* Optional preload job attached to this worker. */
  2918. unsigned int node;
  2919. int bg;
  2920. char url[BR_URL_MAX];
  2921. struct fetch_meta m;
  2922. };
  2923. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2924. static int fetch_tty = -2;
  2925. static void fetch_tty_drain(void);
  2926. static unsigned int fetch_session;
  2927. static unsigned int fetch_seq;
  2928. static struct fetch_meta fetch_meta;
  2929. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2930. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2931. static int fetch_last_error;
  2932. static unsigned int meta_uint(char **pp)
  2933. {
  2934. char *p = *pp;
  2935. unsigned int v = 0;
  2936. while (*p >= '0' && *p <= '9') {
  2937. v = v * 10 + (unsigned int)(*p - '0');
  2938. p++;
  2939. }
  2940. while (*p && *p != '\n')
  2941. p++;
  2942. if (*p == '\n')
  2943. p++;
  2944. *pp = p;
  2945. return v;
  2946. }
  2947. static void meta_str(char **pp, char *out, unsigned int cap)
  2948. {
  2949. char *p = *pp;
  2950. unsigned int n = 0;
  2951. while (*p && *p != '\n' && n + 1 < cap)
  2952. out[n++] = *p++;
  2953. out[n] = '\0';
  2954. while (*p && *p != '\n')
  2955. p++;
  2956. if (*p == '\n')
  2957. p++;
  2958. *pp = p;
  2959. }
  2960. static void worker_wait_ui(void)
  2961. {
  2962. unsigned int action = 0;
  2963. if (!ngui_begin(&ui))
  2964. return;
  2965. draw(&action);
  2966. handle_keys(&action);
  2967. handle_page_click(&action);
  2968. if (action & ACT_WAIT_NAV) {
  2969. pending_action |= action & ACT_WAIT_NAV;
  2970. if ((action & ACT_NAV) && click_url[0])
  2971. s_copy(pending_url, click_url, sizeof(pending_url));
  2972. click_url[0] = '\0';
  2973. cancel_fetch = 1;
  2974. }
  2975. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  2976. ngui_invalidate(&ui);
  2977. ngui_end(&ui);
  2978. }
  2979. static void fetch_path(char *out, unsigned int cap, const char *kind,
  2980. unsigned int session, int slot)
  2981. {
  2982. unsigned int n = 0;
  2983. s_append(out, &n, "/share/bf", cap);
  2984. s_append_dec(out, &n, session, cap);
  2985. s_append(out, &n, "_", cap);
  2986. s_append_dec(out, &n, (unsigned int)slot, cap);
  2987. s_append(out, &n, kind, cap);
  2988. }
  2989. static void fetch_pool_init(void)
  2990. {
  2991. static int ready;
  2992. int i;
  2993. if (ready)
  2994. return;
  2995. ready = 1;
  2996. fetch_session = ((unsigned int)u_getpid() << 16) ^
  2997. (u_ticks_ms() & 0xFFFFu);
  2998. if (!fetch_session)
  2999. fetch_session = 1;
  3000. for (i = 0; i < FETCH_WORKERS; i++) {
  3001. struct fetch_worker *w = &fetch_workers[i];
  3002. w->pid = -1;
  3003. w->slot = i;
  3004. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  3005. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  3006. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  3007. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  3008. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  3009. fetch_path(w->px, sizeof(w->px), "px", fetch_session, i);
  3010. }
  3011. }
  3012. static void fetch_worker_stop(struct fetch_worker *w)
  3013. {
  3014. int i;
  3015. /* An abandoned image job leaves its node loadable again. */
  3016. if (w->busy && w->image_job && w->node < doc.nnode) {
  3017. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  3018. doc.nodes[w->node].bg_img_index = -1;
  3019. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  3020. doc.nodes[w->node].img_index = -1;
  3021. }
  3022. if (w->pid > 0) {
  3023. u_kill((unsigned int)w->pid);
  3024. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  3025. u_sleep_ms(5);
  3026. /* Let the reaper close the socket before we reuse the slot. */
  3027. u_sleep_ms(10);
  3028. }
  3029. w->pid = -1;
  3030. w->busy = 0;
  3031. w->ready = 0;
  3032. w->image_job = 0;
  3033. if (w->req[0]) {
  3034. u_syscall1(SYS_UNLINK, (int)w->done);
  3035. u_syscall1(SYS_UNLINK, (int)w->meta);
  3036. u_syscall1(SYS_UNLINK, (int)w->body);
  3037. u_syscall1(SYS_UNLINK, (int)w->post);
  3038. u_syscall1(SYS_UNLINK, (int)w->req);
  3039. }
  3040. }
  3041. static void fetch_workers_stop_all(void)
  3042. {
  3043. int i;
  3044. for (i = 0; i < FETCH_WORKERS; i++)
  3045. fetch_worker_stop(&fetch_workers[i]);
  3046. }
  3047. /* Abandon the transfers of the current page but keep idle helpers and their
  3048. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  3049. * because its response would otherwise land in a reused /share slot. */
  3050. static void fetch_workers_cancel_busy(void)
  3051. {
  3052. int i;
  3053. for (i = 0; i < FETCH_WORKERS; i++)
  3054. if (fetch_workers[i].busy)
  3055. fetch_worker_stop(&fetch_workers[i]);
  3056. }
  3057. static void fetch_workers_prepare_nav(const char *url)
  3058. {
  3059. int i;
  3060. (void)url;
  3061. for (i = 0; i < FETCH_WORKERS; i++) {
  3062. struct fetch_worker *w = &fetch_workers[i];
  3063. if (w->pid <= 0)
  3064. continue;
  3065. /* Only an in-flight transfer must be aborted. Idle helpers
  3066. * stay warm across origins: there are just FETCH_WORKERS of
  3067. * them, and uhttp_open drops the old connection when the
  3068. * next job is for another host. Killing and respawning all
  3069. * four on every navigation churned processes and sockets
  3070. * while images were still loading. */
  3071. if (w->busy)
  3072. fetch_worker_stop(w);
  3073. }
  3074. }
  3075. /* The browser is no longer the active window and no fetch is running: give
  3076. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  3077. static void fetch_workers_stop_if_unfocused(void)
  3078. {
  3079. int i;
  3080. fetch_tty_drain();
  3081. if (ui.focused || page_loading || preload_active)
  3082. return;
  3083. for (i = 0; i < FETCH_WORKERS; i++)
  3084. if (fetch_workers[i].pid > 0) {
  3085. fetch_workers_stop_all();
  3086. return;
  3087. }
  3088. }
  3089. /* The helpers (and this process, since u_tty_create() rebinds our own
  3090. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  3091. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  3092. * a dozen TLS connections every helper hung in its next log line, so the
  3093. * following cross-origin navigation sat at "Loading..." until it timed out.
  3094. * Drain and discard it from every wait/poll loop. */
  3095. static void fetch_tty_drain(void)
  3096. {
  3097. char sink[512];
  3098. int i;
  3099. if (fetch_tty <= 0)
  3100. return;
  3101. for (i = 0; i < 16; i++)
  3102. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  3103. break;
  3104. }
  3105. static int fetch_worker_start(struct fetch_worker *w, char *err,
  3106. unsigned int errcap)
  3107. {
  3108. char arg[40];
  3109. unsigned int n = 0;
  3110. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  3111. return 0;
  3112. w->pid = -1;
  3113. fetch_pool_init();
  3114. if (fetch_tty == -2) {
  3115. int t = u_tty_create();
  3116. fetch_tty = t > 0 ? t : 0;
  3117. }
  3118. s_append(arg, &n, "__serve ", sizeof(arg));
  3119. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  3120. s_append(arg, &n, " ", sizeof(arg));
  3121. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  3122. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  3123. if (w->pid <= 0) {
  3124. w->pid = -1;
  3125. s_copy(err, "cannot start network helper", errcap);
  3126. return -1;
  3127. }
  3128. return 0;
  3129. }
  3130. static struct fetch_worker *fetch_worker_alloc(void)
  3131. {
  3132. int i;
  3133. fetch_pool_init();
  3134. for (i = 0; i < FETCH_WORKERS; i++)
  3135. if (!fetch_workers[i].busy)
  3136. return &fetch_workers[i];
  3137. return 0;
  3138. }
  3139. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3140. unsigned int cap, const char *method,
  3141. const char *ctype, const char *post,
  3142. unsigned int post_len, unsigned int node,
  3143. int bg, unsigned int dec_w,
  3144. unsigned int dec_h, char *err,
  3145. unsigned int errcap);
  3146. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  3147. unsigned int cap, const char *post,
  3148. unsigned int post_len, unsigned int node,
  3149. int bg, char *err, unsigned int errcap)
  3150. {
  3151. /* A body pointer with no bytes is still a POST: the classic request
  3152. * line would turn it into a GET. */
  3153. if (post && !post_len)
  3154. return fetch_worker_submit_req(w, url, cap, "POST",
  3155. "application/x-www-form-urlencoded", post, 0, node,
  3156. bg, 0, 0, err, errcap);
  3157. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  3158. node, bg, 0, 0, err, errcap);
  3159. }
  3160. /* Image job: ask the helper to decode at these display bounds as well. */
  3161. static int fetch_worker_submit_image(struct fetch_worker *w, const char *url,
  3162. unsigned int cap, unsigned int node,
  3163. int bg, unsigned int dec_w,
  3164. unsigned int dec_h, char *err,
  3165. unsigned int errcap)
  3166. {
  3167. return fetch_worker_submit_req(w, url, cap, 0, 0, 0, 0, node, bg,
  3168. dec_w, dec_h, err, errcap);
  3169. }
  3170. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  3171. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  3172. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3173. unsigned int cap, const char *method,
  3174. const char *ctype, const char *post,
  3175. unsigned int post_len, unsigned int node,
  3176. int bg, unsigned int dec_w,
  3177. unsigned int dec_h, char *err,
  3178. unsigned int errcap)
  3179. {
  3180. static char req[BR_URL_MAX + 256];
  3181. unsigned int n = 0;
  3182. fetch_seq++;
  3183. if (!fetch_seq)
  3184. fetch_seq = 1;
  3185. w->seq = fetch_seq;
  3186. w->ready = 0;
  3187. w->image_job = 0;
  3188. w->retried = 0;
  3189. w->m.error = 0;
  3190. w->node = node;
  3191. w->bg = bg;
  3192. w->dec_w = dec_w;
  3193. w->dec_h = dec_h;
  3194. w->dec_retried = 0;
  3195. s_copy(w->url, url, sizeof(w->url));
  3196. s_append_dec(req, &n, w->seq, sizeof(req));
  3197. s_append(req, &n, " ", sizeof(req));
  3198. s_append_dec(req, &n, cap, sizeof(req));
  3199. s_append(req, &n, " ", sizeof(req));
  3200. if (dec_w || dec_h) {
  3201. s_append(req, &n, "D ", sizeof(req));
  3202. s_append_dec(req, &n, dec_w, sizeof(req));
  3203. s_append(req, &n, " ", sizeof(req));
  3204. s_append_dec(req, &n, dec_h, sizeof(req));
  3205. s_append(req, &n, " ", sizeof(req));
  3206. } else if (method) {
  3207. unsigned int k;
  3208. s_append(req, &n, "X ", sizeof(req));
  3209. s_append(req, &n, method, sizeof(req));
  3210. s_append(req, &n, " ", sizeof(req));
  3211. s_append_dec(req, &n, post_len, sizeof(req));
  3212. s_append(req, &n, " ", sizeof(req));
  3213. if (!ctype || !ctype[0])
  3214. s_append(req, &n, "-", sizeof(req));
  3215. /* One token on the request line: drop the spaces
  3216. * ("application/json; charset=utf-8" stays valid). */
  3217. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  3218. if (ctype[k] != ' ')
  3219. req[n++] = ctype[k];
  3220. req[n] = '\0';
  3221. s_append(req, &n, " ", sizeof(req));
  3222. } else if (post_len) {
  3223. s_append(req, &n, "POST ", sizeof(req));
  3224. s_append_dec(req, &n, post_len, sizeof(req));
  3225. s_append(req, &n, " ", sizeof(req));
  3226. }
  3227. s_append(req, &n, url, sizeof(req));
  3228. s_append(req, &n, "\n", sizeof(req));
  3229. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  3230. (int)post, (int)post_len) < 0) {
  3231. s_copy(err, "cannot queue form body", errcap);
  3232. return -1;
  3233. }
  3234. u_syscall1(SYS_UNLINK, (int)w->done);
  3235. u_syscall1(SYS_UNLINK, (int)w->meta);
  3236. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  3237. s_copy(err, "cannot queue network request", errcap);
  3238. return -1;
  3239. }
  3240. if (fetch_worker_start(w, err, errcap) != 0)
  3241. return -1;
  3242. w->busy = 1;
  3243. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  3244. return 0;
  3245. }
  3246. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  3247. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  3248. unsigned int errcap)
  3249. {
  3250. static char meta[BR_URL_MAX + 1024];
  3251. char *p;
  3252. int rn, mseq;
  3253. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  3254. (int)(sizeof(meta) - 1));
  3255. if (rn <= 0) {
  3256. s_copy(err, "network helper failed", errcap);
  3257. return -1;
  3258. }
  3259. meta[rn] = '\0';
  3260. p = meta;
  3261. mseq = (int)meta_uint(&p);
  3262. if (mseq != (int)w->seq) {
  3263. s_copy(err, "stale network response", errcap);
  3264. return -1;
  3265. }
  3266. w->m.status = (int)meta_uint(&p);
  3267. w->m.error = (int)meta_uint(&p);
  3268. w->m.trunc = (int)meta_uint(&p);
  3269. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  3270. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  3271. meta_str(&p, w->m.final, sizeof(w->m.final));
  3272. w->m.len = meta_uint(&p);
  3273. w->m.open_ms = 0;
  3274. w->m.first_ms = 0;
  3275. w->m.total_ms = 0;
  3276. if (*p) {
  3277. w->m.open_ms = meta_uint(&p);
  3278. w->m.first_ms = meta_uint(&p);
  3279. w->m.total_ms = meta_uint(&p);
  3280. }
  3281. w->m.dw = w->m.dh = w->m.nw = w->m.nh = 0;
  3282. w->m.alpha = w->m.px_len = w->m.dec_ms = 0;
  3283. w->m.dec_err = 0;
  3284. if (*p) {
  3285. w->m.dw = meta_uint(&p);
  3286. w->m.dh = meta_uint(&p);
  3287. w->m.nw = meta_uint(&p);
  3288. w->m.nh = meta_uint(&p);
  3289. w->m.alpha = meta_uint(&p);
  3290. w->m.px_len = meta_uint(&p);
  3291. w->m.dec_err = (int)meta_uint(&p);
  3292. w->m.dec_ms = meta_uint(&p);
  3293. }
  3294. if (w->m.error) {
  3295. s_copy(err, uhttp_error_string(w->m.error), errcap);
  3296. return -1;
  3297. }
  3298. w->ready = 1;
  3299. return 0;
  3300. }
  3301. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  3302. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  3303. unsigned int errcap)
  3304. {
  3305. static char done[24];
  3306. char *p;
  3307. int rn, mseq;
  3308. fetch_tty_drain();
  3309. if (!w->busy)
  3310. return -1;
  3311. if (w->ready)
  3312. return 1;
  3313. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  3314. (int)(sizeof(done) - 1));
  3315. if (rn > 0) {
  3316. done[rn] = '\0';
  3317. p = done;
  3318. mseq = (int)meta_uint(&p);
  3319. if (mseq == (int)w->seq) {
  3320. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  3321. fetch_worker_stop(w);
  3322. return -1;
  3323. }
  3324. return 1;
  3325. }
  3326. }
  3327. if (!u_alive((unsigned int)w->pid)) {
  3328. w->pid = -1;
  3329. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  3330. w->retried = 1;
  3331. return 0;
  3332. }
  3333. s_copy(err, "network helper stopped", errcap);
  3334. fetch_worker_stop(w);
  3335. return -1;
  3336. }
  3337. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  3338. s_copy(err, "network request timed out", errcap);
  3339. fetch_worker_stop(w);
  3340. return -1;
  3341. }
  3342. return 0;
  3343. }
  3344. /* Copy the completed body, inflating it if the server ignored our identity
  3345. * request. Mirrors the old fetch_remote body path. */
  3346. static int fetch_worker_read_body(struct fetch_worker *w,
  3347. unsigned char *plain,
  3348. unsigned int plaincap,
  3349. unsigned char *comp,
  3350. unsigned int compcap,
  3351. int *truncated, char *err,
  3352. unsigned int errcap)
  3353. {
  3354. int rv, zr, was_trunc;
  3355. if (contains_ci(w->m.encoding, "gzip") ||
  3356. contains_ci(w->m.encoding, "deflate")) {
  3357. unsigned int comp_len = 0, plen = 0;
  3358. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  3359. (int)compcap);
  3360. if (rv < 0) {
  3361. s_copy(err, "empty response", errcap);
  3362. return -1;
  3363. }
  3364. comp_len = (unsigned int)rv;
  3365. if (comp_len < w->m.len) {
  3366. s_copy(err, "compressed response is too large", errcap);
  3367. return -1;
  3368. }
  3369. if (contains_ci(w->m.encoding, "deflate"))
  3370. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3371. &plen, 0, &was_trunc);
  3372. else
  3373. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3374. &plen, 1, &was_trunc);
  3375. if (zr != 0) {
  3376. s_copy(err, "compressed response is corrupt", errcap);
  3377. return -1;
  3378. }
  3379. *truncated = w->m.trunc || was_trunc;
  3380. return (int)plen;
  3381. }
  3382. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  3383. if (rv < 0) {
  3384. s_copy(err, "empty response", errcap);
  3385. return -1;
  3386. }
  3387. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  3388. return rv;
  3389. }
  3390. static void fetch_worker_release(struct fetch_worker *w)
  3391. {
  3392. u_syscall1(SYS_UNLINK, (int)w->done);
  3393. u_syscall1(SYS_UNLINK, (int)w->meta);
  3394. u_syscall1(SYS_UNLINK, (int)w->body);
  3395. u_syscall1(SYS_UNLINK, (int)w->post);
  3396. u_syscall1(SYS_UNLINK, (int)w->px);
  3397. u_syscall1(SYS_UNLINK, (int)w->req);
  3398. w->busy = 0;
  3399. w->ready = 0;
  3400. w->image_job = 0;
  3401. w->dec_w = 0;
  3402. w->dec_h = 0;
  3403. w->dec_retried = 0;
  3404. }
  3405. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  3406. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  3407. unsigned int errcap)
  3408. {
  3409. for (;;) {
  3410. int rv;
  3411. if (!fetch_wait_passive)
  3412. worker_wait_ui();
  3413. if (cancel_fetch || pending_action) {
  3414. fetch_workers_cancel_busy();
  3415. return FETCH_ABORT;
  3416. }
  3417. rv = fetch_worker_poll(w, err, errcap);
  3418. if (rv != 0)
  3419. return rv == 1 ? 0 : -1;
  3420. u_sleep_ms(10);
  3421. }
  3422. }
  3423. static int fetch_remote(const char *url, unsigned int cap,
  3424. const char *post, unsigned int post_len,
  3425. unsigned char *plain, unsigned int plaincap,
  3426. unsigned char *comp, unsigned int compcap,
  3427. struct fetch_meta *m, int *truncated,
  3428. char *err, unsigned int errcap)
  3429. {
  3430. struct fetch_worker *w = fetch_worker_alloc();
  3431. int rv;
  3432. fetch_last_error = 0;
  3433. if (!w) {
  3434. s_copy(err, "network busy", errcap);
  3435. return -1;
  3436. }
  3437. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  3438. err, errcap) != 0) {
  3439. fetch_worker_release(w);
  3440. return -1;
  3441. }
  3442. rv = fetch_worker_wait(w, err, errcap);
  3443. if (rv == FETCH_ABORT) {
  3444. fetch_worker_release(w);
  3445. return FETCH_ABORT;
  3446. }
  3447. if (rv != 0) {
  3448. fetch_last_error = w->m.error;
  3449. fetch_worker_release(w);
  3450. return -1;
  3451. }
  3452. *m = w->m;
  3453. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  3454. truncated, err, errcap);
  3455. fetch_worker_release(w);
  3456. if (rv >= 0 && (cancel_fetch || pending_action))
  3457. return FETCH_ABORT;
  3458. return rv;
  3459. }
  3460. static int fetch_worker_status(const struct fetch_worker *w)
  3461. {
  3462. return w->m.status;
  3463. }
  3464. /* fetch()/XHR through a helper: one request, the status and body come back
  3465. * whatever the HTTP status (a 401 is an answer, not a network error). */
  3466. static int js_worker_http(const char *method, const char *url,
  3467. const char *ctype, const char *body,
  3468. unsigned int body_len, struct js_http_resp *r,
  3469. char *err, int errcap)
  3470. {
  3471. struct fetch_worker *w = fetch_worker_alloc();
  3472. unsigned char *plain;
  3473. int rv, tr = 0;
  3474. if (!w) {
  3475. s_copy(err, "network busy", (unsigned int)errcap);
  3476. return -1;
  3477. }
  3478. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  3479. body_len, 0, 0, 0, 0, err,
  3480. (unsigned int)errcap) != 0) {
  3481. fetch_worker_release(w);
  3482. return -1;
  3483. }
  3484. fetch_wait_passive++;
  3485. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  3486. fetch_wait_passive--;
  3487. if (rv != 0) {
  3488. if (rv == FETCH_ABORT)
  3489. s_copy(err, "page is navigating", (unsigned int)errcap);
  3490. fetch_worker_release(w);
  3491. return -1;
  3492. }
  3493. r->status = w->m.status;
  3494. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  3495. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  3496. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  3497. if (!plain) {
  3498. fetch_worker_release(w);
  3499. s_copy(err, "out of memory", (unsigned int)errcap);
  3500. return -1;
  3501. }
  3502. if (w->m.len == 0) {
  3503. rv = 0; /* 204, an empty 200: no body file */
  3504. } else {
  3505. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  3506. image_io_buf, BR_PAGE_COMP_MAX,
  3507. &tr, err, (unsigned int)errcap);
  3508. }
  3509. fetch_worker_release(w);
  3510. if (rv < 0) {
  3511. free(plain);
  3512. return -1;
  3513. }
  3514. plain[rv] = '\0';
  3515. r->body = (char *)plain;
  3516. r->len = (unsigned int)rv;
  3517. return 0;
  3518. }
  3519. /* ---- HTTP / file fetch ---- */
  3520. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  3521. unsigned int *outlen, int *is_local, char *ctype,
  3522. unsigned int ctcap, char *final, unsigned int finalcap,
  3523. char *err, unsigned int errcap, int *truncated,
  3524. const char *post, unsigned int post_len)
  3525. {
  3526. unsigned char *buf;
  3527. unsigned int len;
  3528. int tr = 0;
  3529. int rv;
  3530. *out = 0;
  3531. *outlen = 0;
  3532. *truncated = 0;
  3533. if (final && finalcap)
  3534. final[0] = '\0';
  3535. if (ctype && ctcap)
  3536. ctype[0] = '\0';
  3537. if (url[0] == '/') {
  3538. char pathbuf[BR_URL_MAX];
  3539. const char *open_url = url;
  3540. unsigned int i = 0;
  3541. /* A local form GET keeps ?query in the address bar but the
  3542. * file lookup uses the path alone, like a real browser. */
  3543. while (url[i] && url[i] != '?' && url[i] != '#')
  3544. i++;
  3545. if (url[i]) {
  3546. s_copy(pathbuf, url, i + 1);
  3547. open_url = pathbuf;
  3548. }
  3549. buf = (unsigned char *)malloc(cap);
  3550. if (!buf) {
  3551. s_copy(err, "out of memory", errcap);
  3552. return -1;
  3553. }
  3554. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  3555. if (rv < 0) {
  3556. free(buf);
  3557. s_copy(err, "file not found", errcap);
  3558. return -1;
  3559. }
  3560. *out = buf;
  3561. *outlen = (unsigned int)rv;
  3562. *is_local = 1;
  3563. if (ctype)
  3564. s_copy(ctype, "text/html", ctcap);
  3565. if (final)
  3566. s_copy(final, url, finalcap);
  3567. if ((unsigned int)rv == cap)
  3568. *truncated = 1;
  3569. return 0;
  3570. }
  3571. buf = (unsigned char *)malloc(cap);
  3572. if (!buf) {
  3573. s_copy(err, "out of memory", errcap);
  3574. return -1;
  3575. }
  3576. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3577. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3578. if (rv == FETCH_ABORT) {
  3579. free(buf);
  3580. return FETCH_ABORT;
  3581. }
  3582. if (rv < 0) {
  3583. free(buf);
  3584. return -1;
  3585. }
  3586. len = (unsigned int)rv;
  3587. if (len == 0) {
  3588. free(buf);
  3589. s_copy(err, "empty response", errcap);
  3590. return -1;
  3591. }
  3592. if (ctype)
  3593. s_copy(ctype, fetch_meta.ctype, ctcap);
  3594. if (final && fetch_meta.final[0])
  3595. s_copy(final, fetch_meta.final, finalcap);
  3596. *is_local = 0;
  3597. *out = buf;
  3598. *outlen = len;
  3599. *truncated = tr;
  3600. return 0;
  3601. }
  3602. /* Load every @font-face the parser registered. Local files go through
  3603. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  3604. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  3605. * to the built-in regular/bold/italic/mono set. */
  3606. static void load_font_faces(void)
  3607. {
  3608. unsigned int i;
  3609. memset(font_faces, 0, sizeof(font_faces));
  3610. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  3611. i <= BR_MAX_FACES; i++) {
  3612. const char *url = br_font_face_url((int)i);
  3613. const char *base = br_font_face_base((int)i);
  3614. char abs[BR_URL_MAX];
  3615. if (!url || !url[0])
  3616. continue;
  3617. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  3618. sizeof(abs)) != 0)
  3619. continue;
  3620. if (abs[0] == '/') {
  3621. font_faces[i - 1] = ufont_face_open_path(abs);
  3622. } else if (is_http(abs)) {
  3623. unsigned char *buf;
  3624. char err[64];
  3625. int rv, tr = 0;
  3626. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  3627. if (!buf)
  3628. continue;
  3629. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3630. UFONT_MAX_FILE, image_io_buf,
  3631. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  3632. err, sizeof(err));
  3633. if (rv > 0)
  3634. font_faces[i - 1] = ufont_face_open_mem(buf,
  3635. rv);
  3636. free(buf);
  3637. }
  3638. }
  3639. }
  3640. /* Remote scripts are cached under /share for the current boot, like the
  3641. * stylesheet cache, so reloads and later visits skip the network. */
  3642. static int script_cache_count;
  3643. static unsigned int script_cache_hash(const char *s)
  3644. {
  3645. unsigned int h = 2166136261u;
  3646. while (*s) {
  3647. h ^= (unsigned char)*s++;
  3648. h *= 16777619u;
  3649. }
  3650. return h;
  3651. }
  3652. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3653. {
  3654. unsigned int n = 0;
  3655. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3656. s_append_dec(out, &n, script_cache_hash(url), cap);
  3657. }
  3658. static void script_cache_clear(void)
  3659. {
  3660. struct sys_dirent d;
  3661. char path[96];
  3662. for (;;) {
  3663. int i, found = 0;
  3664. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3665. (int)&d) == 1; i++) {
  3666. unsigned int n = 0;
  3667. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3668. continue;
  3669. s_append(path, &n, "/share/", sizeof(path));
  3670. s_append(path, &n, d.name, sizeof(path));
  3671. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3672. return;
  3673. found = 1;
  3674. break;
  3675. }
  3676. if (!found)
  3677. break;
  3678. }
  3679. script_cache_count = 0;
  3680. }
  3681. static void script_cache_init(void)
  3682. {
  3683. struct sys_dirent d;
  3684. int i, count = 0;
  3685. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3686. (int)&d) == 1; i++)
  3687. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3688. count++;
  3689. if (count >= SCRIPT_CACHE_MAX) {
  3690. script_cache_clear();
  3691. return;
  3692. }
  3693. script_cache_count = count;
  3694. }
  3695. static int script_cache_get(const char *url, unsigned char **out,
  3696. unsigned int *outlen)
  3697. {
  3698. char path[96];
  3699. struct sys_stat st;
  3700. unsigned char *buf;
  3701. int rn;
  3702. script_cache_path(url, path, sizeof(path));
  3703. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3704. st.size >= SCRIPT_CACHE_FILE_MAX)
  3705. return 0;
  3706. buf = (unsigned char *)malloc(st.size + 1);
  3707. if (!buf)
  3708. return 0;
  3709. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3710. if (rn != (int)st.size) {
  3711. free(buf);
  3712. return 0;
  3713. }
  3714. buf[st.size] = '\0';
  3715. *out = buf;
  3716. *outlen = st.size;
  3717. return 1;
  3718. }
  3719. static void script_cache_put(const char *url, const unsigned char *data,
  3720. unsigned int len)
  3721. {
  3722. char path[96];
  3723. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3724. len >= SCRIPT_CACHE_FILE_MAX)
  3725. return;
  3726. script_cache_path(url, path, sizeof(path));
  3727. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3728. (int)len) >= 0)
  3729. script_cache_count++;
  3730. }
  3731. static int script_cache_has(const char *url)
  3732. {
  3733. char path[96];
  3734. struct sys_stat st;
  3735. script_cache_path(url, path, sizeof(path));
  3736. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3737. st.size < SCRIPT_CACHE_FILE_MAX;
  3738. }
  3739. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3740. static int fetch_script_text(const char *url, unsigned char **out,
  3741. unsigned int *outlen, char *err,
  3742. unsigned int errcap)
  3743. {
  3744. unsigned char *buf;
  3745. unsigned int len;
  3746. int local, truncated = 0;
  3747. char ctype[64], final[BR_URL_MAX];
  3748. int rv;
  3749. *out = 0;
  3750. *outlen = 0;
  3751. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3752. return 0;
  3753. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3754. sizeof(ctype), final, sizeof(final), err, errcap,
  3755. &truncated, 0, 0);
  3756. if (rv != 0)
  3757. return rv;
  3758. if (truncated || len >= BR_SCRIPT_MAX) {
  3759. free(buf);
  3760. s_copy(err, "script is too large", errcap);
  3761. return -1;
  3762. }
  3763. buf[len] = '\0';
  3764. if (!local)
  3765. script_cache_put(url, buf, len);
  3766. *out = buf;
  3767. *outlen = len;
  3768. return 0;
  3769. }
  3770. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  3771. * the heap, so images must not allocate their file body from it as well. */
  3772. static int fetch_image(const char *url, unsigned int cap,
  3773. unsigned char **out, unsigned int *outlen,
  3774. char *err, unsigned int errcap)
  3775. {
  3776. unsigned int len;
  3777. int tr = 0;
  3778. int rv;
  3779. *out = 0;
  3780. *outlen = 0;
  3781. if (cap > BR_IMG_FILE_MAX)
  3782. cap = BR_IMG_FILE_MAX;
  3783. if (url[0] == '/') {
  3784. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  3785. (int)cap);
  3786. if (rv < 0) {
  3787. s_copy(err, "file not found", errcap);
  3788. return -1;
  3789. }
  3790. *out = image_file_buf;
  3791. *outlen = (unsigned int)rv;
  3792. return 0;
  3793. }
  3794. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  3795. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  3796. if (rv == FETCH_ABORT)
  3797. return FETCH_ABORT;
  3798. if (rv < 0)
  3799. return -1;
  3800. len = (unsigned int)rv;
  3801. if (len == 0) {
  3802. s_copy(err, "empty image", errcap);
  3803. return -1;
  3804. }
  3805. *out = image_file_buf;
  3806. *outlen = len;
  3807. return 0;
  3808. }
  3809. /* Remote stylesheets are immutable enough for the current boot: keep
  3810. * successful responses under /share so a reload, a second visit or a fresh
  3811. * browser launch does not fetch the same five sheets over the network again.
  3812. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  3813. static int css_cache_count;
  3814. static unsigned int css_cache_hash(const char *s)
  3815. {
  3816. unsigned int h = 2166136261u;
  3817. while (*s) {
  3818. h ^= (unsigned char)*s++;
  3819. h *= 16777619u;
  3820. }
  3821. return h;
  3822. }
  3823. static void css_cache_path(const char *url, char *out, unsigned int cap)
  3824. {
  3825. unsigned int n = 0;
  3826. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  3827. s_append_dec(out, &n, css_cache_hash(url), cap);
  3828. }
  3829. static void css_cache_clear(void)
  3830. {
  3831. struct sys_dirent d;
  3832. char path[96];
  3833. for (;;) {
  3834. int i, found = 0;
  3835. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3836. (int)&d) == 1; i++) {
  3837. unsigned int n = 0;
  3838. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  3839. continue;
  3840. s_append(path, &n, "/share/", sizeof(path));
  3841. s_append(path, &n, d.name, sizeof(path));
  3842. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3843. return;
  3844. found = 1;
  3845. break;
  3846. }
  3847. if (!found)
  3848. break;
  3849. }
  3850. css_cache_count = 0;
  3851. }
  3852. static void css_cache_init(void)
  3853. {
  3854. struct sys_dirent d;
  3855. int i, count = 0;
  3856. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3857. (int)&d) == 1; i++)
  3858. if (starts_with(d.name, CSS_CACHE_PREFIX))
  3859. count++;
  3860. if (count >= CSS_CACHE_MAX) {
  3861. css_cache_clear();
  3862. return;
  3863. }
  3864. css_cache_count = count;
  3865. }
  3866. static int css_cache_get(const char *url, unsigned char **out,
  3867. unsigned int *outlen)
  3868. {
  3869. char path[96];
  3870. int rn;
  3871. css_cache_path(url, path, sizeof(path));
  3872. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  3873. (int)CSS_CACHE_FILE_MAX);
  3874. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  3875. return 0;
  3876. *out = image_io_buf;
  3877. *outlen = (unsigned int)rn;
  3878. return 1;
  3879. }
  3880. static void css_cache_put(const char *url, const unsigned char *data,
  3881. unsigned int len)
  3882. {
  3883. char path[96];
  3884. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  3885. len >= CSS_CACHE_FILE_MAX)
  3886. return;
  3887. css_cache_path(url, path, sizeof(path));
  3888. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3889. (int)len) >= 0)
  3890. css_cache_count++;
  3891. }
  3892. static int css_cache_has(const char *url)
  3893. {
  3894. char path[96];
  3895. struct sys_stat st;
  3896. css_cache_path(url, path, sizeof(path));
  3897. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3898. st.size < CSS_CACHE_FILE_MAX;
  3899. }
  3900. /* Read one stylesheet into the shared static buffer. CSS is parsed
  3901. * immediately, so it does not need the page heap; this leaves the heap for
  3902. * the 2 MB page body, the rules and the scaled image bitmaps. */
  3903. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  3904. char *err, unsigned int errcap)
  3905. {
  3906. unsigned int len;
  3907. int tr = 0;
  3908. int rv;
  3909. *out = 0;
  3910. *outlen = 0;
  3911. if (url[0] == '/') {
  3912. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  3913. (int)BR_CSS_MAX);
  3914. if (rv < 0) {
  3915. s_copy(err, "stylesheet not found", errcap);
  3916. return -1;
  3917. }
  3918. *out = image_io_buf;
  3919. *outlen = (unsigned int)rv;
  3920. return 0;
  3921. }
  3922. if (css_cache_get(url, out, outlen))
  3923. return 0;
  3924. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  3925. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  3926. &fetch_meta, &tr, err, errcap);
  3927. if (rv == FETCH_ABORT)
  3928. return FETCH_ABORT;
  3929. if (rv < 0)
  3930. return -1;
  3931. len = (unsigned int)rv;
  3932. if (len == 0) {
  3933. s_copy(err, "empty stylesheet", errcap);
  3934. return -1;
  3935. }
  3936. *out = image_io_buf;
  3937. *outlen = len;
  3938. css_cache_put(url, image_io_buf, len);
  3939. return 0;
  3940. }
  3941. static void redraw_now(void);
  3942. static char error_page[1024];
  3943. static void show_error(const char *title, const char *detail)
  3944. {
  3945. char *page = error_page;
  3946. unsigned int n = 0;
  3947. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  3948. s_append(page, &n, title, sizeof(error_page));
  3949. s_append(page, &n, "</h2><p>", sizeof(error_page));
  3950. {
  3951. const char *p = detail;
  3952. while (*p && n + 1 < sizeof(error_page)) {
  3953. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  3954. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  3955. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  3956. else page[n++] = *p;
  3957. p++;
  3958. }
  3959. }
  3960. page[n] = '\0';
  3961. s_append(page, &n, "</p><p>", sizeof(error_page));
  3962. s_append(page, &n, page_url, sizeof(error_page));
  3963. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  3964. sizeof(error_page));
  3965. br_parse(&doc, page, n);
  3966. layout_valid = 0;
  3967. preload_active = 0;
  3968. preload_pending = 0;
  3969. preload_wait = 0;
  3970. fetch_workers_cancel_busy();
  3971. s_copy(page_title, title, sizeof(page_title));
  3972. page_loading = 0;
  3973. set_status(title, 1, 0);
  3974. ngui_invalidate(&ui);
  3975. }
  3976. static int decode_direct_image(const unsigned char *data, unsigned int len,
  3977. unsigned int node)
  3978. {
  3979. if (image_count >= BR_MAX_IMAGES)
  3980. return -1;
  3981. if (decode_image_data(data, len, &images[0], 0, 0, 0, 0) != 0)
  3982. return -1;
  3983. doc.nodes[node].img_index = 0;
  3984. image_count = 1;
  3985. return 0;
  3986. }
  3987. static int ancestor_is(unsigned int node, unsigned int tag)
  3988. {
  3989. unsigned int p = doc.nodes[node].parent;
  3990. while (p) {
  3991. if (doc.nodes[p].tag == tag)
  3992. return 1;
  3993. p = doc.nodes[p].parent;
  3994. }
  3995. return 0;
  3996. }
  3997. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  3998. * parallel but parsed in document order, so the cascade is unchanged. */
  3999. static int load_stylesheets(void)
  4000. {
  4001. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  4002. static unsigned char remote[BR_MAX_SHEETS];
  4003. struct fetch_worker *slot[BR_MAX_SHEETS];
  4004. unsigned int i, n = 0, next = 0, k;
  4005. char err[64];
  4006. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  4007. struct br_node *nd = &doc.nodes[i];
  4008. const char *rel, *href;
  4009. char url[BR_URL_MAX];
  4010. int dup = 0;
  4011. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  4012. continue;
  4013. rel = br_rel(&doc, i);
  4014. if (!contains_ci(rel, "stylesheet"))
  4015. continue;
  4016. href = br_href(&doc, i);
  4017. if (!href[0])
  4018. continue;
  4019. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  4020. continue;
  4021. for (k = 0; k < n; k++)
  4022. if (s_eq(urls[k], url)) {
  4023. dup = 1;
  4024. break;
  4025. }
  4026. if (dup)
  4027. continue;
  4028. s_copy(urls[n], url, BR_URL_MAX);
  4029. remote[n] = url[0] != '/' && !css_cache_has(url);
  4030. n++;
  4031. }
  4032. for (i = 0; i < BR_MAX_SHEETS; i++)
  4033. slot[i] = 0;
  4034. /* Start as many remote sheets as there are free workers. */
  4035. for (; next < n; next++) {
  4036. struct fetch_worker *w;
  4037. if (!remote[next])
  4038. continue;
  4039. w = fetch_worker_alloc();
  4040. if (!w)
  4041. break;
  4042. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  4043. err, sizeof(err)) != 0) {
  4044. fetch_worker_release(w);
  4045. remote[next] = 0;
  4046. continue;
  4047. }
  4048. slot[next] = w;
  4049. }
  4050. for (i = 0; i < n; i++) {
  4051. unsigned char *data = 0;
  4052. unsigned int len = 0;
  4053. int rv;
  4054. if (!remote[i]) {
  4055. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  4056. if (rv == FETCH_ABORT) {
  4057. fetch_workers_stop_all();
  4058. return FETCH_ABORT;
  4059. }
  4060. if (rv != 0 || !len)
  4061. continue;
  4062. } else {
  4063. struct fetch_worker *w = slot[i];
  4064. int tr = 0;
  4065. if (!w) {
  4066. w = fetch_worker_alloc();
  4067. if (!w) {
  4068. rv = -1;
  4069. goto css_failed;
  4070. }
  4071. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  4072. 0, 0, 0, 0, err,
  4073. sizeof(err)) != 0) {
  4074. fetch_worker_release(w);
  4075. remote[i] = 0;
  4076. if (i == next)
  4077. next++;
  4078. continue;
  4079. }
  4080. slot[i] = w;
  4081. if (i == next)
  4082. next++;
  4083. }
  4084. rv = fetch_worker_wait(w, err, sizeof(err));
  4085. if (rv == FETCH_ABORT) {
  4086. fetch_workers_stop_all();
  4087. return FETCH_ABORT;
  4088. }
  4089. if (rv == 0)
  4090. rv = fetch_worker_read_body(w, image_io_buf,
  4091. BR_CSS_MAX,
  4092. image_io_buf + BR_CSS_MAX,
  4093. BR_CSS_COMP_MAX, &tr,
  4094. err, sizeof(err));
  4095. else
  4096. rv = -1;
  4097. fetch_worker_release(w);
  4098. slot[i] = 0;
  4099. /* Refill the worker window before parsing this sheet. */
  4100. for (; next < n; next++) {
  4101. struct fetch_worker *nw;
  4102. if (!remote[next])
  4103. continue;
  4104. nw = fetch_worker_alloc();
  4105. if (!nw)
  4106. break;
  4107. if (fetch_worker_submit(nw, urls[next],
  4108. BR_CSS_MAX, 0, 0, 0, 0,
  4109. err, sizeof(err)) != 0) {
  4110. fetch_worker_release(nw);
  4111. remote[next] = 0;
  4112. continue;
  4113. }
  4114. slot[next] = nw;
  4115. }
  4116. css_failed:
  4117. if (rv <= 0) {
  4118. /* One synchronous retry: a dropped sheet leaves the
  4119. * whole page unstyled (seen intermittently on
  4120. * arstechnica's CDN). */
  4121. u_puts("[css] retry ");
  4122. u_puts(urls[i]);
  4123. u_puts(": ");
  4124. u_puts(err[0] ? err : "no worker/empty body");
  4125. u_putc('\n');
  4126. err[0] = '\0';
  4127. rv = fetch_css(urls[i], &data, &len, err,
  4128. sizeof(err));
  4129. if (rv == FETCH_ABORT) {
  4130. fetch_workers_stop_all();
  4131. return FETCH_ABORT;
  4132. }
  4133. if (rv != 0 || !len) {
  4134. u_puts("[css] failed: ");
  4135. u_puts(err);
  4136. u_putc('\n');
  4137. continue;
  4138. }
  4139. } else {
  4140. len = (unsigned int)rv;
  4141. data = image_io_buf;
  4142. css_cache_put(urls[i], data, len);
  4143. }
  4144. }
  4145. if (len) {
  4146. br_set_font_base(urls[i]);
  4147. br_parse_css_text(&doc, (const char *)data, len);
  4148. }
  4149. }
  4150. br_set_font_base(page_url);
  4151. br_parse_inline_css(&doc);
  4152. load_font_faces();
  4153. br_reset_styles(&doc);
  4154. layout_valid = 0;
  4155. return 0;
  4156. }
  4157. static void preload_begin(void)
  4158. {
  4159. preload_active = 1;
  4160. preload_pending = 0;
  4161. preload_wait = 1;
  4162. preload_max_jobs = FETCH_WORKERS;
  4163. preload_node = 0;
  4164. preload_loaded = 0;
  4165. preload_scroll = 0;
  4166. img_stat_start = u_ticks_ms();
  4167. img_stat_wall = 0;
  4168. img_stat_net = img_stat_open = img_stat_first = 0;
  4169. img_stat_io = img_stat_dec = img_stat_scale = 0;
  4170. img_stat_paint = img_stat_reflow = 0;
  4171. img_stat_bytes = 0;
  4172. img_stat_n = 0;
  4173. img_stat_log_len = 0;
  4174. if (img_stat_log[0])
  4175. img_stat_log[0] = '\0';
  4176. img_repaint_ms = 0;
  4177. img_repaint_pending = 0;
  4178. }
  4179. /* Styles are computed top-down during layout, but images inside a hidden
  4180. * menu/carousel are never visited and keep img_top == 0. Without this check
  4181. * the preloader walks the DOM in node order and spends the whole image
  4182. * budget on logos and off-canvas thumbnails the reader cannot see. */
  4183. static struct br_style base_style(void);
  4184. static int node_hidden(unsigned int node)
  4185. {
  4186. unsigned int path[32], n = 0, p = node, i;
  4187. struct br_style st, parent;
  4188. while (p && n < sizeof(path) / sizeof(path[0])) {
  4189. path[n++] = p;
  4190. p = doc.nodes[p].parent;
  4191. }
  4192. /* Node 0 is the <html> element when the page starts with one: it
  4193. * is an ancestor too. Styles are cached per node, so the chain
  4194. * must start from the same base as style_for_node(); seeding it
  4195. * with a zeroed style left <body> cached with black text and no
  4196. * line-height once an image job ran (docs.cloudron.io). */
  4197. if (!p && n && n < sizeof(path) / sizeof(path[0]) &&
  4198. doc.nodes[0].type == BR_NODE_ELEM &&
  4199. doc.nodes[0].tag == BR_TAG_HTML &&
  4200. !(doc.nodes[path[n - 1]].flags & BR_NODE_DETACHED))
  4201. path[n++] = 0;
  4202. parent = base_style();
  4203. for (i = n; i > 0; i--) {
  4204. br_style_for(&doc, path[i - 1], &parent, &st);
  4205. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  4206. st.opacity_hidden)
  4207. return 1;
  4208. parent = st;
  4209. }
  4210. return 0;
  4211. }
  4212. static struct br_style base_style(void);
  4213. static int style_width_px(const struct br_style *st, int base);
  4214. static int style_height_px(const struct br_style *st, int base);
  4215. static void style_for_node(unsigned int node, struct br_style *out)
  4216. {
  4217. unsigned int p = doc.nodes[node].parent;
  4218. struct br_style parent;
  4219. /* Parent index 0 is ambiguous: it is the <html> element when the page
  4220. * starts with one (see root_style()), but also the parent field of a
  4221. * detached subtree root. */
  4222. if (p || (node != 0 && doc.nodes[0].type == BR_NODE_ELEM &&
  4223. doc.nodes[0].tag == BR_TAG_HTML &&
  4224. !(doc.nodes[node].flags & BR_NODE_DETACHED))) {
  4225. style_for_node(p, &parent);
  4226. br_style_for(&doc, node, &parent, out);
  4227. } else {
  4228. parent = base_style();
  4229. br_style_for(&doc, node, &parent, out);
  4230. }
  4231. }
  4232. /* ---- parallel image preloading ---- *
  4233. *
  4234. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  4235. * preload_step() only starts jobs and harvests completed ones; the browser
  4236. * main loop keeps drawing between calls, instead of blocking on one fetch.
  4237. */
  4238. static int preload_active_jobs(void)
  4239. {
  4240. int i, n = 0;
  4241. for (i = 0; i < FETCH_WORKERS; i++)
  4242. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  4243. n++;
  4244. return n;
  4245. }
  4246. static void preload_job_error(struct fetch_worker *w)
  4247. {
  4248. if (w->node < doc.nnode) {
  4249. if (w->bg)
  4250. doc.nodes[w->node].bg_img_index = -2;
  4251. else
  4252. doc.nodes[w->node].img_index = -2;
  4253. image_repaint();
  4254. }
  4255. }
  4256. /* Is the image's box anywhere near the visible page? A decode below the
  4257. * fold changes the layout (scroll extent) but not a single on-screen pixel,
  4258. * so it does not need a repaint. top/h come from the last layout; treat an
  4259. * unknown box as visible to stay safe. */
  4260. static int image_preload_visible(unsigned int node, int bg)
  4261. {
  4262. int top, h, scroll;
  4263. if (node >= BR_MAX_NODES || node >= doc.nnode || page_rect.h <= 0)
  4264. return 1;
  4265. if (bg) {
  4266. top = (int)block_top[node];
  4267. h = (int)block_h[node];
  4268. } else {
  4269. top = (int)img_top[node];
  4270. h = (int)img_h[node];
  4271. }
  4272. if (!top && !h)
  4273. return 1;
  4274. scroll = (int)page_scroll.offset;
  4275. if (top > scroll + page_rect.h + 160)
  4276. return 0;
  4277. if (top + h + 160 < scroll)
  4278. return 0;
  4279. return 1;
  4280. }
  4281. /* Upper bounds for the bitmap an <img> will paint. Zero means "unbounded";
  4282. * decode_image_data applies one scale to both axes so the aspect ratio is
  4283. * preserved. This is what keeps a 1200x800 photo that CSS paints at 400 px
  4284. * from being decoded and box-filtered to the 1000 px layout cap first. */
  4285. static void image_fit_size(unsigned int node, int *out_w, int *out_h)
  4286. {
  4287. struct br_style st;
  4288. struct br_node *nd;
  4289. unsigned int p;
  4290. int cw, w = 0, h = 0;
  4291. *out_w = *out_h = 0;
  4292. if (node >= doc.nnode)
  4293. return;
  4294. nd = &doc.nodes[node];
  4295. style_for_node(node, &st);
  4296. cw = page_rect.w > 24 ? page_rect.w - 24 : 0;
  4297. p = doc.nodes[node].parent;
  4298. if (p && p < BR_MAX_NODES && layout_boxes[p].valid &&
  4299. layout_boxes[p].w > 0 && layout_boxes[p].w < cw)
  4300. cw = layout_boxes[p].w;
  4301. if (st.width_kind)
  4302. w = style_width_px(&st, cw);
  4303. else if (nd->width_attr)
  4304. w = nd->width_pct ? cw * (int)nd->width_attr / 100 :
  4305. (int)nd->width_attr;
  4306. if (st.height_kind)
  4307. h = style_height_px(&st, cw);
  4308. else if (nd->height_attr)
  4309. h = nd->height_pct ? cw * (int)nd->height_attr / 100 :
  4310. (int)nd->height_attr;
  4311. if (st.max_width_kind) {
  4312. int mw = st.max_width_kind == 3 ?
  4313. cw * st.max_width_calc_pct / 100 +
  4314. st.max_width_calc_px :
  4315. st.max_width_kind == 2 ?
  4316. cw * (int)st.max_width / 100 :
  4317. (int)st.max_width;
  4318. if (mw > 0 && (w == 0 || w > mw))
  4319. w = mw;
  4320. }
  4321. if (st.max_height_kind) {
  4322. int mh = st.max_height_kind == 3 ?
  4323. cw * st.max_height_calc_pct / 100 +
  4324. st.max_height_calc_px :
  4325. st.max_height_kind == 2 ?
  4326. cw * (int)st.max_height / 100 :
  4327. (int)st.max_height;
  4328. if (mh > 0 && (h == 0 || h > mh))
  4329. h = mh;
  4330. }
  4331. if (w > BR_IMG_LAYOUT_W)
  4332. w = BR_IMG_LAYOUT_W;
  4333. if (h > 4096)
  4334. h = 4096;
  4335. if (w < 0)
  4336. w = 0;
  4337. if (h < 0)
  4338. h = 0;
  4339. *out_w = w;
  4340. *out_h = h;
  4341. }
  4342. static void preload_accept_image(unsigned int node, int bg, const char *url)
  4343. {
  4344. /* An <img> bitmap only depends on its URL, so the next <img> with the
  4345. * same source reuses it (heise repeats one comment icon 85 times).
  4346. * Backgrounds are scaled to their box and are not shared. */
  4347. images[image_count].url_hash =
  4348. !bg && url ? script_cache_hash(url) | 1u : 0;
  4349. if (bg)
  4350. doc.nodes[node].bg_img_index = (short)image_count;
  4351. else
  4352. doc.nodes[node].img_index = (short)image_count;
  4353. image_count++;
  4354. preload_loaded++;
  4355. /* A background bitmap never changes its box, so keep the (expensive)
  4356. * measured layout and only repaint the pixels. */
  4357. if (bg)
  4358. page_cache_valid = 0;
  4359. else
  4360. layout_valid = 0;
  4361. if (image_preload_visible(node, bg))
  4362. image_repaint();
  4363. }
  4364. /* Install a bitmap decoded by the fetch helper. The helper already applied
  4365. * the display bounds (and the JPEG reduced IDCT), so this is a read + copy
  4366. * on the UI thread instead of a decode. */
  4367. static int preload_store_helper(unsigned int node, int bg,
  4368. unsigned char *px, unsigned int pxlen,
  4369. unsigned int dw, unsigned int dh,
  4370. int alpha, unsigned int nw, unsigned int nh,
  4371. const char *url)
  4372. {
  4373. struct br_image *bi;
  4374. unsigned int npx;
  4375. if (image_count >= BR_MAX_IMAGES || !px || !dw || !dh ||
  4376. dw > 4096 || dh > 4096) {
  4377. free(px);
  4378. return -1;
  4379. }
  4380. npx = dw * dh;
  4381. if (image_pixels + npx > BR_IMG_PIXEL_BUDGET ||
  4382. pxlen < npx * 2u + (alpha ? npx : 0)) {
  4383. free(px);
  4384. return -1;
  4385. }
  4386. bi = &images[image_count];
  4387. bi->img.format = 0;
  4388. bi->img.w = dw;
  4389. bi->img.h = dh;
  4390. bi->img.px = (unsigned short *)px;
  4391. bi->img.alpha = alpha ? px + npx * 2u : 0;
  4392. bi->img.flags = 0;
  4393. bi->native_w = nw ? (int)nw : (int)dw;
  4394. bi->native_h = nh ? (int)nh : (int)dh;
  4395. bi->state = 1;
  4396. image_pixels += npx;
  4397. preload_accept_image(node, bg, url);
  4398. return 0;
  4399. }
  4400. static void preload_decode(unsigned int node, int bg,
  4401. const unsigned char *data, unsigned int len,
  4402. const char *url)
  4403. {
  4404. int fit_w = 0, fit_h = 0;
  4405. if (image_count >= BR_MAX_IMAGES) {
  4406. if (bg)
  4407. doc.nodes[node].bg_img_index = -2;
  4408. else
  4409. doc.nodes[node].img_index = -2;
  4410. return;
  4411. }
  4412. if (!bg)
  4413. image_fit_size(node, &fit_w, &fit_h);
  4414. if (decode_image_data(data, len, &images[image_count],
  4415. bg && node < BR_MAX_NODES &&
  4416. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  4417. bg && node < BR_MAX_NODES &&
  4418. layout_boxes[node].valid ? layout_boxes[node].h : 0,
  4419. fit_w, fit_h) == 0) {
  4420. preload_accept_image(node, bg, url);
  4421. } else {
  4422. if (bg)
  4423. doc.nodes[node].bg_img_index = -2;
  4424. else
  4425. doc.nodes[node].img_index = -2;
  4426. layout_valid = 0;
  4427. }
  4428. if (image_preload_visible(node, bg))
  4429. image_repaint();
  4430. }
  4431. /* ---- data: URLs ----
  4432. *
  4433. * `data:[<type>][;base64],<payload>` decoded to bytes from the page heap
  4434. * (the caller frees them). The payload is percent-decoded, then base64-
  4435. * decoded when the header says so. Infima's menu chevron and many icon
  4436. * fonts' fallbacks are inline SVGs written this way. */
  4437. static int b64_val(int c)
  4438. {
  4439. if (c >= 'A' && c <= 'Z') return c - 'A';
  4440. if (c >= 'a' && c <= 'z') return c - 'a' + 26;
  4441. if (c >= '0' && c <= '9') return c - '0' + 52;
  4442. if (c == '+' || c == '-') return 62;
  4443. if (c == '/' || c == '_') return 63;
  4444. return -1;
  4445. }
  4446. static int hex_val(int c)
  4447. {
  4448. if (c >= '0' && c <= '9') return c - '0';
  4449. c |= 32;
  4450. if (c >= 'a' && c <= 'f') return c - 'a' + 10;
  4451. return -1;
  4452. }
  4453. static int data_url_decode(const char *url, unsigned char **out,
  4454. unsigned int *out_len)
  4455. {
  4456. const char *comma, *p;
  4457. unsigned int n = 0, len, i;
  4458. unsigned char *buf;
  4459. int base64 = 0;
  4460. *out = 0;
  4461. *out_len = 0;
  4462. if (!starts_with(url, "data:"))
  4463. return -1;
  4464. comma = url + 5;
  4465. while (*comma && *comma != ',')
  4466. comma++;
  4467. if (!*comma)
  4468. return -1;
  4469. for (p = url + 5; p + 7 <= comma; p++)
  4470. if (!strncmp(p, ";base64", 7))
  4471. base64 = 1;
  4472. len = s_len(comma + 1);
  4473. buf = (unsigned char *)malloc(len + 1);
  4474. if (!buf)
  4475. return -1;
  4476. for (i = 0, p = comma + 1; i < len; i++) {
  4477. int c = (unsigned char)p[i];
  4478. if (c == '%' && i + 2 < len &&
  4479. hex_val(p[i + 1]) >= 0 && hex_val(p[i + 2]) >= 0) {
  4480. c = hex_val(p[i + 1]) * 16 + hex_val(p[i + 2]);
  4481. i += 2;
  4482. }
  4483. buf[n++] = (unsigned char)c;
  4484. }
  4485. if (base64) {
  4486. unsigned int acc = 0, o = 0;
  4487. int bits = 0;
  4488. for (i = 0; i < n; i++) {
  4489. int v = b64_val(buf[i]);
  4490. if (v < 0)
  4491. continue; /* padding, whitespace */
  4492. acc = (acc << 6) | (unsigned int)v;
  4493. bits += 6;
  4494. if (bits >= 8) {
  4495. bits -= 8;
  4496. buf[o++] = (unsigned char)(acc >> bits);
  4497. }
  4498. }
  4499. n = o;
  4500. }
  4501. buf[n] = 0;
  4502. *out = buf;
  4503. *out_len = n;
  4504. return 0;
  4505. }
  4506. static unsigned int data_img_key(const char *url, int w, int h)
  4507. {
  4508. return (script_cache_hash(url) ^ ((unsigned int)w * 2654435761u) ^
  4509. ((unsigned int)h * 40503u)) | 1u;
  4510. }
  4511. /* The image index of a data: URL decoded for a w x h box (an SVG is
  4512. * rasterized at that size), decoding it on first use; -1 on failure.
  4513. * Decoded bitmaps are found again through url_hash, which is distinct
  4514. * from the <img> sharing hash because it mixes in the size. */
  4515. static int data_url_image(const char *url, int w, int h)
  4516. {
  4517. unsigned int key, len;
  4518. unsigned char *data;
  4519. int i;
  4520. if (!starts_with(url, "data:") || w <= 0 || h <= 0)
  4521. return -1;
  4522. key = data_img_key(url, w, h);
  4523. for (i = 0; i < image_count; i++)
  4524. if (images[i].state == 1 && images[i].url_hash == key)
  4525. return i;
  4526. for (i = 0; i < data_img_nfail; i++)
  4527. if (data_img_fail[i] == key)
  4528. return -1;
  4529. if (image_count < BR_MAX_IMAGES &&
  4530. data_url_decode(url, &data, &len) == 0) {
  4531. int r = decode_image_data(data, len, &images[image_count],
  4532. w, h, w, h);
  4533. free(data);
  4534. if (r == 0) {
  4535. images[image_count].url_hash = key;
  4536. return image_count++;
  4537. }
  4538. }
  4539. if (data_img_nfail < DATA_IMG_FAIL_MAX)
  4540. data_img_fail[data_img_nfail++] = key;
  4541. return -1;
  4542. }
  4543. /* A local file image bypasses the helpers: count its decode so a page opened
  4544. * from /share or /data still produces the same timing breakdown. */
  4545. static void img_stat_local(int before, unsigned int bytes, unsigned int io_ms)
  4546. {
  4547. img_stat_n++;
  4548. img_stat_bytes += bytes;
  4549. img_stat_io += io_ms;
  4550. if (image_count > before) {
  4551. struct br_image *bi = &images[image_count - 1];
  4552. img_stat_dec += img_last_dec_ms;
  4553. img_stat_scale += img_last_scale_ms;
  4554. if (img_stat_log_len + 100 < sizeof(img_stat_log)) {
  4555. unsigned int n = img_stat_log_len;
  4556. s_append(img_stat_log, &n, "local ", sizeof(img_stat_log));
  4557. s_append_dec(img_stat_log, &n, bytes,
  4558. sizeof(img_stat_log));
  4559. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4560. s_append_dec(img_stat_log, &n, img_last_dec_ms,
  4561. sizeof(img_stat_log));
  4562. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4563. s_append_dec(img_stat_log, &n, img_last_scale_ms,
  4564. sizeof(img_stat_log));
  4565. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4566. s_append_dec(img_stat_log, &n,
  4567. (unsigned int)bi->native_w,
  4568. sizeof(img_stat_log));
  4569. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4570. s_append_dec(img_stat_log, &n,
  4571. (unsigned int)bi->native_h,
  4572. sizeof(img_stat_log));
  4573. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4574. s_append_dec(img_stat_log, &n, bi->img.w,
  4575. sizeof(img_stat_log));
  4576. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4577. s_append_dec(img_stat_log, &n, bi->img.h,
  4578. sizeof(img_stat_log));
  4579. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4580. s_append_dec(img_stat_log, &n,
  4581. bi->img.alpha ? 1u : 0u,
  4582. sizeof(img_stat_log));
  4583. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4584. img_stat_log_len = n;
  4585. }
  4586. }
  4587. }
  4588. /* Harvest one completed worker. Returns 1 when a job was finished. */
  4589. static int preload_finish_worker(struct fetch_worker *w)
  4590. {
  4591. char err[64];
  4592. int rv, tr = 0;
  4593. unsigned int t0, io_ms;
  4594. int before;
  4595. int used_px = 0;
  4596. rv = fetch_worker_poll(w, err, sizeof(err));
  4597. if (rv < 0) {
  4598. /* A helper from an older pack does not understand the image
  4599. * decode request; retry once without it and decode in-process. */
  4600. if (w->image_job && w->dec_w && !w->dec_retried &&
  4601. fetch_worker_submit_req(w, w->url, BR_IMG_FILE_MAX,
  4602. 0, 0, 0, 0, w->node, w->bg,
  4603. 0, 0, err, sizeof(err)) == 0) {
  4604. w->image_job = 1;
  4605. w->dec_retried = 1;
  4606. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4607. return 0;
  4608. }
  4609. preload_job_error(w);
  4610. if (img_stat_log_len + 64 < sizeof(img_stat_log)) {
  4611. unsigned int n = img_stat_log_len;
  4612. char u[48];
  4613. s_copy(u, w->url, sizeof(u));
  4614. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4615. s_append(img_stat_log, &n, " error\n",
  4616. sizeof(img_stat_log));
  4617. img_stat_log_len = n;
  4618. }
  4619. img_stat_n++;
  4620. fetch_worker_release(w);
  4621. return 1;
  4622. }
  4623. if (rv == 0)
  4624. return 0;
  4625. t0 = u_ticks_ms();
  4626. rv = -1;
  4627. before = image_count;
  4628. if (w->m.px_len && !w->m.dec_err && w->m.dw && w->m.dh &&
  4629. w->m.px_len <= 8u * 1024u * 1024u) {
  4630. unsigned char *px = (unsigned char *)malloc(w->m.px_len);
  4631. int pr = -1;
  4632. if (px)
  4633. pr = u_syscall3(SYS_READ_FILE, (int)w->px, (int)px,
  4634. (int)w->m.px_len);
  4635. if (pr == (int)w->m.px_len) {
  4636. if (preload_store_helper(w->node, w->bg, px,
  4637. w->m.px_len, w->m.dw,
  4638. w->m.dh, (int)w->m.alpha,
  4639. w->m.nw, w->m.nh,
  4640. w->url) == 0) {
  4641. rv = (int)w->m.len;
  4642. img_last_dec_ms = w->m.dec_ms;
  4643. img_last_scale_ms = 0;
  4644. used_px = 1;
  4645. } else {
  4646. px = 0; /* the helper freed it */
  4647. }
  4648. }
  4649. if (px && !(pr == (int)w->m.px_len))
  4650. free(px);
  4651. }
  4652. io_ms = u_ticks_ms() - t0;
  4653. if (rv < 0) {
  4654. t0 = u_ticks_ms();
  4655. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  4656. image_comp_buf, BR_IMG_FILE_MAX,
  4657. &tr, err, sizeof(err));
  4658. io_ms += u_ticks_ms() - t0;
  4659. before = image_count;
  4660. if (rv >= 0)
  4661. preload_decode(w->node, w->bg, image_file_buf,
  4662. (unsigned int)rv, w->url);
  4663. else
  4664. preload_job_error(w);
  4665. }
  4666. img_stat_n++;
  4667. img_stat_net += w->m.total_ms;
  4668. img_stat_open += w->m.open_ms;
  4669. img_stat_first += w->m.first_ms;
  4670. img_stat_io += io_ms;
  4671. img_stat_bytes += rv > 0 ? (unsigned int)rv : 0;
  4672. img_stat_dec += w->m.dec_ms;
  4673. if (rv >= 0 && !used_px) {
  4674. img_stat_dec += img_last_dec_ms;
  4675. img_stat_scale += img_last_scale_ms;
  4676. }
  4677. if (img_stat_log_len + 160 < sizeof(img_stat_log)) {
  4678. unsigned int n = img_stat_log_len;
  4679. char u[48];
  4680. s_copy(u, w->url, sizeof(u));
  4681. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4682. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4683. s_append_dec(img_stat_log, &n,
  4684. rv > 0 ? (unsigned int)rv : 0,
  4685. sizeof(img_stat_log));
  4686. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4687. s_append_dec(img_stat_log, &n, w->m.open_ms,
  4688. sizeof(img_stat_log));
  4689. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4690. s_append_dec(img_stat_log, &n, w->m.first_ms,
  4691. sizeof(img_stat_log));
  4692. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4693. s_append_dec(img_stat_log, &n, w->m.total_ms,
  4694. sizeof(img_stat_log));
  4695. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4696. s_append_dec(img_stat_log, &n, io_ms, sizeof(img_stat_log));
  4697. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4698. s_append_dec(img_stat_log, &n,
  4699. rv >= 0 ? img_last_dec_ms : 0,
  4700. sizeof(img_stat_log));
  4701. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4702. s_append_dec(img_stat_log, &n,
  4703. rv >= 0 ? img_last_scale_ms : 0,
  4704. sizeof(img_stat_log));
  4705. if (image_count > before) {
  4706. struct br_image *bi = &images[image_count - 1];
  4707. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4708. s_append_dec(img_stat_log, &n,
  4709. (unsigned int)bi->native_w,
  4710. sizeof(img_stat_log));
  4711. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4712. s_append_dec(img_stat_log, &n,
  4713. (unsigned int)bi->native_h,
  4714. sizeof(img_stat_log));
  4715. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4716. s_append_dec(img_stat_log, &n, bi->img.w,
  4717. sizeof(img_stat_log));
  4718. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4719. s_append_dec(img_stat_log, &n, bi->img.h,
  4720. sizeof(img_stat_log));
  4721. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4722. s_append_dec(img_stat_log, &n,
  4723. bi->img.alpha ? 1u : 0u,
  4724. sizeof(img_stat_log));
  4725. }
  4726. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4727. img_stat_log_len = n;
  4728. }
  4729. fetch_worker_release(w);
  4730. return 1;
  4731. }
  4732. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  4733. * the number of jobs started. */
  4734. static int preload_fill_jobs(void)
  4735. {
  4736. int started = 0;
  4737. char err[64];
  4738. while (preload_active && preload_node < doc.nnode) {
  4739. unsigned int i = preload_node;
  4740. struct br_node *nd = &doc.nodes[i];
  4741. const char *src;
  4742. char url[BR_URL_MAX];
  4743. struct fetch_worker *w;
  4744. if (preload_active_jobs() >= preload_max_jobs)
  4745. break;
  4746. if (nd->type != BR_NODE_ELEM) {
  4747. preload_node++;
  4748. continue;
  4749. }
  4750. if (nd->tag != BR_TAG_IMG) {
  4751. if (nd->bg_img_index == -1) {
  4752. struct br_style bs;
  4753. style_for_node(i, &bs);
  4754. if (bs.display != BR_DISPLAY_NONE &&
  4755. !bs.vis_hidden && bs.bg_image) {
  4756. const char *bsrc =
  4757. br_bg_image_url(bs.bg_image - 1);
  4758. /* Lazy like <img>: a background box
  4759. * below the viewport (or not laid
  4760. * out yet) waits for the next scan. */
  4761. if (bsrc[0] &&
  4762. (!layout_boxes[i].valid ||
  4763. block_top[i] >
  4764. (unsigned int)(page_scroll.offset +
  4765. page_rect.h + 160))) {
  4766. preload_pending = 1;
  4767. preload_node++;
  4768. continue;
  4769. }
  4770. if (starts_with(bsrc, "data:")) {
  4771. /* Inline image: decode now,
  4772. * no fetch helper. */
  4773. unsigned char *data;
  4774. unsigned int len;
  4775. preload_node = i + 1;
  4776. if (data_url_decode(bsrc, &data,
  4777. &len) == 0) {
  4778. preload_decode(i, 1, data,
  4779. len, 0);
  4780. free(data);
  4781. } else {
  4782. nd->bg_img_index = -2;
  4783. }
  4784. continue;
  4785. }
  4786. if (bsrc[0] &&
  4787. resolve_link(page_url, bsrc, url,
  4788. sizeof(url)) == 0) {
  4789. if (image_count +
  4790. preload_active_jobs() >=
  4791. BR_MAX_IMAGES) {
  4792. preload_node = doc.nnode;
  4793. break;
  4794. }
  4795. if (url[0] == '/') {
  4796. unsigned char *data = 0;
  4797. unsigned int len = 0;
  4798. unsigned int t0;
  4799. int before;
  4800. preload_node = i + 1;
  4801. before = image_count;
  4802. t0 = u_ticks_ms();
  4803. if (fetch_image(url,
  4804. BR_IMG_FILE_MAX,
  4805. &data, &len,
  4806. err,
  4807. sizeof(err)) == 0) {
  4808. preload_decode(i, 1, data, len, 0);
  4809. img_stat_local(before, len,
  4810. u_ticks_ms() - t0);
  4811. } else {
  4812. nd->bg_img_index = -2;
  4813. }
  4814. continue;
  4815. }
  4816. w = fetch_worker_alloc();
  4817. if (!w)
  4818. return started;
  4819. preload_node = i + 1;
  4820. if (fetch_worker_submit(w, url,
  4821. BR_IMG_FILE_MAX,
  4822. 0, 0, i, 1,
  4823. err,
  4824. sizeof(err)) != 0) {
  4825. nd->bg_img_index = -2;
  4826. fetch_worker_release(w);
  4827. continue;
  4828. }
  4829. w->image_job = 1;
  4830. w->deadline = u_ticks_ms() +
  4831. BR_IMG_JOB_TIMEOUT_MS;
  4832. /* in flight: rescans skip it */
  4833. nd->bg_img_index = -3;
  4834. started++;
  4835. continue;
  4836. }
  4837. }
  4838. nd->bg_img_index = -2;
  4839. }
  4840. preload_node++;
  4841. continue;
  4842. }
  4843. if (nd->img_index != -1) {
  4844. preload_node++;
  4845. continue;
  4846. }
  4847. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  4848. preload_node++;
  4849. continue;
  4850. }
  4851. src = br_src(&doc, i);
  4852. if (starts_with(src, "data:")) {
  4853. unsigned char *data;
  4854. unsigned int len;
  4855. preload_node = i + 1;
  4856. if (data_url_decode(src, &data, &len) == 0) {
  4857. preload_decode(i, 0, data, len, 0);
  4858. free(data);
  4859. } else {
  4860. doc.nodes[i].img_index = -2;
  4861. }
  4862. continue;
  4863. }
  4864. if (!src[0]) {
  4865. preload_node++;
  4866. continue;
  4867. }
  4868. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  4869. preload_node++;
  4870. continue;
  4871. }
  4872. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  4873. preload_node = doc.nnode;
  4874. break;
  4875. }
  4876. /* Do not stop at the first below-fold image: DOM order is
  4877. * not visual order, and a footer/ad image early in the DOM
  4878. * used to hide every later article image from the loader. */
  4879. if (img_top[i] >
  4880. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  4881. preload_pending = 1;
  4882. preload_node++;
  4883. continue;
  4884. }
  4885. {
  4886. unsigned int uh = script_cache_hash(url) | 1u;
  4887. int k;
  4888. for (k = 0; k < image_count; k++)
  4889. if (images[k].state == 1 &&
  4890. images[k].url_hash == uh)
  4891. break;
  4892. if (k < image_count) {
  4893. nd->img_index = (short)k;
  4894. layout_valid = 0;
  4895. preload_node = i + 1;
  4896. image_repaint();
  4897. continue;
  4898. }
  4899. }
  4900. if (url[0] == '/') {
  4901. unsigned char *data = 0;
  4902. unsigned int len = 0;
  4903. unsigned int t0;
  4904. int before;
  4905. preload_node = i + 1;
  4906. before = image_count;
  4907. t0 = u_ticks_ms();
  4908. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  4909. err, sizeof(err)) == 0) {
  4910. preload_decode(i, 0, data, len, url);
  4911. img_stat_local(before, len, u_ticks_ms() - t0);
  4912. } else {
  4913. nd->img_index = -2;
  4914. }
  4915. continue;
  4916. }
  4917. w = fetch_worker_alloc();
  4918. if (!w)
  4919. return started;
  4920. preload_node = i + 1;
  4921. {
  4922. char msg[64];
  4923. unsigned int n = 0;
  4924. s_append(msg, &n, "Loading images ", sizeof(msg));
  4925. s_append_dec(msg, &n,
  4926. (unsigned int)preload_loaded + 1,
  4927. sizeof(msg));
  4928. s_append(msg, &n, "...", sizeof(msg));
  4929. set_status_quiet(msg);
  4930. image_repaint();
  4931. }
  4932. {
  4933. int fit_w = 0, fit_h = 0;
  4934. image_fit_size(i, &fit_w, &fit_h);
  4935. if (!fit_w)
  4936. fit_w = BR_IMG_LAYOUT_W;
  4937. if (fetch_worker_submit_image(w, url, BR_IMG_FILE_MAX,
  4938. i, 0,
  4939. (unsigned int)fit_w,
  4940. (unsigned int)fit_h,
  4941. err, sizeof(err)) != 0) {
  4942. nd->img_index = -2;
  4943. fetch_worker_release(w);
  4944. continue;
  4945. }
  4946. }
  4947. w->image_job = 1;
  4948. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4949. nd->img_index = -3; /* in flight: rescans skip it */
  4950. started++;
  4951. }
  4952. return started;
  4953. }
  4954. /* Report where the image batch spent its time: status bar for the headline,
  4955. * /share/IMGSTAT for the per-image breakdown (cat it from a terminal). */
  4956. static void img_stats_report(void)
  4957. {
  4958. char msg[80];
  4959. static char out[BR_IMG_STAT_LOG + 512];
  4960. unsigned int n = 0, o = 0;
  4961. if (!img_stat_n)
  4962. return;
  4963. img_stat_wall = img_stat_start ?
  4964. u_ticks_ms() - img_stat_start : 1;
  4965. if (!img_stat_wall)
  4966. img_stat_wall = 1;
  4967. /* Compact on-screen form; /share/IMGSTAT has the full breakdown. */
  4968. s_append(msg, &n, "img ", sizeof(msg));
  4969. s_append_dec(msg, &n, (unsigned int)img_stat_n, sizeof(msg));
  4970. s_append(msg, &n, " ", sizeof(msg));
  4971. s_append_dec(msg, &n, img_stat_wall, sizeof(msg));
  4972. s_append(msg, &n, "ms net ", sizeof(msg));
  4973. s_append_dec(msg, &n, img_stat_net, sizeof(msg));
  4974. s_append(msg, &n, " dec ", sizeof(msg));
  4975. s_append_dec(msg, &n, img_stat_dec, sizeof(msg));
  4976. s_append(msg, &n, " sc ", sizeof(msg));
  4977. s_append_dec(msg, &n, img_stat_scale, sizeof(msg));
  4978. s_append(msg, &n, " paint ", sizeof(msg));
  4979. s_append_dec(msg, &n, img_stat_paint, sizeof(msg));
  4980. /* Keep the page's phase breakdown and append the image summary when
  4981. * it fits; never hide a JS error or a truncation notice. */
  4982. if (!post_status_error && !contains_ci(post_status_text, "truncated")) {
  4983. unsigned int plen = s_len(post_status_text);
  4984. if (!plen) {
  4985. s_copy(post_status_text, msg, sizeof(post_status_text));
  4986. } else if (plen + s_len(msg) + 4 < sizeof(post_status_text)) {
  4987. unsigned int pn = plen;
  4988. s_append(post_status_text, &pn, " | ",
  4989. sizeof(post_status_text));
  4990. s_append(post_status_text, &pn, msg,
  4991. sizeof(post_status_text));
  4992. } else {
  4993. s_copy(post_status_text, msg, sizeof(post_status_text));
  4994. }
  4995. post_status_ttl = 12000;
  4996. }
  4997. s_append(out, &o, "browser image stats\n", sizeof(out));
  4998. s_append(out, &o, "n=", sizeof(out));
  4999. s_append_dec(out, &o, (unsigned int)img_stat_n, sizeof(out));
  5000. s_append(out, &o, " wall=", sizeof(out));
  5001. s_append_dec(out, &o, img_stat_wall, sizeof(out));
  5002. s_append(out, &o, " net=", sizeof(out));
  5003. s_append_dec(out, &o, img_stat_net, sizeof(out));
  5004. s_append(out, &o, " open=", sizeof(out));
  5005. s_append_dec(out, &o, img_stat_open, sizeof(out));
  5006. s_append(out, &o, " first=", sizeof(out));
  5007. s_append_dec(out, &o, img_stat_first, sizeof(out));
  5008. s_append(out, &o, " io=", sizeof(out));
  5009. s_append_dec(out, &o, img_stat_io, sizeof(out));
  5010. s_append(out, &o, " dec=", sizeof(out));
  5011. s_append_dec(out, &o, img_stat_dec, sizeof(out));
  5012. s_append(out, &o, " scale=", sizeof(out));
  5013. s_append_dec(out, &o, img_stat_scale, sizeof(out));
  5014. s_append(out, &o, " paint=", sizeof(out));
  5015. s_append_dec(out, &o, img_stat_paint, sizeof(out));
  5016. s_append(out, &o, " reflow=", sizeof(out));
  5017. s_append_dec(out, &o, img_stat_reflow, sizeof(out));
  5018. s_append(out, &o, " bytes=", sizeof(out));
  5019. s_append_dec(out, &o, img_stat_bytes, sizeof(out));
  5020. s_append(out, &o, "\nurl bytes open first total io dec scale native bitmap\n",
  5021. sizeof(out));
  5022. s_append(out, &o, img_stat_log, sizeof(out));
  5023. u_syscall3(SYS_WRITE_FILE, (int)"/share/IMGSTAT", (int)out,
  5024. (int)s_len(out));
  5025. }
  5026. static void preload_step(void)
  5027. {
  5028. int i;
  5029. unsigned int t0;
  5030. if (!preload_active)
  5031. return;
  5032. if (cancel_fetch || pending_action) {
  5033. preload_active = 0;
  5034. preload_pending = 0;
  5035. fetch_workers_cancel_busy();
  5036. return;
  5037. }
  5038. preload_fill_jobs();
  5039. /* Decode completed images in a short batch instead of one per pass.
  5040. * A pass used to decode one image and then sleep 10 ms, so a page of
  5041. * small icons trickled in at the decode rate. The budget keeps a
  5042. * single huge JPEG from monopolising the UI while small images
  5043. * finish together. */
  5044. t0 = u_ticks_ms();
  5045. for (i = 0; i < FETCH_WORKERS; i++) {
  5046. if (!fetch_workers[i].busy)
  5047. continue;
  5048. if (preload_finish_worker(&fetch_workers[i]) &&
  5049. u_ticks_ms() - t0 >= BR_IMG_DECODE_BUDGET_MS)
  5050. break;
  5051. }
  5052. if (preload_active && preload_node >= doc.nnode &&
  5053. preload_active_jobs() == 0) {
  5054. preload_active = 0;
  5055. if (preload_pending)
  5056. preload_scroll = page_scroll.offset;
  5057. else
  5058. preload_pending = 0;
  5059. /* Keep the now idle helpers and their connections; a later
  5060. * navigation reuses them. They exit after ten idle seconds,
  5061. * and losing window focus stops them at once. */
  5062. if (img_repaint_pending) {
  5063. img_repaint_pending = 0;
  5064. ngui_invalidate(&ui);
  5065. }
  5066. img_stats_report();
  5067. set_status(post_status_text, post_status_error, post_status_ttl);
  5068. ngui_invalidate(&ui);
  5069. }
  5070. }
  5071. /* Set by navigate() when it turned a typed bare host into https://; the next
  5072. * load_page() consumes it and may retry over http. */
  5073. static int nav_https_upgraded;
  5074. /* Errors that mean "https is not served here" rather than "the site is
  5075. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  5076. static int https_fallback_error(int e)
  5077. {
  5078. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  5079. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  5080. e == UHTTP_ERR_RESET;
  5081. }
  5082. static void history_push(const char *url)
  5083. {
  5084. if (!url || !url[0])
  5085. return;
  5086. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  5087. s_eq(history[hist_pos], url))
  5088. return;
  5089. if (hist_len > 0 && hist_pos + 1 < hist_len)
  5090. hist_len = hist_pos + 1;
  5091. if (hist_len < BR_HISTORY) {
  5092. s_copy(history[hist_len], url, BR_URL_MAX);
  5093. hist_pos = hist_len;
  5094. hist_len++;
  5095. } else {
  5096. int i;
  5097. for (i = 1; i < BR_HISTORY; i++)
  5098. s_copy(history[i - 1], history[i], BR_URL_MAX);
  5099. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  5100. hist_pos = BR_HISTORY - 1;
  5101. }
  5102. }
  5103. static void load_page(const char *url, int local, int push)
  5104. {
  5105. unsigned char *body = 0;
  5106. unsigned int len = 0;
  5107. int truncated = 0;
  5108. struct img_info image_info;
  5109. char ctype[64];
  5110. char final[BR_URL_MAX];
  5111. char err[80];
  5112. const char *detail = 0;
  5113. const char *post = pending_post_is ? pending_post : 0;
  5114. unsigned int post_len = pending_post_len;
  5115. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  5116. /* Phase timings for the status line: where a slow load spends it. */
  5117. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  5118. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  5119. int upgraded = nav_https_upgraded;
  5120. int retried = 0;
  5121. int rv;
  5122. nav_https_upgraded = 0;
  5123. final[0] = '\0';
  5124. pending_post_len = 0;
  5125. pending_post_is = 0;
  5126. cancel_fetch = 0;
  5127. preload_active = 0;
  5128. preload_pending = 0;
  5129. fetch_workers_prepare_nav(url);
  5130. js_browser_stop();
  5131. js_last_status[0] = '\0';
  5132. js_last_error = 0;
  5133. heap_clear();
  5134. image_reset();
  5135. form_reset_state();
  5136. layout_valid = 0;
  5137. page_scroll.offset = 0;
  5138. page_scroll.dragging = 0;
  5139. page_title[0] = '\0';
  5140. page_loading = 1;
  5141. page_is_local = local;
  5142. s_copy(page_url, url, sizeof(page_url));
  5143. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5144. url_in.len = s_len(url_in.text);
  5145. url_in.cursor = url_in.len;
  5146. url_in.scroll = 0;
  5147. ngui_set_focus(&ui, 0);
  5148. if (final[0])
  5149. final[0] = '\0';
  5150. if (push)
  5151. history_push(url);
  5152. set_status("Loading...", 0, 0);
  5153. ngui_invalidate(&ui);
  5154. /* heap_clear() detaches the fonts, so attach them again before the
  5155. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  5156. if (heap_start() != 0) {
  5157. show_error("Out of memory", "Cannot allocate the page buffer");
  5158. return;
  5159. }
  5160. br_parse_plain(&doc, "", 0); /* blank while loading */
  5161. ngui_font_attach(&ui);
  5162. redraw_now();
  5163. browser_rules_alloc();
  5164. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5165. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  5166. &truncated, post, post_len);
  5167. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  5168. fetch_last_error == UHTTP_ERR_DNS) {
  5169. /* A busy previous page can leave the receiver ring full just
  5170. * long enough to lose a DNS reply. Tear the old helpers down
  5171. * and try once more before giving up. */
  5172. retried = 1;
  5173. fetch_workers_stop_all();
  5174. u_sleep_ms(500);
  5175. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5176. sizeof(ctype), final, sizeof(final), err,
  5177. sizeof(err), &truncated, post, post_len);
  5178. }
  5179. if (rv == FETCH_ABORT)
  5180. return;
  5181. t_fetch = u_ticks_ms() - t_start;
  5182. /* Capture the page timing before CSS/script/image fetches overwrite the
  5183. * shared fetch_meta block. */
  5184. if (rv == 0 && !local) {
  5185. page_open_ms = fetch_meta.open_ms;
  5186. page_first_ms = fetch_meta.first_ms;
  5187. page_total_ms = fetch_meta.total_ms;
  5188. }
  5189. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  5190. https_fallback_error(fetch_last_error)) {
  5191. char http_url[BR_URL_MAX];
  5192. unsigned int n = 0;
  5193. s_append(http_url, &n, "http://", sizeof(http_url));
  5194. s_append(http_url, &n, url + 8, sizeof(http_url));
  5195. /* Replace the https entry instead of adding a second one. */
  5196. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  5197. s_eq(history[hist_pos], url))
  5198. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  5199. load_page(http_url, 0, 0);
  5200. return;
  5201. }
  5202. if (rv != 0) {
  5203. detail = err;
  5204. show_error("Cannot load this page", detail);
  5205. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5206. url_in.len = s_len(url_in.text);
  5207. url_in.cursor = url_in.len;
  5208. url_in.scroll = 0;
  5209. return;
  5210. }
  5211. if (!local)
  5212. origin_cache_learn(url, final[0] ? final : url);
  5213. page_is_local = local;
  5214. if (final[0]) {
  5215. s_copy(page_url, final, sizeof(page_url));
  5216. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5217. url_in.len = s_len(url_in.text);
  5218. url_in.cursor = url_in.len;
  5219. url_in.scroll = 0;
  5220. }
  5221. if (contains_ci(ctype, "text/plain")) {
  5222. br_parse_plain(&doc, (const char *)body, len);
  5223. } else if (contains_ci(ctype, "image/") ||
  5224. (!contains_ci(ctype, "text/html") &&
  5225. img_sniff(body, len, &image_info) == 0)) {
  5226. unsigned int node = br_parse_image_doc(&doc, page_url);
  5227. if (node)
  5228. decode_direct_image(body, len, node);
  5229. s_copy(page_title, "Image", sizeof(page_title));
  5230. } else {
  5231. br_set_viewport(ui.w);
  5232. t_mark = u_ticks_ms();
  5233. br_parse(&doc, (const char *)body, len);
  5234. t_parse = u_ticks_ms() - t_mark;
  5235. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  5236. sizeof(page_title));
  5237. t_mark = u_ticks_ms();
  5238. if (load_stylesheets() == FETCH_ABORT)
  5239. return;
  5240. t_css = u_ticks_ms() - t_mark;
  5241. if (pending_action)
  5242. return;
  5243. }
  5244. preload_begin();
  5245. page_loading = 0;
  5246. hist_visit(page_url, page_title);
  5247. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5248. url_in.len = s_len(url_in.text);
  5249. url_in.cursor = url_in.len;
  5250. url_in.scroll = 0;
  5251. ngui_set_focus(&ui, 0);
  5252. /* Paint the parsed page before fetching/running scripts. A slow
  5253. * remote <script src> then does not hide the page behind the loading
  5254. * screen; the fetch helper pumps this UI while it waits. */
  5255. set_status("Loading scripts...", 0, 0);
  5256. t_mark = u_ticks_ms();
  5257. redraw_now();
  5258. t_paint = u_ticks_ms() - t_mark;
  5259. /* Start one image download before the scripts. The other workers
  5260. * fetch the external script bodies in parallel, and the remaining
  5261. * images start as soon as the script phase ends. */
  5262. preload_max_jobs = 1;
  5263. preload_fill_jobs();
  5264. preload_wait = 0;
  5265. t_mark = u_ticks_ms();
  5266. run_page_scripts();
  5267. t_js = u_ticks_ms() - t_mark;
  5268. preload_max_jobs = FETCH_WORKERS;
  5269. if (pending_action)
  5270. return;
  5271. post_status_text[0] = '\0';
  5272. post_status_error = 0;
  5273. post_status_ttl = 0;
  5274. if (js_last_status[0]) {
  5275. s_copy(post_status_text, js_last_status,
  5276. sizeof(post_status_text));
  5277. post_status_error = js_last_error;
  5278. post_status_ttl = 8000;
  5279. } else if (truncated) {
  5280. s_copy(post_status_text, "Page truncated at the buffer limit",
  5281. sizeof(post_status_text));
  5282. post_status_ttl = 6000;
  5283. } else if (doc.truncated) {
  5284. s_copy(post_status_text, "Page truncated by the parser",
  5285. sizeof(post_status_text));
  5286. post_status_ttl = 6000;
  5287. } else if (page_total_ms) {
  5288. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  5289. * paint 220, js 1750" -- the phases of this load. */
  5290. unsigned int n = 0;
  5291. static const char *const names[] = {
  5292. ", parse ", ", css ", ", paint ", ", js "
  5293. };
  5294. unsigned int vals[4];
  5295. int k;
  5296. vals[0] = t_parse;
  5297. vals[1] = t_css;
  5298. vals[2] = t_paint;
  5299. vals[3] = t_js;
  5300. (void)page_first_ms;
  5301. if (starts_with(page_url, "https://"))
  5302. s_append(post_status_text, &n,
  5303. "HTTPS (not verified), ",
  5304. sizeof(post_status_text));
  5305. s_append(post_status_text, &n, "Loaded in ",
  5306. sizeof(post_status_text));
  5307. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  5308. sizeof(post_status_text));
  5309. s_append(post_status_text, &n, " ms: page ",
  5310. sizeof(post_status_text));
  5311. s_append_dec(post_status_text, &n, t_fetch,
  5312. sizeof(post_status_text));
  5313. s_append(post_status_text, &n, " (headers ",
  5314. sizeof(post_status_text));
  5315. s_append_dec(post_status_text, &n, page_open_ms,
  5316. sizeof(post_status_text));
  5317. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  5318. for (k = 0; k < 4; k++) {
  5319. s_append(post_status_text, &n, names[k],
  5320. sizeof(post_status_text));
  5321. s_append_dec(post_status_text, &n, vals[k],
  5322. sizeof(post_status_text));
  5323. }
  5324. post_status_ttl = 12000;
  5325. } else if (starts_with(page_url, "https://")) {
  5326. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  5327. sizeof(post_status_text));
  5328. post_status_ttl = 6000;
  5329. }
  5330. set_status(post_status_text, post_status_error, post_status_ttl);
  5331. ngui_invalidate(&ui);
  5332. }
  5333. static void load_home(int push)
  5334. {
  5335. pending_post_len = 0;
  5336. pending_post_is = 0;
  5337. cancel_fetch = 0;
  5338. preload_active = 0;
  5339. preload_pending = 0;
  5340. js_browser_stop();
  5341. js_last_status[0] = '\0';
  5342. js_last_error = 0;
  5343. heap_clear();
  5344. image_reset();
  5345. form_reset_state();
  5346. layout_valid = 0;
  5347. page_scroll.offset = 0;
  5348. page_scroll.dragging = 0;
  5349. page_loading = 1;
  5350. page_is_local = 0;
  5351. s_copy(page_url, "about:home", sizeof(page_url));
  5352. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5353. url_in.len = s_len(url_in.text);
  5354. url_in.cursor = url_in.len;
  5355. url_in.scroll = 0;
  5356. ngui_set_focus(&ui, 0);
  5357. if (push)
  5358. history_push(page_url);
  5359. ngui_invalidate(&ui);
  5360. /* See load_page(): reattach the fonts before the first redraw. */
  5361. if (heap_start() != 0) {
  5362. show_error("Out of memory", "Cannot allocate the browser heap");
  5363. return;
  5364. }
  5365. br_parse_plain(&doc, "", 0);
  5366. ngui_font_attach(&ui);
  5367. redraw_now();
  5368. browser_rules_alloc();
  5369. {
  5370. static const char home[] =
  5371. "<html><head><title>NebOS Browser</title><style>"
  5372. "body { margin: 10px; color: #e4e6f0; }"
  5373. "h1 { color: #7fb0ff; }"
  5374. ".box { background-color: #262b3a; margin: 12px; "
  5375. "padding: 10px; }"
  5376. "a { color: #7fb0ff; }"
  5377. "pre { background-color: #32384a; }"
  5378. "</style></head><body>"
  5379. "<h1>NebOS Browser</h1>"
  5380. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  5381. "shared HTTP client and the image library.</p>"
  5382. "<div class=\"box\"><b>Try:</b>"
  5383. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  5384. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  5385. "<li><a href=\"/floppy1/JS.HTM\">/"
  5386. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  5387. "<li><a href=\"http://10.0.2.2:8000/\">"
  5388. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  5389. "<li><a href=\"https://example.com/\">"
  5390. "https://example.com/</a> (TLS, not verified)</li>"
  5391. "</ul></div>"
  5392. "<p>Type a URL in the bar above. Esc closes the "
  5393. "window, Ctrl+L focuses the address bar.</p>"
  5394. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  5395. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  5396. "</body></html>";
  5397. br_set_viewport(ui.w);
  5398. br_parse(&doc, home, sizeof(home) - 1);
  5399. br_parse_inline_css(&doc);
  5400. br_reset_styles(&doc);
  5401. s_copy(page_title, doc.title, sizeof(page_title));
  5402. }
  5403. post_status_text[0] = '\0';
  5404. post_status_error = 0;
  5405. post_status_ttl = 0;
  5406. page_loading = 0;
  5407. set_status("", 0, 0);
  5408. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5409. url_in.len = s_len(url_in.text);
  5410. url_in.cursor = url_in.len;
  5411. url_in.scroll = 0;
  5412. ngui_set_focus(&ui, 0);
  5413. ngui_invalidate(&ui);
  5414. }
  5415. /* Extensions the browser opens from the local filesystem. A dotted input
  5416. * with one of these still resolves relative to the cwd. */
  5417. static int local_file_ext(const char *s)
  5418. {
  5419. static const char *const exts[] = {
  5420. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  5421. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  5422. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  5423. "cfg", "conf", 0
  5424. };
  5425. unsigned int i = 0, start = 0, len = 0, e;
  5426. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  5427. s[i] != '#') {
  5428. if (s[i] == '.') {
  5429. start = i + 1;
  5430. len = 0;
  5431. } else if (start) {
  5432. len++;
  5433. }
  5434. i++;
  5435. }
  5436. if (!len)
  5437. return 0;
  5438. for (e = 0; exts[e]; e++) {
  5439. const char *x = exts[e];
  5440. unsigned int xn = s_len(x), k;
  5441. if (xn != len)
  5442. continue;
  5443. for (k = 0; k < len; k++) {
  5444. char a = s[start + k];
  5445. if (a >= 'A' && a <= 'Z')
  5446. a = (char)(a - 'A' + 'a');
  5447. if (a != x[k])
  5448. break;
  5449. }
  5450. if (k == len)
  5451. return 1;
  5452. }
  5453. return 0;
  5454. }
  5455. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  5456. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  5457. * Enter to the first network request. */
  5458. static int looks_like_host(const char *s)
  5459. {
  5460. unsigned int i = 0;
  5461. int dot = 0;
  5462. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  5463. s[i] != ':') {
  5464. char c = s[i];
  5465. if (c == '.') {
  5466. dot = 1;
  5467. } else if (!((c >= 'a' && c <= 'z') ||
  5468. (c >= 'A' && c <= 'Z') ||
  5469. (c >= '0' && c <= '9') ||
  5470. c == '-' || c == '_')) {
  5471. return 0;
  5472. }
  5473. i++;
  5474. }
  5475. return dot && i > 0 && !local_file_ext(s);
  5476. }
  5477. static void load_remote(const char *url, int push)
  5478. {
  5479. char canon[BR_URL_MAX];
  5480. s_copy(canon, url, sizeof(canon));
  5481. origin_cache_apply(canon, sizeof(canon));
  5482. load_page(canon, 0, push);
  5483. }
  5484. static void navigate(const char *input, int push)
  5485. {
  5486. char target[BR_URL_MAX];
  5487. char *t;
  5488. if (!input)
  5489. return;
  5490. s_copy(target, input, sizeof(target));
  5491. t = trim(target);
  5492. if (!t[0])
  5493. return;
  5494. if (s_eq(t, "about:home")) {
  5495. load_home(push);
  5496. return;
  5497. }
  5498. if (starts_with(t, "file://")) {
  5499. make_abs_local(t + 7, target, sizeof(target));
  5500. load_page(target, 1, push);
  5501. return;
  5502. }
  5503. if (is_http(t)) {
  5504. load_remote(t, push);
  5505. return;
  5506. }
  5507. if (t[0] == '/') {
  5508. make_abs_local(t, target, sizeof(target));
  5509. load_page(target, 1, push);
  5510. return;
  5511. }
  5512. if (!looks_like_host(t)) {
  5513. struct sys_stat st;
  5514. if (u_stat(t, &st) == 0 && !st.is_dir) {
  5515. make_abs_local(t, target, sizeof(target));
  5516. load_page(target, 1, push);
  5517. return;
  5518. }
  5519. }
  5520. {
  5521. /* A typed bare host tries https first: nearly every site
  5522. * redirects http -> https anyway, and that hop costs a whole
  5523. * extra connection. load_page() falls back to http when the
  5524. * https connection itself fails. */
  5525. char with_scheme[BR_URL_MAX];
  5526. unsigned int n = 0;
  5527. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  5528. s_append(with_scheme, &n, t, sizeof(with_scheme));
  5529. nav_https_upgraded = 1;
  5530. load_remote(with_scheme, push);
  5531. }
  5532. }
  5533. /* ---- layout ---- */
  5534. static struct ufont_face *style_face(const struct br_style *st)
  5535. {
  5536. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  5537. return font_faces[st->font_face - 1];
  5538. return 0;
  5539. }
  5540. static struct ufont_face *run_face(const struct lay_run *r)
  5541. {
  5542. if (r->font_face && r->font_face <= BR_MAX_FACES)
  5543. return font_faces[r->font_face - 1];
  5544. return 0;
  5545. }
  5546. static unsigned int face_text_width(struct ngui *gui,
  5547. const struct br_style *st,
  5548. const char *s, unsigned int n)
  5549. {
  5550. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  5551. st->bold, st->italic, st->mono);
  5552. }
  5553. static int face_line_height(struct ngui *gui, const struct br_style *st)
  5554. {
  5555. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  5556. st->mono);
  5557. }
  5558. static unsigned int run_text_width(struct ngui *gui,
  5559. const struct lay_run *r,
  5560. const char *s, unsigned int n)
  5561. {
  5562. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  5563. r->bold, r->italic, r->mono);
  5564. }
  5565. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  5566. {
  5567. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  5568. r->mono);
  5569. }
  5570. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  5571. {
  5572. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  5573. }
  5574. static struct br_style base_style(void)
  5575. {
  5576. struct br_style s = { 0 };
  5577. s.color = ui.theme.text;
  5578. s.bg = ui.theme.bg;
  5579. s.has_bg = 0;
  5580. for (int i = 0; i < 4; i++) {
  5581. s.border_c[i] = 0;
  5582. s.border_w[i] = 0;
  5583. s.border_s[i] = BR_BORDER_SOLID;
  5584. }
  5585. s.font_px = 16;
  5586. s.bold = 0;
  5587. s.italic = 0;
  5588. s.mono = 0;
  5589. s.underline = 0;
  5590. s.strike = 0;
  5591. s.overline = 0;
  5592. s.align = BR_ALIGN_LEFT;
  5593. s.display = BR_DISPLAY_BLOCK;
  5594. s.no_bullet = 0;
  5595. s.list_style = BR_LIST_AUTO;
  5596. s.uppercase = 0;
  5597. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  5598. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  5599. s.width = s.max_width = s.min_width = 0;
  5600. s.height = s.min_height = s.max_height = 0;
  5601. s.box_sizing = 0;
  5602. s.ml_auto = s.mr_auto = 0;
  5603. s.line_h_pct = 0;
  5604. s.line_h_px = 0;
  5605. s.mt = s.mb = s.ml = s.mr = 0;
  5606. s.pt = s.pb = s.pl = s.pr = 0;
  5607. return s;
  5608. }
  5609. /* The style node 0's children inherit. Node 0 is the first parsed node:
  5610. * a minified page that starts `<!doctype html><html ...>` makes it the
  5611. * <html> element itself, and the layout walks only its children, so its
  5612. * own cascade (html { color; font } -- Docusaurus/Infima put the page
  5613. * colour and font there) used to be skipped and the theme defaults showed
  5614. * through. Only inherited properties are taken: the root's box (margins,
  5615. * display, background) is not a container style for its children here. */
  5616. static struct br_style root_style(void)
  5617. {
  5618. struct br_style base = base_style(), st;
  5619. if (!doc.nnode || doc.nodes[doc.root].type != BR_NODE_ELEM ||
  5620. doc.nodes[doc.root].tag != BR_TAG_HTML)
  5621. return base;
  5622. br_style_for(&doc, doc.root, &base, &st);
  5623. base.color = st.color;
  5624. base.font_px = st.font_px;
  5625. base.bold = st.bold;
  5626. base.italic = st.italic;
  5627. base.mono = st.mono;
  5628. base.font_face = st.font_face;
  5629. base.align = st.align;
  5630. base.line_h_pct = st.line_h_pct;
  5631. base.line_h_px = st.line_h_px;
  5632. base.nowrap = st.nowrap;
  5633. base.uppercase = st.uppercase;
  5634. base.cursor = st.cursor;
  5635. base.vis_hidden = st.vis_hidden;
  5636. base.fill_mode = st.fill_mode;
  5637. base.fill = st.fill;
  5638. base.stroke_mode = st.stroke_mode;
  5639. base.stroke = st.stroke;
  5640. base.stroke_w = st.stroke_w;
  5641. base.fill_evenodd = st.fill_evenodd;
  5642. return base;
  5643. }
  5644. /* Resolve a margin/padding raw value. Percentages use the containing
  5645. * block width for all four sides, as CSS specifies. */
  5646. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  5647. {
  5648. if (unit == 1)
  5649. return base * v / 10000;
  5650. if (unit == 2)
  5651. return st->font_px * v / 100;
  5652. if (unit == 3)
  5653. return (int)br_root_font_px() * v / 100;
  5654. if (unit == 4)
  5655. return 0;
  5656. return v;
  5657. }
  5658. static int mp_px(const struct br_style *st, int side, int base)
  5659. {
  5660. int raw;
  5661. switch (side) {
  5662. case 0: raw = st->mt; break;
  5663. case 1: raw = st->mr; break;
  5664. case 2: raw = st->mb; break;
  5665. case 3: raw = st->ml; break;
  5666. case 4: raw = st->pt; break;
  5667. case 5: raw = st->pr; break;
  5668. case 6: raw = st->pb; break;
  5669. default: raw = st->pl; break;
  5670. }
  5671. if (st->mp_unit[side] == 5)
  5672. return base * raw / 100 + st->mp_calc_px[side];
  5673. return css_mp_px(st, raw, st->mp_unit[side], base);
  5674. }
  5675. static int style_width_px(const struct br_style *st, int base)
  5676. {
  5677. if (st->width_kind == 1)
  5678. return st->width;
  5679. if (st->width_kind == 2)
  5680. return base * (int)st->width / 100;
  5681. if (st->width_kind == 3)
  5682. return base * st->width_calc_pct / 100 + st->width_calc_px;
  5683. return 0;
  5684. }
  5685. static int style_height_px(const struct br_style *st, int base)
  5686. {
  5687. if (st->height_kind == 1)
  5688. return st->height;
  5689. if (st->height_kind == 2)
  5690. return base * (int)st->height / 100;
  5691. if (st->height_kind == 3)
  5692. return base * st->height_calc_pct / 100 + st->height_calc_px;
  5693. return 0;
  5694. }
  5695. static int css_size(unsigned char kind, int val, int base)
  5696. {
  5697. if (kind == 1)
  5698. return val;
  5699. if (kind == 2)
  5700. return base * val / 100;
  5701. return -1;
  5702. }
  5703. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  5704. int thick, int horizontal, unsigned short color,
  5705. unsigned char style)
  5706. {
  5707. int pos;
  5708. if (len <= 0 || thick <= 0)
  5709. return;
  5710. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  5711. if (horizontal)
  5712. ngui_fill_rect(ui, (struct ngui_rect){
  5713. x, y, len, thick}, color);
  5714. else
  5715. ngui_fill_rect(ui, (struct ngui_rect){
  5716. x, y, thick, len}, color);
  5717. return;
  5718. }
  5719. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  5720. int seg = len - pos;
  5721. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  5722. seg = style == BR_BORDER_DASHED ? 4 : 2;
  5723. if (horizontal)
  5724. ngui_fill_rect(ui, (struct ngui_rect){
  5725. x + pos, y, seg, thick}, color);
  5726. else
  5727. ngui_fill_rect(ui, (struct ngui_rect){
  5728. x, y + pos, thick, seg}, color);
  5729. }
  5730. }
  5731. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  5732. const struct br_style *st)
  5733. {
  5734. int top = st->border_w[0], right = st->border_w[1];
  5735. int bottom = st->border_w[2], left = st->border_w[3];
  5736. if (r.w <= 0 || r.h <= 0)
  5737. return;
  5738. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  5739. int i;
  5740. for (i = 0; i < 4; i++)
  5741. if (st->border_w[i] && !st->border_t[i]) {
  5742. ngui_fill_rect(ui, r, st->border_c[i]);
  5743. break;
  5744. }
  5745. return;
  5746. }
  5747. if (top && !st->border_t[0])
  5748. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  5749. st->border_c[0], st->border_s[0]);
  5750. if (bottom && !st->border_t[2])
  5751. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  5752. st->border_c[2], st->border_s[2]);
  5753. if (left && !st->border_t[3])
  5754. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  5755. left, 0, st->border_c[3], st->border_s[3]);
  5756. if (right && !st->border_t[1])
  5757. draw_border_side(ui, r.x + r.w - right, r.y + top,
  5758. r.h - top - bottom, right, 0,
  5759. st->border_c[1], st->border_s[1]);
  5760. }
  5761. static void transform_origin(const struct br_style *st, int w, int h,
  5762. int *ox, int *oy)
  5763. {
  5764. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  5765. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  5766. }
  5767. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  5768. unsigned int a)
  5769. {
  5770. unsigned int dr, dg, db, sr, sg, sb;
  5771. if (a >= 255)
  5772. return s;
  5773. dr = (d >> 11) & 31;
  5774. dg = (d >> 5) & 63;
  5775. db = d & 31;
  5776. sr = (s >> 11) & 31;
  5777. sg = (s >> 5) & 63;
  5778. sb = s & 31;
  5779. dr = (dr * (255 - a) + sr * a) / 255;
  5780. dg = (dg * (255 - a) + sg * a) / 255;
  5781. db = (db * (255 - a) + sb * a) / 255;
  5782. return (unsigned short)((dr << 11) | (dg << 5) | db);
  5783. }
  5784. /* Paint a solid box through scale()/rotate() around transform-origin. This
  5785. * transforms the element's own background box; text and descendants keep
  5786. * their layout (documented approximation). */
  5787. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  5788. unsigned short color,
  5789. const struct br_style *st)
  5790. {
  5791. double sx = st->scale_x / 100.0;
  5792. double sy = st->scale_y / 100.0;
  5793. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  5794. double c = cos(th), sn = sin(th);
  5795. int ox, oy, minx, miny, maxx, maxy, x, y;
  5796. double ax, ay;
  5797. double px[4], py[4];
  5798. int cx1, cy1, cx2, cy2, i;
  5799. if (sx == 0)
  5800. sx = 0.01;
  5801. if (sy == 0)
  5802. sy = 0.01;
  5803. transform_origin(st, box.w, box.h, &ox, &oy);
  5804. ax = box.x + ox;
  5805. ay = box.y + oy;
  5806. px[0] = -ox; py[0] = -oy;
  5807. px[1] = box.w - ox; py[1] = -oy;
  5808. px[2] = box.w - ox; py[2] = box.h - oy;
  5809. px[3] = -ox; py[3] = box.h - oy;
  5810. minx = miny = 1000000;
  5811. maxx = maxy = -1000000;
  5812. for (i = 0; i < 4; i++) {
  5813. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  5814. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  5815. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5816. if (dx < minx) minx = dx;
  5817. if (dx > maxx) maxx = dx;
  5818. if (dy < miny) miny = dy;
  5819. if (dy > maxy) maxy = dy;
  5820. }
  5821. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5822. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5823. cx2 = page_rect.x + page_rect.w - 12;
  5824. cy2 = page_rect.y + page_rect.h;
  5825. if (cx2 > gui->w) cx2 = gui->w;
  5826. if (cy2 > gui->h) cy2 = gui->h;
  5827. if (minx < cx1) minx = cx1;
  5828. if (miny < cy1) miny = cy1;
  5829. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5830. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5831. for (y = miny; y <= maxy; y++) {
  5832. for (x = minx; x <= maxx; x++) {
  5833. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  5834. double rx = dx * c + dy * sn;
  5835. double ry = -dx * sn + dy * c;
  5836. double bx = rx / sx + ox;
  5837. double by = ry / sy + oy;
  5838. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  5839. gui->px[y * gui->w + x] = color;
  5840. }
  5841. }
  5842. }
  5843. static void draw_image_transformed(struct ngui *gui,
  5844. const struct img_image *im,
  5845. int x, int y, int w, int h,
  5846. int sx100, int sy100, int rot100,
  5847. int origin_x, int origin_y,
  5848. int origin_x_kind, int origin_y_kind)
  5849. {
  5850. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  5851. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  5852. double c = cos(th), sn = sin(th);
  5853. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  5854. double ax, ay;
  5855. double bx[4], by[4];
  5856. int cx1, cy1, cx2, cy2;
  5857. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  5858. return;
  5859. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  5860. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  5861. ax = x + ox;
  5862. ay = y + oy;
  5863. bx[0] = -ox; by[0] = -oy;
  5864. bx[1] = w - ox; by[1] = -oy;
  5865. bx[2] = w - ox; by[2] = h - oy;
  5866. bx[3] = -ox; by[3] = h - oy;
  5867. minx = miny = 1000000;
  5868. maxx = maxy = -1000000;
  5869. for (i = 0; i < 4; i++) {
  5870. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  5871. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  5872. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5873. if (dx < minx) minx = dx;
  5874. if (dx > maxx) maxx = dx;
  5875. if (dy < miny) miny = dy;
  5876. if (dy > maxy) maxy = dy;
  5877. }
  5878. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5879. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5880. cx2 = page_rect.x + page_rect.w - 12;
  5881. cy2 = page_rect.y + page_rect.h;
  5882. if (cx2 > gui->w) cx2 = gui->w;
  5883. if (cy2 > gui->h) cy2 = gui->h;
  5884. if (minx < cx1) minx = cx1;
  5885. if (miny < cy1) miny = cy1;
  5886. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5887. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5888. for (py = miny; py <= maxy; py++) {
  5889. for (px = minx; px <= maxx; px++) {
  5890. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  5891. double rx = dx * c + dy * sn;
  5892. double ry = -dx * sn + dy * c;
  5893. double fx = rx / sx + ox;
  5894. double fy = ry / sy + oy;
  5895. int ix, iy;
  5896. unsigned int si, a;
  5897. unsigned short src;
  5898. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  5899. continue;
  5900. ix = (int)(fx * (double)im->w / w);
  5901. iy = (int)(fy * (double)im->h / h);
  5902. if (ix < 0 || ix >= (int)im->w ||
  5903. iy < 0 || iy >= (int)im->h)
  5904. continue;
  5905. si = (unsigned int)iy * im->w + (unsigned int)ix;
  5906. src = im->px[si];
  5907. a = im->alpha ? im->alpha[si] : 255;
  5908. gui->px[py * gui->w + px] =
  5909. a >= 255 ? src :
  5910. blend_rgb565(gui->px[py * gui->w + px],
  5911. src, a);
  5912. }
  5913. }
  5914. }
  5915. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5916. unsigned int node, const struct br_style *st);
  5917. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  5918. * first and every pixel outside a corner's arc is restored afterwards. */
  5919. #define BG_ROUND_MAX 64
  5920. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  5921. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  5922. unsigned int node, const struct br_style *st,
  5923. int rtl, int rtr, int rbr, int rbl)
  5924. {
  5925. struct ngui *ui = l->ui;
  5926. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  5927. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  5928. if (ui->nclip > 0)
  5929. clip = ui->clip[ui->nclip - 1];
  5930. for (c = 0; c < 4; c++) {
  5931. if (r[c] > BG_ROUND_MAX)
  5932. r[c] = BG_ROUND_MAX;
  5933. if (r[c] > box.w / 2)
  5934. r[c] = box.w / 2;
  5935. if (r[c] > box.h / 2)
  5936. r[c] = box.h / 2;
  5937. }
  5938. for (c = 0; c < 4; c++) {
  5939. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5940. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5941. for (dy = 0; dy < r[c]; dy++)
  5942. for (dx = 0; dx < r[c]; dx++) {
  5943. int px = ox + dx, py = oy + dy;
  5944. if (px >= clip.x && py >= clip.y &&
  5945. px < clip.x + clip.w && py < clip.y + clip.h)
  5946. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  5947. ui->px[py * ui->w + px];
  5948. }
  5949. }
  5950. draw_bg_image(l, box, node, st);
  5951. for (c = 0; c < 4; c++) {
  5952. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5953. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5954. /* arc centre, in corner-square coordinates */
  5955. int cx = (c == 1 || c == 2) ? 0 : r[c];
  5956. int cy = (c >= 2) ? 0 : r[c];
  5957. for (dy = 0; dy < r[c]; dy++)
  5958. for (dx = 0; dx < r[c]; dx++) {
  5959. int px = ox + dx, py = oy + dy;
  5960. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  5961. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  5962. continue;
  5963. if (px >= clip.x && py >= clip.y &&
  5964. px < clip.x + clip.w && py < clip.y + clip.h)
  5965. ui->px[py * ui->w + px] =
  5966. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  5967. }
  5968. }
  5969. }
  5970. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5971. unsigned int node, const struct br_style *st)
  5972. {
  5973. struct br_image *bi;
  5974. struct img_blit b;
  5975. int tw, th, x, y, rep_x, rep_y, posx, posy;
  5976. unsigned int scale = 65536;
  5977. int legacy, tiles = 0, rows = 0;
  5978. int cx1, cy1, cx2, cy2;
  5979. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  5980. return;
  5981. if (doc.nodes[node].bg_img_index < 0 ||
  5982. doc.nodes[node].bg_img_index >= image_count)
  5983. return;
  5984. bi = &images[doc.nodes[node].bg_img_index];
  5985. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  5986. return;
  5987. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  5988. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  5989. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  5990. if (legacy) {
  5991. scale = ((unsigned int)box.w << 16) / bi->img.w;
  5992. tw = box.w;
  5993. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  5994. x = box.x;
  5995. y = box.y;
  5996. rep_x = rep_y = 0;
  5997. } else {
  5998. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  5999. unsigned int sx = ((unsigned int)box.w << 16) /
  6000. bi->img.w;
  6001. unsigned int sy = ((unsigned int)box.h << 16) /
  6002. bi->img.h;
  6003. scale = st->bg_size_kind == 3 ?
  6004. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  6005. } else if (st->bg_size_kind == 1 ||
  6006. st->bg_size_kind == 2) {
  6007. int w = st->bg_size_w;
  6008. int h = st->bg_size_h;
  6009. if (st->bg_size_kind == 2) {
  6010. if (w)
  6011. w = box.w * w / 100;
  6012. if (h)
  6013. h = box.h * h / 100;
  6014. }
  6015. if (w)
  6016. scale = ((unsigned int)w << 16) / bi->img.w;
  6017. else if (h)
  6018. scale = ((unsigned int)h << 16) / bi->img.h;
  6019. }
  6020. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  6021. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6022. if (tw < 1)
  6023. tw = 1;
  6024. if (th < 1)
  6025. th = 1;
  6026. posx = st->bg_pos_x_kind == 1 ?
  6027. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  6028. posy = st->bg_pos_y_kind == 1 ?
  6029. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  6030. x = box.x + posx;
  6031. y = box.y + posy;
  6032. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  6033. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  6034. if (rep_x) {
  6035. int m = (x - box.x) % tw;
  6036. if (m > 0)
  6037. m -= tw;
  6038. x = box.x + m;
  6039. }
  6040. if (rep_y) {
  6041. int m = (y - box.y) % th;
  6042. if (m > 0)
  6043. m -= th;
  6044. y = box.y + m;
  6045. }
  6046. }
  6047. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  6048. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  6049. cx2 = box.x + box.w;
  6050. cy2 = box.y + box.h;
  6051. if (cx2 > page_rect.x + page_rect.w - 12)
  6052. cx2 = page_rect.x + page_rect.w - 12;
  6053. if (cy2 > page_rect.y + page_rect.h)
  6054. cy2 = page_rect.y + page_rect.h;
  6055. if (cx1 >= cx2 || cy1 >= cy2)
  6056. return;
  6057. b.dst = l->ui->px;
  6058. b.dst_w = l->ui->w;
  6059. b.dst_h = l->ui->h;
  6060. b.clip_x = cx1;
  6061. b.clip_y = cy1;
  6062. b.clip_w = cx2 - cx1;
  6063. b.clip_h = cy2 - cy1;
  6064. b.bg = ui.theme.bg;
  6065. b.bg2 = ui.theme.bg;
  6066. b.dst_a = 0;
  6067. {
  6068. struct img_image *src = image_display_get(bi, tw, th);
  6069. int row_x;
  6070. if (!src)
  6071. src = &bi->img;
  6072. b.scale = ((unsigned int)tw << 16) / src->w;
  6073. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  6074. row_x = x;
  6075. for (;;) {
  6076. for (;;) {
  6077. b.x = x;
  6078. b.y = y;
  6079. img_draw(src, &b);
  6080. if (!rep_x || ++tiles > 512)
  6081. break;
  6082. x += tw;
  6083. if (x >= box.x + box.w)
  6084. break;
  6085. }
  6086. if (!rep_y || ++rows > 64)
  6087. break;
  6088. y += th;
  6089. if (y >= box.y + box.h)
  6090. break;
  6091. x = row_x;
  6092. }
  6093. }
  6094. }
  6095. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  6096. int *out_w, int *out_h);
  6097. static void svg_paint_box(struct ngui *ui, unsigned int node,
  6098. const struct br_style *st, int x, int y, int w,
  6099. int h);
  6100. /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
  6101. * RUN_SVG an inline <svg> icon (its node in off), RUN_PBOX an empty
  6102. * ::before/::after box with a background (Infima's menu chevrons). */
  6103. #define RUN_SVG (-3)
  6104. #define RUN_PBOX (-4)
  6105. static int run_width(const struct lay_run *r)
  6106. {
  6107. if (r->img >= 0)
  6108. return r->iw;
  6109. if (r->img == -2 || r->img == RUN_SVG || r->img == RUN_PBOX)
  6110. return r->iw;
  6111. return (int)r->w;
  6112. }
  6113. static void start_line(struct lay *l, const struct br_style *st)
  6114. {
  6115. (void)st;
  6116. if (l->nruns == 0) {
  6117. l->line_y = l->y;
  6118. l->line_h = 0;
  6119. }
  6120. l->line_left = l->left;
  6121. l->line_right = l->right;
  6122. if (l->float_active && l->line_y < l->float_bottom) {
  6123. if (l->float_left > l->line_left)
  6124. l->line_left = l->float_left;
  6125. if (l->float_right < l->line_right)
  6126. l->line_right = l->float_right;
  6127. }
  6128. if (l->line_right < l->line_left + 8)
  6129. l->line_right = l->line_left + 8;
  6130. l->line_x = l->line_left;
  6131. l->run_x = l->line_left;
  6132. }
  6133. static void flush_line(struct lay *l)
  6134. {
  6135. int total, x, i, vis;
  6136. if (!l->nruns && l->line_x == l->line_left) {
  6137. l->line_h = 0;
  6138. return;
  6139. }
  6140. total = l->line_x - l->line_left;
  6141. x = l->line_left;
  6142. vis = 1;
  6143. if (l->draw) {
  6144. int lh = l->line_h ? l->line_h : 16;
  6145. vis = l->line_y + lh >= page_rect.y &&
  6146. l->line_y <= page_rect.y + page_rect.h;
  6147. }
  6148. if (l->align == BR_ALIGN_CENTER)
  6149. x += (l->line_right - l->line_left - total) / 2;
  6150. else if (l->align == BR_ALIGN_RIGHT)
  6151. x = l->line_right - total;
  6152. if (x < l->line_left)
  6153. x = l->line_left;
  6154. for (i = 0; i < l->nruns; i++) {
  6155. struct lay_run *r = &l->runs[i];
  6156. int w = run_width(r);
  6157. int ry = l->line_y + r->dy;
  6158. x += r->gap;
  6159. if (l->draw && vis) {
  6160. if (r->form) {
  6161. unsigned int node = r->form - 1;
  6162. struct form_state *fs = form_get(node, 1);
  6163. int hh = r->ih ? r->ih : 20;
  6164. int focused = form_focus == node;
  6165. int disabled = r->form_disabled;
  6166. unsigned short bg = l->ui->theme.panel_alt;
  6167. unsigned short fg = disabled ? 0x8410 : r->color;
  6168. struct ngui_rect box = {x, ry, w, hh};
  6169. if (r->form_kind == FORM_CHECKBOX ||
  6170. r->form_kind == FORM_RADIO) {
  6171. ngui_fill_rect(l->ui, box, bg);
  6172. ngui_frame(l->ui, box,
  6173. focused ? l->ui->theme.accent :
  6174. l->ui->theme.border);
  6175. if (fs && fs->checked) {
  6176. struct ngui_rect dot = {
  6177. x + 4, ry + 4,
  6178. w > 8 ? w - 8 : 1,
  6179. hh > 8 ? hh - 8 : 1
  6180. };
  6181. if (r->form_kind == FORM_RADIO)
  6182. ngui_fill_round_rect(
  6183. l->ui, dot, 4,
  6184. 4, 4, 4,
  6185. l->ui->theme.accent);
  6186. else
  6187. ngui_fill_rect(l->ui,
  6188. dot,
  6189. l->ui->theme.accent);
  6190. }
  6191. } else {
  6192. int editable =
  6193. r->form_kind == FORM_TEXT ||
  6194. r->form_kind == FORM_PASSWORD ||
  6195. r->form_kind == FORM_TEXTAREA;
  6196. int scroll = 0;
  6197. /* Editable fields draw the live value
  6198. * (r->lit is a short copy). */
  6199. static char shown[FORM_VALUE_MAX + 1];
  6200. const char *txt = r->lit;
  6201. unsigned int tl = s_len(r->lit);
  6202. if (editable && fs && fs->len) {
  6203. unsigned int k;
  6204. if (r->form_kind == FORM_PASSWORD) {
  6205. for (k = 0; k < fs->len; k++)
  6206. shown[k] = '*';
  6207. shown[k] = '\0';
  6208. txt = shown;
  6209. } else {
  6210. txt = fs->value;
  6211. }
  6212. tl = fs->len;
  6213. }
  6214. struct br_style fst;
  6215. int author, tx = x + 6, pr = 6;
  6216. style_for_node(node, &fst);
  6217. author = form_author_styled(&fst);
  6218. if (author) {
  6219. /* The page styled the control:
  6220. * its background, border, radius
  6221. * and text colour. */
  6222. form_paint_author(l->ui, box, &fst,
  6223. focused);
  6224. tx = x + fst.border_w[3] +
  6225. mp_px(&fst, 7, w);
  6226. pr = fst.border_w[1] +
  6227. mp_px(&fst, 5, w);
  6228. if (tx < x + 2 && !editable)
  6229. tx = x + 2;
  6230. if (!disabled)
  6231. fg = editable && fs &&
  6232. !fs->len ?
  6233. 0x8410 : fst.color;
  6234. if (!editable) {
  6235. int tw0 = (int)
  6236. run_text_width(l->ui,
  6237. r, txt, tl);
  6238. tx = x + (w - tw0) / 2;
  6239. }
  6240. } else {
  6241. /* The box is drawn in theme colours, so
  6242. * the text is too: the page's CSS colour
  6243. * (dark on a light page) would vanish on
  6244. * the dark field. */
  6245. if (!disabled)
  6246. fg = editable && fs && !fs->len ?
  6247. l->ui->theme.text_dim :
  6248. l->ui->theme.text;
  6249. ngui_fill_rect(l->ui, box, bg);
  6250. ngui_frame(l->ui, box,
  6251. focused ? l->ui->theme.accent :
  6252. l->ui->theme.border);
  6253. }
  6254. /* A value wider than the field shows its
  6255. * tail (where typing happens). */
  6256. if (editable && fs && fs->len &&
  6257. w > (tx - x) + pr) {
  6258. int tw = (int)run_text_width(l->ui,
  6259. r, txt, tl);
  6260. int room = w - (tx - x) - pr;
  6261. if (tw > room)
  6262. scroll = tw - room;
  6263. }
  6264. ngui_push_clip(l->ui, (struct ngui_rect){
  6265. x + 1, ry + 1,
  6266. w > 2 ? w - 2 : 1,
  6267. hh > 2 ? hh - 2 : 1 });
  6268. ngui_text_px_face(l->ui, run_face(r),
  6269. tx - scroll,
  6270. ry + (hh - r->font_px) / 2 - 1,
  6271. txt, tl, fg, r->font_px,
  6272. r->bold, r->italic, r->mono);
  6273. if (focused && fs && editable) {
  6274. int cw = 0;
  6275. if (fs->len && fs->caret)
  6276. cw = (int)run_text_width(
  6277. l->ui, r, txt,
  6278. fs->caret < fs->len ?
  6279. fs->caret : fs->len);
  6280. ngui_fill_rect(l->ui,
  6281. (struct ngui_rect){
  6282. tx + cw - scroll,
  6283. ry + 4, 1,
  6284. hh > 8 ? hh - 8 : 1
  6285. },
  6286. l->ui->theme.accent);
  6287. }
  6288. ngui_pop_clip(l->ui);
  6289. if (r->form_kind == FORM_SELECT) {
  6290. ngui_text_px(l->ui, x + w - 12,
  6291. ry + 2, "v", 1, fg,
  6292. r->font_px, 0, 0, 0);
  6293. }
  6294. }
  6295. } else if (r->img == RUN_PBOX) {
  6296. struct ngui_rect bx = { x, ry, w, r->ih };
  6297. ngui_push_clip(l->ui, bx);
  6298. if (r->pb_has_bg)
  6299. ngui_fill_rect(l->ui, bx, r->pb_bg);
  6300. if (r->pb_img >= 0 && r->pb_img < image_count &&
  6301. images[r->pb_img].state == 1) {
  6302. /* Rotate about the box centre: the
  6303. * image is centred in it here. */
  6304. draw_image_transformed(l->ui,
  6305. &images[r->pb_img].img,
  6306. x + r->pb_x, ry + r->pb_y,
  6307. r->pb_w, r->pb_h,
  6308. r->transform_scale ?
  6309. r->scale_x : 100,
  6310. r->transform_scale ?
  6311. r->scale_y : 100,
  6312. r->transform_scale ?
  6313. r->rotate_x100 : 0,
  6314. 50, 50, 1, 1);
  6315. }
  6316. ngui_pop_clip(l->ui);
  6317. } else if (r->img == RUN_SVG) {
  6318. struct br_style sst;
  6319. style_for_node(r->off, &sst);
  6320. svg_paint_box(l->ui, r->off, &sst, x, ry, w,
  6321. r->ih);
  6322. } else if (r->img == -2) {
  6323. int hh = r->ih ? r->ih : 20;
  6324. ngui_fill_rect(l->ui,
  6325. (struct ngui_rect){x, ry, w, hh},
  6326. l->ui->theme.panel_alt);
  6327. ngui_frame(l->ui,
  6328. (struct ngui_rect){x, ry, w, hh},
  6329. l->ui->theme.border);
  6330. ngui_text_px_face(l->ui, run_face(r),
  6331. x + 6, ry + 2, r->lit,
  6332. s_len(r->lit), r->color,
  6333. r->font_px, r->bold, r->italic,
  6334. r->mono);
  6335. } else if (r->img >= 0) {
  6336. struct br_image *bi = &images[r->img];
  6337. if (bi->state == 1 && r->transform_scale) {
  6338. draw_image_transformed(l->ui, &bi->img,
  6339. x, ry, r->iw, r->ih,
  6340. r->scale_x, r->scale_y,
  6341. r->rotate_x100, r->origin_x,
  6342. r->origin_y, r->origin_x_kind,
  6343. r->origin_y_kind);
  6344. } else if (bi->state == 1) {
  6345. struct img_image *src =
  6346. image_display_get(bi, r->iw, r->ih);
  6347. struct img_blit b;
  6348. if (!src)
  6349. src = &bi->img;
  6350. b.dst = l->ui->px;
  6351. b.dst_w = l->ui->w;
  6352. b.dst_h = l->ui->h;
  6353. b.clip_x = page_rect.x;
  6354. b.clip_y = page_rect.y;
  6355. b.clip_w = page_rect.w - 12;
  6356. b.clip_h = page_rect.h;
  6357. b.x = x;
  6358. b.y = ry;
  6359. b.scale = ((unsigned int)r->iw << 16) /
  6360. src->w;
  6361. b.bg = ui.theme.bg;
  6362. b.bg2 = ui.theme.bg;
  6363. b.dst_a = 0;
  6364. b.flags = src->alpha ?
  6365. IMG_BLIT_OVER_DST : 0;
  6366. img_draw(src, &b);
  6367. }
  6368. } else {
  6369. const char *s = r->has_lit ? r->lit :
  6370. doc.text + r->off;
  6371. unsigned int n = r->has_lit ? s_len(r->lit) :
  6372. r->len;
  6373. ngui_text_px_face(l->ui, run_face(r), x, ry,
  6374. s, n, r->color, r->font_px,
  6375. r->bold, r->italic, r->mono);
  6376. if (r->underline)
  6377. ngui_fill_rect(l->ui,
  6378. (struct ngui_rect){x,
  6379. ry + run_ascent(l->ui, r) + 2,
  6380. w, 1}, r->color);
  6381. if (r->strike)
  6382. ngui_fill_rect(l->ui,
  6383. (struct ngui_rect){x,
  6384. ry + run_ascent(l->ui, r) -
  6385. (r->font_px > 3 ?
  6386. r->font_px / 3 : 1),
  6387. w, 1}, r->color);
  6388. if (r->overline)
  6389. ngui_fill_rect(l->ui,
  6390. (struct ngui_rect){x, ry,
  6391. w, 1}, r->color);
  6392. }
  6393. if (r->form || r->href) {
  6394. if (nhits < HIT_MAX) {
  6395. struct hit *h = &hits[nhits];
  6396. unsigned int target = r->form ?
  6397. r->form - 1 : r->href;
  6398. int hh = (r->form || r->img >= 0 ||
  6399. r->img == RUN_SVG) ?
  6400. r->ih :
  6401. run_line_height(l->ui, r);
  6402. int merge = nhits > 0 &&
  6403. hits[nhits - 1].node == target &&
  6404. hits[nhits - 1].y == ry &&
  6405. hits[nhits - 1].h == hh &&
  6406. x <= hits[nhits - 1].x +
  6407. hits[nhits - 1].w + 2;
  6408. if (merge) {
  6409. struct hit *p = &hits[nhits - 1];
  6410. int end = x + w;
  6411. if (end > p->x + p->w)
  6412. p->w = end - p->x;
  6413. } else {
  6414. h->x = x;
  6415. h->y = ry;
  6416. h->w = w;
  6417. h->h = hh;
  6418. h->node = (unsigned short)target;
  6419. nhits++;
  6420. }
  6421. }
  6422. }
  6423. }
  6424. x += w;
  6425. }
  6426. l->y += l->line_h + 2;
  6427. if (l->float_active && l->y >= l->float_bottom)
  6428. l->float_active = 0;
  6429. l->nruns = 0;
  6430. l->line_x = l->left;
  6431. l->run_x = l->left;
  6432. l->line_left = l->left;
  6433. l->line_right = l->right;
  6434. l->line_h = 0;
  6435. l->space_pending = 0;
  6436. }
  6437. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  6438. const struct br_style *st, unsigned short href,
  6439. const char *lit)
  6440. {
  6441. unsigned int n = lit ? s_len(lit) : len;
  6442. const char *tp = lit ? lit : doc.text + off;
  6443. int w = (int)face_text_width(l->ui, st, tp, n);
  6444. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6445. flush_line(l);
  6446. if (l->nruns == 0) {
  6447. l->line_y = l->y;
  6448. l->line_h = 0;
  6449. start_line(l, st);
  6450. }
  6451. {
  6452. struct lay_run *r = &l->runs[l->nruns++];
  6453. int gap = l->line_x - l->run_x;
  6454. if (gap < 0)
  6455. gap = 0;
  6456. r->gap = (unsigned short)gap;
  6457. r->off = off;
  6458. r->len = len;
  6459. r->color = st->color;
  6460. r->href = href;
  6461. r->dy = 0;
  6462. r->has_lit = 0;
  6463. r->form = 0;
  6464. r->form_kind = 0;
  6465. r->form_disabled = 0;
  6466. r->lit[0] = '\0';
  6467. if (lit && lit[0]) {
  6468. unsigned int i;
  6469. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  6470. r->lit[i] = lit[i];
  6471. r->lit[i] = '\0';
  6472. r->has_lit = 1;
  6473. }
  6474. r->img = -1;
  6475. r->iw = r->ih = 0;
  6476. r->font_px = st->font_px;
  6477. r->bold = st->bold;
  6478. r->italic = st->italic;
  6479. r->mono = st->mono;
  6480. r->font_face = st->font_face;
  6481. /* A control with its own background is a button, not body copy;
  6482. * an inherited link underline would strike through the fill. */
  6483. r->underline = st->underline && !st->has_bg;
  6484. r->strike = st->strike && !st->has_bg;
  6485. r->overline = st->overline && !st->has_bg;
  6486. r->w = (unsigned short)w;
  6487. if (r->has_lit)
  6488. r->w = (unsigned short)run_text_width(
  6489. l->ui, r, r->lit, s_len(r->lit));
  6490. w = r->w;
  6491. }
  6492. l->line_x += w;
  6493. l->run_x = l->line_x;
  6494. {
  6495. int lh = face_line_height(l->ui, st);
  6496. if (st->line_h_px)
  6497. lh = st->line_h_px;
  6498. else if (st->line_h_pct)
  6499. lh = st->font_px * st->line_h_pct / 100;
  6500. if (lh < face_line_height(l->ui, st))
  6501. lh = face_line_height(l->ui, st);
  6502. if (l->line_h < lh)
  6503. l->line_h = lh;
  6504. }
  6505. }
  6506. static void add_image_run(struct lay *l, unsigned int node,
  6507. const struct br_style *st, unsigned short href)
  6508. {
  6509. struct br_image *bi = 0;
  6510. int idx = doc.nodes[node].img_index;
  6511. int dw, dh, maxw;
  6512. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  6513. bi = &images[idx];
  6514. if (l->nruns == 0)
  6515. start_line(l, st);
  6516. if (l->space_pending &&
  6517. (l->nruns > 0 || l->line_x > l->line_left)) {
  6518. int sp = (int)face_text_width(l->ui, st, " ", 1);
  6519. if (l->line_x + sp <= l->line_right)
  6520. l->line_x += sp;
  6521. }
  6522. l->space_pending = 0;
  6523. if (!bi) {
  6524. const char *alt = br_alt(&doc, node);
  6525. struct br_style gs = *st;
  6526. char tmp[96];
  6527. unsigned int n = 0;
  6528. int w;
  6529. gs.color = BR_GRAY;
  6530. gs.underline = 0;
  6531. s_append(tmp, &n, "[", sizeof(tmp));
  6532. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  6533. s_append(tmp, &n, "]", sizeof(tmp));
  6534. w = (int)face_text_width(l->ui, &gs, tmp, n);
  6535. if (l->line_x + w > l->line_right &&
  6536. (l->nruns > 0 || l->line_x > l->line_left))
  6537. flush_line(l);
  6538. add_run(l, 0, 0, &gs, href, tmp);
  6539. if (!l->draw) {
  6540. int t = l->line_y < 0 ? 0 : l->line_y;
  6541. int hh = face_line_height(l->ui, &gs);
  6542. if (t > 65535)
  6543. t = 65535;
  6544. if (hh > 65535)
  6545. hh = 65535;
  6546. img_top[node] = (unsigned short)t;
  6547. img_h[node] = (unsigned short)hh;
  6548. }
  6549. return;
  6550. }
  6551. maxw = l->line_right - l->line_left;
  6552. if (maxw < 8)
  6553. maxw = 8;
  6554. {
  6555. int iw = bi->native_w, ih = bi->native_h;
  6556. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  6557. if (iw <= 0 || ih <= 0) {
  6558. iw = (int)bi->img.w;
  6559. ih = (int)bi->img.h;
  6560. }
  6561. dw = iw;
  6562. dh = ih;
  6563. if (doc.nodes[node].width_attr) {
  6564. int want = doc.nodes[node].width_attr;
  6565. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  6566. have_w = 1;
  6567. }
  6568. if (doc.nodes[node].height_attr) {
  6569. int want = doc.nodes[node].height_attr;
  6570. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  6571. have_h = 1;
  6572. }
  6573. if (have_w && !have_h)
  6574. dh = ih ? ih * dw / iw : 0;
  6575. if (have_h && !have_w)
  6576. dw = iw ? iw * dh / ih : 0;
  6577. if (st->width_kind) {
  6578. css_w = 1;
  6579. if (st->width_kind == 3)
  6580. dw = maxw * st->width_calc_pct / 100 +
  6581. st->width_calc_px;
  6582. else
  6583. dw = st->width_kind == 2 ?
  6584. maxw * (int)st->width / 100 :
  6585. (int)st->width;
  6586. }
  6587. /* Percentage heights resolve against the containing block's
  6588. * definite height (Docusaurus' logo: `.navbar__logo { height:
  6589. * 2rem }` holding an `img { height: 100% }`), and are auto
  6590. * when it has none; they used to use the width. */
  6591. if (st->height_kind == 1 ||
  6592. ((st->height_kind == 2 || st->height_kind == 3) &&
  6593. l->cb_h > 0)) {
  6594. css_h = 1;
  6595. if (st->height_kind == 3)
  6596. dh = l->cb_h * st->height_calc_pct / 100 +
  6597. st->height_calc_px;
  6598. else
  6599. dh = st->height_kind == 2 ?
  6600. l->cb_h * (int)st->height / 100 :
  6601. (int)st->height;
  6602. }
  6603. if (css_w && !css_h)
  6604. dh = ih ? ih * dw / iw : 0;
  6605. if (css_h && !css_w)
  6606. dw = iw ? iw * dh / ih : 0;
  6607. if (st->max_width_kind) {
  6608. int mw = st->max_width_kind == 3 ?
  6609. maxw * st->max_width_calc_pct / 100 +
  6610. st->max_width_calc_px :
  6611. st->max_width_kind == 2 ?
  6612. maxw * (int)st->max_width / 100 :
  6613. (int)st->max_width;
  6614. if (mw > 0 && dw > mw) {
  6615. dh = iw ? ih * mw / iw : 0;
  6616. dw = mw;
  6617. }
  6618. }
  6619. }
  6620. if (dw < 8)
  6621. dw = 8;
  6622. if (dh < 8)
  6623. dh = 8;
  6624. if (dw > maxw) {
  6625. dh = dw ? dh * maxw / dw : dh;
  6626. dw = maxw;
  6627. }
  6628. if (!l->draw) {
  6629. int t = l->line_y < 0 ? 0 : l->line_y;
  6630. if (t > 65535)
  6631. t = 65535;
  6632. if (dh > 65535)
  6633. dh = 65535;
  6634. img_top[node] = (unsigned short)t;
  6635. img_h[node] = (unsigned short)dh;
  6636. }
  6637. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  6638. l->line_x > l->line_left))
  6639. flush_line(l);
  6640. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6641. flush_line(l);
  6642. if (l->nruns == 0) {
  6643. l->line_y = l->y;
  6644. l->line_h = 0;
  6645. start_line(l, st);
  6646. }
  6647. {
  6648. struct lay_run *r = &l->runs[l->nruns++];
  6649. int gap = l->line_x - l->run_x;
  6650. if (gap < 0)
  6651. gap = 0;
  6652. r->gap = (unsigned short)gap;
  6653. r->off = 0;
  6654. r->len = 0;
  6655. r->color = 0;
  6656. r->href = href;
  6657. r->form = 0;
  6658. r->form_kind = 0;
  6659. r->form_disabled = 0;
  6660. /* Inline replaced elements honour their vertical margins; this
  6661. * is how Bootstrap's negative logo margins centre the wordmark. */
  6662. {
  6663. int idy = mp_px(st, 0, l->right - l->left);
  6664. if (idy < -2048)
  6665. idy = -2048;
  6666. if (idy > 2048)
  6667. idy = 2048;
  6668. r->dy = (signed short)idy;
  6669. }
  6670. r->has_lit = 0;
  6671. r->lit[0] = '\0';
  6672. r->img = (short)idx;
  6673. r->iw = (unsigned short)dw;
  6674. r->ih = (unsigned short)dh;
  6675. r->w = (unsigned short)dw;
  6676. r->font_px = st->font_px;
  6677. r->bold = st->bold;
  6678. r->italic = st->italic;
  6679. r->mono = st->mono;
  6680. r->font_face = st->font_face;
  6681. r->transform_scale = st->transform_scale;
  6682. r->scale_x = st->scale_x;
  6683. r->scale_y = st->scale_y;
  6684. r->rotate_x100 = st->rotate_x100;
  6685. r->origin_x = st->origin_x;
  6686. r->origin_y = st->origin_y;
  6687. r->origin_x_kind = st->origin_x_kind;
  6688. r->origin_y_kind = st->origin_y_kind;
  6689. r->underline = 0;
  6690. }
  6691. if (node < BR_MAX_NODES) {
  6692. layout_boxes[node].x = l->line_x;
  6693. layout_boxes[node].y = l->line_y +
  6694. mp_px(st, 0, l->right - l->left);
  6695. layout_boxes[node].w = dw;
  6696. layout_boxes[node].h = dh;
  6697. layout_boxes[node].valid = 1;
  6698. }
  6699. l->line_x += dw;
  6700. l->run_x = l->line_x;
  6701. if (l->line_h < dh)
  6702. l->line_h = dh;
  6703. }
  6704. /* An inline (or inline-block) <svg> is a replaced element in the text
  6705. * line, like an <img>: comment bubbles and arrows sit next to their label
  6706. * instead of starting a block of their own. */
  6707. static void add_svg_run(struct lay *l, unsigned int node,
  6708. const struct br_style *st, unsigned short href)
  6709. {
  6710. struct lay_run *r;
  6711. int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
  6712. if (lw < 8)
  6713. lw = 8;
  6714. cw = st->width_kind ? style_width_px(st, lw) : lw;
  6715. if (cw < 1)
  6716. cw = 1;
  6717. svg_size(node, st, cw, &dw, &dh);
  6718. if (dw > lw)
  6719. dw = lw;
  6720. ml = mp_px(st, 3, lw);
  6721. mr = mp_px(st, 1, lw);
  6722. if (ml < 0)
  6723. ml = 0;
  6724. if (mr < 0)
  6725. mr = 0;
  6726. if (l->line_x + ml + dw > l->line_right &&
  6727. (l->nruns > 0 || l->line_x > l->line_left))
  6728. flush_line(l);
  6729. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6730. flush_line(l);
  6731. if (l->nruns == 0) {
  6732. l->line_y = l->y;
  6733. l->line_h = 0;
  6734. start_line(l, st);
  6735. }
  6736. l->line_x += ml;
  6737. r = &l->runs[l->nruns++];
  6738. memset(r, 0, sizeof(*r));
  6739. r->gap = (unsigned short)(l->line_x > l->run_x ?
  6740. l->line_x - l->run_x : 0);
  6741. r->off = node;
  6742. r->color = st->color;
  6743. r->href = href;
  6744. r->img = RUN_SVG;
  6745. r->iw = (unsigned short)dw;
  6746. r->ih = (unsigned short)dh;
  6747. r->w = (unsigned short)dw;
  6748. r->font_px = st->font_px;
  6749. if (node < BR_MAX_NODES) {
  6750. layout_boxes[node].x = l->line_x;
  6751. layout_boxes[node].y = l->line_y;
  6752. layout_boxes[node].w = dw;
  6753. layout_boxes[node].h = dh;
  6754. layout_boxes[node].valid = 1;
  6755. }
  6756. l->line_x += dw + mr;
  6757. l->run_x = l->line_x;
  6758. if (l->line_h < dh)
  6759. l->line_h = dh;
  6760. }
  6761. static int text_width(struct lay *l, const char *s, unsigned int n,
  6762. const struct br_style *st)
  6763. {
  6764. return (int)face_text_width(l->ui, st, s, n);
  6765. }
  6766. /* Longest prefix that fits in maxw, at least one byte. */
  6767. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  6768. const struct br_style *st, int maxw)
  6769. {
  6770. unsigned int take = 0;
  6771. while (take < n) {
  6772. if (text_width(l, s, take + 1, st) > maxw)
  6773. break;
  6774. take++;
  6775. }
  6776. return take ? take : 1;
  6777. }
  6778. static void emit_word(struct lay *l, const char *s, unsigned int start,
  6779. unsigned int n, unsigned int base,
  6780. const struct br_style *st, unsigned short href)
  6781. {
  6782. int avail;
  6783. int w = text_width(l, s + start, n, st);
  6784. unsigned int off = start;
  6785. if (l->nruns == 0)
  6786. start_line(l, st);
  6787. avail = l->line_right - l->line_left;
  6788. if (st->nowrap) {
  6789. if (n)
  6790. add_run(l, base + start,
  6791. (unsigned short)n, st, href, 0);
  6792. return;
  6793. }
  6794. /* A padded/bordered one-word button can be a few pixels wider than
  6795. * the content box; keep it on one line instead of splitting it. */
  6796. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  6797. add_run(l, base + start,
  6798. (unsigned short)n, st, href, 0);
  6799. return;
  6800. }
  6801. if (l->line_x + w > l->line_right &&
  6802. (l->nruns > 0 || l->line_x > l->line_left)) {
  6803. flush_line(l);
  6804. start_line(l, st);
  6805. avail = l->line_right - l->line_left;
  6806. }
  6807. if (w <= avail) {
  6808. if (n)
  6809. add_run(l, base + start,
  6810. (unsigned short)n, st, href, 0);
  6811. return;
  6812. }
  6813. while (n > 0) {
  6814. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  6815. add_run(l, base + off,
  6816. (unsigned short)take, st, href, 0);
  6817. off += take;
  6818. n -= take;
  6819. if (n) {
  6820. flush_line(l);
  6821. start_line(l, st);
  6822. avail = l->line_right - l->line_left;
  6823. }
  6824. }
  6825. }
  6826. static void emit_text(struct lay *l, const char *s, unsigned int len,
  6827. const struct br_style *st, unsigned short href, int pre)
  6828. {
  6829. unsigned int i = 0;
  6830. unsigned int base;
  6831. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  6832. if (!s || !len)
  6833. return;
  6834. if (space_w <= 0)
  6835. space_w = 8;
  6836. if (l->nruns == 0)
  6837. start_line(l, st);
  6838. base = (unsigned int)(s - doc.text);
  6839. if (st->uppercase) {
  6840. char *p = (char *)s;
  6841. unsigned int j;
  6842. for (j = 0; j < len; j++)
  6843. if (p[j] >= 'a' && p[j] <= 'z')
  6844. p[j] = (char)(p[j] - 'a' + 'A');
  6845. }
  6846. if (pre) {
  6847. while (i < len) {
  6848. unsigned int start;
  6849. if (s[i] == '\n') {
  6850. flush_line(l);
  6851. start_line(l, st);
  6852. i++;
  6853. continue;
  6854. }
  6855. if (s[i] == ' ') {
  6856. if (l->line_x + space_w > l->line_right &&
  6857. (l->nruns > 0 || l->line_x > l->line_left)) {
  6858. flush_line(l);
  6859. start_line(l, st);
  6860. } else {
  6861. l->line_x += space_w;
  6862. }
  6863. i++;
  6864. continue;
  6865. }
  6866. start = i;
  6867. while (i < len && s[i] != ' ' && s[i] != '\n')
  6868. i++;
  6869. emit_word(l, s, start, i - start, base, st, href);
  6870. }
  6871. return;
  6872. }
  6873. while (i < len) {
  6874. unsigned int start, n;
  6875. if (s[i] == ' ') {
  6876. l->space_pending = 1;
  6877. i++;
  6878. continue;
  6879. }
  6880. start = i;
  6881. while (i < len && s[i] != ' ')
  6882. i++;
  6883. n = i - start;
  6884. if (l->space_pending &&
  6885. (l->nruns > 0 || l->line_x > l->line_left)) {
  6886. if (st->nowrap ||
  6887. l->line_x + space_w <= l->line_right)
  6888. l->line_x += space_w;
  6889. }
  6890. l->space_pending = 0;
  6891. emit_word(l, s, start, n, base, st, href);
  6892. }
  6893. }
  6894. static int list_index(unsigned int parent, unsigned int node)
  6895. {
  6896. unsigned int n = 0, i;
  6897. for (i = doc.nodes[parent].first; i && i != node;
  6898. i = doc.nodes[i].next)
  6899. if (doc.nodes[i].tag == BR_TAG_LI)
  6900. n++;
  6901. return (int)n + 1;
  6902. }
  6903. static void list_roman(char *m, unsigned int *n, int v, int upper,
  6904. unsigned int cap)
  6905. {
  6906. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  6907. 50, 40, 10, 9, 5, 4, 1 };
  6908. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  6909. "l", "xl", "x", "ix", "v", "iv", "i" };
  6910. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  6911. "L", "XL", "X", "IX", "V", "IV", "I" };
  6912. unsigned int i;
  6913. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  6914. while (v >= val[i] && *n + 1 < cap) {
  6915. const char *s = upper ? up[i] : lo[i];
  6916. while (*s && *n + 1 < cap)
  6917. m[(*n)++] = *s++;
  6918. v -= val[i];
  6919. }
  6920. }
  6921. }
  6922. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  6923. {
  6924. unsigned int n = 0;
  6925. if (style == BR_LIST_DISC) {
  6926. m[n++] = '-';
  6927. } else if (style == BR_LIST_CIRCLE) {
  6928. m[n++] = 'o';
  6929. } else if (style == BR_LIST_SQUARE) {
  6930. m[n++] = '+';
  6931. } else if (style == BR_LIST_LOWER_ALPHA ||
  6932. style == BR_LIST_UPPER_ALPHA) {
  6933. if (idx >= 1 && idx <= 26)
  6934. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  6935. 'A' : 'a') + idx - 1);
  6936. else
  6937. m[n++] = '?';
  6938. m[n++] = '.';
  6939. } else if (style == BR_LIST_LOWER_ROMAN ||
  6940. style == BR_LIST_UPPER_ROMAN) {
  6941. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  6942. if (n + 1 < cap)
  6943. m[n++] = '.';
  6944. } else {
  6945. s_append_dec(m, &n, (unsigned int)idx, cap);
  6946. if (n + 1 < cap)
  6947. m[n++] = '.';
  6948. }
  6949. m[n] = '\0';
  6950. }
  6951. /* A control the page styled itself (background, border or radius in author
  6952. * CSS -- `background:transparent;border:none` counts) is painted with that
  6953. * style, sized from its padding/height and keeps the page's text colour.
  6954. * Unstyled controls keep the ngui theme look. */
  6955. static int form_author_styled(const struct br_style *st)
  6956. {
  6957. int i;
  6958. if (st->bg_set)
  6959. return 1;
  6960. for (i = 0; i < 4; i++)
  6961. if (st->border_w[i] || st->radius[i])
  6962. return 1;
  6963. return 0;
  6964. }
  6965. /* Set by the layout when the control is stretched to its line: a flex item
  6966. * (its box width was assigned by the flex row) or a child of a flex column,
  6967. * whose default align-items: stretch makes inputs full width. */
  6968. static int form_fill_line;
  6969. static void add_form_run(struct lay *l, unsigned int node,
  6970. const struct br_style *st, unsigned short href)
  6971. {
  6972. struct form_state *fs = form_get(node, 1);
  6973. char shown[FORM_VALUE_MAX + 1];
  6974. char opt[64];
  6975. const char *text = "";
  6976. struct lay_run *r;
  6977. int kind = form_kind_of(node);
  6978. int disabled = form_disabled(node);
  6979. int author = form_author_styled(st);
  6980. int tw, w = 120, h = 20, i, line_w, pad_x, pad_y;
  6981. int ml = 0, mr = 0, mt = 0, mb = 0;
  6982. if (!fs)
  6983. return;
  6984. if (l->nruns == 0)
  6985. start_line(l, st);
  6986. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  6987. text = "";
  6988. w = 16;
  6989. h = 16;
  6990. } else if (kind == FORM_SELECT) {
  6991. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  6992. s_copy(opt, "Select", sizeof(opt));
  6993. text = opt;
  6994. w = 120;
  6995. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  6996. kind == FORM_RESET) {
  6997. if (fs->len)
  6998. text = fs->value;
  6999. else if (doc.nodes[node].tag == BR_TAG_BUTTON)
  7000. /* A <button>'s label is its content: an empty one
  7001. * (Docusaurus' sidebar caret, drawn by a CSS
  7002. * ::before icon) shows none. Only <input> buttons
  7003. * get the UA's default label. */
  7004. text = "";
  7005. else
  7006. text = kind == FORM_SUBMIT ? "Submit" :
  7007. kind == FORM_RESET ? "Reset" : "Button";
  7008. } else if (kind == FORM_PASSWORD) {
  7009. for (i = 0; i < fs->len; i++)
  7010. shown[i] = '*';
  7011. shown[fs->len] = '\0';
  7012. text = fs->len ? shown : br_placeholder(&doc, node);
  7013. } else {
  7014. if (fs->len)
  7015. text = fs->value;
  7016. else
  7017. text = br_placeholder(&doc, node);
  7018. if (kind == FORM_TEXTAREA) {
  7019. w = 180;
  7020. h = 40;
  7021. }
  7022. }
  7023. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  7024. line_w = l->line_right - l->line_left;
  7025. pad_x = mp_px(st, 7, line_w) + mp_px(st, 5, line_w) +
  7026. st->border_w[1] + st->border_w[3];
  7027. pad_y = mp_px(st, 4, line_w) + mp_px(st, 6, line_w) +
  7028. st->border_w[0] + st->border_w[2];
  7029. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  7030. /* Buttons are border-box in every UA stylesheet: an
  7031. * explicit width/height is the whole box. */
  7032. if (author || pad_x) {
  7033. w = tw + pad_x;
  7034. } else {
  7035. w = tw + 18;
  7036. if (w < 64)
  7037. w = 64;
  7038. }
  7039. if (st->width_kind)
  7040. w = style_width_px(st, line_w);
  7041. if (st->min_width_kind == 1 && w < (int)st->min_width)
  7042. w = st->min_width;
  7043. if (st->height_kind == 1)
  7044. h = st->height;
  7045. else if (author)
  7046. h = st->font_px + 6 + pad_y;
  7047. else
  7048. h = 22;
  7049. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  7050. kind == FORM_TEXTAREA) {
  7051. int fill = form_fill_line || st->display == BR_DISPLAY_BLOCK ||
  7052. st->display == BR_DISPLAY_FLEX;
  7053. int boxed = st->box_sizing ? 0 : pad_x;
  7054. if (st->width_kind)
  7055. w = style_width_px(st, line_w) + boxed;
  7056. else if (fill)
  7057. w = line_w - (l->line_x - l->line_left);
  7058. else
  7059. w = kind == FORM_TEXTAREA ? 180 : 120;
  7060. if (kind == FORM_TEXTAREA) {
  7061. const char *ra = br_find_attr(&doc, node, "rows");
  7062. int rows = 0;
  7063. int lh = st->line_h_px ? st->line_h_px :
  7064. st->font_px * 5 / 4;
  7065. while (ra && *ra >= '0' && *ra <= '9')
  7066. rows = rows * 10 + (*ra++ - '0');
  7067. if (rows < 1 || rows > 40)
  7068. rows = 2;
  7069. h = author ? rows * lh + pad_y : 40;
  7070. } else if (author) {
  7071. h = st->font_px + 8 + pad_y;
  7072. } else if (st->font_px + 8 > h) {
  7073. /* Taller fields for large text (min-height/padding
  7074. * on login pages): keep the box around the glyphs. */
  7075. h = st->font_px + 8;
  7076. }
  7077. if (st->height_kind == 1)
  7078. h = st->height + (st->box_sizing ? 0 : pad_y);
  7079. if (st->min_height_kind == 1 && h < (int)st->min_height)
  7080. h = st->min_height;
  7081. } else if (kind == FORM_SELECT) {
  7082. w = st->width_kind == 1 ? st->width : 120;
  7083. }
  7084. if (author) {
  7085. /* Inline margins (Google's `margin:11px 4px` between its
  7086. * two submit buttons). */
  7087. ml = mp_px(st, 3, line_w);
  7088. mr = mp_px(st, 1, line_w);
  7089. mt = mp_px(st, 0, line_w);
  7090. mb = mp_px(st, 2, line_w);
  7091. if (ml < 0 || ml > 64) ml = 0;
  7092. if (mr < 0 || mr > 64) mr = 0;
  7093. if (mt < 0 || mt > 64) mt = 0;
  7094. if (mb < 0 || mb > 64) mb = 0;
  7095. }
  7096. if (w > line_w - ml - mr)
  7097. w = line_w - ml - mr;
  7098. if (w < 8)
  7099. w = 8;
  7100. if (h > 400)
  7101. h = 400;
  7102. if (l->line_x + ml + w > l->line_right &&
  7103. (l->nruns > 0 || l->line_x > l->line_left))
  7104. flush_line(l);
  7105. if (l->nruns >= 96)
  7106. return;
  7107. if (l->nruns == 0) {
  7108. l->line_y = l->y;
  7109. l->line_h = 0;
  7110. start_line(l, st);
  7111. }
  7112. l->line_x += ml;
  7113. r = &l->runs[l->nruns++];
  7114. r->gap = (unsigned short)(l->line_x - l->run_x);
  7115. r->off = r->len = 0;
  7116. r->color = st->color;
  7117. r->href = href;
  7118. r->dy = (signed short)mt;
  7119. r->has_lit = 1;
  7120. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  7121. r->lit[i] = text[i];
  7122. r->lit[i] = '\0';
  7123. r->img = -2;
  7124. r->iw = (unsigned short)w;
  7125. r->ih = (unsigned short)h;
  7126. r->w = (unsigned short)w;
  7127. r->font_px = st->font_px;
  7128. r->bold = st->bold;
  7129. r->italic = st->italic;
  7130. r->mono = st->mono;
  7131. r->font_face = st->font_face;
  7132. r->underline = 0;
  7133. r->form = node + 1;
  7134. r->form_kind = (unsigned char)kind;
  7135. r->form_disabled = (unsigned char)disabled;
  7136. if (node < BR_MAX_NODES) {
  7137. layout_boxes[node].x = l->line_x;
  7138. layout_boxes[node].y = l->line_y + mt;
  7139. layout_boxes[node].w = w;
  7140. layout_boxes[node].h = h;
  7141. layout_boxes[node].valid = 1;
  7142. }
  7143. l->line_x += w;
  7144. l->run_x = l->line_x;
  7145. l->line_x += mr;
  7146. if (l->line_h < h + mt + mb)
  7147. l->line_h = h + mt + mb;
  7148. }
  7149. /* Background, border and corner radius of an author-styled control, the
  7150. * same decoration rules as a block box. */
  7151. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  7152. const struct br_style *st, int focused)
  7153. {
  7154. int rtl = css_radius(st, 0, box.w, box.h);
  7155. int rtr = css_radius(st, 1, box.w, box.h);
  7156. int rbr = css_radius(st, 2, box.w, box.h);
  7157. int rbl = css_radius(st, 3, box.w, box.h);
  7158. int bw = st->border_t[0] ? 0 : st->border_w[0];
  7159. (void)focused;
  7160. if (box.w <= 0 || box.h <= 0)
  7161. return;
  7162. if (rtl || rtr || rbr || rbl) {
  7163. if (bw > 0 && st->has_bg && st->border_c[0] != st->bg &&
  7164. box.w > bw * 2 && box.h > bw * 2) {
  7165. struct ngui_rect in = { box.x + bw, box.y + bw,
  7166. box.w - bw * 2,
  7167. box.h - bw * 2 };
  7168. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  7169. st->border_c[0]);
  7170. ngui_fill_round_rect(ui, in,
  7171. rtl > bw ? rtl - bw : 0,
  7172. rtr > bw ? rtr - bw : 0,
  7173. rbr > bw ? rbr - bw : 0,
  7174. rbl > bw ? rbl - bw : 0, st->bg);
  7175. } else if (st->has_bg) {
  7176. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  7177. st->bg);
  7178. } else if (bw > 0) {
  7179. ngui_frame_round(ui, box, rtl, rtr, rbr, rbl, bw,
  7180. st->border_c[0]);
  7181. }
  7182. return;
  7183. }
  7184. if (st->has_bg)
  7185. ngui_fill_rect(ui, box, st->bg);
  7186. if (st->border_w[0] || st->border_w[1] || st->border_w[2] ||
  7187. st->border_w[3])
  7188. draw_border_box(ui, box, st);
  7189. }
  7190. /* A poster wrapper is absolutely positioned over the media slot; the
  7191. * measured height of its picture is normally added back to the flow. When a
  7192. * loading-skeleton sibling already reserves that slot, adding both doubles
  7193. * the media height and pushes the article text a full screen down. */
  7194. static int has_skeleton_sibling(unsigned int node)
  7195. {
  7196. unsigned int p = doc.nodes[node].parent, c;
  7197. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  7198. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  7199. continue;
  7200. if (doc.nodes[c].class_off &&
  7201. contains_ci(doc.attrs + doc.nodes[c].class_off,
  7202. "skeleton"))
  7203. return 1;
  7204. }
  7205. return 0;
  7206. }
  7207. static void layout_children(struct lay *l, unsigned int parent,
  7208. const struct br_style *pst, int depth,
  7209. unsigned short link);
  7210. static void layout_flex_children(struct lay *l, unsigned int parent,
  7211. const struct br_style *pst, int depth,
  7212. unsigned short link);
  7213. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  7214. struct br_style *ps, int base);
  7215. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  7216. const struct br_style *ps, unsigned short link);
  7217. static void layout_grid_children(struct lay *l, unsigned int parent,
  7218. const struct br_style *pst, int depth,
  7219. unsigned short link);
  7220. static void layout_grid_auto(struct lay *l, unsigned int parent,
  7221. const struct br_style *pst, int depth,
  7222. unsigned short link);
  7223. static int flex_item_width(struct lay *l, unsigned int n,
  7224. const struct br_style *cs, int avail);
  7225. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  7226. const struct br_style *pst, int depth,
  7227. unsigned short link);
  7228. static void layout_table_row(struct lay *l, unsigned int row,
  7229. const struct br_style *pst, int depth,
  7230. unsigned short link);
  7231. static int table_has_rowspan(unsigned int table);
  7232. static void layout_table(struct lay *l, unsigned int table,
  7233. const struct br_style *st, int depth,
  7234. unsigned short link);
  7235. /* A flex container whose items are only inline spans is usually just a
  7236. * heading/icon pair. Our flex row positions such items without emitting
  7237. * their inline text in some deep page contexts; normal inline flow renders
  7238. * the same content correctly. */
  7239. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  7240. {
  7241. unsigned int c;
  7242. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7243. struct br_node *nd = &doc.nodes[c];
  7244. struct br_style cs;
  7245. if (nd->type == BR_NODE_TEXT)
  7246. continue;
  7247. br_style_for(&doc, c, pst, &cs);
  7248. if (cs.display == BR_DISPLAY_NONE)
  7249. continue;
  7250. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  7251. cs.width_kind || cs.has_bg ||
  7252. cs.border_w[0] || cs.border_w[1] ||
  7253. cs.border_w[2] || cs.border_w[3] ||
  7254. nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG)
  7255. return 1;
  7256. }
  7257. return 0;
  7258. }
  7259. static int css_radius(const struct br_style *st, int corner,
  7260. int w, int h)
  7261. {
  7262. int r = st->radius[corner];
  7263. if (r <= 0)
  7264. return 0;
  7265. if (r > w / 2)
  7266. r = w / 2;
  7267. if (r > h / 2)
  7268. r = h / 2;
  7269. return r;
  7270. }
  7271. /* ---- inline SVG ----
  7272. *
  7273. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  7274. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  7275. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  7276. * opacity and solid paint; a gradient paints the average of its stops) and
  7277. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  7278. #define SVG_CACHE_MAX 48
  7279. #define SVG_CACHE_PIXELS (640 * 1024)
  7280. #define SVG_MAX_POINTS 24576
  7281. struct svg_cache_ent {
  7282. unsigned int node;
  7283. int w, h;
  7284. unsigned short *px;
  7285. unsigned char *a;
  7286. unsigned int stamp;
  7287. };
  7288. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  7289. static unsigned int svg_cache_pixels, svg_cache_clock;
  7290. static struct svgr svg_geom;
  7291. static void *svg_geom_buf;
  7292. /* Current viewport in user units: percentage lengths resolve against it
  7293. * (the viewBox size, not the device pixels). */
  7294. static double svg_vp_w = 300, svg_vp_h = 150;
  7295. /* The layers live in the page heap: forget them before heap_reset(). */
  7296. static void svg_cache_clear(void)
  7297. {
  7298. memset(svg_cache, 0, sizeof(svg_cache));
  7299. svg_cache_pixels = 0;
  7300. svg_geom_buf = 0;
  7301. }
  7302. static int svg_name_is(const char *a, const char *b)
  7303. {
  7304. while (*a && *b) {
  7305. char x = *a, y = *b;
  7306. if (x >= 'A' && x <= 'Z')
  7307. x = (char)(x - 'A' + 'a');
  7308. if (x != y)
  7309. return 0;
  7310. a++;
  7311. b++;
  7312. }
  7313. return *a == *b;
  7314. }
  7315. static const char *svg_elem_name(unsigned int node)
  7316. {
  7317. const struct br_node *nd = &doc.nodes[node];
  7318. if (nd->name_off)
  7319. return doc.attrs + nd->name_off;
  7320. return br_tag_name(nd->tag);
  7321. }
  7322. /* A numeric attribute; a percentage resolves against `base`. */
  7323. static double svg_attr_num(unsigned int node, const char *name, double def,
  7324. double base)
  7325. {
  7326. const char *v = br_find_attr(&doc, node, name);
  7327. const char *p = v;
  7328. int ok = 0;
  7329. double x;
  7330. if (!v)
  7331. return def;
  7332. x = svgr_num(&p, &ok);
  7333. if (!ok)
  7334. return def;
  7335. if (*p == '%')
  7336. x = x * base / 100.0;
  7337. return x;
  7338. }
  7339. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  7340. static int svg_viewbox4(unsigned int node, double vb[4])
  7341. {
  7342. const char *v = br_find_attr(&doc, node, "viewbox");
  7343. const char *p = v;
  7344. int i, ok = 1;
  7345. if (!v)
  7346. return 0;
  7347. for (i = 0; i < 4 && ok; i++)
  7348. vb[i] = svgr_num(&p, &ok);
  7349. return ok && vb[2] > 0 && vb[3] > 0;
  7350. }
  7351. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  7352. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  7353. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  7354. double w, double h, double m[6])
  7355. {
  7356. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  7357. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  7358. int ax = 1, ay = 1;
  7359. if (par && contains_ci(par, "none")) {
  7360. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  7361. m[4] = -vb[0] * sx;
  7362. m[5] = -vb[1] * sy;
  7363. return;
  7364. }
  7365. if (par) {
  7366. if (contains_ci(par, "xmin"))
  7367. ax = 0;
  7368. else if (contains_ci(par, "xmax"))
  7369. ax = 2;
  7370. if (contains_ci(par, "ymin"))
  7371. ay = 0;
  7372. else if (contains_ci(par, "ymax"))
  7373. ay = 2;
  7374. }
  7375. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  7376. (sx < sy ? sx : sy);
  7377. tx = (w - vb[2] * s) * ax / 2.0;
  7378. ty = (h - vb[3] * s) * ay / 2.0;
  7379. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  7380. m[4] = tx - vb[0] * s;
  7381. m[5] = ty - vb[1] * s;
  7382. }
  7383. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  7384. * the paint attribute, then average the gradient's stops. */
  7385. static int svg_url_paint(unsigned int node, const char *attr,
  7386. unsigned short *color, unsigned int *alpha)
  7387. {
  7388. const char *v = 0, *h;
  7389. char id[64];
  7390. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  7391. for (k = 0; node && k < 32 && !v; k++) {
  7392. v = br_find_attr(&doc, node, attr);
  7393. if (!v) {
  7394. const char *style = br_find_attr(&doc, node, "style");
  7395. if (style && contains_ci(style, "url(#"))
  7396. v = strstr(style, "url(#");
  7397. }
  7398. if (v && !contains_ci(v, "url("))
  7399. v = 0;
  7400. node = doc.nodes[node].parent;
  7401. }
  7402. if (!v || !(h = strstr(v, "#")))
  7403. return 0;
  7404. h++;
  7405. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  7406. id[n++] = *h++;
  7407. id[n] = '\0';
  7408. g = br_find_id(&doc, id);
  7409. /* Follow href chains (a gradient that only references another one's
  7410. * stops), at most a few hops. */
  7411. for (k = 0; g && k < 4; k++) {
  7412. unsigned int gi = g - 1;
  7413. const char *ref;
  7414. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  7415. const char *nm, *sc, *so;
  7416. unsigned short col = 0;
  7417. double op = 1;
  7418. if (doc.nodes[c].type != BR_NODE_ELEM)
  7419. continue;
  7420. nm = svg_elem_name(c);
  7421. if (!svg_name_is(nm, "stop"))
  7422. continue;
  7423. sc = br_find_attr(&doc, c, "stop-color");
  7424. so = br_find_attr(&doc, c, "stop-opacity");
  7425. {
  7426. const char *st = br_find_attr(&doc, c, "style");
  7427. const char *q;
  7428. if (st && (q = strstr(st, "stop-color:")) != 0)
  7429. sc = q + 11;
  7430. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  7431. so = q + 13;
  7432. }
  7433. if (sc) {
  7434. unsigned int L = 0;
  7435. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  7436. L++;
  7437. if (!br_parse_color(sc, L, &col))
  7438. col = 0;
  7439. }
  7440. if (so) {
  7441. const char *p = so;
  7442. int ok = 0;
  7443. double x = svgr_num(&p, &ok);
  7444. if (ok)
  7445. op = x < 0 ? 0 : x > 1 ? 1 : x;
  7446. }
  7447. sr += (col >> 11) & 31;
  7448. sg += (col >> 5) & 63;
  7449. sb += col & 31;
  7450. sa += (unsigned int)(op * 255);
  7451. cnt++;
  7452. }
  7453. if (cnt)
  7454. break;
  7455. ref = br_find_attr(&doc, gi, "href");
  7456. if (!ref)
  7457. ref = br_find_attr(&doc, gi, "xlink:href");
  7458. if (!ref || ref[0] != '#')
  7459. break;
  7460. g = br_find_id(&doc, ref + 1);
  7461. }
  7462. if (!cnt)
  7463. return 0;
  7464. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  7465. (sb / cnt));
  7466. *alpha = sa / cnt;
  7467. return 1;
  7468. }
  7469. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  7470. unsigned short *color, unsigned int *alpha)
  7471. {
  7472. int mode = fill ? st->fill_mode : st->stroke_mode;
  7473. const char *op = br_find_attr(&doc, node,
  7474. fill ? "fill-opacity" : "stroke-opacity");
  7475. *alpha = 255;
  7476. switch (mode) {
  7477. case BR_PAINT_UNSET:
  7478. if (!fill)
  7479. return 0;
  7480. *color = 0;
  7481. break;
  7482. case BR_PAINT_COLOR:
  7483. *color = fill ? st->fill : st->stroke;
  7484. break;
  7485. case BR_PAINT_CURRENT:
  7486. *color = st->color;
  7487. break;
  7488. case BR_PAINT_URL:
  7489. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  7490. alpha))
  7491. return 0;
  7492. break;
  7493. default:
  7494. return 0;
  7495. }
  7496. if (op) {
  7497. const char *p = op;
  7498. int ok = 0;
  7499. double x = svgr_num(&p, &ok);
  7500. if (ok)
  7501. *alpha = (unsigned int)(*alpha *
  7502. (x < 0 ? 0 : x > 1 ? 1 : x));
  7503. }
  7504. return *alpha > 0;
  7505. }
  7506. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7507. const double m[6], const struct br_style *pst,
  7508. unsigned int alpha, int depth);
  7509. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  7510. const double m[6], const struct br_style *st,
  7511. unsigned int alpha, int depth)
  7512. {
  7513. unsigned int c;
  7514. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  7515. if (doc.nodes[c].type == BR_NODE_ELEM)
  7516. svg_draw_node(L, c, m, st, alpha, depth + 1);
  7517. }
  7518. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7519. const double pm[6], const struct br_style *pst,
  7520. unsigned int alpha, int depth)
  7521. {
  7522. struct br_style st;
  7523. const char *nm = svg_elem_name(node);
  7524. const char *tf;
  7525. double m[6];
  7526. unsigned short color;
  7527. unsigned int pa;
  7528. int shape = 0, fillable = 1;
  7529. if (depth > 24 || !nm)
  7530. return;
  7531. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  7532. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  7533. svg_name_is(nm, "lineargradient") ||
  7534. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  7535. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  7536. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  7537. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  7538. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  7539. svg_name_is(nm, "foreignobject"))
  7540. return;
  7541. br_style_for(&doc, node, pst, &st);
  7542. if (st.display == BR_DISPLAY_NONE)
  7543. return;
  7544. memcpy(m, pm, sizeof(m));
  7545. tf = br_find_attr(&doc, node, "transform");
  7546. if (tf)
  7547. svgr_transform(m, tf);
  7548. {
  7549. const char *op = br_find_attr(&doc, node, "opacity");
  7550. if (op) {
  7551. const char *p = op;
  7552. int ok = 0;
  7553. double x = svgr_num(&p, &ok);
  7554. if (ok)
  7555. alpha = (unsigned int)(alpha *
  7556. (x < 0 ? 0 :
  7557. x > 1 ? 1 : x));
  7558. }
  7559. }
  7560. if (!alpha)
  7561. return;
  7562. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  7563. svg_name_is(nm, "switch")) {
  7564. svg_draw_children(L, node, m, &st, alpha, depth);
  7565. return;
  7566. }
  7567. if (svg_name_is(nm, "svg")) {
  7568. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  7569. y = svg_attr_num(node, "y", 0, 0);
  7570. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7571. t[4] = x;
  7572. t[5] = y;
  7573. svgr_mat_mul(m, m, t);
  7574. double ow = svg_vp_w, oh = svg_vp_h;
  7575. if (svg_viewbox4(node, vb)) {
  7576. double w = svg_attr_num(node, "width", vb[2], ow);
  7577. double h = svg_attr_num(node, "height", vb[3], oh);
  7578. double vm[6];
  7579. svg_viewport_matrix(node, vb, w, h, vm);
  7580. svgr_mat_mul(m, m, vm);
  7581. svg_vp_w = vb[2];
  7582. svg_vp_h = vb[3];
  7583. }
  7584. svg_draw_children(L, node, m, &st, alpha, depth);
  7585. svg_vp_w = ow;
  7586. svg_vp_h = oh;
  7587. return;
  7588. }
  7589. if (svg_name_is(nm, "use")) {
  7590. const char *ref = br_find_attr(&doc, node, "href");
  7591. unsigned int tgt;
  7592. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7593. if (!ref)
  7594. ref = br_find_attr(&doc, node, "xlink:href");
  7595. if (!ref || ref[0] != '#')
  7596. return;
  7597. tgt = br_find_id(&doc, ref + 1);
  7598. if (!tgt || tgt - 1 == node)
  7599. return;
  7600. tgt--;
  7601. t[4] = svg_attr_num(node, "x", 0, 0);
  7602. t[5] = svg_attr_num(node, "y", 0, 0);
  7603. svgr_mat_mul(m, m, t);
  7604. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  7605. double vb[4];
  7606. double ow = svg_vp_w, oh = svg_vp_h;
  7607. if (svg_viewbox4(tgt, vb)) {
  7608. double w = svg_attr_num(node, "width", vb[2],
  7609. ow);
  7610. double h = svg_attr_num(node, "height", vb[3],
  7611. oh);
  7612. double vm[6];
  7613. svg_viewport_matrix(tgt, vb, w, h, vm);
  7614. svgr_mat_mul(m, m, vm);
  7615. svg_vp_w = vb[2];
  7616. svg_vp_h = vb[3];
  7617. }
  7618. svg_draw_children(L, tgt, m, &st, alpha, depth);
  7619. svg_vp_w = ow;
  7620. svg_vp_h = oh;
  7621. } else {
  7622. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  7623. }
  7624. return;
  7625. }
  7626. svgr_reset(&svg_geom, m);
  7627. if (svg_name_is(nm, "path")) {
  7628. const char *d = br_find_attr(&doc, node, "d");
  7629. if (d) {
  7630. svgr_path(&svg_geom, d);
  7631. shape = 1;
  7632. }
  7633. } else if (svg_name_is(nm, "rect")) {
  7634. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  7635. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  7636. double rx = svg_attr_num(node, "rx", -1, w);
  7637. double ry = svg_attr_num(node, "ry", -1, h);
  7638. if (rx < 0)
  7639. rx = ry < 0 ? 0 : ry;
  7640. if (ry < 0)
  7641. ry = rx;
  7642. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  7643. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  7644. shape = 1;
  7645. } else if (svg_name_is(nm, "circle")) {
  7646. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  7647. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7648. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  7649. shape = 1;
  7650. } else if (svg_name_is(nm, "ellipse")) {
  7651. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7652. svg_attr_num(node, "cy", 0, svg_vp_h),
  7653. svg_attr_num(node, "rx", 0, svg_vp_w),
  7654. svg_attr_num(node, "ry", 0, svg_vp_h));
  7655. shape = 1;
  7656. } else if (svg_name_is(nm, "line")) {
  7657. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  7658. svg_attr_num(node, "y1", 0, svg_vp_h));
  7659. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  7660. svg_attr_num(node, "y2", 0, svg_vp_h));
  7661. shape = 1;
  7662. fillable = 0;
  7663. } else if (svg_name_is(nm, "polyline") ||
  7664. svg_name_is(nm, "polygon")) {
  7665. const char *pts = br_find_attr(&doc, node, "points");
  7666. if (pts) {
  7667. svgr_points(&svg_geom, pts,
  7668. svg_name_is(nm, "polygon"));
  7669. shape = 1;
  7670. }
  7671. }
  7672. if (!shape)
  7673. return;
  7674. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  7675. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  7676. st.fill_evenodd);
  7677. if (svg_paint(node, &st, 0, &color, &pa)) {
  7678. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  7679. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7680. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  7681. }
  7682. }
  7683. /* <text> elements: drawn straight onto the page every frame (the glyph
  7684. * renderer targets the ngui canvas, not a layer). x/y map through the
  7685. * accumulated transform; the font size scales with it. */
  7686. static void svg_draw_text(struct ngui *ui, unsigned int node,
  7687. const double pm[6], const struct br_style *pst,
  7688. int ox, int oy, int depth)
  7689. {
  7690. unsigned int c;
  7691. if (depth > 24)
  7692. return;
  7693. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7694. struct br_style st;
  7695. const char *nm, *tf;
  7696. double m[6];
  7697. if (doc.nodes[c].type != BR_NODE_ELEM)
  7698. continue;
  7699. nm = svg_elem_name(c);
  7700. if (!nm || svg_name_is(nm, "defs") ||
  7701. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  7702. svg_name_is(nm, "clippath"))
  7703. continue;
  7704. br_style_for(&doc, c, pst, &st);
  7705. if (st.display == BR_DISPLAY_NONE)
  7706. continue;
  7707. memcpy(m, pm, sizeof(m));
  7708. tf = br_find_attr(&doc, c, "transform");
  7709. if (tf)
  7710. svgr_transform(m, tf);
  7711. if (svg_name_is(nm, "text")) {
  7712. unsigned int t = doc.nodes[c].first;
  7713. const char *s;
  7714. unsigned int n, tw;
  7715. double x = svg_attr_num(c, "x", 0, 0),
  7716. y = svg_attr_num(c, "y", 0, 0);
  7717. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7718. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  7719. int tx, ty, anchor;
  7720. unsigned short col;
  7721. unsigned int pa;
  7722. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  7723. continue;
  7724. if (px < 6)
  7725. px = 6;
  7726. if (px > 72)
  7727. px = 72;
  7728. if (!svg_paint(c, &st, 1, &col, &pa))
  7729. continue;
  7730. s = doc.text + doc.nodes[t].text_off;
  7731. n = doc.nodes[t].text_len;
  7732. st.font_px = (unsigned char)px;
  7733. tw = face_text_width(ui, &st, s, n);
  7734. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  7735. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  7736. ngui_text_ascent_face(ui, style_face(&st), px,
  7737. st.mono);
  7738. anchor = st.align;
  7739. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  7740. anchor = BR_ALIGN_CENTER;
  7741. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  7742. anchor = BR_ALIGN_RIGHT;
  7743. if (anchor == BR_ALIGN_CENTER)
  7744. tx -= (int)tw / 2;
  7745. else if (anchor == BR_ALIGN_RIGHT)
  7746. tx -= (int)tw;
  7747. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  7748. col, px, st.bold, st.italic,
  7749. st.mono);
  7750. } else {
  7751. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  7752. }
  7753. }
  7754. }
  7755. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  7756. {
  7757. double vb[4];
  7758. if (svg_viewbox4(node, vb)) {
  7759. svg_viewport_matrix(node, vb, w, h, m);
  7760. } else {
  7761. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  7762. }
  7763. }
  7764. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  7765. const struct br_style *st)
  7766. {
  7767. struct svg_cache_ent *e = 0;
  7768. struct svgr_layer L;
  7769. double m[6];
  7770. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  7771. svg_cache_clock++;
  7772. for (i = 0; i < SVG_CACHE_MAX; i++)
  7773. if (svg_cache[i].px && svg_cache[i].node == node &&
  7774. svg_cache[i].w == w && svg_cache[i].h == h) {
  7775. svg_cache[i].stamp = svg_cache_clock;
  7776. return &svg_cache[i];
  7777. }
  7778. if (need > SVG_CACHE_PIXELS)
  7779. return 0;
  7780. /* Evict least recently used layers until this one fits. */
  7781. for (;;) {
  7782. struct svg_cache_ent *lru = 0, *free_slot = 0;
  7783. for (i = 0; i < SVG_CACHE_MAX; i++) {
  7784. if (!svg_cache[i].px) {
  7785. if (!free_slot)
  7786. free_slot = &svg_cache[i];
  7787. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  7788. lru = &svg_cache[i];
  7789. }
  7790. }
  7791. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  7792. e = free_slot;
  7793. break;
  7794. }
  7795. if (!lru)
  7796. return 0;
  7797. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  7798. free(lru->px);
  7799. free(lru->a);
  7800. memset(lru, 0, sizeof(*lru));
  7801. }
  7802. if (!svg_geom_buf) {
  7803. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7804. if (!svg_geom_buf)
  7805. return 0;
  7806. }
  7807. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  7808. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  7809. e->a = (unsigned char *)calloc(need, 1);
  7810. if (!e->px || !e->a) {
  7811. free(e->px);
  7812. free(e->a);
  7813. memset(e, 0, sizeof(*e));
  7814. return 0;
  7815. }
  7816. e->node = node;
  7817. e->w = w;
  7818. e->h = h;
  7819. e->stamp = svg_cache_clock;
  7820. svg_cache_pixels += need;
  7821. L.px = e->px;
  7822. L.a = e->a;
  7823. L.w = w;
  7824. L.h = h;
  7825. svg_root_matrix(node, w, h, m);
  7826. {
  7827. double vb[4];
  7828. if (svg_viewbox4(node, vb)) {
  7829. svg_vp_w = vb[2];
  7830. svg_vp_h = vb[3];
  7831. } else {
  7832. svg_vp_w = w;
  7833. svg_vp_h = h;
  7834. }
  7835. }
  7836. svg_draw_children(&L, node, m, st, 255, 0);
  7837. return e;
  7838. }
  7839. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  7840. *
  7841. * The markup is parsed into a detached subtree of the page document and
  7842. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  7843. * bitmap, which then behaves like any decoded image. currentColor is
  7844. * black (an image has no inherited text colour); <text> is not drawn. */
  7845. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  7846. {
  7847. unsigned int i = 0;
  7848. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  7849. i = 3;
  7850. while (i < len) {
  7851. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  7852. d[i] == '\r' || d[i] == '\n'))
  7853. i++;
  7854. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  7855. return 1;
  7856. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  7857. i += 4;
  7858. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  7859. i++;
  7860. i += 3;
  7861. continue;
  7862. }
  7863. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  7864. while (i < len && d[i] != '>')
  7865. i++;
  7866. i++;
  7867. continue;
  7868. }
  7869. return 0;
  7870. }
  7871. return 0;
  7872. }
  7873. static int svg_len_attr(unsigned int node, const char *name)
  7874. {
  7875. const char *v = br_find_attr(&doc, node, name);
  7876. int n = 0, any = 0;
  7877. if (!v)
  7878. return 0;
  7879. while (*v == ' ')
  7880. v++;
  7881. while (*v >= '0' && *v <= '9') {
  7882. n = n * 10 + (*v++ - '0');
  7883. any = 1;
  7884. }
  7885. if (*v == '.')
  7886. while (*++v >= '0' && *v <= '9')
  7887. ;
  7888. if (!any || *v == '%')
  7889. return 0;
  7890. return n;
  7891. }
  7892. static int svg_decode_image(const unsigned char *data, unsigned int len,
  7893. struct br_image *bi, int box_w, int box_h)
  7894. {
  7895. unsigned int holder, svg = 0, c, need, i;
  7896. struct br_style base = base_style(), st;
  7897. struct svgr_layer L;
  7898. double vb[4], m[6];
  7899. int w, h, have_vb, nat_w, nat_h;
  7900. holder = br_create_element(&doc, "div", 3);
  7901. if (!holder) {
  7902. s_copy(bi->err, "page is full", sizeof(bi->err));
  7903. return -1;
  7904. }
  7905. holder--;
  7906. br_set_inner_html(&doc, holder, (const char *)data, len);
  7907. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  7908. if (doc.nodes[c].type == BR_NODE_ELEM &&
  7909. doc.nodes[c].tag == BR_TAG_SVG) {
  7910. svg = c;
  7911. break;
  7912. }
  7913. if (!svg) {
  7914. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  7915. return -1;
  7916. }
  7917. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  7918. w = svg_len_attr(svg, "width");
  7919. h = svg_len_attr(svg, "height");
  7920. if (box_w > 0 && box_h > 0) {
  7921. w = box_w;
  7922. h = box_h;
  7923. } else if (!w && !h) {
  7924. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  7925. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  7926. } else if (!w) {
  7927. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  7928. } else if (!h) {
  7929. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  7930. }
  7931. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  7932. * so CSS scaling stays crisp. */
  7933. nat_w = w;
  7934. nat_h = h;
  7935. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  7936. w *= 2;
  7937. h *= 2;
  7938. }
  7939. if (w > BR_IMG_LAYOUT_W) {
  7940. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  7941. w = BR_IMG_LAYOUT_W;
  7942. }
  7943. if (h > 2048)
  7944. h = 2048;
  7945. if (w < 1)
  7946. w = 1;
  7947. if (h < 1)
  7948. h = 1;
  7949. need = (unsigned int)w * (unsigned int)h;
  7950. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  7951. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  7952. return -1;
  7953. }
  7954. if (!svg_geom_buf) {
  7955. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7956. if (!svg_geom_buf) {
  7957. s_copy(bi->err, "out of memory", sizeof(bi->err));
  7958. return -1;
  7959. }
  7960. }
  7961. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  7962. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  7963. L.a = (unsigned char *)calloc(need, 1);
  7964. if (!L.px || !L.a) {
  7965. free(L.px);
  7966. free(L.a);
  7967. s_copy(bi->err, "out of memory", sizeof(bi->err));
  7968. return -1;
  7969. }
  7970. for (i = 0; i < need; i++)
  7971. L.px[i] = 0xFFFF;
  7972. L.w = w;
  7973. L.h = h;
  7974. base.color = 0x0000;
  7975. br_style_for(&doc, svg, &base, &st);
  7976. svg_root_matrix(svg, w, h, m);
  7977. if (!have_vb && nat_w > 0 && nat_h > 0) {
  7978. /* No viewBox: user units are CSS pixels of the natural size,
  7979. * so the up-to-4x raster (and a box size) must scale them.
  7980. * A 40x20 icon used to fill only the top-left quarter of its
  7981. * 160x80 bitmap and was drawn at a quarter of its size. */
  7982. m[0] = (double)w / nat_w;
  7983. m[3] = (double)h / nat_h;
  7984. }
  7985. svg_vp_w = have_vb ? vb[2] : nat_w;
  7986. svg_vp_h = have_vb ? vb[3] : nat_h;
  7987. svg_draw_children(&L, svg, m, &st, 255, 0);
  7988. bi->native_w = nat_w;
  7989. bi->native_h = nat_h;
  7990. bi->img.format = 0;
  7991. bi->img.w = (unsigned int)w;
  7992. bi->img.h = (unsigned int)h;
  7993. bi->img.px = L.px;
  7994. bi->img.alpha = L.a;
  7995. bi->img.flags = 0;
  7996. bi->state = 1;
  7997. image_pixels += need;
  7998. return 0;
  7999. }
  8000. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  8001. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  8002. int *out_w, int *out_h)
  8003. {
  8004. double vb[4];
  8005. int has_vb = svg_viewbox4(node, vb);
  8006. double aw = svg_attr_num(node, "width", -1, cw);
  8007. double ah = svg_attr_num(node, "height", -1, 0);
  8008. int w, h;
  8009. if (st->width_kind)
  8010. w = cw;
  8011. else if (aw > 0)
  8012. w = (int)(aw + 0.5);
  8013. else if (st->height_kind == 1 && has_vb)
  8014. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  8015. else if (ah > 0 && has_vb)
  8016. w = (int)(ah * vb[2] / vb[3] + 0.5);
  8017. else if (has_vb)
  8018. w = cw;
  8019. else
  8020. w = 300;
  8021. if (st->max_width_kind == 1 && w > st->max_width)
  8022. w = st->max_width;
  8023. if (w > cw && cw > 0 && !(aw > 0))
  8024. w = cw;
  8025. if (w < 1)
  8026. w = 1;
  8027. if (w > 2000)
  8028. w = 2000;
  8029. if (st->height_kind == 1)
  8030. h = st->height;
  8031. else if (ah > 0)
  8032. h = (int)(ah + 0.5);
  8033. else if (has_vb)
  8034. h = (int)(w * vb[3] / vb[2] + 0.5);
  8035. else
  8036. h = 150;
  8037. if (h < 1)
  8038. h = 1;
  8039. if (h > 1400)
  8040. h = 1400;
  8041. *out_w = w;
  8042. *out_h = h;
  8043. }
  8044. static void svg_paint_box(struct ngui *ui, unsigned int node,
  8045. const struct br_style *st, int x, int y, int w, int h)
  8046. {
  8047. struct svg_cache_ent *e;
  8048. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  8049. int cx0, cy0, cx1, cy1, px, py;
  8050. double m[6];
  8051. if (ui->nclip > 0)
  8052. clip = ui->clip[ui->nclip - 1];
  8053. cx0 = r.x > clip.x ? r.x : clip.x;
  8054. cy0 = r.y > clip.y ? r.y : clip.y;
  8055. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  8056. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  8057. if (cx0 >= cx1 || cy0 >= cy1)
  8058. return;
  8059. e = svg_layer(node, w, h, st);
  8060. if (e) {
  8061. for (py = cy0; py < cy1; py++) {
  8062. unsigned int srow = (unsigned int)(py - y) *
  8063. (unsigned int)w;
  8064. unsigned short *dst = ui->px + py * ui->w;
  8065. for (px = cx0; px < cx1; px++) {
  8066. unsigned int si = srow + (unsigned int)(px - x);
  8067. unsigned int a = e->a[si];
  8068. if (!a)
  8069. continue;
  8070. dst[px] = a >= 255 ? e->px[si] :
  8071. blend_rgb565(dst[px], e->px[si], a);
  8072. }
  8073. }
  8074. }
  8075. svg_root_matrix(node, w, h, m);
  8076. ngui_push_clip(ui, r);
  8077. svg_draw_text(ui, node, m, st, x, y, 0);
  8078. ngui_pop_clip(ui);
  8079. }
  8080. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  8081. * keep using add_image_run(); this covers the CSS `position:absolute;
  8082. * width:100%` poster pattern used by news sites. */
  8083. static void image_block_size(unsigned int node, const struct br_style *st,
  8084. int cbw, int *out_w, int *out_h)
  8085. {
  8086. struct br_node *nd = &doc.nodes[node];
  8087. int idx = nd->img_index;
  8088. int iw = 0, ih = 0, w, h, aw, ah;
  8089. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  8090. iw = (int)images[idx].img.w;
  8091. ih = (int)images[idx].img.h;
  8092. if (iw <= 0 || ih <= 0) {
  8093. iw = (int)images[idx].native_w;
  8094. ih = (int)images[idx].native_h;
  8095. }
  8096. }
  8097. if (st->width_kind)
  8098. w = style_width_px(st, cbw);
  8099. else if (nd->width_attr)
  8100. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  8101. (int)nd->width_attr;
  8102. else if (nd->height_attr && !nd->height_pct && iw && ih)
  8103. w = iw * (int)nd->height_attr / ih;
  8104. else if (iw)
  8105. w = iw;
  8106. else
  8107. w = 64;
  8108. /* max-width/min-width against the containing block: Tailwind's
  8109. * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
  8110. * 300x300 thumbnail to its 75 px avatar box. */
  8111. if (st->max_width_kind) {
  8112. int mw = st->max_width_kind == 3 ?
  8113. cbw * st->max_width_calc_pct / 100 +
  8114. st->max_width_calc_px :
  8115. st->max_width_kind == 2 ?
  8116. cbw * (int)st->max_width / 100 : (int)st->max_width;
  8117. if (mw > 0 && w > mw)
  8118. w = mw;
  8119. }
  8120. if (st->min_width_kind) {
  8121. int mn = st->min_width_kind == 3 ?
  8122. cbw * st->min_width_calc_pct / 100 +
  8123. st->min_width_calc_px :
  8124. st->min_width_kind == 2 ?
  8125. cbw * (int)st->min_width / 100 : (int)st->min_width;
  8126. if (mn > w)
  8127. w = mn;
  8128. }
  8129. if (w < 8)
  8130. w = 8;
  8131. if (cbw > 0 && w > cbw)
  8132. w = cbw;
  8133. /* Without a CSS height the attributes (or the bitmap) only give the
  8134. * aspect ratio: a width clamped by max-width scales the height too,
  8135. * instead of letterboxing the image into its attribute height. */
  8136. aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
  8137. ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
  8138. if (st->height_kind)
  8139. h = style_height_px(st, cbw);
  8140. else if (aw > 0 && ah > 0)
  8141. h = w * ah / aw;
  8142. else if (nd->height_attr)
  8143. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  8144. (int)nd->height_attr;
  8145. else
  8146. h = 64;
  8147. if (h < 8)
  8148. h = 8;
  8149. *out_w = w;
  8150. *out_h = h;
  8151. }
  8152. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  8153. int dw, int dh)
  8154. {
  8155. int idx = doc.nodes[node].img_index;
  8156. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  8157. struct img_image *src = image_display_get(&images[idx], dw, dh);
  8158. struct img_blit b;
  8159. if (!src)
  8160. src = &images[idx].img;
  8161. b.dst = l->ui->px;
  8162. b.dst_w = l->ui->w;
  8163. b.dst_h = l->ui->h;
  8164. b.clip_x = page_rect.x;
  8165. b.clip_y = page_rect.y;
  8166. b.clip_w = page_rect.w - 12;
  8167. b.clip_h = page_rect.h;
  8168. b.x = x;
  8169. b.y = y;
  8170. b.scale = ((unsigned int)dw << 16) / src->w;
  8171. b.bg = ui.theme.bg;
  8172. b.bg2 = ui.theme.bg;
  8173. b.dst_a = 0;
  8174. /* OVER_DST is only needed for an alpha source; an opaque one can
  8175. * take img_draw's 1:1 copy path. */
  8176. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  8177. img_draw(src, &b);
  8178. } else if (l->draw) {
  8179. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  8180. 0xD69A);
  8181. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  8182. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  8183. }
  8184. }
  8185. static void layout_block(struct lay *l, unsigned int node,
  8186. const struct br_style *st, int depth,
  8187. unsigned short link)
  8188. {
  8189. int old_left = l->left, old_right = l->right, old_align = l->align;
  8190. int parent_cb_h = l->cb_h;
  8191. int saved_parent_top = l->parent_top;
  8192. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  8193. int saved_cb_top = l->cb_top;
  8194. int top, l0, r0;
  8195. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  8196. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  8197. int deco_w, deco_h, content_w, content_h, box_h;
  8198. int img_dh = 0;
  8199. int definite_w = 0;
  8200. int normal_top = 0;
  8201. int rel_dx = 0, rel_dy = 0;
  8202. int clip_pushed = 0;
  8203. struct ngui_rect clip_rect;
  8204. /* A DOM level costs about two depth units (layout_block ->
  8205. * layout_children), so 48 covers a ~24-level page. Real news pages
  8206. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  8207. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  8208. return;
  8209. flow_y = l->y;
  8210. flow_left = l->left;
  8211. flow_right = l->right;
  8212. positioned = st->pos == 1 || st->pos == 2;
  8213. relative = st->pos == 3;
  8214. sticky = st->pos == 4;
  8215. shifted = relative || sticky || st->transform_set;
  8216. if (positioned) {
  8217. int def_w = st->width_kind == 1 ? st->width : -1;
  8218. if (st->pos == 2) {
  8219. int avail_w = page_rect.w - 12;
  8220. if (st->right_set && def_w >= 0)
  8221. l->left = page_rect.x + avail_w - st->right -
  8222. def_w;
  8223. else
  8224. l->left = page_rect.x +
  8225. (st->left_set ? st->left : 0);
  8226. l->right = def_w >= 0 ? l->left + def_w :
  8227. page_rect.x + avail_w;
  8228. if (st->bottom_set && st->height_kind)
  8229. l->y = page_rect.y + page_rect.h -
  8230. st->bottom -
  8231. style_height_px(st, page_rect.w);
  8232. else
  8233. l->y = page_rect.y +
  8234. (st->top_set ? st->top : 0);
  8235. } else {
  8236. int left = flow_left + (st->left_set ? st->left : 0);
  8237. unsigned int parent = doc.nodes[node].parent;
  8238. if (st->right_set && def_w >= 0)
  8239. left = flow_right - st->right - def_w;
  8240. l->left = left;
  8241. l->right = def_w >= 0 ? left + def_w :
  8242. flow_right +
  8243. (st->left_set ? st->left : 0);
  8244. l->y = flow_y + (st->top_set ? st->top : 0);
  8245. if (st->bottom_set && st->height_kind &&
  8246. parent < BR_MAX_NODES && block_h[parent] > 0)
  8247. l->y = flow_y + block_h[parent] - st->bottom -
  8248. style_height_px(st, old_right - old_left);
  8249. }
  8250. /* `left: 100%` parks a box (Docusaurus' "Skip to main
  8251. * content" link) past the containing block's right edge
  8252. * until it is focused. An auto width then has no room: it
  8253. * used to collapse to 8 px and wrap one word per line into a
  8254. * tall column painted over the page. Lay it out at the
  8255. * containing block's width so it stays one line and
  8256. * overflows (off-screen) like in a real browser. */
  8257. if (def_w < 0 && l->right - l->left < 8) {
  8258. int avail = st->pos == 2 ? page_rect.w - 12 :
  8259. flow_right - flow_left;
  8260. l->right = l->left + (avail > 8 ? avail : 8);
  8261. }
  8262. old_left = l->left;
  8263. old_right = l->right;
  8264. } else if (relative) {
  8265. rel_dx = st->left_set ? st->left :
  8266. (st->right_set ? -st->right : 0);
  8267. rel_dy = st->top_set ? st->top :
  8268. (st->bottom_set ? -st->bottom : 0);
  8269. }
  8270. if (st->transform_set) {
  8271. rel_dx += st->tx;
  8272. rel_dy += st->ty;
  8273. }
  8274. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  8275. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  8276. doc.nodes[node].tag == BR_TAG_SELECT ||
  8277. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  8278. !button_has_elements(node)) {
  8279. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  8280. s_eq(br_type(&doc, node), "hidden"))
  8281. return;
  8282. /* Reached as a block-level box (a flex item): the control
  8283. * fills the box the caller assigned, and its line is flushed
  8284. * here; flex layout resets the run list for the next item, so
  8285. * a queued run would never be drawn. */
  8286. form_fill_line = 1;
  8287. add_form_run(l, node, st, link);
  8288. form_fill_line = 0;
  8289. flush_line(l);
  8290. return;
  8291. }
  8292. flush_line(l);
  8293. cbw = old_right - old_left;
  8294. if (cbw < 8)
  8295. cbw = 8;
  8296. l->y += mp_px(st, 0, cbw);
  8297. top = l->y;
  8298. ml = mp_px(st, 3, cbw);
  8299. mr = mp_px(st, 1, cbw);
  8300. bl = st->border_w[3];
  8301. br = st->border_w[1];
  8302. pl = mp_px(st, 7, cbw);
  8303. pr = mp_px(st, 5, cbw);
  8304. bt = st->border_w[0];
  8305. bb = st->border_w[2];
  8306. pt = mp_px(st, 4, cbw);
  8307. pb = mp_px(st, 6, cbw);
  8308. deco_w = bl + br + pl + pr;
  8309. deco_h = bt + bb + pt + pb;
  8310. if (st->width_kind) {
  8311. int w;
  8312. if (st->width_kind == 3)
  8313. w = cbw * st->width_calc_pct / 100 +
  8314. st->width_calc_px;
  8315. else
  8316. w = css_size(st->width_kind, st->width, cbw);
  8317. if (w < 0)
  8318. w = 0;
  8319. content_w = st->box_sizing ? w - deco_w : w;
  8320. definite_w = 1;
  8321. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  8322. doc.nodes[node].tag == BR_TAG_TD ||
  8323. doc.nodes[node].tag == BR_TAG_TH) &&
  8324. doc.nodes[node].width_attr) {
  8325. /* Legacy table/cell width attributes: percentages resolve
  8326. * against the containing block, bare numbers are pixels. */
  8327. int w = doc.nodes[node].width_pct ?
  8328. cbw * doc.nodes[node].width_attr / 100 :
  8329. doc.nodes[node].width_attr;
  8330. if (w < 0)
  8331. w = 0;
  8332. content_w = st->box_sizing ? w - deco_w : w;
  8333. definite_w = 1;
  8334. } else {
  8335. content_w = cbw - ml - mr - deco_w;
  8336. }
  8337. if (content_w < 0)
  8338. content_w = 0;
  8339. if (st->max_width_kind) {
  8340. int mw = st->max_width_kind == 3 ?
  8341. cbw * st->max_width_calc_pct / 100 +
  8342. st->max_width_calc_px :
  8343. css_size(st->max_width_kind, st->max_width, cbw);
  8344. int max_box = st->box_sizing ? mw : mw + deco_w;
  8345. /* A clamped auto width is used as the width, so auto
  8346. * margins share the rest (Google's 688 px search box). */
  8347. if (content_w + deco_w > max_box) {
  8348. content_w = max_box - deco_w;
  8349. definite_w = 1;
  8350. }
  8351. }
  8352. if (st->min_width_kind) {
  8353. int mw = st->min_width_kind == 3 ?
  8354. cbw * st->min_width_calc_pct / 100 +
  8355. st->min_width_calc_px :
  8356. css_size(st->min_width_kind, st->min_width, cbw);
  8357. int min_box = st->box_sizing ? mw : mw + deco_w;
  8358. if (content_w + deco_w < min_box) {
  8359. content_w = min_box - deco_w;
  8360. definite_w = 1;
  8361. }
  8362. }
  8363. if (content_w < 8)
  8364. content_w = 8;
  8365. if (definite_w) {
  8366. int free_w = cbw - ml - mr - deco_w - content_w;
  8367. if (free_w < 0)
  8368. free_w = 0;
  8369. if (st->ml_auto && st->mr_auto) {
  8370. ml = free_w / 2;
  8371. mr = free_w - ml;
  8372. } else if (st->ml_auto) {
  8373. ml = free_w;
  8374. } else if (st->mr_auto) {
  8375. mr = free_w;
  8376. }
  8377. }
  8378. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8379. int iw, ih;
  8380. image_block_size(node, st, cbw, &iw, &ih);
  8381. content_w = iw;
  8382. img_dh = ih;
  8383. }
  8384. l0 = old_left + ml;
  8385. r0 = l0 + deco_w + content_w;
  8386. if (r0 < l0 + 8)
  8387. r0 = l0 + 8;
  8388. normal_top = top;
  8389. if (sticky) {
  8390. if (st->top_set) {
  8391. int stick = page_rect.y + 4 + st->top;
  8392. if (normal_top < stick)
  8393. rel_dy += stick - normal_top;
  8394. } else if (st->bottom_set && block_h[node]) {
  8395. int stick = page_rect.y + page_rect.h - st->bottom -
  8396. block_h[node];
  8397. if (normal_top > stick)
  8398. rel_dy += stick - normal_top;
  8399. }
  8400. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  8401. block_h[doc.nodes[node].parent]) {
  8402. unsigned int p = doc.nodes[node].parent;
  8403. int ptop = l->parent_top;
  8404. int pbottom = ptop + block_h[p];
  8405. int eh = block_h[node];
  8406. int moved_top = normal_top + rel_dy;
  8407. int moved_bottom = moved_top + eh;
  8408. if (moved_bottom > pbottom)
  8409. rel_dy -= moved_bottom - pbottom;
  8410. moved_top = normal_top + rel_dy;
  8411. if (moved_top < ptop)
  8412. rel_dy += ptop - moved_top;
  8413. }
  8414. }
  8415. if (shifted && l->draw) {
  8416. top += rel_dy;
  8417. l0 += rel_dx;
  8418. r0 += rel_dx;
  8419. }
  8420. l->parent_top = top;
  8421. if (st->pos != 0) {
  8422. /* Positioned boxes establish the containing block for their
  8423. * absolutely positioned descendants. */
  8424. l->cb_left = l0;
  8425. l->cb_right = r0;
  8426. l->cb_top = top;
  8427. }
  8428. if (l->draw && block_h[node] &&
  8429. top < page_rect.y + page_rect.h &&
  8430. top + block_h[node] > page_rect.y) {
  8431. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  8432. int rtl = css_radius(st, 0, box.w, box.h);
  8433. int rtr = css_radius(st, 1, box.w, box.h);
  8434. int rbr = css_radius(st, 2, box.w, box.h);
  8435. int rbl = css_radius(st, 3, box.w, box.h);
  8436. if (st->transform_scale) {
  8437. if (st->has_bg)
  8438. fill_transformed_rect(l->ui, box, st->bg, st);
  8439. } else if (rtl || rtr || rbr || rbl) {
  8440. if (st->has_bg) {
  8441. int bw = st->border_w[0];
  8442. if (bw > 0 && !st->border_t[0] &&
  8443. st->border_c[0] != st->bg &&
  8444. box.w > bw * 2 && box.h > bw * 2) {
  8445. struct ngui_rect inner = {
  8446. box.x + bw, box.y + bw,
  8447. box.w - bw * 2, box.h - bw * 2
  8448. };
  8449. int itl = rtl > bw ? rtl - bw : 0;
  8450. int itr = rtr > bw ? rtr - bw : 0;
  8451. int ibr = rbr > bw ? rbr - bw : 0;
  8452. int ibl = rbl > bw ? rbl - bw : 0;
  8453. ngui_fill_round_rect(l->ui, box, rtl,
  8454. rtr, rbr, rbl,
  8455. st->border_c[0]);
  8456. ngui_fill_round_rect(l->ui, inner,
  8457. itl, itr, ibr,
  8458. ibl, st->bg);
  8459. } else {
  8460. ngui_fill_round_rect(l->ui, box, rtl,
  8461. rtr, rbr, rbl,
  8462. st->bg);
  8463. }
  8464. } else if (st->border_w[0] && !st->border_t[0]) {
  8465. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  8466. rbl, st->border_w[0],
  8467. st->border_c[0]);
  8468. }
  8469. /* Rounded boxes paint their background image too
  8470. * (app icons are rounded squares), kept inside the
  8471. * corner arcs. */
  8472. if (st->bg_image)
  8473. draw_bg_image_round(l, box, node, st, rtl, rtr,
  8474. rbr, rbl);
  8475. } else {
  8476. if (st->has_bg)
  8477. ngui_fill_rect(l->ui, box, st->bg);
  8478. if (st->bg_image)
  8479. draw_bg_image(l, box, node, st);
  8480. if (st->border_w[0] || st->border_w[1] ||
  8481. st->border_w[2] || st->border_w[3])
  8482. draw_border_box(l->ui, box, st);
  8483. }
  8484. }
  8485. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  8486. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  8487. content_w, img_dh);
  8488. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  8489. l->ui && l->ui->nclip < 4) {
  8490. clip_rect.x = l0 + bl;
  8491. clip_rect.y = top + bt;
  8492. clip_rect.w = (r0 - l0) - bl - br;
  8493. clip_rect.h = (int)block_h[node] - bt - bb;
  8494. if (clip_rect.w > 0 && clip_rect.h > 0) {
  8495. ngui_push_clip(l->ui, clip_rect);
  8496. clip_pushed = 1;
  8497. }
  8498. }
  8499. l->left = l0 + bl + pl;
  8500. l->right = l->left + content_w;
  8501. if (l->right < l->left + 8)
  8502. l->right = l->left + 8;
  8503. l->align = st->align;
  8504. l->line_left = l->left;
  8505. l->line_right = l->right;
  8506. l->y = top + bt + pt;
  8507. if (doc.nodes[node].tag == BR_TAG_HR) {
  8508. if (l->draw)
  8509. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  8510. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  8511. l->y += 8;
  8512. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  8513. int vw = l->right - l->left;
  8514. int vh;
  8515. if (doc.nodes[node].width_pct)
  8516. vw = vw * doc.nodes[node].width_attr / 100;
  8517. else if (doc.nodes[node].width_attr)
  8518. vw = doc.nodes[node].width_attr;
  8519. if (vw > l->right - l->left)
  8520. vw = l->right - l->left;
  8521. if (vw < 8)
  8522. vw = 8;
  8523. vh = vw * 9 / 16;
  8524. if (vh > 240)
  8525. vh = 240;
  8526. if (vh < 80)
  8527. vh = 80;
  8528. if (l->draw) {
  8529. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  8530. vw, vh}, 0xD69A);
  8531. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  8532. vw, vh}, 0x8410);
  8533. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  8534. 0x4208);
  8535. }
  8536. l->y += vh + 4;
  8537. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  8538. int dw, dh, cw = l->right - l->left;
  8539. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  8540. if (l->draw && l->y < page_rect.y + page_rect.h &&
  8541. l->y + dh > page_rect.y)
  8542. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  8543. l->y += dh;
  8544. } else {
  8545. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  8546. !st->no_bullet) {
  8547. char *m = li_marker[node];
  8548. if (!m[0]) {
  8549. unsigned int parent = doc.nodes[node].parent;
  8550. int style = st->list_style;
  8551. int idx = parent ? list_index(parent, node) : 1;
  8552. if (style == BR_LIST_AUTO)
  8553. style = (parent &&
  8554. doc.nodes[parent].tag ==
  8555. BR_TAG_OL) ?
  8556. BR_LIST_DECIMAL : BR_LIST_DISC;
  8557. list_marker_text(m, sizeof(li_marker[node]),
  8558. style, idx);
  8559. }
  8560. if (l->draw && m[0]) {
  8561. int mw = (int)ngui_text_width_ui(l->ui, m);
  8562. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  8563. st->color);
  8564. }
  8565. }
  8566. /* This box's definite content height, for its children's
  8567. * percentage heights. */
  8568. if (doc.nodes[node].tag == BR_TAG_HTML ||
  8569. doc.nodes[node].tag == BR_TAG_BODY)
  8570. l->cb_h = layout_view_h;
  8571. else if (st->height_kind == 1)
  8572. l->cb_h = (int)st->height -
  8573. (st->box_sizing ? deco_h : 0);
  8574. else if (st->height_kind == 2 && parent_cb_h > 0)
  8575. l->cb_h = parent_cb_h * (int)st->height / 100 -
  8576. (st->box_sizing ? deco_h : 0);
  8577. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  8578. l->cb_h = content_w * (int)st->aspect_h /
  8579. (int)st->aspect_w;
  8580. else
  8581. l->cb_h = 0;
  8582. if (l->cb_h < 0)
  8583. l->cb_h = 0;
  8584. if (doc.nodes[node].tag == BR_TAG_TR)
  8585. layout_table_row(l, node, st, depth + 1, link);
  8586. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  8587. table_has_rowspan(node))
  8588. layout_table(l, node, st, depth + 1, link);
  8589. else if (st->grid_auto)
  8590. layout_grid_auto(l, node, st, depth + 1, link);
  8591. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  8592. st->grid_gap > 0)
  8593. layout_grid_children(l, node, st, depth + 1, link);
  8594. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  8595. flex_wants_row(node, st))
  8596. layout_flex_children(l, node, st, depth + 1, link);
  8597. else if (st->display == BR_DISPLAY_FLEX && st->flex_col &&
  8598. st->align_items == 1) {
  8599. /* align-items: center in a column: the items' lines
  8600. * (an app card's icon and label) are centred; a child
  8601. * with its own text-align keeps it. */
  8602. struct br_style cst = *st;
  8603. cst.align = BR_ALIGN_CENTER;
  8604. l->align = BR_ALIGN_CENTER;
  8605. layout_children(l, node, &cst, depth + 1, link);
  8606. } else
  8607. layout_children(l, node, st, depth + 1, link);
  8608. l->cb_h = parent_cb_h;
  8609. }
  8610. flush_line(l);
  8611. if (clip_pushed)
  8612. ngui_pop_clip(l->ui);
  8613. if (l->float_active) {
  8614. if (l->y < l->float_bottom)
  8615. l->y = l->float_bottom;
  8616. l->float_active = 0;
  8617. }
  8618. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8619. content_h = img_dh;
  8620. } else if (st->height_kind == 2 &&
  8621. doc.nodes[node].tag != BR_TAG_HTML &&
  8622. doc.nodes[node].tag != BR_TAG_BODY) {
  8623. /* A percentage of the containing block's definite height, or
  8624. * auto when it has none (it used to resolve against the
  8625. * width). The result is a minimum: without scrollable inner
  8626. * boxes, an app shell's height:100%; overflow:hidden column
  8627. * would otherwise clip everything past the first screen. */
  8628. int auto_h = l->y - (top + bt + pt);
  8629. content_h = parent_cb_h > 0 ?
  8630. parent_cb_h * (int)st->height / 100 -
  8631. (st->box_sizing ? deco_h : 0) : 0;
  8632. if (content_h < auto_h)
  8633. content_h = auto_h;
  8634. } else if (st->height_kind &&
  8635. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8636. doc.nodes[node].tag == BR_TAG_BODY) &&
  8637. st->height_kind == 2)) {
  8638. content_h = style_height_px(st, cbw);
  8639. if (st->box_sizing)
  8640. content_h -= deco_h;
  8641. } else {
  8642. /* Percentage heights on html/body resolve against the
  8643. * viewport, but their content still defines the document
  8644. * scroll height. Treating them as auto avoids collapsing
  8645. * the measured page to the containing block width. */
  8646. content_h = l->y - (top + bt + pt);
  8647. /* aspect-ratio: the preferred height of an auto-height box
  8648. * (Tailwind aspect-video image frames); content can still
  8649. * make it taller, as with min-height: auto. */
  8650. if (st->aspect_w && st->aspect_h && content_w > 0) {
  8651. int ah = content_w * (int)st->aspect_h /
  8652. (int)st->aspect_w;
  8653. if (content_h < ah)
  8654. content_h = ah;
  8655. }
  8656. }
  8657. if (content_h < 0)
  8658. content_h = 0;
  8659. if (st->max_height_kind) {
  8660. int mh = st->max_height_kind == 3 ?
  8661. cbw * st->max_height_calc_pct / 100 +
  8662. st->max_height_calc_px :
  8663. css_size(st->max_height_kind, st->max_height, cbw);
  8664. int max_box = st->box_sizing ? mh : mh + deco_h;
  8665. if (content_h + deco_h > max_box)
  8666. content_h = max_box - deco_h;
  8667. }
  8668. if (st->min_height_kind &&
  8669. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8670. doc.nodes[node].tag == BR_TAG_BODY) &&
  8671. st->min_height_kind == 2)) {
  8672. int mh = st->min_height_kind == 3 ?
  8673. cbw * st->min_height_calc_pct / 100 +
  8674. st->min_height_calc_px :
  8675. css_size(st->min_height_kind, st->min_height, cbw);
  8676. int min_box = st->box_sizing ? mh : mh + deco_h;
  8677. if (content_h + deco_h < min_box)
  8678. content_h = min_box - deco_h;
  8679. }
  8680. if (content_h < 0)
  8681. content_h = 0;
  8682. box_h = deco_h + content_h;
  8683. if (box_h < 0)
  8684. box_h = 0;
  8685. l->y = (shifted ? normal_top : top) + box_h;
  8686. if (node < BR_MAX_NODES) {
  8687. layout_boxes[node].x = l0;
  8688. layout_boxes[node].y = top;
  8689. layout_boxes[node].w = r0 - l0;
  8690. layout_boxes[node].h = box_h;
  8691. layout_boxes[node].valid = r0 > l0;
  8692. }
  8693. l->left = old_left;
  8694. l->right = old_right;
  8695. l->align = old_align;
  8696. l->y += mp_px(st, 2, cbw);
  8697. if (!l->draw) {
  8698. if (box_h > 65535)
  8699. box_h = 65535;
  8700. block_h[node] = (unsigned short)box_h;
  8701. block_top[node] = (unsigned short)(top < 0 ? 0 :
  8702. top > 65535 ? 65535 : top);
  8703. }
  8704. if (positioned) {
  8705. l->y = flow_y;
  8706. l->left = flow_left;
  8707. l->right = flow_right;
  8708. }
  8709. l->parent_top = saved_parent_top;
  8710. l->cb_left = saved_cb_left;
  8711. l->cb_right = saved_cb_right;
  8712. l->cb_top = saved_cb_top;
  8713. }
  8714. static int text_node_blank(const struct br_node *nd)
  8715. {
  8716. const char *t = doc.text + nd->text_off;
  8717. unsigned int i;
  8718. for (i = 0; i < nd->text_len; i++)
  8719. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  8720. t[i] != '\r')
  8721. return 0;
  8722. return 1;
  8723. }
  8724. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  8725. * text/image widths in the subtree, plus padding and margins. This keeps
  8726. * Bootstrap's floated nav items on one line instead of giving each the whole
  8727. * row. */
  8728. static int text_space(char c)
  8729. {
  8730. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  8731. }
  8732. static int intrinsic_width(struct ngui *ui, unsigned int node,
  8733. const struct br_style *pst, int depth, int base)
  8734. {
  8735. unsigned int c;
  8736. int line_w = 0, max_w = 0;
  8737. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  8738. if (depth > 32)
  8739. return 0;
  8740. if (doc.npe_rules) {
  8741. struct br_style ps;
  8742. /* Icon boxes (::before/::after with a size) are inline
  8743. * content of the element. */
  8744. line_w += pseudo_box_w(node, pst, 1, &ps, base) +
  8745. pseudo_box_w(node, pst, 2, &ps, base);
  8746. }
  8747. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8748. struct br_node *nd = &doc.nodes[c];
  8749. struct br_style cs;
  8750. if (nd->type == BR_NODE_TEXT) {
  8751. const char *t = doc.text + nd->text_off;
  8752. unsigned int tn = nd->text_len;
  8753. if (doc.nodes[node].tag == BR_TAG_PRE) {
  8754. line_w += (int)face_text_width(ui, pst, t, tn);
  8755. } else {
  8756. unsigned int ti = 0;
  8757. int first = 1;
  8758. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  8759. int sp = (int)face_text_width(ui, pst, " ", 1);
  8760. while (ti < tn) {
  8761. unsigned int ts;
  8762. while (ti < tn && text_space(t[ti]))
  8763. ti++;
  8764. ts = ti;
  8765. while (ti < tn && !text_space(t[ti]))
  8766. ti++;
  8767. if (ti == ts)
  8768. break;
  8769. if (!first || lead)
  8770. line_w += sp;
  8771. lead = 0;
  8772. line_w += (int)face_text_width(ui, pst,
  8773. t + ts, ti - ts);
  8774. first = 0;
  8775. }
  8776. }
  8777. continue;
  8778. }
  8779. br_style_for(&doc, c, pst, &cs);
  8780. if (cs.display == BR_DISPLAY_NONE)
  8781. continue;
  8782. if (nd->tag == BR_TAG_BR) {
  8783. if (line_w > max_w)
  8784. max_w = line_w;
  8785. line_w = 0;
  8786. continue;
  8787. }
  8788. if (nd->tag == BR_TAG_IMG) {
  8789. /* Measure the image as layout will draw it: a CSS or
  8790. * attribute height keeps the intrinsic aspect ratio, and
  8791. * a CSS width overrides the native pixel width. Bootstrap
  8792. * sizes the Cloudron logo with height:40px only. */
  8793. int idx = nd->img_index;
  8794. int iw = 0, ih = 0;
  8795. if (idx >= 0 && idx < image_count &&
  8796. images[idx].state == 1) {
  8797. iw = (int)images[idx].native_w;
  8798. ih = (int)images[idx].native_h;
  8799. if (iw <= 0 || ih <= 0) {
  8800. iw = (int)images[idx].img.w;
  8801. ih = (int)images[idx].img.h;
  8802. }
  8803. }
  8804. if (cs.width_kind) {
  8805. int ww = style_width_px(&cs, base);
  8806. line_w += ww > 0 ? ww : 64;
  8807. } else if (nd->width_attr) {
  8808. line_w += nd->width_attr;
  8809. } else if (nd->height_attr && iw && ih) {
  8810. line_w += iw * (int)nd->height_attr / ih;
  8811. } else if (cs.height_kind && iw && ih) {
  8812. /* A percentage height needs the parent's
  8813. * definite height (the logo's 2rem box), as in
  8814. * add_image_run(); otherwise it is auto. */
  8815. int hh = cs.height_kind == 1 ?
  8816. style_height_px(&cs, base) :
  8817. cs.height_kind == 2 &&
  8818. pst->height_kind == 1 ?
  8819. (int)pst->height * (int)cs.height / 100 :
  8820. 0;
  8821. line_w += hh > 0 ? iw * hh / ih : iw;
  8822. } else if (iw) {
  8823. line_w += iw;
  8824. } else {
  8825. line_w += 64;
  8826. }
  8827. continue;
  8828. }
  8829. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  8830. nd->tag == BR_TAG_TEXTAREA) &&
  8831. !s_eq(br_type(&doc, c), "hidden")) {
  8832. /* Form controls are replaced: CSS width applies even
  8833. * when they are inline (add_form_run's sizes). */
  8834. int fw = cs.width_kind ? style_width_px(&cs, base) :
  8835. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  8836. if (s_eq(br_type(&doc, c), "checkbox") ||
  8837. s_eq(br_type(&doc, c), "radio"))
  8838. fw = 16;
  8839. line_w += (fw > 0 ? fw : 120) +
  8840. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  8841. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  8842. continue;
  8843. }
  8844. if (nd->tag == BR_TAG_SVG) {
  8845. /* A replaced element: its own size, like add_svg_run()
  8846. * (its path children have no width). */
  8847. int sw, sh, sb = cs.width_kind ?
  8848. style_width_px(&cs, base) : base;
  8849. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  8850. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  8851. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  8852. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8853. line_w += sw;
  8854. } else {
  8855. if (line_w > max_w)
  8856. max_w = line_w;
  8857. line_w = 0;
  8858. if (sw > max_w)
  8859. max_w = sw;
  8860. }
  8861. continue;
  8862. }
  8863. {
  8864. int cw = mp_px(&cs, 7, base) +
  8865. mp_px(&cs, 5, base) +
  8866. mp_px(&cs, 3, base) +
  8867. mp_px(&cs, 1, base) +
  8868. cs.border_w[1] + cs.border_w[3];
  8869. /* width/height do not apply to non-replaced inline
  8870. * boxes. The tagesschau home label is an inline span
  8871. * with width:1px for the mobile icon-only header; using
  8872. * that width made the whole subnav collapse to a
  8873. * one-character column. */
  8874. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  8875. cw += cs.width_kind == 1 ? cs.width :
  8876. style_width_px(&cs, base);
  8877. else
  8878. cw += intrinsic_width(ui, c, &cs, depth + 1,
  8879. base);
  8880. if (flex_row || cs.float_left ||
  8881. cs.display == BR_DISPLAY_INLINE ||
  8882. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8883. line_w += cw;
  8884. } else {
  8885. if (line_w > max_w)
  8886. max_w = line_w;
  8887. line_w = 0;
  8888. if (cw > max_w)
  8889. max_w = cw;
  8890. }
  8891. }
  8892. if (line_w > 4096 || max_w > 4096)
  8893. break;
  8894. }
  8895. return line_w > max_w ? line_w : max_w;
  8896. }
  8897. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  8898. * the main user: .row > .col-md-* with float:left and a percentage width.
  8899. * Each column is laid out with its own left/right edge and the row advances
  8900. * to the tallest column. Returns the first child not consumed. */
  8901. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  8902. const struct br_style *pst, int depth,
  8903. unsigned short link)
  8904. {
  8905. unsigned int n = first;
  8906. int row_left = l->left, row_right = l->right;
  8907. int row_top, row_bottom, xl, xr, any = 0;
  8908. int fl_left = row_left, fl_right = row_right, fl_bottom;
  8909. flush_line(l);
  8910. row_top = l->y;
  8911. row_bottom = l->y;
  8912. fl_bottom = row_top;
  8913. xl = row_left;
  8914. xr = row_right;
  8915. while (n) {
  8916. struct br_node *nd = &doc.nodes[n];
  8917. struct br_style cs;
  8918. unsigned short lk = link;
  8919. int colw, right;
  8920. if (nd->type == BR_NODE_TEXT) {
  8921. if (text_node_blank(nd)) {
  8922. n = nd->next;
  8923. continue;
  8924. }
  8925. break;
  8926. }
  8927. br_style_for(&doc, n, pst, &cs);
  8928. if (cs.display == BR_DISPLAY_NONE) {
  8929. n = nd->next;
  8930. continue;
  8931. }
  8932. /* A float blockifies its box: Bootstrap floats inline
  8933. * anchors too (the navbar brand and its text links), and
  8934. * their padding must be honoured. */
  8935. if (!cs.float_left)
  8936. break;
  8937. if (nd->tag == BR_TAG_A && nd->href_off)
  8938. lk = (unsigned short)n;
  8939. right = cs.float_left == 2;
  8940. if (cs.width_kind == 1 || cs.width_kind == 2 ||
  8941. cs.width_kind == 3) {
  8942. /* The column is the margin box: `width` is the
  8943. * content (or, with border-box, the border) box,
  8944. * and layout_block() takes margins, padding and
  8945. * borders back out of the column. A 200px float
  8946. * with margin-right:20px used to get 180px of
  8947. * content. */
  8948. int base = row_right - row_left;
  8949. colw = cs.width_kind == 1 ? (int)cs.width :
  8950. style_width_px(&cs, base);
  8951. colw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  8952. if (!cs.box_sizing)
  8953. colw += mp_px(&cs, 7, base) +
  8954. mp_px(&cs, 5, base) +
  8955. cs.border_w[1] + cs.border_w[3];
  8956. } else {
  8957. int base = row_right - row_left;
  8958. /* Shrink-to-fit outer width: borders too (Google's
  8959. * 1px-bordered "Anmelden" pill wrapped otherwise). */
  8960. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  8961. mp_px(&cs, 7, base) +
  8962. mp_px(&cs, 5, base) +
  8963. mp_px(&cs, 3, base) +
  8964. mp_px(&cs, 1, base) +
  8965. cs.border_w[1] + cs.border_w[3];
  8966. if (colw < 8)
  8967. colw = 8;
  8968. }
  8969. if (colw < 8)
  8970. colw = 8;
  8971. if (colw > row_right - row_left)
  8972. colw = row_right - row_left;
  8973. /* The float column width is already resolved. */
  8974. cs.width_kind = 0;
  8975. cs.max_width_kind = 0;
  8976. if (right) {
  8977. if (any && xr - colw < xl) {
  8978. row_top = row_bottom;
  8979. row_bottom = row_top;
  8980. xl = row_left;
  8981. xr = row_right;
  8982. }
  8983. if (xr - colw < xl)
  8984. colw = xr - xl;
  8985. if (colw < 8)
  8986. colw = 8;
  8987. l->left = xr - colw;
  8988. if (l->left < row_left)
  8989. l->left = row_left;
  8990. l->right = xr;
  8991. xr = l->left;
  8992. if (xr < fl_right)
  8993. fl_right = xr;
  8994. } else {
  8995. if (any && xl + colw > xr) {
  8996. row_top = row_bottom;
  8997. row_bottom = row_top;
  8998. xl = row_left;
  8999. xr = row_right;
  9000. }
  9001. l->left = xl;
  9002. l->right = xl + colw;
  9003. xl += colw;
  9004. if (xl > fl_left)
  9005. fl_left = xl;
  9006. }
  9007. if (l->right < l->left + 8)
  9008. l->right = l->left + 8;
  9009. l->y = row_top;
  9010. l->line_x = l->left;
  9011. l->run_x = l->left;
  9012. l->line_y = l->y;
  9013. l->line_h = 0;
  9014. l->nruns = 0;
  9015. l->space_pending = 0;
  9016. l->align = cs.align;
  9017. layout_block(l, n, &cs, depth + 1, lk);
  9018. if (l->y > row_bottom)
  9019. row_bottom = l->y;
  9020. if (l->y > fl_bottom)
  9021. fl_bottom = l->y;
  9022. any = 1;
  9023. n = nd->next;
  9024. }
  9025. l->left = row_left;
  9026. l->right = row_right;
  9027. if (n && any) {
  9028. struct br_node *nd = &doc.nodes[n];
  9029. int inline_next = 0;
  9030. if (nd->type == BR_NODE_TEXT) {
  9031. inline_next = 1;
  9032. } else if (nd->type == BR_NODE_ELEM) {
  9033. struct br_style cs;
  9034. br_style_for(&doc, n, pst, &cs);
  9035. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  9036. cs.display != BR_DISPLAY_NONE &&
  9037. !br_tag_is_block(nd->tag);
  9038. }
  9039. if (inline_next) {
  9040. if (l->float_active) {
  9041. if (l->float_left > fl_left)
  9042. fl_left = l->float_left;
  9043. if (l->float_right < fl_right)
  9044. fl_right = l->float_right;
  9045. if (l->float_bottom > fl_bottom)
  9046. fl_bottom = l->float_bottom;
  9047. }
  9048. l->float_active = 1;
  9049. l->float_left = fl_left;
  9050. l->float_right = fl_right;
  9051. l->float_bottom = fl_bottom;
  9052. l->y = row_top;
  9053. } else {
  9054. l->float_active = 0;
  9055. l->y = row_bottom;
  9056. }
  9057. } else {
  9058. l->float_active = 0;
  9059. l->y = row_bottom;
  9060. }
  9061. l->line_x = l->left;
  9062. l->run_x = l->left;
  9063. l->line_left = l->left;
  9064. l->line_right = l->right;
  9065. l->line_y = l->y;
  9066. l->line_h = 0;
  9067. l->nruns = 0;
  9068. l->space_pending = 0;
  9069. return n;
  9070. }
  9071. static int flex_item_width(struct lay *l, unsigned int n,
  9072. const struct br_style *cs, int avail)
  9073. {
  9074. struct br_node *nd = &doc.nodes[n];
  9075. (void)l;
  9076. int w;
  9077. if (cs->width_kind == 2 || cs->width_kind == 3)
  9078. w = style_width_px(cs, avail);
  9079. else if (cs->width_kind == 1)
  9080. w = (int)cs->width;
  9081. else if (nd->tag == BR_TAG_IMG) {
  9082. int idx = nd->img_index;
  9083. if (idx >= 0 && idx < image_count &&
  9084. images[idx].state == 1)
  9085. w = (int)images[idx].img.w;
  9086. else if (nd->width_attr)
  9087. w = (int)nd->width_attr;
  9088. else
  9089. w = 64;
  9090. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  9091. nd->tag == BR_TAG_TEXTAREA) {
  9092. /* A control has no content to measure: its default size
  9093. * (a search field in a filter bar). */
  9094. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  9095. } else {
  9096. w = intrinsic_width(l->ui, n, cs, 0, avail);
  9097. }
  9098. /* Explicit widths are content-box sizes; the flex item's outer width
  9099. * must include padding, borders and margins. */
  9100. w += mp_px(cs, 7, avail);
  9101. w += mp_px(cs, 5, avail);
  9102. w += mp_px(cs, 3, avail);
  9103. w += mp_px(cs, 1, avail);
  9104. w += cs->border_w[1] + cs->border_w[3];
  9105. if (w < 24)
  9106. w = 24;
  9107. if (w > avail)
  9108. w = avail;
  9109. return w;
  9110. }
  9111. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  9112. int depth);
  9113. /* An inline child of a text-only inline-block: the same test minus the
  9114. * display check (an inline <span> may have padding/background in CSS, but
  9115. * the inline path paints those for spans anyway). */
  9116. static int inline_block_flows_inline(unsigned int node,
  9117. const struct br_style *cs, int depth)
  9118. {
  9119. unsigned int c;
  9120. if (depth > 3 || cs->pos)
  9121. return 0;
  9122. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9123. const struct br_node *nd = &doc.nodes[c];
  9124. struct br_style ch;
  9125. if (nd->type != BR_NODE_ELEM)
  9126. continue;
  9127. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  9128. br_tag_is_block(nd->tag))
  9129. return 0;
  9130. br_style_for(&doc, c, cs, &ch);
  9131. if (ch.display == BR_DISPLAY_NONE)
  9132. continue;
  9133. if (ch.display != BR_DISPLAY_INLINE ||
  9134. !inline_block_flows_inline(c, &ch, depth + 1))
  9135. return 0;
  9136. }
  9137. return 1;
  9138. }
  9139. /* An inline-block that is only text in a line (a <time> in a byline, a
  9140. * label) with no box of its own -- no size, background, border or padding
  9141. * -- lays out exactly like an inline element, so it stays in the text line
  9142. * instead of ending it. Boxes with any of those keep the row path. */
  9143. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  9144. int depth)
  9145. {
  9146. unsigned int c;
  9147. int i;
  9148. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  9149. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  9150. cs->pos || depth > 3)
  9151. return 0;
  9152. for (i = 0; i < 4; i++)
  9153. if (cs->border_w[i])
  9154. return 0;
  9155. for (i = 4; i < 8; i++)
  9156. if (mp_px(cs, i, 0) > 0)
  9157. return 0;
  9158. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9159. const struct br_node *nd = &doc.nodes[c];
  9160. struct br_style ch;
  9161. if (nd->type != BR_NODE_ELEM)
  9162. continue;
  9163. if (nd->tag == BR_TAG_SVG) {
  9164. /* An icon box (Docusaurus' admonition heading:
  9165. * `<span inline-block><svg/></span>Note`): the SVG
  9166. * is an inline replaced run, so the box can stay in
  9167. * the text line. */
  9168. br_style_for(&doc, c, cs, &ch);
  9169. if (ch.display == BR_DISPLAY_NONE ||
  9170. ch.display == BR_DISPLAY_INLINE ||
  9171. ch.display == BR_DISPLAY_INLINE_BLOCK)
  9172. continue;
  9173. return 0;
  9174. }
  9175. if (nd->tag == BR_TAG_IMG || br_tag_is_block(nd->tag))
  9176. return 0;
  9177. br_style_for(&doc, c, cs, &ch);
  9178. if (ch.display == BR_DISPLAY_NONE)
  9179. continue;
  9180. if (ch.display != BR_DISPLAY_INLINE ||
  9181. !inline_block_flows_inline(c, &ch, depth + 1))
  9182. return 0;
  9183. }
  9184. return 1;
  9185. }
  9186. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  9187. * on one line, not one full-width block each. Place intrinsic widths from
  9188. * left to right and wrap when the row is full. */
  9189. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  9190. const struct br_style *pst, int depth,
  9191. unsigned short link)
  9192. {
  9193. unsigned int n = first;
  9194. int row_left = l->left, row_right = l->right;
  9195. int avail = row_right - row_left;
  9196. int x = row_left, y = l->y, row_h = 0, any = 0;
  9197. /* Each box sets l->align from its own style; the text after the row
  9198. * must keep the container's (a centred .fa-fw icon centred the menu
  9199. * label that followed it). */
  9200. unsigned char row_align = l->align;
  9201. flush_line(l);
  9202. y = l->y;
  9203. while (n) {
  9204. struct br_node *nd = &doc.nodes[n];
  9205. struct br_style cs;
  9206. unsigned short lk = link;
  9207. int colw, h;
  9208. if (nd->type == BR_NODE_TEXT) {
  9209. if (!text_node_blank(nd))
  9210. break;
  9211. if (any)
  9212. x += 4;
  9213. n = nd->next;
  9214. continue;
  9215. }
  9216. br_style_for(&doc, n, pst, &cs);
  9217. if (cs.display == BR_DISPLAY_NONE) {
  9218. n = nd->next;
  9219. continue;
  9220. }
  9221. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  9222. break;
  9223. if (nd->tag == BR_TAG_A && nd->href_off)
  9224. lk = (unsigned short)n;
  9225. colw = flex_item_width(l, n, &cs, avail);
  9226. /* A few pixels of slack keep a single long token (boot.S)
  9227. * from wrapping at the exact content width. */
  9228. colw += 8;
  9229. if (colw > avail)
  9230. colw = avail;
  9231. cs.width_kind = 0;
  9232. cs.max_width_kind = 0;
  9233. if (any && x + colw > row_right) {
  9234. y += row_h + 2;
  9235. x = row_left;
  9236. row_h = 0;
  9237. any = 0;
  9238. }
  9239. if (any && x > row_left)
  9240. x += 4;
  9241. l->left = x;
  9242. l->right = x + colw;
  9243. if (l->right < l->left + 8)
  9244. l->right = l->left + 8;
  9245. l->y = y;
  9246. l->line_x = l->left;
  9247. l->run_x = l->left;
  9248. l->line_y = l->y;
  9249. l->line_h = 0;
  9250. l->nruns = 0;
  9251. l->space_pending = 0;
  9252. l->align = cs.align;
  9253. layout_block(l, n, &cs, depth + 1, lk);
  9254. h = l->y - y;
  9255. if (h > row_h)
  9256. row_h = h;
  9257. x += colw;
  9258. any = 1;
  9259. n = nd->next;
  9260. }
  9261. if (any)
  9262. y += row_h;
  9263. l->left = row_left;
  9264. l->right = row_right;
  9265. l->align = row_align;
  9266. l->y = y;
  9267. l->line_x = l->left;
  9268. l->run_x = l->left;
  9269. l->line_y = l->y;
  9270. l->line_h = 0;
  9271. l->nruns = 0;
  9272. l->space_pending = 0;
  9273. return n;
  9274. }
  9275. struct flex_item {
  9276. unsigned int node;
  9277. unsigned short link;
  9278. int w;
  9279. };
  9280. /* An item's min-width/max-width as outer (margin-box) widths in the flex
  9281. * row, or -1 when unset. Percentages and calc() resolve against the
  9282. * container width. */
  9283. static int flex_limit_w(const struct br_style *cs, int which_max, int avail)
  9284. {
  9285. unsigned char kind = which_max ? cs->max_width_kind :
  9286. cs->min_width_kind;
  9287. int w;
  9288. if (kind == 3)
  9289. w = which_max ?
  9290. avail * cs->max_width_calc_pct / 100 +
  9291. cs->max_width_calc_px :
  9292. avail * cs->min_width_calc_pct / 100 +
  9293. cs->min_width_calc_px;
  9294. else
  9295. w = css_size(kind, which_max ? cs->max_width : cs->min_width,
  9296. avail);
  9297. if (w < 0)
  9298. return -1;
  9299. if (!cs->box_sizing)
  9300. w += mp_px(cs, 7, avail) + mp_px(cs, 5, avail) +
  9301. cs->border_w[1] + cs->border_w[3];
  9302. return w + mp_px(cs, 3, avail) + mp_px(cs, 1, avail);
  9303. }
  9304. static int flex_clamp_w(const struct br_style *cs, int w, int avail)
  9305. {
  9306. int mx = flex_limit_w(cs, 1, avail), mn = flex_limit_w(cs, 0, avail);
  9307. if (mx >= 0 && w > mx)
  9308. w = mx;
  9309. if (mn >= 0 && w < mn)
  9310. w = mn;
  9311. return w;
  9312. }
  9313. static void layout_flex_children(struct lay *l, unsigned int parent,
  9314. const struct br_style *pst, int depth,
  9315. unsigned short link)
  9316. {
  9317. struct flex_item it[32];
  9318. unsigned int c;
  9319. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  9320. int grow_need = 0; /* growing items at their content width */
  9321. int row_left = l->left, row_right = l->right;
  9322. int avail = row_right - row_left;
  9323. int idx, row_top;
  9324. unsigned char row_align = l->align;
  9325. int box_left = l->left, box_right = l->right, row_top0 = l->y;
  9326. int bw = 0, aw = 0, first_h = -1;
  9327. struct br_style bps, aps;
  9328. if (avail < 8 || depth > 48) {
  9329. layout_children(l, parent, pst, depth, link);
  9330. return;
  9331. }
  9332. /* If direct text is not just whitespace, normal block flow handles it
  9333. * better than pretending it is a flex item. */
  9334. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9335. struct br_node *nd = &doc.nodes[c];
  9336. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9337. layout_children(l, parent, pst, depth, link);
  9338. return;
  9339. }
  9340. }
  9341. /* ::before/::after icon boxes are the row's first and last items
  9342. * (Docusaurus' sidebar chevron): reserve their columns. */
  9343. if (doc.npe_rules) {
  9344. bw = pseudo_box_w(parent, pst, 1, &bps, avail);
  9345. aw = pseudo_box_w(parent, pst, 2, &aps, avail);
  9346. if (bw + aw > avail - 8) {
  9347. bw = 0;
  9348. aw = 0;
  9349. }
  9350. row_left += bw;
  9351. row_right -= aw;
  9352. avail = row_right - row_left;
  9353. }
  9354. for (c = doc.nodes[parent].first;
  9355. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  9356. c = doc.nodes[c].next) {
  9357. struct br_node *nd = &doc.nodes[c];
  9358. struct br_style cs;
  9359. if (nd->type == BR_NODE_TEXT)
  9360. continue;
  9361. br_style_for(&doc, c, pst, &cs);
  9362. if (cs.display == BR_DISPLAY_NONE)
  9363. continue;
  9364. it[nitem].node = c;
  9365. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  9366. (unsigned short)c : link;
  9367. it[nitem].w = 0;
  9368. if (cs.flex_grow && !cs.width_kind) {
  9369. grow_count++;
  9370. grow_need += flex_item_width(l, c, &cs, avail);
  9371. } else
  9372. fixed += flex_clamp_w(&cs,
  9373. flex_item_width(l, c, &cs, avail),
  9374. avail);
  9375. nitem++;
  9376. }
  9377. /* A narrow container (an icon row sized to its content, Google's
  9378. * mic + lens buttons) is still a row when its items fit; only a
  9379. * narrow one that would overflow or squeeze growing items falls
  9380. * back to block flow. */
  9381. if (avail < 160 && fixed + grow_need > avail) {
  9382. layout_children(l, parent, pst, depth, link);
  9383. return;
  9384. }
  9385. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  9386. /* A growing item capped by max-width (Docusaurus' doc column,
  9387. * `max-width: 75%`; its main container, `calc(100% - 300px)`)
  9388. * keeps its cap and leaves the rest of the free space to the other
  9389. * growing items. */
  9390. if (grow_count) {
  9391. int pass, capped[32] = { 0 };
  9392. for (pass = 0; pass < nitem; pass++) {
  9393. int changed = 0;
  9394. for (idx = 0; idx < nitem; idx++) {
  9395. struct br_style cs;
  9396. int lim;
  9397. if (capped[idx])
  9398. continue;
  9399. br_style_for(&doc, it[idx].node, pst, &cs);
  9400. if (!cs.flex_grow || cs.width_kind)
  9401. continue;
  9402. lim = flex_clamp_w(&cs, grow_w, avail);
  9403. if (lim == grow_w)
  9404. continue;
  9405. capped[idx] = lim + 1;
  9406. fixed += lim;
  9407. grow_count--;
  9408. changed = 1;
  9409. }
  9410. if (!changed || !grow_count)
  9411. break;
  9412. grow_w = (avail - fixed) / grow_count;
  9413. }
  9414. for (idx = 0; idx < nitem; idx++)
  9415. it[idx].w = capped[idx] ? capped[idx] - 1 : 0;
  9416. }
  9417. if (grow_w < 96 && avail >= 160)
  9418. grow_w = 96;
  9419. for (idx = 0; idx < nitem; idx++) {
  9420. struct br_style cs;
  9421. if (it[idx].w)
  9422. continue; /* capped growing item */
  9423. br_style_for(&doc, it[idx].node, pst, &cs);
  9424. if (cs.flex_grow && !cs.width_kind)
  9425. it[idx].w = grow_w;
  9426. else
  9427. it[idx].w = flex_clamp_w(&cs,
  9428. flex_item_width(l,
  9429. it[idx].node,
  9430. &cs, avail),
  9431. avail);
  9432. if (it[idx].w > avail)
  9433. it[idx].w = avail;
  9434. if (it[idx].w < 8)
  9435. it[idx].w = 8;
  9436. }
  9437. row_top = l->y;
  9438. idx = 0;
  9439. while (idx < nitem) {
  9440. int start = idx, count = 0, row_w = 0;
  9441. int free_w, x, extra = 0, row_h = 0, k;
  9442. while (idx < nitem) {
  9443. int add = it[idx].w + (count ? gap : 0);
  9444. /* CSS default is nowrap; only flex-wrap: wrap (1)
  9445. * starts a new row. */
  9446. if (count && pst->flex_wrap == 1 &&
  9447. row_w + add > avail)
  9448. break;
  9449. row_w += add;
  9450. count++;
  9451. idx++;
  9452. }
  9453. if (!count) {
  9454. count = 1;
  9455. row_w = it[start].w;
  9456. idx = start + 1;
  9457. }
  9458. free_w = avail - row_w;
  9459. if (free_w < 0)
  9460. free_w = 0;
  9461. x = row_left;
  9462. if (pst->justify == 1) {
  9463. x += free_w / 2;
  9464. } else if (pst->justify == 2) {
  9465. x += free_w;
  9466. } else if (pst->justify == 3) {
  9467. extra = count > 1 ? free_w / (count - 1) : 0;
  9468. } else if (pst->justify == 4) {
  9469. extra = count ? free_w / count : 0;
  9470. x += extra / 2;
  9471. } else if (pst->justify == 5) {
  9472. extra = count ? free_w / (count + 1) : 0;
  9473. x += extra;
  9474. }
  9475. for (k = 0; k < count; k++) {
  9476. int node = (int)it[start + k].node;
  9477. int h = block_h[node];
  9478. if (h > row_h)
  9479. row_h = h;
  9480. }
  9481. if (pst->height_kind) {
  9482. int hh = style_height_px(pst, avail);
  9483. if (hh > row_h)
  9484. row_h = hh;
  9485. }
  9486. for (k = 0; k < count; k++) {
  9487. struct br_style cs;
  9488. int node = (int)it[start + k].node;
  9489. int yoff = 0;
  9490. br_style_for(&doc, node, pst, &cs);
  9491. cs.width_kind = 0;
  9492. cs.max_width_kind = 0;
  9493. {
  9494. int ai = cs.align_self ? cs.align_self - 1 :
  9495. pst->align_items;
  9496. if (l->draw && ai && row_h > block_h[node]) {
  9497. if (ai == 1)
  9498. yoff = (row_h -
  9499. block_h[node]) / 2;
  9500. else if (ai == 2)
  9501. yoff = row_h - block_h[node];
  9502. }
  9503. }
  9504. l->left = x;
  9505. l->right = x + it[start + k].w;
  9506. if (l->right < l->left + 8)
  9507. l->right = l->left + 8;
  9508. l->y = row_top + yoff;
  9509. l->line_x = l->left;
  9510. l->run_x = l->left;
  9511. l->line_y = l->y;
  9512. l->line_h = 0;
  9513. l->nruns = 0;
  9514. l->space_pending = 0;
  9515. l->align = cs.align;
  9516. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  9517. if (!l->draw) {
  9518. int h = l->y - row_top;
  9519. if (h > row_h)
  9520. row_h = h;
  9521. }
  9522. x += it[start + k].w;
  9523. if (k + 1 < count)
  9524. x += gap + extra;
  9525. }
  9526. if (first_h < 0)
  9527. first_h = row_h;
  9528. row_top += row_h;
  9529. }
  9530. if (bw || aw) {
  9531. int pass;
  9532. for (pass = 0; pass < 2; pass++) {
  9533. const struct br_style *ps = pass ? &aps : &bps;
  9534. int a = pass ? row_right : box_left;
  9535. int b = pass ? box_right : row_left;
  9536. int h = ps->height_kind ?
  9537. style_height_px(ps, box_right - box_left) : 0;
  9538. if (!(pass ? aw : bw))
  9539. continue;
  9540. l->left = l->line_left = l->line_x = l->run_x = a;
  9541. l->right = l->line_right = b;
  9542. l->y = row_top0;
  9543. if (pst->align_items == 1 && first_h > h)
  9544. l->y += (first_h - h) / 2;
  9545. l->line_y = l->y;
  9546. l->line_h = 0;
  9547. l->nruns = 0;
  9548. l->space_pending = 0;
  9549. emit_pseudo_box(l, pst, ps, link);
  9550. flush_line(l);
  9551. /* The box sits inside the first row; it only makes
  9552. * the row taller when it is taller itself. */
  9553. if (row_top0 + h > row_top)
  9554. row_top = row_top0 + h;
  9555. }
  9556. }
  9557. l->left = box_left;
  9558. l->right = box_right;
  9559. l->align = row_align;
  9560. l->y = row_top;
  9561. l->line_x = l->left;
  9562. l->run_x = l->left;
  9563. l->line_y = l->y;
  9564. l->line_h = 0;
  9565. l->nruns = 0;
  9566. l->space_pending = 0;
  9567. }
  9568. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  9569. * plus the grid-area hints used by site shells (site notice/footer full
  9570. * width, column-start left, page-content right). Anything more elaborate
  9571. * falls back to normal block flow. */
  9572. static int grid_track_width(unsigned char kind, unsigned short val,
  9573. int avail, int other)
  9574. {
  9575. if (kind == 2)
  9576. return avail * (int)val / 100;
  9577. if (kind == 1)
  9578. return val;
  9579. return other;
  9580. }
  9581. static void layout_grid_children(struct lay *l, unsigned int parent,
  9582. const struct br_style *pst, int depth,
  9583. unsigned short link)
  9584. {
  9585. unsigned int n;
  9586. int row_left = l->left, row_right = l->right;
  9587. int avail = row_right - row_left;
  9588. int gap = pst->grid_gap;
  9589. int track_total = avail - gap;
  9590. int col0, col1, x0, x1;
  9591. int row_y, row_bottom, have_left = 0, have_right = 0;
  9592. unsigned int c;
  9593. if (avail < 32 || depth > 48)
  9594. return;
  9595. if (track_total < 16)
  9596. track_total = 16;
  9597. col0 = grid_track_width((unsigned char)(pst->width_kind),
  9598. pst->width, track_total, 0);
  9599. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  9600. pst->max_width, track_total, 0);
  9601. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  9602. int w0 = pst->width ? pst->width : 1;
  9603. int w1 = pst->max_width ? pst->max_width : 1;
  9604. col0 = track_total * w0 / (w0 + w1);
  9605. col1 = track_total - col0;
  9606. } else if (pst->width_kind == 3) {
  9607. col0 = track_total - col1;
  9608. if (col0 < 24)
  9609. col0 = 24;
  9610. } else if (pst->max_width_kind == 3) {
  9611. col1 = track_total - col0;
  9612. if (col1 < 24)
  9613. col1 = 24;
  9614. }
  9615. if (col0 < 24)
  9616. col0 = 24;
  9617. if (col1 < 24)
  9618. col1 = 24;
  9619. if (col0 + col1 > track_total) {
  9620. col1 = track_total - col0;
  9621. if (col1 < 24)
  9622. col1 = 24;
  9623. }
  9624. x0 = row_left;
  9625. x1 = row_left + col0 + gap;
  9626. /* Direct text makes a grid ambiguous; use block flow instead. */
  9627. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9628. struct br_node *nd = &doc.nodes[c];
  9629. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9630. layout_children(l, parent, pst, depth, link);
  9631. return;
  9632. }
  9633. }
  9634. row_y = row_bottom = l->y;
  9635. n = doc.nodes[parent].first;
  9636. while (n) {
  9637. struct br_node *nd = &doc.nodes[n];
  9638. struct br_style cs;
  9639. unsigned short lk = link;
  9640. int slot, x, w;
  9641. if (nd->type == BR_NODE_TEXT) {
  9642. n = nd->next;
  9643. continue;
  9644. }
  9645. br_style_for(&doc, n, pst, &cs);
  9646. if (cs.display == BR_DISPLAY_NONE) {
  9647. n = nd->next;
  9648. continue;
  9649. }
  9650. if (nd->tag == BR_TAG_A && nd->href_off)
  9651. lk = (unsigned short)n;
  9652. slot = cs.grid_slot;
  9653. if (!slot) {
  9654. if (!have_left)
  9655. slot = 2;
  9656. else if (!have_right)
  9657. slot = 3;
  9658. else
  9659. slot = 2;
  9660. }
  9661. if (slot == 1) {
  9662. if (have_left || have_right) {
  9663. row_y = row_bottom;
  9664. have_left = have_right = 0;
  9665. }
  9666. x = row_left;
  9667. w = avail;
  9668. } else if (slot == 2) {
  9669. if (have_left) {
  9670. row_y = row_bottom;
  9671. have_left = have_right = 0;
  9672. }
  9673. x = x0;
  9674. w = col0;
  9675. have_left = 1;
  9676. } else {
  9677. if (have_right) {
  9678. row_y = row_bottom;
  9679. have_left = have_right = 0;
  9680. }
  9681. x = x1;
  9682. w = col1;
  9683. have_right = 1;
  9684. }
  9685. cs.width_kind = 0;
  9686. cs.max_width_kind = 0;
  9687. l->left = x;
  9688. l->right = x + w;
  9689. if (l->right < l->left + 8)
  9690. l->right = l->left + 8;
  9691. l->y = row_y;
  9692. l->line_x = l->left;
  9693. l->run_x = l->left;
  9694. l->line_y = l->y;
  9695. l->line_h = 0;
  9696. l->nruns = 0;
  9697. l->space_pending = 0;
  9698. l->align = cs.align;
  9699. layout_block(l, n, &cs, depth + 1, lk);
  9700. if (l->y > row_bottom)
  9701. row_bottom = l->y;
  9702. n = nd->next;
  9703. }
  9704. l->left = row_left;
  9705. l->right = row_right;
  9706. l->y = row_bottom;
  9707. l->line_x = l->left;
  9708. l->run_x = l->left;
  9709. l->line_y = l->y;
  9710. l->line_h = 0;
  9711. l->nruns = 0;
  9712. l->space_pending = 0;
  9713. }
  9714. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  9715. * capped at four. Used by the project docs' card grids. A fixed
  9716. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  9717. static void layout_grid_auto(struct lay *l, unsigned int parent,
  9718. const struct br_style *pst, int depth,
  9719. unsigned short link)
  9720. {
  9721. unsigned int n, c;
  9722. int row_left = l->left, row_right = l->right;
  9723. int avail = row_right - row_left;
  9724. int gap = pst->grid_gap;
  9725. int minw = pst->width_kind == 1 ? pst->width : 200;
  9726. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  9727. if (avail < 32 || depth > 48) {
  9728. layout_children(l, parent, pst, depth, link);
  9729. return;
  9730. }
  9731. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9732. struct br_node *nd = &doc.nodes[c];
  9733. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9734. layout_children(l, parent, pst, depth, link);
  9735. return;
  9736. }
  9737. }
  9738. if (minw < 80)
  9739. minw = 80;
  9740. ncols = (avail + gap) / (minw + gap);
  9741. if (ncols < 1)
  9742. ncols = 1;
  9743. if (ncols > 4)
  9744. ncols = 4;
  9745. if (pst->grid_auto > BR_GRID_FIXED) {
  9746. /* grid-template-columns: repeat(N, 1fr) */
  9747. ncols = pst->grid_auto - BR_GRID_FIXED;
  9748. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  9749. ncols--;
  9750. }
  9751. colw = (avail - gap * (ncols - 1)) / ncols;
  9752. if (colw < 24)
  9753. colw = 24;
  9754. x = row_left;
  9755. n = doc.nodes[parent].first;
  9756. while (n) {
  9757. struct br_node *nd = &doc.nodes[n];
  9758. struct br_style cs;
  9759. unsigned short lk = link;
  9760. int h;
  9761. if (nd->type == BR_NODE_TEXT) {
  9762. n = nd->next;
  9763. continue;
  9764. }
  9765. br_style_for(&doc, n, pst, &cs);
  9766. if (cs.display == BR_DISPLAY_NONE) {
  9767. n = nd->next;
  9768. continue;
  9769. }
  9770. if (nd->tag == BR_TAG_A && nd->href_off)
  9771. lk = (unsigned short)n;
  9772. cs.width_kind = 0;
  9773. cs.max_width_kind = 0;
  9774. l->left = x;
  9775. l->right = x + colw;
  9776. if (l->right < l->left + 8)
  9777. l->right = l->left + 8;
  9778. l->y = y;
  9779. l->line_x = l->left;
  9780. l->run_x = l->left;
  9781. l->line_y = l->y;
  9782. l->line_h = 0;
  9783. l->nruns = 0;
  9784. l->space_pending = 0;
  9785. l->align = cs.align;
  9786. layout_block(l, n, &cs, depth + 1, lk);
  9787. h = l->y - y;
  9788. if (h > row_h)
  9789. row_h = h;
  9790. col++;
  9791. n = nd->next;
  9792. if (col == ncols) {
  9793. y += row_h + gap;
  9794. x = row_left;
  9795. row_h = 0;
  9796. col = 0;
  9797. } else {
  9798. x += colw + gap;
  9799. }
  9800. }
  9801. if (col)
  9802. y += row_h;
  9803. else if (y > start_y)
  9804. y -= gap;
  9805. l->left = row_left;
  9806. l->right = row_right;
  9807. l->y = y;
  9808. l->line_x = l->left;
  9809. l->run_x = l->left;
  9810. l->line_y = l->y;
  9811. l->line_h = 0;
  9812. l->nruns = 0;
  9813. l->space_pending = 0;
  9814. }
  9815. /* Column widths are the widest cell in each column across every row, so all
  9816. * rows line up. The table model is still deliberately basic: no colspan,
  9817. * border-collapse or percentage columns. */
  9818. static void table_columns(struct lay *l, unsigned int table,
  9819. const struct br_style *pst, int avail,
  9820. int *raw, int maxcols, int *out_cols,
  9821. int *out_total)
  9822. {
  9823. unsigned int r, c;
  9824. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  9825. int fixed[12];
  9826. for (c = 0; c < (unsigned int)maxcols; c++) {
  9827. raw[c] = 0;
  9828. fixed[c] = 0;
  9829. }
  9830. /* Intrinsic widths of single-column cells. */
  9831. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9832. struct br_node *rn = &doc.nodes[r];
  9833. int col = 0;
  9834. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9835. continue;
  9836. for (c = rn->first; c; c = doc.nodes[c].next) {
  9837. struct br_node *cn = &doc.nodes[c];
  9838. struct br_style cs;
  9839. int w, span;
  9840. if (cn->type != BR_NODE_ELEM ||
  9841. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9842. continue;
  9843. span = cn->colspan ? cn->colspan : 1;
  9844. br_style_for(&doc, c, pst, &cs);
  9845. if (cs.display == BR_DISPLAY_NONE)
  9846. continue;
  9847. if (col + span > maxcols)
  9848. span = maxcols - col;
  9849. if (span < 1)
  9850. break;
  9851. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  9852. mp_px(&cs, 7, avail) +
  9853. mp_px(&cs, 5, avail) +
  9854. mp_px(&cs, 3, avail) +
  9855. mp_px(&cs, 1, avail) +
  9856. cs.border_w[0] + cs.border_w[1] +
  9857. cs.border_w[2] + cs.border_w[3];
  9858. if (w < 24)
  9859. w = 24;
  9860. if (span == 1) {
  9861. if (w > raw[col])
  9862. raw[col] = w;
  9863. }
  9864. if (col + span > cols)
  9865. cols = col + span;
  9866. col += span;
  9867. }
  9868. }
  9869. /* A colspan cell only has to be as wide as the sum of its columns. */
  9870. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9871. struct br_node *rn = &doc.nodes[r];
  9872. int col = 0;
  9873. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9874. continue;
  9875. for (c = rn->first; c; c = doc.nodes[c].next) {
  9876. struct br_node *cn = &doc.nodes[c];
  9877. struct br_style cs;
  9878. int span, w, sum, i;
  9879. if (cn->type != BR_NODE_ELEM ||
  9880. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9881. continue;
  9882. span = cn->colspan ? cn->colspan : 1;
  9883. if (col + span > maxcols)
  9884. span = maxcols - col;
  9885. if (span < 1)
  9886. break;
  9887. if (span > 1) {
  9888. br_style_for(&doc, c, pst, &cs);
  9889. if (cs.display != BR_DISPLAY_NONE) {
  9890. w = intrinsic_width(l->ui, c, &cs,
  9891. 0, avail) +
  9892. mp_px(&cs, 7, avail) +
  9893. mp_px(&cs, 5, avail) +
  9894. mp_px(&cs, 3, avail) +
  9895. mp_px(&cs, 1, avail) +
  9896. cs.border_w[0] + cs.border_w[1] +
  9897. cs.border_w[2] + cs.border_w[3];
  9898. sum = 0;
  9899. for (i = 0; i < span; i++)
  9900. sum += raw[col + i];
  9901. if (w > sum)
  9902. raw[col + span - 1] += w - sum;
  9903. }
  9904. }
  9905. col += span;
  9906. }
  9907. }
  9908. /* Explicit and percentage widths override intrinsic widths. */
  9909. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9910. struct br_node *rn = &doc.nodes[r];
  9911. int col = 0;
  9912. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9913. continue;
  9914. for (c = rn->first; c; c = doc.nodes[c].next) {
  9915. struct br_node *cn = &doc.nodes[c];
  9916. struct br_style cs;
  9917. int span;
  9918. if (cn->type != BR_NODE_ELEM ||
  9919. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9920. continue;
  9921. span = cn->colspan ? cn->colspan : 1;
  9922. if (col + span > maxcols)
  9923. span = maxcols - col;
  9924. if (span < 1)
  9925. break;
  9926. if (span == 1) {
  9927. br_style_for(&doc, c, pst, &cs);
  9928. if (cs.display != BR_DISPLAY_NONE) {
  9929. if (cs.width_kind == 1) {
  9930. raw[col] = cs.width;
  9931. fixed[col] = 1;
  9932. } else if (cs.width_kind == 2 ||
  9933. cs.width_kind == 3) {
  9934. raw[col] = style_width_px(&cs,
  9935. avail);
  9936. fixed[col] = 1;
  9937. }
  9938. }
  9939. }
  9940. col += span;
  9941. }
  9942. }
  9943. for (c = 0; c < (unsigned int)cols; c++) {
  9944. if (raw[c] < 8)
  9945. raw[c] = 8;
  9946. total += raw[c];
  9947. if (fixed[c])
  9948. fixed_sum += raw[c];
  9949. else {
  9950. free_raw += raw[c];
  9951. free_cols++;
  9952. }
  9953. }
  9954. if (fixed_sum > 0 && fixed_sum < avail) {
  9955. int free_avail = avail - fixed_sum;
  9956. int i;
  9957. if (free_raw > 0) {
  9958. for (i = 0; i < cols; i++)
  9959. if (!fixed[i])
  9960. raw[i] = free_avail * raw[i] /
  9961. free_raw;
  9962. } else if (free_cols > 0) {
  9963. for (i = 0; i < cols; i++)
  9964. if (!fixed[i])
  9965. raw[i] = free_avail / free_cols;
  9966. }
  9967. total = 0;
  9968. for (i = 0; i < cols; i++)
  9969. total += raw[i];
  9970. } else if (total < avail && total > 0) {
  9971. int i;
  9972. for (i = 0; i < cols; i++)
  9973. raw[i] = raw[i] * avail / total;
  9974. total = 0;
  9975. for (i = 0; i < cols; i++)
  9976. total += raw[i];
  9977. }
  9978. *out_cols = cols;
  9979. *out_total = total;
  9980. }
  9981. static void layout_table_row(struct lay *l, unsigned int row,
  9982. const struct br_style *pst, int depth,
  9983. unsigned short link)
  9984. {
  9985. unsigned int n, cell[12];
  9986. int raw[12], colstart[12], colspan[12];
  9987. int prefix[13];
  9988. int ncell = 0, total = 0, cols = 0, col = 0;
  9989. int row_left = l->left, row_right = l->right;
  9990. int avail = row_right - row_left;
  9991. int y = l->y, bottom = l->y;
  9992. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  9993. struct br_node *nd = &doc.nodes[n];
  9994. struct br_style cs;
  9995. int span;
  9996. if (nd->type == BR_NODE_TEXT) {
  9997. if (text_node_blank(nd))
  9998. continue;
  9999. layout_children(l, row, pst, depth, link);
  10000. return;
  10001. }
  10002. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  10003. layout_children(l, row, pst, depth, link);
  10004. return;
  10005. }
  10006. br_style_for(&doc, n, pst, &cs);
  10007. if (cs.display == BR_DISPLAY_NONE)
  10008. continue;
  10009. if (ncell >= 12) {
  10010. layout_children(l, row, pst, depth, link);
  10011. return;
  10012. }
  10013. span = nd->colspan ? nd->colspan : 1;
  10014. if (span > 12 - col)
  10015. span = 12 - col;
  10016. if (span < 1)
  10017. continue;
  10018. cell[ncell] = n;
  10019. colstart[ncell] = col;
  10020. colspan[ncell] = span;
  10021. col += span;
  10022. ncell++;
  10023. }
  10024. if (ncell < 1 || avail < 32) {
  10025. layout_children(l, row, pst, depth, link);
  10026. return;
  10027. }
  10028. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  10029. &total);
  10030. if (cols < 2 || total <= 0) {
  10031. int c;
  10032. total = 0;
  10033. for (c = 0; c < ncell; c++) {
  10034. struct br_style cs;
  10035. br_style_for(&doc, cell[c], pst, &cs);
  10036. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  10037. avail) +
  10038. mp_px(&cs, 7, avail) +
  10039. mp_px(&cs, 5, avail) +
  10040. mp_px(&cs, 3, avail) +
  10041. mp_px(&cs, 1, avail);
  10042. if (raw[c] < 24)
  10043. raw[c] = 24;
  10044. total += raw[c];
  10045. }
  10046. /* A one-column table still has to fill its own width; the
  10047. * intrinsic fallback above otherwise leaves the cell at its
  10048. * text width (HN's outer table and nested story table). */
  10049. if (total > 0 && total < avail) {
  10050. int c;
  10051. for (c = 0; c < ncell; c++)
  10052. raw[c] = raw[c] * avail / total;
  10053. total = avail;
  10054. }
  10055. }
  10056. prefix[0] = row_left;
  10057. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  10058. prefix[n + 1] = prefix[n] + raw[n];
  10059. for (n = 0; n < (unsigned int)ncell; n++) {
  10060. struct br_style cs;
  10061. int start = colstart[n];
  10062. int end = start + colspan[n];
  10063. int w;
  10064. if (end > cols)
  10065. end = cols;
  10066. if (start >= cols)
  10067. continue;
  10068. w = prefix[end] - prefix[start];
  10069. br_style_for(&doc, cell[n], pst, &cs);
  10070. /* The column width already reflects the cell's width property. */
  10071. cs.width_kind = 0;
  10072. cs.max_width_kind = 0;
  10073. if (w < 24)
  10074. w = 24;
  10075. if (w < 8)
  10076. w = 8;
  10077. l->left = prefix[start];
  10078. l->right = l->left + w;
  10079. l->y = y;
  10080. l->line_x = l->left;
  10081. l->run_x = l->left;
  10082. l->line_y = l->y;
  10083. l->line_h = 0;
  10084. l->nruns = 0;
  10085. l->space_pending = 0;
  10086. l->align = cs.align;
  10087. layout_block(l, cell[n], &cs, depth + 1, link);
  10088. if (l->y > bottom)
  10089. bottom = l->y;
  10090. }
  10091. l->left = row_left;
  10092. l->right = row_right;
  10093. l->y = bottom;
  10094. l->line_x = l->left;
  10095. l->run_x = l->left;
  10096. l->line_y = l->y;
  10097. l->line_h = 0;
  10098. l->nruns = 0;
  10099. l->space_pending = 0;
  10100. }
  10101. #define TBL_MAX_ROWS 32
  10102. #define TBL_MAX_COLS 12
  10103. #define TBL_MAX_CELLS 128
  10104. struct tbl_cell {
  10105. unsigned int node;
  10106. unsigned char row, col, rowspan, colspan;
  10107. int height;
  10108. };
  10109. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  10110. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  10111. static int table_active;
  10112. static int table_has_rowspan(unsigned int table)
  10113. {
  10114. unsigned int r, c;
  10115. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10116. struct br_node *rn = &doc.nodes[r];
  10117. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10118. continue;
  10119. for (c = rn->first; c; c = doc.nodes[c].next) {
  10120. struct br_node *cn = &doc.nodes[c];
  10121. if (cn->type == BR_NODE_ELEM &&
  10122. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  10123. cn->rowspan > 1)
  10124. return 1;
  10125. }
  10126. }
  10127. return 0;
  10128. }
  10129. static void table_cell_style(unsigned int row, unsigned int cell,
  10130. const struct br_style *st, struct br_style *out)
  10131. {
  10132. struct br_style trs;
  10133. br_style_for(&doc, row, st, &trs);
  10134. br_style_for(&doc, cell, &trs, out);
  10135. }
  10136. /* Tables that use rowspan need row heights before anything is painted. This
  10137. * path builds a small occupancy grid, measures the natural cell heights, then
  10138. * lays every cell out at its row/column position. Tables without rowspan
  10139. * keep the lighter per-row path in layout_table_row(). */
  10140. static void layout_table(struct lay *l, unsigned int table,
  10141. const struct br_style *st, int depth,
  10142. unsigned short link)
  10143. {
  10144. unsigned int rows[TBL_MAX_ROWS];
  10145. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  10146. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  10147. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  10148. int free_raw = 0, free_cols = 0;
  10149. int table_left = l->left, table_right = l->right;
  10150. int top = l->y, avail = table_right - table_left;
  10151. unsigned int r, c;
  10152. int i, rr, cc;
  10153. if (depth > 48 || table_active) {
  10154. layout_children(l, table, st, depth, link);
  10155. return;
  10156. }
  10157. table_active = 1;
  10158. for (r = doc.nodes[table].first;
  10159. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  10160. struct br_node *rn = &doc.nodes[r];
  10161. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  10162. rows[nrows++] = r;
  10163. }
  10164. if (!nrows) {
  10165. table_active = 0;
  10166. layout_children(l, table, st, depth, link);
  10167. return;
  10168. }
  10169. for (rr = 0; rr < nrows; rr++)
  10170. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  10171. tbl_at[rr][cc] = 0;
  10172. for (rr = 0; rr < nrows; rr++) {
  10173. int col = 0;
  10174. for (c = doc.nodes[rows[rr]].first; c;
  10175. c = doc.nodes[c].next) {
  10176. struct br_node *cn = &doc.nodes[c];
  10177. struct br_style cs;
  10178. int rs, csn;
  10179. if (cn->type != BR_NODE_ELEM ||
  10180. (cn->tag != BR_TAG_TD &&
  10181. cn->tag != BR_TAG_TH))
  10182. continue;
  10183. table_cell_style(rows[rr], c, st, &cs);
  10184. if (cs.display == BR_DISPLAY_NONE)
  10185. continue;
  10186. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  10187. col++;
  10188. if (col >= TBL_MAX_COLS)
  10189. break;
  10190. rs = cn->rowspan ? cn->rowspan : 1;
  10191. csn = cn->colspan ? cn->colspan : 1;
  10192. if (rr + rs > nrows)
  10193. rs = nrows - rr;
  10194. if (col + csn > TBL_MAX_COLS)
  10195. csn = TBL_MAX_COLS - col;
  10196. if (rs < 1 || csn < 1)
  10197. continue;
  10198. if (ncells >= TBL_MAX_CELLS)
  10199. break;
  10200. tbl_cells[ncells].node = c;
  10201. tbl_cells[ncells].row = (unsigned char)rr;
  10202. tbl_cells[ncells].col = (unsigned char)col;
  10203. tbl_cells[ncells].rowspan = (unsigned char)rs;
  10204. tbl_cells[ncells].colspan = (unsigned char)csn;
  10205. tbl_cells[ncells].height = 0;
  10206. for (i = rr; i < rr + rs; i++)
  10207. for (int j = col; j < col + csn; j++)
  10208. tbl_at[i][j] =
  10209. (unsigned short)(ncells + 1);
  10210. ncells++;
  10211. col += csn;
  10212. if (col > cols)
  10213. cols = col;
  10214. }
  10215. }
  10216. if (!ncells || cols < 1) {
  10217. table_active = 0;
  10218. layout_children(l, table, st, depth, link);
  10219. return;
  10220. }
  10221. for (i = 0; i < cols; i++) {
  10222. raw[i] = 0;
  10223. fixed[i] = 0;
  10224. }
  10225. /* Intrinsic widths of single-column cells. */
  10226. for (i = 0; i < ncells; i++) {
  10227. struct br_style cs;
  10228. int w;
  10229. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10230. st, &cs);
  10231. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10232. mp_px(&cs, 7, avail) +
  10233. mp_px(&cs, 5, avail) +
  10234. mp_px(&cs, 3, avail) +
  10235. mp_px(&cs, 1, avail) +
  10236. cs.border_w[0] + cs.border_w[1] +
  10237. cs.border_w[2] + cs.border_w[3];
  10238. if (w < 24)
  10239. w = 24;
  10240. if (tbl_cells[i].colspan == 1) {
  10241. int col = tbl_cells[i].col;
  10242. if (w > raw[col])
  10243. raw[col] = w;
  10244. }
  10245. }
  10246. /* A spanning cell only needs the sum of its columns to be large
  10247. * enough; put the deficit in the last column. */
  10248. for (i = 0; i < ncells; i++) {
  10249. struct br_style cs;
  10250. int w, sum, col, span;
  10251. if (tbl_cells[i].colspan < 2)
  10252. continue;
  10253. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10254. st, &cs);
  10255. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10256. mp_px(&cs, 7, avail) +
  10257. mp_px(&cs, 5, avail) +
  10258. mp_px(&cs, 3, avail) +
  10259. mp_px(&cs, 1, avail) +
  10260. cs.border_w[0] + cs.border_w[1] +
  10261. cs.border_w[2] + cs.border_w[3];
  10262. col = tbl_cells[i].col;
  10263. span = tbl_cells[i].colspan;
  10264. sum = 0;
  10265. for (int j = 0; j < span; j++)
  10266. sum += raw[col + j];
  10267. if (w > sum)
  10268. raw[col + span - 1] += w - sum;
  10269. }
  10270. /* Explicit/percentage widths, as in table_columns(). */
  10271. for (i = 0; i < ncells; i++) {
  10272. struct br_style cs;
  10273. int col;
  10274. if (tbl_cells[i].colspan != 1)
  10275. continue;
  10276. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10277. st, &cs);
  10278. col = tbl_cells[i].col;
  10279. if (cs.width_kind == 1) {
  10280. raw[col] = cs.width;
  10281. fixed[col] = 1;
  10282. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  10283. raw[col] = style_width_px(&cs, avail);
  10284. fixed[col] = 1;
  10285. }
  10286. }
  10287. for (i = 0; i < cols; i++) {
  10288. if (raw[i] < 8)
  10289. raw[i] = 8;
  10290. total += raw[i];
  10291. if (fixed[i])
  10292. fixed_sum += raw[i];
  10293. else {
  10294. free_raw += raw[i];
  10295. free_cols++;
  10296. }
  10297. }
  10298. if (fixed_sum > 0 && fixed_sum < avail) {
  10299. int free_avail = avail - fixed_sum;
  10300. if (free_raw > 0) {
  10301. for (i = 0; i < cols; i++)
  10302. if (!fixed[i])
  10303. raw[i] = free_avail * raw[i] /
  10304. free_raw;
  10305. } else if (free_cols > 0) {
  10306. for (i = 0; i < cols; i++)
  10307. if (!fixed[i])
  10308. raw[i] = free_avail / free_cols;
  10309. }
  10310. } else if (total < avail && total > 0) {
  10311. for (i = 0; i < cols; i++)
  10312. raw[i] = raw[i] * avail / total;
  10313. }
  10314. prefix[0] = table_left;
  10315. for (i = 0; i < cols; i++)
  10316. prefix[i + 1] = prefix[i] + raw[i];
  10317. /* Measure natural cell heights with the column widths. */
  10318. for (i = 0; i < ncells; i++) {
  10319. struct br_style cs;
  10320. int col = tbl_cells[i].col;
  10321. int span = tbl_cells[i].colspan;
  10322. int w = prefix[col + span] - prefix[col];
  10323. int sl = l->left, sr = l->right, sy = l->y;
  10324. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10325. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10326. int sal = l->align, sdraw = l->draw;
  10327. struct ngui *sui = l->ui;
  10328. if (w < 8)
  10329. w = 8;
  10330. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10331. st, &cs);
  10332. cs.width_kind = 0;
  10333. cs.max_width_kind = 0;
  10334. l->draw = 0;
  10335. l->ui = 0;
  10336. l->left = prefix[col];
  10337. l->right = l->left + w;
  10338. l->y = 0;
  10339. l->line_x = l->left;
  10340. l->run_x = l->left;
  10341. l->line_y = 0;
  10342. l->line_h = 0;
  10343. l->nruns = 0;
  10344. l->space_pending = 0;
  10345. l->align = cs.align;
  10346. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10347. tbl_cells[i].height = block_h[tbl_cells[i].node];
  10348. l->left = sl;
  10349. l->right = sr;
  10350. l->y = sy;
  10351. l->line_x = slx;
  10352. l->run_x = srx;
  10353. l->line_y = sly;
  10354. l->line_h = slh;
  10355. l->nruns = snr;
  10356. l->space_pending = ssp;
  10357. l->align = sal;
  10358. l->draw = sdraw;
  10359. l->ui = sui;
  10360. }
  10361. for (i = 0; i < nrows; i++)
  10362. rowh[i] = 0;
  10363. for (i = 0; i < ncells; i++) {
  10364. int row = tbl_cells[i].row;
  10365. if (tbl_cells[i].rowspan == 1) {
  10366. if (tbl_cells[i].height > rowh[row])
  10367. rowh[row] = tbl_cells[i].height;
  10368. }
  10369. }
  10370. for (i = 0; i < ncells; i++) {
  10371. int row = tbl_cells[i].row;
  10372. int span = tbl_cells[i].rowspan;
  10373. int sum = 0;
  10374. if (span < 2)
  10375. continue;
  10376. for (int j = 0; j < span; j++)
  10377. sum += rowh[row + j];
  10378. if (sum < tbl_cells[i].height)
  10379. rowh[row + span - 1] +=
  10380. tbl_cells[i].height - sum;
  10381. }
  10382. for (i = 0; i < nrows; i++)
  10383. if (rowh[i] < 8)
  10384. rowh[i] = 8;
  10385. rowy[0] = top;
  10386. for (i = 1; i < nrows; i++)
  10387. rowy[i] = rowy[i - 1] + rowh[i - 1];
  10388. if (!l->draw) {
  10389. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10390. table_active = 0;
  10391. return;
  10392. }
  10393. for (i = 0; i < ncells; i++) {
  10394. struct br_style cs;
  10395. int col = tbl_cells[i].col;
  10396. int span = tbl_cells[i].colspan;
  10397. int row = tbl_cells[i].row;
  10398. int rspan = tbl_cells[i].rowspan;
  10399. int w = prefix[col + span] - prefix[col];
  10400. int h = 0;
  10401. int sl = l->left, sr = l->right, sy = l->y;
  10402. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10403. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10404. int sal = l->align;
  10405. int deco;
  10406. for (int j = 0; j < rspan; j++)
  10407. h += rowh[row + j];
  10408. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  10409. cs.width_kind = 0;
  10410. cs.max_width_kind = 0;
  10411. cs.box_sizing = 0;
  10412. deco = mp_px(&cs, 4, avail) +
  10413. mp_px(&cs, 6, avail) +
  10414. cs.border_w[0] + cs.border_w[2];
  10415. cs.height_kind = 1;
  10416. cs.height = h > deco ? h - deco : 0;
  10417. /* The block painter reads block_h[] from the measure pass; make
  10418. * the table cell fill its row/rowspan, not just its content. */
  10419. if (h > 0 && h < 65536)
  10420. block_h[tbl_cells[i].node] = (unsigned short)h;
  10421. l->left = prefix[col];
  10422. l->right = l->left + w;
  10423. l->y = rowy[row];
  10424. l->line_x = l->left;
  10425. l->run_x = l->left;
  10426. l->line_y = l->y;
  10427. l->line_h = 0;
  10428. l->nruns = 0;
  10429. l->space_pending = 0;
  10430. l->align = cs.align;
  10431. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10432. l->left = sl;
  10433. l->right = sr;
  10434. l->y = sy;
  10435. l->line_x = slx;
  10436. l->run_x = srx;
  10437. l->line_y = sly;
  10438. l->line_h = slh;
  10439. l->nruns = snr;
  10440. l->space_pending = ssp;
  10441. l->align = sal;
  10442. }
  10443. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10444. table_active = 0;
  10445. }
  10446. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  10447. * flow so they sit above it, like CSS painting order. Their flow origin is
  10448. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  10449. struct br_deferred {
  10450. unsigned int node;
  10451. int flow_y, flow_left, flow_right;
  10452. int parent_top; /* the parent box top, for sticky clamping */
  10453. unsigned short link;
  10454. signed short z_index;
  10455. unsigned char z_set;
  10456. unsigned int order;
  10457. };
  10458. /* Positioned boxes painted after the flow. News front pages have one or two
  10459. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  10460. * old 16 entries the rest fell back into the flow, so a hero image landed
  10461. * below its padding-top aspect box instead of on top of it. */
  10462. #define BR_MAX_DEFERRED 256
  10463. static struct br_deferred deferred[BR_MAX_DEFERRED];
  10464. static int ndeferred;
  10465. /* Outer width of an element's empty ::before (pe 1) / ::after (pe 2) icon
  10466. * box, 0 when it has none; *ps receives the pseudo-element's style. */
  10467. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  10468. struct br_style *ps, int base)
  10469. {
  10470. char buf[8];
  10471. int w, h;
  10472. if (!doc.npe_rules ||
  10473. br_pseudo(&doc, node, pe, st, ps, buf, sizeof(buf)) ||
  10474. ps->content != BR_CONTENT_EMPTY || ps->display == BR_DISPLAY_NONE)
  10475. return 0;
  10476. w = ps->width_kind ? style_width_px(ps, base) : 0;
  10477. h = ps->height_kind ? style_height_px(ps, base) : 0;
  10478. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  10479. w = (int)ps->min_width;
  10480. if (w <= 0)
  10481. w = h;
  10482. if (w <= 0 || w > 512)
  10483. return 0;
  10484. return w + (ps->ml_auto ? 0 : mp_px(ps, 3, base)) + mp_px(ps, 1, base);
  10485. }
  10486. /* An empty ::before/::after with a size and a background: one run the
  10487. * size of the box. Only data: background images are drawn (decoded at
  10488. * the background-size); `margin-left: auto` inside a flex parent pushes
  10489. * the box to the line's right edge like the flex row would. */
  10490. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  10491. const struct br_style *ps, unsigned short link)
  10492. {
  10493. struct lay_run *r;
  10494. int lw = l->line_right - l->line_left, w, h, ml, mr, tw, th;
  10495. const char *url = ps->bg_image ? br_bg_image_url(ps->bg_image - 1) : "";
  10496. if (lw < 8)
  10497. lw = 8;
  10498. w = ps->width_kind ? style_width_px(ps, lw) : 0;
  10499. h = ps->height_kind ? style_height_px(ps, lw) : 0;
  10500. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  10501. w = (int)ps->min_width;
  10502. if (w <= 0)
  10503. w = h;
  10504. if (h <= 0)
  10505. h = w;
  10506. if (w <= 0 || w > 512 || h > 512)
  10507. return;
  10508. ml = ps->ml_auto ? 0 : mp_px(ps, 3, lw);
  10509. mr = mp_px(ps, 1, lw);
  10510. if (ml < 0)
  10511. ml = 0;
  10512. if (mr < 0)
  10513. mr = 0;
  10514. if (l->line_x + ml + w > l->line_right &&
  10515. (l->nruns > 0 || l->line_x > l->line_left))
  10516. flush_line(l);
  10517. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  10518. flush_line(l);
  10519. if (l->nruns == 0) {
  10520. l->line_y = l->y;
  10521. l->line_h = 0;
  10522. start_line(l, ps);
  10523. }
  10524. if (ps->ml_auto && parent->display == BR_DISPLAY_FLEX &&
  10525. l->line_right - w - mr > l->line_x)
  10526. l->line_x = l->line_right - w - mr;
  10527. else
  10528. l->line_x += ml;
  10529. r = &l->runs[l->nruns++];
  10530. memset(r, 0, sizeof(*r));
  10531. r->gap = (unsigned short)(l->line_x > l->run_x ?
  10532. l->line_x - l->run_x : 0);
  10533. r->img = RUN_PBOX;
  10534. r->href = link;
  10535. r->iw = (unsigned short)w;
  10536. r->ih = (unsigned short)h;
  10537. r->w = (unsigned short)w;
  10538. r->font_px = ps->font_px;
  10539. r->pb_has_bg = ps->has_bg;
  10540. r->pb_bg = ps->bg;
  10541. r->pb_img = -1;
  10542. if (ps->transform_set) {
  10543. r->transform_scale = 1;
  10544. r->scale_x = ps->scale_x;
  10545. r->scale_y = ps->scale_y;
  10546. r->rotate_x100 = ps->rotate_x100;
  10547. }
  10548. /* Background size and position, as draw_bg_image() resolves them. */
  10549. tw = w;
  10550. th = h;
  10551. if (ps->bg_size_kind == 1 || ps->bg_size_kind == 2) {
  10552. int bw = ps->bg_size_w, bh = ps->bg_size_h;
  10553. if (ps->bg_size_kind == 2) {
  10554. bw = bw ? w * bw / 100 : 0;
  10555. bh = bh ? h * bh / 100 : 0;
  10556. }
  10557. tw = bw ? bw : (bh ? bh : w);
  10558. th = bh ? bh : tw;
  10559. }
  10560. if (tw > 0 && th > 0 && tw <= 512 && th <= 512 && url[0])
  10561. r->pb_img = (short)data_url_image(url, tw, th);
  10562. r->pb_w = (short)tw;
  10563. r->pb_h = (short)th;
  10564. r->pb_x = (short)(ps->bg_pos_x_kind == 1 ?
  10565. (w - tw) * ps->bg_pos_x / 100 : ps->bg_pos_x);
  10566. r->pb_y = (short)(ps->bg_pos_y_kind == 1 ?
  10567. (h - th) * ps->bg_pos_y / 100 : ps->bg_pos_y);
  10568. l->line_x += w + mr;
  10569. l->run_x = l->line_x;
  10570. if (l->line_h < h)
  10571. l->line_h = h;
  10572. }
  10573. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  10574. * element's line. A block-level pseudo-element gets its own line; its box
  10575. * (margins, padding, background) is not drawn. */
  10576. static void emit_pseudo(struct lay *l, unsigned int node,
  10577. const struct br_style *st, int pe, unsigned short link)
  10578. {
  10579. char buf[160];
  10580. struct br_style ps;
  10581. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  10582. unsigned int i = 0;
  10583. int block, space_w;
  10584. if (!n && ps.content == BR_CONTENT_EMPTY &&
  10585. ps.display != BR_DISPLAY_NONE) {
  10586. emit_pseudo_box(l, st, &ps, link);
  10587. return;
  10588. }
  10589. if (!n)
  10590. return;
  10591. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  10592. if (block)
  10593. flush_line(l);
  10594. if (ps.uppercase)
  10595. for (i = 0; i < n; i++)
  10596. if (buf[i] >= 'a' && buf[i] <= 'z')
  10597. buf[i] = (char)(buf[i] - 'a' + 'A');
  10598. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  10599. if (space_w <= 0)
  10600. space_w = 8;
  10601. i = 0;
  10602. while (i < n) {
  10603. char word[28];
  10604. unsigned int k = 0;
  10605. int w;
  10606. if (buf[i] == ' ') {
  10607. l->space_pending = 1;
  10608. i++;
  10609. continue;
  10610. }
  10611. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  10612. word[k++] = buf[i++];
  10613. word[k] = '\0';
  10614. if (l->space_pending &&
  10615. (l->nruns > 0 || l->line_x > l->line_left) &&
  10616. l->line_x + space_w <= l->line_right)
  10617. l->line_x += space_w;
  10618. l->space_pending = 0;
  10619. w = (int)face_text_width(l->ui, &ps, word, k);
  10620. if (l->line_x + w > l->line_right &&
  10621. (l->nruns > 0 || l->line_x > l->line_left))
  10622. flush_line(l);
  10623. add_run(l, 0, 0, &ps, link, word);
  10624. }
  10625. if (block)
  10626. flush_line(l);
  10627. }
  10628. static void layout_children(struct lay *l, unsigned int parent,
  10629. const struct br_style *pst, int depth,
  10630. unsigned short link)
  10631. {
  10632. unsigned int n;
  10633. if (depth > 48)
  10634. return;
  10635. emit_pseudo(l, parent, pst, 1, link);
  10636. n = doc.nodes[parent].first;
  10637. while (n) {
  10638. struct br_node *nd = &doc.nodes[n];
  10639. struct br_style cs;
  10640. unsigned short lk = link;
  10641. if (nd->type == BR_NODE_TEXT) {
  10642. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  10643. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  10644. n = nd->next;
  10645. continue;
  10646. }
  10647. br_style_for(&doc, n, pst, &cs);
  10648. if (cs.display == BR_DISPLAY_NONE) {
  10649. n = nd->next;
  10650. continue;
  10651. }
  10652. if (cs.clear && l->float_active) {
  10653. flush_line(l);
  10654. if (l->y < l->float_bottom)
  10655. l->y = l->float_bottom;
  10656. l->float_active = 0;
  10657. l->line_x = l->left;
  10658. l->run_x = l->left;
  10659. l->line_left = l->left;
  10660. l->line_right = l->right;
  10661. l->line_y = l->y;
  10662. l->line_h = 0;
  10663. l->nruns = 0;
  10664. l->space_pending = 0;
  10665. }
  10666. if (nd->tag == BR_TAG_A && nd->href_off)
  10667. lk = (unsigned short)n;
  10668. if (cs.pos == 1 || cs.pos == 2 ||
  10669. ((cs.pos == 3 || cs.pos == 4) && cs.z_set)) {
  10670. if ((cs.pos == 3 || cs.pos == 4) && l->draw &&
  10671. ndeferred < BR_MAX_DEFERRED) {
  10672. /* Relative or sticky z-index (a sticky site
  10673. * header): measure and advance the flow without
  10674. * painting, then paint it in the deferred
  10675. * (stacked) pass, above the content after it. */
  10676. int fy = l->y, fl = l->left, fr = l->right;
  10677. int save_draw = l->draw;
  10678. l->draw = 0;
  10679. layout_block(l, n, &cs, depth + 1, lk);
  10680. l->draw = save_draw;
  10681. deferred[ndeferred].node = n;
  10682. deferred[ndeferred].parent_top = l->parent_top;
  10683. deferred[ndeferred].flow_y = fy;
  10684. deferred[ndeferred].flow_left = fl;
  10685. deferred[ndeferred].flow_right = fr;
  10686. deferred[ndeferred].link = lk;
  10687. deferred[ndeferred].z_index = cs.z_index;
  10688. deferred[ndeferred].z_set = cs.z_set;
  10689. deferred[ndeferred].order = (unsigned int)ndeferred;
  10690. ndeferred++;
  10691. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  10692. deferred[ndeferred].node = n;
  10693. deferred[ndeferred].parent_top = l->parent_top;
  10694. deferred[ndeferred].flow_y =
  10695. cs.pos == 1 ? l->cb_top : l->y;
  10696. deferred[ndeferred].flow_left =
  10697. cs.pos == 1 ? l->cb_left : l->left;
  10698. deferred[ndeferred].flow_right =
  10699. cs.pos == 1 ? l->cb_right : l->right;
  10700. deferred[ndeferred].link = lk;
  10701. deferred[ndeferred].z_index = cs.z_index;
  10702. deferred[ndeferred].z_set = cs.z_set;
  10703. deferred[ndeferred].order = (unsigned int)ndeferred;
  10704. ndeferred++;
  10705. } else if (l->draw && cs.pos == 1) {
  10706. /* Deferred list full: paint in place, but still
  10707. * against the containing block, not the flow. */
  10708. int fy = l->y, fl = l->left, fr = l->right;
  10709. l->y = l->cb_top;
  10710. l->left = l->cb_left;
  10711. l->right = l->cb_right;
  10712. layout_block(l, n, &cs, depth + 1, lk);
  10713. l->y = fy;
  10714. l->left = fl;
  10715. l->right = fr;
  10716. } else {
  10717. layout_block(l, n, &cs, depth + 1, lk);
  10718. }
  10719. if (cs.pos == 1 && block_h[n] &&
  10720. doc.nodes[n].class_off) {
  10721. const char *cl = doc.attrs +
  10722. doc.nodes[n].class_off;
  10723. if ((contains_ci(cl, "poster-wrapper") ||
  10724. contains_ci(cl, "ts-picture")) &&
  10725. !has_skeleton_sibling(n))
  10726. l->y += block_h[n];
  10727. }
  10728. n = nd->next;
  10729. continue;
  10730. }
  10731. if (nd->tag == BR_TAG_BR) {
  10732. flush_line(l);
  10733. n = nd->next;
  10734. continue;
  10735. }
  10736. if (nd->tag == BR_TAG_HR) {
  10737. flush_line(l);
  10738. if (l->draw)
  10739. ngui_fill_rect(l->ui,
  10740. (struct ngui_rect){l->left, l->y + 2,
  10741. l->right - l->left, 1}, BR_GRAY);
  10742. l->y += 8;
  10743. n = nd->next;
  10744. continue;
  10745. }
  10746. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  10747. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  10748. !button_has_elements(n)) {
  10749. if (!(nd->tag == BR_TAG_INPUT &&
  10750. s_eq(br_type(&doc, n), "hidden"))) {
  10751. form_fill_line = pst->display ==
  10752. BR_DISPLAY_FLEX &&
  10753. pst->flex_col;
  10754. add_form_run(l, n, &cs, lk);
  10755. form_fill_line = 0;
  10756. }
  10757. n = nd->next;
  10758. continue;
  10759. }
  10760. if (nd->tag == BR_TAG_IMG) {
  10761. add_image_run(l, n, &cs, lk);
  10762. n = nd->next;
  10763. continue;
  10764. }
  10765. if (nd->tag == BR_TAG_SVG &&
  10766. (cs.display == BR_DISPLAY_INLINE ||
  10767. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  10768. !cs.float_left) {
  10769. add_svg_run(l, n, &cs, lk);
  10770. n = nd->next;
  10771. continue;
  10772. }
  10773. if (nd->tag == BR_TAG_VIDEO) {
  10774. layout_block(l, n, &cs, depth + 1, lk);
  10775. n = nd->next;
  10776. continue;
  10777. }
  10778. if (cs.float_left) {
  10779. n = layout_float_group(l, n, pst, depth, lk);
  10780. continue;
  10781. }
  10782. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  10783. inline_block_flows(n, &cs, 0)) {
  10784. layout_children(l, n, &cs, depth + 1, lk);
  10785. n = nd->next;
  10786. continue;
  10787. }
  10788. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  10789. n = layout_inline_blocks(l, n, pst, depth, link);
  10790. continue;
  10791. }
  10792. /* A flex container is block-level like any block box even when
  10793. * the element is an inline tag such as <a> (a link card with
  10794. * display:flex is common on news sites). Without the block box
  10795. * its children were laid out in the parent flow with a 0x0 box
  10796. * of their own. */
  10797. /* inline-flex around inline content only ("| mehr" link
  10798. * tails, icon+label pills) stays in the text line. */
  10799. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  10800. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  10801. !flex_wants_row(n, &cs)) {
  10802. layout_children(l, n, &cs, depth + 1, lk);
  10803. } else if (cs.display == BR_DISPLAY_BLOCK ||
  10804. cs.display == BR_DISPLAY_FLEX ||
  10805. br_tag_is_block(nd->tag))
  10806. layout_block(l, n, &cs, depth + 1, lk);
  10807. else {
  10808. layout_children(l, n, &cs, depth + 1, lk);
  10809. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  10810. l->space_pending = 1;
  10811. }
  10812. n = nd->next;
  10813. }
  10814. emit_pseudo(l, parent, pst, 2, link);
  10815. }
  10816. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  10817. * runs and a recursive page can otherwise overflow the stack. */
  10818. static struct lay layout_state;
  10819. static int measure_page(int left, int right)
  10820. {
  10821. struct lay *l = &layout_state;
  10822. struct br_style base = base_style();
  10823. unsigned int i;
  10824. for (i = 0; i < BR_MAX_NODES; i++) {
  10825. block_h[i] = 0;
  10826. img_top[i] = 0;
  10827. block_top[i] = 0;
  10828. img_h[i] = 0;
  10829. layout_boxes[i].valid = 0;
  10830. }
  10831. memset(li_marker, 0, sizeof(li_marker));
  10832. l->draw = 0;
  10833. l->ui = &ui;
  10834. l->left = left;
  10835. l->right = right;
  10836. l->y = 0;
  10837. l->line_x = left;
  10838. l->run_x = left;
  10839. l->line_left = left;
  10840. l->line_right = right;
  10841. l->line_y = 0;
  10842. l->line_h = 0;
  10843. l->align = BR_ALIGN_LEFT;
  10844. l->cb_h = layout_view_h;
  10845. l->float_active = 0;
  10846. l->parent_top = 0;
  10847. l->cb_left = left;
  10848. l->cb_right = right;
  10849. l->cb_top = 0;
  10850. l->depth = 0;
  10851. l->nruns = 0;
  10852. l->space_pending = 0;
  10853. base = root_style();
  10854. layout_children(l, doc.root, &base, 0, 0);
  10855. return l->y + 8;
  10856. }
  10857. static int deferred_cmp(const struct br_deferred *a,
  10858. const struct br_deferred *b)
  10859. {
  10860. int az = a->z_set ? a->z_index : 0;
  10861. int bz = b->z_set ? b->z_index : 0;
  10862. if (az != bz)
  10863. return az < bz ? -1 : 1;
  10864. if (a->order != b->order)
  10865. return a->order < b->order ? -1 : 1;
  10866. return 0;
  10867. }
  10868. static void sort_deferred(void)
  10869. {
  10870. int i;
  10871. for (i = 1; i < ndeferred; i++) {
  10872. struct br_deferred key = deferred[i];
  10873. int j = i;
  10874. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  10875. deferred[j] = deferred[j - 1];
  10876. j--;
  10877. }
  10878. deferred[j] = key;
  10879. }
  10880. }
  10881. static void render_page(int left, int right, int y0)
  10882. {
  10883. struct lay *l = &layout_state;
  10884. struct br_style base = base_style();
  10885. l->draw = 1;
  10886. l->ui = &ui;
  10887. l->left = left;
  10888. l->right = right;
  10889. l->y = y0;
  10890. l->line_x = left;
  10891. l->run_x = left;
  10892. l->line_left = left;
  10893. l->line_right = right;
  10894. l->line_y = y0;
  10895. l->line_h = 0;
  10896. l->align = BR_ALIGN_LEFT;
  10897. l->cb_h = layout_view_h;
  10898. l->float_active = 0;
  10899. l->parent_top = 0;
  10900. l->cb_left = left;
  10901. l->cb_right = right;
  10902. l->cb_top = y0;
  10903. l->depth = 0;
  10904. l->nruns = 0;
  10905. l->space_pending = 0;
  10906. nhits = 0;
  10907. ndeferred = 0;
  10908. base = root_style();
  10909. layout_children(l, doc.root, &base, 0, 0);
  10910. sort_deferred();
  10911. {
  10912. int i;
  10913. for (i = 0; i < ndeferred; i++) {
  10914. struct br_style st;
  10915. br_style_for(&doc, deferred[i].node, &base, &st);
  10916. if (st.display == BR_DISPLAY_NONE)
  10917. continue;
  10918. l->draw = 1;
  10919. l->left = deferred[i].flow_left;
  10920. l->right = deferred[i].flow_right;
  10921. l->y = deferred[i].flow_y;
  10922. l->parent_top = deferred[i].parent_top;
  10923. l->line_x = l->left;
  10924. l->run_x = l->left;
  10925. l->line_y = l->y;
  10926. l->line_h = 0;
  10927. l->nruns = 0;
  10928. l->space_pending = 0;
  10929. l->align = st.align;
  10930. if (st.pos == 2 && block_h[deferred[i].node]) {
  10931. struct ngui_rect clip;
  10932. int ch = block_h[deferred[i].node] + 24;
  10933. int pr = page_rect.x + page_rect.w - 12;
  10934. int x0 = page_rect.x, x1 = pr;
  10935. /* The background pre-fill spans the box's own
  10936. * columns, not the whole page: Docusaurus parks
  10937. * a white "Skip to main content" link at
  10938. * `left: 100%` with a z-index above the navbar,
  10939. * and a full-width fill painted over the bar. */
  10940. if (st.left_set)
  10941. x0 = page_rect.x + st.left;
  10942. if (st.width_kind == 1) {
  10943. if (st.right_set && !st.left_set)
  10944. x0 = pr - st.right - st.width;
  10945. x1 = x0 + st.width;
  10946. } else if (st.right_set) {
  10947. x1 = pr - st.right;
  10948. }
  10949. if (x0 >= pr || x1 <= page_rect.x)
  10950. continue; /* entirely off-screen */
  10951. if (x0 < page_rect.x)
  10952. x0 = page_rect.x;
  10953. if (x1 > pr)
  10954. x1 = pr;
  10955. clip.x = x0;
  10956. clip.y = page_rect.y;
  10957. clip.w = x1 - x0;
  10958. if (ch > page_rect.h)
  10959. ch = page_rect.h;
  10960. clip.h = ch;
  10961. ngui_push_clip(&ui, clip);
  10962. if (st.has_bg)
  10963. ngui_fill_rect(&ui, clip, st.bg);
  10964. layout_block(l, deferred[i].node, &st, 0,
  10965. deferred[i].link);
  10966. ngui_pop_clip(&ui);
  10967. } else {
  10968. layout_block(l, deferred[i].node, &st, 0,
  10969. deferred[i].link);
  10970. }
  10971. }
  10972. }
  10973. }
  10974. /* ---- UI ---- */
  10975. static int find_hit(int x, int y)
  10976. {
  10977. int i;
  10978. for (i = nhits - 1; i >= 0; i--) {
  10979. struct hit *h = &hits[i];
  10980. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  10981. y < h->y + h->h)
  10982. return (int)h->node;
  10983. }
  10984. return 0;
  10985. }
  10986. /* ---- URL-bar autocomplete ----
  10987. *
  10988. * While the address bar has the focus a dropdown lists up to SUG_MAX
  10989. * history entries. An empty bar (a fresh focus, Ctrl+L) shows the most
  10990. * visited/recent sites; typing ranks prefix matches of the URL (with or
  10991. * without the scheme and "www.") above substring matches of the URL, then
  10992. * of the title, and adds visit count and recency. Typing at the end of the
  10993. * text also completes inline to the next '/' of the best prefix match
  10994. * ("clo" -> "cloudron.io/"), with the added part selected so the next
  10995. * keystroke replaces it; Enter on that text opens the history URL it came
  10996. * from (scheme included). Up/Down preview a row in the bar, Delete on a
  10997. * highlighted row forgets it, Esc closes the list (a second Esc leaves the
  10998. * bar), and a click on a row opens it. */
  10999. #define SUG_MAX 6
  11000. #define SUG_ROW_H 36
  11001. static int sug_idx[SUG_MAX];
  11002. static int sug_n, sug_sel = -1, sug_open;
  11003. static char sug_typed[NGUI_INPUT_MAX]; /* what the user typed */
  11004. static char sug_restore[NGUI_INPUT_MAX]; /* bar text before a preview */
  11005. static char ac_text[NGUI_INPUT_MAX]; /* bar text of the inline completion */
  11006. static char ac_url[HIST_URL_MAX]; /* the history URL it stands for */
  11007. static struct ngui_rect url_rect, sug_rect;
  11008. static int url_had_focus;
  11009. static char lc(char c)
  11010. {
  11011. return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
  11012. }
  11013. static int prefix_ci(const char *s, const char *p) /* p is lower case */
  11014. {
  11015. for (; *p; s++, p++)
  11016. if (lc(*s) != *p)
  11017. return 0;
  11018. return 1;
  11019. }
  11020. static unsigned int url_scheme_len(const char *url)
  11021. {
  11022. if (starts_with(url, "https://"))
  11023. return 8;
  11024. if (starts_with(url, "http://"))
  11025. return 7;
  11026. return 0;
  11027. }
  11028. /* Offset in `url` where the lower-case text `t` matches as a prefix: the
  11029. * whole URL, the URL without its scheme, or without scheme and "www.". */
  11030. static int hist_prefix_at(const char *url, const char *t)
  11031. {
  11032. unsigned int s = url_scheme_len(url);
  11033. if (prefix_ci(url, t))
  11034. return 0;
  11035. if (s && prefix_ci(url + s, t))
  11036. return (int)s;
  11037. if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
  11038. return (int)s + 4;
  11039. return -1;
  11040. }
  11041. static int hist_score(const struct hist_ent *e, const char *t,
  11042. unsigned int next)
  11043. {
  11044. unsigned int age = next - e->stamp;
  11045. int sc, at;
  11046. if (!t[0]) {
  11047. sc = 0;
  11048. } else if ((at = hist_prefix_at(e->url, t)) >= 0) {
  11049. /* Shorter rests first: "cloudron.io/" before its subpages. */
  11050. int rest = (int)s_len(e->url + at);
  11051. sc = 4000 - (rest > 400 ? 400 : rest);
  11052. } else if (contains_ci(e->url, t)) {
  11053. sc = 1000;
  11054. } else if (contains_ci(e->title, t)) {
  11055. sc = 600;
  11056. } else {
  11057. return -1;
  11058. }
  11059. sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
  11060. sc += age >= 500 ? 0 : (int)(500 - age);
  11061. return sc;
  11062. }
  11063. static void sug_lower(char *t, unsigned int cap)
  11064. {
  11065. unsigned int k;
  11066. for (k = 0; sug_typed[k] && k + 1 < cap; k++)
  11067. t[k] = lc(sug_typed[k]);
  11068. t[k] = '\0';
  11069. }
  11070. static void sug_refresh(void)
  11071. {
  11072. char t[NGUI_INPUT_MAX];
  11073. int sc[SUG_MAX], i, j;
  11074. unsigned int next = hist_next_stamp();
  11075. sug_lower(t, sizeof(t));
  11076. sug_n = 0;
  11077. for (i = 0; i < hist_n; i++) {
  11078. int s = hist_score(&hist_tab[i], t, next);
  11079. if (s < 0)
  11080. continue;
  11081. j = sug_n;
  11082. if (j == SUG_MAX) {
  11083. if (sc[SUG_MAX - 1] >= s)
  11084. continue;
  11085. j = SUG_MAX - 1;
  11086. }
  11087. while (j > 0 && sc[j - 1] < s) {
  11088. sc[j] = sc[j - 1];
  11089. sug_idx[j] = sug_idx[j - 1];
  11090. j--;
  11091. }
  11092. sc[j] = s;
  11093. sug_idx[j] = i;
  11094. if (sug_n < SUG_MAX)
  11095. sug_n++;
  11096. }
  11097. if (sug_sel >= sug_n)
  11098. sug_sel = -1;
  11099. }
  11100. /* Complete the typed text inline to the next '/' of the best prefix match. */
  11101. static void sug_inline(void)
  11102. {
  11103. char t[NGUI_INPUT_MAX];
  11104. const char *url, *rest;
  11105. unsigned int L, start, end, hs, tn, n = 0;
  11106. unsigned int next = hist_next_stamp();
  11107. int i, best = -1, best_sc = -1, at = 0;
  11108. sug_lower(t, sizeof(t));
  11109. L = s_len(t);
  11110. if (!L)
  11111. return;
  11112. for (i = 0; i < hist_n; i++) {
  11113. int a = hist_prefix_at(hist_tab[i].url, t), s;
  11114. if (a < 0)
  11115. continue;
  11116. s = hist_score(&hist_tab[i], t, next);
  11117. if (s > best_sc) {
  11118. best_sc = s;
  11119. best = i;
  11120. at = a;
  11121. }
  11122. }
  11123. if (best < 0)
  11124. return;
  11125. url = hist_tab[best].url;
  11126. rest = url + at;
  11127. /* Typing the scheme ("htt") completes past "https://", not to it. */
  11128. hs = at == 0 ? url_scheme_len(url) : 0;
  11129. start = L > hs ? L : hs;
  11130. end = start;
  11131. while (rest[end] && rest[end] != '/')
  11132. end++;
  11133. if (rest[end] == '/')
  11134. end++;
  11135. tn = s_len(sug_typed);
  11136. if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
  11137. return;
  11138. s_append(ac_text, &n, sug_typed, sizeof(ac_text));
  11139. for (; L < end && n + 1 < sizeof(ac_text); L++)
  11140. ac_text[n++] = rest[L];
  11141. ac_text[n] = '\0';
  11142. s_copy(ac_url, url, (unsigned int)at + end + 1);
  11143. ngui_input_set(&url_in, ac_text);
  11144. url_in.anchor = tn; /* select the completed part */
  11145. }
  11146. static void sug_close(void)
  11147. {
  11148. sug_open = 0;
  11149. sug_sel = -1;
  11150. ac_text[0] = '\0';
  11151. }
  11152. static int sug_visible(void)
  11153. {
  11154. return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
  11155. }
  11156. /* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
  11157. * start page) lists the top sites until something is typed. */
  11158. static int sug_focus_check(void)
  11159. {
  11160. int focused = ngui_focus(&ui) == ID_URL;
  11161. if (focused && !url_had_focus) {
  11162. sug_typed[0] = '\0';
  11163. sug_close();
  11164. sug_open = 1;
  11165. sug_refresh();
  11166. }
  11167. url_had_focus = focused;
  11168. return focused;
  11169. }
  11170. static void url_submit(unsigned int *action)
  11171. {
  11172. if (ac_text[0] && s_eq(url_in.text, ac_text))
  11173. s_copy(click_url, ac_url, sizeof(click_url));
  11174. *action |= ACT_NAV;
  11175. sug_close();
  11176. }
  11177. /* The bar text changed through typing or editing. */
  11178. static void sug_changed(void)
  11179. {
  11180. unsigned int pl = s_len(sug_typed);
  11181. int grew = url_in.len > pl && url_in.cursor == url_in.len &&
  11182. !memcmp(url_in.text, sug_typed, pl);
  11183. s_copy(sug_typed, url_in.text, sizeof(sug_typed));
  11184. ac_text[0] = '\0';
  11185. sug_sel = -1;
  11186. sug_open = 1;
  11187. sug_refresh();
  11188. if (grew)
  11189. sug_inline();
  11190. }
  11191. /* Keys for the list, taken off the queue before the text field sees them.
  11192. * Only a leading run is handled; the rest goes to the field. */
  11193. static void sug_keys(void)
  11194. {
  11195. int k;
  11196. while ((k = ngui_key_peek(&ui)) != 0) {
  11197. if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
  11198. ngui_key(&ui);
  11199. if (!sug_open) {
  11200. sug_open = 1;
  11201. continue;
  11202. }
  11203. if (sug_sel < 0)
  11204. s_copy(sug_restore, url_in.text,
  11205. sizeof(sug_restore));
  11206. if (k == NGUI_KEY_DOWN)
  11207. sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
  11208. else
  11209. sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
  11210. ngui_input_set(&url_in, sug_sel >= 0 ?
  11211. hist_tab[sug_idx[sug_sel]].url :
  11212. sug_restore);
  11213. } else if (k == NGUI_KEY_ESC && sug_visible()) {
  11214. ngui_key(&ui);
  11215. if (sug_sel >= 0)
  11216. ngui_input_set(&url_in, sug_restore);
  11217. else if (ac_text[0] && s_eq(url_in.text, ac_text))
  11218. ngui_input_set(&url_in, sug_typed);
  11219. sug_close();
  11220. } else if (k == NGUI_KEY_DELETE && sug_visible() &&
  11221. sug_sel >= 0) {
  11222. ngui_key(&ui);
  11223. hist_forget(sug_idx[sug_sel]);
  11224. ngui_input_set(&url_in, sug_restore);
  11225. sug_sel = -1;
  11226. sug_refresh();
  11227. } else {
  11228. break;
  11229. }
  11230. }
  11231. }
  11232. /* A press on a row of last frame's list opens it; any press on the list is
  11233. * swallowed so the page underneath does not see it. */
  11234. static void sug_click(unsigned int *action)
  11235. {
  11236. int row;
  11237. if (!(ui.pressed & 1) || !sug_rect.w ||
  11238. !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
  11239. return;
  11240. row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
  11241. if (row >= 0 && row < sug_n) {
  11242. s_copy(click_url, hist_tab[sug_idx[row]].url,
  11243. sizeof(click_url));
  11244. *action |= ACT_NAV;
  11245. sug_close();
  11246. }
  11247. ui.pressed = 0;
  11248. }
  11249. static void draw_suggest(struct ngui_rect page)
  11250. {
  11251. struct ngui_rect r;
  11252. int i, rows = sug_n, hover = -1;
  11253. r.x = url_rect.x;
  11254. r.y = url_rect.y + url_rect.h + 1;
  11255. r.w = url_rect.w < 320 ? 320 : url_rect.w;
  11256. if (r.x + r.w > ui.w - 2)
  11257. r.w = ui.w - 2 - r.x;
  11258. while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
  11259. rows--;
  11260. if (rows <= 0 || r.w < 60) {
  11261. sug_rect.w = 0;
  11262. return;
  11263. }
  11264. r.h = rows * SUG_ROW_H + 2;
  11265. sug_rect = r;
  11266. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  11267. hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
  11268. ngui_set_cursor(&ui, CURSOR_POINTER);
  11269. }
  11270. ngui_fill_rect(&ui, r, ui.theme.border);
  11271. for (i = 0; i < rows; i++) {
  11272. const struct hist_ent *e = &hist_tab[sug_idx[i]];
  11273. struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
  11274. r.w - 2, SUG_ROW_H};
  11275. struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
  11276. unsigned short bg = i == sug_sel ? ui.theme.selection :
  11277. i == hover ? ui.theme.panel_alt :
  11278. ui.theme.panel;
  11279. ngui_fill_rect(&ui, rr, bg);
  11280. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
  11281. e->title[0] ? e->title : e->url,
  11282. ui.theme.text);
  11283. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
  11284. i == sug_sel ? ui.theme.text :
  11285. ui.theme.text_dim);
  11286. }
  11287. }
  11288. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  11289. {
  11290. int x = r.x + 4, y = r.y + 4, h = 22;
  11291. int compact = r.w < 560;
  11292. int go_w = r.w < 420 ? 32 : 42;
  11293. int in_x, in_w, res;
  11294. ngui_fill_rect(&ui, r, ui.theme.panel);
  11295. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  11296. ui.theme.border);
  11297. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  11298. NGUI_ICON_CHEVRON_LEFT))
  11299. *action |= ACT_BACK;
  11300. x += 32;
  11301. if (!compact) {
  11302. if (ngui_icon_button(&ui, ID_FORWARD,
  11303. (struct ngui_rect){x, y, 28, h},
  11304. NGUI_ICON_CHEVRON_RIGHT))
  11305. *action |= ACT_FORWARD;
  11306. x += 32;
  11307. }
  11308. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  11309. NGUI_ICON_REFRESH))
  11310. *action |= ACT_RELOAD;
  11311. x += 32;
  11312. if (!compact) {
  11313. if (ngui_icon_button(&ui, ID_HOME,
  11314. (struct ngui_rect){x, y, 28, h},
  11315. NGUI_ICON_HOME))
  11316. *action |= ACT_HOME;
  11317. x += 32;
  11318. }
  11319. in_x = x + 2;
  11320. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  11321. if (in_w < 60)
  11322. in_w = 60;
  11323. url_rect = (struct ngui_rect){in_x, y, in_w, h};
  11324. if (sug_focus_check())
  11325. sug_keys();
  11326. res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
  11327. sug_focus_check(); /* a click into the bar focuses it here */
  11328. if (res & NGUI_INPUT_CHANGED)
  11329. sug_changed();
  11330. if (res & NGUI_INPUT_SUBMIT)
  11331. url_submit(action);
  11332. if (res & NGUI_INPUT_CANCEL)
  11333. ngui_set_focus(&ui, 0);
  11334. if (ngui_button(&ui, ID_GO,
  11335. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  11336. "Go"))
  11337. url_submit(action);
  11338. if (!sug_focus_check())
  11339. sug_close();
  11340. }
  11341. static int page_hover_node(void)
  11342. {
  11343. if (!ui.inside)
  11344. return 0;
  11345. if (ui.mouse_x < page_rect.x ||
  11346. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  11347. ui.mouse_y < page_rect.y ||
  11348. ui.mouse_y >= page_rect.y + page_rect.h)
  11349. return 0;
  11350. return find_hit(ui.mouse_x, ui.mouse_y);
  11351. }
  11352. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  11353. {
  11354. int x, y, w = page.w, h = page.h;
  11355. if (!src || w <= 0 || h <= 0)
  11356. return;
  11357. for (y = 0; y < h; y++) {
  11358. unsigned short *s = src + (page.y + y) * sw + page.x;
  11359. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  11360. for (x = 0; x + 1 < w; x += 2) {
  11361. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  11362. }
  11363. if (x < w)
  11364. d[x] = s[x];
  11365. }
  11366. }
  11367. static void draw_page(struct ngui_rect page)
  11368. {
  11369. int left, right, ch;
  11370. int old_panel, old_dim;
  11371. unsigned short *saved_px;
  11372. unsigned short page_bg = ui.theme.bg;
  11373. int saved_w, saved_h, use_buf;
  11374. unsigned int t0 = u_ticks_ms();
  11375. page_rect = page;
  11376. {
  11377. unsigned int root = doc.nnode > 1 ?
  11378. br_find_tag(&doc, BR_TAG_HTML) : 0;
  11379. unsigned int body = doc.nnode > 1 ?
  11380. br_find_tag(&doc, BR_TAG_BODY) : 0;
  11381. struct br_style bs;
  11382. int bg_found = 0;
  11383. if (root) {
  11384. style_for_node(root - 1, &bs);
  11385. if (bs.has_bg) {
  11386. page_bg = bs.bg;
  11387. bg_found = 1;
  11388. }
  11389. }
  11390. if (body) {
  11391. style_for_node(body - 1, &bs);
  11392. if (bs.has_bg) {
  11393. page_bg = bs.bg;
  11394. bg_found = 1;
  11395. }
  11396. }
  11397. /* No canvas colour, but the author made the text dark
  11398. * (Infima's light theme: `--ifm-background-color:
  11399. * transparent` on html, #1c1e21 text): the page expects the
  11400. * white canvas of a normal browser, and dark text on the
  11401. * dark default canvas is unreadable. */
  11402. if (!bg_found && (body || root) && bs.color != ui.theme.text) {
  11403. unsigned int c = bs.color;
  11404. unsigned int lum = ((c >> 11) & 31) * 8 * 299 +
  11405. ((c >> 5) & 63) * 4 * 587 +
  11406. (c & 31) * 8 * 114;
  11407. if (lum < 100 * 1000)
  11408. page_bg = 0xFFFF;
  11409. }
  11410. }
  11411. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  11412. page_cache_valid && layout_valid &&
  11413. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  11414. !(ui.scroll_y &&
  11415. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  11416. page_scroll.offset == page_cache_scroll &&
  11417. page_cache_nnode == doc.nnode &&
  11418. page_cache_x == page.x && page_cache_y == page.y &&
  11419. page_cache_w == page.w && page_cache_h == page.h) {
  11420. blit_page(page, page_backbuf, pagebuf_w);
  11421. if (img_stat_n)
  11422. img_stat_paint += u_ticks_ms() - t0;
  11423. return;
  11424. }
  11425. ngui_fill_rect(&ui, page, page_bg);
  11426. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  11427. const char *s = page_loading ? "Loading..." : "No page";
  11428. int w = (int)ngui_text_width_ui(&ui, s);
  11429. ngui_text(&ui, page.x + (page.w - w) / 2,
  11430. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  11431. page_scroll.content_h = 0;
  11432. page_scroll.view_h = page.h;
  11433. page_cache_valid = 0;
  11434. return;
  11435. }
  11436. if (page.w < 40 || page.h < 40) {
  11437. page_cache_valid = 0;
  11438. return;
  11439. }
  11440. saved_px = ui.px;
  11441. saved_w = ui.w;
  11442. saved_h = ui.h;
  11443. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  11444. if (use_buf) {
  11445. ui.px = page_backbuf;
  11446. ui.w = pagebuf_w;
  11447. ui.h = pagebuf_h;
  11448. ngui_fill_rect(&ui, page, page_bg);
  11449. }
  11450. left = page.x + 8;
  11451. right = page.x + page.w - 16;
  11452. if (!layout_valid || left != layout_left || right != layout_right ||
  11453. layout_nnode != doc.nnode) {
  11454. unsigned int tm = u_ticks_ms();
  11455. layout_view_h = page.h - 8;
  11456. layout_content_h = measure_page(left, right);
  11457. if (img_stat_n)
  11458. img_stat_reflow += u_ticks_ms() - tm;
  11459. layout_valid = 1;
  11460. layout_left = left;
  11461. layout_right = right;
  11462. layout_nnode = doc.nnode;
  11463. /* Scripts that measured before any layout (offsetWidth on
  11464. * mount) get a resize event once real boxes exist, and again
  11465. * whenever the page width changes. */
  11466. if (js_browser_active() && right - left != resize_sent_w)
  11467. resize_pending = 1;
  11468. }
  11469. ch = layout_content_h;
  11470. page_scroll.content_h = ch;
  11471. page_scroll.view_h = page.h;
  11472. t0 = u_ticks_ms();
  11473. ngui_scroll_begin(&ui, page, &page_scroll);
  11474. ngui_scroll_wheel(&ui, page, &page_scroll);
  11475. render_page(left, right, page.y + 4 - page_scroll.offset);
  11476. old_panel = ui.theme.panel_alt;
  11477. old_dim = ui.theme.text_dim;
  11478. ui.theme.panel_alt = 0xC618;
  11479. ui.theme.text_dim = 0x8410;
  11480. ngui_scroll_end(&ui, page, &page_scroll);
  11481. ui.theme.panel_alt = old_panel;
  11482. ui.theme.text_dim = old_dim;
  11483. if (use_buf) {
  11484. ui.px = saved_px;
  11485. ui.w = saved_w;
  11486. ui.h = saved_h;
  11487. blit_page(page, page_backbuf, pagebuf_w);
  11488. page_cache_valid = 1;
  11489. page_cache_scroll = page_scroll.offset;
  11490. page_cache_nnode = doc.nnode;
  11491. page_cache_x = page.x;
  11492. page_cache_y = page.y;
  11493. page_cache_w = page.w;
  11494. page_cache_h = page.h;
  11495. } else {
  11496. page_cache_valid = 0;
  11497. }
  11498. if (img_stat_n)
  11499. img_stat_paint += u_ticks_ms() - t0;
  11500. }
  11501. static void draw_status(struct ngui_rect r)
  11502. {
  11503. static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
  11504. unsigned int n = 0;
  11505. int hover = page_hover_node();
  11506. unsigned short color;
  11507. const char *kind;
  11508. ngui_fill_rect(&ui, r, ui.theme.panel);
  11509. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  11510. ui.theme.border);
  11511. if (hover) {
  11512. const char *href = br_href(&doc, (unsigned int)hover);
  11513. char url[BR_URL_MAX];
  11514. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  11515. s_append(msg, &n, "Link: ", sizeof(msg));
  11516. s_append(msg, &n, url, sizeof(msg));
  11517. } else {
  11518. s_copy(msg, "Link", sizeof(msg));
  11519. }
  11520. color = ui.theme.accent;
  11521. } else if (status_text[0]) {
  11522. s_copy(msg, status_text, sizeof(msg));
  11523. color = status_error ? ui.theme.error : ui.theme.text;
  11524. } else if (page_title[0]) {
  11525. s_copy(msg, page_title, sizeof(msg));
  11526. color = ui.theme.text;
  11527. } else {
  11528. s_copy(msg, "Ready", sizeof(msg));
  11529. color = ui.theme.text_dim;
  11530. }
  11531. kind = s_eq(page_url, "about:home") ? "HOME" :
  11532. page_is_local ? "FILE" :
  11533. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  11534. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  11535. {
  11536. int kw = (int)ngui_text_width_ui(&ui, kind);
  11537. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  11538. ui.theme.text_dim);
  11539. }
  11540. }
  11541. /* Mouse cursor over the page: the hovered node's CSS `cursor` (inherited);
  11542. * for `auto`, a hand over links, the I-beam over text fields, and the
  11543. * progress arrow anywhere on the page while it is still loading. The
  11544. * toolbar's URL field sets its own I-beam through ngui. */
  11545. static void page_cursor(void)
  11546. {
  11547. int hover = page_hover_node();
  11548. struct br_style st;
  11549. if (!hover) {
  11550. if (page_loading && ui.inside &&
  11551. ngui_rect_contains(&page_rect, ui.mouse_x, ui.mouse_y))
  11552. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  11553. return;
  11554. }
  11555. style_for_node((unsigned int)hover, &st);
  11556. if (st.cursor != BR_CURSOR_AUTO) {
  11557. ngui_set_cursor(&ui, (int)st.cursor - 1);
  11558. return;
  11559. }
  11560. if (br_href(&doc, (unsigned int)hover)) {
  11561. ngui_set_cursor(&ui, CURSOR_POINTER);
  11562. return;
  11563. }
  11564. if (form_is_control((unsigned int)hover)) {
  11565. int k = form_kind_of((unsigned int)hover);
  11566. if (form_disabled((unsigned int)hover))
  11567. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  11568. else if (k == FORM_TEXT || k == FORM_PASSWORD ||
  11569. k == FORM_TEXTAREA)
  11570. ngui_set_cursor(&ui, CURSOR_TEXT);
  11571. return;
  11572. }
  11573. if (page_loading)
  11574. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  11575. }
  11576. static void draw(unsigned int *action)
  11577. {
  11578. struct ngui_rect r = {0, 0, ui.w, ui.h};
  11579. struct ngui_rect toolbar, status, page;
  11580. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  11581. status = ngui_cut_bottom(&r, BR_STATUS_H);
  11582. page = r;
  11583. if (sug_visible())
  11584. sug_click(action);
  11585. draw_toolbar(toolbar, action);
  11586. draw_page(page);
  11587. draw_status(status);
  11588. page_cursor();
  11589. if (sug_visible())
  11590. draw_suggest(page);
  11591. else
  11592. sug_rect.w = 0;
  11593. }
  11594. static void redraw_now(void)
  11595. {
  11596. unsigned int action = 0;
  11597. ngui_begin(&ui);
  11598. draw(&action);
  11599. ngui_end(&ui);
  11600. }
  11601. static void handle_keys(unsigned int *action)
  11602. {
  11603. int k, scrolled = 0;
  11604. if (form_focus >= doc.nnode)
  11605. form_focus = 0;
  11606. if (form_focus && !ngui_focus(&ui)) {
  11607. while ((k = ngui_key(&ui)) != 0)
  11608. form_key(k);
  11609. return;
  11610. }
  11611. /* Batch queued page keys: a slow full-page render must not make a
  11612. * held Page Down advance only once every few frames. */
  11613. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  11614. scrolled++;
  11615. if (scrolled)
  11616. ngui_invalidate(&ui);
  11617. if (ngui_focus(&ui))
  11618. return;
  11619. while ((k = ngui_key(&ui)) != 0) {
  11620. switch (k) {
  11621. case NGUI_KEY_ESC:
  11622. *action |= ACT_CLOSE;
  11623. break;
  11624. case NGUI_KEY_TAB:
  11625. case 0x0C: /* Ctrl+L */
  11626. ngui_set_focus(&ui, ID_URL);
  11627. break;
  11628. case 0x12: /* Ctrl+R */
  11629. *action |= ACT_RELOAD;
  11630. break;
  11631. case NGUI_KEY_BACKSPACE:
  11632. *action |= ACT_BACK;
  11633. break;
  11634. case NGUI_KEY_UP:
  11635. ngui_scroll_to(&page_scroll,
  11636. page_scroll.offset - 24);
  11637. ngui_invalidate(&ui);
  11638. break;
  11639. case NGUI_KEY_DOWN:
  11640. ngui_scroll_to(&page_scroll,
  11641. page_scroll.offset + 24);
  11642. ngui_invalidate(&ui);
  11643. break;
  11644. case NGUI_KEY_HOME:
  11645. ngui_scroll_to(&page_scroll, 0);
  11646. ngui_invalidate(&ui);
  11647. break;
  11648. case NGUI_KEY_END:
  11649. ngui_scroll_to(&page_scroll,
  11650. page_scroll.content_h -
  11651. page_scroll.view_h);
  11652. ngui_invalidate(&ui);
  11653. break;
  11654. default:
  11655. break;
  11656. }
  11657. }
  11658. }
  11659. static unsigned int form_ancestor(unsigned int node)
  11660. {
  11661. unsigned int p = node;
  11662. while (p && p < doc.nnode) {
  11663. if (doc.nodes[p].tag == BR_TAG_FORM &&
  11664. doc.nodes[p].type == BR_NODE_ELEM)
  11665. return p;
  11666. p = doc.nodes[p].parent;
  11667. }
  11668. return 0;
  11669. }
  11670. static int form_descendant(unsigned int node, unsigned int form)
  11671. {
  11672. unsigned int p = node;
  11673. while (p && p < doc.nnode) {
  11674. if (p == form)
  11675. return 1;
  11676. p = doc.nodes[p].parent;
  11677. }
  11678. return 0;
  11679. }
  11680. static void form_reset_form(unsigned int form)
  11681. {
  11682. unsigned int i;
  11683. for (i = 0; i < FORM_MAX; i++)
  11684. if (form_states[i].used &&
  11685. form_descendant(form_states[i].node, form))
  11686. form_states[i].used = 0;
  11687. form_focus = 0;
  11688. }
  11689. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  11690. const char *s)
  11691. {
  11692. static const char hex[] = "0123456789ABCDEF";
  11693. while (s && *s && *n + 1 < cap) {
  11694. unsigned char c = (unsigned char)*s++;
  11695. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  11696. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  11697. c == '.' || c == '~') {
  11698. dst[(*n)++] = (char)c;
  11699. } else if (c == ' ') {
  11700. dst[(*n)++] = '+';
  11701. } else if (*n + 3 < cap) {
  11702. dst[(*n)++] = '%';
  11703. dst[(*n)++] = hex[c >> 4];
  11704. dst[(*n)++] = hex[c & 15];
  11705. }
  11706. }
  11707. dst[*n] = '\0';
  11708. }
  11709. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  11710. const char *name, const char *value, int *first)
  11711. {
  11712. if (!name || !name[0])
  11713. return;
  11714. if (!*first && *n + 1 < cap)
  11715. dst[(*n)++] = '&';
  11716. *first = 0;
  11717. form_url_append(dst, n, cap, name);
  11718. if (*n + 1 < cap)
  11719. dst[(*n)++] = '=';
  11720. form_url_append(dst, n, cap, value ? value : "");
  11721. dst[*n] = '\0';
  11722. }
  11723. static int form_submit_form(unsigned int node, int fire_event)
  11724. {
  11725. unsigned int form = form_ancestor(node);
  11726. char action[BR_URL_MAX], query[2048];
  11727. unsigned int qn = 0, i;
  11728. int first = 1, is_post = 0;
  11729. const char *a, *method;
  11730. if (!form)
  11731. return 0;
  11732. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  11733. return 0;
  11734. method = br_find_attr(&doc, form, "method");
  11735. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  11736. is_post = 1;
  11737. a = br_find_attr(&doc, form, "action");
  11738. if (a && a[0]) {
  11739. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  11740. return 0;
  11741. } else {
  11742. s_copy(action, page_url, sizeof(action));
  11743. }
  11744. query[0] = '\0';
  11745. for (i = 0; i < doc.nnode; i++) {
  11746. struct br_node *nd = &doc.nodes[i];
  11747. struct form_state *fs;
  11748. const char *name;
  11749. const char *value = "";
  11750. if (nd->type != BR_NODE_ELEM || i == form ||
  11751. !form_descendant(i, form))
  11752. continue;
  11753. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  11754. nd->tag != BR_TAG_SELECT)
  11755. continue;
  11756. if (form_disabled(i))
  11757. continue;
  11758. name = br_find_attr(&doc, i, "name");
  11759. if (!name || !name[0])
  11760. continue;
  11761. fs = form_get(i, 1);
  11762. if (!fs)
  11763. continue;
  11764. if (nd->tag == BR_TAG_SELECT) {
  11765. char opt[64];
  11766. if (!form_option_text(i, fs->selected, opt,
  11767. sizeof(opt)))
  11768. s_copy(opt, "", sizeof(opt));
  11769. value = opt;
  11770. {
  11771. unsigned int c, oi = 0;
  11772. for (c = nd->first; c;
  11773. c = doc.nodes[c].next) {
  11774. if (doc.nodes[c].type != BR_NODE_ELEM ||
  11775. doc.nodes[c].tag != BR_TAG_OPTION)
  11776. continue;
  11777. if (oi == fs->selected) {
  11778. const char *v =
  11779. br_value(&doc, c);
  11780. if (v && v[0])
  11781. value = v;
  11782. break;
  11783. }
  11784. oi++;
  11785. }
  11786. }
  11787. } else if (nd->tag == BR_TAG_INPUT) {
  11788. int kind = form_kind_of(i);
  11789. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  11790. if (!fs->checked)
  11791. continue;
  11792. value = br_value(&doc, i);
  11793. if (!value || !value[0])
  11794. value = "on";
  11795. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  11796. kind == FORM_BUTTON) {
  11797. if (i != node)
  11798. continue;
  11799. value = fs->value;
  11800. } else {
  11801. value = fs->value;
  11802. }
  11803. } else {
  11804. value = fs->value;
  11805. }
  11806. form_add_param(query, &qn, sizeof(query), name, value, &first);
  11807. }
  11808. if (is_post) {
  11809. if (action[0] == '/') {
  11810. set_status("POST forms need an HTTP action URL", 1, 4000);
  11811. ngui_invalidate(&ui);
  11812. return 0;
  11813. }
  11814. if (qn >= sizeof(pending_post))
  11815. qn = sizeof(pending_post) - 1;
  11816. if (qn)
  11817. memcpy(pending_post, query, qn);
  11818. pending_post[qn] = '\0';
  11819. pending_post_len = qn;
  11820. pending_post_is = 1;
  11821. } else {
  11822. pending_post_len = 0;
  11823. pending_post_is = 0;
  11824. if (qn) {
  11825. unsigned int an = s_len(action);
  11826. if (an + qn + 2 < sizeof(action)) {
  11827. action[an++] = strchr(action, '?') ? '&' : '?';
  11828. action[an] = '\0';
  11829. s_copy(action + an, query,
  11830. sizeof(action) - an);
  11831. }
  11832. }
  11833. }
  11834. s_copy(pending_url, action, sizeof(pending_url));
  11835. pending_action |= ACT_NAV;
  11836. cancel_fetch = 1;
  11837. ngui_invalidate(&ui);
  11838. return 1;
  11839. }
  11840. static void form_reset_event(unsigned int form)
  11841. {
  11842. if (form && !js_browser_event(form, "reset", 1, 1))
  11843. return;
  11844. if (form)
  11845. form_reset_form(form);
  11846. else
  11847. form_reset_state();
  11848. form_dirty = 0;
  11849. layout_valid = 0;
  11850. ngui_invalidate(&ui);
  11851. }
  11852. static void form_blur(void)
  11853. {
  11854. unsigned int node = form_focus;
  11855. form_focus = 0;
  11856. if (node && form_dirty) {
  11857. form_dirty = 0;
  11858. js_browser_event(node, "change", 1, 0);
  11859. }
  11860. }
  11861. static void form_click(unsigned int node)
  11862. {
  11863. struct form_state *fs;
  11864. int kind, changed = 0;
  11865. if (!form_is_control(node) || form_disabled(node))
  11866. return;
  11867. if (form_focus != node)
  11868. form_blur();
  11869. if (!js_browser_event(node, "click", 1, 1))
  11870. return;
  11871. fs = form_get(node, 1);
  11872. if (!fs)
  11873. return;
  11874. kind = form_kind_of(node);
  11875. form_focus = node;
  11876. form_dirty = 0;
  11877. if (kind == FORM_CHECKBOX) {
  11878. fs->checked = !fs->checked;
  11879. changed = 1;
  11880. } else if (kind == FORM_RADIO) {
  11881. const char *name = br_find_attr(&doc, node, "name");
  11882. unsigned int i;
  11883. fs->checked = 1;
  11884. changed = 1;
  11885. if (name) {
  11886. for (i = 0; i < FORM_MAX; i++) {
  11887. struct form_state *o = &form_states[i];
  11888. if (!o->used || o->node == node)
  11889. continue;
  11890. if (form_kind_of(o->node) == FORM_RADIO) {
  11891. const char *on = br_find_attr(&doc,
  11892. o->node,
  11893. "name");
  11894. if (on && s_eq(on, name))
  11895. o->checked = 0;
  11896. }
  11897. }
  11898. }
  11899. } else if (kind == FORM_SELECT) {
  11900. unsigned int n = form_option_count(node);
  11901. if (n) {
  11902. fs->selected = (unsigned char)
  11903. ((fs->selected + 1) % n);
  11904. changed = 1;
  11905. }
  11906. } else if (kind == FORM_SUBMIT) {
  11907. form_submit_form(node, 1);
  11908. return;
  11909. } else if (kind == FORM_RESET) {
  11910. form_reset_event(form_ancestor(node));
  11911. return;
  11912. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  11913. kind == FORM_TEXTAREA) {
  11914. fs->caret = fs->len;
  11915. }
  11916. if (changed) {
  11917. js_browser_event(node, "input", 1, 0);
  11918. js_browser_event(node, "change", 1, 0);
  11919. }
  11920. layout_valid = 0;
  11921. ngui_invalidate(&ui);
  11922. }
  11923. static void form_focus_next(void)
  11924. {
  11925. unsigned int start = form_focus ? form_focus + 1 : 0;
  11926. unsigned int i;
  11927. form_blur();
  11928. for (i = start; i < doc.nnode; i++) {
  11929. if (form_is_control(i) && !form_disabled(i) &&
  11930. !s_eq(br_type(&doc, i), "hidden")) {
  11931. form_focus = i;
  11932. layout_valid = 0;
  11933. ngui_invalidate(&ui);
  11934. return;
  11935. }
  11936. }
  11937. form_focus = 0;
  11938. layout_valid = 0;
  11939. ngui_invalidate(&ui);
  11940. }
  11941. static void form_key(int k)
  11942. {
  11943. struct form_state *fs;
  11944. int kind;
  11945. if (!form_focus || form_focus >= doc.nnode) {
  11946. form_focus = 0;
  11947. return;
  11948. }
  11949. fs = form_get(form_focus, 1);
  11950. if (!fs || form_disabled(form_focus))
  11951. return;
  11952. kind = form_kind_of(form_focus);
  11953. if (kind == FORM_SELECT) {
  11954. unsigned int n = form_option_count(form_focus);
  11955. int changed = 0;
  11956. if (k == NGUI_KEY_UP && n) {
  11957. fs->selected = (unsigned char)
  11958. ((fs->selected + n - 1) % n);
  11959. changed = 1;
  11960. } else if (k == NGUI_KEY_DOWN && n) {
  11961. fs->selected = (unsigned char)
  11962. ((fs->selected + 1) % n);
  11963. changed = 1;
  11964. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  11965. form_blur();
  11966. layout_valid = 0;
  11967. ngui_invalidate(&ui);
  11968. return;
  11969. } else {
  11970. return;
  11971. }
  11972. if (changed) {
  11973. js_browser_event(form_focus, "input", 1, 0);
  11974. js_browser_event(form_focus, "change", 1, 0);
  11975. }
  11976. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  11977. if (k == ' ') {
  11978. form_click(form_focus);
  11979. return;
  11980. }
  11981. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  11982. form_blur();
  11983. layout_valid = 0;
  11984. ngui_invalidate(&ui);
  11985. }
  11986. return;
  11987. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  11988. kind == FORM_RESET) {
  11989. if (k == NGUI_KEY_ESC) {
  11990. form_blur();
  11991. layout_valid = 0;
  11992. ngui_invalidate(&ui);
  11993. } else if (k == '\r' || k == '\n' || k == ' ') {
  11994. form_click(form_focus);
  11995. }
  11996. return;
  11997. } else if (k == NGUI_KEY_TAB) {
  11998. form_focus_next();
  11999. return;
  12000. } else if (k == NGUI_KEY_ESC) {
  12001. form_blur();
  12002. layout_valid = 0;
  12003. ngui_invalidate(&ui);
  12004. return;
  12005. } else if (k == '\r' || k == '\n') {
  12006. unsigned int node = form_focus;
  12007. form_blur();
  12008. if (form_ancestor(node))
  12009. form_submit_form(node, 1);
  12010. layout_valid = 0;
  12011. ngui_invalidate(&ui);
  12012. return;
  12013. } else if (k == NGUI_KEY_BACKSPACE) {
  12014. if (fs->caret) {
  12015. unsigned int i = --fs->caret;
  12016. for (; i < fs->len; i++)
  12017. fs->value[i] = fs->value[i + 1];
  12018. if (fs->len)
  12019. fs->len--;
  12020. form_dirty = 1;
  12021. js_browser_event(form_focus, "input", 1, 0);
  12022. }
  12023. } else if (k == NGUI_KEY_DELETE) {
  12024. if (fs->caret < fs->len) {
  12025. unsigned int i;
  12026. for (i = fs->caret; i < fs->len; i++)
  12027. fs->value[i] = fs->value[i + 1];
  12028. fs->len--;
  12029. form_dirty = 1;
  12030. js_browser_event(form_focus, "input", 1, 0);
  12031. }
  12032. } else if (k == NGUI_KEY_LEFT) {
  12033. if (fs->caret)
  12034. fs->caret--;
  12035. } else if (k == NGUI_KEY_RIGHT) {
  12036. if (fs->caret < fs->len)
  12037. fs->caret++;
  12038. } else if (k == NGUI_KEY_HOME) {
  12039. fs->caret = 0;
  12040. } else if (k == NGUI_KEY_END) {
  12041. fs->caret = fs->len;
  12042. } else if (k >= 32 && k < 127) {
  12043. if (fs->len < FORM_VALUE_MAX) {
  12044. unsigned int i;
  12045. for (i = fs->len; i > fs->caret; i--)
  12046. fs->value[i] = fs->value[i - 1];
  12047. fs->value[fs->caret++] = (char)k;
  12048. fs->len++;
  12049. form_dirty = 1;
  12050. js_browser_event(form_focus, "input", 1, 0);
  12051. }
  12052. } else {
  12053. return;
  12054. }
  12055. fs->value[fs->len] = '\0';
  12056. layout_valid = 0;
  12057. ngui_invalidate(&ui);
  12058. }
  12059. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  12060. * a same-document navigation: update the URL and fire hashchange. Returns
  12061. * 1 when handled. */
  12062. static int link_fragment_nav(unsigned int node)
  12063. {
  12064. const char *href = br_href(&doc, node);
  12065. char url[BR_URL_MAX];
  12066. unsigned int n = 0;
  12067. if (!href || !href[0] || !js_browser_active())
  12068. return 0;
  12069. if (href[0] == '#') {
  12070. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  12071. url[n] = page_url[n];
  12072. n++;
  12073. }
  12074. url[n] = '\0';
  12075. s_append(url, &n, href, sizeof(url));
  12076. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  12077. return 0;
  12078. }
  12079. if (!same_doc_fragment(url))
  12080. return href[0] == '#';
  12081. page_set_fragment(url, 1);
  12082. js_browser_hashchange();
  12083. return 1;
  12084. }
  12085. /* The innermost laid-out box under a screen point: the smallest valid box
  12086. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  12087. * Used to deliver clicks to elements that are neither links nor controls
  12088. * (a Vue <div role="button">, a card with a click listener). */
  12089. static unsigned int find_box_hit(int x, int y)
  12090. {
  12091. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  12092. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  12093. const struct br_layout_box *b = &layout_boxes[i];
  12094. unsigned int area;
  12095. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  12096. x < b->x || y < b->y || x >= b->x + b->w ||
  12097. y >= b->y + b->h)
  12098. continue;
  12099. area = (unsigned int)b->w * (unsigned int)b->h;
  12100. if (area <= best_area) {
  12101. best = i;
  12102. best_area = area;
  12103. }
  12104. }
  12105. return best;
  12106. }
  12107. static void handle_page_click(unsigned int *action)
  12108. {
  12109. int node;
  12110. char url[BR_URL_MAX];
  12111. if (!ui.pressed)
  12112. return;
  12113. if (ui.press_x < page_rect.x ||
  12114. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  12115. ui.press_y < page_rect.y ||
  12116. ui.press_y >= page_rect.y + page_rect.h)
  12117. return;
  12118. node = find_hit(ui.press_x, ui.press_y);
  12119. if (!node) {
  12120. unsigned int box;
  12121. if (!js_browser_active())
  12122. return;
  12123. box = find_box_hit(ui.press_x, ui.press_y);
  12124. if (box) {
  12125. form_blur();
  12126. js_browser_event(box, "click", 1, 1);
  12127. }
  12128. return;
  12129. }
  12130. if (form_is_control((unsigned int)node)) {
  12131. form_click((unsigned int)node);
  12132. return;
  12133. }
  12134. form_blur();
  12135. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  12136. return;
  12137. if (link_fragment_nav((unsigned int)node))
  12138. return;
  12139. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  12140. sizeof(url)) != 0)
  12141. return;
  12142. s_copy(click_url, url, sizeof(click_url));
  12143. *action |= ACT_NAV;
  12144. }
  12145. void _start(const char *arg)
  12146. {
  12147. struct win_info wi;
  12148. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  12149. u_win_create(960, 640, "Browser", &wi) != 0 &&
  12150. u_win_create(780, 540, "Browser", &wi) != 0) {
  12151. u_puts("browser: no graphics window\n");
  12152. u_exit(1);
  12153. }
  12154. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  12155. url_in.placeholder = "http://...";
  12156. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  12157. ui.theme.accent);
  12158. br_set_viewport(wi.width);
  12159. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  12160. s_copy(cwd, "/", sizeof(cwd));
  12161. heap_clear();
  12162. origin_cache_load();
  12163. css_cache_init();
  12164. script_cache_init();
  12165. persist_restore();
  12166. hist_load();
  12167. page_scroll.offset = 0;
  12168. page_scroll.content_h = 0;
  12169. if (arg && arg[0]) {
  12170. navigate(arg, 1);
  12171. } else {
  12172. load_home(1);
  12173. /* Start ready to type: keep the home page, but leave the address
  12174. * bar empty instead of showing "about:home". */
  12175. ngui_input_set(&url_in, "");
  12176. ngui_set_focus(&ui, ID_URL);
  12177. }
  12178. for (;;) {
  12179. unsigned int action = 0;
  12180. unsigned int now;
  12181. click_url[0] = '\0';
  12182. if (pending_action) {
  12183. action |= pending_action & ACT_WAIT_NAV;
  12184. if (pending_url[0])
  12185. s_copy(click_url, pending_url, sizeof(click_url));
  12186. pending_action = 0;
  12187. pending_url[0] = '\0';
  12188. cancel_fetch = 0;
  12189. } else if (preload_active) {
  12190. if (preload_wait)
  12191. preload_wait = 0;
  12192. else
  12193. preload_step();
  12194. } else if ((preload_pending &&
  12195. page_scroll.offset != preload_scroll) ||
  12196. (preload_rescan && layout_valid)) {
  12197. preload_scroll = page_scroll.offset;
  12198. preload_rescan = 0;
  12199. preload_pending = 0;
  12200. preload_node = 0;
  12201. preload_active = 1;
  12202. }
  12203. js_browser_tick();
  12204. if (resize_pending && !pending_action) {
  12205. resize_pending = 0;
  12206. resize_sent_w = layout_right - layout_left;
  12207. js_browser_window_event("resize");
  12208. }
  12209. persist_tick();
  12210. if (pending_action)
  12211. continue;
  12212. now = u_ticks_ms();
  12213. if (status_until && (int)(now - status_until) >= 0) {
  12214. status_text[0] = '\0';
  12215. status_until = 0;
  12216. status_error = 0;
  12217. ngui_invalidate(&ui);
  12218. }
  12219. if (!ngui_begin(&ui)) {
  12220. /* A queued navigation (e.g. Enter in the URL bar during
  12221. * a slow fetch) must be handled even when this frame
  12222. * needs no redraw. */
  12223. if (!action) {
  12224. fetch_workers_stop_if_unfocused();
  12225. u_sleep_ms(10);
  12226. continue;
  12227. }
  12228. } else {
  12229. draw(&action);
  12230. handle_keys(&action);
  12231. handle_page_click(&action);
  12232. ngui_end(&ui);
  12233. }
  12234. if (action & ACT_NAV) {
  12235. if (click_url[0]) {
  12236. navigate(click_url, 1);
  12237. click_url[0] = '\0';
  12238. } else {
  12239. navigate(url_in.text, 1);
  12240. }
  12241. }
  12242. if (action & ACT_BACK) {
  12243. if (hist_pos > 0) {
  12244. hist_pos--;
  12245. if (same_doc_fragment(history[hist_pos])) {
  12246. page_set_fragment(history[hist_pos], 0);
  12247. js_browser_hashchange();
  12248. } else {
  12249. navigate(history[hist_pos], 0);
  12250. }
  12251. }
  12252. }
  12253. if (action & ACT_FORWARD) {
  12254. if (hist_pos + 1 < hist_len) {
  12255. hist_pos++;
  12256. if (same_doc_fragment(history[hist_pos])) {
  12257. page_set_fragment(history[hist_pos], 0);
  12258. js_browser_hashchange();
  12259. } else {
  12260. navigate(history[hist_pos], 0);
  12261. }
  12262. }
  12263. }
  12264. if (action & ACT_RELOAD) {
  12265. if (s_eq(page_url, "about:home"))
  12266. load_home(0);
  12267. else
  12268. navigate(page_url, 0);
  12269. }
  12270. if (action & ACT_HOME)
  12271. load_home(1);
  12272. if (action & ACT_CLOSE)
  12273. quit = 1;
  12274. if (quit)
  12275. break;
  12276. if (pending_action)
  12277. continue;
  12278. fetch_workers_stop_if_unfocused();
  12279. u_sleep_ms(10);
  12280. }
  12281. fetch_workers_stop_all();
  12282. u_win_close();
  12283. u_exit(0);
  12284. }