browser.c 315 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999
  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. };
  233. struct lay {
  234. int draw;
  235. struct ngui *ui;
  236. int left, right;
  237. int y;
  238. int line_x, line_y, line_h;
  239. int line_left, line_right;
  240. int parent_top;
  241. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  242. int cb_h; /* definite content height of the containing block for
  243. * percentage heights; 0 = indefinite (auto) */
  244. int run_x;
  245. int align;
  246. int depth;
  247. int space_pending;
  248. unsigned char float_active;
  249. int float_left, float_right, float_bottom;
  250. struct lay_run runs[96];
  251. int nruns;
  252. };
  253. struct hit {
  254. int x, y, w, h;
  255. unsigned short node;
  256. };
  257. /* Live form state; the DOM attributes stay the initial/default value. */
  258. #define FORM_MAX 64
  259. #define FORM_VALUE_MAX 63
  260. enum {
  261. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  262. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  263. };
  264. struct form_state {
  265. unsigned int node;
  266. char value[FORM_VALUE_MAX + 1];
  267. unsigned char len, caret, checked, selected, used;
  268. };
  269. static struct form_state form_states[FORM_MAX];
  270. static unsigned int form_focus;
  271. static unsigned int form_dirty;
  272. static int form_descendant(unsigned int node, unsigned int form);
  273. static int form_submit_form(unsigned int node, int fire_event);
  274. static int link_fragment_nav(unsigned int node);
  275. static void history_push(const char *url);
  276. static void form_reset_event(unsigned int form);
  277. static unsigned int s_len(const char *s);
  278. static int s_eq(const char *a, const char *b);
  279. static void form_key(int k);
  280. static void form_click(unsigned int node);
  281. static void style_for_node(unsigned int node, struct br_style *out);
  282. static int form_author_styled(const struct br_style *st);
  283. static int css_radius(const struct br_style *st, int corner, int w, int h);
  284. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  285. const struct br_style *st, int focused);
  286. static int form_disabled(unsigned int node)
  287. {
  288. struct br_node *n = &doc.nodes[node];
  289. if (n->attr_flags & BR_ATTR_DISABLED)
  290. return 1;
  291. return br_find_attr(&doc, node, "disabled") != 0;
  292. }
  293. static int form_kind_of(unsigned int node)
  294. {
  295. const char *type = br_type(&doc, node);
  296. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  297. return FORM_TEXTAREA;
  298. if (doc.nodes[node].tag == BR_TAG_SELECT)
  299. return FORM_SELECT;
  300. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  301. if (s_eq(type, "reset"))
  302. return FORM_RESET;
  303. if (s_eq(type, "button"))
  304. return FORM_BUTTON;
  305. return FORM_SUBMIT;
  306. }
  307. if (s_eq(type, "password"))
  308. return FORM_PASSWORD;
  309. if (s_eq(type, "checkbox"))
  310. return FORM_CHECKBOX;
  311. if (s_eq(type, "radio"))
  312. return FORM_RADIO;
  313. if (s_eq(type, "submit"))
  314. return FORM_SUBMIT;
  315. if (s_eq(type, "reset"))
  316. return FORM_RESET;
  317. if (s_eq(type, "button"))
  318. return FORM_BUTTON;
  319. return FORM_TEXT;
  320. }
  321. static unsigned int form_option_count(unsigned int node)
  322. {
  323. unsigned int c, n = 0;
  324. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  325. if (doc.nodes[c].type == BR_NODE_ELEM &&
  326. doc.nodes[c].tag == BR_TAG_OPTION)
  327. n++;
  328. return n;
  329. }
  330. static unsigned int form_option_selected(unsigned int node)
  331. {
  332. unsigned int c, i = 0;
  333. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  334. if (doc.nodes[c].type != BR_NODE_ELEM ||
  335. doc.nodes[c].tag != BR_TAG_OPTION)
  336. continue;
  337. if (br_find_attr(&doc, c, "selected"))
  338. return i;
  339. i++;
  340. }
  341. return 0;
  342. }
  343. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  344. char *out, unsigned int cap)
  345. {
  346. unsigned int c, i = 0;
  347. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  348. if (doc.nodes[c].type != BR_NODE_ELEM ||
  349. doc.nodes[c].tag != BR_TAG_OPTION)
  350. continue;
  351. if (i == idx)
  352. return br_text_content(&doc, c, out, cap);
  353. i++;
  354. }
  355. return 0;
  356. }
  357. static struct form_state *form_get(unsigned int node, int create)
  358. {
  359. struct form_state *slot = 0;
  360. unsigned int i;
  361. for (i = 0; i < FORM_MAX; i++) {
  362. if (form_states[i].used) {
  363. if (form_states[i].node == node)
  364. return &form_states[i];
  365. } else if (!slot) {
  366. slot = &form_states[i];
  367. }
  368. }
  369. if (!create || !slot)
  370. return 0;
  371. slot->node = node;
  372. slot->len = 0;
  373. slot->caret = 0;
  374. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  375. slot->selected = form_option_selected(node);
  376. slot->used = 1;
  377. {
  378. unsigned int n = 0;
  379. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  380. n = br_text_content(&doc, node, slot->value,
  381. FORM_VALUE_MAX + 1);
  382. } else {
  383. const char *v = br_value(&doc, node);
  384. if (v) {
  385. n = s_len(v);
  386. if (n > FORM_VALUE_MAX)
  387. n = FORM_VALUE_MAX;
  388. for (unsigned int j = 0; j < n; j++)
  389. slot->value[j] = v[j];
  390. }
  391. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  392. n = br_text_content(&doc, node, slot->value,
  393. FORM_VALUE_MAX + 1);
  394. }
  395. if (n > FORM_VALUE_MAX)
  396. n = FORM_VALUE_MAX;
  397. slot->value[n] = '\0';
  398. slot->len = (unsigned char)n;
  399. slot->caret = (unsigned char)n;
  400. }
  401. return slot;
  402. }
  403. static void form_reset_state(void)
  404. {
  405. unsigned int i;
  406. for (i = 0; i < FORM_MAX; i++)
  407. form_states[i].used = 0;
  408. form_focus = 0;
  409. }
  410. /* A <button> with element content (an icon <svg>/<img>, a <span> label)
  411. * is laid out like a normal element so that content shows; only a text or
  412. * empty button is drawn as a native control. Clicks still reach it
  413. * through the box hit test. */
  414. static int button_has_elements(unsigned int node)
  415. {
  416. unsigned int c;
  417. if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
  418. return 0;
  419. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  420. if (doc.nodes[c].type == BR_NODE_ELEM)
  421. return 1;
  422. return 0;
  423. }
  424. static int form_is_control(unsigned int node)
  425. {
  426. unsigned int tag;
  427. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  428. return 0;
  429. tag = doc.nodes[node].tag;
  430. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  431. tag == BR_TAG_SELECT ||
  432. (tag == BR_TAG_BUTTON && !button_has_elements(node));
  433. }
  434. #define HIT_MAX 96
  435. static struct hit hits[HIT_MAX];
  436. static int nhits;
  437. static unsigned short block_h[BR_MAX_NODES];
  438. /* Measure-pass top of each block, in the same document coordinates as
  439. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  440. * paint, so it cannot drive the lazy background loader). */
  441. static unsigned short block_top[BR_MAX_NODES];
  442. static char li_marker[BR_MAX_NODES][12];
  443. /* one connection object; the browser fetches one resource at a time */
  444. /* ---- tiny strings ---- */
  445. static unsigned int s_len(const char *s)
  446. {
  447. unsigned int n = 0;
  448. while (s && s[n])
  449. n++;
  450. return n;
  451. }
  452. static void s_copy(char *d, const char *s, unsigned int cap)
  453. {
  454. unsigned int i = 0;
  455. if (!cap)
  456. return;
  457. while (s && s[i] && i + 1 < cap) {
  458. d[i] = s[i];
  459. i++;
  460. }
  461. d[i] = '\0';
  462. }
  463. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  464. {
  465. while (s && *s && *n + 1 < cap)
  466. d[(*n)++] = *s++;
  467. d[*n] = '\0';
  468. }
  469. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  470. unsigned int cap)
  471. {
  472. char tmp[12];
  473. unsigned int i = 0, j;
  474. do {
  475. tmp[i++] = (char)('0' + v % 10);
  476. v /= 10;
  477. } while (v && i < sizeof(tmp));
  478. for (j = 0; j < i && *n + 1 < cap; j++)
  479. d[(*n)++] = tmp[i - 1 - j];
  480. d[*n] = '\0';
  481. }
  482. static int s_eq(const char *a, const char *b)
  483. {
  484. while (*a && *b) {
  485. if (*a != *b)
  486. return 0;
  487. a++;
  488. b++;
  489. }
  490. return *a == *b;
  491. }
  492. static int starts_with(const char *s, const char *p)
  493. {
  494. unsigned int i = 0;
  495. while (p[i]) {
  496. if (s[i] != p[i])
  497. return 0;
  498. i++;
  499. }
  500. return 1;
  501. }
  502. static int contains_ci(const char *s, const char *p)
  503. {
  504. unsigned int i, j;
  505. for (i = 0; s[i]; i++) {
  506. for (j = 0; p[j]; j++) {
  507. char a = s[i + j];
  508. if (a >= 'A' && a <= 'Z')
  509. a = (char)(a - 'A' + 'a');
  510. if (a != p[j])
  511. break;
  512. }
  513. if (!p[j])
  514. return 1;
  515. }
  516. return 0;
  517. }
  518. static char *trim(char *s)
  519. {
  520. unsigned int n;
  521. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  522. s++;
  523. n = s_len(s);
  524. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  525. s[n - 1] == '\r' || s[n - 1] == '\n'))
  526. s[--n] = '\0';
  527. return s;
  528. }
  529. /* ---- per-process heap ---- */
  530. static int heap_start(void)
  531. {
  532. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  533. if (!image_io_buf)
  534. return -1;
  535. page_backbuf = (unsigned short *)malloc(
  536. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  537. pagebuf_w = page_backbuf ? ui.w : 0;
  538. pagebuf_h = page_backbuf ? ui.h : 0;
  539. page_cache_valid = 0;
  540. return 0;
  541. }
  542. static void heap_clear(void)
  543. {
  544. memset(font_faces, 0, sizeof(font_faces));
  545. ngui_font_detach(&ui);
  546. svg_cache_clear();
  547. decode_arena = 0; /* lives in the page heap too */
  548. decode_arena_size = 0;
  549. heap_reset();
  550. /* The document arenas live in that heap; drop the stale pointers so
  551. * the next br_parse_plain() allocates fresh ones. */
  552. doc.nodes = 0;
  553. doc.text = 0;
  554. doc.attrs = 0;
  555. image_io_buf = 0;
  556. page_backbuf = 0;
  557. pagebuf_w = pagebuf_h = 0;
  558. page_cache_valid = 0;
  559. }
  560. static void browser_rules_alloc(void)
  561. {
  562. struct br_rule *rules;
  563. rules = (struct br_rule *)malloc(
  564. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  565. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  566. }
  567. /* ---- status ---- */
  568. static void set_status(const char *s, int err, unsigned int ttl_ms)
  569. {
  570. s_copy(status_text, s, sizeof(status_text));
  571. status_error = err;
  572. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  573. ngui_invalidate(&ui);
  574. }
  575. /* Update the status text without forcing a frame; the throttled image
  576. * repaint picks it up. Starting one helper per image used to invalidate the
  577. * whole page before every decode. */
  578. static void set_status_quiet(const char *s)
  579. {
  580. s_copy(status_text, s, sizeof(status_text));
  581. status_error = 0;
  582. status_until = 0;
  583. }
  584. /* ---- JavaScript ---- */
  585. static int resolve_link(const char *base, const char *href, char *out,
  586. unsigned int cap);
  587. static char js_last_status[BR_STATUS_MAX];
  588. static int js_last_error;
  589. static void js_host_status(const char *msg, int error)
  590. {
  591. s_copy(js_last_status, msg, sizeof(js_last_status));
  592. js_last_error = error;
  593. set_status(msg, error, 6000);
  594. }
  595. static void js_host_report(const char *msg)
  596. {
  597. u_puts("[js] ");
  598. u_puts(msg);
  599. u_putc('\n');
  600. s_copy(js_last_status, msg, sizeof(js_last_status));
  601. js_last_error = 1;
  602. set_status(msg, 1, 8000);
  603. }
  604. static void js_host_navigate(const char *url)
  605. {
  606. char resolved[BR_URL_MAX];
  607. if (!url || !url[0])
  608. return;
  609. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  610. return;
  611. s_copy(pending_url, resolved, sizeof(pending_url));
  612. pending_action |= ACT_NAV;
  613. cancel_fetch = 1;
  614. }
  615. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  616. * back/forward between fragments): the page URL, address bar and history
  617. * follow, nothing is reloaded. `push` adds a history entry. */
  618. static int page_set_fragment(const char *url, int push)
  619. {
  620. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  621. return -1;
  622. s_copy(page_url, url, sizeof(page_url));
  623. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  624. url_in.len = s_len(url_in.text);
  625. url_in.cursor = url_in.len;
  626. url_in.scroll = 0;
  627. if (push)
  628. history_push(page_url);
  629. ngui_invalidate(&ui);
  630. return 0;
  631. }
  632. static int js_host_set_hash(const char *url)
  633. {
  634. return page_set_fragment(url, 1);
  635. }
  636. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  637. * the page, so a hash router can react). */
  638. static int same_doc_fragment(const char *url)
  639. {
  640. unsigned int a = 0, b = 0;
  641. if (!js_browser_active() || !url)
  642. return 0;
  643. while (url[a] && url[a] != '#')
  644. a++;
  645. while (page_url[b] && page_url[b] != '#')
  646. b++;
  647. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  648. !s_eq(url, page_url);
  649. }
  650. static void js_host_changed(void)
  651. {
  652. /* Class/style/attribute mutations change computed styles, not just the
  653. * text: drop the per-node style cache before the next layout. */
  654. br_reset_styles(&doc);
  655. layout_valid = 0;
  656. /* Script-built content (Angular's ng-repeat cards) brings new images
  657. * and inline background styles: rescan once the main loop is idle. */
  658. preload_rescan = 1;
  659. ngui_invalidate(&ui);
  660. }
  661. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  662. {
  663. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  664. return 0;
  665. *x = layout_boxes[node].x - page_rect.x;
  666. *y = layout_boxes[node].y - page_rect.y;
  667. *w = layout_boxes[node].w;
  668. *h = layout_boxes[node].h;
  669. return 1;
  670. }
  671. static void form_copy_out(const char *s, char *buf, int cap)
  672. {
  673. int i = 0;
  674. if (!buf || cap <= 0)
  675. return;
  676. while (s && s[i] && i + 1 < cap) {
  677. buf[i] = s[i];
  678. i++;
  679. }
  680. buf[i] = '\0';
  681. }
  682. static int js_host_form_value(unsigned int node, char *buf, int cap)
  683. {
  684. struct form_state *fs;
  685. int kind;
  686. if (!form_is_control(node))
  687. return 0;
  688. kind = form_kind_of(node);
  689. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  690. return 0;
  691. if (kind == FORM_SELECT) {
  692. char opt[64] = "";
  693. unsigned int c, i = 0;
  694. fs = form_get(node, 1);
  695. if (!fs)
  696. return 0;
  697. form_option_text(node, fs->selected, opt, sizeof(opt));
  698. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  699. if (doc.nodes[c].type != BR_NODE_ELEM ||
  700. doc.nodes[c].tag != BR_TAG_OPTION)
  701. continue;
  702. if (i == fs->selected) {
  703. const char *v = br_value(&doc, c);
  704. if (v && v[0])
  705. form_copy_out(v, buf, cap);
  706. else
  707. form_copy_out(opt, buf, cap);
  708. return 1;
  709. }
  710. i++;
  711. }
  712. form_copy_out(opt, buf, cap);
  713. return 1;
  714. }
  715. fs = form_get(node, 1);
  716. if (!fs)
  717. return 0;
  718. form_copy_out(fs->value, buf, cap);
  719. return 1;
  720. }
  721. static int js_host_form_checked(unsigned int node)
  722. {
  723. struct form_state *fs;
  724. int kind;
  725. if (!form_is_control(node))
  726. return -1;
  727. kind = form_kind_of(node);
  728. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  729. return -1;
  730. fs = form_get(node, 1);
  731. return fs ? fs->checked : 0;
  732. }
  733. static int js_host_form_selected(unsigned int node)
  734. {
  735. struct form_state *fs;
  736. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  737. return -1;
  738. fs = form_get(node, 1);
  739. return fs ? fs->selected : 0;
  740. }
  741. static int js_host_form_set_value(unsigned int node, const char *value)
  742. {
  743. struct form_state *fs;
  744. unsigned int n;
  745. if (!form_is_control(node))
  746. return 0;
  747. fs = form_get(node, 1);
  748. if (!fs)
  749. return 0;
  750. n = s_len(value ? value : "");
  751. if (n > FORM_VALUE_MAX)
  752. n = FORM_VALUE_MAX;
  753. for (unsigned int i = 0; i < n; i++)
  754. fs->value[i] = value[i];
  755. fs->value[n] = '\0';
  756. fs->len = (unsigned char)n;
  757. fs->caret = (unsigned char)n;
  758. layout_valid = 0;
  759. ngui_invalidate(&ui);
  760. return 1;
  761. }
  762. static int js_host_form_set_checked(unsigned int node, int checked)
  763. {
  764. struct form_state *fs;
  765. int kind;
  766. if (!form_is_control(node))
  767. return 0;
  768. kind = form_kind_of(node);
  769. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  770. return 0;
  771. fs = form_get(node, 1);
  772. if (!fs)
  773. return 0;
  774. fs->checked = (unsigned char)(checked != 0);
  775. layout_valid = 0;
  776. ngui_invalidate(&ui);
  777. return 1;
  778. }
  779. static int js_host_form_set_selected(unsigned int node, int index)
  780. {
  781. struct form_state *fs;
  782. unsigned int n;
  783. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  784. return 0;
  785. fs = form_get(node, 1);
  786. if (!fs)
  787. return 0;
  788. n = form_option_count(node);
  789. if (index < 0)
  790. index = 0;
  791. if (n && (unsigned int)index >= n)
  792. index = (int)n - 1;
  793. fs->selected = (unsigned char)index;
  794. layout_valid = 0;
  795. ngui_invalidate(&ui);
  796. return 1;
  797. }
  798. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  799. {
  800. unsigned int i;
  801. int n = 0;
  802. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  803. doc.nodes[form].tag != BR_TAG_FORM)
  804. return 0;
  805. for (i = 0; i < doc.nnode && n < cap; i++) {
  806. struct br_node *nd = &doc.nodes[i];
  807. if (i == form || nd->type != BR_NODE_ELEM)
  808. continue;
  809. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  810. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  811. continue;
  812. if (!form_descendant(i, form))
  813. continue;
  814. out[n++] = i;
  815. }
  816. return n;
  817. }
  818. static int js_host_form_submit(unsigned int form)
  819. {
  820. form_submit_form(form, 0);
  821. return 1;
  822. }
  823. static int js_host_form_reset(unsigned int form)
  824. {
  825. form_reset_event(form);
  826. return 1;
  827. }
  828. static void css_computed_name(const char *p, char *out, int cap)
  829. {
  830. int n = 0;
  831. for (; p && *p && n + 2 < cap; p++) {
  832. char c = *p;
  833. if (c >= 'A' && c <= 'Z') {
  834. out[n++] = '-';
  835. c = (char)(c - 'A' + 'a');
  836. } else if (c == '_') {
  837. c = '-';
  838. } else if (c >= 'a' && c <= 'z') {
  839. /* keep */
  840. }
  841. out[n++] = c;
  842. }
  843. out[n] = '\0';
  844. if (!strcmp(out, "css-float"))
  845. strcpy(out, "float");
  846. }
  847. static void css_rgb(unsigned short c, char *buf, int cap)
  848. {
  849. int r = ((c >> 11) & 31) * 255 / 31;
  850. int g = ((c >> 5) & 63) * 255 / 63;
  851. int b = (c & 31) * 255 / 31;
  852. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  853. }
  854. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  855. int font_px)
  856. {
  857. if (unit == 4) {
  858. snprintf(buf, cap, "auto");
  859. } else if (unit == 0) {
  860. snprintf(buf, cap, "%dpx", raw);
  861. } else if (unit == 1) {
  862. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  863. } else if (unit == 2) {
  864. /* Chrome's getComputedStyle() reports used pixel values. */
  865. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  866. } else if (unit == 3) {
  867. snprintf(buf, cap, "%dpx",
  868. (int)br_root_font_px() * raw / 100);
  869. } else {
  870. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  871. raw / 100, raw % 100, px);
  872. }
  873. }
  874. static int js_host_computed(unsigned int node, const char *property,
  875. char *buf, int cap)
  876. {
  877. struct br_style st;
  878. char name[40];
  879. if (!buf || cap <= 0 || node >= doc.nnode || node == 0)
  880. return 0;
  881. buf[0] = '\0';
  882. css_computed_name(property, name, sizeof(name));
  883. style_for_node(node, &st);
  884. if (!strcmp(name, "display")) {
  885. const char *v = "inline";
  886. if (st.display == BR_DISPLAY_BLOCK)
  887. v = "block";
  888. else if (st.display == BR_DISPLAY_NONE)
  889. v = "none";
  890. else if (st.display == BR_DISPLAY_FLEX)
  891. v = "flex";
  892. else if (st.display == BR_DISPLAY_GRID)
  893. v = "grid";
  894. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  895. v = "inline-block";
  896. snprintf(buf, cap, "%s", v);
  897. } else if (!strcmp(name, "position")) {
  898. static const char *pos[] = {
  899. "static", "absolute", "fixed", "relative", "sticky"
  900. };
  901. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  902. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  903. int is_w = name[0] == 'w';
  904. int kind = is_w ? st.width_kind : st.height_kind;
  905. int val = is_w ? st.width : st.height;
  906. if (kind == 3) {
  907. if (is_w)
  908. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  909. st.width_calc_pct / 100,
  910. st.width_calc_pct % 100,
  911. st.width_calc_px);
  912. else
  913. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  914. st.height_calc_pct / 100,
  915. st.height_calc_pct % 100,
  916. st.height_calc_px);
  917. } else if (kind == 1) {
  918. snprintf(buf, cap, "%dpx", val);
  919. } else if (kind == 2) {
  920. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  921. } else {
  922. snprintf(buf, cap, "auto");
  923. }
  924. } else if (!strcmp(name, "color") ||
  925. !strcmp(name, "background-color")) {
  926. if (!strcmp(name, "background-color") && !st.has_bg)
  927. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  928. else
  929. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  930. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  931. int is_fill = name[0] == 'f';
  932. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  933. if (mode == BR_PAINT_COLOR)
  934. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  935. else if (mode == BR_PAINT_CURRENT)
  936. css_rgb(st.color, buf, cap);
  937. else if (mode == BR_PAINT_UNSET && is_fill)
  938. snprintf(buf, cap, "rgb(0, 0, 0)");
  939. else if (mode == BR_PAINT_URL)
  940. snprintf(buf, cap, "url()");
  941. else
  942. snprintf(buf, cap, "none");
  943. } else if (!strcmp(name, "font-size")) {
  944. snprintf(buf, cap, "%dpx", st.font_px);
  945. } else if (!strcmp(name, "font-weight")) {
  946. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  947. } else if (!strcmp(name, "font-style")) {
  948. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  949. } else if (!strcmp(name, "font-family")) {
  950. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  951. br_font_face_family(st.font_face)[0])
  952. snprintf(buf, cap, "%s",
  953. br_font_face_family(st.font_face));
  954. else
  955. snprintf(buf, cap, "%s",
  956. st.mono ? "monospace" : "sans-serif");
  957. } else if (!strcmp(name, "text-align")) {
  958. static const char *al[] = { "left", "center", "right", "justify" };
  959. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  960. } else if (!strcmp(name, "float")) {
  961. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  962. st.float_left == 2 ? "right" : "none");
  963. } else if (!strcmp(name, "clear")) {
  964. static const char *cl[] = { "none", "left", "right", "both" };
  965. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  966. } else if (!strcmp(name, "opacity")) {
  967. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  968. } else if (!strcmp(name, "visibility")) {
  969. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  970. } else if (!strcmp(name, "overflow")) {
  971. snprintf(buf, cap, "%s",
  972. st.overflow_hidden ? "hidden" : "visible");
  973. } else if (!strcmp(name, "white-space")) {
  974. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  975. } else if (!strcmp(name, "text-transform")) {
  976. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  977. } else if (!strcmp(name, "box-sizing")) {
  978. snprintf(buf, cap, "%s",
  979. st.box_sizing ? "border-box" : "content-box");
  980. } else if (!strcmp(name, "line-height")) {
  981. if (st.line_h_px)
  982. snprintf(buf, cap, "%dpx", st.line_h_px);
  983. else if (st.line_h_pct)
  984. snprintf(buf, cap, "%d%%", st.line_h_pct);
  985. else
  986. snprintf(buf, cap, "normal");
  987. } else if (!strcmp(name, "z-index")) {
  988. if (st.z_set)
  989. snprintf(buf, cap, "%d", st.z_index);
  990. else
  991. snprintf(buf, cap, "auto");
  992. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  993. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  994. int set = name[0] == 't' ? st.top_set :
  995. name[0] == 'l' ? st.left_set :
  996. name[0] == 'r' ? st.right_set : st.bottom_set;
  997. int v = name[0] == 't' ? st.top :
  998. name[0] == 'l' ? st.left :
  999. name[0] == 'r' ? st.right : st.bottom;
  1000. if (set)
  1001. snprintf(buf, cap, "%dpx", v);
  1002. else
  1003. snprintf(buf, cap, "auto");
  1004. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  1005. !strcmp(name, "margin-bottom") ||
  1006. !strcmp(name, "margin-left") ||
  1007. !strcmp(name, "padding-top") ||
  1008. !strcmp(name, "padding-right") ||
  1009. !strcmp(name, "padding-bottom") ||
  1010. !strcmp(name, "padding-left")) {
  1011. int is_pad = name[0] == 'p';
  1012. int side = name[strlen(name) - 1] == 'p' ? 0 :
  1013. name[strlen(name) - 1] == 't' ? 1 :
  1014. name[strlen(name) - 1] == 'm' ? 2 : 3;
  1015. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  1016. if (!strcmp(name, "margin-right") ||
  1017. !strcmp(name, "padding-right"))
  1018. side = 1;
  1019. else if (!strcmp(name, "margin-bottom") ||
  1020. !strcmp(name, "padding-bottom"))
  1021. side = 2;
  1022. else if (!strcmp(name, "margin-left") ||
  1023. !strcmp(name, "padding-left"))
  1024. side = 3;
  1025. else
  1026. side = 0;
  1027. side += is_pad ? 4 : 0;
  1028. css_mp_value(buf, cap,
  1029. side == 0 ? st.mt : side == 1 ? st.mr :
  1030. side == 2 ? st.mb : side == 3 ? st.ml :
  1031. side == 4 ? st.pt : side == 5 ? st.pr :
  1032. side == 6 ? st.pb : st.pl,
  1033. st.mp_unit[side], st.mp_calc_px[side],
  1034. st.font_px);
  1035. } else if (!strcmp(name, "border-top-width") ||
  1036. !strcmp(name, "border-right-width") ||
  1037. !strcmp(name, "border-bottom-width") ||
  1038. !strcmp(name, "border-left-width")) {
  1039. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1040. name[7] == 'b' ? 2 : 3;
  1041. snprintf(buf, cap, "%dpx", st.border_w[side]);
  1042. } else if (!strcmp(name, "border-top-color") ||
  1043. !strcmp(name, "border-right-color") ||
  1044. !strcmp(name, "border-bottom-color") ||
  1045. !strcmp(name, "border-left-color")) {
  1046. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1047. name[7] == 'b' ? 2 : 3;
  1048. if (st.border_w[side] && !st.border_t[side])
  1049. css_rgb(st.border_c[side], buf, cap);
  1050. else
  1051. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1052. } else if (!strcmp(name, "background-image")) {
  1053. if (st.bg_image)
  1054. snprintf(buf, cap, "url(\"%s\")",
  1055. br_bg_image_url(st.bg_image - 1));
  1056. else
  1057. snprintf(buf, cap, "none");
  1058. } else if (!strcmp(name, "background-repeat")) {
  1059. static const char *rp[] = {
  1060. "repeat", "no-repeat", "repeat-x", "repeat-y"
  1061. };
  1062. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  1063. st.bg_repeat : 0]);
  1064. } else if (!strcmp(name, "background-position")) {
  1065. if (st.bg_pos_x_kind == 1)
  1066. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  1067. st.bg_pos_y);
  1068. else
  1069. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1070. st.bg_pos_y);
  1071. } else if (!strcmp(name, "background-size")) {
  1072. if (st.bg_size_kind == 3)
  1073. snprintf(buf, cap, "cover");
  1074. else if (st.bg_size_kind == 4)
  1075. snprintf(buf, cap, "contain");
  1076. else if (st.bg_size_kind == 1)
  1077. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1078. st.bg_size_h);
  1079. else if (st.bg_size_kind == 2)
  1080. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1081. st.bg_size_h);
  1082. else
  1083. snprintf(buf, cap, "auto");
  1084. } else if (!strcmp(name, "transform")) {
  1085. char tmp[128];
  1086. unsigned int n = 0;
  1087. if (!st.transform_set) {
  1088. snprintf(buf, cap, "none");
  1089. } else {
  1090. tmp[0] = '\0';
  1091. if (st.tx || st.ty) {
  1092. snprintf(tmp + n, sizeof(tmp) - n,
  1093. "translate(%dpx, %dpx)", st.tx, st.ty);
  1094. n = (unsigned int)strlen(tmp);
  1095. }
  1096. if (st.transform_scale) {
  1097. snprintf(tmp + n, sizeof(tmp) - n,
  1098. "%sscale(%d.%02d, %d.%02d)",
  1099. n ? " " : "", st.scale_x / 100,
  1100. st.scale_x % 100, st.scale_y / 100,
  1101. st.scale_y % 100);
  1102. n = (unsigned int)strlen(tmp);
  1103. if (st.rotate_x100) {
  1104. snprintf(tmp + n, sizeof(tmp) - n,
  1105. " rotate(%d.%02ddeg)",
  1106. st.rotate_x100 / 100,
  1107. st.rotate_x100 % 100);
  1108. }
  1109. } else if (st.rotate_x100) {
  1110. snprintf(tmp + n, sizeof(tmp) - n,
  1111. "%srotate(%d.%02ddeg)",
  1112. n ? " " : "", st.rotate_x100 / 100,
  1113. st.rotate_x100 % 100);
  1114. }
  1115. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1116. }
  1117. } else {
  1118. return 0;
  1119. }
  1120. return buf[0] != '\0';
  1121. }
  1122. static int js_host_click(unsigned int node)
  1123. {
  1124. char url[BR_URL_MAX];
  1125. const char *href;
  1126. if (node >= doc.nnode)
  1127. return 0;
  1128. if (form_is_control(node)) {
  1129. form_click(node); /* dispatches its own click event */
  1130. return 1;
  1131. }
  1132. /* element.click() fires a bubbling, cancelable click before the
  1133. * default action, like a real click (delegated list handlers). */
  1134. if (!js_browser_event(node, "click", 1, 1))
  1135. return 1;
  1136. if (link_fragment_nav(node))
  1137. return 1;
  1138. href = br_href(&doc, node);
  1139. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1140. return 0;
  1141. s_copy(pending_url, url, sizeof(pending_url));
  1142. pending_action |= ACT_NAV;
  1143. cancel_fetch = 1;
  1144. ngui_invalidate(&ui);
  1145. return 1;
  1146. }
  1147. static int fetch_script_text(const char *url, unsigned char **out,
  1148. unsigned int *outlen, char *err,
  1149. unsigned int errcap);
  1150. struct fetch_worker;
  1151. static struct fetch_worker *fetch_worker_alloc(void);
  1152. static void fetch_worker_release(struct fetch_worker *w);
  1153. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1154. unsigned int cap, const char *post,
  1155. unsigned int post_len, unsigned int node,
  1156. int bg, char *err, unsigned int errcap);
  1157. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1158. unsigned int errcap);
  1159. static int fetch_worker_read_body(struct fetch_worker *w,
  1160. unsigned char *plain,
  1161. unsigned int plaincap,
  1162. unsigned char *comp,
  1163. unsigned int compcap,
  1164. int *truncated, char *err,
  1165. unsigned int errcap);
  1166. static void fetch_workers_stop_all(void);
  1167. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1168. unsigned int cap, const char *method,
  1169. const char *ctype, const char *post,
  1170. unsigned int post_len, unsigned int node,
  1171. int bg, unsigned int dec_w,
  1172. unsigned int dec_h, char *err,
  1173. unsigned int errcap);
  1174. static int script_cache_has(const char *url);
  1175. static void script_cache_put(const char *url, const unsigned char *data,
  1176. unsigned int len);
  1177. static unsigned int script_cache_hash(const char *s);
  1178. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1179. unsigned int errcap);
  1180. static void fetch_workers_cancel_busy(void);
  1181. static void worker_wait_ui(void);
  1182. static int fetch_worker_status(const struct fetch_worker *w);
  1183. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1184. * module load: the wait must not pump input, or a click would dispatch DOM
  1185. * events into the middle of the running script. */
  1186. static int fetch_wait_passive;
  1187. static void script_error(const char *what, const char *url, const char *why)
  1188. {
  1189. char msg[192];
  1190. unsigned int n = 0;
  1191. s_append(msg, &n, what, sizeof(msg));
  1192. if (url && url[0]) {
  1193. s_append(msg, &n, " ", sizeof(msg));
  1194. s_append(msg, &n, url, sizeof(msg));
  1195. }
  1196. if (why && why[0]) {
  1197. s_append(msg, &n, ": ", sizeof(msg));
  1198. s_append(msg, &n, why, sizeof(msg));
  1199. }
  1200. js_host_report(msg);
  1201. }
  1202. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1203. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1204. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1205. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1206. #define JS_HTTP_POST_MAX (16u * 1024u)
  1207. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1208. static int js_worker_http(const char *method, const char *url,
  1209. const char *ctype, const char *body,
  1210. unsigned int body_len, struct js_http_resp *r,
  1211. char *err, int errcap);
  1212. static int js_host_http(const char *method, const char *url,
  1213. const char *ctype, const char *body,
  1214. unsigned int body_len, struct js_http_resp *r,
  1215. char *err, int errcap)
  1216. {
  1217. if (pending_action) {
  1218. s_copy(err, "page is navigating", (unsigned int)errcap);
  1219. return -1;
  1220. }
  1221. if (url[0] == '/') {
  1222. /* Local file: GET only. */
  1223. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1224. int rv;
  1225. if (!buf) {
  1226. s_copy(err, "out of memory", (unsigned int)errcap);
  1227. return -1;
  1228. }
  1229. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1230. (int)JS_HTTP_MAX);
  1231. r->status = rv < 0 ? 404 : 200;
  1232. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1233. buf[r->len] = '\0';
  1234. r->body = (char *)buf;
  1235. s_copy(r->url, url, sizeof(r->url));
  1236. if (contains_ci(url, ".json"))
  1237. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1238. return 0;
  1239. }
  1240. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1241. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1242. return -1;
  1243. }
  1244. if (body_len > JS_HTTP_POST_MAX) {
  1245. s_copy(err, "request body too large", (unsigned int)errcap);
  1246. return -1;
  1247. }
  1248. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1249. errcap);
  1250. }
  1251. /* Module source for the engine's loader: the boot script cache first, then
  1252. * one blocking fetch with input pumping disabled (the loader runs inside
  1253. * JavaScript). */
  1254. static char *js_host_load_script(const char *url, unsigned int *len)
  1255. {
  1256. unsigned char *data = 0;
  1257. char err[64];
  1258. int rv;
  1259. fetch_wait_passive++;
  1260. set_status("Loading module...", 0, 0);
  1261. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1262. fetch_wait_passive--;
  1263. if (rv != 0) {
  1264. script_error("Cannot load module", url,
  1265. rv == FETCH_ABORT ? "navigation" : err);
  1266. return 0;
  1267. }
  1268. return (char *)data;
  1269. }
  1270. /* Web Storage lives in /share, outside the page heap that every navigation
  1271. * resets: localStorage per origin for the boot, sessionStorage per origin
  1272. * and browser window. */
  1273. #define JS_ORIGIN_MAX 160
  1274. /* scheme://host[:port] of the page (a local page's whole path). */
  1275. static void js_page_origin(char *origin, unsigned int cap)
  1276. {
  1277. unsigned int i = 0, slashes = 0;
  1278. while (page_url[i] && i + 1 < cap) {
  1279. if (page_url[i] == '/' && ++slashes == 3)
  1280. break;
  1281. origin[i] = page_url[i];
  1282. i++;
  1283. }
  1284. origin[i] = '\0';
  1285. }
  1286. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1287. {
  1288. unsigned int n = 0;
  1289. s_append(out, &n, "/share/bls", cap);
  1290. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1291. }
  1292. static void js_storage_path(int kind, char *out, unsigned int cap)
  1293. {
  1294. char origin[JS_ORIGIN_MAX];
  1295. unsigned int n = 0;
  1296. js_page_origin(origin, sizeof(origin));
  1297. if (!kind) {
  1298. js_origin_path(origin, out, cap);
  1299. return;
  1300. }
  1301. s_append(out, &n, "/share/bss", cap);
  1302. if (kind) {
  1303. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1304. s_append(out, &n, "-", cap);
  1305. }
  1306. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1307. }
  1308. static void persist_mark_origin(const char *origin);
  1309. static int persist_store_lookup(const char *origin, char *out, int cap);
  1310. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1311. {
  1312. char path[48], origin[JS_ORIGIN_MAX];
  1313. int rv;
  1314. js_storage_path(kind, path, sizeof(path));
  1315. if (set) {
  1316. if (kind) {
  1317. if (!set[0] || !strcmp(set, "{}")) {
  1318. u_syscall1(SYS_UNLINK, (int)path);
  1319. return 0;
  1320. }
  1321. } else {
  1322. /* localStorage keeps an explicit "{}" rather than no
  1323. * file: a missing /share file means "not loaded from
  1324. * /data yet", and a cleared store must not come back
  1325. * from the disk copy before it is flushed. */
  1326. if (!set[0])
  1327. set = "{}";
  1328. js_page_origin(origin, sizeof(origin));
  1329. persist_mark_origin(origin);
  1330. }
  1331. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1332. (int)strlen(set)) < 0 ? -1 : 0;
  1333. }
  1334. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1335. if (rv < 0 && !kind) {
  1336. /* First use this boot: the persistent copy on /data. */
  1337. js_page_origin(origin, sizeof(origin));
  1338. rv = persist_store_lookup(origin, out, cap);
  1339. if (rv >= 0)
  1340. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1341. }
  1342. if (rv < 0)
  1343. return -1;
  1344. out[rv] = '\0';
  1345. return rv;
  1346. }
  1347. /* ---- persistence on /data ----
  1348. *
  1349. * /share is the working copy (RAM, shared by every helper and window); the
  1350. * installed disk's /data volume keeps the cookie jar and localStorage
  1351. * across reboots when it is mounted. The browser owns the disk copies: at
  1352. * start it restores the jar into /share, and its main loop writes back
  1353. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1354. * setItem updates costs one FAT write. The helpers only touch /share (they
  1355. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1356. * /data mount every disk access simply fails. Both files are plaintext
  1357. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1358. #define PERSIST_MS 3000u
  1359. #define SHARE_COOKIES "/share/bcookies"
  1360. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1361. #define DATA_STORE "/data/BSTORE.DAT"
  1362. #define DATA_STORE_MAGIC "NBLS1\n"
  1363. #define DATA_STORE_MAX (192u * 1024u)
  1364. #define PERSIST_DIRTY_MAX 8
  1365. static unsigned int persist_due;
  1366. static unsigned int cookie_sum_saved;
  1367. static int cookie_sum_valid;
  1368. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1369. static int persist_ndirty;
  1370. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1371. {
  1372. unsigned int h = 2166136261u, i;
  1373. for (i = 0; i < n; i++)
  1374. h = (h ^ p[i]) * 16777619u;
  1375. return h;
  1376. }
  1377. /* Called once at startup, before any helper runs. */
  1378. static void persist_restore(void)
  1379. {
  1380. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1381. int n;
  1382. if (!jar)
  1383. return;
  1384. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1385. (int)sizeof(struct uhttp_jar));
  1386. if (n != (int)sizeof(struct uhttp_jar)) {
  1387. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1388. (int)sizeof(struct uhttp_jar));
  1389. if (n == (int)sizeof(struct uhttp_jar)) {
  1390. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1391. (int)jar, n);
  1392. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1393. cookie_sum_valid = 1;
  1394. }
  1395. }
  1396. free(jar);
  1397. persist_due = u_ticks_ms() + PERSIST_MS;
  1398. }
  1399. static void persist_mark_origin(const char *origin)
  1400. {
  1401. int i;
  1402. for (i = 0; i < persist_ndirty; i++)
  1403. if (s_eq(persist_dirty[i], origin))
  1404. return;
  1405. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1406. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1407. }
  1408. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1409. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1410. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1411. unsigned int *o_off, unsigned int *o_len,
  1412. unsigned int *d_off, unsigned int *d_len,
  1413. unsigned int *rec_end)
  1414. {
  1415. unsigned int p = *pos, v = 0;
  1416. if (p >= len)
  1417. return 0;
  1418. *o_off = p;
  1419. while (p < len && buf[p] != '\n')
  1420. p++;
  1421. if (p >= len)
  1422. return 0;
  1423. *o_len = p - *o_off;
  1424. p++;
  1425. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1426. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1427. if (p >= len || buf[p] != '\n')
  1428. return 0;
  1429. p++;
  1430. if (v > len - p)
  1431. return 0;
  1432. *d_off = p;
  1433. *d_len = v;
  1434. p += v;
  1435. if (p < len && buf[p] == '\n')
  1436. p++;
  1437. *rec_end = p;
  1438. *pos = p;
  1439. return 1;
  1440. }
  1441. static int store_load(char **out)
  1442. {
  1443. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1444. int n;
  1445. *out = buf;
  1446. if (!buf)
  1447. return -1;
  1448. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1449. (int)DATA_STORE_MAX);
  1450. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1451. !starts_with(buf, DATA_STORE_MAGIC))
  1452. return 0;
  1453. return n;
  1454. }
  1455. static int persist_store_lookup(const char *origin, char *out, int cap)
  1456. {
  1457. char *buf;
  1458. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1459. unsigned int olen = s_len(origin);
  1460. int n = store_load(&buf), rv = -1;
  1461. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1462. &dl, &e)) {
  1463. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1464. if ((int)dl < cap) {
  1465. memcpy(out, buf + d, dl);
  1466. out[dl] = '\0';
  1467. rv = (int)dl;
  1468. }
  1469. break;
  1470. }
  1471. }
  1472. free(buf);
  1473. return rv;
  1474. }
  1475. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1476. static void persist_store_flush(void)
  1477. {
  1478. char *old, *nb, path[48];
  1479. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1480. int n = store_load(&old), i, w;
  1481. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1482. if (n < 0 || !nb) {
  1483. free(old);
  1484. free(nb);
  1485. return;
  1486. }
  1487. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1488. /* Untouched origins first, in their old order. */
  1489. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1490. &dl, &e)) {
  1491. int dirty = 0;
  1492. for (i = 0; i < persist_ndirty; i++)
  1493. if (s_len(persist_dirty[i]) == ol &&
  1494. !memcmp(persist_dirty[i], old + oo, ol))
  1495. dirty = 1;
  1496. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1497. continue;
  1498. memcpy(nb + nn, old + oo, e - oo);
  1499. nn += e - oo;
  1500. }
  1501. /* Then the changed ones (an emptied store is dropped). */
  1502. for (i = 0; i < persist_ndirty; i++) {
  1503. char num[12];
  1504. unsigned int k = 0;
  1505. js_origin_path(persist_dirty[i], path, sizeof(path));
  1506. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1507. (int)DATA_STORE_MAX);
  1508. if (w <= 2) /* missing or "{}" */
  1509. continue;
  1510. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1511. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1512. DATA_STORE_MAX) {
  1513. set_status("Saved site data is full; a site's "
  1514. "localStorage was not saved", 1, 6000);
  1515. continue;
  1516. }
  1517. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1518. nb[nn++] = '\n';
  1519. s_append(nb, &nn, num, DATA_STORE_MAX);
  1520. nb[nn++] = '\n';
  1521. memcpy(nb + nn, old, (unsigned int)w);
  1522. nn += (unsigned int)w;
  1523. nb[nn++] = '\n';
  1524. }
  1525. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1526. persist_ndirty = 0;
  1527. free(old);
  1528. free(nb);
  1529. }
  1530. static void persist_cookies_flush(void)
  1531. {
  1532. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1533. unsigned int sum;
  1534. int n;
  1535. if (!jar)
  1536. return;
  1537. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1538. (int)sizeof(struct uhttp_jar));
  1539. if (n == (int)sizeof(struct uhttp_jar)) {
  1540. sum = persist_sum(jar, (unsigned int)n);
  1541. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1542. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1543. (int)jar, n) >= 0) {
  1544. cookie_sum_saved = sum;
  1545. cookie_sum_valid = 1;
  1546. }
  1547. }
  1548. }
  1549. free(jar);
  1550. }
  1551. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1552. static void persist_tick(void)
  1553. {
  1554. unsigned int now = u_ticks_ms();
  1555. if ((int)(now - persist_due) < 0)
  1556. return;
  1557. persist_due = now + PERSIST_MS;
  1558. persist_cookies_flush();
  1559. if (persist_ndirty)
  1560. persist_store_flush();
  1561. }
  1562. /* <link rel="modulepreload">: download the page's module graph on all
  1563. * helpers at once into the boot script cache, before any script runs. The
  1564. * engine's module loader is sequential (one blocking fetch per import), so
  1565. * without this a Vite app with a dozen chunks pays every round trip in a
  1566. * row. Failures are ignored; the loader fetches what is missing. */
  1567. #define MODULE_PRELOAD_MAX 24
  1568. static void prefetch_module_preloads(void)
  1569. {
  1570. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1571. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1572. unsigned int count = 0, next = 0, done = 0, i;
  1573. char err[64];
  1574. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1575. struct br_node *nd = &doc.nodes[i];
  1576. const char *rel, *href;
  1577. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1578. continue;
  1579. rel = br_rel(&doc, i);
  1580. href = br_href(&doc, i);
  1581. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1582. continue;
  1583. if (resolve_link(page_url, href, urls[count],
  1584. sizeof(urls[count])) != 0 ||
  1585. urls[count][0] == '/' || script_cache_has(urls[count]))
  1586. continue;
  1587. slot[count++] = 0;
  1588. }
  1589. if (!count)
  1590. return;
  1591. set_status("Loading modules...", 0, 0);
  1592. while (done < count) {
  1593. struct fetch_worker *w;
  1594. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1595. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1596. 0, 0, 0, err,
  1597. sizeof(err)) != 0) {
  1598. fetch_worker_release(w);
  1599. done++;
  1600. } else {
  1601. slot[next] = w;
  1602. }
  1603. next++;
  1604. }
  1605. worker_wait_ui();
  1606. if (cancel_fetch || pending_action) {
  1607. fetch_workers_cancel_busy();
  1608. return;
  1609. }
  1610. for (i = 0; i < next; i++) {
  1611. unsigned char *body;
  1612. int rv, tr = 0;
  1613. if (!slot[i])
  1614. continue;
  1615. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1616. if (rv == 0)
  1617. continue;
  1618. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1619. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1620. if (body) {
  1621. rv = fetch_worker_read_body(slot[i], body,
  1622. BR_SCRIPT_MAX, image_io_buf,
  1623. BR_PAGE_COMP_MAX, &tr, err,
  1624. sizeof(err));
  1625. if (rv > 0 && !tr)
  1626. script_cache_put(urls[i], body,
  1627. (unsigned int)rv);
  1628. free(body);
  1629. }
  1630. fetch_worker_release(slot[i]);
  1631. slot[i] = 0;
  1632. done++;
  1633. }
  1634. u_sleep_ms(10);
  1635. }
  1636. }
  1637. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1638. * submitted to helper workers ahead of time, but scripts still execute in
  1639. * document order. */
  1640. #define SCRIPT_INLINE 0
  1641. #define SCRIPT_LOCAL 1
  1642. #define SCRIPT_REMOTE 2
  1643. #define SCRIPT_ERROR 3
  1644. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1645. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1646. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1647. static void script_submit_window(unsigned int *next, char *err,
  1648. unsigned int errcap)
  1649. {
  1650. while (*next < doc.nscripts) {
  1651. struct fetch_worker *w;
  1652. if (script_kind[*next] != SCRIPT_REMOTE) {
  1653. (*next)++;
  1654. continue;
  1655. }
  1656. w = fetch_worker_alloc();
  1657. if (!w)
  1658. return;
  1659. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1660. 0, 0, 0, 0, err, errcap) != 0) {
  1661. fetch_worker_release(w);
  1662. script_kind[*next] = SCRIPT_ERROR;
  1663. (*next)++;
  1664. continue;
  1665. }
  1666. script_slot[*next] = w;
  1667. (*next)++;
  1668. }
  1669. }
  1670. /* Run the page's scripts in document order. External bodies are prefetched
  1671. * in parallel so downloading script N+1 overlaps executing script N; inline
  1672. * bodies are copied because the engine needs NUL-terminated text. */
  1673. static void run_page_scripts(void)
  1674. {
  1675. struct js_browser_host host;
  1676. unsigned int i, next = 0;
  1677. char err[64], ferr[64];
  1678. if (!doc.nscripts)
  1679. return;
  1680. host.status = js_host_status;
  1681. host.report = js_host_report;
  1682. host.navigate = js_host_navigate;
  1683. host.changed = js_host_changed;
  1684. host.rect = js_host_rect;
  1685. host.form_value = js_host_form_value;
  1686. host.form_checked = js_host_form_checked;
  1687. host.form_selected = js_host_form_selected;
  1688. host.form_set_value = js_host_form_set_value;
  1689. host.form_set_checked = js_host_form_set_checked;
  1690. host.form_set_selected = js_host_form_set_selected;
  1691. host.form_elements = js_host_form_elements;
  1692. host.form_submit = js_host_form_submit;
  1693. host.form_reset = js_host_form_reset;
  1694. host.click = js_host_click;
  1695. host.computed = js_host_computed;
  1696. host.http = js_host_http;
  1697. host.load_script = js_host_load_script;
  1698. host.storage = js_host_storage;
  1699. host.set_hash = js_host_set_hash;
  1700. host.page_url = page_url;
  1701. host.width = ui.w;
  1702. host.height = ui.h;
  1703. if (js_browser_start(&doc, &host) != 0) {
  1704. js_host_status("JavaScript: out of memory", 1);
  1705. return;
  1706. }
  1707. resize_sent_w = -1;
  1708. resize_pending = 0;
  1709. prefetch_module_preloads();
  1710. for (i = 0; i < doc.nscripts; i++) {
  1711. struct br_script *script = &doc.scripts[i];
  1712. const char *src_attr = script->src_off ?
  1713. doc.attrs + script->src_off : "";
  1714. script_slot[i] = 0;
  1715. if (!script->src_off) {
  1716. script_kind[i] = SCRIPT_INLINE;
  1717. continue;
  1718. }
  1719. if (!src_attr[0] ||
  1720. resolve_link(page_url, src_attr, script_urls[i],
  1721. sizeof(script_urls[i])) != 0) {
  1722. script_urls[i][0] = '\0';
  1723. script_kind[i] = SCRIPT_ERROR;
  1724. continue;
  1725. }
  1726. if (script_urls[i][0] == '/' ||
  1727. script_cache_has(script_urls[i]))
  1728. script_kind[i] = SCRIPT_LOCAL;
  1729. else
  1730. script_kind[i] = SCRIPT_REMOTE;
  1731. }
  1732. script_submit_window(&next, ferr, sizeof(ferr));
  1733. for (i = 0; i < doc.nscripts; i++) {
  1734. struct br_script *script = &doc.scripts[i];
  1735. /* document.currentScript for classic scripts (null for modules) */
  1736. js_browser_set_current_script(script->module ? 0 : script->node);
  1737. if (script_kind[i] == SCRIPT_INLINE) {
  1738. unsigned int off = script->off;
  1739. unsigned int len = script->len;
  1740. unsigned int k;
  1741. char *src = (char *)malloc(len + 1);
  1742. if (!src) {
  1743. js_host_status("JavaScript: out of memory", 1);
  1744. break;
  1745. }
  1746. for (k = 0; k < len; k++)
  1747. src[k] = doc.script_src[off + k];
  1748. src[len] = '\0';
  1749. if (script->module) {
  1750. /* A distinct module name per inline module
  1751. * (QuickJS registers modules by name); the
  1752. * fragment keeps relative imports resolving
  1753. * against the page. */
  1754. char mname[BR_URL_MAX + 16];
  1755. unsigned int mn = 0;
  1756. s_append(mname, &mn, page_url, sizeof(mname));
  1757. s_append(mname, &mn, "#module", sizeof(mname));
  1758. s_append_dec(mname, &mn, i, sizeof(mname));
  1759. js_browser_run_module(src, mname);
  1760. } else {
  1761. js_browser_run(src, page_url);
  1762. }
  1763. free(src);
  1764. } else if (script->src_off) {
  1765. const char *src_attr = doc.attrs + script->src_off;
  1766. if (script_kind[i] == SCRIPT_ERROR) {
  1767. script_error("Cannot load script", src_attr,
  1768. script_urls[i][0] ?
  1769. "network busy" :
  1770. "unsupported URL");
  1771. continue;
  1772. }
  1773. if (script_kind[i] == SCRIPT_LOCAL) {
  1774. unsigned char *data = 0;
  1775. unsigned int len = 0;
  1776. int rv;
  1777. set_status("Loading script...", 0, 0);
  1778. rv = fetch_script_text(script_urls[i], &data,
  1779. &len, err, sizeof(err));
  1780. if (rv == FETCH_ABORT)
  1781. break;
  1782. if (rv != 0) {
  1783. script_error("Cannot load script",
  1784. script_urls[i], err);
  1785. continue;
  1786. }
  1787. if (script->module)
  1788. js_browser_run_module(
  1789. (const char *)data,
  1790. script_urls[i]);
  1791. else
  1792. js_browser_run((const char *)data,
  1793. script_urls[i]);
  1794. free(data);
  1795. } else {
  1796. struct fetch_worker *w = script_slot[i];
  1797. unsigned char *body = 0;
  1798. int tr = 0, rv;
  1799. if (!w) {
  1800. w = fetch_worker_alloc();
  1801. if (!w)
  1802. continue;
  1803. if (fetch_worker_submit(w,
  1804. script_urls[i],
  1805. BR_SCRIPT_MAX,
  1806. 0, 0, 0, 0, err,
  1807. sizeof(err)) != 0) {
  1808. fetch_worker_release(w);
  1809. script_kind[i] = SCRIPT_ERROR;
  1810. if (i == next)
  1811. next++;
  1812. continue;
  1813. }
  1814. script_slot[i] = w;
  1815. if (i == next)
  1816. next++;
  1817. }
  1818. set_status("Loading script...", 0, 0);
  1819. rv = fetch_worker_wait(w, err, sizeof(err));
  1820. if (rv == FETCH_ABORT) {
  1821. fetch_workers_stop_all();
  1822. break;
  1823. }
  1824. /* The body gets its own buffer (scripts are up
  1825. * to 2 MB); image_io_buf takes the gzip
  1826. * stream. */
  1827. body = rv == 0 ? (unsigned char *)malloc(
  1828. BR_SCRIPT_MAX + 1) : 0;
  1829. if (body)
  1830. rv = fetch_worker_read_body(w, body,
  1831. BR_SCRIPT_MAX, image_io_buf,
  1832. BR_PAGE_COMP_MAX, &tr, err,
  1833. sizeof(err));
  1834. else {
  1835. if (rv == 0)
  1836. s_copy(err, "out of memory",
  1837. sizeof(err));
  1838. rv = -1;
  1839. }
  1840. fetch_worker_release(w);
  1841. script_slot[i] = 0;
  1842. script_submit_window(&next, ferr, sizeof(ferr));
  1843. if (rv <= 0)
  1844. script_error("Cannot load script",
  1845. script_urls[i], err);
  1846. else if (tr || (unsigned int)rv >=
  1847. BR_SCRIPT_MAX)
  1848. script_error("Cannot load script",
  1849. script_urls[i],
  1850. "script is too large");
  1851. else {
  1852. body[rv] = '\0';
  1853. script_cache_put(script_urls[i], body,
  1854. (unsigned int)rv);
  1855. if (script->module)
  1856. js_browser_run_module(
  1857. (const char *)body,
  1858. script_urls[i]);
  1859. else
  1860. js_browser_run(
  1861. (const char *)body,
  1862. script_urls[i]);
  1863. }
  1864. free(body);
  1865. }
  1866. }
  1867. if (pending_action)
  1868. break;
  1869. }
  1870. js_browser_set_current_script(0);
  1871. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  1872. * load_home() stop it before the next navigation. */
  1873. if (doc.scripts_truncated && !js_last_error)
  1874. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  1875. 1);
  1876. }
  1877. /* ---- images ---- */
  1878. static void image_reset(void)
  1879. {
  1880. int i;
  1881. for (i = 0; i < BR_MAX_IMAGES; i++) {
  1882. images[i].state = 0;
  1883. images[i].native_w = images[i].native_h = 0;
  1884. images[i].err[0] = '\0';
  1885. /* heap_clear() ran before us, so these pointers are stale: drop
  1886. * them without calling free(). */
  1887. memset(&images[i].disp, 0, sizeof(images[i].disp));
  1888. images[i].disp_pixels = 0;
  1889. images[i].disp_last = 0;
  1890. }
  1891. image_count = 0;
  1892. image_pixels = 0;
  1893. image_disp_pixels = 0;
  1894. image_disp_clock = 0;
  1895. memset(img_stat_log, 0, sizeof(img_stat_log));
  1896. img_stat_log_len = 0;
  1897. img_stat_start = 0;
  1898. img_stat_wall = 0;
  1899. img_stat_net = img_stat_open = img_stat_first = 0;
  1900. img_stat_io = img_stat_dec = img_stat_scale = 0;
  1901. img_stat_paint = img_stat_reflow = 0;
  1902. img_stat_bytes = 0;
  1903. img_stat_n = 0;
  1904. img_last_dec_ms = img_last_scale_ms = 0;
  1905. img_repaint_ms = 0;
  1906. img_repaint_pending = 0;
  1907. preload_active = 0;
  1908. preload_pending = 0;
  1909. preload_wait = 0;
  1910. preload_node = 0;
  1911. preload_loaded = 0;
  1912. }
  1913. /* Ask for a repaint, but not more often than BR_IMG_REPAINT_MS while images
  1914. * are arriving. The main loop draws once per dirty frame; without this a
  1915. * page of N images did N full layout+paint passes. */
  1916. static void image_repaint(void)
  1917. {
  1918. unsigned int now = u_ticks_ms();
  1919. if (!img_repaint_ms || (now - img_repaint_ms) >= BR_IMG_REPAINT_MS) {
  1920. img_repaint_ms = now;
  1921. img_repaint_pending = 0;
  1922. ngui_invalidate(&ui);
  1923. } else {
  1924. img_repaint_pending = 1;
  1925. }
  1926. }
  1927. static void image_disp_drop(struct br_image *bi)
  1928. {
  1929. if (bi->disp.px)
  1930. free(bi->disp.px);
  1931. if (bi->disp.alpha)
  1932. free(bi->disp.alpha);
  1933. memset(&bi->disp, 0, sizeof(bi->disp));
  1934. if (bi->disp_pixels) {
  1935. if (image_disp_pixels >= bi->disp_pixels)
  1936. image_disp_pixels -= bi->disp_pixels;
  1937. bi->disp_pixels = 0;
  1938. }
  1939. }
  1940. /* Free the least recently used display caches until need pixels fit. The
  1941. * source bitmap (bi->img) is never evicted; a later draw rescales it again. */
  1942. static int image_disp_room(unsigned int need)
  1943. {
  1944. while (image_disp_pixels + need > BR_IMG_DISP_BUDGET) {
  1945. unsigned int oldest = ~0u;
  1946. int i, victim = -1;
  1947. for (i = 0; i < image_count; i++) {
  1948. if (!images[i].disp.px)
  1949. continue;
  1950. if (images[i].disp_last < oldest) {
  1951. oldest = images[i].disp_last;
  1952. victim = i;
  1953. }
  1954. }
  1955. if (victim < 0)
  1956. return -1;
  1957. image_disp_drop(&images[victim]);
  1958. }
  1959. return 0;
  1960. }
  1961. /* Return a bitmap at exactly dw x dh, building it once from the capped source
  1962. * bitmap. Callers then draw with scale 1 and img_draw's copy fast path. */
  1963. static struct img_image *image_display_get(struct br_image *bi, int dw, int dh)
  1964. {
  1965. struct img_blit b;
  1966. unsigned int px;
  1967. if (!bi || bi->state != 1 || !bi->img.px || dw < 1 || dh < 1)
  1968. return 0;
  1969. if (dw == (int)bi->img.w && dh == (int)bi->img.h)
  1970. return &bi->img;
  1971. if (dw > 4096 || dh > 4096)
  1972. return &bi->img;
  1973. if (bi->disp.px && bi->disp.w == (unsigned int)dw &&
  1974. bi->disp.h == (unsigned int)dh) {
  1975. bi->disp_last = ++image_disp_clock;
  1976. return &bi->disp;
  1977. }
  1978. px = (unsigned int)dw * (unsigned int)dh;
  1979. if (px > BR_IMG_DISP_BUDGET || image_disp_room(px) != 0)
  1980. return &bi->img;
  1981. image_disp_drop(bi);
  1982. bi->disp.px = (unsigned short *)malloc(px * 2u);
  1983. if (!bi->disp.px)
  1984. return &bi->img;
  1985. if (bi->img.alpha) {
  1986. bi->disp.alpha = (unsigned char *)malloc(px);
  1987. if (!bi->disp.alpha) {
  1988. free(bi->disp.px);
  1989. bi->disp.px = 0;
  1990. return &bi->img;
  1991. }
  1992. }
  1993. bi->disp.w = (unsigned int)dw;
  1994. bi->disp.h = (unsigned int)dh;
  1995. bi->disp.format = bi->img.format;
  1996. bi->disp.flags = 0;
  1997. memset(&b, 0, sizeof(b));
  1998. b.dst = bi->disp.px;
  1999. b.dst_w = dw;
  2000. b.dst_h = dh;
  2001. b.clip_w = dw;
  2002. b.clip_h = dh;
  2003. b.scale = ((unsigned int)dw << 16) / bi->img.w;
  2004. b.dst_a = bi->disp.alpha;
  2005. b.flags = bi->disp.alpha ? IMG_BLIT_SAVE_ALPHA : 0;
  2006. img_draw(&bi->img, &b);
  2007. bi->disp_pixels = px;
  2008. image_disp_pixels += px;
  2009. bi->disp_last = ++image_disp_clock;
  2010. return &bi->disp;
  2011. }
  2012. /* Decode into the shared arena, then copy/scale the result into a display
  2013. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  2014. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  2015. * pixels. Transparent edges are composited over white. */
  2016. /* One decode scratch arena per page, reused across images. Allocating and
  2017. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  2018. * each small display bitmap landed in the hole the previous arena left, so
  2019. * the next arena no longer fit and the heap ratcheted up until an app
  2020. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  2021. * still released right after their one image. */
  2022. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  2023. static unsigned char *decode_arena_get(unsigned int bytes)
  2024. {
  2025. if (decode_arena && decode_arena_size >= bytes)
  2026. return decode_arena;
  2027. free(decode_arena);
  2028. decode_arena = (unsigned char *)malloc(bytes);
  2029. decode_arena_size = decode_arena ? bytes : 0;
  2030. return decode_arena;
  2031. }
  2032. static void decode_arena_put(void)
  2033. {
  2034. if (decode_arena_size > DECODE_ARENA_KEEP) {
  2035. free(decode_arena);
  2036. decode_arena = 0;
  2037. decode_arena_size = 0;
  2038. }
  2039. }
  2040. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  2041. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  2042. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  2043. static int svg_text_sniff(const unsigned char *d, unsigned int len);
  2044. static int svg_decode_image(const unsigned char *data, unsigned int len,
  2045. struct br_image *bi, int box_w, int box_h);
  2046. static int decode_image_data(const unsigned char *data, unsigned int len,
  2047. struct br_image *bi, int box_w, int box_h,
  2048. int fit_w, int fit_h)
  2049. {
  2050. struct img_info info;
  2051. struct img_options opt;
  2052. struct img_mem mem;
  2053. struct img_image decoded;
  2054. unsigned char *arena;
  2055. unsigned int est, bytes, i;
  2056. unsigned int t0;
  2057. unsigned short *px;
  2058. unsigned char *alpha = 0;
  2059. int dw, dh, r;
  2060. bi->url_hash = 0;
  2061. img_last_dec_ms = 0;
  2062. img_last_scale_ms = 0;
  2063. if (img_sniff(data, len, &info) != 0) {
  2064. if (svg_text_sniff(data, len))
  2065. return svg_decode_image(data, len, bi,
  2066. box_w > 0 && box_h > 0 ? box_w : fit_w,
  2067. box_w > 0 && box_h > 0 ? box_h : fit_h);
  2068. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  2069. return -1;
  2070. }
  2071. est = img_estimate(&info);
  2072. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  2073. s_copy(bi->err, "image too large", sizeof(bi->err));
  2074. return -1;
  2075. }
  2076. arena = decode_arena_get(est);
  2077. if (!arena) {
  2078. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2079. return -1;
  2080. }
  2081. img_mem_init(&mem, arena, est);
  2082. opt.max_pixels = BR_IMG_PIX_MAX;
  2083. opt.max_w = fit_w > 0 ? (unsigned int)fit_w :
  2084. (box_w > 0 ? (unsigned int)box_w : 0);
  2085. opt.max_h = fit_h > 0 ? (unsigned int)fit_h :
  2086. (box_h > 0 ? (unsigned int)box_h : 0);
  2087. t0 = u_ticks_ms();
  2088. r = img_decode(data, len, &opt, &mem, &decoded);
  2089. img_last_dec_ms = u_ticks_ms() - t0;
  2090. if (r != 0) {
  2091. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  2092. goto fail;
  2093. }
  2094. if (decoded.w == 0 || decoded.h == 0) {
  2095. s_copy(bi->err, "empty image", sizeof(bi->err));
  2096. goto fail;
  2097. }
  2098. /* The JPEG decoder may have reduced the IDCT output; the layout still
  2099. * needs the intrinsic dimensions from the header. */
  2100. bi->native_w = info.width ? (int)info.width : (int)decoded.w;
  2101. bi->native_h = info.height ? (int)info.height : (int)decoded.h;
  2102. dw = (int)decoded.w;
  2103. dh = (int)decoded.h;
  2104. /* An <img> with a CSS/attribute box only ever needs a bitmap that big:
  2105. * decoding 1200x800 and then box-filtering it to 1000x666, only to
  2106. * paint it at 400x267, doubled the decode-time scaling work. cap both
  2107. * axes with one scale so the aspect ratio is preserved. */
  2108. if (fit_w > 0 || fit_h > 0) {
  2109. unsigned int scw = fit_w > 0 ?
  2110. ((unsigned int)fit_w << 16) / decoded.w : ~0u;
  2111. unsigned int sch = fit_h > 0 ?
  2112. ((unsigned int)fit_h << 16) / decoded.h : ~0u;
  2113. unsigned int sc = scw < sch ? scw : sch;
  2114. if (sc < 0x10000u) {
  2115. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2116. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2117. if (dw < 1)
  2118. dw = 1;
  2119. if (dh < 1)
  2120. dh = 1;
  2121. }
  2122. }
  2123. if (box_w > 0 && box_h > 0) {
  2124. /* cover: scale so both box sides are filled, never up */
  2125. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  2126. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  2127. unsigned int sc = sw > sh ? sw : sh;
  2128. if (sc < 0x10000u) {
  2129. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2130. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2131. }
  2132. }
  2133. if (dw > BR_IMG_LAYOUT_W) {
  2134. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  2135. dw = BR_IMG_LAYOUT_W;
  2136. }
  2137. if (dh < 1)
  2138. dh = 1;
  2139. if (dw < 1)
  2140. dw = 1;
  2141. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  2142. BR_IMG_PIXEL_BUDGET) {
  2143. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  2144. goto fail;
  2145. }
  2146. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  2147. px = (unsigned short *)malloc(bytes);
  2148. if (!px) {
  2149. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2150. goto fail;
  2151. }
  2152. /* Keep the alpha plane for the scaled image so transparent logos and
  2153. * icons composite over the page instead of the browser's dark theme
  2154. * background. Very large alpha images stay flattened to bound the
  2155. * heap use. */
  2156. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  2157. alpha = (unsigned char *)malloc((unsigned int)dw *
  2158. (unsigned int)dh);
  2159. if (alpha) {
  2160. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2161. alpha[i] = 255;
  2162. }
  2163. }
  2164. /* With an alpha plane the colour under transparent pixels only shows
  2165. * through partially covered edge pixels of the downscale: use white,
  2166. * as documented above, not the dark browser theme (which left a dark
  2167. * fringe around scaled app icons). */
  2168. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2169. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  2170. {
  2171. struct img_blit b;
  2172. b.dst = px;
  2173. b.dst_w = dw;
  2174. b.dst_h = dh;
  2175. b.clip_x = 0;
  2176. b.clip_y = 0;
  2177. b.clip_w = dw;
  2178. b.clip_h = dh;
  2179. b.x = 0;
  2180. b.y = 0;
  2181. b.scale = ((unsigned int)dw << 16) / decoded.w;
  2182. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  2183. b.bg2 = b.bg;
  2184. b.dst_a = alpha;
  2185. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  2186. t0 = u_ticks_ms();
  2187. img_draw(&decoded, &b);
  2188. img_last_scale_ms = u_ticks_ms() - t0;
  2189. }
  2190. bi->img.format = decoded.format;
  2191. bi->img.w = (unsigned int)dw;
  2192. bi->img.h = (unsigned int)dh;
  2193. bi->img.px = px;
  2194. bi->img.alpha = alpha;
  2195. bi->img.flags = 0;
  2196. bi->state = 1;
  2197. image_pixels += (unsigned int)dw * (unsigned int)dh;
  2198. decode_arena_put();
  2199. return 0;
  2200. fail:
  2201. decode_arena_put();
  2202. return -1;
  2203. }
  2204. /* ---- URL / local path handling ---- */
  2205. static int is_http(const char *s)
  2206. {
  2207. return starts_with(s, "http://") || starts_with(s, "https://");
  2208. }
  2209. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  2210. static int normalize_abs(const char *in, char *out, unsigned int cap)
  2211. {
  2212. char seg[64];
  2213. unsigned int i = 0, o = 1;
  2214. int depth = 0;
  2215. int trailing;
  2216. if (!in || in[0] != '/' || cap < 2)
  2217. return -1;
  2218. trailing = 0;
  2219. {
  2220. unsigned int n = s_len(in);
  2221. if (n > 1 && in[n - 1] == '/')
  2222. trailing = 1;
  2223. }
  2224. out[0] = '/';
  2225. while (in[i]) {
  2226. unsigned int n = 0;
  2227. while (in[i] == '/')
  2228. i++;
  2229. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  2230. if (n + 1 < sizeof(seg))
  2231. seg[n++] = in[i];
  2232. i++;
  2233. }
  2234. seg[n] = '\0';
  2235. if (n == 0)
  2236. break;
  2237. if (s_eq(seg, "."))
  2238. continue;
  2239. if (s_eq(seg, "..")) {
  2240. if (depth > 0) {
  2241. while (o > 1 && out[o - 1] != '/')
  2242. o--;
  2243. if (o > 1)
  2244. o--;
  2245. depth--;
  2246. }
  2247. continue;
  2248. }
  2249. if (o > 1) {
  2250. if (o + 1 >= cap)
  2251. return -1;
  2252. out[o++] = '/';
  2253. }
  2254. if (o + n + 1 >= cap)
  2255. return -1;
  2256. {
  2257. unsigned int j;
  2258. for (j = 0; j < n; j++)
  2259. out[o++] = seg[j];
  2260. }
  2261. depth++;
  2262. }
  2263. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2264. if (o + 1 >= cap)
  2265. return -1;
  2266. out[o++] = '/';
  2267. }
  2268. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2269. if (in[i] == '?' || in[i] == '#') {
  2270. while (in[i]) {
  2271. if (o + 1 >= cap)
  2272. return -1;
  2273. out[o++] = in[i++];
  2274. }
  2275. }
  2276. out[o] = '\0';
  2277. return 0;
  2278. }
  2279. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2280. {
  2281. char joined[BR_URL_MAX];
  2282. if (!in || !in[0]) {
  2283. s_copy(out, cwd[0] ? cwd : "/", cap);
  2284. return;
  2285. }
  2286. if (in[0] == '/') {
  2287. if (normalize_abs(in, out, cap) != 0)
  2288. s_copy(out, in, cap);
  2289. return;
  2290. }
  2291. {
  2292. unsigned int n = 0;
  2293. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2294. s_append(joined, &n, "/", sizeof(joined));
  2295. s_append(joined, &n, in, sizeof(joined));
  2296. }
  2297. if (normalize_abs(joined, out, cap) != 0)
  2298. s_copy(out, joined, cap);
  2299. }
  2300. /* ---- canonical origin cache ---- *
  2301. *
  2302. * Sites commonly redirect http://host to https://host and then to
  2303. * https://www.host. Remember the final scheme/host of the last navigation so
  2304. * a bare domain typed again goes straight there instead of paying for two
  2305. * more connections and TLS handshakes. Only default-port requests are
  2306. * rewritten; explicit ports are left alone. */
  2307. #define ORIGIN_CACHE_MAX 8
  2308. #define ORIGIN_FILE "/share/borigins"
  2309. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2310. UHTTP_HOST_MAX + 2))
  2311. struct origin_cache_entry {
  2312. char host[UHTTP_HOST_MAX];
  2313. char origin[UHTTP_HOST_MAX + 16];
  2314. };
  2315. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2316. static int origin_count;
  2317. static char origin_buf[ORIGIN_BUF_SIZE];
  2318. static int default_port(const struct uhttp_url *u)
  2319. {
  2320. return u->secure ? u->port == 443 : u->port == 80;
  2321. }
  2322. static void url_origin(const struct uhttp_url *u, char *out,
  2323. unsigned int cap)
  2324. {
  2325. unsigned int n = 0;
  2326. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2327. s_append(out, &n, u->host, cap);
  2328. if (!default_port(u)) {
  2329. s_append(out, &n, ":", cap);
  2330. s_append_dec(out, &n, u->port, cap);
  2331. }
  2332. }
  2333. static void origin_cache_apply(char *url, unsigned int cap)
  2334. {
  2335. struct uhttp_url u;
  2336. char out[BR_URL_MAX];
  2337. unsigned int n = 0;
  2338. int i;
  2339. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2340. return;
  2341. for (i = 0; i < origin_count; i++) {
  2342. if (!s_eq(u.host, origins[i].host))
  2343. continue;
  2344. s_append(out, &n, origins[i].origin, sizeof(out));
  2345. s_append(out, &n, u.path, sizeof(out));
  2346. s_copy(url, out, cap);
  2347. return;
  2348. }
  2349. }
  2350. static void origin_cache_save(void)
  2351. {
  2352. unsigned int n = 0;
  2353. int i;
  2354. for (i = 0; i < origin_count; i++) {
  2355. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2356. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2357. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2358. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2359. }
  2360. if (n)
  2361. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2362. (int)origin_buf, (int)n);
  2363. }
  2364. static void origin_cache_load(void)
  2365. {
  2366. char *p;
  2367. int rn;
  2368. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2369. (int)(sizeof(origin_buf) - 1));
  2370. if (rn <= 0)
  2371. return;
  2372. origin_buf[rn] = '\0';
  2373. p = origin_buf;
  2374. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2375. char *line = p, *origin;
  2376. while (*p && *p != '\n')
  2377. p++;
  2378. if (*p)
  2379. *p++ = '\0';
  2380. if (!line[0])
  2381. continue;
  2382. origin = line;
  2383. while (*origin && *origin != ' ')
  2384. origin++;
  2385. if (!*origin)
  2386. continue;
  2387. *origin++ = '\0';
  2388. if (!line[0] || !is_http(origin))
  2389. continue;
  2390. {
  2391. struct uhttp_url uo;
  2392. if (uhttp_parse_url(origin, &uo) != 0 ||
  2393. !s_eq(uo.path, "/"))
  2394. continue;
  2395. }
  2396. s_copy(origins[origin_count].host, line,
  2397. sizeof(origins[origin_count].host));
  2398. s_copy(origins[origin_count].origin, origin,
  2399. sizeof(origins[origin_count].origin));
  2400. origin_count++;
  2401. }
  2402. }
  2403. static int host_is_www_of(const char *host, const char *base)
  2404. {
  2405. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2406. host[3] == '.' && s_eq(host + 4, base);
  2407. }
  2408. static void origin_cache_learn(const char *requested, const char *final)
  2409. {
  2410. struct uhttp_url from, to;
  2411. char origin[UHTTP_HOST_MAX + 16];
  2412. int i;
  2413. if (!is_http(requested) || !is_http(final))
  2414. return;
  2415. if (uhttp_parse_url(requested, &from) != 0 ||
  2416. uhttp_parse_url(final, &to) != 0)
  2417. return;
  2418. if (!default_port(&from))
  2419. return;
  2420. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2421. from.port == to.port)
  2422. return;
  2423. /* Only remember origin-level canonicalisation: the same path, and
  2424. * either the same host or its www./apex sibling. A path- or
  2425. * host-specific redirect (a shortener, a login page) must not poison
  2426. * every request to the typed host. */
  2427. if (!s_eq(from.path, to.path))
  2428. return;
  2429. if (!s_eq(from.host, to.host) &&
  2430. !host_is_www_of(to.host, from.host) &&
  2431. !host_is_www_of(from.host, to.host))
  2432. return;
  2433. url_origin(&to, origin, sizeof(origin));
  2434. for (i = 0; i < origin_count; i++) {
  2435. if (s_eq(origins[i].host, from.host)) {
  2436. if (!s_eq(origins[i].origin, origin)) {
  2437. s_copy(origins[i].origin, origin,
  2438. sizeof(origins[i].origin));
  2439. origin_cache_save();
  2440. }
  2441. return;
  2442. }
  2443. }
  2444. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2445. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2446. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2447. origin_cache_save();
  2448. }
  2449. static int path_dir(const char *path, char *out, unsigned int cap)
  2450. {
  2451. unsigned int i, last = 0;
  2452. for (i = 0; path[i]; i++)
  2453. if (path[i] == '/')
  2454. last = i;
  2455. if (last == 0) {
  2456. if (cap < 2)
  2457. return -1;
  2458. out[0] = '/';
  2459. out[1] = '\0';
  2460. return 0;
  2461. }
  2462. if (last + 1 >= cap)
  2463. return -1;
  2464. {
  2465. unsigned int j;
  2466. for (j = 0; j < last; j++)
  2467. out[j] = path[j];
  2468. out[last] = '\0';
  2469. }
  2470. return 0;
  2471. }
  2472. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2473. static int resolve_link(const char *base, const char *href, char *out,
  2474. unsigned int cap)
  2475. {
  2476. static char joined[BR_URL_MAX]; /* leaf: off the stack */
  2477. if (!href || !href[0] || href[0] == '#')
  2478. return -1;
  2479. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2480. starts_with(href, "data:") || starts_with(href, "tel:"))
  2481. return -1;
  2482. if (starts_with(href, "about:")) {
  2483. s_copy(out, href, cap);
  2484. return 0;
  2485. }
  2486. if (is_http(href)) {
  2487. s_copy(out, href, cap);
  2488. return 0;
  2489. }
  2490. if (starts_with(href, "//")) {
  2491. if (is_http(base)) {
  2492. unsigned int n = 0;
  2493. s_append(out, &n, starts_with(base, "https:") ?
  2494. "https:" : "http:", cap);
  2495. s_append(out, &n, href, cap);
  2496. return 0;
  2497. }
  2498. return -1;
  2499. }
  2500. if (is_http(base)) {
  2501. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2502. }
  2503. /* local page */
  2504. if (href[0] == '/') {
  2505. if (normalize_abs(href, out, cap) != 0)
  2506. return -1;
  2507. return 0;
  2508. }
  2509. {
  2510. static char dir[BR_URL_MAX];
  2511. unsigned int n = 0;
  2512. if (s_eq(base, "about:home"))
  2513. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2514. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2515. s_copy(dir, "/", sizeof(dir));
  2516. s_append(joined, &n, dir, sizeof(joined));
  2517. if (n == 0 || joined[n - 1] != '/')
  2518. s_append(joined, &n, "/", sizeof(joined));
  2519. s_append(joined, &n, href, sizeof(joined));
  2520. }
  2521. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2522. }
  2523. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2524. * rest instead of failing when a page or stylesheet is larger than the
  2525. * buffer. The stream is still walked to the end, so a normal page is
  2526. * verified; a truncated compressed input still returns whatever was decoded
  2527. * so far. */
  2528. struct trunc_buf {
  2529. unsigned char *dst;
  2530. unsigned int cap, pos;
  2531. int full;
  2532. };
  2533. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2534. {
  2535. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2536. if (len > m->cap - m->pos) {
  2537. unsigned int room = m->cap - m->pos;
  2538. if (room) {
  2539. unsigned int i;
  2540. for (i = 0; i < room; i++)
  2541. m->dst[m->pos + i] = data[i];
  2542. m->pos += room;
  2543. }
  2544. m->full = 1;
  2545. return 0;
  2546. }
  2547. {
  2548. unsigned int i;
  2549. for (i = 0; i < len; i++)
  2550. m->dst[m->pos + i] = data[i];
  2551. }
  2552. m->pos += len;
  2553. return 0;
  2554. }
  2555. static void worker_wait_ui(void);
  2556. static void inflate_ui_pump(void *ctx)
  2557. {
  2558. static unsigned int last;
  2559. unsigned int now = u_ticks_ms();
  2560. (void)ctx;
  2561. if ((int)(now - last) >= 50) {
  2562. last = now;
  2563. worker_wait_ui();
  2564. }
  2565. }
  2566. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2567. unsigned char *dst, unsigned int cap,
  2568. unsigned int *outlen, int gzip, int *truncated)
  2569. {
  2570. struct inflate_src in;
  2571. struct inflate_sink sink;
  2572. struct trunc_buf m;
  2573. unsigned int got = 0;
  2574. int r;
  2575. in.p = src;
  2576. in.len = len;
  2577. in.more = 0;
  2578. in.ctx = 0;
  2579. m.dst = dst;
  2580. m.cap = cap;
  2581. m.pos = 0;
  2582. m.full = 0;
  2583. sink.write = trunc_write;
  2584. sink.ctx = &m;
  2585. inflate_init(&image_inflate_ws, &in, &sink);
  2586. image_inflate_ws.progress = inflate_ui_pump;
  2587. image_inflate_ws.progress_ctx = 0;
  2588. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2589. inflate_zlib(&image_inflate_ws, &got);
  2590. *outlen = m.pos;
  2591. *truncated = m.full || r != 0;
  2592. if (r != 0 && m.pos == 0)
  2593. return -1;
  2594. return 0;
  2595. }
  2596. /* ---- headless fetch workers ------------------------------------------ *
  2597. *
  2598. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2599. * writes the raw response, a small metadata file and a done marker under
  2600. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2601. * or a multi-megabyte body never freezes the UI and images download in
  2602. * parallel.
  2603. */
  2604. struct fetch_meta {
  2605. int status;
  2606. int error;
  2607. int trunc;
  2608. unsigned int len;
  2609. unsigned int open_ms;
  2610. unsigned int first_ms;
  2611. unsigned int total_ms;
  2612. /* Optional decoded bitmap produced by the helper (image jobs). */
  2613. unsigned int dw, dh, nw, nh;
  2614. unsigned int alpha;
  2615. unsigned int px_len;
  2616. unsigned int dec_ms;
  2617. int dec_err;
  2618. char encoding[16];
  2619. char ctype[64];
  2620. char final[BR_URL_MAX];
  2621. };
  2622. static void draw(unsigned int *action);
  2623. static void handle_keys(unsigned int *action);
  2624. static void handle_page_click(unsigned int *action);
  2625. #define FETCH_WORKERS 4
  2626. #define FETCH_PATH_MAX 32
  2627. /* One long-lived curl __serve helper per worker. Each worker has its own
  2628. * request/body/meta/done files under /share so several downloads can be in
  2629. * flight at once; the keep-alive connection stays in the helper process, so
  2630. * tls.c's per-process state remains valid. */
  2631. struct fetch_worker {
  2632. int pid;
  2633. int slot;
  2634. int busy;
  2635. int ready;
  2636. int image_job;
  2637. unsigned int seq;
  2638. unsigned int deadline;
  2639. int retried;
  2640. unsigned int dec_w, dec_h;
  2641. int dec_retried;
  2642. char req[FETCH_PATH_MAX];
  2643. char body[FETCH_PATH_MAX];
  2644. char meta[FETCH_PATH_MAX];
  2645. char done[FETCH_PATH_MAX];
  2646. char post[FETCH_PATH_MAX];
  2647. char px[FETCH_PATH_MAX];
  2648. /* Optional preload job attached to this worker. */
  2649. unsigned int node;
  2650. int bg;
  2651. char url[BR_URL_MAX];
  2652. struct fetch_meta m;
  2653. };
  2654. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2655. static int fetch_tty = -2;
  2656. static void fetch_tty_drain(void);
  2657. static unsigned int fetch_session;
  2658. static unsigned int fetch_seq;
  2659. static struct fetch_meta fetch_meta;
  2660. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2661. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2662. static int fetch_last_error;
  2663. static unsigned int meta_uint(char **pp)
  2664. {
  2665. char *p = *pp;
  2666. unsigned int v = 0;
  2667. while (*p >= '0' && *p <= '9') {
  2668. v = v * 10 + (unsigned int)(*p - '0');
  2669. p++;
  2670. }
  2671. while (*p && *p != '\n')
  2672. p++;
  2673. if (*p == '\n')
  2674. p++;
  2675. *pp = p;
  2676. return v;
  2677. }
  2678. static void meta_str(char **pp, char *out, unsigned int cap)
  2679. {
  2680. char *p = *pp;
  2681. unsigned int n = 0;
  2682. while (*p && *p != '\n' && n + 1 < cap)
  2683. out[n++] = *p++;
  2684. out[n] = '\0';
  2685. while (*p && *p != '\n')
  2686. p++;
  2687. if (*p == '\n')
  2688. p++;
  2689. *pp = p;
  2690. }
  2691. static void worker_wait_ui(void)
  2692. {
  2693. unsigned int action = 0;
  2694. if (!ngui_begin(&ui))
  2695. return;
  2696. draw(&action);
  2697. handle_keys(&action);
  2698. handle_page_click(&action);
  2699. if (action & ACT_WAIT_NAV) {
  2700. pending_action |= action & ACT_WAIT_NAV;
  2701. if ((action & ACT_NAV) && click_url[0])
  2702. s_copy(pending_url, click_url, sizeof(pending_url));
  2703. click_url[0] = '\0';
  2704. cancel_fetch = 1;
  2705. }
  2706. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  2707. ngui_invalidate(&ui);
  2708. ngui_end(&ui);
  2709. }
  2710. static void fetch_path(char *out, unsigned int cap, const char *kind,
  2711. unsigned int session, int slot)
  2712. {
  2713. unsigned int n = 0;
  2714. s_append(out, &n, "/share/bf", cap);
  2715. s_append_dec(out, &n, session, cap);
  2716. s_append(out, &n, "_", cap);
  2717. s_append_dec(out, &n, (unsigned int)slot, cap);
  2718. s_append(out, &n, kind, cap);
  2719. }
  2720. static void fetch_pool_init(void)
  2721. {
  2722. static int ready;
  2723. int i;
  2724. if (ready)
  2725. return;
  2726. ready = 1;
  2727. fetch_session = ((unsigned int)u_getpid() << 16) ^
  2728. (u_ticks_ms() & 0xFFFFu);
  2729. if (!fetch_session)
  2730. fetch_session = 1;
  2731. for (i = 0; i < FETCH_WORKERS; i++) {
  2732. struct fetch_worker *w = &fetch_workers[i];
  2733. w->pid = -1;
  2734. w->slot = i;
  2735. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  2736. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  2737. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  2738. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  2739. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  2740. fetch_path(w->px, sizeof(w->px), "px", fetch_session, i);
  2741. }
  2742. }
  2743. static void fetch_worker_stop(struct fetch_worker *w)
  2744. {
  2745. int i;
  2746. /* An abandoned image job leaves its node loadable again. */
  2747. if (w->busy && w->image_job && w->node < doc.nnode) {
  2748. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  2749. doc.nodes[w->node].bg_img_index = -1;
  2750. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  2751. doc.nodes[w->node].img_index = -1;
  2752. }
  2753. if (w->pid > 0) {
  2754. u_kill((unsigned int)w->pid);
  2755. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  2756. u_sleep_ms(5);
  2757. /* Let the reaper close the socket before we reuse the slot. */
  2758. u_sleep_ms(10);
  2759. }
  2760. w->pid = -1;
  2761. w->busy = 0;
  2762. w->ready = 0;
  2763. w->image_job = 0;
  2764. if (w->req[0]) {
  2765. u_syscall1(SYS_UNLINK, (int)w->done);
  2766. u_syscall1(SYS_UNLINK, (int)w->meta);
  2767. u_syscall1(SYS_UNLINK, (int)w->body);
  2768. u_syscall1(SYS_UNLINK, (int)w->post);
  2769. u_syscall1(SYS_UNLINK, (int)w->req);
  2770. }
  2771. }
  2772. static void fetch_workers_stop_all(void)
  2773. {
  2774. int i;
  2775. for (i = 0; i < FETCH_WORKERS; i++)
  2776. fetch_worker_stop(&fetch_workers[i]);
  2777. }
  2778. /* Abandon the transfers of the current page but keep idle helpers and their
  2779. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  2780. * because its response would otherwise land in a reused /share slot. */
  2781. static void fetch_workers_cancel_busy(void)
  2782. {
  2783. int i;
  2784. for (i = 0; i < FETCH_WORKERS; i++)
  2785. if (fetch_workers[i].busy)
  2786. fetch_worker_stop(&fetch_workers[i]);
  2787. }
  2788. static void fetch_workers_prepare_nav(const char *url)
  2789. {
  2790. int i;
  2791. (void)url;
  2792. for (i = 0; i < FETCH_WORKERS; i++) {
  2793. struct fetch_worker *w = &fetch_workers[i];
  2794. if (w->pid <= 0)
  2795. continue;
  2796. /* Only an in-flight transfer must be aborted. Idle helpers
  2797. * stay warm across origins: there are just FETCH_WORKERS of
  2798. * them, and uhttp_open drops the old connection when the
  2799. * next job is for another host. Killing and respawning all
  2800. * four on every navigation churned processes and sockets
  2801. * while images were still loading. */
  2802. if (w->busy)
  2803. fetch_worker_stop(w);
  2804. }
  2805. }
  2806. /* The browser is no longer the active window and no fetch is running: give
  2807. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  2808. static void fetch_workers_stop_if_unfocused(void)
  2809. {
  2810. int i;
  2811. fetch_tty_drain();
  2812. if (ui.focused || page_loading || preload_active)
  2813. return;
  2814. for (i = 0; i < FETCH_WORKERS; i++)
  2815. if (fetch_workers[i].pid > 0) {
  2816. fetch_workers_stop_all();
  2817. return;
  2818. }
  2819. }
  2820. /* The helpers (and this process, since u_tty_create() rebinds our own
  2821. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  2822. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  2823. * a dozen TLS connections every helper hung in its next log line, so the
  2824. * following cross-origin navigation sat at "Loading..." until it timed out.
  2825. * Drain and discard it from every wait/poll loop. */
  2826. static void fetch_tty_drain(void)
  2827. {
  2828. char sink[512];
  2829. int i;
  2830. if (fetch_tty <= 0)
  2831. return;
  2832. for (i = 0; i < 16; i++)
  2833. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  2834. break;
  2835. }
  2836. static int fetch_worker_start(struct fetch_worker *w, char *err,
  2837. unsigned int errcap)
  2838. {
  2839. char arg[40];
  2840. unsigned int n = 0;
  2841. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  2842. return 0;
  2843. w->pid = -1;
  2844. fetch_pool_init();
  2845. if (fetch_tty == -2) {
  2846. int t = u_tty_create();
  2847. fetch_tty = t > 0 ? t : 0;
  2848. }
  2849. s_append(arg, &n, "__serve ", sizeof(arg));
  2850. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  2851. s_append(arg, &n, " ", sizeof(arg));
  2852. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  2853. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  2854. if (w->pid <= 0) {
  2855. w->pid = -1;
  2856. s_copy(err, "cannot start network helper", errcap);
  2857. return -1;
  2858. }
  2859. return 0;
  2860. }
  2861. static struct fetch_worker *fetch_worker_alloc(void)
  2862. {
  2863. int i;
  2864. fetch_pool_init();
  2865. for (i = 0; i < FETCH_WORKERS; i++)
  2866. if (!fetch_workers[i].busy)
  2867. return &fetch_workers[i];
  2868. return 0;
  2869. }
  2870. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  2871. unsigned int cap, const char *method,
  2872. const char *ctype, const char *post,
  2873. unsigned int post_len, unsigned int node,
  2874. int bg, unsigned int dec_w,
  2875. unsigned int dec_h, char *err,
  2876. unsigned int errcap);
  2877. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  2878. unsigned int cap, const char *post,
  2879. unsigned int post_len, unsigned int node,
  2880. int bg, char *err, unsigned int errcap)
  2881. {
  2882. /* A body pointer with no bytes is still a POST: the classic request
  2883. * line would turn it into a GET. */
  2884. if (post && !post_len)
  2885. return fetch_worker_submit_req(w, url, cap, "POST",
  2886. "application/x-www-form-urlencoded", post, 0, node,
  2887. bg, 0, 0, err, errcap);
  2888. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  2889. node, bg, 0, 0, err, errcap);
  2890. }
  2891. /* Image job: ask the helper to decode at these display bounds as well. */
  2892. static int fetch_worker_submit_image(struct fetch_worker *w, const char *url,
  2893. unsigned int cap, unsigned int node,
  2894. int bg, unsigned int dec_w,
  2895. unsigned int dec_h, char *err,
  2896. unsigned int errcap)
  2897. {
  2898. return fetch_worker_submit_req(w, url, cap, 0, 0, 0, 0, node, bg,
  2899. dec_w, dec_h, err, errcap);
  2900. }
  2901. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  2902. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  2903. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  2904. unsigned int cap, const char *method,
  2905. const char *ctype, const char *post,
  2906. unsigned int post_len, unsigned int node,
  2907. int bg, unsigned int dec_w,
  2908. unsigned int dec_h, char *err,
  2909. unsigned int errcap)
  2910. {
  2911. static char req[BR_URL_MAX + 256];
  2912. unsigned int n = 0;
  2913. fetch_seq++;
  2914. if (!fetch_seq)
  2915. fetch_seq = 1;
  2916. w->seq = fetch_seq;
  2917. w->ready = 0;
  2918. w->image_job = 0;
  2919. w->retried = 0;
  2920. w->m.error = 0;
  2921. w->node = node;
  2922. w->bg = bg;
  2923. w->dec_w = dec_w;
  2924. w->dec_h = dec_h;
  2925. w->dec_retried = 0;
  2926. s_copy(w->url, url, sizeof(w->url));
  2927. s_append_dec(req, &n, w->seq, sizeof(req));
  2928. s_append(req, &n, " ", sizeof(req));
  2929. s_append_dec(req, &n, cap, sizeof(req));
  2930. s_append(req, &n, " ", sizeof(req));
  2931. if (dec_w || dec_h) {
  2932. s_append(req, &n, "D ", sizeof(req));
  2933. s_append_dec(req, &n, dec_w, sizeof(req));
  2934. s_append(req, &n, " ", sizeof(req));
  2935. s_append_dec(req, &n, dec_h, sizeof(req));
  2936. s_append(req, &n, " ", sizeof(req));
  2937. } else if (method) {
  2938. unsigned int k;
  2939. s_append(req, &n, "X ", sizeof(req));
  2940. s_append(req, &n, method, sizeof(req));
  2941. s_append(req, &n, " ", sizeof(req));
  2942. s_append_dec(req, &n, post_len, sizeof(req));
  2943. s_append(req, &n, " ", sizeof(req));
  2944. if (!ctype || !ctype[0])
  2945. s_append(req, &n, "-", sizeof(req));
  2946. /* One token on the request line: drop the spaces
  2947. * ("application/json; charset=utf-8" stays valid). */
  2948. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  2949. if (ctype[k] != ' ')
  2950. req[n++] = ctype[k];
  2951. req[n] = '\0';
  2952. s_append(req, &n, " ", sizeof(req));
  2953. } else if (post_len) {
  2954. s_append(req, &n, "POST ", sizeof(req));
  2955. s_append_dec(req, &n, post_len, sizeof(req));
  2956. s_append(req, &n, " ", sizeof(req));
  2957. }
  2958. s_append(req, &n, url, sizeof(req));
  2959. s_append(req, &n, "\n", sizeof(req));
  2960. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  2961. (int)post, (int)post_len) < 0) {
  2962. s_copy(err, "cannot queue form body", errcap);
  2963. return -1;
  2964. }
  2965. u_syscall1(SYS_UNLINK, (int)w->done);
  2966. u_syscall1(SYS_UNLINK, (int)w->meta);
  2967. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  2968. s_copy(err, "cannot queue network request", errcap);
  2969. return -1;
  2970. }
  2971. if (fetch_worker_start(w, err, errcap) != 0)
  2972. return -1;
  2973. w->busy = 1;
  2974. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  2975. return 0;
  2976. }
  2977. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  2978. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  2979. unsigned int errcap)
  2980. {
  2981. static char meta[BR_URL_MAX + 1024];
  2982. char *p;
  2983. int rn, mseq;
  2984. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  2985. (int)(sizeof(meta) - 1));
  2986. if (rn <= 0) {
  2987. s_copy(err, "network helper failed", errcap);
  2988. return -1;
  2989. }
  2990. meta[rn] = '\0';
  2991. p = meta;
  2992. mseq = (int)meta_uint(&p);
  2993. if (mseq != (int)w->seq) {
  2994. s_copy(err, "stale network response", errcap);
  2995. return -1;
  2996. }
  2997. w->m.status = (int)meta_uint(&p);
  2998. w->m.error = (int)meta_uint(&p);
  2999. w->m.trunc = (int)meta_uint(&p);
  3000. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  3001. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  3002. meta_str(&p, w->m.final, sizeof(w->m.final));
  3003. w->m.len = meta_uint(&p);
  3004. w->m.open_ms = 0;
  3005. w->m.first_ms = 0;
  3006. w->m.total_ms = 0;
  3007. if (*p) {
  3008. w->m.open_ms = meta_uint(&p);
  3009. w->m.first_ms = meta_uint(&p);
  3010. w->m.total_ms = meta_uint(&p);
  3011. }
  3012. w->m.dw = w->m.dh = w->m.nw = w->m.nh = 0;
  3013. w->m.alpha = w->m.px_len = w->m.dec_ms = 0;
  3014. w->m.dec_err = 0;
  3015. if (*p) {
  3016. w->m.dw = meta_uint(&p);
  3017. w->m.dh = meta_uint(&p);
  3018. w->m.nw = meta_uint(&p);
  3019. w->m.nh = meta_uint(&p);
  3020. w->m.alpha = meta_uint(&p);
  3021. w->m.px_len = meta_uint(&p);
  3022. w->m.dec_err = (int)meta_uint(&p);
  3023. w->m.dec_ms = meta_uint(&p);
  3024. }
  3025. if (w->m.error) {
  3026. s_copy(err, uhttp_error_string(w->m.error), errcap);
  3027. return -1;
  3028. }
  3029. w->ready = 1;
  3030. return 0;
  3031. }
  3032. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  3033. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  3034. unsigned int errcap)
  3035. {
  3036. static char done[24];
  3037. char *p;
  3038. int rn, mseq;
  3039. fetch_tty_drain();
  3040. if (!w->busy)
  3041. return -1;
  3042. if (w->ready)
  3043. return 1;
  3044. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  3045. (int)(sizeof(done) - 1));
  3046. if (rn > 0) {
  3047. done[rn] = '\0';
  3048. p = done;
  3049. mseq = (int)meta_uint(&p);
  3050. if (mseq == (int)w->seq) {
  3051. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  3052. fetch_worker_stop(w);
  3053. return -1;
  3054. }
  3055. return 1;
  3056. }
  3057. }
  3058. if (!u_alive((unsigned int)w->pid)) {
  3059. w->pid = -1;
  3060. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  3061. w->retried = 1;
  3062. return 0;
  3063. }
  3064. s_copy(err, "network helper stopped", errcap);
  3065. fetch_worker_stop(w);
  3066. return -1;
  3067. }
  3068. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  3069. s_copy(err, "network request timed out", errcap);
  3070. fetch_worker_stop(w);
  3071. return -1;
  3072. }
  3073. return 0;
  3074. }
  3075. /* Copy the completed body, inflating it if the server ignored our identity
  3076. * request. Mirrors the old fetch_remote body path. */
  3077. static int fetch_worker_read_body(struct fetch_worker *w,
  3078. unsigned char *plain,
  3079. unsigned int plaincap,
  3080. unsigned char *comp,
  3081. unsigned int compcap,
  3082. int *truncated, char *err,
  3083. unsigned int errcap)
  3084. {
  3085. int rv, zr, was_trunc;
  3086. if (contains_ci(w->m.encoding, "gzip") ||
  3087. contains_ci(w->m.encoding, "deflate")) {
  3088. unsigned int comp_len = 0, plen = 0;
  3089. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  3090. (int)compcap);
  3091. if (rv < 0) {
  3092. s_copy(err, "empty response", errcap);
  3093. return -1;
  3094. }
  3095. comp_len = (unsigned int)rv;
  3096. if (comp_len < w->m.len) {
  3097. s_copy(err, "compressed response is too large", errcap);
  3098. return -1;
  3099. }
  3100. if (contains_ci(w->m.encoding, "deflate"))
  3101. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3102. &plen, 0, &was_trunc);
  3103. else
  3104. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3105. &plen, 1, &was_trunc);
  3106. if (zr != 0) {
  3107. s_copy(err, "compressed response is corrupt", errcap);
  3108. return -1;
  3109. }
  3110. *truncated = w->m.trunc || was_trunc;
  3111. return (int)plen;
  3112. }
  3113. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  3114. if (rv < 0) {
  3115. s_copy(err, "empty response", errcap);
  3116. return -1;
  3117. }
  3118. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  3119. return rv;
  3120. }
  3121. static void fetch_worker_release(struct fetch_worker *w)
  3122. {
  3123. u_syscall1(SYS_UNLINK, (int)w->done);
  3124. u_syscall1(SYS_UNLINK, (int)w->meta);
  3125. u_syscall1(SYS_UNLINK, (int)w->body);
  3126. u_syscall1(SYS_UNLINK, (int)w->post);
  3127. u_syscall1(SYS_UNLINK, (int)w->px);
  3128. u_syscall1(SYS_UNLINK, (int)w->req);
  3129. w->busy = 0;
  3130. w->ready = 0;
  3131. w->image_job = 0;
  3132. w->dec_w = 0;
  3133. w->dec_h = 0;
  3134. w->dec_retried = 0;
  3135. }
  3136. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  3137. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  3138. unsigned int errcap)
  3139. {
  3140. for (;;) {
  3141. int rv;
  3142. if (!fetch_wait_passive)
  3143. worker_wait_ui();
  3144. if (cancel_fetch || pending_action) {
  3145. fetch_workers_cancel_busy();
  3146. return FETCH_ABORT;
  3147. }
  3148. rv = fetch_worker_poll(w, err, errcap);
  3149. if (rv != 0)
  3150. return rv == 1 ? 0 : -1;
  3151. u_sleep_ms(10);
  3152. }
  3153. }
  3154. static int fetch_remote(const char *url, unsigned int cap,
  3155. const char *post, unsigned int post_len,
  3156. unsigned char *plain, unsigned int plaincap,
  3157. unsigned char *comp, unsigned int compcap,
  3158. struct fetch_meta *m, int *truncated,
  3159. char *err, unsigned int errcap)
  3160. {
  3161. struct fetch_worker *w = fetch_worker_alloc();
  3162. int rv;
  3163. fetch_last_error = 0;
  3164. if (!w) {
  3165. s_copy(err, "network busy", errcap);
  3166. return -1;
  3167. }
  3168. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  3169. err, errcap) != 0) {
  3170. fetch_worker_release(w);
  3171. return -1;
  3172. }
  3173. rv = fetch_worker_wait(w, err, errcap);
  3174. if (rv == FETCH_ABORT) {
  3175. fetch_worker_release(w);
  3176. return FETCH_ABORT;
  3177. }
  3178. if (rv != 0) {
  3179. fetch_last_error = w->m.error;
  3180. fetch_worker_release(w);
  3181. return -1;
  3182. }
  3183. *m = w->m;
  3184. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  3185. truncated, err, errcap);
  3186. fetch_worker_release(w);
  3187. if (rv >= 0 && (cancel_fetch || pending_action))
  3188. return FETCH_ABORT;
  3189. return rv;
  3190. }
  3191. static int fetch_worker_status(const struct fetch_worker *w)
  3192. {
  3193. return w->m.status;
  3194. }
  3195. /* fetch()/XHR through a helper: one request, the status and body come back
  3196. * whatever the HTTP status (a 401 is an answer, not a network error). */
  3197. static int js_worker_http(const char *method, const char *url,
  3198. const char *ctype, const char *body,
  3199. unsigned int body_len, struct js_http_resp *r,
  3200. char *err, int errcap)
  3201. {
  3202. struct fetch_worker *w = fetch_worker_alloc();
  3203. unsigned char *plain;
  3204. int rv, tr = 0;
  3205. if (!w) {
  3206. s_copy(err, "network busy", (unsigned int)errcap);
  3207. return -1;
  3208. }
  3209. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  3210. body_len, 0, 0, 0, 0, err,
  3211. (unsigned int)errcap) != 0) {
  3212. fetch_worker_release(w);
  3213. return -1;
  3214. }
  3215. fetch_wait_passive++;
  3216. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  3217. fetch_wait_passive--;
  3218. if (rv != 0) {
  3219. if (rv == FETCH_ABORT)
  3220. s_copy(err, "page is navigating", (unsigned int)errcap);
  3221. fetch_worker_release(w);
  3222. return -1;
  3223. }
  3224. r->status = w->m.status;
  3225. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  3226. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  3227. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  3228. if (!plain) {
  3229. fetch_worker_release(w);
  3230. s_copy(err, "out of memory", (unsigned int)errcap);
  3231. return -1;
  3232. }
  3233. if (w->m.len == 0) {
  3234. rv = 0; /* 204, an empty 200: no body file */
  3235. } else {
  3236. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  3237. image_io_buf, BR_PAGE_COMP_MAX,
  3238. &tr, err, (unsigned int)errcap);
  3239. }
  3240. fetch_worker_release(w);
  3241. if (rv < 0) {
  3242. free(plain);
  3243. return -1;
  3244. }
  3245. plain[rv] = '\0';
  3246. r->body = (char *)plain;
  3247. r->len = (unsigned int)rv;
  3248. return 0;
  3249. }
  3250. /* ---- HTTP / file fetch ---- */
  3251. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  3252. unsigned int *outlen, int *is_local, char *ctype,
  3253. unsigned int ctcap, char *final, unsigned int finalcap,
  3254. char *err, unsigned int errcap, int *truncated,
  3255. const char *post, unsigned int post_len)
  3256. {
  3257. unsigned char *buf;
  3258. unsigned int len;
  3259. int tr = 0;
  3260. int rv;
  3261. *out = 0;
  3262. *outlen = 0;
  3263. *truncated = 0;
  3264. if (final && finalcap)
  3265. final[0] = '\0';
  3266. if (ctype && ctcap)
  3267. ctype[0] = '\0';
  3268. if (url[0] == '/') {
  3269. char pathbuf[BR_URL_MAX];
  3270. const char *open_url = url;
  3271. unsigned int i = 0;
  3272. /* A local form GET keeps ?query in the address bar but the
  3273. * file lookup uses the path alone, like a real browser. */
  3274. while (url[i] && url[i] != '?' && url[i] != '#')
  3275. i++;
  3276. if (url[i]) {
  3277. s_copy(pathbuf, url, i + 1);
  3278. open_url = pathbuf;
  3279. }
  3280. buf = (unsigned char *)malloc(cap);
  3281. if (!buf) {
  3282. s_copy(err, "out of memory", errcap);
  3283. return -1;
  3284. }
  3285. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  3286. if (rv < 0) {
  3287. free(buf);
  3288. s_copy(err, "file not found", errcap);
  3289. return -1;
  3290. }
  3291. *out = buf;
  3292. *outlen = (unsigned int)rv;
  3293. *is_local = 1;
  3294. if (ctype)
  3295. s_copy(ctype, "text/html", ctcap);
  3296. if (final)
  3297. s_copy(final, url, finalcap);
  3298. if ((unsigned int)rv == cap)
  3299. *truncated = 1;
  3300. return 0;
  3301. }
  3302. buf = (unsigned char *)malloc(cap);
  3303. if (!buf) {
  3304. s_copy(err, "out of memory", errcap);
  3305. return -1;
  3306. }
  3307. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3308. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3309. if (rv == FETCH_ABORT) {
  3310. free(buf);
  3311. return FETCH_ABORT;
  3312. }
  3313. if (rv < 0) {
  3314. free(buf);
  3315. return -1;
  3316. }
  3317. len = (unsigned int)rv;
  3318. if (len == 0) {
  3319. free(buf);
  3320. s_copy(err, "empty response", errcap);
  3321. return -1;
  3322. }
  3323. if (ctype)
  3324. s_copy(ctype, fetch_meta.ctype, ctcap);
  3325. if (final && fetch_meta.final[0])
  3326. s_copy(final, fetch_meta.final, finalcap);
  3327. *is_local = 0;
  3328. *out = buf;
  3329. *outlen = len;
  3330. *truncated = tr;
  3331. return 0;
  3332. }
  3333. /* Load every @font-face the parser registered. Local files go through
  3334. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  3335. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  3336. * to the built-in regular/bold/italic/mono set. */
  3337. static void load_font_faces(void)
  3338. {
  3339. unsigned int i;
  3340. memset(font_faces, 0, sizeof(font_faces));
  3341. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  3342. i <= BR_MAX_FACES; i++) {
  3343. const char *url = br_font_face_url((int)i);
  3344. const char *base = br_font_face_base((int)i);
  3345. char abs[BR_URL_MAX];
  3346. if (!url || !url[0])
  3347. continue;
  3348. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  3349. sizeof(abs)) != 0)
  3350. continue;
  3351. if (abs[0] == '/') {
  3352. font_faces[i - 1] = ufont_face_open_path(abs);
  3353. } else if (is_http(abs)) {
  3354. unsigned char *buf;
  3355. char err[64];
  3356. int rv, tr = 0;
  3357. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  3358. if (!buf)
  3359. continue;
  3360. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3361. UFONT_MAX_FILE, image_io_buf,
  3362. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  3363. err, sizeof(err));
  3364. if (rv > 0)
  3365. font_faces[i - 1] = ufont_face_open_mem(buf,
  3366. rv);
  3367. free(buf);
  3368. }
  3369. }
  3370. }
  3371. /* Remote scripts are cached under /share for the current boot, like the
  3372. * stylesheet cache, so reloads and later visits skip the network. */
  3373. static int script_cache_count;
  3374. static unsigned int script_cache_hash(const char *s)
  3375. {
  3376. unsigned int h = 2166136261u;
  3377. while (*s) {
  3378. h ^= (unsigned char)*s++;
  3379. h *= 16777619u;
  3380. }
  3381. return h;
  3382. }
  3383. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3384. {
  3385. unsigned int n = 0;
  3386. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3387. s_append_dec(out, &n, script_cache_hash(url), cap);
  3388. }
  3389. static void script_cache_clear(void)
  3390. {
  3391. struct sys_dirent d;
  3392. char path[96];
  3393. for (;;) {
  3394. int i, found = 0;
  3395. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3396. (int)&d) == 1; i++) {
  3397. unsigned int n = 0;
  3398. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3399. continue;
  3400. s_append(path, &n, "/share/", sizeof(path));
  3401. s_append(path, &n, d.name, sizeof(path));
  3402. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3403. return;
  3404. found = 1;
  3405. break;
  3406. }
  3407. if (!found)
  3408. break;
  3409. }
  3410. script_cache_count = 0;
  3411. }
  3412. static void script_cache_init(void)
  3413. {
  3414. struct sys_dirent d;
  3415. int i, count = 0;
  3416. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3417. (int)&d) == 1; i++)
  3418. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3419. count++;
  3420. if (count >= SCRIPT_CACHE_MAX) {
  3421. script_cache_clear();
  3422. return;
  3423. }
  3424. script_cache_count = count;
  3425. }
  3426. static int script_cache_get(const char *url, unsigned char **out,
  3427. unsigned int *outlen)
  3428. {
  3429. char path[96];
  3430. struct sys_stat st;
  3431. unsigned char *buf;
  3432. int rn;
  3433. script_cache_path(url, path, sizeof(path));
  3434. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3435. st.size >= SCRIPT_CACHE_FILE_MAX)
  3436. return 0;
  3437. buf = (unsigned char *)malloc(st.size + 1);
  3438. if (!buf)
  3439. return 0;
  3440. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3441. if (rn != (int)st.size) {
  3442. free(buf);
  3443. return 0;
  3444. }
  3445. buf[st.size] = '\0';
  3446. *out = buf;
  3447. *outlen = st.size;
  3448. return 1;
  3449. }
  3450. static void script_cache_put(const char *url, const unsigned char *data,
  3451. unsigned int len)
  3452. {
  3453. char path[96];
  3454. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3455. len >= SCRIPT_CACHE_FILE_MAX)
  3456. return;
  3457. script_cache_path(url, path, sizeof(path));
  3458. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3459. (int)len) >= 0)
  3460. script_cache_count++;
  3461. }
  3462. static int script_cache_has(const char *url)
  3463. {
  3464. char path[96];
  3465. struct sys_stat st;
  3466. script_cache_path(url, path, sizeof(path));
  3467. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3468. st.size < SCRIPT_CACHE_FILE_MAX;
  3469. }
  3470. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3471. static int fetch_script_text(const char *url, unsigned char **out,
  3472. unsigned int *outlen, char *err,
  3473. unsigned int errcap)
  3474. {
  3475. unsigned char *buf;
  3476. unsigned int len;
  3477. int local, truncated = 0;
  3478. char ctype[64], final[BR_URL_MAX];
  3479. int rv;
  3480. *out = 0;
  3481. *outlen = 0;
  3482. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3483. return 0;
  3484. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3485. sizeof(ctype), final, sizeof(final), err, errcap,
  3486. &truncated, 0, 0);
  3487. if (rv != 0)
  3488. return rv;
  3489. if (truncated || len >= BR_SCRIPT_MAX) {
  3490. free(buf);
  3491. s_copy(err, "script is too large", errcap);
  3492. return -1;
  3493. }
  3494. buf[len] = '\0';
  3495. if (!local)
  3496. script_cache_put(url, buf, len);
  3497. *out = buf;
  3498. *outlen = len;
  3499. return 0;
  3500. }
  3501. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  3502. * the heap, so images must not allocate their file body from it as well. */
  3503. static int fetch_image(const char *url, unsigned int cap,
  3504. unsigned char **out, unsigned int *outlen,
  3505. char *err, unsigned int errcap)
  3506. {
  3507. unsigned int len;
  3508. int tr = 0;
  3509. int rv;
  3510. *out = 0;
  3511. *outlen = 0;
  3512. if (cap > BR_IMG_FILE_MAX)
  3513. cap = BR_IMG_FILE_MAX;
  3514. if (url[0] == '/') {
  3515. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  3516. (int)cap);
  3517. if (rv < 0) {
  3518. s_copy(err, "file not found", errcap);
  3519. return -1;
  3520. }
  3521. *out = image_file_buf;
  3522. *outlen = (unsigned int)rv;
  3523. return 0;
  3524. }
  3525. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  3526. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  3527. if (rv == FETCH_ABORT)
  3528. return FETCH_ABORT;
  3529. if (rv < 0)
  3530. return -1;
  3531. len = (unsigned int)rv;
  3532. if (len == 0) {
  3533. s_copy(err, "empty image", errcap);
  3534. return -1;
  3535. }
  3536. *out = image_file_buf;
  3537. *outlen = len;
  3538. return 0;
  3539. }
  3540. /* Remote stylesheets are immutable enough for the current boot: keep
  3541. * successful responses under /share so a reload, a second visit or a fresh
  3542. * browser launch does not fetch the same five sheets over the network again.
  3543. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  3544. static int css_cache_count;
  3545. static unsigned int css_cache_hash(const char *s)
  3546. {
  3547. unsigned int h = 2166136261u;
  3548. while (*s) {
  3549. h ^= (unsigned char)*s++;
  3550. h *= 16777619u;
  3551. }
  3552. return h;
  3553. }
  3554. static void css_cache_path(const char *url, char *out, unsigned int cap)
  3555. {
  3556. unsigned int n = 0;
  3557. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  3558. s_append_dec(out, &n, css_cache_hash(url), cap);
  3559. }
  3560. static void css_cache_clear(void)
  3561. {
  3562. struct sys_dirent d;
  3563. char path[96];
  3564. for (;;) {
  3565. int i, found = 0;
  3566. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3567. (int)&d) == 1; i++) {
  3568. unsigned int n = 0;
  3569. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  3570. continue;
  3571. s_append(path, &n, "/share/", sizeof(path));
  3572. s_append(path, &n, d.name, sizeof(path));
  3573. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3574. return;
  3575. found = 1;
  3576. break;
  3577. }
  3578. if (!found)
  3579. break;
  3580. }
  3581. css_cache_count = 0;
  3582. }
  3583. static void css_cache_init(void)
  3584. {
  3585. struct sys_dirent d;
  3586. int i, count = 0;
  3587. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3588. (int)&d) == 1; i++)
  3589. if (starts_with(d.name, CSS_CACHE_PREFIX))
  3590. count++;
  3591. if (count >= CSS_CACHE_MAX) {
  3592. css_cache_clear();
  3593. return;
  3594. }
  3595. css_cache_count = count;
  3596. }
  3597. static int css_cache_get(const char *url, unsigned char **out,
  3598. unsigned int *outlen)
  3599. {
  3600. char path[96];
  3601. int rn;
  3602. css_cache_path(url, path, sizeof(path));
  3603. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  3604. (int)CSS_CACHE_FILE_MAX);
  3605. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  3606. return 0;
  3607. *out = image_io_buf;
  3608. *outlen = (unsigned int)rn;
  3609. return 1;
  3610. }
  3611. static void css_cache_put(const char *url, const unsigned char *data,
  3612. unsigned int len)
  3613. {
  3614. char path[96];
  3615. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  3616. len >= CSS_CACHE_FILE_MAX)
  3617. return;
  3618. css_cache_path(url, path, sizeof(path));
  3619. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3620. (int)len) >= 0)
  3621. css_cache_count++;
  3622. }
  3623. static int css_cache_has(const char *url)
  3624. {
  3625. char path[96];
  3626. struct sys_stat st;
  3627. css_cache_path(url, path, sizeof(path));
  3628. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3629. st.size < CSS_CACHE_FILE_MAX;
  3630. }
  3631. /* Read one stylesheet into the shared static buffer. CSS is parsed
  3632. * immediately, so it does not need the page heap; this leaves the heap for
  3633. * the 2 MB page body, the rules and the scaled image bitmaps. */
  3634. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  3635. char *err, unsigned int errcap)
  3636. {
  3637. unsigned int len;
  3638. int tr = 0;
  3639. int rv;
  3640. *out = 0;
  3641. *outlen = 0;
  3642. if (url[0] == '/') {
  3643. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  3644. (int)BR_CSS_MAX);
  3645. if (rv < 0) {
  3646. s_copy(err, "stylesheet not found", errcap);
  3647. return -1;
  3648. }
  3649. *out = image_io_buf;
  3650. *outlen = (unsigned int)rv;
  3651. return 0;
  3652. }
  3653. if (css_cache_get(url, out, outlen))
  3654. return 0;
  3655. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  3656. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  3657. &fetch_meta, &tr, err, errcap);
  3658. if (rv == FETCH_ABORT)
  3659. return FETCH_ABORT;
  3660. if (rv < 0)
  3661. return -1;
  3662. len = (unsigned int)rv;
  3663. if (len == 0) {
  3664. s_copy(err, "empty stylesheet", errcap);
  3665. return -1;
  3666. }
  3667. *out = image_io_buf;
  3668. *outlen = len;
  3669. css_cache_put(url, image_io_buf, len);
  3670. return 0;
  3671. }
  3672. static void redraw_now(void);
  3673. static char error_page[1024];
  3674. static void show_error(const char *title, const char *detail)
  3675. {
  3676. char *page = error_page;
  3677. unsigned int n = 0;
  3678. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  3679. s_append(page, &n, title, sizeof(error_page));
  3680. s_append(page, &n, "</h2><p>", sizeof(error_page));
  3681. {
  3682. const char *p = detail;
  3683. while (*p && n + 1 < sizeof(error_page)) {
  3684. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  3685. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  3686. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  3687. else page[n++] = *p;
  3688. p++;
  3689. }
  3690. }
  3691. page[n] = '\0';
  3692. s_append(page, &n, "</p><p>", sizeof(error_page));
  3693. s_append(page, &n, page_url, sizeof(error_page));
  3694. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  3695. sizeof(error_page));
  3696. br_parse(&doc, page, n);
  3697. layout_valid = 0;
  3698. preload_active = 0;
  3699. preload_pending = 0;
  3700. preload_wait = 0;
  3701. fetch_workers_cancel_busy();
  3702. s_copy(page_title, title, sizeof(page_title));
  3703. page_loading = 0;
  3704. set_status(title, 1, 0);
  3705. ngui_invalidate(&ui);
  3706. }
  3707. static int decode_direct_image(const unsigned char *data, unsigned int len,
  3708. unsigned int node)
  3709. {
  3710. if (image_count >= BR_MAX_IMAGES)
  3711. return -1;
  3712. if (decode_image_data(data, len, &images[0], 0, 0, 0, 0) != 0)
  3713. return -1;
  3714. doc.nodes[node].img_index = 0;
  3715. image_count = 1;
  3716. return 0;
  3717. }
  3718. static int ancestor_is(unsigned int node, unsigned int tag)
  3719. {
  3720. unsigned int p = doc.nodes[node].parent;
  3721. while (p) {
  3722. if (doc.nodes[p].tag == tag)
  3723. return 1;
  3724. p = doc.nodes[p].parent;
  3725. }
  3726. return 0;
  3727. }
  3728. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  3729. * parallel but parsed in document order, so the cascade is unchanged. */
  3730. static int load_stylesheets(void)
  3731. {
  3732. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  3733. static unsigned char remote[BR_MAX_SHEETS];
  3734. struct fetch_worker *slot[BR_MAX_SHEETS];
  3735. unsigned int i, n = 0, next = 0, k;
  3736. char err[64];
  3737. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  3738. struct br_node *nd = &doc.nodes[i];
  3739. const char *rel, *href;
  3740. char url[BR_URL_MAX];
  3741. int dup = 0;
  3742. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  3743. continue;
  3744. rel = br_rel(&doc, i);
  3745. if (!contains_ci(rel, "stylesheet"))
  3746. continue;
  3747. href = br_href(&doc, i);
  3748. if (!href[0])
  3749. continue;
  3750. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  3751. continue;
  3752. for (k = 0; k < n; k++)
  3753. if (s_eq(urls[k], url)) {
  3754. dup = 1;
  3755. break;
  3756. }
  3757. if (dup)
  3758. continue;
  3759. s_copy(urls[n], url, BR_URL_MAX);
  3760. remote[n] = url[0] != '/' && !css_cache_has(url);
  3761. n++;
  3762. }
  3763. for (i = 0; i < BR_MAX_SHEETS; i++)
  3764. slot[i] = 0;
  3765. /* Start as many remote sheets as there are free workers. */
  3766. for (; next < n; next++) {
  3767. struct fetch_worker *w;
  3768. if (!remote[next])
  3769. continue;
  3770. w = fetch_worker_alloc();
  3771. if (!w)
  3772. break;
  3773. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  3774. err, sizeof(err)) != 0) {
  3775. fetch_worker_release(w);
  3776. remote[next] = 0;
  3777. continue;
  3778. }
  3779. slot[next] = w;
  3780. }
  3781. for (i = 0; i < n; i++) {
  3782. unsigned char *data = 0;
  3783. unsigned int len = 0;
  3784. int rv;
  3785. if (!remote[i]) {
  3786. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  3787. if (rv == FETCH_ABORT) {
  3788. fetch_workers_stop_all();
  3789. return FETCH_ABORT;
  3790. }
  3791. if (rv != 0 || !len)
  3792. continue;
  3793. } else {
  3794. struct fetch_worker *w = slot[i];
  3795. int tr = 0;
  3796. if (!w) {
  3797. w = fetch_worker_alloc();
  3798. if (!w) {
  3799. rv = -1;
  3800. goto css_failed;
  3801. }
  3802. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  3803. 0, 0, 0, 0, err,
  3804. sizeof(err)) != 0) {
  3805. fetch_worker_release(w);
  3806. remote[i] = 0;
  3807. if (i == next)
  3808. next++;
  3809. continue;
  3810. }
  3811. slot[i] = w;
  3812. if (i == next)
  3813. next++;
  3814. }
  3815. rv = fetch_worker_wait(w, err, sizeof(err));
  3816. if (rv == FETCH_ABORT) {
  3817. fetch_workers_stop_all();
  3818. return FETCH_ABORT;
  3819. }
  3820. if (rv == 0)
  3821. rv = fetch_worker_read_body(w, image_io_buf,
  3822. BR_CSS_MAX,
  3823. image_io_buf + BR_CSS_MAX,
  3824. BR_CSS_COMP_MAX, &tr,
  3825. err, sizeof(err));
  3826. else
  3827. rv = -1;
  3828. fetch_worker_release(w);
  3829. slot[i] = 0;
  3830. /* Refill the worker window before parsing this sheet. */
  3831. for (; next < n; next++) {
  3832. struct fetch_worker *nw;
  3833. if (!remote[next])
  3834. continue;
  3835. nw = fetch_worker_alloc();
  3836. if (!nw)
  3837. break;
  3838. if (fetch_worker_submit(nw, urls[next],
  3839. BR_CSS_MAX, 0, 0, 0, 0,
  3840. err, sizeof(err)) != 0) {
  3841. fetch_worker_release(nw);
  3842. remote[next] = 0;
  3843. continue;
  3844. }
  3845. slot[next] = nw;
  3846. }
  3847. css_failed:
  3848. if (rv <= 0) {
  3849. /* One synchronous retry: a dropped sheet leaves the
  3850. * whole page unstyled (seen intermittently on
  3851. * arstechnica's CDN). */
  3852. u_puts("[css] retry ");
  3853. u_puts(urls[i]);
  3854. u_puts(": ");
  3855. u_puts(err[0] ? err : "no worker/empty body");
  3856. u_putc('\n');
  3857. err[0] = '\0';
  3858. rv = fetch_css(urls[i], &data, &len, err,
  3859. sizeof(err));
  3860. if (rv == FETCH_ABORT) {
  3861. fetch_workers_stop_all();
  3862. return FETCH_ABORT;
  3863. }
  3864. if (rv != 0 || !len) {
  3865. u_puts("[css] failed: ");
  3866. u_puts(err);
  3867. u_putc('\n');
  3868. continue;
  3869. }
  3870. } else {
  3871. len = (unsigned int)rv;
  3872. data = image_io_buf;
  3873. css_cache_put(urls[i], data, len);
  3874. }
  3875. }
  3876. if (len) {
  3877. br_set_font_base(urls[i]);
  3878. br_parse_css_text(&doc, (const char *)data, len);
  3879. }
  3880. }
  3881. br_set_font_base(page_url);
  3882. br_parse_inline_css(&doc);
  3883. load_font_faces();
  3884. br_reset_styles(&doc);
  3885. layout_valid = 0;
  3886. return 0;
  3887. }
  3888. static void preload_begin(void)
  3889. {
  3890. preload_active = 1;
  3891. preload_pending = 0;
  3892. preload_wait = 1;
  3893. preload_max_jobs = FETCH_WORKERS;
  3894. preload_node = 0;
  3895. preload_loaded = 0;
  3896. preload_scroll = 0;
  3897. img_stat_start = u_ticks_ms();
  3898. img_stat_wall = 0;
  3899. img_stat_net = img_stat_open = img_stat_first = 0;
  3900. img_stat_io = img_stat_dec = img_stat_scale = 0;
  3901. img_stat_paint = img_stat_reflow = 0;
  3902. img_stat_bytes = 0;
  3903. img_stat_n = 0;
  3904. img_stat_log_len = 0;
  3905. if (img_stat_log[0])
  3906. img_stat_log[0] = '\0';
  3907. img_repaint_ms = 0;
  3908. img_repaint_pending = 0;
  3909. }
  3910. /* Styles are computed top-down during layout, but images inside a hidden
  3911. * menu/carousel are never visited and keep img_top == 0. Without this check
  3912. * the preloader walks the DOM in node order and spends the whole image
  3913. * budget on logos and off-canvas thumbnails the reader cannot see. */
  3914. static int node_hidden(unsigned int node)
  3915. {
  3916. unsigned int path[32], n = 0, p = node, i;
  3917. struct br_style st, parent;
  3918. while (p && n < sizeof(path) / sizeof(path[0])) {
  3919. path[n++] = p;
  3920. p = doc.nodes[p].parent;
  3921. }
  3922. parent = (struct br_style){0};
  3923. parent.font_px = 16;
  3924. parent.display = BR_DISPLAY_BLOCK;
  3925. for (i = n; i > 0; i--) {
  3926. br_style_for(&doc, path[i - 1], &parent, &st);
  3927. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  3928. st.opacity_hidden)
  3929. return 1;
  3930. parent = st;
  3931. }
  3932. return 0;
  3933. }
  3934. static struct br_style base_style(void);
  3935. static int style_width_px(const struct br_style *st, int base);
  3936. static int style_height_px(const struct br_style *st, int base);
  3937. static void style_for_node(unsigned int node, struct br_style *out)
  3938. {
  3939. unsigned int p = doc.nodes[node].parent;
  3940. struct br_style parent;
  3941. if (p) {
  3942. style_for_node(p, &parent);
  3943. br_style_for(&doc, node, &parent, out);
  3944. } else {
  3945. parent = base_style();
  3946. br_style_for(&doc, node, &parent, out);
  3947. }
  3948. }
  3949. /* ---- parallel image preloading ---- *
  3950. *
  3951. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  3952. * preload_step() only starts jobs and harvests completed ones; the browser
  3953. * main loop keeps drawing between calls, instead of blocking on one fetch.
  3954. */
  3955. static int preload_active_jobs(void)
  3956. {
  3957. int i, n = 0;
  3958. for (i = 0; i < FETCH_WORKERS; i++)
  3959. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  3960. n++;
  3961. return n;
  3962. }
  3963. static void preload_job_error(struct fetch_worker *w)
  3964. {
  3965. if (w->node < doc.nnode) {
  3966. if (w->bg)
  3967. doc.nodes[w->node].bg_img_index = -2;
  3968. else
  3969. doc.nodes[w->node].img_index = -2;
  3970. image_repaint();
  3971. }
  3972. }
  3973. /* Is the image's box anywhere near the visible page? A decode below the
  3974. * fold changes the layout (scroll extent) but not a single on-screen pixel,
  3975. * so it does not need a repaint. top/h come from the last layout; treat an
  3976. * unknown box as visible to stay safe. */
  3977. static int image_preload_visible(unsigned int node, int bg)
  3978. {
  3979. int top, h, scroll;
  3980. if (node >= BR_MAX_NODES || node >= doc.nnode || page_rect.h <= 0)
  3981. return 1;
  3982. if (bg) {
  3983. top = (int)block_top[node];
  3984. h = (int)block_h[node];
  3985. } else {
  3986. top = (int)img_top[node];
  3987. h = (int)img_h[node];
  3988. }
  3989. if (!top && !h)
  3990. return 1;
  3991. scroll = (int)page_scroll.offset;
  3992. if (top > scroll + page_rect.h + 160)
  3993. return 0;
  3994. if (top + h + 160 < scroll)
  3995. return 0;
  3996. return 1;
  3997. }
  3998. /* Upper bounds for the bitmap an <img> will paint. Zero means "unbounded";
  3999. * decode_image_data applies one scale to both axes so the aspect ratio is
  4000. * preserved. This is what keeps a 1200x800 photo that CSS paints at 400 px
  4001. * from being decoded and box-filtered to the 1000 px layout cap first. */
  4002. static void image_fit_size(unsigned int node, int *out_w, int *out_h)
  4003. {
  4004. struct br_style st;
  4005. struct br_node *nd;
  4006. unsigned int p;
  4007. int cw, w = 0, h = 0;
  4008. *out_w = *out_h = 0;
  4009. if (node >= doc.nnode)
  4010. return;
  4011. nd = &doc.nodes[node];
  4012. style_for_node(node, &st);
  4013. cw = page_rect.w > 24 ? page_rect.w - 24 : 0;
  4014. p = doc.nodes[node].parent;
  4015. if (p && p < BR_MAX_NODES && layout_boxes[p].valid &&
  4016. layout_boxes[p].w > 0 && layout_boxes[p].w < cw)
  4017. cw = layout_boxes[p].w;
  4018. if (st.width_kind)
  4019. w = style_width_px(&st, cw);
  4020. else if (nd->width_attr)
  4021. w = nd->width_pct ? cw * (int)nd->width_attr / 100 :
  4022. (int)nd->width_attr;
  4023. if (st.height_kind)
  4024. h = style_height_px(&st, cw);
  4025. else if (nd->height_attr)
  4026. h = nd->height_pct ? cw * (int)nd->height_attr / 100 :
  4027. (int)nd->height_attr;
  4028. if (st.max_width_kind) {
  4029. int mw = st.max_width_kind == 3 ?
  4030. cw * st.max_width_calc_pct / 100 +
  4031. st.max_width_calc_px :
  4032. st.max_width_kind == 2 ?
  4033. cw * (int)st.max_width / 100 :
  4034. (int)st.max_width;
  4035. if (mw > 0 && (w == 0 || w > mw))
  4036. w = mw;
  4037. }
  4038. if (st.max_height_kind) {
  4039. int mh = st.max_height_kind == 3 ?
  4040. cw * st.max_height_calc_pct / 100 +
  4041. st.max_height_calc_px :
  4042. st.max_height_kind == 2 ?
  4043. cw * (int)st.max_height / 100 :
  4044. (int)st.max_height;
  4045. if (mh > 0 && (h == 0 || h > mh))
  4046. h = mh;
  4047. }
  4048. if (w > BR_IMG_LAYOUT_W)
  4049. w = BR_IMG_LAYOUT_W;
  4050. if (h > 4096)
  4051. h = 4096;
  4052. if (w < 0)
  4053. w = 0;
  4054. if (h < 0)
  4055. h = 0;
  4056. *out_w = w;
  4057. *out_h = h;
  4058. }
  4059. static void preload_accept_image(unsigned int node, int bg, const char *url)
  4060. {
  4061. /* An <img> bitmap only depends on its URL, so the next <img> with the
  4062. * same source reuses it (heise repeats one comment icon 85 times).
  4063. * Backgrounds are scaled to their box and are not shared. */
  4064. images[image_count].url_hash =
  4065. !bg && url ? script_cache_hash(url) | 1u : 0;
  4066. if (bg)
  4067. doc.nodes[node].bg_img_index = (short)image_count;
  4068. else
  4069. doc.nodes[node].img_index = (short)image_count;
  4070. image_count++;
  4071. preload_loaded++;
  4072. /* A background bitmap never changes its box, so keep the (expensive)
  4073. * measured layout and only repaint the pixels. */
  4074. if (bg)
  4075. page_cache_valid = 0;
  4076. else
  4077. layout_valid = 0;
  4078. if (image_preload_visible(node, bg))
  4079. image_repaint();
  4080. }
  4081. /* Install a bitmap decoded by the fetch helper. The helper already applied
  4082. * the display bounds (and the JPEG reduced IDCT), so this is a read + copy
  4083. * on the UI thread instead of a decode. */
  4084. static int preload_store_helper(unsigned int node, int bg,
  4085. unsigned char *px, unsigned int pxlen,
  4086. unsigned int dw, unsigned int dh,
  4087. int alpha, unsigned int nw, unsigned int nh,
  4088. const char *url)
  4089. {
  4090. struct br_image *bi;
  4091. unsigned int npx;
  4092. if (image_count >= BR_MAX_IMAGES || !px || !dw || !dh ||
  4093. dw > 4096 || dh > 4096) {
  4094. free(px);
  4095. return -1;
  4096. }
  4097. npx = dw * dh;
  4098. if (image_pixels + npx > BR_IMG_PIXEL_BUDGET ||
  4099. pxlen < npx * 2u + (alpha ? npx : 0)) {
  4100. free(px);
  4101. return -1;
  4102. }
  4103. bi = &images[image_count];
  4104. bi->img.format = 0;
  4105. bi->img.w = dw;
  4106. bi->img.h = dh;
  4107. bi->img.px = (unsigned short *)px;
  4108. bi->img.alpha = alpha ? px + npx * 2u : 0;
  4109. bi->img.flags = 0;
  4110. bi->native_w = nw ? (int)nw : (int)dw;
  4111. bi->native_h = nh ? (int)nh : (int)dh;
  4112. bi->state = 1;
  4113. image_pixels += npx;
  4114. preload_accept_image(node, bg, url);
  4115. return 0;
  4116. }
  4117. static void preload_decode(unsigned int node, int bg,
  4118. const unsigned char *data, unsigned int len,
  4119. const char *url)
  4120. {
  4121. int fit_w = 0, fit_h = 0;
  4122. if (image_count >= BR_MAX_IMAGES) {
  4123. if (bg)
  4124. doc.nodes[node].bg_img_index = -2;
  4125. else
  4126. doc.nodes[node].img_index = -2;
  4127. return;
  4128. }
  4129. if (!bg)
  4130. image_fit_size(node, &fit_w, &fit_h);
  4131. if (decode_image_data(data, len, &images[image_count],
  4132. bg && node < BR_MAX_NODES &&
  4133. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  4134. bg && node < BR_MAX_NODES &&
  4135. layout_boxes[node].valid ? layout_boxes[node].h : 0,
  4136. fit_w, fit_h) == 0) {
  4137. preload_accept_image(node, bg, url);
  4138. } else {
  4139. if (bg)
  4140. doc.nodes[node].bg_img_index = -2;
  4141. else
  4142. doc.nodes[node].img_index = -2;
  4143. layout_valid = 0;
  4144. }
  4145. if (image_preload_visible(node, bg))
  4146. image_repaint();
  4147. }
  4148. /* A local file image bypasses the helpers: count its decode so a page opened
  4149. * from /share or /data still produces the same timing breakdown. */
  4150. static void img_stat_local(int before, unsigned int bytes, unsigned int io_ms)
  4151. {
  4152. img_stat_n++;
  4153. img_stat_bytes += bytes;
  4154. img_stat_io += io_ms;
  4155. if (image_count > before) {
  4156. struct br_image *bi = &images[image_count - 1];
  4157. img_stat_dec += img_last_dec_ms;
  4158. img_stat_scale += img_last_scale_ms;
  4159. if (img_stat_log_len + 100 < sizeof(img_stat_log)) {
  4160. unsigned int n = img_stat_log_len;
  4161. s_append(img_stat_log, &n, "local ", sizeof(img_stat_log));
  4162. s_append_dec(img_stat_log, &n, bytes,
  4163. sizeof(img_stat_log));
  4164. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4165. s_append_dec(img_stat_log, &n, img_last_dec_ms,
  4166. sizeof(img_stat_log));
  4167. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4168. s_append_dec(img_stat_log, &n, img_last_scale_ms,
  4169. sizeof(img_stat_log));
  4170. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4171. s_append_dec(img_stat_log, &n,
  4172. (unsigned int)bi->native_w,
  4173. sizeof(img_stat_log));
  4174. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4175. s_append_dec(img_stat_log, &n,
  4176. (unsigned int)bi->native_h,
  4177. sizeof(img_stat_log));
  4178. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4179. s_append_dec(img_stat_log, &n, bi->img.w,
  4180. sizeof(img_stat_log));
  4181. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4182. s_append_dec(img_stat_log, &n, bi->img.h,
  4183. sizeof(img_stat_log));
  4184. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4185. s_append_dec(img_stat_log, &n,
  4186. bi->img.alpha ? 1u : 0u,
  4187. sizeof(img_stat_log));
  4188. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4189. img_stat_log_len = n;
  4190. }
  4191. }
  4192. }
  4193. /* Harvest one completed worker. Returns 1 when a job was finished. */
  4194. static int preload_finish_worker(struct fetch_worker *w)
  4195. {
  4196. char err[64];
  4197. int rv, tr = 0;
  4198. unsigned int t0, io_ms;
  4199. int before;
  4200. int used_px = 0;
  4201. rv = fetch_worker_poll(w, err, sizeof(err));
  4202. if (rv < 0) {
  4203. /* A helper from an older pack does not understand the image
  4204. * decode request; retry once without it and decode in-process. */
  4205. if (w->image_job && w->dec_w && !w->dec_retried &&
  4206. fetch_worker_submit_req(w, w->url, BR_IMG_FILE_MAX,
  4207. 0, 0, 0, 0, w->node, w->bg,
  4208. 0, 0, err, sizeof(err)) == 0) {
  4209. w->image_job = 1;
  4210. w->dec_retried = 1;
  4211. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4212. return 0;
  4213. }
  4214. preload_job_error(w);
  4215. if (img_stat_log_len + 64 < sizeof(img_stat_log)) {
  4216. unsigned int n = img_stat_log_len;
  4217. char u[48];
  4218. s_copy(u, w->url, sizeof(u));
  4219. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4220. s_append(img_stat_log, &n, " error\n",
  4221. sizeof(img_stat_log));
  4222. img_stat_log_len = n;
  4223. }
  4224. img_stat_n++;
  4225. fetch_worker_release(w);
  4226. return 1;
  4227. }
  4228. if (rv == 0)
  4229. return 0;
  4230. t0 = u_ticks_ms();
  4231. rv = -1;
  4232. before = image_count;
  4233. if (w->m.px_len && !w->m.dec_err && w->m.dw && w->m.dh &&
  4234. w->m.px_len <= 8u * 1024u * 1024u) {
  4235. unsigned char *px = (unsigned char *)malloc(w->m.px_len);
  4236. int pr = -1;
  4237. if (px)
  4238. pr = u_syscall3(SYS_READ_FILE, (int)w->px, (int)px,
  4239. (int)w->m.px_len);
  4240. if (pr == (int)w->m.px_len) {
  4241. if (preload_store_helper(w->node, w->bg, px,
  4242. w->m.px_len, w->m.dw,
  4243. w->m.dh, (int)w->m.alpha,
  4244. w->m.nw, w->m.nh,
  4245. w->url) == 0) {
  4246. rv = (int)w->m.len;
  4247. img_last_dec_ms = w->m.dec_ms;
  4248. img_last_scale_ms = 0;
  4249. used_px = 1;
  4250. } else {
  4251. px = 0; /* the helper freed it */
  4252. }
  4253. }
  4254. if (px && !(pr == (int)w->m.px_len))
  4255. free(px);
  4256. }
  4257. io_ms = u_ticks_ms() - t0;
  4258. if (rv < 0) {
  4259. t0 = u_ticks_ms();
  4260. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  4261. image_comp_buf, BR_IMG_FILE_MAX,
  4262. &tr, err, sizeof(err));
  4263. io_ms += u_ticks_ms() - t0;
  4264. before = image_count;
  4265. if (rv >= 0)
  4266. preload_decode(w->node, w->bg, image_file_buf,
  4267. (unsigned int)rv, w->url);
  4268. else
  4269. preload_job_error(w);
  4270. }
  4271. img_stat_n++;
  4272. img_stat_net += w->m.total_ms;
  4273. img_stat_open += w->m.open_ms;
  4274. img_stat_first += w->m.first_ms;
  4275. img_stat_io += io_ms;
  4276. img_stat_bytes += rv > 0 ? (unsigned int)rv : 0;
  4277. img_stat_dec += w->m.dec_ms;
  4278. if (rv >= 0 && !used_px) {
  4279. img_stat_dec += img_last_dec_ms;
  4280. img_stat_scale += img_last_scale_ms;
  4281. }
  4282. if (img_stat_log_len + 160 < sizeof(img_stat_log)) {
  4283. unsigned int n = img_stat_log_len;
  4284. char u[48];
  4285. s_copy(u, w->url, sizeof(u));
  4286. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4287. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4288. s_append_dec(img_stat_log, &n,
  4289. rv > 0 ? (unsigned int)rv : 0,
  4290. sizeof(img_stat_log));
  4291. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4292. s_append_dec(img_stat_log, &n, w->m.open_ms,
  4293. sizeof(img_stat_log));
  4294. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4295. s_append_dec(img_stat_log, &n, w->m.first_ms,
  4296. sizeof(img_stat_log));
  4297. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4298. s_append_dec(img_stat_log, &n, w->m.total_ms,
  4299. sizeof(img_stat_log));
  4300. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4301. s_append_dec(img_stat_log, &n, io_ms, sizeof(img_stat_log));
  4302. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4303. s_append_dec(img_stat_log, &n,
  4304. rv >= 0 ? img_last_dec_ms : 0,
  4305. sizeof(img_stat_log));
  4306. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4307. s_append_dec(img_stat_log, &n,
  4308. rv >= 0 ? img_last_scale_ms : 0,
  4309. sizeof(img_stat_log));
  4310. if (image_count > before) {
  4311. struct br_image *bi = &images[image_count - 1];
  4312. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4313. s_append_dec(img_stat_log, &n,
  4314. (unsigned int)bi->native_w,
  4315. sizeof(img_stat_log));
  4316. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4317. s_append_dec(img_stat_log, &n,
  4318. (unsigned int)bi->native_h,
  4319. sizeof(img_stat_log));
  4320. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4321. s_append_dec(img_stat_log, &n, bi->img.w,
  4322. sizeof(img_stat_log));
  4323. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4324. s_append_dec(img_stat_log, &n, bi->img.h,
  4325. sizeof(img_stat_log));
  4326. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4327. s_append_dec(img_stat_log, &n,
  4328. bi->img.alpha ? 1u : 0u,
  4329. sizeof(img_stat_log));
  4330. }
  4331. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4332. img_stat_log_len = n;
  4333. }
  4334. fetch_worker_release(w);
  4335. return 1;
  4336. }
  4337. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  4338. * the number of jobs started. */
  4339. static int preload_fill_jobs(void)
  4340. {
  4341. int started = 0;
  4342. char err[64];
  4343. while (preload_active && preload_node < doc.nnode) {
  4344. unsigned int i = preload_node;
  4345. struct br_node *nd = &doc.nodes[i];
  4346. const char *src;
  4347. char url[BR_URL_MAX];
  4348. struct fetch_worker *w;
  4349. if (preload_active_jobs() >= preload_max_jobs)
  4350. break;
  4351. if (nd->type != BR_NODE_ELEM) {
  4352. preload_node++;
  4353. continue;
  4354. }
  4355. if (nd->tag != BR_TAG_IMG) {
  4356. if (nd->bg_img_index == -1) {
  4357. struct br_style bs;
  4358. style_for_node(i, &bs);
  4359. if (bs.display != BR_DISPLAY_NONE &&
  4360. !bs.vis_hidden && bs.bg_image) {
  4361. const char *bsrc =
  4362. br_bg_image_url(bs.bg_image - 1);
  4363. /* Lazy like <img>: a background box
  4364. * below the viewport (or not laid
  4365. * out yet) waits for the next scan. */
  4366. if (bsrc[0] &&
  4367. (!layout_boxes[i].valid ||
  4368. block_top[i] >
  4369. (unsigned int)(page_scroll.offset +
  4370. page_rect.h + 160))) {
  4371. preload_pending = 1;
  4372. preload_node++;
  4373. continue;
  4374. }
  4375. if (bsrc[0] &&
  4376. !starts_with(bsrc, "data:") &&
  4377. resolve_link(page_url, bsrc, url,
  4378. sizeof(url)) == 0) {
  4379. if (image_count +
  4380. preload_active_jobs() >=
  4381. BR_MAX_IMAGES) {
  4382. preload_node = doc.nnode;
  4383. break;
  4384. }
  4385. if (url[0] == '/') {
  4386. unsigned char *data = 0;
  4387. unsigned int len = 0;
  4388. unsigned int t0;
  4389. int before;
  4390. preload_node = i + 1;
  4391. before = image_count;
  4392. t0 = u_ticks_ms();
  4393. if (fetch_image(url,
  4394. BR_IMG_FILE_MAX,
  4395. &data, &len,
  4396. err,
  4397. sizeof(err)) == 0) {
  4398. preload_decode(i, 1, data, len, 0);
  4399. img_stat_local(before, len,
  4400. u_ticks_ms() - t0);
  4401. } else {
  4402. nd->bg_img_index = -2;
  4403. }
  4404. continue;
  4405. }
  4406. w = fetch_worker_alloc();
  4407. if (!w)
  4408. return started;
  4409. preload_node = i + 1;
  4410. if (fetch_worker_submit(w, url,
  4411. BR_IMG_FILE_MAX,
  4412. 0, 0, i, 1,
  4413. err,
  4414. sizeof(err)) != 0) {
  4415. nd->bg_img_index = -2;
  4416. fetch_worker_release(w);
  4417. continue;
  4418. }
  4419. w->image_job = 1;
  4420. w->deadline = u_ticks_ms() +
  4421. BR_IMG_JOB_TIMEOUT_MS;
  4422. /* in flight: rescans skip it */
  4423. nd->bg_img_index = -3;
  4424. started++;
  4425. continue;
  4426. }
  4427. }
  4428. nd->bg_img_index = -2;
  4429. }
  4430. preload_node++;
  4431. continue;
  4432. }
  4433. if (nd->img_index != -1) {
  4434. preload_node++;
  4435. continue;
  4436. }
  4437. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  4438. preload_node++;
  4439. continue;
  4440. }
  4441. src = br_src(&doc, i);
  4442. if (!src[0] || starts_with(src, "data:")) {
  4443. preload_node++;
  4444. continue;
  4445. }
  4446. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  4447. preload_node++;
  4448. continue;
  4449. }
  4450. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  4451. preload_node = doc.nnode;
  4452. break;
  4453. }
  4454. /* Do not stop at the first below-fold image: DOM order is
  4455. * not visual order, and a footer/ad image early in the DOM
  4456. * used to hide every later article image from the loader. */
  4457. if (img_top[i] >
  4458. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  4459. preload_pending = 1;
  4460. preload_node++;
  4461. continue;
  4462. }
  4463. {
  4464. unsigned int uh = script_cache_hash(url) | 1u;
  4465. int k;
  4466. for (k = 0; k < image_count; k++)
  4467. if (images[k].state == 1 &&
  4468. images[k].url_hash == uh)
  4469. break;
  4470. if (k < image_count) {
  4471. nd->img_index = (short)k;
  4472. layout_valid = 0;
  4473. preload_node = i + 1;
  4474. image_repaint();
  4475. continue;
  4476. }
  4477. }
  4478. if (url[0] == '/') {
  4479. unsigned char *data = 0;
  4480. unsigned int len = 0;
  4481. unsigned int t0;
  4482. int before;
  4483. preload_node = i + 1;
  4484. before = image_count;
  4485. t0 = u_ticks_ms();
  4486. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  4487. err, sizeof(err)) == 0) {
  4488. preload_decode(i, 0, data, len, url);
  4489. img_stat_local(before, len, u_ticks_ms() - t0);
  4490. } else {
  4491. nd->img_index = -2;
  4492. }
  4493. continue;
  4494. }
  4495. w = fetch_worker_alloc();
  4496. if (!w)
  4497. return started;
  4498. preload_node = i + 1;
  4499. {
  4500. char msg[64];
  4501. unsigned int n = 0;
  4502. s_append(msg, &n, "Loading images ", sizeof(msg));
  4503. s_append_dec(msg, &n,
  4504. (unsigned int)preload_loaded + 1,
  4505. sizeof(msg));
  4506. s_append(msg, &n, "...", sizeof(msg));
  4507. set_status_quiet(msg);
  4508. image_repaint();
  4509. }
  4510. {
  4511. int fit_w = 0, fit_h = 0;
  4512. image_fit_size(i, &fit_w, &fit_h);
  4513. if (!fit_w)
  4514. fit_w = BR_IMG_LAYOUT_W;
  4515. if (fetch_worker_submit_image(w, url, BR_IMG_FILE_MAX,
  4516. i, 0,
  4517. (unsigned int)fit_w,
  4518. (unsigned int)fit_h,
  4519. err, sizeof(err)) != 0) {
  4520. nd->img_index = -2;
  4521. fetch_worker_release(w);
  4522. continue;
  4523. }
  4524. }
  4525. w->image_job = 1;
  4526. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4527. nd->img_index = -3; /* in flight: rescans skip it */
  4528. started++;
  4529. }
  4530. return started;
  4531. }
  4532. /* Report where the image batch spent its time: status bar for the headline,
  4533. * /share/IMGSTAT for the per-image breakdown (cat it from a terminal). */
  4534. static void img_stats_report(void)
  4535. {
  4536. char msg[80];
  4537. static char out[BR_IMG_STAT_LOG + 512];
  4538. unsigned int n = 0, o = 0;
  4539. if (!img_stat_n)
  4540. return;
  4541. img_stat_wall = img_stat_start ?
  4542. u_ticks_ms() - img_stat_start : 1;
  4543. if (!img_stat_wall)
  4544. img_stat_wall = 1;
  4545. /* Compact on-screen form; /share/IMGSTAT has the full breakdown. */
  4546. s_append(msg, &n, "img ", sizeof(msg));
  4547. s_append_dec(msg, &n, (unsigned int)img_stat_n, sizeof(msg));
  4548. s_append(msg, &n, " ", sizeof(msg));
  4549. s_append_dec(msg, &n, img_stat_wall, sizeof(msg));
  4550. s_append(msg, &n, "ms net ", sizeof(msg));
  4551. s_append_dec(msg, &n, img_stat_net, sizeof(msg));
  4552. s_append(msg, &n, " dec ", sizeof(msg));
  4553. s_append_dec(msg, &n, img_stat_dec, sizeof(msg));
  4554. s_append(msg, &n, " sc ", sizeof(msg));
  4555. s_append_dec(msg, &n, img_stat_scale, sizeof(msg));
  4556. s_append(msg, &n, " paint ", sizeof(msg));
  4557. s_append_dec(msg, &n, img_stat_paint, sizeof(msg));
  4558. /* Keep the page's phase breakdown and append the image summary when
  4559. * it fits; never hide a JS error or a truncation notice. */
  4560. if (!post_status_error && !contains_ci(post_status_text, "truncated")) {
  4561. unsigned int plen = s_len(post_status_text);
  4562. if (!plen) {
  4563. s_copy(post_status_text, msg, sizeof(post_status_text));
  4564. } else if (plen + s_len(msg) + 4 < sizeof(post_status_text)) {
  4565. unsigned int pn = plen;
  4566. s_append(post_status_text, &pn, " | ",
  4567. sizeof(post_status_text));
  4568. s_append(post_status_text, &pn, msg,
  4569. sizeof(post_status_text));
  4570. } else {
  4571. s_copy(post_status_text, msg, sizeof(post_status_text));
  4572. }
  4573. post_status_ttl = 12000;
  4574. }
  4575. s_append(out, &o, "browser image stats\n", sizeof(out));
  4576. s_append(out, &o, "n=", sizeof(out));
  4577. s_append_dec(out, &o, (unsigned int)img_stat_n, sizeof(out));
  4578. s_append(out, &o, " wall=", sizeof(out));
  4579. s_append_dec(out, &o, img_stat_wall, sizeof(out));
  4580. s_append(out, &o, " net=", sizeof(out));
  4581. s_append_dec(out, &o, img_stat_net, sizeof(out));
  4582. s_append(out, &o, " open=", sizeof(out));
  4583. s_append_dec(out, &o, img_stat_open, sizeof(out));
  4584. s_append(out, &o, " first=", sizeof(out));
  4585. s_append_dec(out, &o, img_stat_first, sizeof(out));
  4586. s_append(out, &o, " io=", sizeof(out));
  4587. s_append_dec(out, &o, img_stat_io, sizeof(out));
  4588. s_append(out, &o, " dec=", sizeof(out));
  4589. s_append_dec(out, &o, img_stat_dec, sizeof(out));
  4590. s_append(out, &o, " scale=", sizeof(out));
  4591. s_append_dec(out, &o, img_stat_scale, sizeof(out));
  4592. s_append(out, &o, " paint=", sizeof(out));
  4593. s_append_dec(out, &o, img_stat_paint, sizeof(out));
  4594. s_append(out, &o, " reflow=", sizeof(out));
  4595. s_append_dec(out, &o, img_stat_reflow, sizeof(out));
  4596. s_append(out, &o, " bytes=", sizeof(out));
  4597. s_append_dec(out, &o, img_stat_bytes, sizeof(out));
  4598. s_append(out, &o, "\nurl bytes open first total io dec scale native bitmap\n",
  4599. sizeof(out));
  4600. s_append(out, &o, img_stat_log, sizeof(out));
  4601. u_syscall3(SYS_WRITE_FILE, (int)"/share/IMGSTAT", (int)out,
  4602. (int)s_len(out));
  4603. }
  4604. static void preload_step(void)
  4605. {
  4606. int i;
  4607. unsigned int t0;
  4608. if (!preload_active)
  4609. return;
  4610. if (cancel_fetch || pending_action) {
  4611. preload_active = 0;
  4612. preload_pending = 0;
  4613. fetch_workers_cancel_busy();
  4614. return;
  4615. }
  4616. preload_fill_jobs();
  4617. /* Decode completed images in a short batch instead of one per pass.
  4618. * A pass used to decode one image and then sleep 10 ms, so a page of
  4619. * small icons trickled in at the decode rate. The budget keeps a
  4620. * single huge JPEG from monopolising the UI while small images
  4621. * finish together. */
  4622. t0 = u_ticks_ms();
  4623. for (i = 0; i < FETCH_WORKERS; i++) {
  4624. if (!fetch_workers[i].busy)
  4625. continue;
  4626. if (preload_finish_worker(&fetch_workers[i]) &&
  4627. u_ticks_ms() - t0 >= BR_IMG_DECODE_BUDGET_MS)
  4628. break;
  4629. }
  4630. if (preload_active && preload_node >= doc.nnode &&
  4631. preload_active_jobs() == 0) {
  4632. preload_active = 0;
  4633. if (preload_pending)
  4634. preload_scroll = page_scroll.offset;
  4635. else
  4636. preload_pending = 0;
  4637. /* Keep the now idle helpers and their connections; a later
  4638. * navigation reuses them. They exit after ten idle seconds,
  4639. * and losing window focus stops them at once. */
  4640. if (img_repaint_pending) {
  4641. img_repaint_pending = 0;
  4642. ngui_invalidate(&ui);
  4643. }
  4644. img_stats_report();
  4645. set_status(post_status_text, post_status_error, post_status_ttl);
  4646. ngui_invalidate(&ui);
  4647. }
  4648. }
  4649. /* Set by navigate() when it turned a typed bare host into https://; the next
  4650. * load_page() consumes it and may retry over http. */
  4651. static int nav_https_upgraded;
  4652. /* Errors that mean "https is not served here" rather than "the site is
  4653. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  4654. static int https_fallback_error(int e)
  4655. {
  4656. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  4657. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  4658. e == UHTTP_ERR_RESET;
  4659. }
  4660. static void history_push(const char *url)
  4661. {
  4662. if (!url || !url[0])
  4663. return;
  4664. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  4665. s_eq(history[hist_pos], url))
  4666. return;
  4667. if (hist_len > 0 && hist_pos + 1 < hist_len)
  4668. hist_len = hist_pos + 1;
  4669. if (hist_len < BR_HISTORY) {
  4670. s_copy(history[hist_len], url, BR_URL_MAX);
  4671. hist_pos = hist_len;
  4672. hist_len++;
  4673. } else {
  4674. int i;
  4675. for (i = 1; i < BR_HISTORY; i++)
  4676. s_copy(history[i - 1], history[i], BR_URL_MAX);
  4677. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  4678. hist_pos = BR_HISTORY - 1;
  4679. }
  4680. }
  4681. static void load_page(const char *url, int local, int push)
  4682. {
  4683. unsigned char *body = 0;
  4684. unsigned int len = 0;
  4685. int truncated = 0;
  4686. struct img_info image_info;
  4687. char ctype[64];
  4688. char final[BR_URL_MAX];
  4689. char err[80];
  4690. const char *detail = 0;
  4691. const char *post = pending_post_is ? pending_post : 0;
  4692. unsigned int post_len = pending_post_len;
  4693. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  4694. /* Phase timings for the status line: where a slow load spends it. */
  4695. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  4696. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  4697. int upgraded = nav_https_upgraded;
  4698. int retried = 0;
  4699. int rv;
  4700. nav_https_upgraded = 0;
  4701. final[0] = '\0';
  4702. pending_post_len = 0;
  4703. pending_post_is = 0;
  4704. cancel_fetch = 0;
  4705. preload_active = 0;
  4706. preload_pending = 0;
  4707. fetch_workers_prepare_nav(url);
  4708. js_browser_stop();
  4709. js_last_status[0] = '\0';
  4710. js_last_error = 0;
  4711. heap_clear();
  4712. image_reset();
  4713. form_reset_state();
  4714. layout_valid = 0;
  4715. page_scroll.offset = 0;
  4716. page_scroll.dragging = 0;
  4717. page_title[0] = '\0';
  4718. page_loading = 1;
  4719. page_is_local = local;
  4720. s_copy(page_url, url, sizeof(page_url));
  4721. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4722. url_in.len = s_len(url_in.text);
  4723. url_in.cursor = url_in.len;
  4724. url_in.scroll = 0;
  4725. ngui_set_focus(&ui, 0);
  4726. if (final[0])
  4727. final[0] = '\0';
  4728. if (push)
  4729. history_push(url);
  4730. set_status("Loading...", 0, 0);
  4731. ngui_invalidate(&ui);
  4732. /* heap_clear() detaches the fonts, so attach them again before the
  4733. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  4734. if (heap_start() != 0) {
  4735. show_error("Out of memory", "Cannot allocate the page buffer");
  4736. return;
  4737. }
  4738. br_parse_plain(&doc, "", 0); /* blank while loading */
  4739. ngui_font_attach(&ui);
  4740. redraw_now();
  4741. browser_rules_alloc();
  4742. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  4743. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  4744. &truncated, post, post_len);
  4745. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  4746. fetch_last_error == UHTTP_ERR_DNS) {
  4747. /* A busy previous page can leave the receiver ring full just
  4748. * long enough to lose a DNS reply. Tear the old helpers down
  4749. * and try once more before giving up. */
  4750. retried = 1;
  4751. fetch_workers_stop_all();
  4752. u_sleep_ms(500);
  4753. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  4754. sizeof(ctype), final, sizeof(final), err,
  4755. sizeof(err), &truncated, post, post_len);
  4756. }
  4757. if (rv == FETCH_ABORT)
  4758. return;
  4759. t_fetch = u_ticks_ms() - t_start;
  4760. /* Capture the page timing before CSS/script/image fetches overwrite the
  4761. * shared fetch_meta block. */
  4762. if (rv == 0 && !local) {
  4763. page_open_ms = fetch_meta.open_ms;
  4764. page_first_ms = fetch_meta.first_ms;
  4765. page_total_ms = fetch_meta.total_ms;
  4766. }
  4767. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  4768. https_fallback_error(fetch_last_error)) {
  4769. char http_url[BR_URL_MAX];
  4770. unsigned int n = 0;
  4771. s_append(http_url, &n, "http://", sizeof(http_url));
  4772. s_append(http_url, &n, url + 8, sizeof(http_url));
  4773. /* Replace the https entry instead of adding a second one. */
  4774. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  4775. s_eq(history[hist_pos], url))
  4776. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  4777. load_page(http_url, 0, 0);
  4778. return;
  4779. }
  4780. if (rv != 0) {
  4781. detail = err;
  4782. show_error("Cannot load this page", detail);
  4783. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4784. url_in.len = s_len(url_in.text);
  4785. url_in.cursor = url_in.len;
  4786. url_in.scroll = 0;
  4787. return;
  4788. }
  4789. if (!local)
  4790. origin_cache_learn(url, final[0] ? final : url);
  4791. page_is_local = local;
  4792. if (final[0]) {
  4793. s_copy(page_url, final, sizeof(page_url));
  4794. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4795. url_in.len = s_len(url_in.text);
  4796. url_in.cursor = url_in.len;
  4797. url_in.scroll = 0;
  4798. }
  4799. if (contains_ci(ctype, "text/plain")) {
  4800. br_parse_plain(&doc, (const char *)body, len);
  4801. } else if (contains_ci(ctype, "image/") ||
  4802. (!contains_ci(ctype, "text/html") &&
  4803. img_sniff(body, len, &image_info) == 0)) {
  4804. unsigned int node = br_parse_image_doc(&doc, page_url);
  4805. if (node)
  4806. decode_direct_image(body, len, node);
  4807. s_copy(page_title, "Image", sizeof(page_title));
  4808. } else {
  4809. br_set_viewport(ui.w);
  4810. t_mark = u_ticks_ms();
  4811. br_parse(&doc, (const char *)body, len);
  4812. t_parse = u_ticks_ms() - t_mark;
  4813. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  4814. sizeof(page_title));
  4815. t_mark = u_ticks_ms();
  4816. if (load_stylesheets() == FETCH_ABORT)
  4817. return;
  4818. t_css = u_ticks_ms() - t_mark;
  4819. if (pending_action)
  4820. return;
  4821. }
  4822. preload_begin();
  4823. page_loading = 0;
  4824. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4825. url_in.len = s_len(url_in.text);
  4826. url_in.cursor = url_in.len;
  4827. url_in.scroll = 0;
  4828. ngui_set_focus(&ui, 0);
  4829. /* Paint the parsed page before fetching/running scripts. A slow
  4830. * remote <script src> then does not hide the page behind the loading
  4831. * screen; the fetch helper pumps this UI while it waits. */
  4832. set_status("Loading scripts...", 0, 0);
  4833. t_mark = u_ticks_ms();
  4834. redraw_now();
  4835. t_paint = u_ticks_ms() - t_mark;
  4836. /* Start one image download before the scripts. The other workers
  4837. * fetch the external script bodies in parallel, and the remaining
  4838. * images start as soon as the script phase ends. */
  4839. preload_max_jobs = 1;
  4840. preload_fill_jobs();
  4841. preload_wait = 0;
  4842. t_mark = u_ticks_ms();
  4843. run_page_scripts();
  4844. t_js = u_ticks_ms() - t_mark;
  4845. preload_max_jobs = FETCH_WORKERS;
  4846. if (pending_action)
  4847. return;
  4848. post_status_text[0] = '\0';
  4849. post_status_error = 0;
  4850. post_status_ttl = 0;
  4851. if (js_last_status[0]) {
  4852. s_copy(post_status_text, js_last_status,
  4853. sizeof(post_status_text));
  4854. post_status_error = js_last_error;
  4855. post_status_ttl = 8000;
  4856. } else if (truncated) {
  4857. s_copy(post_status_text, "Page truncated at the buffer limit",
  4858. sizeof(post_status_text));
  4859. post_status_ttl = 6000;
  4860. } else if (doc.truncated) {
  4861. s_copy(post_status_text, "Page truncated by the parser",
  4862. sizeof(post_status_text));
  4863. post_status_ttl = 6000;
  4864. } else if (page_total_ms) {
  4865. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  4866. * paint 220, js 1750" -- the phases of this load. */
  4867. unsigned int n = 0;
  4868. static const char *const names[] = {
  4869. ", parse ", ", css ", ", paint ", ", js "
  4870. };
  4871. unsigned int vals[4];
  4872. int k;
  4873. vals[0] = t_parse;
  4874. vals[1] = t_css;
  4875. vals[2] = t_paint;
  4876. vals[3] = t_js;
  4877. (void)page_first_ms;
  4878. if (starts_with(page_url, "https://"))
  4879. s_append(post_status_text, &n,
  4880. "HTTPS (not verified), ",
  4881. sizeof(post_status_text));
  4882. s_append(post_status_text, &n, "Loaded in ",
  4883. sizeof(post_status_text));
  4884. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  4885. sizeof(post_status_text));
  4886. s_append(post_status_text, &n, " ms: page ",
  4887. sizeof(post_status_text));
  4888. s_append_dec(post_status_text, &n, t_fetch,
  4889. sizeof(post_status_text));
  4890. s_append(post_status_text, &n, " (headers ",
  4891. sizeof(post_status_text));
  4892. s_append_dec(post_status_text, &n, page_open_ms,
  4893. sizeof(post_status_text));
  4894. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  4895. for (k = 0; k < 4; k++) {
  4896. s_append(post_status_text, &n, names[k],
  4897. sizeof(post_status_text));
  4898. s_append_dec(post_status_text, &n, vals[k],
  4899. sizeof(post_status_text));
  4900. }
  4901. post_status_ttl = 12000;
  4902. } else if (starts_with(page_url, "https://")) {
  4903. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  4904. sizeof(post_status_text));
  4905. post_status_ttl = 6000;
  4906. }
  4907. set_status(post_status_text, post_status_error, post_status_ttl);
  4908. ngui_invalidate(&ui);
  4909. }
  4910. static void load_home(int push)
  4911. {
  4912. pending_post_len = 0;
  4913. pending_post_is = 0;
  4914. cancel_fetch = 0;
  4915. preload_active = 0;
  4916. preload_pending = 0;
  4917. js_browser_stop();
  4918. js_last_status[0] = '\0';
  4919. js_last_error = 0;
  4920. heap_clear();
  4921. image_reset();
  4922. form_reset_state();
  4923. layout_valid = 0;
  4924. page_scroll.offset = 0;
  4925. page_scroll.dragging = 0;
  4926. page_loading = 1;
  4927. page_is_local = 0;
  4928. s_copy(page_url, "about:home", sizeof(page_url));
  4929. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4930. url_in.len = s_len(url_in.text);
  4931. url_in.cursor = url_in.len;
  4932. url_in.scroll = 0;
  4933. ngui_set_focus(&ui, 0);
  4934. if (push)
  4935. history_push(page_url);
  4936. ngui_invalidate(&ui);
  4937. /* See load_page(): reattach the fonts before the first redraw. */
  4938. if (heap_start() != 0) {
  4939. show_error("Out of memory", "Cannot allocate the browser heap");
  4940. return;
  4941. }
  4942. br_parse_plain(&doc, "", 0);
  4943. ngui_font_attach(&ui);
  4944. redraw_now();
  4945. browser_rules_alloc();
  4946. {
  4947. static const char home[] =
  4948. "<html><head><title>NebOS Browser</title><style>"
  4949. "body { margin: 10px; color: #e4e6f0; }"
  4950. "h1 { color: #7fb0ff; }"
  4951. ".box { background-color: #262b3a; margin: 12px; "
  4952. "padding: 10px; }"
  4953. "a { color: #7fb0ff; }"
  4954. "pre { background-color: #32384a; }"
  4955. "</style></head><body>"
  4956. "<h1>NebOS Browser</h1>"
  4957. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  4958. "shared HTTP client and the image library.</p>"
  4959. "<div class=\"box\"><b>Try:</b>"
  4960. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  4961. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  4962. "<li><a href=\"/floppy1/JS.HTM\">/"
  4963. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  4964. "<li><a href=\"http://10.0.2.2:8000/\">"
  4965. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  4966. "<li><a href=\"https://example.com/\">"
  4967. "https://example.com/</a> (TLS, not verified)</li>"
  4968. "</ul></div>"
  4969. "<p>Type a URL in the bar above. Esc closes the "
  4970. "window, Ctrl+L focuses the address bar.</p>"
  4971. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  4972. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  4973. "</body></html>";
  4974. br_set_viewport(ui.w);
  4975. br_parse(&doc, home, sizeof(home) - 1);
  4976. br_parse_inline_css(&doc);
  4977. br_reset_styles(&doc);
  4978. s_copy(page_title, doc.title, sizeof(page_title));
  4979. }
  4980. post_status_text[0] = '\0';
  4981. post_status_error = 0;
  4982. post_status_ttl = 0;
  4983. page_loading = 0;
  4984. set_status("", 0, 0);
  4985. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4986. url_in.len = s_len(url_in.text);
  4987. url_in.cursor = url_in.len;
  4988. url_in.scroll = 0;
  4989. ngui_set_focus(&ui, 0);
  4990. ngui_invalidate(&ui);
  4991. }
  4992. /* Extensions the browser opens from the local filesystem. A dotted input
  4993. * with one of these still resolves relative to the cwd. */
  4994. static int local_file_ext(const char *s)
  4995. {
  4996. static const char *const exts[] = {
  4997. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  4998. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  4999. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  5000. "cfg", "conf", 0
  5001. };
  5002. unsigned int i = 0, start = 0, len = 0, e;
  5003. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  5004. s[i] != '#') {
  5005. if (s[i] == '.') {
  5006. start = i + 1;
  5007. len = 0;
  5008. } else if (start) {
  5009. len++;
  5010. }
  5011. i++;
  5012. }
  5013. if (!len)
  5014. return 0;
  5015. for (e = 0; exts[e]; e++) {
  5016. const char *x = exts[e];
  5017. unsigned int xn = s_len(x), k;
  5018. if (xn != len)
  5019. continue;
  5020. for (k = 0; k < len; k++) {
  5021. char a = s[start + k];
  5022. if (a >= 'A' && a <= 'Z')
  5023. a = (char)(a - 'A' + 'a');
  5024. if (a != x[k])
  5025. break;
  5026. }
  5027. if (k == len)
  5028. return 1;
  5029. }
  5030. return 0;
  5031. }
  5032. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  5033. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  5034. * Enter to the first network request. */
  5035. static int looks_like_host(const char *s)
  5036. {
  5037. unsigned int i = 0;
  5038. int dot = 0;
  5039. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  5040. s[i] != ':') {
  5041. char c = s[i];
  5042. if (c == '.') {
  5043. dot = 1;
  5044. } else if (!((c >= 'a' && c <= 'z') ||
  5045. (c >= 'A' && c <= 'Z') ||
  5046. (c >= '0' && c <= '9') ||
  5047. c == '-' || c == '_')) {
  5048. return 0;
  5049. }
  5050. i++;
  5051. }
  5052. return dot && i > 0 && !local_file_ext(s);
  5053. }
  5054. static void load_remote(const char *url, int push)
  5055. {
  5056. char canon[BR_URL_MAX];
  5057. s_copy(canon, url, sizeof(canon));
  5058. origin_cache_apply(canon, sizeof(canon));
  5059. load_page(canon, 0, push);
  5060. }
  5061. static void navigate(const char *input, int push)
  5062. {
  5063. char target[BR_URL_MAX];
  5064. char *t;
  5065. if (!input)
  5066. return;
  5067. s_copy(target, input, sizeof(target));
  5068. t = trim(target);
  5069. if (!t[0])
  5070. return;
  5071. if (s_eq(t, "about:home")) {
  5072. load_home(push);
  5073. return;
  5074. }
  5075. if (starts_with(t, "file://")) {
  5076. make_abs_local(t + 7, target, sizeof(target));
  5077. load_page(target, 1, push);
  5078. return;
  5079. }
  5080. if (is_http(t)) {
  5081. load_remote(t, push);
  5082. return;
  5083. }
  5084. if (t[0] == '/') {
  5085. make_abs_local(t, target, sizeof(target));
  5086. load_page(target, 1, push);
  5087. return;
  5088. }
  5089. if (!looks_like_host(t)) {
  5090. struct sys_stat st;
  5091. if (u_stat(t, &st) == 0 && !st.is_dir) {
  5092. make_abs_local(t, target, sizeof(target));
  5093. load_page(target, 1, push);
  5094. return;
  5095. }
  5096. }
  5097. {
  5098. /* A typed bare host tries https first: nearly every site
  5099. * redirects http -> https anyway, and that hop costs a whole
  5100. * extra connection. load_page() falls back to http when the
  5101. * https connection itself fails. */
  5102. char with_scheme[BR_URL_MAX];
  5103. unsigned int n = 0;
  5104. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  5105. s_append(with_scheme, &n, t, sizeof(with_scheme));
  5106. nav_https_upgraded = 1;
  5107. load_remote(with_scheme, push);
  5108. }
  5109. }
  5110. /* ---- layout ---- */
  5111. static struct ufont_face *style_face(const struct br_style *st)
  5112. {
  5113. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  5114. return font_faces[st->font_face - 1];
  5115. return 0;
  5116. }
  5117. static struct ufont_face *run_face(const struct lay_run *r)
  5118. {
  5119. if (r->font_face && r->font_face <= BR_MAX_FACES)
  5120. return font_faces[r->font_face - 1];
  5121. return 0;
  5122. }
  5123. static unsigned int face_text_width(struct ngui *gui,
  5124. const struct br_style *st,
  5125. const char *s, unsigned int n)
  5126. {
  5127. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  5128. st->bold, st->italic, st->mono);
  5129. }
  5130. static int face_line_height(struct ngui *gui, const struct br_style *st)
  5131. {
  5132. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  5133. st->mono);
  5134. }
  5135. static unsigned int run_text_width(struct ngui *gui,
  5136. const struct lay_run *r,
  5137. const char *s, unsigned int n)
  5138. {
  5139. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  5140. r->bold, r->italic, r->mono);
  5141. }
  5142. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  5143. {
  5144. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  5145. r->mono);
  5146. }
  5147. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  5148. {
  5149. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  5150. }
  5151. static struct br_style base_style(void)
  5152. {
  5153. struct br_style s = { 0 };
  5154. s.color = ui.theme.text;
  5155. s.bg = ui.theme.bg;
  5156. s.has_bg = 0;
  5157. for (int i = 0; i < 4; i++) {
  5158. s.border_c[i] = 0;
  5159. s.border_w[i] = 0;
  5160. s.border_s[i] = BR_BORDER_SOLID;
  5161. }
  5162. s.font_px = 16;
  5163. s.bold = 0;
  5164. s.italic = 0;
  5165. s.mono = 0;
  5166. s.underline = 0;
  5167. s.strike = 0;
  5168. s.overline = 0;
  5169. s.align = BR_ALIGN_LEFT;
  5170. s.display = BR_DISPLAY_BLOCK;
  5171. s.no_bullet = 0;
  5172. s.list_style = BR_LIST_AUTO;
  5173. s.uppercase = 0;
  5174. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  5175. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  5176. s.width = s.max_width = s.min_width = 0;
  5177. s.height = s.min_height = s.max_height = 0;
  5178. s.box_sizing = 0;
  5179. s.ml_auto = s.mr_auto = 0;
  5180. s.line_h_pct = 0;
  5181. s.line_h_px = 0;
  5182. s.mt = s.mb = s.ml = s.mr = 0;
  5183. s.pt = s.pb = s.pl = s.pr = 0;
  5184. return s;
  5185. }
  5186. /* Resolve a margin/padding raw value. Percentages use the containing
  5187. * block width for all four sides, as CSS specifies. */
  5188. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  5189. {
  5190. if (unit == 1)
  5191. return base * v / 10000;
  5192. if (unit == 2)
  5193. return st->font_px * v / 100;
  5194. if (unit == 3)
  5195. return (int)br_root_font_px() * v / 100;
  5196. if (unit == 4)
  5197. return 0;
  5198. return v;
  5199. }
  5200. static int mp_px(const struct br_style *st, int side, int base)
  5201. {
  5202. int raw;
  5203. switch (side) {
  5204. case 0: raw = st->mt; break;
  5205. case 1: raw = st->mr; break;
  5206. case 2: raw = st->mb; break;
  5207. case 3: raw = st->ml; break;
  5208. case 4: raw = st->pt; break;
  5209. case 5: raw = st->pr; break;
  5210. case 6: raw = st->pb; break;
  5211. default: raw = st->pl; break;
  5212. }
  5213. if (st->mp_unit[side] == 5)
  5214. return base * raw / 100 + st->mp_calc_px[side];
  5215. return css_mp_px(st, raw, st->mp_unit[side], base);
  5216. }
  5217. static int style_width_px(const struct br_style *st, int base)
  5218. {
  5219. if (st->width_kind == 1)
  5220. return st->width;
  5221. if (st->width_kind == 2)
  5222. return base * (int)st->width / 100;
  5223. if (st->width_kind == 3)
  5224. return base * st->width_calc_pct / 100 + st->width_calc_px;
  5225. return 0;
  5226. }
  5227. static int style_height_px(const struct br_style *st, int base)
  5228. {
  5229. if (st->height_kind == 1)
  5230. return st->height;
  5231. if (st->height_kind == 2)
  5232. return base * (int)st->height / 100;
  5233. if (st->height_kind == 3)
  5234. return base * st->height_calc_pct / 100 + st->height_calc_px;
  5235. return 0;
  5236. }
  5237. static int css_size(unsigned char kind, int val, int base)
  5238. {
  5239. if (kind == 1)
  5240. return val;
  5241. if (kind == 2)
  5242. return base * val / 100;
  5243. return -1;
  5244. }
  5245. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  5246. int thick, int horizontal, unsigned short color,
  5247. unsigned char style)
  5248. {
  5249. int pos;
  5250. if (len <= 0 || thick <= 0)
  5251. return;
  5252. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  5253. if (horizontal)
  5254. ngui_fill_rect(ui, (struct ngui_rect){
  5255. x, y, len, thick}, color);
  5256. else
  5257. ngui_fill_rect(ui, (struct ngui_rect){
  5258. x, y, thick, len}, color);
  5259. return;
  5260. }
  5261. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  5262. int seg = len - pos;
  5263. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  5264. seg = style == BR_BORDER_DASHED ? 4 : 2;
  5265. if (horizontal)
  5266. ngui_fill_rect(ui, (struct ngui_rect){
  5267. x + pos, y, seg, thick}, color);
  5268. else
  5269. ngui_fill_rect(ui, (struct ngui_rect){
  5270. x, y + pos, thick, seg}, color);
  5271. }
  5272. }
  5273. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  5274. const struct br_style *st)
  5275. {
  5276. int top = st->border_w[0], right = st->border_w[1];
  5277. int bottom = st->border_w[2], left = st->border_w[3];
  5278. if (r.w <= 0 || r.h <= 0)
  5279. return;
  5280. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  5281. int i;
  5282. for (i = 0; i < 4; i++)
  5283. if (st->border_w[i] && !st->border_t[i]) {
  5284. ngui_fill_rect(ui, r, st->border_c[i]);
  5285. break;
  5286. }
  5287. return;
  5288. }
  5289. if (top && !st->border_t[0])
  5290. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  5291. st->border_c[0], st->border_s[0]);
  5292. if (bottom && !st->border_t[2])
  5293. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  5294. st->border_c[2], st->border_s[2]);
  5295. if (left && !st->border_t[3])
  5296. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  5297. left, 0, st->border_c[3], st->border_s[3]);
  5298. if (right && !st->border_t[1])
  5299. draw_border_side(ui, r.x + r.w - right, r.y + top,
  5300. r.h - top - bottom, right, 0,
  5301. st->border_c[1], st->border_s[1]);
  5302. }
  5303. static void transform_origin(const struct br_style *st, int w, int h,
  5304. int *ox, int *oy)
  5305. {
  5306. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  5307. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  5308. }
  5309. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  5310. unsigned int a)
  5311. {
  5312. unsigned int dr, dg, db, sr, sg, sb;
  5313. if (a >= 255)
  5314. return s;
  5315. dr = (d >> 11) & 31;
  5316. dg = (d >> 5) & 63;
  5317. db = d & 31;
  5318. sr = (s >> 11) & 31;
  5319. sg = (s >> 5) & 63;
  5320. sb = s & 31;
  5321. dr = (dr * (255 - a) + sr * a) / 255;
  5322. dg = (dg * (255 - a) + sg * a) / 255;
  5323. db = (db * (255 - a) + sb * a) / 255;
  5324. return (unsigned short)((dr << 11) | (dg << 5) | db);
  5325. }
  5326. /* Paint a solid box through scale()/rotate() around transform-origin. This
  5327. * transforms the element's own background box; text and descendants keep
  5328. * their layout (documented approximation). */
  5329. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  5330. unsigned short color,
  5331. const struct br_style *st)
  5332. {
  5333. double sx = st->scale_x / 100.0;
  5334. double sy = st->scale_y / 100.0;
  5335. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  5336. double c = cos(th), sn = sin(th);
  5337. int ox, oy, minx, miny, maxx, maxy, x, y;
  5338. double ax, ay;
  5339. double px[4], py[4];
  5340. int cx1, cy1, cx2, cy2, i;
  5341. if (sx == 0)
  5342. sx = 0.01;
  5343. if (sy == 0)
  5344. sy = 0.01;
  5345. transform_origin(st, box.w, box.h, &ox, &oy);
  5346. ax = box.x + ox;
  5347. ay = box.y + oy;
  5348. px[0] = -ox; py[0] = -oy;
  5349. px[1] = box.w - ox; py[1] = -oy;
  5350. px[2] = box.w - ox; py[2] = box.h - oy;
  5351. px[3] = -ox; py[3] = box.h - oy;
  5352. minx = miny = 1000000;
  5353. maxx = maxy = -1000000;
  5354. for (i = 0; i < 4; i++) {
  5355. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  5356. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  5357. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5358. if (dx < minx) minx = dx;
  5359. if (dx > maxx) maxx = dx;
  5360. if (dy < miny) miny = dy;
  5361. if (dy > maxy) maxy = dy;
  5362. }
  5363. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5364. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5365. cx2 = page_rect.x + page_rect.w - 12;
  5366. cy2 = page_rect.y + page_rect.h;
  5367. if (cx2 > gui->w) cx2 = gui->w;
  5368. if (cy2 > gui->h) cy2 = gui->h;
  5369. if (minx < cx1) minx = cx1;
  5370. if (miny < cy1) miny = cy1;
  5371. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5372. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5373. for (y = miny; y <= maxy; y++) {
  5374. for (x = minx; x <= maxx; x++) {
  5375. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  5376. double rx = dx * c + dy * sn;
  5377. double ry = -dx * sn + dy * c;
  5378. double bx = rx / sx + ox;
  5379. double by = ry / sy + oy;
  5380. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  5381. gui->px[y * gui->w + x] = color;
  5382. }
  5383. }
  5384. }
  5385. static void draw_image_transformed(struct ngui *gui,
  5386. const struct img_image *im,
  5387. int x, int y, int w, int h,
  5388. int sx100, int sy100, int rot100,
  5389. int origin_x, int origin_y,
  5390. int origin_x_kind, int origin_y_kind)
  5391. {
  5392. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  5393. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  5394. double c = cos(th), sn = sin(th);
  5395. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  5396. double ax, ay;
  5397. double bx[4], by[4];
  5398. int cx1, cy1, cx2, cy2;
  5399. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  5400. return;
  5401. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  5402. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  5403. ax = x + ox;
  5404. ay = y + oy;
  5405. bx[0] = -ox; by[0] = -oy;
  5406. bx[1] = w - ox; by[1] = -oy;
  5407. bx[2] = w - ox; by[2] = h - oy;
  5408. bx[3] = -ox; by[3] = h - oy;
  5409. minx = miny = 1000000;
  5410. maxx = maxy = -1000000;
  5411. for (i = 0; i < 4; i++) {
  5412. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  5413. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  5414. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5415. if (dx < minx) minx = dx;
  5416. if (dx > maxx) maxx = dx;
  5417. if (dy < miny) miny = dy;
  5418. if (dy > maxy) maxy = dy;
  5419. }
  5420. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5421. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5422. cx2 = page_rect.x + page_rect.w - 12;
  5423. cy2 = page_rect.y + page_rect.h;
  5424. if (cx2 > gui->w) cx2 = gui->w;
  5425. if (cy2 > gui->h) cy2 = gui->h;
  5426. if (minx < cx1) minx = cx1;
  5427. if (miny < cy1) miny = cy1;
  5428. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5429. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5430. for (py = miny; py <= maxy; py++) {
  5431. for (px = minx; px <= maxx; px++) {
  5432. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  5433. double rx = dx * c + dy * sn;
  5434. double ry = -dx * sn + dy * c;
  5435. double fx = rx / sx + ox;
  5436. double fy = ry / sy + oy;
  5437. int ix, iy;
  5438. unsigned int si, a;
  5439. unsigned short src;
  5440. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  5441. continue;
  5442. ix = (int)(fx * (double)im->w / w);
  5443. iy = (int)(fy * (double)im->h / h);
  5444. if (ix < 0 || ix >= (int)im->w ||
  5445. iy < 0 || iy >= (int)im->h)
  5446. continue;
  5447. si = (unsigned int)iy * im->w + (unsigned int)ix;
  5448. src = im->px[si];
  5449. a = im->alpha ? im->alpha[si] : 255;
  5450. gui->px[py * gui->w + px] =
  5451. a >= 255 ? src :
  5452. blend_rgb565(gui->px[py * gui->w + px],
  5453. src, a);
  5454. }
  5455. }
  5456. }
  5457. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5458. unsigned int node, const struct br_style *st);
  5459. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  5460. * first and every pixel outside a corner's arc is restored afterwards. */
  5461. #define BG_ROUND_MAX 64
  5462. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  5463. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  5464. unsigned int node, const struct br_style *st,
  5465. int rtl, int rtr, int rbr, int rbl)
  5466. {
  5467. struct ngui *ui = l->ui;
  5468. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  5469. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  5470. if (ui->nclip > 0)
  5471. clip = ui->clip[ui->nclip - 1];
  5472. for (c = 0; c < 4; c++) {
  5473. if (r[c] > BG_ROUND_MAX)
  5474. r[c] = BG_ROUND_MAX;
  5475. if (r[c] > box.w / 2)
  5476. r[c] = box.w / 2;
  5477. if (r[c] > box.h / 2)
  5478. r[c] = box.h / 2;
  5479. }
  5480. for (c = 0; c < 4; c++) {
  5481. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5482. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5483. for (dy = 0; dy < r[c]; dy++)
  5484. for (dx = 0; dx < r[c]; dx++) {
  5485. int px = ox + dx, py = oy + dy;
  5486. if (px >= clip.x && py >= clip.y &&
  5487. px < clip.x + clip.w && py < clip.y + clip.h)
  5488. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  5489. ui->px[py * ui->w + px];
  5490. }
  5491. }
  5492. draw_bg_image(l, box, node, st);
  5493. for (c = 0; c < 4; c++) {
  5494. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5495. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5496. /* arc centre, in corner-square coordinates */
  5497. int cx = (c == 1 || c == 2) ? 0 : r[c];
  5498. int cy = (c >= 2) ? 0 : r[c];
  5499. for (dy = 0; dy < r[c]; dy++)
  5500. for (dx = 0; dx < r[c]; dx++) {
  5501. int px = ox + dx, py = oy + dy;
  5502. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  5503. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  5504. continue;
  5505. if (px >= clip.x && py >= clip.y &&
  5506. px < clip.x + clip.w && py < clip.y + clip.h)
  5507. ui->px[py * ui->w + px] =
  5508. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  5509. }
  5510. }
  5511. }
  5512. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5513. unsigned int node, const struct br_style *st)
  5514. {
  5515. struct br_image *bi;
  5516. struct img_blit b;
  5517. int tw, th, x, y, rep_x, rep_y, posx, posy;
  5518. unsigned int scale = 65536;
  5519. int legacy, tiles = 0, rows = 0;
  5520. int cx1, cy1, cx2, cy2;
  5521. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  5522. return;
  5523. if (doc.nodes[node].bg_img_index < 0 ||
  5524. doc.nodes[node].bg_img_index >= image_count)
  5525. return;
  5526. bi = &images[doc.nodes[node].bg_img_index];
  5527. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  5528. return;
  5529. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  5530. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  5531. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  5532. if (legacy) {
  5533. scale = ((unsigned int)box.w << 16) / bi->img.w;
  5534. tw = box.w;
  5535. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  5536. x = box.x;
  5537. y = box.y;
  5538. rep_x = rep_y = 0;
  5539. } else {
  5540. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  5541. unsigned int sx = ((unsigned int)box.w << 16) /
  5542. bi->img.w;
  5543. unsigned int sy = ((unsigned int)box.h << 16) /
  5544. bi->img.h;
  5545. scale = st->bg_size_kind == 3 ?
  5546. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  5547. } else if (st->bg_size_kind == 1 ||
  5548. st->bg_size_kind == 2) {
  5549. int w = st->bg_size_w;
  5550. int h = st->bg_size_h;
  5551. if (st->bg_size_kind == 2) {
  5552. if (w)
  5553. w = box.w * w / 100;
  5554. if (h)
  5555. h = box.h * h / 100;
  5556. }
  5557. if (w)
  5558. scale = ((unsigned int)w << 16) / bi->img.w;
  5559. else if (h)
  5560. scale = ((unsigned int)h << 16) / bi->img.h;
  5561. }
  5562. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  5563. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  5564. if (tw < 1)
  5565. tw = 1;
  5566. if (th < 1)
  5567. th = 1;
  5568. posx = st->bg_pos_x_kind == 1 ?
  5569. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  5570. posy = st->bg_pos_y_kind == 1 ?
  5571. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  5572. x = box.x + posx;
  5573. y = box.y + posy;
  5574. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  5575. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  5576. if (rep_x) {
  5577. int m = (x - box.x) % tw;
  5578. if (m > 0)
  5579. m -= tw;
  5580. x = box.x + m;
  5581. }
  5582. if (rep_y) {
  5583. int m = (y - box.y) % th;
  5584. if (m > 0)
  5585. m -= th;
  5586. y = box.y + m;
  5587. }
  5588. }
  5589. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  5590. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  5591. cx2 = box.x + box.w;
  5592. cy2 = box.y + box.h;
  5593. if (cx2 > page_rect.x + page_rect.w - 12)
  5594. cx2 = page_rect.x + page_rect.w - 12;
  5595. if (cy2 > page_rect.y + page_rect.h)
  5596. cy2 = page_rect.y + page_rect.h;
  5597. if (cx1 >= cx2 || cy1 >= cy2)
  5598. return;
  5599. b.dst = l->ui->px;
  5600. b.dst_w = l->ui->w;
  5601. b.dst_h = l->ui->h;
  5602. b.clip_x = cx1;
  5603. b.clip_y = cy1;
  5604. b.clip_w = cx2 - cx1;
  5605. b.clip_h = cy2 - cy1;
  5606. b.bg = ui.theme.bg;
  5607. b.bg2 = ui.theme.bg;
  5608. b.dst_a = 0;
  5609. {
  5610. struct img_image *src = image_display_get(bi, tw, th);
  5611. int row_x;
  5612. if (!src)
  5613. src = &bi->img;
  5614. b.scale = ((unsigned int)tw << 16) / src->w;
  5615. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  5616. row_x = x;
  5617. for (;;) {
  5618. for (;;) {
  5619. b.x = x;
  5620. b.y = y;
  5621. img_draw(src, &b);
  5622. if (!rep_x || ++tiles > 512)
  5623. break;
  5624. x += tw;
  5625. if (x >= box.x + box.w)
  5626. break;
  5627. }
  5628. if (!rep_y || ++rows > 64)
  5629. break;
  5630. y += th;
  5631. if (y >= box.y + box.h)
  5632. break;
  5633. x = row_x;
  5634. }
  5635. }
  5636. }
  5637. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  5638. int *out_w, int *out_h);
  5639. static void svg_paint_box(struct ngui *ui, unsigned int node,
  5640. const struct br_style *st, int x, int y, int w,
  5641. int h);
  5642. /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
  5643. * RUN_SVG an inline <svg> icon (its node in off). */
  5644. #define RUN_SVG (-3)
  5645. static int run_width(const struct lay_run *r)
  5646. {
  5647. if (r->img >= 0)
  5648. return r->iw;
  5649. if (r->img == -2 || r->img == RUN_SVG)
  5650. return r->iw;
  5651. return (int)r->w;
  5652. }
  5653. static void start_line(struct lay *l, const struct br_style *st)
  5654. {
  5655. (void)st;
  5656. if (l->nruns == 0) {
  5657. l->line_y = l->y;
  5658. l->line_h = 0;
  5659. }
  5660. l->line_left = l->left;
  5661. l->line_right = l->right;
  5662. if (l->float_active && l->line_y < l->float_bottom) {
  5663. if (l->float_left > l->line_left)
  5664. l->line_left = l->float_left;
  5665. if (l->float_right < l->line_right)
  5666. l->line_right = l->float_right;
  5667. }
  5668. if (l->line_right < l->line_left + 8)
  5669. l->line_right = l->line_left + 8;
  5670. l->line_x = l->line_left;
  5671. l->run_x = l->line_left;
  5672. }
  5673. static void flush_line(struct lay *l)
  5674. {
  5675. int total, x, i, vis;
  5676. if (!l->nruns && l->line_x == l->line_left) {
  5677. l->line_h = 0;
  5678. return;
  5679. }
  5680. total = l->line_x - l->line_left;
  5681. x = l->line_left;
  5682. vis = 1;
  5683. if (l->draw) {
  5684. int lh = l->line_h ? l->line_h : 16;
  5685. vis = l->line_y + lh >= page_rect.y &&
  5686. l->line_y <= page_rect.y + page_rect.h;
  5687. }
  5688. if (l->align == BR_ALIGN_CENTER)
  5689. x += (l->line_right - l->line_left - total) / 2;
  5690. else if (l->align == BR_ALIGN_RIGHT)
  5691. x = l->line_right - total;
  5692. if (x < l->line_left)
  5693. x = l->line_left;
  5694. for (i = 0; i < l->nruns; i++) {
  5695. struct lay_run *r = &l->runs[i];
  5696. int w = run_width(r);
  5697. int ry = l->line_y + r->dy;
  5698. x += r->gap;
  5699. if (l->draw && vis) {
  5700. if (r->form) {
  5701. unsigned int node = r->form - 1;
  5702. struct form_state *fs = form_get(node, 1);
  5703. int hh = r->ih ? r->ih : 20;
  5704. int focused = form_focus == node;
  5705. int disabled = r->form_disabled;
  5706. unsigned short bg = l->ui->theme.panel_alt;
  5707. unsigned short fg = disabled ? 0x8410 : r->color;
  5708. struct ngui_rect box = {x, ry, w, hh};
  5709. if (r->form_kind == FORM_CHECKBOX ||
  5710. r->form_kind == FORM_RADIO) {
  5711. ngui_fill_rect(l->ui, box, bg);
  5712. ngui_frame(l->ui, box,
  5713. focused ? l->ui->theme.accent :
  5714. l->ui->theme.border);
  5715. if (fs && fs->checked) {
  5716. struct ngui_rect dot = {
  5717. x + 4, ry + 4,
  5718. w > 8 ? w - 8 : 1,
  5719. hh > 8 ? hh - 8 : 1
  5720. };
  5721. if (r->form_kind == FORM_RADIO)
  5722. ngui_fill_round_rect(
  5723. l->ui, dot, 4,
  5724. 4, 4, 4,
  5725. l->ui->theme.accent);
  5726. else
  5727. ngui_fill_rect(l->ui,
  5728. dot,
  5729. l->ui->theme.accent);
  5730. }
  5731. } else {
  5732. int editable =
  5733. r->form_kind == FORM_TEXT ||
  5734. r->form_kind == FORM_PASSWORD ||
  5735. r->form_kind == FORM_TEXTAREA;
  5736. int scroll = 0;
  5737. /* Editable fields draw the live value
  5738. * (r->lit is a short copy). */
  5739. static char shown[FORM_VALUE_MAX + 1];
  5740. const char *txt = r->lit;
  5741. unsigned int tl = s_len(r->lit);
  5742. if (editable && fs && fs->len) {
  5743. unsigned int k;
  5744. if (r->form_kind == FORM_PASSWORD) {
  5745. for (k = 0; k < fs->len; k++)
  5746. shown[k] = '*';
  5747. shown[k] = '\0';
  5748. txt = shown;
  5749. } else {
  5750. txt = fs->value;
  5751. }
  5752. tl = fs->len;
  5753. }
  5754. struct br_style fst;
  5755. int author, tx = x + 6, pr = 6;
  5756. style_for_node(node, &fst);
  5757. author = form_author_styled(&fst);
  5758. if (author) {
  5759. /* The page styled the control:
  5760. * its background, border, radius
  5761. * and text colour. */
  5762. form_paint_author(l->ui, box, &fst,
  5763. focused);
  5764. tx = x + fst.border_w[3] +
  5765. mp_px(&fst, 7, w);
  5766. pr = fst.border_w[1] +
  5767. mp_px(&fst, 5, w);
  5768. if (tx < x + 2 && !editable)
  5769. tx = x + 2;
  5770. if (!disabled)
  5771. fg = editable && fs &&
  5772. !fs->len ?
  5773. 0x8410 : fst.color;
  5774. if (!editable) {
  5775. int tw0 = (int)
  5776. run_text_width(l->ui,
  5777. r, txt, tl);
  5778. tx = x + (w - tw0) / 2;
  5779. }
  5780. } else {
  5781. /* The box is drawn in theme colours, so
  5782. * the text is too: the page's CSS colour
  5783. * (dark on a light page) would vanish on
  5784. * the dark field. */
  5785. if (!disabled)
  5786. fg = editable && fs && !fs->len ?
  5787. l->ui->theme.text_dim :
  5788. l->ui->theme.text;
  5789. ngui_fill_rect(l->ui, box, bg);
  5790. ngui_frame(l->ui, box,
  5791. focused ? l->ui->theme.accent :
  5792. l->ui->theme.border);
  5793. }
  5794. /* A value wider than the field shows its
  5795. * tail (where typing happens). */
  5796. if (editable && fs && fs->len &&
  5797. w > (tx - x) + pr) {
  5798. int tw = (int)run_text_width(l->ui,
  5799. r, txt, tl);
  5800. int room = w - (tx - x) - pr;
  5801. if (tw > room)
  5802. scroll = tw - room;
  5803. }
  5804. ngui_push_clip(l->ui, (struct ngui_rect){
  5805. x + 1, ry + 1,
  5806. w > 2 ? w - 2 : 1,
  5807. hh > 2 ? hh - 2 : 1 });
  5808. ngui_text_px_face(l->ui, run_face(r),
  5809. tx - scroll,
  5810. ry + (hh - r->font_px) / 2 - 1,
  5811. txt, tl, fg, r->font_px,
  5812. r->bold, r->italic, r->mono);
  5813. if (focused && fs && editable) {
  5814. int cw = 0;
  5815. if (fs->len && fs->caret)
  5816. cw = (int)run_text_width(
  5817. l->ui, r, txt,
  5818. fs->caret < fs->len ?
  5819. fs->caret : fs->len);
  5820. ngui_fill_rect(l->ui,
  5821. (struct ngui_rect){
  5822. tx + cw - scroll,
  5823. ry + 4, 1,
  5824. hh > 8 ? hh - 8 : 1
  5825. },
  5826. l->ui->theme.accent);
  5827. }
  5828. ngui_pop_clip(l->ui);
  5829. if (r->form_kind == FORM_SELECT) {
  5830. ngui_text_px(l->ui, x + w - 12,
  5831. ry + 2, "v", 1, fg,
  5832. r->font_px, 0, 0, 0);
  5833. }
  5834. }
  5835. } else if (r->img == RUN_SVG) {
  5836. struct br_style sst;
  5837. style_for_node(r->off, &sst);
  5838. svg_paint_box(l->ui, r->off, &sst, x, ry, w,
  5839. r->ih);
  5840. } else if (r->img == -2) {
  5841. int hh = r->ih ? r->ih : 20;
  5842. ngui_fill_rect(l->ui,
  5843. (struct ngui_rect){x, ry, w, hh},
  5844. l->ui->theme.panel_alt);
  5845. ngui_frame(l->ui,
  5846. (struct ngui_rect){x, ry, w, hh},
  5847. l->ui->theme.border);
  5848. ngui_text_px_face(l->ui, run_face(r),
  5849. x + 6, ry + 2, r->lit,
  5850. s_len(r->lit), r->color,
  5851. r->font_px, r->bold, r->italic,
  5852. r->mono);
  5853. } else if (r->img >= 0) {
  5854. struct br_image *bi = &images[r->img];
  5855. if (bi->state == 1 && r->transform_scale) {
  5856. draw_image_transformed(l->ui, &bi->img,
  5857. x, ry, r->iw, r->ih,
  5858. r->scale_x, r->scale_y,
  5859. r->rotate_x100, r->origin_x,
  5860. r->origin_y, r->origin_x_kind,
  5861. r->origin_y_kind);
  5862. } else if (bi->state == 1) {
  5863. struct img_image *src =
  5864. image_display_get(bi, r->iw, r->ih);
  5865. struct img_blit b;
  5866. if (!src)
  5867. src = &bi->img;
  5868. b.dst = l->ui->px;
  5869. b.dst_w = l->ui->w;
  5870. b.dst_h = l->ui->h;
  5871. b.clip_x = page_rect.x;
  5872. b.clip_y = page_rect.y;
  5873. b.clip_w = page_rect.w - 12;
  5874. b.clip_h = page_rect.h;
  5875. b.x = x;
  5876. b.y = ry;
  5877. b.scale = ((unsigned int)r->iw << 16) /
  5878. src->w;
  5879. b.bg = ui.theme.bg;
  5880. b.bg2 = ui.theme.bg;
  5881. b.dst_a = 0;
  5882. b.flags = src->alpha ?
  5883. IMG_BLIT_OVER_DST : 0;
  5884. img_draw(src, &b);
  5885. }
  5886. } else {
  5887. const char *s = r->has_lit ? r->lit :
  5888. doc.text + r->off;
  5889. unsigned int n = r->has_lit ? s_len(r->lit) :
  5890. r->len;
  5891. ngui_text_px_face(l->ui, run_face(r), x, ry,
  5892. s, n, r->color, r->font_px,
  5893. r->bold, r->italic, r->mono);
  5894. if (r->underline)
  5895. ngui_fill_rect(l->ui,
  5896. (struct ngui_rect){x,
  5897. ry + run_ascent(l->ui, r) + 2,
  5898. w, 1}, r->color);
  5899. if (r->strike)
  5900. ngui_fill_rect(l->ui,
  5901. (struct ngui_rect){x,
  5902. ry + run_ascent(l->ui, r) -
  5903. (r->font_px > 3 ?
  5904. r->font_px / 3 : 1),
  5905. w, 1}, r->color);
  5906. if (r->overline)
  5907. ngui_fill_rect(l->ui,
  5908. (struct ngui_rect){x, ry,
  5909. w, 1}, r->color);
  5910. }
  5911. if (r->form || r->href) {
  5912. if (nhits < HIT_MAX) {
  5913. struct hit *h = &hits[nhits];
  5914. unsigned int target = r->form ?
  5915. r->form - 1 : r->href;
  5916. int hh = (r->form || r->img >= 0 ||
  5917. r->img == RUN_SVG) ?
  5918. r->ih :
  5919. run_line_height(l->ui, r);
  5920. int merge = nhits > 0 &&
  5921. hits[nhits - 1].node == target &&
  5922. hits[nhits - 1].y == ry &&
  5923. hits[nhits - 1].h == hh &&
  5924. x <= hits[nhits - 1].x +
  5925. hits[nhits - 1].w + 2;
  5926. if (merge) {
  5927. struct hit *p = &hits[nhits - 1];
  5928. int end = x + w;
  5929. if (end > p->x + p->w)
  5930. p->w = end - p->x;
  5931. } else {
  5932. h->x = x;
  5933. h->y = ry;
  5934. h->w = w;
  5935. h->h = hh;
  5936. h->node = (unsigned short)target;
  5937. nhits++;
  5938. }
  5939. }
  5940. }
  5941. }
  5942. x += w;
  5943. }
  5944. l->y += l->line_h + 2;
  5945. if (l->float_active && l->y >= l->float_bottom)
  5946. l->float_active = 0;
  5947. l->nruns = 0;
  5948. l->line_x = l->left;
  5949. l->run_x = l->left;
  5950. l->line_left = l->left;
  5951. l->line_right = l->right;
  5952. l->line_h = 0;
  5953. l->space_pending = 0;
  5954. }
  5955. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  5956. const struct br_style *st, unsigned short href,
  5957. const char *lit)
  5958. {
  5959. unsigned int n = lit ? s_len(lit) : len;
  5960. const char *tp = lit ? lit : doc.text + off;
  5961. int w = (int)face_text_width(l->ui, st, tp, n);
  5962. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  5963. flush_line(l);
  5964. if (l->nruns == 0) {
  5965. l->line_y = l->y;
  5966. l->line_h = 0;
  5967. start_line(l, st);
  5968. }
  5969. {
  5970. struct lay_run *r = &l->runs[l->nruns++];
  5971. int gap = l->line_x - l->run_x;
  5972. if (gap < 0)
  5973. gap = 0;
  5974. r->gap = (unsigned short)gap;
  5975. r->off = off;
  5976. r->len = len;
  5977. r->color = st->color;
  5978. r->href = href;
  5979. r->dy = 0;
  5980. r->has_lit = 0;
  5981. r->form = 0;
  5982. r->form_kind = 0;
  5983. r->form_disabled = 0;
  5984. r->lit[0] = '\0';
  5985. if (lit && lit[0]) {
  5986. unsigned int i;
  5987. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  5988. r->lit[i] = lit[i];
  5989. r->lit[i] = '\0';
  5990. r->has_lit = 1;
  5991. }
  5992. r->img = -1;
  5993. r->iw = r->ih = 0;
  5994. r->font_px = st->font_px;
  5995. r->bold = st->bold;
  5996. r->italic = st->italic;
  5997. r->mono = st->mono;
  5998. r->font_face = st->font_face;
  5999. /* A control with its own background is a button, not body copy;
  6000. * an inherited link underline would strike through the fill. */
  6001. r->underline = st->underline && !st->has_bg;
  6002. r->strike = st->strike && !st->has_bg;
  6003. r->overline = st->overline && !st->has_bg;
  6004. r->w = (unsigned short)w;
  6005. if (r->has_lit)
  6006. r->w = (unsigned short)run_text_width(
  6007. l->ui, r, r->lit, s_len(r->lit));
  6008. w = r->w;
  6009. }
  6010. l->line_x += w;
  6011. l->run_x = l->line_x;
  6012. {
  6013. int lh = face_line_height(l->ui, st);
  6014. if (st->line_h_px)
  6015. lh = st->line_h_px;
  6016. else if (st->line_h_pct)
  6017. lh = st->font_px * st->line_h_pct / 100;
  6018. if (lh < face_line_height(l->ui, st))
  6019. lh = face_line_height(l->ui, st);
  6020. if (l->line_h < lh)
  6021. l->line_h = lh;
  6022. }
  6023. }
  6024. static void add_image_run(struct lay *l, unsigned int node,
  6025. const struct br_style *st, unsigned short href)
  6026. {
  6027. struct br_image *bi = 0;
  6028. int idx = doc.nodes[node].img_index;
  6029. int dw, dh, maxw;
  6030. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  6031. bi = &images[idx];
  6032. if (l->nruns == 0)
  6033. start_line(l, st);
  6034. if (l->space_pending &&
  6035. (l->nruns > 0 || l->line_x > l->line_left)) {
  6036. int sp = (int)face_text_width(l->ui, st, " ", 1);
  6037. if (l->line_x + sp <= l->line_right)
  6038. l->line_x += sp;
  6039. }
  6040. l->space_pending = 0;
  6041. if (!bi) {
  6042. const char *alt = br_alt(&doc, node);
  6043. struct br_style gs = *st;
  6044. char tmp[96];
  6045. unsigned int n = 0;
  6046. int w;
  6047. gs.color = BR_GRAY;
  6048. gs.underline = 0;
  6049. s_append(tmp, &n, "[", sizeof(tmp));
  6050. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  6051. s_append(tmp, &n, "]", sizeof(tmp));
  6052. w = (int)face_text_width(l->ui, &gs, tmp, n);
  6053. if (l->line_x + w > l->line_right &&
  6054. (l->nruns > 0 || l->line_x > l->line_left))
  6055. flush_line(l);
  6056. add_run(l, 0, 0, &gs, href, tmp);
  6057. if (!l->draw) {
  6058. int t = l->line_y < 0 ? 0 : l->line_y;
  6059. int hh = face_line_height(l->ui, &gs);
  6060. if (t > 65535)
  6061. t = 65535;
  6062. if (hh > 65535)
  6063. hh = 65535;
  6064. img_top[node] = (unsigned short)t;
  6065. img_h[node] = (unsigned short)hh;
  6066. }
  6067. return;
  6068. }
  6069. maxw = l->line_right - l->line_left;
  6070. if (maxw < 8)
  6071. maxw = 8;
  6072. {
  6073. int iw = bi->native_w, ih = bi->native_h;
  6074. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  6075. if (iw <= 0 || ih <= 0) {
  6076. iw = (int)bi->img.w;
  6077. ih = (int)bi->img.h;
  6078. }
  6079. dw = iw;
  6080. dh = ih;
  6081. if (doc.nodes[node].width_attr) {
  6082. int want = doc.nodes[node].width_attr;
  6083. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  6084. have_w = 1;
  6085. }
  6086. if (doc.nodes[node].height_attr) {
  6087. int want = doc.nodes[node].height_attr;
  6088. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  6089. have_h = 1;
  6090. }
  6091. if (have_w && !have_h)
  6092. dh = ih ? ih * dw / iw : 0;
  6093. if (have_h && !have_w)
  6094. dw = iw ? iw * dh / ih : 0;
  6095. if (st->width_kind) {
  6096. css_w = 1;
  6097. if (st->width_kind == 3)
  6098. dw = maxw * st->width_calc_pct / 100 +
  6099. st->width_calc_px;
  6100. else
  6101. dw = st->width_kind == 2 ?
  6102. maxw * (int)st->width / 100 :
  6103. (int)st->width;
  6104. }
  6105. if (st->height_kind) {
  6106. css_h = 1;
  6107. if (st->height_kind == 3)
  6108. dh = maxw * st->height_calc_pct / 100 +
  6109. st->height_calc_px;
  6110. else
  6111. dh = st->height_kind == 2 ?
  6112. maxw * (int)st->height / 100 :
  6113. (int)st->height;
  6114. }
  6115. if (css_w && !css_h)
  6116. dh = ih ? ih * dw / iw : 0;
  6117. if (css_h && !css_w)
  6118. dw = iw ? iw * dh / ih : 0;
  6119. if (st->max_width_kind) {
  6120. int mw = st->max_width_kind == 3 ?
  6121. maxw * st->max_width_calc_pct / 100 +
  6122. st->max_width_calc_px :
  6123. st->max_width_kind == 2 ?
  6124. maxw * (int)st->max_width / 100 :
  6125. (int)st->max_width;
  6126. if (mw > 0 && dw > mw) {
  6127. dh = iw ? ih * mw / iw : 0;
  6128. dw = mw;
  6129. }
  6130. }
  6131. }
  6132. if (dw < 8)
  6133. dw = 8;
  6134. if (dh < 8)
  6135. dh = 8;
  6136. if (dw > maxw) {
  6137. dh = dw ? dh * maxw / dw : dh;
  6138. dw = maxw;
  6139. }
  6140. if (!l->draw) {
  6141. int t = l->line_y < 0 ? 0 : l->line_y;
  6142. if (t > 65535)
  6143. t = 65535;
  6144. if (dh > 65535)
  6145. dh = 65535;
  6146. img_top[node] = (unsigned short)t;
  6147. img_h[node] = (unsigned short)dh;
  6148. }
  6149. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  6150. l->line_x > l->line_left))
  6151. flush_line(l);
  6152. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6153. flush_line(l);
  6154. if (l->nruns == 0) {
  6155. l->line_y = l->y;
  6156. l->line_h = 0;
  6157. start_line(l, st);
  6158. }
  6159. {
  6160. struct lay_run *r = &l->runs[l->nruns++];
  6161. int gap = l->line_x - l->run_x;
  6162. if (gap < 0)
  6163. gap = 0;
  6164. r->gap = (unsigned short)gap;
  6165. r->off = 0;
  6166. r->len = 0;
  6167. r->color = 0;
  6168. r->href = href;
  6169. r->form = 0;
  6170. r->form_kind = 0;
  6171. r->form_disabled = 0;
  6172. /* Inline replaced elements honour their vertical margins; this
  6173. * is how Bootstrap's negative logo margins centre the wordmark. */
  6174. {
  6175. int idy = mp_px(st, 0, l->right - l->left);
  6176. if (idy < -2048)
  6177. idy = -2048;
  6178. if (idy > 2048)
  6179. idy = 2048;
  6180. r->dy = (signed short)idy;
  6181. }
  6182. r->has_lit = 0;
  6183. r->lit[0] = '\0';
  6184. r->img = (short)idx;
  6185. r->iw = (unsigned short)dw;
  6186. r->ih = (unsigned short)dh;
  6187. r->w = (unsigned short)dw;
  6188. r->font_px = st->font_px;
  6189. r->bold = st->bold;
  6190. r->italic = st->italic;
  6191. r->mono = st->mono;
  6192. r->font_face = st->font_face;
  6193. r->transform_scale = st->transform_scale;
  6194. r->scale_x = st->scale_x;
  6195. r->scale_y = st->scale_y;
  6196. r->rotate_x100 = st->rotate_x100;
  6197. r->origin_x = st->origin_x;
  6198. r->origin_y = st->origin_y;
  6199. r->origin_x_kind = st->origin_x_kind;
  6200. r->origin_y_kind = st->origin_y_kind;
  6201. r->underline = 0;
  6202. }
  6203. if (node < BR_MAX_NODES) {
  6204. layout_boxes[node].x = l->line_x;
  6205. layout_boxes[node].y = l->line_y +
  6206. mp_px(st, 0, l->right - l->left);
  6207. layout_boxes[node].w = dw;
  6208. layout_boxes[node].h = dh;
  6209. layout_boxes[node].valid = 1;
  6210. }
  6211. l->line_x += dw;
  6212. l->run_x = l->line_x;
  6213. if (l->line_h < dh)
  6214. l->line_h = dh;
  6215. }
  6216. /* An inline (or inline-block) <svg> is a replaced element in the text
  6217. * line, like an <img>: comment bubbles and arrows sit next to their label
  6218. * instead of starting a block of their own. */
  6219. static void add_svg_run(struct lay *l, unsigned int node,
  6220. const struct br_style *st, unsigned short href)
  6221. {
  6222. struct lay_run *r;
  6223. int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
  6224. if (lw < 8)
  6225. lw = 8;
  6226. cw = st->width_kind ? style_width_px(st, lw) : lw;
  6227. if (cw < 1)
  6228. cw = 1;
  6229. svg_size(node, st, cw, &dw, &dh);
  6230. if (dw > lw)
  6231. dw = lw;
  6232. ml = mp_px(st, 3, lw);
  6233. mr = mp_px(st, 1, lw);
  6234. if (ml < 0)
  6235. ml = 0;
  6236. if (mr < 0)
  6237. mr = 0;
  6238. if (l->line_x + ml + dw > l->line_right &&
  6239. (l->nruns > 0 || l->line_x > l->line_left))
  6240. flush_line(l);
  6241. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6242. flush_line(l);
  6243. if (l->nruns == 0) {
  6244. l->line_y = l->y;
  6245. l->line_h = 0;
  6246. start_line(l, st);
  6247. }
  6248. l->line_x += ml;
  6249. r = &l->runs[l->nruns++];
  6250. memset(r, 0, sizeof(*r));
  6251. r->gap = (unsigned short)(l->line_x > l->run_x ?
  6252. l->line_x - l->run_x : 0);
  6253. r->off = node;
  6254. r->color = st->color;
  6255. r->href = href;
  6256. r->img = RUN_SVG;
  6257. r->iw = (unsigned short)dw;
  6258. r->ih = (unsigned short)dh;
  6259. r->w = (unsigned short)dw;
  6260. r->font_px = st->font_px;
  6261. if (node < BR_MAX_NODES) {
  6262. layout_boxes[node].x = l->line_x;
  6263. layout_boxes[node].y = l->line_y;
  6264. layout_boxes[node].w = dw;
  6265. layout_boxes[node].h = dh;
  6266. layout_boxes[node].valid = 1;
  6267. }
  6268. l->line_x += dw + mr;
  6269. l->run_x = l->line_x;
  6270. if (l->line_h < dh)
  6271. l->line_h = dh;
  6272. }
  6273. static int text_width(struct lay *l, const char *s, unsigned int n,
  6274. const struct br_style *st)
  6275. {
  6276. return (int)face_text_width(l->ui, st, s, n);
  6277. }
  6278. /* Longest prefix that fits in maxw, at least one byte. */
  6279. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  6280. const struct br_style *st, int maxw)
  6281. {
  6282. unsigned int take = 0;
  6283. while (take < n) {
  6284. if (text_width(l, s, take + 1, st) > maxw)
  6285. break;
  6286. take++;
  6287. }
  6288. return take ? take : 1;
  6289. }
  6290. static void emit_word(struct lay *l, const char *s, unsigned int start,
  6291. unsigned int n, unsigned int base,
  6292. const struct br_style *st, unsigned short href)
  6293. {
  6294. int avail;
  6295. int w = text_width(l, s + start, n, st);
  6296. unsigned int off = start;
  6297. if (l->nruns == 0)
  6298. start_line(l, st);
  6299. avail = l->line_right - l->line_left;
  6300. if (st->nowrap) {
  6301. if (n)
  6302. add_run(l, base + start,
  6303. (unsigned short)n, st, href, 0);
  6304. return;
  6305. }
  6306. /* A padded/bordered one-word button can be a few pixels wider than
  6307. * the content box; keep it on one line instead of splitting it. */
  6308. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  6309. add_run(l, base + start,
  6310. (unsigned short)n, st, href, 0);
  6311. return;
  6312. }
  6313. if (l->line_x + w > l->line_right &&
  6314. (l->nruns > 0 || l->line_x > l->line_left)) {
  6315. flush_line(l);
  6316. start_line(l, st);
  6317. avail = l->line_right - l->line_left;
  6318. }
  6319. if (w <= avail) {
  6320. if (n)
  6321. add_run(l, base + start,
  6322. (unsigned short)n, st, href, 0);
  6323. return;
  6324. }
  6325. while (n > 0) {
  6326. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  6327. add_run(l, base + off,
  6328. (unsigned short)take, st, href, 0);
  6329. off += take;
  6330. n -= take;
  6331. if (n) {
  6332. flush_line(l);
  6333. start_line(l, st);
  6334. avail = l->line_right - l->line_left;
  6335. }
  6336. }
  6337. }
  6338. static void emit_text(struct lay *l, const char *s, unsigned int len,
  6339. const struct br_style *st, unsigned short href, int pre)
  6340. {
  6341. unsigned int i = 0;
  6342. unsigned int base;
  6343. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  6344. if (!s || !len)
  6345. return;
  6346. if (space_w <= 0)
  6347. space_w = 8;
  6348. if (l->nruns == 0)
  6349. start_line(l, st);
  6350. base = (unsigned int)(s - doc.text);
  6351. if (st->uppercase) {
  6352. char *p = (char *)s;
  6353. unsigned int j;
  6354. for (j = 0; j < len; j++)
  6355. if (p[j] >= 'a' && p[j] <= 'z')
  6356. p[j] = (char)(p[j] - 'a' + 'A');
  6357. }
  6358. if (pre) {
  6359. while (i < len) {
  6360. unsigned int start;
  6361. if (s[i] == '\n') {
  6362. flush_line(l);
  6363. start_line(l, st);
  6364. i++;
  6365. continue;
  6366. }
  6367. if (s[i] == ' ') {
  6368. if (l->line_x + space_w > l->line_right &&
  6369. (l->nruns > 0 || l->line_x > l->line_left)) {
  6370. flush_line(l);
  6371. start_line(l, st);
  6372. } else {
  6373. l->line_x += space_w;
  6374. }
  6375. i++;
  6376. continue;
  6377. }
  6378. start = i;
  6379. while (i < len && s[i] != ' ' && s[i] != '\n')
  6380. i++;
  6381. emit_word(l, s, start, i - start, base, st, href);
  6382. }
  6383. return;
  6384. }
  6385. while (i < len) {
  6386. unsigned int start, n;
  6387. if (s[i] == ' ') {
  6388. l->space_pending = 1;
  6389. i++;
  6390. continue;
  6391. }
  6392. start = i;
  6393. while (i < len && s[i] != ' ')
  6394. i++;
  6395. n = i - start;
  6396. if (l->space_pending &&
  6397. (l->nruns > 0 || l->line_x > l->line_left)) {
  6398. if (st->nowrap ||
  6399. l->line_x + space_w <= l->line_right)
  6400. l->line_x += space_w;
  6401. }
  6402. l->space_pending = 0;
  6403. emit_word(l, s, start, n, base, st, href);
  6404. }
  6405. }
  6406. static int list_index(unsigned int parent, unsigned int node)
  6407. {
  6408. unsigned int n = 0, i;
  6409. for (i = doc.nodes[parent].first; i && i != node;
  6410. i = doc.nodes[i].next)
  6411. if (doc.nodes[i].tag == BR_TAG_LI)
  6412. n++;
  6413. return (int)n + 1;
  6414. }
  6415. static void list_roman(char *m, unsigned int *n, int v, int upper,
  6416. unsigned int cap)
  6417. {
  6418. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  6419. 50, 40, 10, 9, 5, 4, 1 };
  6420. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  6421. "l", "xl", "x", "ix", "v", "iv", "i" };
  6422. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  6423. "L", "XL", "X", "IX", "V", "IV", "I" };
  6424. unsigned int i;
  6425. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  6426. while (v >= val[i] && *n + 1 < cap) {
  6427. const char *s = upper ? up[i] : lo[i];
  6428. while (*s && *n + 1 < cap)
  6429. m[(*n)++] = *s++;
  6430. v -= val[i];
  6431. }
  6432. }
  6433. }
  6434. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  6435. {
  6436. unsigned int n = 0;
  6437. if (style == BR_LIST_DISC) {
  6438. m[n++] = '-';
  6439. } else if (style == BR_LIST_CIRCLE) {
  6440. m[n++] = 'o';
  6441. } else if (style == BR_LIST_SQUARE) {
  6442. m[n++] = '+';
  6443. } else if (style == BR_LIST_LOWER_ALPHA ||
  6444. style == BR_LIST_UPPER_ALPHA) {
  6445. if (idx >= 1 && idx <= 26)
  6446. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  6447. 'A' : 'a') + idx - 1);
  6448. else
  6449. m[n++] = '?';
  6450. m[n++] = '.';
  6451. } else if (style == BR_LIST_LOWER_ROMAN ||
  6452. style == BR_LIST_UPPER_ROMAN) {
  6453. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  6454. if (n + 1 < cap)
  6455. m[n++] = '.';
  6456. } else {
  6457. s_append_dec(m, &n, (unsigned int)idx, cap);
  6458. if (n + 1 < cap)
  6459. m[n++] = '.';
  6460. }
  6461. m[n] = '\0';
  6462. }
  6463. /* A control the page styled itself (background, border or radius in author
  6464. * CSS -- `background:transparent;border:none` counts) is painted with that
  6465. * style, sized from its padding/height and keeps the page's text colour.
  6466. * Unstyled controls keep the ngui theme look. */
  6467. static int form_author_styled(const struct br_style *st)
  6468. {
  6469. int i;
  6470. if (st->bg_set)
  6471. return 1;
  6472. for (i = 0; i < 4; i++)
  6473. if (st->border_w[i] || st->radius[i])
  6474. return 1;
  6475. return 0;
  6476. }
  6477. /* Set by the layout when the control is stretched to its line: a flex item
  6478. * (its box width was assigned by the flex row) or a child of a flex column,
  6479. * whose default align-items: stretch makes inputs full width. */
  6480. static int form_fill_line;
  6481. static void add_form_run(struct lay *l, unsigned int node,
  6482. const struct br_style *st, unsigned short href)
  6483. {
  6484. struct form_state *fs = form_get(node, 1);
  6485. char shown[FORM_VALUE_MAX + 1];
  6486. char opt[64];
  6487. const char *text = "";
  6488. struct lay_run *r;
  6489. int kind = form_kind_of(node);
  6490. int disabled = form_disabled(node);
  6491. int author = form_author_styled(st);
  6492. int tw, w = 120, h = 20, i, line_w, pad_x, pad_y;
  6493. int ml = 0, mr = 0, mt = 0, mb = 0;
  6494. if (!fs)
  6495. return;
  6496. if (l->nruns == 0)
  6497. start_line(l, st);
  6498. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  6499. text = "";
  6500. w = 16;
  6501. h = 16;
  6502. } else if (kind == FORM_SELECT) {
  6503. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  6504. s_copy(opt, "Select", sizeof(opt));
  6505. text = opt;
  6506. w = 120;
  6507. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  6508. kind == FORM_RESET) {
  6509. if (fs->len)
  6510. text = fs->value;
  6511. else
  6512. text = kind == FORM_SUBMIT ? "Submit" :
  6513. kind == FORM_RESET ? "Reset" : "Button";
  6514. } else if (kind == FORM_PASSWORD) {
  6515. for (i = 0; i < fs->len; i++)
  6516. shown[i] = '*';
  6517. shown[fs->len] = '\0';
  6518. text = fs->len ? shown : br_placeholder(&doc, node);
  6519. } else {
  6520. if (fs->len)
  6521. text = fs->value;
  6522. else
  6523. text = br_placeholder(&doc, node);
  6524. if (kind == FORM_TEXTAREA) {
  6525. w = 180;
  6526. h = 40;
  6527. }
  6528. }
  6529. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  6530. line_w = l->line_right - l->line_left;
  6531. pad_x = mp_px(st, 7, line_w) + mp_px(st, 5, line_w) +
  6532. st->border_w[1] + st->border_w[3];
  6533. pad_y = mp_px(st, 4, line_w) + mp_px(st, 6, line_w) +
  6534. st->border_w[0] + st->border_w[2];
  6535. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  6536. /* Buttons are border-box in every UA stylesheet: an
  6537. * explicit width/height is the whole box. */
  6538. if (author || pad_x) {
  6539. w = tw + pad_x;
  6540. } else {
  6541. w = tw + 18;
  6542. if (w < 64)
  6543. w = 64;
  6544. }
  6545. if (st->width_kind)
  6546. w = style_width_px(st, line_w);
  6547. if (st->min_width_kind == 1 && w < (int)st->min_width)
  6548. w = st->min_width;
  6549. if (st->height_kind == 1)
  6550. h = st->height;
  6551. else if (author)
  6552. h = st->font_px + 6 + pad_y;
  6553. else
  6554. h = 22;
  6555. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  6556. kind == FORM_TEXTAREA) {
  6557. int fill = form_fill_line || st->display == BR_DISPLAY_BLOCK ||
  6558. st->display == BR_DISPLAY_FLEX;
  6559. int boxed = st->box_sizing ? 0 : pad_x;
  6560. if (st->width_kind)
  6561. w = style_width_px(st, line_w) + boxed;
  6562. else if (fill)
  6563. w = line_w - (l->line_x - l->line_left);
  6564. else
  6565. w = kind == FORM_TEXTAREA ? 180 : 120;
  6566. if (kind == FORM_TEXTAREA) {
  6567. const char *ra = br_find_attr(&doc, node, "rows");
  6568. int rows = 0;
  6569. int lh = st->line_h_px ? st->line_h_px :
  6570. st->font_px * 5 / 4;
  6571. while (ra && *ra >= '0' && *ra <= '9')
  6572. rows = rows * 10 + (*ra++ - '0');
  6573. if (rows < 1 || rows > 40)
  6574. rows = 2;
  6575. h = author ? rows * lh + pad_y : 40;
  6576. } else if (author) {
  6577. h = st->font_px + 8 + pad_y;
  6578. } else if (st->font_px + 8 > h) {
  6579. /* Taller fields for large text (min-height/padding
  6580. * on login pages): keep the box around the glyphs. */
  6581. h = st->font_px + 8;
  6582. }
  6583. if (st->height_kind == 1)
  6584. h = st->height + (st->box_sizing ? 0 : pad_y);
  6585. if (st->min_height_kind == 1 && h < (int)st->min_height)
  6586. h = st->min_height;
  6587. } else if (kind == FORM_SELECT) {
  6588. w = st->width_kind == 1 ? st->width : 120;
  6589. }
  6590. if (author) {
  6591. /* Inline margins (Google's `margin:11px 4px` between its
  6592. * two submit buttons). */
  6593. ml = mp_px(st, 3, line_w);
  6594. mr = mp_px(st, 1, line_w);
  6595. mt = mp_px(st, 0, line_w);
  6596. mb = mp_px(st, 2, line_w);
  6597. if (ml < 0 || ml > 64) ml = 0;
  6598. if (mr < 0 || mr > 64) mr = 0;
  6599. if (mt < 0 || mt > 64) mt = 0;
  6600. if (mb < 0 || mb > 64) mb = 0;
  6601. }
  6602. if (w > line_w - ml - mr)
  6603. w = line_w - ml - mr;
  6604. if (w < 8)
  6605. w = 8;
  6606. if (h > 400)
  6607. h = 400;
  6608. if (l->line_x + ml + w > l->line_right &&
  6609. (l->nruns > 0 || l->line_x > l->line_left))
  6610. flush_line(l);
  6611. if (l->nruns >= 96)
  6612. return;
  6613. if (l->nruns == 0) {
  6614. l->line_y = l->y;
  6615. l->line_h = 0;
  6616. start_line(l, st);
  6617. }
  6618. l->line_x += ml;
  6619. r = &l->runs[l->nruns++];
  6620. r->gap = (unsigned short)(l->line_x - l->run_x);
  6621. r->off = r->len = 0;
  6622. r->color = st->color;
  6623. r->href = href;
  6624. r->dy = (signed short)mt;
  6625. r->has_lit = 1;
  6626. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  6627. r->lit[i] = text[i];
  6628. r->lit[i] = '\0';
  6629. r->img = -2;
  6630. r->iw = (unsigned short)w;
  6631. r->ih = (unsigned short)h;
  6632. r->w = (unsigned short)w;
  6633. r->font_px = st->font_px;
  6634. r->bold = st->bold;
  6635. r->italic = st->italic;
  6636. r->mono = st->mono;
  6637. r->font_face = st->font_face;
  6638. r->underline = 0;
  6639. r->form = node + 1;
  6640. r->form_kind = (unsigned char)kind;
  6641. r->form_disabled = (unsigned char)disabled;
  6642. if (node < BR_MAX_NODES) {
  6643. layout_boxes[node].x = l->line_x;
  6644. layout_boxes[node].y = l->line_y + mt;
  6645. layout_boxes[node].w = w;
  6646. layout_boxes[node].h = h;
  6647. layout_boxes[node].valid = 1;
  6648. }
  6649. l->line_x += w;
  6650. l->run_x = l->line_x;
  6651. l->line_x += mr;
  6652. if (l->line_h < h + mt + mb)
  6653. l->line_h = h + mt + mb;
  6654. }
  6655. /* Background, border and corner radius of an author-styled control, the
  6656. * same decoration rules as a block box. */
  6657. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  6658. const struct br_style *st, int focused)
  6659. {
  6660. int rtl = css_radius(st, 0, box.w, box.h);
  6661. int rtr = css_radius(st, 1, box.w, box.h);
  6662. int rbr = css_radius(st, 2, box.w, box.h);
  6663. int rbl = css_radius(st, 3, box.w, box.h);
  6664. int bw = st->border_t[0] ? 0 : st->border_w[0];
  6665. (void)focused;
  6666. if (box.w <= 0 || box.h <= 0)
  6667. return;
  6668. if (rtl || rtr || rbr || rbl) {
  6669. if (bw > 0 && st->has_bg && st->border_c[0] != st->bg &&
  6670. box.w > bw * 2 && box.h > bw * 2) {
  6671. struct ngui_rect in = { box.x + bw, box.y + bw,
  6672. box.w - bw * 2,
  6673. box.h - bw * 2 };
  6674. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  6675. st->border_c[0]);
  6676. ngui_fill_round_rect(ui, in,
  6677. rtl > bw ? rtl - bw : 0,
  6678. rtr > bw ? rtr - bw : 0,
  6679. rbr > bw ? rbr - bw : 0,
  6680. rbl > bw ? rbl - bw : 0, st->bg);
  6681. } else if (st->has_bg) {
  6682. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  6683. st->bg);
  6684. } else if (bw > 0) {
  6685. ngui_frame_round(ui, box, rtl, rtr, rbr, rbl, bw,
  6686. st->border_c[0]);
  6687. }
  6688. return;
  6689. }
  6690. if (st->has_bg)
  6691. ngui_fill_rect(ui, box, st->bg);
  6692. if (st->border_w[0] || st->border_w[1] || st->border_w[2] ||
  6693. st->border_w[3])
  6694. draw_border_box(ui, box, st);
  6695. }
  6696. /* A poster wrapper is absolutely positioned over the media slot; the
  6697. * measured height of its picture is normally added back to the flow. When a
  6698. * loading-skeleton sibling already reserves that slot, adding both doubles
  6699. * the media height and pushes the article text a full screen down. */
  6700. static int has_skeleton_sibling(unsigned int node)
  6701. {
  6702. unsigned int p = doc.nodes[node].parent, c;
  6703. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  6704. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  6705. continue;
  6706. if (doc.nodes[c].class_off &&
  6707. contains_ci(doc.attrs + doc.nodes[c].class_off,
  6708. "skeleton"))
  6709. return 1;
  6710. }
  6711. return 0;
  6712. }
  6713. static void layout_children(struct lay *l, unsigned int parent,
  6714. const struct br_style *pst, int depth,
  6715. unsigned short link);
  6716. static void layout_flex_children(struct lay *l, unsigned int parent,
  6717. const struct br_style *pst, int depth,
  6718. unsigned short link);
  6719. static void layout_grid_children(struct lay *l, unsigned int parent,
  6720. const struct br_style *pst, int depth,
  6721. unsigned short link);
  6722. static void layout_grid_auto(struct lay *l, unsigned int parent,
  6723. const struct br_style *pst, int depth,
  6724. unsigned short link);
  6725. static int flex_item_width(struct lay *l, unsigned int n,
  6726. const struct br_style *cs, int avail);
  6727. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  6728. const struct br_style *pst, int depth,
  6729. unsigned short link);
  6730. static void layout_table_row(struct lay *l, unsigned int row,
  6731. const struct br_style *pst, int depth,
  6732. unsigned short link);
  6733. static int table_has_rowspan(unsigned int table);
  6734. static void layout_table(struct lay *l, unsigned int table,
  6735. const struct br_style *st, int depth,
  6736. unsigned short link);
  6737. /* A flex container whose items are only inline spans is usually just a
  6738. * heading/icon pair. Our flex row positions such items without emitting
  6739. * their inline text in some deep page contexts; normal inline flow renders
  6740. * the same content correctly. */
  6741. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  6742. {
  6743. unsigned int c;
  6744. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  6745. struct br_node *nd = &doc.nodes[c];
  6746. struct br_style cs;
  6747. if (nd->type == BR_NODE_TEXT)
  6748. continue;
  6749. br_style_for(&doc, c, pst, &cs);
  6750. if (cs.display == BR_DISPLAY_NONE)
  6751. continue;
  6752. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  6753. cs.width_kind || cs.has_bg ||
  6754. cs.border_w[0] || cs.border_w[1] ||
  6755. cs.border_w[2] || cs.border_w[3] ||
  6756. nd->tag == BR_TAG_IMG)
  6757. return 1;
  6758. }
  6759. return 0;
  6760. }
  6761. static int css_radius(const struct br_style *st, int corner,
  6762. int w, int h)
  6763. {
  6764. int r = st->radius[corner];
  6765. if (r <= 0)
  6766. return 0;
  6767. if (r > w / 2)
  6768. r = w / 2;
  6769. if (r > h / 2)
  6770. r = h / 2;
  6771. return r;
  6772. }
  6773. /* ---- inline SVG ----
  6774. *
  6775. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  6776. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  6777. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  6778. * opacity and solid paint; a gradient paints the average of its stops) and
  6779. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  6780. #define SVG_CACHE_MAX 48
  6781. #define SVG_CACHE_PIXELS (640 * 1024)
  6782. #define SVG_MAX_POINTS 24576
  6783. struct svg_cache_ent {
  6784. unsigned int node;
  6785. int w, h;
  6786. unsigned short *px;
  6787. unsigned char *a;
  6788. unsigned int stamp;
  6789. };
  6790. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  6791. static unsigned int svg_cache_pixels, svg_cache_clock;
  6792. static struct svgr svg_geom;
  6793. static void *svg_geom_buf;
  6794. /* Current viewport in user units: percentage lengths resolve against it
  6795. * (the viewBox size, not the device pixels). */
  6796. static double svg_vp_w = 300, svg_vp_h = 150;
  6797. /* The layers live in the page heap: forget them before heap_reset(). */
  6798. static void svg_cache_clear(void)
  6799. {
  6800. memset(svg_cache, 0, sizeof(svg_cache));
  6801. svg_cache_pixels = 0;
  6802. svg_geom_buf = 0;
  6803. }
  6804. static int svg_name_is(const char *a, const char *b)
  6805. {
  6806. while (*a && *b) {
  6807. char x = *a, y = *b;
  6808. if (x >= 'A' && x <= 'Z')
  6809. x = (char)(x - 'A' + 'a');
  6810. if (x != y)
  6811. return 0;
  6812. a++;
  6813. b++;
  6814. }
  6815. return *a == *b;
  6816. }
  6817. static const char *svg_elem_name(unsigned int node)
  6818. {
  6819. const struct br_node *nd = &doc.nodes[node];
  6820. if (nd->name_off)
  6821. return doc.attrs + nd->name_off;
  6822. return br_tag_name(nd->tag);
  6823. }
  6824. /* A numeric attribute; a percentage resolves against `base`. */
  6825. static double svg_attr_num(unsigned int node, const char *name, double def,
  6826. double base)
  6827. {
  6828. const char *v = br_find_attr(&doc, node, name);
  6829. const char *p = v;
  6830. int ok = 0;
  6831. double x;
  6832. if (!v)
  6833. return def;
  6834. x = svgr_num(&p, &ok);
  6835. if (!ok)
  6836. return def;
  6837. if (*p == '%')
  6838. x = x * base / 100.0;
  6839. return x;
  6840. }
  6841. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  6842. static int svg_viewbox4(unsigned int node, double vb[4])
  6843. {
  6844. const char *v = br_find_attr(&doc, node, "viewbox");
  6845. const char *p = v;
  6846. int i, ok = 1;
  6847. if (!v)
  6848. return 0;
  6849. for (i = 0; i < 4 && ok; i++)
  6850. vb[i] = svgr_num(&p, &ok);
  6851. return ok && vb[2] > 0 && vb[3] > 0;
  6852. }
  6853. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  6854. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  6855. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  6856. double w, double h, double m[6])
  6857. {
  6858. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  6859. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  6860. int ax = 1, ay = 1;
  6861. if (par && contains_ci(par, "none")) {
  6862. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  6863. m[4] = -vb[0] * sx;
  6864. m[5] = -vb[1] * sy;
  6865. return;
  6866. }
  6867. if (par) {
  6868. if (contains_ci(par, "xmin"))
  6869. ax = 0;
  6870. else if (contains_ci(par, "xmax"))
  6871. ax = 2;
  6872. if (contains_ci(par, "ymin"))
  6873. ay = 0;
  6874. else if (contains_ci(par, "ymax"))
  6875. ay = 2;
  6876. }
  6877. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  6878. (sx < sy ? sx : sy);
  6879. tx = (w - vb[2] * s) * ax / 2.0;
  6880. ty = (h - vb[3] * s) * ay / 2.0;
  6881. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  6882. m[4] = tx - vb[0] * s;
  6883. m[5] = ty - vb[1] * s;
  6884. }
  6885. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  6886. * the paint attribute, then average the gradient's stops. */
  6887. static int svg_url_paint(unsigned int node, const char *attr,
  6888. unsigned short *color, unsigned int *alpha)
  6889. {
  6890. const char *v = 0, *h;
  6891. char id[64];
  6892. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  6893. for (k = 0; node && k < 32 && !v; k++) {
  6894. v = br_find_attr(&doc, node, attr);
  6895. if (!v) {
  6896. const char *style = br_find_attr(&doc, node, "style");
  6897. if (style && contains_ci(style, "url(#"))
  6898. v = strstr(style, "url(#");
  6899. }
  6900. if (v && !contains_ci(v, "url("))
  6901. v = 0;
  6902. node = doc.nodes[node].parent;
  6903. }
  6904. if (!v || !(h = strstr(v, "#")))
  6905. return 0;
  6906. h++;
  6907. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  6908. id[n++] = *h++;
  6909. id[n] = '\0';
  6910. g = br_find_id(&doc, id);
  6911. /* Follow href chains (a gradient that only references another one's
  6912. * stops), at most a few hops. */
  6913. for (k = 0; g && k < 4; k++) {
  6914. unsigned int gi = g - 1;
  6915. const char *ref;
  6916. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  6917. const char *nm, *sc, *so;
  6918. unsigned short col = 0;
  6919. double op = 1;
  6920. if (doc.nodes[c].type != BR_NODE_ELEM)
  6921. continue;
  6922. nm = svg_elem_name(c);
  6923. if (!svg_name_is(nm, "stop"))
  6924. continue;
  6925. sc = br_find_attr(&doc, c, "stop-color");
  6926. so = br_find_attr(&doc, c, "stop-opacity");
  6927. {
  6928. const char *st = br_find_attr(&doc, c, "style");
  6929. const char *q;
  6930. if (st && (q = strstr(st, "stop-color:")) != 0)
  6931. sc = q + 11;
  6932. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  6933. so = q + 13;
  6934. }
  6935. if (sc) {
  6936. unsigned int L = 0;
  6937. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  6938. L++;
  6939. if (!br_parse_color(sc, L, &col))
  6940. col = 0;
  6941. }
  6942. if (so) {
  6943. const char *p = so;
  6944. int ok = 0;
  6945. double x = svgr_num(&p, &ok);
  6946. if (ok)
  6947. op = x < 0 ? 0 : x > 1 ? 1 : x;
  6948. }
  6949. sr += (col >> 11) & 31;
  6950. sg += (col >> 5) & 63;
  6951. sb += col & 31;
  6952. sa += (unsigned int)(op * 255);
  6953. cnt++;
  6954. }
  6955. if (cnt)
  6956. break;
  6957. ref = br_find_attr(&doc, gi, "href");
  6958. if (!ref)
  6959. ref = br_find_attr(&doc, gi, "xlink:href");
  6960. if (!ref || ref[0] != '#')
  6961. break;
  6962. g = br_find_id(&doc, ref + 1);
  6963. }
  6964. if (!cnt)
  6965. return 0;
  6966. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  6967. (sb / cnt));
  6968. *alpha = sa / cnt;
  6969. return 1;
  6970. }
  6971. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  6972. unsigned short *color, unsigned int *alpha)
  6973. {
  6974. int mode = fill ? st->fill_mode : st->stroke_mode;
  6975. const char *op = br_find_attr(&doc, node,
  6976. fill ? "fill-opacity" : "stroke-opacity");
  6977. *alpha = 255;
  6978. switch (mode) {
  6979. case BR_PAINT_UNSET:
  6980. if (!fill)
  6981. return 0;
  6982. *color = 0;
  6983. break;
  6984. case BR_PAINT_COLOR:
  6985. *color = fill ? st->fill : st->stroke;
  6986. break;
  6987. case BR_PAINT_CURRENT:
  6988. *color = st->color;
  6989. break;
  6990. case BR_PAINT_URL:
  6991. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  6992. alpha))
  6993. return 0;
  6994. break;
  6995. default:
  6996. return 0;
  6997. }
  6998. if (op) {
  6999. const char *p = op;
  7000. int ok = 0;
  7001. double x = svgr_num(&p, &ok);
  7002. if (ok)
  7003. *alpha = (unsigned int)(*alpha *
  7004. (x < 0 ? 0 : x > 1 ? 1 : x));
  7005. }
  7006. return *alpha > 0;
  7007. }
  7008. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7009. const double m[6], const struct br_style *pst,
  7010. unsigned int alpha, int depth);
  7011. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  7012. const double m[6], const struct br_style *st,
  7013. unsigned int alpha, int depth)
  7014. {
  7015. unsigned int c;
  7016. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  7017. if (doc.nodes[c].type == BR_NODE_ELEM)
  7018. svg_draw_node(L, c, m, st, alpha, depth + 1);
  7019. }
  7020. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7021. const double pm[6], const struct br_style *pst,
  7022. unsigned int alpha, int depth)
  7023. {
  7024. struct br_style st;
  7025. const char *nm = svg_elem_name(node);
  7026. const char *tf;
  7027. double m[6];
  7028. unsigned short color;
  7029. unsigned int pa;
  7030. int shape = 0, fillable = 1;
  7031. if (depth > 24 || !nm)
  7032. return;
  7033. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  7034. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  7035. svg_name_is(nm, "lineargradient") ||
  7036. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  7037. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  7038. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  7039. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  7040. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  7041. svg_name_is(nm, "foreignobject"))
  7042. return;
  7043. br_style_for(&doc, node, pst, &st);
  7044. if (st.display == BR_DISPLAY_NONE)
  7045. return;
  7046. memcpy(m, pm, sizeof(m));
  7047. tf = br_find_attr(&doc, node, "transform");
  7048. if (tf)
  7049. svgr_transform(m, tf);
  7050. {
  7051. const char *op = br_find_attr(&doc, node, "opacity");
  7052. if (op) {
  7053. const char *p = op;
  7054. int ok = 0;
  7055. double x = svgr_num(&p, &ok);
  7056. if (ok)
  7057. alpha = (unsigned int)(alpha *
  7058. (x < 0 ? 0 :
  7059. x > 1 ? 1 : x));
  7060. }
  7061. }
  7062. if (!alpha)
  7063. return;
  7064. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  7065. svg_name_is(nm, "switch")) {
  7066. svg_draw_children(L, node, m, &st, alpha, depth);
  7067. return;
  7068. }
  7069. if (svg_name_is(nm, "svg")) {
  7070. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  7071. y = svg_attr_num(node, "y", 0, 0);
  7072. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7073. t[4] = x;
  7074. t[5] = y;
  7075. svgr_mat_mul(m, m, t);
  7076. double ow = svg_vp_w, oh = svg_vp_h;
  7077. if (svg_viewbox4(node, vb)) {
  7078. double w = svg_attr_num(node, "width", vb[2], ow);
  7079. double h = svg_attr_num(node, "height", vb[3], oh);
  7080. double vm[6];
  7081. svg_viewport_matrix(node, vb, w, h, vm);
  7082. svgr_mat_mul(m, m, vm);
  7083. svg_vp_w = vb[2];
  7084. svg_vp_h = vb[3];
  7085. }
  7086. svg_draw_children(L, node, m, &st, alpha, depth);
  7087. svg_vp_w = ow;
  7088. svg_vp_h = oh;
  7089. return;
  7090. }
  7091. if (svg_name_is(nm, "use")) {
  7092. const char *ref = br_find_attr(&doc, node, "href");
  7093. unsigned int tgt;
  7094. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7095. if (!ref)
  7096. ref = br_find_attr(&doc, node, "xlink:href");
  7097. if (!ref || ref[0] != '#')
  7098. return;
  7099. tgt = br_find_id(&doc, ref + 1);
  7100. if (!tgt || tgt - 1 == node)
  7101. return;
  7102. tgt--;
  7103. t[4] = svg_attr_num(node, "x", 0, 0);
  7104. t[5] = svg_attr_num(node, "y", 0, 0);
  7105. svgr_mat_mul(m, m, t);
  7106. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  7107. double vb[4];
  7108. double ow = svg_vp_w, oh = svg_vp_h;
  7109. if (svg_viewbox4(tgt, vb)) {
  7110. double w = svg_attr_num(node, "width", vb[2],
  7111. ow);
  7112. double h = svg_attr_num(node, "height", vb[3],
  7113. oh);
  7114. double vm[6];
  7115. svg_viewport_matrix(tgt, vb, w, h, vm);
  7116. svgr_mat_mul(m, m, vm);
  7117. svg_vp_w = vb[2];
  7118. svg_vp_h = vb[3];
  7119. }
  7120. svg_draw_children(L, tgt, m, &st, alpha, depth);
  7121. svg_vp_w = ow;
  7122. svg_vp_h = oh;
  7123. } else {
  7124. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  7125. }
  7126. return;
  7127. }
  7128. svgr_reset(&svg_geom, m);
  7129. if (svg_name_is(nm, "path")) {
  7130. const char *d = br_find_attr(&doc, node, "d");
  7131. if (d) {
  7132. svgr_path(&svg_geom, d);
  7133. shape = 1;
  7134. }
  7135. } else if (svg_name_is(nm, "rect")) {
  7136. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  7137. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  7138. double rx = svg_attr_num(node, "rx", -1, w);
  7139. double ry = svg_attr_num(node, "ry", -1, h);
  7140. if (rx < 0)
  7141. rx = ry < 0 ? 0 : ry;
  7142. if (ry < 0)
  7143. ry = rx;
  7144. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  7145. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  7146. shape = 1;
  7147. } else if (svg_name_is(nm, "circle")) {
  7148. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  7149. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7150. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  7151. shape = 1;
  7152. } else if (svg_name_is(nm, "ellipse")) {
  7153. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7154. svg_attr_num(node, "cy", 0, svg_vp_h),
  7155. svg_attr_num(node, "rx", 0, svg_vp_w),
  7156. svg_attr_num(node, "ry", 0, svg_vp_h));
  7157. shape = 1;
  7158. } else if (svg_name_is(nm, "line")) {
  7159. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  7160. svg_attr_num(node, "y1", 0, svg_vp_h));
  7161. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  7162. svg_attr_num(node, "y2", 0, svg_vp_h));
  7163. shape = 1;
  7164. fillable = 0;
  7165. } else if (svg_name_is(nm, "polyline") ||
  7166. svg_name_is(nm, "polygon")) {
  7167. const char *pts = br_find_attr(&doc, node, "points");
  7168. if (pts) {
  7169. svgr_points(&svg_geom, pts,
  7170. svg_name_is(nm, "polygon"));
  7171. shape = 1;
  7172. }
  7173. }
  7174. if (!shape)
  7175. return;
  7176. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  7177. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  7178. st.fill_evenodd);
  7179. if (svg_paint(node, &st, 0, &color, &pa)) {
  7180. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  7181. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7182. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  7183. }
  7184. }
  7185. /* <text> elements: drawn straight onto the page every frame (the glyph
  7186. * renderer targets the ngui canvas, not a layer). x/y map through the
  7187. * accumulated transform; the font size scales with it. */
  7188. static void svg_draw_text(struct ngui *ui, unsigned int node,
  7189. const double pm[6], const struct br_style *pst,
  7190. int ox, int oy, int depth)
  7191. {
  7192. unsigned int c;
  7193. if (depth > 24)
  7194. return;
  7195. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7196. struct br_style st;
  7197. const char *nm, *tf;
  7198. double m[6];
  7199. if (doc.nodes[c].type != BR_NODE_ELEM)
  7200. continue;
  7201. nm = svg_elem_name(c);
  7202. if (!nm || svg_name_is(nm, "defs") ||
  7203. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  7204. svg_name_is(nm, "clippath"))
  7205. continue;
  7206. br_style_for(&doc, c, pst, &st);
  7207. if (st.display == BR_DISPLAY_NONE)
  7208. continue;
  7209. memcpy(m, pm, sizeof(m));
  7210. tf = br_find_attr(&doc, c, "transform");
  7211. if (tf)
  7212. svgr_transform(m, tf);
  7213. if (svg_name_is(nm, "text")) {
  7214. unsigned int t = doc.nodes[c].first;
  7215. const char *s;
  7216. unsigned int n, tw;
  7217. double x = svg_attr_num(c, "x", 0, 0),
  7218. y = svg_attr_num(c, "y", 0, 0);
  7219. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7220. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  7221. int tx, ty, anchor;
  7222. unsigned short col;
  7223. unsigned int pa;
  7224. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  7225. continue;
  7226. if (px < 6)
  7227. px = 6;
  7228. if (px > 72)
  7229. px = 72;
  7230. if (!svg_paint(c, &st, 1, &col, &pa))
  7231. continue;
  7232. s = doc.text + doc.nodes[t].text_off;
  7233. n = doc.nodes[t].text_len;
  7234. st.font_px = (unsigned char)px;
  7235. tw = face_text_width(ui, &st, s, n);
  7236. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  7237. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  7238. ngui_text_ascent_face(ui, style_face(&st), px,
  7239. st.mono);
  7240. anchor = st.align;
  7241. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  7242. anchor = BR_ALIGN_CENTER;
  7243. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  7244. anchor = BR_ALIGN_RIGHT;
  7245. if (anchor == BR_ALIGN_CENTER)
  7246. tx -= (int)tw / 2;
  7247. else if (anchor == BR_ALIGN_RIGHT)
  7248. tx -= (int)tw;
  7249. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  7250. col, px, st.bold, st.italic,
  7251. st.mono);
  7252. } else {
  7253. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  7254. }
  7255. }
  7256. }
  7257. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  7258. {
  7259. double vb[4];
  7260. if (svg_viewbox4(node, vb)) {
  7261. svg_viewport_matrix(node, vb, w, h, m);
  7262. } else {
  7263. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  7264. }
  7265. }
  7266. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  7267. const struct br_style *st)
  7268. {
  7269. struct svg_cache_ent *e = 0;
  7270. struct svgr_layer L;
  7271. double m[6];
  7272. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  7273. svg_cache_clock++;
  7274. for (i = 0; i < SVG_CACHE_MAX; i++)
  7275. if (svg_cache[i].px && svg_cache[i].node == node &&
  7276. svg_cache[i].w == w && svg_cache[i].h == h) {
  7277. svg_cache[i].stamp = svg_cache_clock;
  7278. return &svg_cache[i];
  7279. }
  7280. if (need > SVG_CACHE_PIXELS)
  7281. return 0;
  7282. /* Evict least recently used layers until this one fits. */
  7283. for (;;) {
  7284. struct svg_cache_ent *lru = 0, *free_slot = 0;
  7285. for (i = 0; i < SVG_CACHE_MAX; i++) {
  7286. if (!svg_cache[i].px) {
  7287. if (!free_slot)
  7288. free_slot = &svg_cache[i];
  7289. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  7290. lru = &svg_cache[i];
  7291. }
  7292. }
  7293. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  7294. e = free_slot;
  7295. break;
  7296. }
  7297. if (!lru)
  7298. return 0;
  7299. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  7300. free(lru->px);
  7301. free(lru->a);
  7302. memset(lru, 0, sizeof(*lru));
  7303. }
  7304. if (!svg_geom_buf) {
  7305. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7306. if (!svg_geom_buf)
  7307. return 0;
  7308. }
  7309. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  7310. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  7311. e->a = (unsigned char *)calloc(need, 1);
  7312. if (!e->px || !e->a) {
  7313. free(e->px);
  7314. free(e->a);
  7315. memset(e, 0, sizeof(*e));
  7316. return 0;
  7317. }
  7318. e->node = node;
  7319. e->w = w;
  7320. e->h = h;
  7321. e->stamp = svg_cache_clock;
  7322. svg_cache_pixels += need;
  7323. L.px = e->px;
  7324. L.a = e->a;
  7325. L.w = w;
  7326. L.h = h;
  7327. svg_root_matrix(node, w, h, m);
  7328. {
  7329. double vb[4];
  7330. if (svg_viewbox4(node, vb)) {
  7331. svg_vp_w = vb[2];
  7332. svg_vp_h = vb[3];
  7333. } else {
  7334. svg_vp_w = w;
  7335. svg_vp_h = h;
  7336. }
  7337. }
  7338. svg_draw_children(&L, node, m, st, 255, 0);
  7339. return e;
  7340. }
  7341. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  7342. *
  7343. * The markup is parsed into a detached subtree of the page document and
  7344. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  7345. * bitmap, which then behaves like any decoded image. currentColor is
  7346. * black (an image has no inherited text colour); <text> is not drawn. */
  7347. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  7348. {
  7349. unsigned int i = 0;
  7350. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  7351. i = 3;
  7352. while (i < len) {
  7353. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  7354. d[i] == '\r' || d[i] == '\n'))
  7355. i++;
  7356. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  7357. return 1;
  7358. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  7359. i += 4;
  7360. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  7361. i++;
  7362. i += 3;
  7363. continue;
  7364. }
  7365. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  7366. while (i < len && d[i] != '>')
  7367. i++;
  7368. i++;
  7369. continue;
  7370. }
  7371. return 0;
  7372. }
  7373. return 0;
  7374. }
  7375. static int svg_len_attr(unsigned int node, const char *name)
  7376. {
  7377. const char *v = br_find_attr(&doc, node, name);
  7378. int n = 0, any = 0;
  7379. if (!v)
  7380. return 0;
  7381. while (*v == ' ')
  7382. v++;
  7383. while (*v >= '0' && *v <= '9') {
  7384. n = n * 10 + (*v++ - '0');
  7385. any = 1;
  7386. }
  7387. if (*v == '.')
  7388. while (*++v >= '0' && *v <= '9')
  7389. ;
  7390. if (!any || *v == '%')
  7391. return 0;
  7392. return n;
  7393. }
  7394. static int svg_decode_image(const unsigned char *data, unsigned int len,
  7395. struct br_image *bi, int box_w, int box_h)
  7396. {
  7397. unsigned int holder, svg = 0, c, need, i;
  7398. struct br_style base = base_style(), st;
  7399. struct svgr_layer L;
  7400. double vb[4], m[6];
  7401. int w, h, have_vb, nat_w, nat_h;
  7402. holder = br_create_element(&doc, "div", 3);
  7403. if (!holder) {
  7404. s_copy(bi->err, "page is full", sizeof(bi->err));
  7405. return -1;
  7406. }
  7407. holder--;
  7408. br_set_inner_html(&doc, holder, (const char *)data, len);
  7409. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  7410. if (doc.nodes[c].type == BR_NODE_ELEM &&
  7411. doc.nodes[c].tag == BR_TAG_SVG) {
  7412. svg = c;
  7413. break;
  7414. }
  7415. if (!svg) {
  7416. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  7417. return -1;
  7418. }
  7419. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  7420. w = svg_len_attr(svg, "width");
  7421. h = svg_len_attr(svg, "height");
  7422. if (box_w > 0 && box_h > 0) {
  7423. w = box_w;
  7424. h = box_h;
  7425. } else if (!w && !h) {
  7426. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  7427. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  7428. } else if (!w) {
  7429. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  7430. } else if (!h) {
  7431. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  7432. }
  7433. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  7434. * so CSS scaling stays crisp. */
  7435. nat_w = w;
  7436. nat_h = h;
  7437. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  7438. w *= 2;
  7439. h *= 2;
  7440. }
  7441. if (w > BR_IMG_LAYOUT_W) {
  7442. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  7443. w = BR_IMG_LAYOUT_W;
  7444. }
  7445. if (h > 2048)
  7446. h = 2048;
  7447. if (w < 1)
  7448. w = 1;
  7449. if (h < 1)
  7450. h = 1;
  7451. need = (unsigned int)w * (unsigned int)h;
  7452. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  7453. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  7454. return -1;
  7455. }
  7456. if (!svg_geom_buf) {
  7457. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7458. if (!svg_geom_buf) {
  7459. s_copy(bi->err, "out of memory", sizeof(bi->err));
  7460. return -1;
  7461. }
  7462. }
  7463. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  7464. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  7465. L.a = (unsigned char *)calloc(need, 1);
  7466. if (!L.px || !L.a) {
  7467. free(L.px);
  7468. free(L.a);
  7469. s_copy(bi->err, "out of memory", sizeof(bi->err));
  7470. return -1;
  7471. }
  7472. for (i = 0; i < need; i++)
  7473. L.px[i] = 0xFFFF;
  7474. L.w = w;
  7475. L.h = h;
  7476. base.color = 0x0000;
  7477. br_style_for(&doc, svg, &base, &st);
  7478. svg_root_matrix(svg, w, h, m);
  7479. svg_vp_w = have_vb ? vb[2] : w;
  7480. svg_vp_h = have_vb ? vb[3] : h;
  7481. svg_draw_children(&L, svg, m, &st, 255, 0);
  7482. bi->native_w = nat_w;
  7483. bi->native_h = nat_h;
  7484. bi->img.format = 0;
  7485. bi->img.w = (unsigned int)w;
  7486. bi->img.h = (unsigned int)h;
  7487. bi->img.px = L.px;
  7488. bi->img.alpha = L.a;
  7489. bi->img.flags = 0;
  7490. bi->state = 1;
  7491. image_pixels += need;
  7492. return 0;
  7493. }
  7494. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  7495. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  7496. int *out_w, int *out_h)
  7497. {
  7498. double vb[4];
  7499. int has_vb = svg_viewbox4(node, vb);
  7500. double aw = svg_attr_num(node, "width", -1, cw);
  7501. double ah = svg_attr_num(node, "height", -1, 0);
  7502. int w, h;
  7503. if (st->width_kind)
  7504. w = cw;
  7505. else if (aw > 0)
  7506. w = (int)(aw + 0.5);
  7507. else if (st->height_kind == 1 && has_vb)
  7508. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  7509. else if (ah > 0 && has_vb)
  7510. w = (int)(ah * vb[2] / vb[3] + 0.5);
  7511. else if (has_vb)
  7512. w = cw;
  7513. else
  7514. w = 300;
  7515. if (st->max_width_kind == 1 && w > st->max_width)
  7516. w = st->max_width;
  7517. if (w > cw && cw > 0 && !(aw > 0))
  7518. w = cw;
  7519. if (w < 1)
  7520. w = 1;
  7521. if (w > 2000)
  7522. w = 2000;
  7523. if (st->height_kind == 1)
  7524. h = st->height;
  7525. else if (ah > 0)
  7526. h = (int)(ah + 0.5);
  7527. else if (has_vb)
  7528. h = (int)(w * vb[3] / vb[2] + 0.5);
  7529. else
  7530. h = 150;
  7531. if (h < 1)
  7532. h = 1;
  7533. if (h > 1400)
  7534. h = 1400;
  7535. *out_w = w;
  7536. *out_h = h;
  7537. }
  7538. static void svg_paint_box(struct ngui *ui, unsigned int node,
  7539. const struct br_style *st, int x, int y, int w, int h)
  7540. {
  7541. struct svg_cache_ent *e;
  7542. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  7543. int cx0, cy0, cx1, cy1, px, py;
  7544. double m[6];
  7545. if (ui->nclip > 0)
  7546. clip = ui->clip[ui->nclip - 1];
  7547. cx0 = r.x > clip.x ? r.x : clip.x;
  7548. cy0 = r.y > clip.y ? r.y : clip.y;
  7549. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  7550. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  7551. if (cx0 >= cx1 || cy0 >= cy1)
  7552. return;
  7553. e = svg_layer(node, w, h, st);
  7554. if (e) {
  7555. for (py = cy0; py < cy1; py++) {
  7556. unsigned int srow = (unsigned int)(py - y) *
  7557. (unsigned int)w;
  7558. unsigned short *dst = ui->px + py * ui->w;
  7559. for (px = cx0; px < cx1; px++) {
  7560. unsigned int si = srow + (unsigned int)(px - x);
  7561. unsigned int a = e->a[si];
  7562. if (!a)
  7563. continue;
  7564. dst[px] = a >= 255 ? e->px[si] :
  7565. blend_rgb565(dst[px], e->px[si], a);
  7566. }
  7567. }
  7568. }
  7569. svg_root_matrix(node, w, h, m);
  7570. ngui_push_clip(ui, r);
  7571. svg_draw_text(ui, node, m, st, x, y, 0);
  7572. ngui_pop_clip(ui);
  7573. }
  7574. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  7575. * keep using add_image_run(); this covers the CSS `position:absolute;
  7576. * width:100%` poster pattern used by news sites. */
  7577. static void image_block_size(unsigned int node, const struct br_style *st,
  7578. int cbw, int *out_w, int *out_h)
  7579. {
  7580. struct br_node *nd = &doc.nodes[node];
  7581. int idx = nd->img_index;
  7582. int iw = 0, ih = 0, w, h, aw, ah;
  7583. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  7584. iw = (int)images[idx].img.w;
  7585. ih = (int)images[idx].img.h;
  7586. if (iw <= 0 || ih <= 0) {
  7587. iw = (int)images[idx].native_w;
  7588. ih = (int)images[idx].native_h;
  7589. }
  7590. }
  7591. if (st->width_kind)
  7592. w = style_width_px(st, cbw);
  7593. else if (nd->width_attr)
  7594. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  7595. (int)nd->width_attr;
  7596. else if (nd->height_attr && !nd->height_pct && iw && ih)
  7597. w = iw * (int)nd->height_attr / ih;
  7598. else if (iw)
  7599. w = iw;
  7600. else
  7601. w = 64;
  7602. /* max-width/min-width against the containing block: Tailwind's
  7603. * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
  7604. * 300x300 thumbnail to its 75 px avatar box. */
  7605. if (st->max_width_kind) {
  7606. int mw = st->max_width_kind == 3 ?
  7607. cbw * st->max_width_calc_pct / 100 +
  7608. st->max_width_calc_px :
  7609. st->max_width_kind == 2 ?
  7610. cbw * (int)st->max_width / 100 : (int)st->max_width;
  7611. if (mw > 0 && w > mw)
  7612. w = mw;
  7613. }
  7614. if (st->min_width_kind) {
  7615. int mn = st->min_width_kind == 3 ?
  7616. cbw * st->min_width_calc_pct / 100 +
  7617. st->min_width_calc_px :
  7618. st->min_width_kind == 2 ?
  7619. cbw * (int)st->min_width / 100 : (int)st->min_width;
  7620. if (mn > w)
  7621. w = mn;
  7622. }
  7623. if (w < 8)
  7624. w = 8;
  7625. if (cbw > 0 && w > cbw)
  7626. w = cbw;
  7627. /* Without a CSS height the attributes (or the bitmap) only give the
  7628. * aspect ratio: a width clamped by max-width scales the height too,
  7629. * instead of letterboxing the image into its attribute height. */
  7630. aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
  7631. ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
  7632. if (st->height_kind)
  7633. h = style_height_px(st, cbw);
  7634. else if (aw > 0 && ah > 0)
  7635. h = w * ah / aw;
  7636. else if (nd->height_attr)
  7637. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  7638. (int)nd->height_attr;
  7639. else
  7640. h = 64;
  7641. if (h < 8)
  7642. h = 8;
  7643. *out_w = w;
  7644. *out_h = h;
  7645. }
  7646. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  7647. int dw, int dh)
  7648. {
  7649. int idx = doc.nodes[node].img_index;
  7650. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  7651. struct img_image *src = image_display_get(&images[idx], dw, dh);
  7652. struct img_blit b;
  7653. if (!src)
  7654. src = &images[idx].img;
  7655. b.dst = l->ui->px;
  7656. b.dst_w = l->ui->w;
  7657. b.dst_h = l->ui->h;
  7658. b.clip_x = page_rect.x;
  7659. b.clip_y = page_rect.y;
  7660. b.clip_w = page_rect.w - 12;
  7661. b.clip_h = page_rect.h;
  7662. b.x = x;
  7663. b.y = y;
  7664. b.scale = ((unsigned int)dw << 16) / src->w;
  7665. b.bg = ui.theme.bg;
  7666. b.bg2 = ui.theme.bg;
  7667. b.dst_a = 0;
  7668. /* OVER_DST is only needed for an alpha source; an opaque one can
  7669. * take img_draw's 1:1 copy path. */
  7670. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  7671. img_draw(src, &b);
  7672. } else if (l->draw) {
  7673. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  7674. 0xD69A);
  7675. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  7676. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  7677. }
  7678. }
  7679. static void layout_block(struct lay *l, unsigned int node,
  7680. const struct br_style *st, int depth,
  7681. unsigned short link)
  7682. {
  7683. int old_left = l->left, old_right = l->right, old_align = l->align;
  7684. int parent_cb_h = l->cb_h;
  7685. int saved_parent_top = l->parent_top;
  7686. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  7687. int saved_cb_top = l->cb_top;
  7688. int top, l0, r0;
  7689. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  7690. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  7691. int deco_w, deco_h, content_w, content_h, box_h;
  7692. int img_dh = 0;
  7693. int definite_w = 0;
  7694. int normal_top = 0;
  7695. int rel_dx = 0, rel_dy = 0;
  7696. int clip_pushed = 0;
  7697. struct ngui_rect clip_rect;
  7698. /* A DOM level costs about two depth units (layout_block ->
  7699. * layout_children), so 48 covers a ~24-level page. Real news pages
  7700. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  7701. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  7702. return;
  7703. flow_y = l->y;
  7704. flow_left = l->left;
  7705. flow_right = l->right;
  7706. positioned = st->pos == 1 || st->pos == 2;
  7707. relative = st->pos == 3;
  7708. sticky = st->pos == 4;
  7709. shifted = relative || sticky || st->transform_set;
  7710. if (positioned) {
  7711. int def_w = st->width_kind == 1 ? st->width : -1;
  7712. if (st->pos == 2) {
  7713. int avail_w = page_rect.w - 12;
  7714. if (st->right_set && def_w >= 0)
  7715. l->left = page_rect.x + avail_w - st->right -
  7716. def_w;
  7717. else
  7718. l->left = page_rect.x +
  7719. (st->left_set ? st->left : 0);
  7720. l->right = def_w >= 0 ? l->left + def_w :
  7721. page_rect.x + avail_w;
  7722. if (st->bottom_set && st->height_kind)
  7723. l->y = page_rect.y + page_rect.h -
  7724. st->bottom -
  7725. style_height_px(st, page_rect.w);
  7726. else
  7727. l->y = page_rect.y +
  7728. (st->top_set ? st->top : 0);
  7729. } else {
  7730. int left = flow_left + (st->left_set ? st->left : 0);
  7731. unsigned int parent = doc.nodes[node].parent;
  7732. if (st->right_set && def_w >= 0)
  7733. left = flow_right - st->right - def_w;
  7734. l->left = left;
  7735. l->right = def_w >= 0 ? left + def_w :
  7736. flow_right +
  7737. (st->left_set ? st->left : 0);
  7738. l->y = flow_y + (st->top_set ? st->top : 0);
  7739. if (st->bottom_set && st->height_kind &&
  7740. parent < BR_MAX_NODES && block_h[parent] > 0)
  7741. l->y = flow_y + block_h[parent] - st->bottom -
  7742. style_height_px(st, old_right - old_left);
  7743. }
  7744. old_left = l->left;
  7745. old_right = l->right;
  7746. } else if (relative) {
  7747. rel_dx = st->left_set ? st->left :
  7748. (st->right_set ? -st->right : 0);
  7749. rel_dy = st->top_set ? st->top :
  7750. (st->bottom_set ? -st->bottom : 0);
  7751. }
  7752. if (st->transform_set) {
  7753. rel_dx += st->tx;
  7754. rel_dy += st->ty;
  7755. }
  7756. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  7757. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  7758. doc.nodes[node].tag == BR_TAG_SELECT ||
  7759. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  7760. !button_has_elements(node)) {
  7761. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  7762. s_eq(br_type(&doc, node), "hidden"))
  7763. return;
  7764. /* Reached as a block-level box (a flex item): the control
  7765. * fills the box the caller assigned, and its line is flushed
  7766. * here; flex layout resets the run list for the next item, so
  7767. * a queued run would never be drawn. */
  7768. form_fill_line = 1;
  7769. add_form_run(l, node, st, link);
  7770. form_fill_line = 0;
  7771. flush_line(l);
  7772. return;
  7773. }
  7774. flush_line(l);
  7775. cbw = old_right - old_left;
  7776. if (cbw < 8)
  7777. cbw = 8;
  7778. l->y += mp_px(st, 0, cbw);
  7779. top = l->y;
  7780. ml = mp_px(st, 3, cbw);
  7781. mr = mp_px(st, 1, cbw);
  7782. bl = st->border_w[3];
  7783. br = st->border_w[1];
  7784. pl = mp_px(st, 7, cbw);
  7785. pr = mp_px(st, 5, cbw);
  7786. bt = st->border_w[0];
  7787. bb = st->border_w[2];
  7788. pt = mp_px(st, 4, cbw);
  7789. pb = mp_px(st, 6, cbw);
  7790. deco_w = bl + br + pl + pr;
  7791. deco_h = bt + bb + pt + pb;
  7792. if (st->width_kind) {
  7793. int w;
  7794. if (st->width_kind == 3)
  7795. w = cbw * st->width_calc_pct / 100 +
  7796. st->width_calc_px;
  7797. else
  7798. w = css_size(st->width_kind, st->width, cbw);
  7799. if (w < 0)
  7800. w = 0;
  7801. content_w = st->box_sizing ? w - deco_w : w;
  7802. definite_w = 1;
  7803. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  7804. doc.nodes[node].tag == BR_TAG_TD ||
  7805. doc.nodes[node].tag == BR_TAG_TH) &&
  7806. doc.nodes[node].width_attr) {
  7807. /* Legacy table/cell width attributes: percentages resolve
  7808. * against the containing block, bare numbers are pixels. */
  7809. int w = doc.nodes[node].width_pct ?
  7810. cbw * doc.nodes[node].width_attr / 100 :
  7811. doc.nodes[node].width_attr;
  7812. if (w < 0)
  7813. w = 0;
  7814. content_w = st->box_sizing ? w - deco_w : w;
  7815. definite_w = 1;
  7816. } else {
  7817. content_w = cbw - ml - mr - deco_w;
  7818. }
  7819. if (content_w < 0)
  7820. content_w = 0;
  7821. if (st->max_width_kind) {
  7822. int mw = st->max_width_kind == 3 ?
  7823. cbw * st->max_width_calc_pct / 100 +
  7824. st->max_width_calc_px :
  7825. css_size(st->max_width_kind, st->max_width, cbw);
  7826. int max_box = st->box_sizing ? mw : mw + deco_w;
  7827. /* A clamped auto width is used as the width, so auto
  7828. * margins share the rest (Google's 688 px search box). */
  7829. if (content_w + deco_w > max_box) {
  7830. content_w = max_box - deco_w;
  7831. definite_w = 1;
  7832. }
  7833. }
  7834. if (st->min_width_kind) {
  7835. int mw = st->min_width_kind == 3 ?
  7836. cbw * st->min_width_calc_pct / 100 +
  7837. st->min_width_calc_px :
  7838. css_size(st->min_width_kind, st->min_width, cbw);
  7839. int min_box = st->box_sizing ? mw : mw + deco_w;
  7840. if (content_w + deco_w < min_box) {
  7841. content_w = min_box - deco_w;
  7842. definite_w = 1;
  7843. }
  7844. }
  7845. if (content_w < 8)
  7846. content_w = 8;
  7847. if (definite_w) {
  7848. int free_w = cbw - ml - mr - deco_w - content_w;
  7849. if (free_w < 0)
  7850. free_w = 0;
  7851. if (st->ml_auto && st->mr_auto) {
  7852. ml = free_w / 2;
  7853. mr = free_w - ml;
  7854. } else if (st->ml_auto) {
  7855. ml = free_w;
  7856. } else if (st->mr_auto) {
  7857. mr = free_w;
  7858. }
  7859. }
  7860. if (doc.nodes[node].tag == BR_TAG_IMG) {
  7861. int iw, ih;
  7862. image_block_size(node, st, cbw, &iw, &ih);
  7863. content_w = iw;
  7864. img_dh = ih;
  7865. }
  7866. l0 = old_left + ml;
  7867. r0 = l0 + deco_w + content_w;
  7868. if (r0 < l0 + 8)
  7869. r0 = l0 + 8;
  7870. normal_top = top;
  7871. if (sticky) {
  7872. if (st->top_set) {
  7873. int stick = page_rect.y + 4 + st->top;
  7874. if (normal_top < stick)
  7875. rel_dy += stick - normal_top;
  7876. } else if (st->bottom_set && block_h[node]) {
  7877. int stick = page_rect.y + page_rect.h - st->bottom -
  7878. block_h[node];
  7879. if (normal_top > stick)
  7880. rel_dy += stick - normal_top;
  7881. }
  7882. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  7883. block_h[doc.nodes[node].parent]) {
  7884. unsigned int p = doc.nodes[node].parent;
  7885. int ptop = l->parent_top;
  7886. int pbottom = ptop + block_h[p];
  7887. int eh = block_h[node];
  7888. int moved_top = normal_top + rel_dy;
  7889. int moved_bottom = moved_top + eh;
  7890. if (moved_bottom > pbottom)
  7891. rel_dy -= moved_bottom - pbottom;
  7892. moved_top = normal_top + rel_dy;
  7893. if (moved_top < ptop)
  7894. rel_dy += ptop - moved_top;
  7895. }
  7896. }
  7897. if (shifted && l->draw) {
  7898. top += rel_dy;
  7899. l0 += rel_dx;
  7900. r0 += rel_dx;
  7901. }
  7902. l->parent_top = top;
  7903. if (st->pos != 0) {
  7904. /* Positioned boxes establish the containing block for their
  7905. * absolutely positioned descendants. */
  7906. l->cb_left = l0;
  7907. l->cb_right = r0;
  7908. l->cb_top = top;
  7909. }
  7910. if (l->draw && block_h[node] &&
  7911. top < page_rect.y + page_rect.h &&
  7912. top + block_h[node] > page_rect.y) {
  7913. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  7914. int rtl = css_radius(st, 0, box.w, box.h);
  7915. int rtr = css_radius(st, 1, box.w, box.h);
  7916. int rbr = css_radius(st, 2, box.w, box.h);
  7917. int rbl = css_radius(st, 3, box.w, box.h);
  7918. if (st->transform_scale) {
  7919. if (st->has_bg)
  7920. fill_transformed_rect(l->ui, box, st->bg, st);
  7921. } else if (rtl || rtr || rbr || rbl) {
  7922. if (st->has_bg) {
  7923. int bw = st->border_w[0];
  7924. if (bw > 0 && !st->border_t[0] &&
  7925. st->border_c[0] != st->bg &&
  7926. box.w > bw * 2 && box.h > bw * 2) {
  7927. struct ngui_rect inner = {
  7928. box.x + bw, box.y + bw,
  7929. box.w - bw * 2, box.h - bw * 2
  7930. };
  7931. int itl = rtl > bw ? rtl - bw : 0;
  7932. int itr = rtr > bw ? rtr - bw : 0;
  7933. int ibr = rbr > bw ? rbr - bw : 0;
  7934. int ibl = rbl > bw ? rbl - bw : 0;
  7935. ngui_fill_round_rect(l->ui, box, rtl,
  7936. rtr, rbr, rbl,
  7937. st->border_c[0]);
  7938. ngui_fill_round_rect(l->ui, inner,
  7939. itl, itr, ibr,
  7940. ibl, st->bg);
  7941. } else {
  7942. ngui_fill_round_rect(l->ui, box, rtl,
  7943. rtr, rbr, rbl,
  7944. st->bg);
  7945. }
  7946. } else if (st->border_w[0] && !st->border_t[0]) {
  7947. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  7948. rbl, st->border_w[0],
  7949. st->border_c[0]);
  7950. }
  7951. /* Rounded boxes paint their background image too
  7952. * (app icons are rounded squares), kept inside the
  7953. * corner arcs. */
  7954. if (st->bg_image)
  7955. draw_bg_image_round(l, box, node, st, rtl, rtr,
  7956. rbr, rbl);
  7957. } else {
  7958. if (st->has_bg)
  7959. ngui_fill_rect(l->ui, box, st->bg);
  7960. if (st->bg_image)
  7961. draw_bg_image(l, box, node, st);
  7962. if (st->border_w[0] || st->border_w[1] ||
  7963. st->border_w[2] || st->border_w[3])
  7964. draw_border_box(l->ui, box, st);
  7965. }
  7966. }
  7967. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  7968. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  7969. content_w, img_dh);
  7970. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  7971. l->ui && l->ui->nclip < 4) {
  7972. clip_rect.x = l0 + bl;
  7973. clip_rect.y = top + bt;
  7974. clip_rect.w = (r0 - l0) - bl - br;
  7975. clip_rect.h = (int)block_h[node] - bt - bb;
  7976. if (clip_rect.w > 0 && clip_rect.h > 0) {
  7977. ngui_push_clip(l->ui, clip_rect);
  7978. clip_pushed = 1;
  7979. }
  7980. }
  7981. l->left = l0 + bl + pl;
  7982. l->right = l->left + content_w;
  7983. if (l->right < l->left + 8)
  7984. l->right = l->left + 8;
  7985. l->align = st->align;
  7986. l->line_left = l->left;
  7987. l->line_right = l->right;
  7988. l->y = top + bt + pt;
  7989. if (doc.nodes[node].tag == BR_TAG_HR) {
  7990. if (l->draw)
  7991. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  7992. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  7993. l->y += 8;
  7994. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  7995. int vw = l->right - l->left;
  7996. int vh;
  7997. if (doc.nodes[node].width_pct)
  7998. vw = vw * doc.nodes[node].width_attr / 100;
  7999. else if (doc.nodes[node].width_attr)
  8000. vw = doc.nodes[node].width_attr;
  8001. if (vw > l->right - l->left)
  8002. vw = l->right - l->left;
  8003. if (vw < 8)
  8004. vw = 8;
  8005. vh = vw * 9 / 16;
  8006. if (vh > 240)
  8007. vh = 240;
  8008. if (vh < 80)
  8009. vh = 80;
  8010. if (l->draw) {
  8011. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  8012. vw, vh}, 0xD69A);
  8013. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  8014. vw, vh}, 0x8410);
  8015. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  8016. 0x4208);
  8017. }
  8018. l->y += vh + 4;
  8019. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  8020. int dw, dh, cw = l->right - l->left;
  8021. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  8022. if (l->draw && l->y < page_rect.y + page_rect.h &&
  8023. l->y + dh > page_rect.y)
  8024. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  8025. l->y += dh;
  8026. } else {
  8027. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  8028. !st->no_bullet) {
  8029. char *m = li_marker[node];
  8030. if (!m[0]) {
  8031. unsigned int parent = doc.nodes[node].parent;
  8032. int style = st->list_style;
  8033. int idx = parent ? list_index(parent, node) : 1;
  8034. if (style == BR_LIST_AUTO)
  8035. style = (parent &&
  8036. doc.nodes[parent].tag ==
  8037. BR_TAG_OL) ?
  8038. BR_LIST_DECIMAL : BR_LIST_DISC;
  8039. list_marker_text(m, sizeof(li_marker[node]),
  8040. style, idx);
  8041. }
  8042. if (l->draw && m[0]) {
  8043. int mw = (int)ngui_text_width_ui(l->ui, m);
  8044. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  8045. st->color);
  8046. }
  8047. }
  8048. /* This box's definite content height, for its children's
  8049. * percentage heights. */
  8050. if (doc.nodes[node].tag == BR_TAG_HTML ||
  8051. doc.nodes[node].tag == BR_TAG_BODY)
  8052. l->cb_h = layout_view_h;
  8053. else if (st->height_kind == 1)
  8054. l->cb_h = (int)st->height -
  8055. (st->box_sizing ? deco_h : 0);
  8056. else if (st->height_kind == 2 && parent_cb_h > 0)
  8057. l->cb_h = parent_cb_h * (int)st->height / 100 -
  8058. (st->box_sizing ? deco_h : 0);
  8059. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  8060. l->cb_h = content_w * (int)st->aspect_h /
  8061. (int)st->aspect_w;
  8062. else
  8063. l->cb_h = 0;
  8064. if (l->cb_h < 0)
  8065. l->cb_h = 0;
  8066. if (doc.nodes[node].tag == BR_TAG_TR)
  8067. layout_table_row(l, node, st, depth + 1, link);
  8068. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  8069. table_has_rowspan(node))
  8070. layout_table(l, node, st, depth + 1, link);
  8071. else if (st->grid_auto)
  8072. layout_grid_auto(l, node, st, depth + 1, link);
  8073. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  8074. st->grid_gap > 0)
  8075. layout_grid_children(l, node, st, depth + 1, link);
  8076. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  8077. flex_wants_row(node, st))
  8078. layout_flex_children(l, node, st, depth + 1, link);
  8079. else if (st->display == BR_DISPLAY_FLEX && st->flex_col &&
  8080. st->align_items == 1) {
  8081. /* align-items: center in a column: the items' lines
  8082. * (an app card's icon and label) are centred; a child
  8083. * with its own text-align keeps it. */
  8084. struct br_style cst = *st;
  8085. cst.align = BR_ALIGN_CENTER;
  8086. l->align = BR_ALIGN_CENTER;
  8087. layout_children(l, node, &cst, depth + 1, link);
  8088. } else
  8089. layout_children(l, node, st, depth + 1, link);
  8090. l->cb_h = parent_cb_h;
  8091. }
  8092. flush_line(l);
  8093. if (clip_pushed)
  8094. ngui_pop_clip(l->ui);
  8095. if (l->float_active) {
  8096. if (l->y < l->float_bottom)
  8097. l->y = l->float_bottom;
  8098. l->float_active = 0;
  8099. }
  8100. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8101. content_h = img_dh;
  8102. } else if (st->height_kind == 2 &&
  8103. doc.nodes[node].tag != BR_TAG_HTML &&
  8104. doc.nodes[node].tag != BR_TAG_BODY) {
  8105. /* A percentage of the containing block's definite height, or
  8106. * auto when it has none (it used to resolve against the
  8107. * width). The result is a minimum: without scrollable inner
  8108. * boxes, an app shell's height:100%; overflow:hidden column
  8109. * would otherwise clip everything past the first screen. */
  8110. int auto_h = l->y - (top + bt + pt);
  8111. content_h = parent_cb_h > 0 ?
  8112. parent_cb_h * (int)st->height / 100 -
  8113. (st->box_sizing ? deco_h : 0) : 0;
  8114. if (content_h < auto_h)
  8115. content_h = auto_h;
  8116. } else if (st->height_kind &&
  8117. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8118. doc.nodes[node].tag == BR_TAG_BODY) &&
  8119. st->height_kind == 2)) {
  8120. content_h = style_height_px(st, cbw);
  8121. if (st->box_sizing)
  8122. content_h -= deco_h;
  8123. } else {
  8124. /* Percentage heights on html/body resolve against the
  8125. * viewport, but their content still defines the document
  8126. * scroll height. Treating them as auto avoids collapsing
  8127. * the measured page to the containing block width. */
  8128. content_h = l->y - (top + bt + pt);
  8129. /* aspect-ratio: the preferred height of an auto-height box
  8130. * (Tailwind aspect-video image frames); content can still
  8131. * make it taller, as with min-height: auto. */
  8132. if (st->aspect_w && st->aspect_h && content_w > 0) {
  8133. int ah = content_w * (int)st->aspect_h /
  8134. (int)st->aspect_w;
  8135. if (content_h < ah)
  8136. content_h = ah;
  8137. }
  8138. }
  8139. if (content_h < 0)
  8140. content_h = 0;
  8141. if (st->max_height_kind) {
  8142. int mh = st->max_height_kind == 3 ?
  8143. cbw * st->max_height_calc_pct / 100 +
  8144. st->max_height_calc_px :
  8145. css_size(st->max_height_kind, st->max_height, cbw);
  8146. int max_box = st->box_sizing ? mh : mh + deco_h;
  8147. if (content_h + deco_h > max_box)
  8148. content_h = max_box - deco_h;
  8149. }
  8150. if (st->min_height_kind &&
  8151. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8152. doc.nodes[node].tag == BR_TAG_BODY) &&
  8153. st->min_height_kind == 2)) {
  8154. int mh = st->min_height_kind == 3 ?
  8155. cbw * st->min_height_calc_pct / 100 +
  8156. st->min_height_calc_px :
  8157. css_size(st->min_height_kind, st->min_height, cbw);
  8158. int min_box = st->box_sizing ? mh : mh + deco_h;
  8159. if (content_h + deco_h < min_box)
  8160. content_h = min_box - deco_h;
  8161. }
  8162. if (content_h < 0)
  8163. content_h = 0;
  8164. box_h = deco_h + content_h;
  8165. if (box_h < 0)
  8166. box_h = 0;
  8167. l->y = (shifted ? normal_top : top) + box_h;
  8168. if (node < BR_MAX_NODES) {
  8169. layout_boxes[node].x = l0;
  8170. layout_boxes[node].y = top;
  8171. layout_boxes[node].w = r0 - l0;
  8172. layout_boxes[node].h = box_h;
  8173. layout_boxes[node].valid = r0 > l0;
  8174. }
  8175. l->left = old_left;
  8176. l->right = old_right;
  8177. l->align = old_align;
  8178. l->y += mp_px(st, 2, cbw);
  8179. if (!l->draw) {
  8180. if (box_h > 65535)
  8181. box_h = 65535;
  8182. block_h[node] = (unsigned short)box_h;
  8183. block_top[node] = (unsigned short)(top < 0 ? 0 :
  8184. top > 65535 ? 65535 : top);
  8185. }
  8186. if (positioned) {
  8187. l->y = flow_y;
  8188. l->left = flow_left;
  8189. l->right = flow_right;
  8190. }
  8191. l->parent_top = saved_parent_top;
  8192. l->cb_left = saved_cb_left;
  8193. l->cb_right = saved_cb_right;
  8194. l->cb_top = saved_cb_top;
  8195. }
  8196. static int text_node_blank(const struct br_node *nd)
  8197. {
  8198. const char *t = doc.text + nd->text_off;
  8199. unsigned int i;
  8200. for (i = 0; i < nd->text_len; i++)
  8201. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  8202. t[i] != '\r')
  8203. return 0;
  8204. return 1;
  8205. }
  8206. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  8207. * text/image widths in the subtree, plus padding and margins. This keeps
  8208. * Bootstrap's floated nav items on one line instead of giving each the whole
  8209. * row. */
  8210. static int text_space(char c)
  8211. {
  8212. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  8213. }
  8214. static int intrinsic_width(struct ngui *ui, unsigned int node,
  8215. const struct br_style *pst, int depth, int base)
  8216. {
  8217. unsigned int c;
  8218. int line_w = 0, max_w = 0;
  8219. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  8220. if (depth > 32)
  8221. return 0;
  8222. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8223. struct br_node *nd = &doc.nodes[c];
  8224. struct br_style cs;
  8225. if (nd->type == BR_NODE_TEXT) {
  8226. const char *t = doc.text + nd->text_off;
  8227. unsigned int tn = nd->text_len;
  8228. if (doc.nodes[node].tag == BR_TAG_PRE) {
  8229. line_w += (int)face_text_width(ui, pst, t, tn);
  8230. } else {
  8231. unsigned int ti = 0;
  8232. int first = 1;
  8233. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  8234. int sp = (int)face_text_width(ui, pst, " ", 1);
  8235. while (ti < tn) {
  8236. unsigned int ts;
  8237. while (ti < tn && text_space(t[ti]))
  8238. ti++;
  8239. ts = ti;
  8240. while (ti < tn && !text_space(t[ti]))
  8241. ti++;
  8242. if (ti == ts)
  8243. break;
  8244. if (!first || lead)
  8245. line_w += sp;
  8246. lead = 0;
  8247. line_w += (int)face_text_width(ui, pst,
  8248. t + ts, ti - ts);
  8249. first = 0;
  8250. }
  8251. }
  8252. continue;
  8253. }
  8254. br_style_for(&doc, c, pst, &cs);
  8255. if (cs.display == BR_DISPLAY_NONE)
  8256. continue;
  8257. if (nd->tag == BR_TAG_BR) {
  8258. if (line_w > max_w)
  8259. max_w = line_w;
  8260. line_w = 0;
  8261. continue;
  8262. }
  8263. if (nd->tag == BR_TAG_IMG) {
  8264. /* Measure the image as layout will draw it: a CSS or
  8265. * attribute height keeps the intrinsic aspect ratio, and
  8266. * a CSS width overrides the native pixel width. Bootstrap
  8267. * sizes the Cloudron logo with height:40px only. */
  8268. int idx = nd->img_index;
  8269. int iw = 0, ih = 0;
  8270. if (idx >= 0 && idx < image_count &&
  8271. images[idx].state == 1) {
  8272. iw = (int)images[idx].native_w;
  8273. ih = (int)images[idx].native_h;
  8274. if (iw <= 0 || ih <= 0) {
  8275. iw = (int)images[idx].img.w;
  8276. ih = (int)images[idx].img.h;
  8277. }
  8278. }
  8279. if (cs.width_kind) {
  8280. int ww = style_width_px(&cs, base);
  8281. line_w += ww > 0 ? ww : 64;
  8282. } else if (nd->width_attr) {
  8283. line_w += nd->width_attr;
  8284. } else if (nd->height_attr && iw && ih) {
  8285. line_w += iw * (int)nd->height_attr / ih;
  8286. } else if (cs.height_kind && iw && ih) {
  8287. int hh = style_height_px(&cs, base);
  8288. line_w += hh > 0 ? iw * hh / ih : iw;
  8289. } else if (iw) {
  8290. line_w += iw;
  8291. } else {
  8292. line_w += 64;
  8293. }
  8294. continue;
  8295. }
  8296. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  8297. nd->tag == BR_TAG_TEXTAREA) &&
  8298. !s_eq(br_type(&doc, c), "hidden")) {
  8299. /* Form controls are replaced: CSS width applies even
  8300. * when they are inline (add_form_run's sizes). */
  8301. int fw = cs.width_kind ? style_width_px(&cs, base) :
  8302. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  8303. if (s_eq(br_type(&doc, c), "checkbox") ||
  8304. s_eq(br_type(&doc, c), "radio"))
  8305. fw = 16;
  8306. line_w += (fw > 0 ? fw : 120) +
  8307. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  8308. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  8309. continue;
  8310. }
  8311. if (nd->tag == BR_TAG_SVG) {
  8312. /* A replaced element: its own size, like add_svg_run()
  8313. * (its path children have no width). */
  8314. int sw, sh, sb = cs.width_kind ?
  8315. style_width_px(&cs, base) : base;
  8316. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  8317. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  8318. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  8319. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8320. line_w += sw;
  8321. } else {
  8322. if (line_w > max_w)
  8323. max_w = line_w;
  8324. line_w = 0;
  8325. if (sw > max_w)
  8326. max_w = sw;
  8327. }
  8328. continue;
  8329. }
  8330. {
  8331. int cw = mp_px(&cs, 7, base) +
  8332. mp_px(&cs, 5, base) +
  8333. mp_px(&cs, 3, base) +
  8334. mp_px(&cs, 1, base) +
  8335. cs.border_w[1] + cs.border_w[3];
  8336. /* width/height do not apply to non-replaced inline
  8337. * boxes. The tagesschau home label is an inline span
  8338. * with width:1px for the mobile icon-only header; using
  8339. * that width made the whole subnav collapse to a
  8340. * one-character column. */
  8341. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  8342. cw += cs.width_kind == 1 ? cs.width :
  8343. style_width_px(&cs, base);
  8344. else
  8345. cw += intrinsic_width(ui, c, &cs, depth + 1,
  8346. base);
  8347. if (flex_row || cs.float_left ||
  8348. cs.display == BR_DISPLAY_INLINE ||
  8349. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8350. line_w += cw;
  8351. } else {
  8352. if (line_w > max_w)
  8353. max_w = line_w;
  8354. line_w = 0;
  8355. if (cw > max_w)
  8356. max_w = cw;
  8357. }
  8358. }
  8359. if (line_w > 4096 || max_w > 4096)
  8360. break;
  8361. }
  8362. return line_w > max_w ? line_w : max_w;
  8363. }
  8364. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  8365. * the main user: .row > .col-md-* with float:left and a percentage width.
  8366. * Each column is laid out with its own left/right edge and the row advances
  8367. * to the tallest column. Returns the first child not consumed. */
  8368. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  8369. const struct br_style *pst, int depth,
  8370. unsigned short link)
  8371. {
  8372. unsigned int n = first;
  8373. int row_left = l->left, row_right = l->right;
  8374. int row_top, row_bottom, xl, xr, any = 0;
  8375. int fl_left = row_left, fl_right = row_right, fl_bottom;
  8376. flush_line(l);
  8377. row_top = l->y;
  8378. row_bottom = l->y;
  8379. fl_bottom = row_top;
  8380. xl = row_left;
  8381. xr = row_right;
  8382. while (n) {
  8383. struct br_node *nd = &doc.nodes[n];
  8384. struct br_style cs;
  8385. unsigned short lk = link;
  8386. int colw, right;
  8387. if (nd->type == BR_NODE_TEXT) {
  8388. if (text_node_blank(nd)) {
  8389. n = nd->next;
  8390. continue;
  8391. }
  8392. break;
  8393. }
  8394. br_style_for(&doc, n, pst, &cs);
  8395. if (cs.display == BR_DISPLAY_NONE) {
  8396. n = nd->next;
  8397. continue;
  8398. }
  8399. /* A float blockifies its box: Bootstrap floats inline
  8400. * anchors too (the navbar brand and its text links), and
  8401. * their padding must be honoured. */
  8402. if (!cs.float_left)
  8403. break;
  8404. if (nd->tag == BR_TAG_A && nd->href_off)
  8405. lk = (unsigned short)n;
  8406. right = cs.float_left == 2;
  8407. if (cs.width_kind == 2 || cs.width_kind == 3) {
  8408. colw = style_width_px(&cs, row_right - row_left);
  8409. } else if (cs.width_kind == 1) {
  8410. colw = (int)cs.width;
  8411. } else {
  8412. int base = row_right - row_left;
  8413. /* Shrink-to-fit outer width: borders too (Google's
  8414. * 1px-bordered "Anmelden" pill wrapped otherwise). */
  8415. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  8416. mp_px(&cs, 7, base) +
  8417. mp_px(&cs, 5, base) +
  8418. mp_px(&cs, 3, base) +
  8419. mp_px(&cs, 1, base) +
  8420. cs.border_w[1] + cs.border_w[3];
  8421. if (colw < 8)
  8422. colw = 8;
  8423. }
  8424. if (colw < 8)
  8425. colw = 8;
  8426. if (colw > row_right - row_left)
  8427. colw = row_right - row_left;
  8428. /* The float column width is already resolved. */
  8429. cs.width_kind = 0;
  8430. cs.max_width_kind = 0;
  8431. if (right) {
  8432. if (any && xr - colw < xl) {
  8433. row_top = row_bottom;
  8434. row_bottom = row_top;
  8435. xl = row_left;
  8436. xr = row_right;
  8437. }
  8438. if (xr - colw < xl)
  8439. colw = xr - xl;
  8440. if (colw < 8)
  8441. colw = 8;
  8442. l->left = xr - colw;
  8443. if (l->left < row_left)
  8444. l->left = row_left;
  8445. l->right = xr;
  8446. xr = l->left;
  8447. if (xr < fl_right)
  8448. fl_right = xr;
  8449. } else {
  8450. if (any && xl + colw > xr) {
  8451. row_top = row_bottom;
  8452. row_bottom = row_top;
  8453. xl = row_left;
  8454. xr = row_right;
  8455. }
  8456. l->left = xl;
  8457. l->right = xl + colw;
  8458. xl += colw;
  8459. if (xl > fl_left)
  8460. fl_left = xl;
  8461. }
  8462. if (l->right < l->left + 8)
  8463. l->right = l->left + 8;
  8464. l->y = row_top;
  8465. l->line_x = l->left;
  8466. l->run_x = l->left;
  8467. l->line_y = l->y;
  8468. l->line_h = 0;
  8469. l->nruns = 0;
  8470. l->space_pending = 0;
  8471. l->align = cs.align;
  8472. layout_block(l, n, &cs, depth + 1, lk);
  8473. if (l->y > row_bottom)
  8474. row_bottom = l->y;
  8475. if (l->y > fl_bottom)
  8476. fl_bottom = l->y;
  8477. any = 1;
  8478. n = nd->next;
  8479. }
  8480. l->left = row_left;
  8481. l->right = row_right;
  8482. if (n && any) {
  8483. struct br_node *nd = &doc.nodes[n];
  8484. int inline_next = 0;
  8485. if (nd->type == BR_NODE_TEXT) {
  8486. inline_next = 1;
  8487. } else if (nd->type == BR_NODE_ELEM) {
  8488. struct br_style cs;
  8489. br_style_for(&doc, n, pst, &cs);
  8490. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  8491. cs.display != BR_DISPLAY_NONE &&
  8492. !br_tag_is_block(nd->tag);
  8493. }
  8494. if (inline_next) {
  8495. if (l->float_active) {
  8496. if (l->float_left > fl_left)
  8497. fl_left = l->float_left;
  8498. if (l->float_right < fl_right)
  8499. fl_right = l->float_right;
  8500. if (l->float_bottom > fl_bottom)
  8501. fl_bottom = l->float_bottom;
  8502. }
  8503. l->float_active = 1;
  8504. l->float_left = fl_left;
  8505. l->float_right = fl_right;
  8506. l->float_bottom = fl_bottom;
  8507. l->y = row_top;
  8508. } else {
  8509. l->float_active = 0;
  8510. l->y = row_bottom;
  8511. }
  8512. } else {
  8513. l->float_active = 0;
  8514. l->y = row_bottom;
  8515. }
  8516. l->line_x = l->left;
  8517. l->run_x = l->left;
  8518. l->line_left = l->left;
  8519. l->line_right = l->right;
  8520. l->line_y = l->y;
  8521. l->line_h = 0;
  8522. l->nruns = 0;
  8523. l->space_pending = 0;
  8524. return n;
  8525. }
  8526. static int flex_item_width(struct lay *l, unsigned int n,
  8527. const struct br_style *cs, int avail)
  8528. {
  8529. struct br_node *nd = &doc.nodes[n];
  8530. (void)l;
  8531. int w;
  8532. if (cs->width_kind == 2 || cs->width_kind == 3)
  8533. w = style_width_px(cs, avail);
  8534. else if (cs->width_kind == 1)
  8535. w = (int)cs->width;
  8536. else if (nd->tag == BR_TAG_IMG) {
  8537. int idx = nd->img_index;
  8538. if (idx >= 0 && idx < image_count &&
  8539. images[idx].state == 1)
  8540. w = (int)images[idx].img.w;
  8541. else if (nd->width_attr)
  8542. w = (int)nd->width_attr;
  8543. else
  8544. w = 64;
  8545. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  8546. nd->tag == BR_TAG_TEXTAREA) {
  8547. /* A control has no content to measure: its default size
  8548. * (a search field in a filter bar). */
  8549. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  8550. } else {
  8551. w = intrinsic_width(l->ui, n, cs, 0, avail);
  8552. }
  8553. /* Explicit widths are content-box sizes; the flex item's outer width
  8554. * must include padding, borders and margins. */
  8555. w += mp_px(cs, 7, avail);
  8556. w += mp_px(cs, 5, avail);
  8557. w += mp_px(cs, 3, avail);
  8558. w += mp_px(cs, 1, avail);
  8559. w += cs->border_w[1] + cs->border_w[3];
  8560. if (w < 24)
  8561. w = 24;
  8562. if (w > avail)
  8563. w = avail;
  8564. return w;
  8565. }
  8566. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  8567. int depth);
  8568. /* An inline child of a text-only inline-block: the same test minus the
  8569. * display check (an inline <span> may have padding/background in CSS, but
  8570. * the inline path paints those for spans anyway). */
  8571. static int inline_block_flows_inline(unsigned int node,
  8572. const struct br_style *cs, int depth)
  8573. {
  8574. unsigned int c;
  8575. if (depth > 3 || cs->pos)
  8576. return 0;
  8577. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8578. const struct br_node *nd = &doc.nodes[c];
  8579. struct br_style ch;
  8580. if (nd->type != BR_NODE_ELEM)
  8581. continue;
  8582. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  8583. br_tag_is_block(nd->tag))
  8584. return 0;
  8585. br_style_for(&doc, c, cs, &ch);
  8586. if (ch.display == BR_DISPLAY_NONE)
  8587. continue;
  8588. if (ch.display != BR_DISPLAY_INLINE ||
  8589. !inline_block_flows_inline(c, &ch, depth + 1))
  8590. return 0;
  8591. }
  8592. return 1;
  8593. }
  8594. /* An inline-block that is only text in a line (a <time> in a byline, a
  8595. * label) with no box of its own -- no size, background, border or padding
  8596. * -- lays out exactly like an inline element, so it stays in the text line
  8597. * instead of ending it. Boxes with any of those keep the row path. */
  8598. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  8599. int depth)
  8600. {
  8601. unsigned int c;
  8602. int i;
  8603. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  8604. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  8605. cs->pos || depth > 3)
  8606. return 0;
  8607. for (i = 0; i < 4; i++)
  8608. if (cs->border_w[i])
  8609. return 0;
  8610. for (i = 4; i < 8; i++)
  8611. if (mp_px(cs, i, 0) > 0)
  8612. return 0;
  8613. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8614. const struct br_node *nd = &doc.nodes[c];
  8615. struct br_style ch;
  8616. if (nd->type != BR_NODE_ELEM)
  8617. continue;
  8618. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  8619. br_tag_is_block(nd->tag))
  8620. return 0;
  8621. br_style_for(&doc, c, cs, &ch);
  8622. if (ch.display == BR_DISPLAY_NONE)
  8623. continue;
  8624. if (ch.display != BR_DISPLAY_INLINE ||
  8625. !inline_block_flows_inline(c, &ch, depth + 1))
  8626. return 0;
  8627. }
  8628. return 1;
  8629. }
  8630. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  8631. * on one line, not one full-width block each. Place intrinsic widths from
  8632. * left to right and wrap when the row is full. */
  8633. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  8634. const struct br_style *pst, int depth,
  8635. unsigned short link)
  8636. {
  8637. unsigned int n = first;
  8638. int row_left = l->left, row_right = l->right;
  8639. int avail = row_right - row_left;
  8640. int x = row_left, y = l->y, row_h = 0, any = 0;
  8641. /* Each box sets l->align from its own style; the text after the row
  8642. * must keep the container's (a centred .fa-fw icon centred the menu
  8643. * label that followed it). */
  8644. unsigned char row_align = l->align;
  8645. flush_line(l);
  8646. y = l->y;
  8647. while (n) {
  8648. struct br_node *nd = &doc.nodes[n];
  8649. struct br_style cs;
  8650. unsigned short lk = link;
  8651. int colw, h;
  8652. if (nd->type == BR_NODE_TEXT) {
  8653. if (!text_node_blank(nd))
  8654. break;
  8655. if (any)
  8656. x += 4;
  8657. n = nd->next;
  8658. continue;
  8659. }
  8660. br_style_for(&doc, n, pst, &cs);
  8661. if (cs.display == BR_DISPLAY_NONE) {
  8662. n = nd->next;
  8663. continue;
  8664. }
  8665. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  8666. break;
  8667. if (nd->tag == BR_TAG_A && nd->href_off)
  8668. lk = (unsigned short)n;
  8669. colw = flex_item_width(l, n, &cs, avail);
  8670. /* A few pixels of slack keep a single long token (boot.S)
  8671. * from wrapping at the exact content width. */
  8672. colw += 8;
  8673. if (colw > avail)
  8674. colw = avail;
  8675. cs.width_kind = 0;
  8676. cs.max_width_kind = 0;
  8677. if (any && x + colw > row_right) {
  8678. y += row_h + 2;
  8679. x = row_left;
  8680. row_h = 0;
  8681. any = 0;
  8682. }
  8683. if (any && x > row_left)
  8684. x += 4;
  8685. l->left = x;
  8686. l->right = x + colw;
  8687. if (l->right < l->left + 8)
  8688. l->right = l->left + 8;
  8689. l->y = y;
  8690. l->line_x = l->left;
  8691. l->run_x = l->left;
  8692. l->line_y = l->y;
  8693. l->line_h = 0;
  8694. l->nruns = 0;
  8695. l->space_pending = 0;
  8696. l->align = cs.align;
  8697. layout_block(l, n, &cs, depth + 1, lk);
  8698. h = l->y - y;
  8699. if (h > row_h)
  8700. row_h = h;
  8701. x += colw;
  8702. any = 1;
  8703. n = nd->next;
  8704. }
  8705. if (any)
  8706. y += row_h;
  8707. l->left = row_left;
  8708. l->right = row_right;
  8709. l->align = row_align;
  8710. l->y = y;
  8711. l->line_x = l->left;
  8712. l->run_x = l->left;
  8713. l->line_y = l->y;
  8714. l->line_h = 0;
  8715. l->nruns = 0;
  8716. l->space_pending = 0;
  8717. return n;
  8718. }
  8719. struct flex_item {
  8720. unsigned int node;
  8721. unsigned short link;
  8722. int w;
  8723. };
  8724. static void layout_flex_children(struct lay *l, unsigned int parent,
  8725. const struct br_style *pst, int depth,
  8726. unsigned short link)
  8727. {
  8728. struct flex_item it[32];
  8729. unsigned int c;
  8730. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  8731. int row_left = l->left, row_right = l->right;
  8732. int avail = row_right - row_left;
  8733. int idx, row_top;
  8734. unsigned char row_align = l->align;
  8735. if (avail < 8 || depth > 48) {
  8736. layout_children(l, parent, pst, depth, link);
  8737. return;
  8738. }
  8739. /* If direct text is not just whitespace, normal block flow handles it
  8740. * better than pretending it is a flex item. */
  8741. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  8742. struct br_node *nd = &doc.nodes[c];
  8743. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  8744. layout_children(l, parent, pst, depth, link);
  8745. return;
  8746. }
  8747. }
  8748. for (c = doc.nodes[parent].first;
  8749. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  8750. c = doc.nodes[c].next) {
  8751. struct br_node *nd = &doc.nodes[c];
  8752. struct br_style cs;
  8753. if (nd->type == BR_NODE_TEXT)
  8754. continue;
  8755. br_style_for(&doc, c, pst, &cs);
  8756. if (cs.display == BR_DISPLAY_NONE)
  8757. continue;
  8758. it[nitem].node = c;
  8759. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  8760. (unsigned short)c : link;
  8761. it[nitem].w = 0;
  8762. if (cs.flex_grow && !cs.width_kind)
  8763. grow_count++;
  8764. else
  8765. fixed += flex_item_width(l, c, &cs, avail);
  8766. nitem++;
  8767. }
  8768. /* A narrow container (an icon row sized to its content, Google's
  8769. * mic + lens buttons) is still a row when its items fit; only a
  8770. * narrow one that would overflow or squeeze growing items falls
  8771. * back to block flow. */
  8772. if (avail < 160 && (grow_count || fixed > avail)) {
  8773. layout_children(l, parent, pst, depth, link);
  8774. return;
  8775. }
  8776. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  8777. if (grow_w < 96)
  8778. grow_w = 96;
  8779. for (idx = 0; idx < nitem; idx++) {
  8780. struct br_style cs;
  8781. br_style_for(&doc, it[idx].node, pst, &cs);
  8782. if (cs.flex_grow && !cs.width_kind)
  8783. it[idx].w = grow_w;
  8784. else
  8785. it[idx].w = flex_item_width(l, it[idx].node, &cs, avail);
  8786. if (it[idx].w > avail)
  8787. it[idx].w = avail;
  8788. if (it[idx].w < 8)
  8789. it[idx].w = 8;
  8790. }
  8791. row_top = l->y;
  8792. idx = 0;
  8793. while (idx < nitem) {
  8794. int start = idx, count = 0, row_w = 0;
  8795. int free_w, x, extra = 0, row_h = 0, k;
  8796. while (idx < nitem) {
  8797. int add = it[idx].w + (count ? gap : 0);
  8798. /* CSS default is nowrap; only flex-wrap: wrap (1)
  8799. * starts a new row. */
  8800. if (count && pst->flex_wrap == 1 &&
  8801. row_w + add > avail)
  8802. break;
  8803. row_w += add;
  8804. count++;
  8805. idx++;
  8806. }
  8807. if (!count) {
  8808. count = 1;
  8809. row_w = it[start].w;
  8810. idx = start + 1;
  8811. }
  8812. free_w = avail - row_w;
  8813. if (free_w < 0)
  8814. free_w = 0;
  8815. x = row_left;
  8816. if (pst->justify == 1) {
  8817. x += free_w / 2;
  8818. } else if (pst->justify == 2) {
  8819. x += free_w;
  8820. } else if (pst->justify == 3) {
  8821. extra = count > 1 ? free_w / (count - 1) : 0;
  8822. } else if (pst->justify == 4) {
  8823. extra = count ? free_w / count : 0;
  8824. x += extra / 2;
  8825. } else if (pst->justify == 5) {
  8826. extra = count ? free_w / (count + 1) : 0;
  8827. x += extra;
  8828. }
  8829. for (k = 0; k < count; k++) {
  8830. int node = (int)it[start + k].node;
  8831. int h = block_h[node];
  8832. if (h > row_h)
  8833. row_h = h;
  8834. }
  8835. if (pst->height_kind) {
  8836. int hh = style_height_px(pst, avail);
  8837. if (hh > row_h)
  8838. row_h = hh;
  8839. }
  8840. for (k = 0; k < count; k++) {
  8841. struct br_style cs;
  8842. int node = (int)it[start + k].node;
  8843. int yoff = 0;
  8844. br_style_for(&doc, node, pst, &cs);
  8845. cs.width_kind = 0;
  8846. cs.max_width_kind = 0;
  8847. {
  8848. int ai = cs.align_self ? cs.align_self - 1 :
  8849. pst->align_items;
  8850. if (l->draw && ai && row_h > block_h[node]) {
  8851. if (ai == 1)
  8852. yoff = (row_h -
  8853. block_h[node]) / 2;
  8854. else if (ai == 2)
  8855. yoff = row_h - block_h[node];
  8856. }
  8857. }
  8858. l->left = x;
  8859. l->right = x + it[start + k].w;
  8860. if (l->right < l->left + 8)
  8861. l->right = l->left + 8;
  8862. l->y = row_top + yoff;
  8863. l->line_x = l->left;
  8864. l->run_x = l->left;
  8865. l->line_y = l->y;
  8866. l->line_h = 0;
  8867. l->nruns = 0;
  8868. l->space_pending = 0;
  8869. l->align = cs.align;
  8870. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  8871. if (!l->draw) {
  8872. int h = l->y - row_top;
  8873. if (h > row_h)
  8874. row_h = h;
  8875. }
  8876. x += it[start + k].w;
  8877. if (k + 1 < count)
  8878. x += gap + extra;
  8879. }
  8880. row_top += row_h;
  8881. }
  8882. l->left = row_left;
  8883. l->right = row_right;
  8884. l->align = row_align;
  8885. l->y = row_top;
  8886. l->line_x = l->left;
  8887. l->run_x = l->left;
  8888. l->line_y = l->y;
  8889. l->line_h = 0;
  8890. l->nruns = 0;
  8891. l->space_pending = 0;
  8892. }
  8893. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  8894. * plus the grid-area hints used by site shells (site notice/footer full
  8895. * width, column-start left, page-content right). Anything more elaborate
  8896. * falls back to normal block flow. */
  8897. static int grid_track_width(unsigned char kind, unsigned short val,
  8898. int avail, int other)
  8899. {
  8900. if (kind == 2)
  8901. return avail * (int)val / 100;
  8902. if (kind == 1)
  8903. return val;
  8904. return other;
  8905. }
  8906. static void layout_grid_children(struct lay *l, unsigned int parent,
  8907. const struct br_style *pst, int depth,
  8908. unsigned short link)
  8909. {
  8910. unsigned int n;
  8911. int row_left = l->left, row_right = l->right;
  8912. int avail = row_right - row_left;
  8913. int gap = pst->grid_gap;
  8914. int track_total = avail - gap;
  8915. int col0, col1, x0, x1;
  8916. int row_y, row_bottom, have_left = 0, have_right = 0;
  8917. unsigned int c;
  8918. if (avail < 32 || depth > 48)
  8919. return;
  8920. if (track_total < 16)
  8921. track_total = 16;
  8922. col0 = grid_track_width((unsigned char)(pst->width_kind),
  8923. pst->width, track_total, 0);
  8924. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  8925. pst->max_width, track_total, 0);
  8926. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  8927. int w0 = pst->width ? pst->width : 1;
  8928. int w1 = pst->max_width ? pst->max_width : 1;
  8929. col0 = track_total * w0 / (w0 + w1);
  8930. col1 = track_total - col0;
  8931. } else if (pst->width_kind == 3) {
  8932. col0 = track_total - col1;
  8933. if (col0 < 24)
  8934. col0 = 24;
  8935. } else if (pst->max_width_kind == 3) {
  8936. col1 = track_total - col0;
  8937. if (col1 < 24)
  8938. col1 = 24;
  8939. }
  8940. if (col0 < 24)
  8941. col0 = 24;
  8942. if (col1 < 24)
  8943. col1 = 24;
  8944. if (col0 + col1 > track_total) {
  8945. col1 = track_total - col0;
  8946. if (col1 < 24)
  8947. col1 = 24;
  8948. }
  8949. x0 = row_left;
  8950. x1 = row_left + col0 + gap;
  8951. /* Direct text makes a grid ambiguous; use block flow instead. */
  8952. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  8953. struct br_node *nd = &doc.nodes[c];
  8954. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  8955. layout_children(l, parent, pst, depth, link);
  8956. return;
  8957. }
  8958. }
  8959. row_y = row_bottom = l->y;
  8960. n = doc.nodes[parent].first;
  8961. while (n) {
  8962. struct br_node *nd = &doc.nodes[n];
  8963. struct br_style cs;
  8964. unsigned short lk = link;
  8965. int slot, x, w;
  8966. if (nd->type == BR_NODE_TEXT) {
  8967. n = nd->next;
  8968. continue;
  8969. }
  8970. br_style_for(&doc, n, pst, &cs);
  8971. if (cs.display == BR_DISPLAY_NONE) {
  8972. n = nd->next;
  8973. continue;
  8974. }
  8975. if (nd->tag == BR_TAG_A && nd->href_off)
  8976. lk = (unsigned short)n;
  8977. slot = cs.grid_slot;
  8978. if (!slot) {
  8979. if (!have_left)
  8980. slot = 2;
  8981. else if (!have_right)
  8982. slot = 3;
  8983. else
  8984. slot = 2;
  8985. }
  8986. if (slot == 1) {
  8987. if (have_left || have_right) {
  8988. row_y = row_bottom;
  8989. have_left = have_right = 0;
  8990. }
  8991. x = row_left;
  8992. w = avail;
  8993. } else if (slot == 2) {
  8994. if (have_left) {
  8995. row_y = row_bottom;
  8996. have_left = have_right = 0;
  8997. }
  8998. x = x0;
  8999. w = col0;
  9000. have_left = 1;
  9001. } else {
  9002. if (have_right) {
  9003. row_y = row_bottom;
  9004. have_left = have_right = 0;
  9005. }
  9006. x = x1;
  9007. w = col1;
  9008. have_right = 1;
  9009. }
  9010. cs.width_kind = 0;
  9011. cs.max_width_kind = 0;
  9012. l->left = x;
  9013. l->right = x + w;
  9014. if (l->right < l->left + 8)
  9015. l->right = l->left + 8;
  9016. l->y = row_y;
  9017. l->line_x = l->left;
  9018. l->run_x = l->left;
  9019. l->line_y = l->y;
  9020. l->line_h = 0;
  9021. l->nruns = 0;
  9022. l->space_pending = 0;
  9023. l->align = cs.align;
  9024. layout_block(l, n, &cs, depth + 1, lk);
  9025. if (l->y > row_bottom)
  9026. row_bottom = l->y;
  9027. n = nd->next;
  9028. }
  9029. l->left = row_left;
  9030. l->right = row_right;
  9031. l->y = row_bottom;
  9032. l->line_x = l->left;
  9033. l->run_x = l->left;
  9034. l->line_y = l->y;
  9035. l->line_h = 0;
  9036. l->nruns = 0;
  9037. l->space_pending = 0;
  9038. }
  9039. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  9040. * capped at four. Used by the project docs' card grids. A fixed
  9041. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  9042. static void layout_grid_auto(struct lay *l, unsigned int parent,
  9043. const struct br_style *pst, int depth,
  9044. unsigned short link)
  9045. {
  9046. unsigned int n, c;
  9047. int row_left = l->left, row_right = l->right;
  9048. int avail = row_right - row_left;
  9049. int gap = pst->grid_gap;
  9050. int minw = pst->width_kind == 1 ? pst->width : 200;
  9051. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  9052. if (avail < 32 || depth > 48) {
  9053. layout_children(l, parent, pst, depth, link);
  9054. return;
  9055. }
  9056. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9057. struct br_node *nd = &doc.nodes[c];
  9058. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9059. layout_children(l, parent, pst, depth, link);
  9060. return;
  9061. }
  9062. }
  9063. if (minw < 80)
  9064. minw = 80;
  9065. ncols = (avail + gap) / (minw + gap);
  9066. if (ncols < 1)
  9067. ncols = 1;
  9068. if (ncols > 4)
  9069. ncols = 4;
  9070. if (pst->grid_auto > BR_GRID_FIXED) {
  9071. /* grid-template-columns: repeat(N, 1fr) */
  9072. ncols = pst->grid_auto - BR_GRID_FIXED;
  9073. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  9074. ncols--;
  9075. }
  9076. colw = (avail - gap * (ncols - 1)) / ncols;
  9077. if (colw < 24)
  9078. colw = 24;
  9079. x = row_left;
  9080. n = doc.nodes[parent].first;
  9081. while (n) {
  9082. struct br_node *nd = &doc.nodes[n];
  9083. struct br_style cs;
  9084. unsigned short lk = link;
  9085. int h;
  9086. if (nd->type == BR_NODE_TEXT) {
  9087. n = nd->next;
  9088. continue;
  9089. }
  9090. br_style_for(&doc, n, pst, &cs);
  9091. if (cs.display == BR_DISPLAY_NONE) {
  9092. n = nd->next;
  9093. continue;
  9094. }
  9095. if (nd->tag == BR_TAG_A && nd->href_off)
  9096. lk = (unsigned short)n;
  9097. cs.width_kind = 0;
  9098. cs.max_width_kind = 0;
  9099. l->left = x;
  9100. l->right = x + colw;
  9101. if (l->right < l->left + 8)
  9102. l->right = l->left + 8;
  9103. l->y = y;
  9104. l->line_x = l->left;
  9105. l->run_x = l->left;
  9106. l->line_y = l->y;
  9107. l->line_h = 0;
  9108. l->nruns = 0;
  9109. l->space_pending = 0;
  9110. l->align = cs.align;
  9111. layout_block(l, n, &cs, depth + 1, lk);
  9112. h = l->y - y;
  9113. if (h > row_h)
  9114. row_h = h;
  9115. col++;
  9116. n = nd->next;
  9117. if (col == ncols) {
  9118. y += row_h + gap;
  9119. x = row_left;
  9120. row_h = 0;
  9121. col = 0;
  9122. } else {
  9123. x += colw + gap;
  9124. }
  9125. }
  9126. if (col)
  9127. y += row_h;
  9128. else if (y > start_y)
  9129. y -= gap;
  9130. l->left = row_left;
  9131. l->right = row_right;
  9132. l->y = y;
  9133. l->line_x = l->left;
  9134. l->run_x = l->left;
  9135. l->line_y = l->y;
  9136. l->line_h = 0;
  9137. l->nruns = 0;
  9138. l->space_pending = 0;
  9139. }
  9140. /* Column widths are the widest cell in each column across every row, so all
  9141. * rows line up. The table model is still deliberately basic: no colspan,
  9142. * border-collapse or percentage columns. */
  9143. static void table_columns(struct lay *l, unsigned int table,
  9144. const struct br_style *pst, int avail,
  9145. int *raw, int maxcols, int *out_cols,
  9146. int *out_total)
  9147. {
  9148. unsigned int r, c;
  9149. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  9150. int fixed[12];
  9151. for (c = 0; c < (unsigned int)maxcols; c++) {
  9152. raw[c] = 0;
  9153. fixed[c] = 0;
  9154. }
  9155. /* Intrinsic widths of single-column cells. */
  9156. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9157. struct br_node *rn = &doc.nodes[r];
  9158. int col = 0;
  9159. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9160. continue;
  9161. for (c = rn->first; c; c = doc.nodes[c].next) {
  9162. struct br_node *cn = &doc.nodes[c];
  9163. struct br_style cs;
  9164. int w, span;
  9165. if (cn->type != BR_NODE_ELEM ||
  9166. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9167. continue;
  9168. span = cn->colspan ? cn->colspan : 1;
  9169. br_style_for(&doc, c, pst, &cs);
  9170. if (cs.display == BR_DISPLAY_NONE)
  9171. continue;
  9172. if (col + span > maxcols)
  9173. span = maxcols - col;
  9174. if (span < 1)
  9175. break;
  9176. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  9177. mp_px(&cs, 7, avail) +
  9178. mp_px(&cs, 5, avail) +
  9179. mp_px(&cs, 3, avail) +
  9180. mp_px(&cs, 1, avail) +
  9181. cs.border_w[0] + cs.border_w[1] +
  9182. cs.border_w[2] + cs.border_w[3];
  9183. if (w < 24)
  9184. w = 24;
  9185. if (span == 1) {
  9186. if (w > raw[col])
  9187. raw[col] = w;
  9188. }
  9189. if (col + span > cols)
  9190. cols = col + span;
  9191. col += span;
  9192. }
  9193. }
  9194. /* A colspan cell only has to be as wide as the sum of its columns. */
  9195. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9196. struct br_node *rn = &doc.nodes[r];
  9197. int col = 0;
  9198. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9199. continue;
  9200. for (c = rn->first; c; c = doc.nodes[c].next) {
  9201. struct br_node *cn = &doc.nodes[c];
  9202. struct br_style cs;
  9203. int span, w, sum, i;
  9204. if (cn->type != BR_NODE_ELEM ||
  9205. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9206. continue;
  9207. span = cn->colspan ? cn->colspan : 1;
  9208. if (col + span > maxcols)
  9209. span = maxcols - col;
  9210. if (span < 1)
  9211. break;
  9212. if (span > 1) {
  9213. br_style_for(&doc, c, pst, &cs);
  9214. if (cs.display != BR_DISPLAY_NONE) {
  9215. w = intrinsic_width(l->ui, c, &cs,
  9216. 0, avail) +
  9217. mp_px(&cs, 7, avail) +
  9218. mp_px(&cs, 5, avail) +
  9219. mp_px(&cs, 3, avail) +
  9220. mp_px(&cs, 1, avail) +
  9221. cs.border_w[0] + cs.border_w[1] +
  9222. cs.border_w[2] + cs.border_w[3];
  9223. sum = 0;
  9224. for (i = 0; i < span; i++)
  9225. sum += raw[col + i];
  9226. if (w > sum)
  9227. raw[col + span - 1] += w - sum;
  9228. }
  9229. }
  9230. col += span;
  9231. }
  9232. }
  9233. /* Explicit and percentage widths override intrinsic widths. */
  9234. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9235. struct br_node *rn = &doc.nodes[r];
  9236. int col = 0;
  9237. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9238. continue;
  9239. for (c = rn->first; c; c = doc.nodes[c].next) {
  9240. struct br_node *cn = &doc.nodes[c];
  9241. struct br_style cs;
  9242. int span;
  9243. if (cn->type != BR_NODE_ELEM ||
  9244. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9245. continue;
  9246. span = cn->colspan ? cn->colspan : 1;
  9247. if (col + span > maxcols)
  9248. span = maxcols - col;
  9249. if (span < 1)
  9250. break;
  9251. if (span == 1) {
  9252. br_style_for(&doc, c, pst, &cs);
  9253. if (cs.display != BR_DISPLAY_NONE) {
  9254. if (cs.width_kind == 1) {
  9255. raw[col] = cs.width;
  9256. fixed[col] = 1;
  9257. } else if (cs.width_kind == 2 ||
  9258. cs.width_kind == 3) {
  9259. raw[col] = style_width_px(&cs,
  9260. avail);
  9261. fixed[col] = 1;
  9262. }
  9263. }
  9264. }
  9265. col += span;
  9266. }
  9267. }
  9268. for (c = 0; c < (unsigned int)cols; c++) {
  9269. if (raw[c] < 8)
  9270. raw[c] = 8;
  9271. total += raw[c];
  9272. if (fixed[c])
  9273. fixed_sum += raw[c];
  9274. else {
  9275. free_raw += raw[c];
  9276. free_cols++;
  9277. }
  9278. }
  9279. if (fixed_sum > 0 && fixed_sum < avail) {
  9280. int free_avail = avail - fixed_sum;
  9281. int i;
  9282. if (free_raw > 0) {
  9283. for (i = 0; i < cols; i++)
  9284. if (!fixed[i])
  9285. raw[i] = free_avail * raw[i] /
  9286. free_raw;
  9287. } else if (free_cols > 0) {
  9288. for (i = 0; i < cols; i++)
  9289. if (!fixed[i])
  9290. raw[i] = free_avail / free_cols;
  9291. }
  9292. total = 0;
  9293. for (i = 0; i < cols; i++)
  9294. total += raw[i];
  9295. } else if (total < avail && total > 0) {
  9296. int i;
  9297. for (i = 0; i < cols; i++)
  9298. raw[i] = raw[i] * avail / total;
  9299. total = 0;
  9300. for (i = 0; i < cols; i++)
  9301. total += raw[i];
  9302. }
  9303. *out_cols = cols;
  9304. *out_total = total;
  9305. }
  9306. static void layout_table_row(struct lay *l, unsigned int row,
  9307. const struct br_style *pst, int depth,
  9308. unsigned short link)
  9309. {
  9310. unsigned int n, cell[12];
  9311. int raw[12], colstart[12], colspan[12];
  9312. int prefix[13];
  9313. int ncell = 0, total = 0, cols = 0, col = 0;
  9314. int row_left = l->left, row_right = l->right;
  9315. int avail = row_right - row_left;
  9316. int y = l->y, bottom = l->y;
  9317. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  9318. struct br_node *nd = &doc.nodes[n];
  9319. struct br_style cs;
  9320. int span;
  9321. if (nd->type == BR_NODE_TEXT) {
  9322. if (text_node_blank(nd))
  9323. continue;
  9324. layout_children(l, row, pst, depth, link);
  9325. return;
  9326. }
  9327. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  9328. layout_children(l, row, pst, depth, link);
  9329. return;
  9330. }
  9331. br_style_for(&doc, n, pst, &cs);
  9332. if (cs.display == BR_DISPLAY_NONE)
  9333. continue;
  9334. if (ncell >= 12) {
  9335. layout_children(l, row, pst, depth, link);
  9336. return;
  9337. }
  9338. span = nd->colspan ? nd->colspan : 1;
  9339. if (span > 12 - col)
  9340. span = 12 - col;
  9341. if (span < 1)
  9342. continue;
  9343. cell[ncell] = n;
  9344. colstart[ncell] = col;
  9345. colspan[ncell] = span;
  9346. col += span;
  9347. ncell++;
  9348. }
  9349. if (ncell < 1 || avail < 32) {
  9350. layout_children(l, row, pst, depth, link);
  9351. return;
  9352. }
  9353. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  9354. &total);
  9355. if (cols < 2 || total <= 0) {
  9356. int c;
  9357. total = 0;
  9358. for (c = 0; c < ncell; c++) {
  9359. struct br_style cs;
  9360. br_style_for(&doc, cell[c], pst, &cs);
  9361. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  9362. avail) +
  9363. mp_px(&cs, 7, avail) +
  9364. mp_px(&cs, 5, avail) +
  9365. mp_px(&cs, 3, avail) +
  9366. mp_px(&cs, 1, avail);
  9367. if (raw[c] < 24)
  9368. raw[c] = 24;
  9369. total += raw[c];
  9370. }
  9371. /* A one-column table still has to fill its own width; the
  9372. * intrinsic fallback above otherwise leaves the cell at its
  9373. * text width (HN's outer table and nested story table). */
  9374. if (total > 0 && total < avail) {
  9375. int c;
  9376. for (c = 0; c < ncell; c++)
  9377. raw[c] = raw[c] * avail / total;
  9378. total = avail;
  9379. }
  9380. }
  9381. prefix[0] = row_left;
  9382. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  9383. prefix[n + 1] = prefix[n] + raw[n];
  9384. for (n = 0; n < (unsigned int)ncell; n++) {
  9385. struct br_style cs;
  9386. int start = colstart[n];
  9387. int end = start + colspan[n];
  9388. int w;
  9389. if (end > cols)
  9390. end = cols;
  9391. if (start >= cols)
  9392. continue;
  9393. w = prefix[end] - prefix[start];
  9394. br_style_for(&doc, cell[n], pst, &cs);
  9395. /* The column width already reflects the cell's width property. */
  9396. cs.width_kind = 0;
  9397. cs.max_width_kind = 0;
  9398. if (w < 24)
  9399. w = 24;
  9400. if (w < 8)
  9401. w = 8;
  9402. l->left = prefix[start];
  9403. l->right = l->left + w;
  9404. l->y = y;
  9405. l->line_x = l->left;
  9406. l->run_x = l->left;
  9407. l->line_y = l->y;
  9408. l->line_h = 0;
  9409. l->nruns = 0;
  9410. l->space_pending = 0;
  9411. l->align = cs.align;
  9412. layout_block(l, cell[n], &cs, depth + 1, link);
  9413. if (l->y > bottom)
  9414. bottom = l->y;
  9415. }
  9416. l->left = row_left;
  9417. l->right = row_right;
  9418. l->y = bottom;
  9419. l->line_x = l->left;
  9420. l->run_x = l->left;
  9421. l->line_y = l->y;
  9422. l->line_h = 0;
  9423. l->nruns = 0;
  9424. l->space_pending = 0;
  9425. }
  9426. #define TBL_MAX_ROWS 32
  9427. #define TBL_MAX_COLS 12
  9428. #define TBL_MAX_CELLS 128
  9429. struct tbl_cell {
  9430. unsigned int node;
  9431. unsigned char row, col, rowspan, colspan;
  9432. int height;
  9433. };
  9434. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  9435. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  9436. static int table_active;
  9437. static int table_has_rowspan(unsigned int table)
  9438. {
  9439. unsigned int r, c;
  9440. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9441. struct br_node *rn = &doc.nodes[r];
  9442. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9443. continue;
  9444. for (c = rn->first; c; c = doc.nodes[c].next) {
  9445. struct br_node *cn = &doc.nodes[c];
  9446. if (cn->type == BR_NODE_ELEM &&
  9447. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  9448. cn->rowspan > 1)
  9449. return 1;
  9450. }
  9451. }
  9452. return 0;
  9453. }
  9454. static void table_cell_style(unsigned int row, unsigned int cell,
  9455. const struct br_style *st, struct br_style *out)
  9456. {
  9457. struct br_style trs;
  9458. br_style_for(&doc, row, st, &trs);
  9459. br_style_for(&doc, cell, &trs, out);
  9460. }
  9461. /* Tables that use rowspan need row heights before anything is painted. This
  9462. * path builds a small occupancy grid, measures the natural cell heights, then
  9463. * lays every cell out at its row/column position. Tables without rowspan
  9464. * keep the lighter per-row path in layout_table_row(). */
  9465. static void layout_table(struct lay *l, unsigned int table,
  9466. const struct br_style *st, int depth,
  9467. unsigned short link)
  9468. {
  9469. unsigned int rows[TBL_MAX_ROWS];
  9470. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  9471. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  9472. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  9473. int free_raw = 0, free_cols = 0;
  9474. int table_left = l->left, table_right = l->right;
  9475. int top = l->y, avail = table_right - table_left;
  9476. unsigned int r, c;
  9477. int i, rr, cc;
  9478. if (depth > 48 || table_active) {
  9479. layout_children(l, table, st, depth, link);
  9480. return;
  9481. }
  9482. table_active = 1;
  9483. for (r = doc.nodes[table].first;
  9484. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  9485. struct br_node *rn = &doc.nodes[r];
  9486. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  9487. rows[nrows++] = r;
  9488. }
  9489. if (!nrows) {
  9490. table_active = 0;
  9491. layout_children(l, table, st, depth, link);
  9492. return;
  9493. }
  9494. for (rr = 0; rr < nrows; rr++)
  9495. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  9496. tbl_at[rr][cc] = 0;
  9497. for (rr = 0; rr < nrows; rr++) {
  9498. int col = 0;
  9499. for (c = doc.nodes[rows[rr]].first; c;
  9500. c = doc.nodes[c].next) {
  9501. struct br_node *cn = &doc.nodes[c];
  9502. struct br_style cs;
  9503. int rs, csn;
  9504. if (cn->type != BR_NODE_ELEM ||
  9505. (cn->tag != BR_TAG_TD &&
  9506. cn->tag != BR_TAG_TH))
  9507. continue;
  9508. table_cell_style(rows[rr], c, st, &cs);
  9509. if (cs.display == BR_DISPLAY_NONE)
  9510. continue;
  9511. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  9512. col++;
  9513. if (col >= TBL_MAX_COLS)
  9514. break;
  9515. rs = cn->rowspan ? cn->rowspan : 1;
  9516. csn = cn->colspan ? cn->colspan : 1;
  9517. if (rr + rs > nrows)
  9518. rs = nrows - rr;
  9519. if (col + csn > TBL_MAX_COLS)
  9520. csn = TBL_MAX_COLS - col;
  9521. if (rs < 1 || csn < 1)
  9522. continue;
  9523. if (ncells >= TBL_MAX_CELLS)
  9524. break;
  9525. tbl_cells[ncells].node = c;
  9526. tbl_cells[ncells].row = (unsigned char)rr;
  9527. tbl_cells[ncells].col = (unsigned char)col;
  9528. tbl_cells[ncells].rowspan = (unsigned char)rs;
  9529. tbl_cells[ncells].colspan = (unsigned char)csn;
  9530. tbl_cells[ncells].height = 0;
  9531. for (i = rr; i < rr + rs; i++)
  9532. for (int j = col; j < col + csn; j++)
  9533. tbl_at[i][j] =
  9534. (unsigned short)(ncells + 1);
  9535. ncells++;
  9536. col += csn;
  9537. if (col > cols)
  9538. cols = col;
  9539. }
  9540. }
  9541. if (!ncells || cols < 1) {
  9542. table_active = 0;
  9543. layout_children(l, table, st, depth, link);
  9544. return;
  9545. }
  9546. for (i = 0; i < cols; i++) {
  9547. raw[i] = 0;
  9548. fixed[i] = 0;
  9549. }
  9550. /* Intrinsic widths of single-column cells. */
  9551. for (i = 0; i < ncells; i++) {
  9552. struct br_style cs;
  9553. int w;
  9554. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  9555. st, &cs);
  9556. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  9557. mp_px(&cs, 7, avail) +
  9558. mp_px(&cs, 5, avail) +
  9559. mp_px(&cs, 3, avail) +
  9560. mp_px(&cs, 1, avail) +
  9561. cs.border_w[0] + cs.border_w[1] +
  9562. cs.border_w[2] + cs.border_w[3];
  9563. if (w < 24)
  9564. w = 24;
  9565. if (tbl_cells[i].colspan == 1) {
  9566. int col = tbl_cells[i].col;
  9567. if (w > raw[col])
  9568. raw[col] = w;
  9569. }
  9570. }
  9571. /* A spanning cell only needs the sum of its columns to be large
  9572. * enough; put the deficit in the last column. */
  9573. for (i = 0; i < ncells; i++) {
  9574. struct br_style cs;
  9575. int w, sum, col, span;
  9576. if (tbl_cells[i].colspan < 2)
  9577. continue;
  9578. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  9579. st, &cs);
  9580. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  9581. mp_px(&cs, 7, avail) +
  9582. mp_px(&cs, 5, avail) +
  9583. mp_px(&cs, 3, avail) +
  9584. mp_px(&cs, 1, avail) +
  9585. cs.border_w[0] + cs.border_w[1] +
  9586. cs.border_w[2] + cs.border_w[3];
  9587. col = tbl_cells[i].col;
  9588. span = tbl_cells[i].colspan;
  9589. sum = 0;
  9590. for (int j = 0; j < span; j++)
  9591. sum += raw[col + j];
  9592. if (w > sum)
  9593. raw[col + span - 1] += w - sum;
  9594. }
  9595. /* Explicit/percentage widths, as in table_columns(). */
  9596. for (i = 0; i < ncells; i++) {
  9597. struct br_style cs;
  9598. int col;
  9599. if (tbl_cells[i].colspan != 1)
  9600. continue;
  9601. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  9602. st, &cs);
  9603. col = tbl_cells[i].col;
  9604. if (cs.width_kind == 1) {
  9605. raw[col] = cs.width;
  9606. fixed[col] = 1;
  9607. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  9608. raw[col] = style_width_px(&cs, avail);
  9609. fixed[col] = 1;
  9610. }
  9611. }
  9612. for (i = 0; i < cols; i++) {
  9613. if (raw[i] < 8)
  9614. raw[i] = 8;
  9615. total += raw[i];
  9616. if (fixed[i])
  9617. fixed_sum += raw[i];
  9618. else {
  9619. free_raw += raw[i];
  9620. free_cols++;
  9621. }
  9622. }
  9623. if (fixed_sum > 0 && fixed_sum < avail) {
  9624. int free_avail = avail - fixed_sum;
  9625. if (free_raw > 0) {
  9626. for (i = 0; i < cols; i++)
  9627. if (!fixed[i])
  9628. raw[i] = free_avail * raw[i] /
  9629. free_raw;
  9630. } else if (free_cols > 0) {
  9631. for (i = 0; i < cols; i++)
  9632. if (!fixed[i])
  9633. raw[i] = free_avail / free_cols;
  9634. }
  9635. } else if (total < avail && total > 0) {
  9636. for (i = 0; i < cols; i++)
  9637. raw[i] = raw[i] * avail / total;
  9638. }
  9639. prefix[0] = table_left;
  9640. for (i = 0; i < cols; i++)
  9641. prefix[i + 1] = prefix[i] + raw[i];
  9642. /* Measure natural cell heights with the column widths. */
  9643. for (i = 0; i < ncells; i++) {
  9644. struct br_style cs;
  9645. int col = tbl_cells[i].col;
  9646. int span = tbl_cells[i].colspan;
  9647. int w = prefix[col + span] - prefix[col];
  9648. int sl = l->left, sr = l->right, sy = l->y;
  9649. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  9650. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  9651. int sal = l->align, sdraw = l->draw;
  9652. struct ngui *sui = l->ui;
  9653. if (w < 8)
  9654. w = 8;
  9655. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  9656. st, &cs);
  9657. cs.width_kind = 0;
  9658. cs.max_width_kind = 0;
  9659. l->draw = 0;
  9660. l->ui = 0;
  9661. l->left = prefix[col];
  9662. l->right = l->left + w;
  9663. l->y = 0;
  9664. l->line_x = l->left;
  9665. l->run_x = l->left;
  9666. l->line_y = 0;
  9667. l->line_h = 0;
  9668. l->nruns = 0;
  9669. l->space_pending = 0;
  9670. l->align = cs.align;
  9671. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  9672. tbl_cells[i].height = block_h[tbl_cells[i].node];
  9673. l->left = sl;
  9674. l->right = sr;
  9675. l->y = sy;
  9676. l->line_x = slx;
  9677. l->run_x = srx;
  9678. l->line_y = sly;
  9679. l->line_h = slh;
  9680. l->nruns = snr;
  9681. l->space_pending = ssp;
  9682. l->align = sal;
  9683. l->draw = sdraw;
  9684. l->ui = sui;
  9685. }
  9686. for (i = 0; i < nrows; i++)
  9687. rowh[i] = 0;
  9688. for (i = 0; i < ncells; i++) {
  9689. int row = tbl_cells[i].row;
  9690. if (tbl_cells[i].rowspan == 1) {
  9691. if (tbl_cells[i].height > rowh[row])
  9692. rowh[row] = tbl_cells[i].height;
  9693. }
  9694. }
  9695. for (i = 0; i < ncells; i++) {
  9696. int row = tbl_cells[i].row;
  9697. int span = tbl_cells[i].rowspan;
  9698. int sum = 0;
  9699. if (span < 2)
  9700. continue;
  9701. for (int j = 0; j < span; j++)
  9702. sum += rowh[row + j];
  9703. if (sum < tbl_cells[i].height)
  9704. rowh[row + span - 1] +=
  9705. tbl_cells[i].height - sum;
  9706. }
  9707. for (i = 0; i < nrows; i++)
  9708. if (rowh[i] < 8)
  9709. rowh[i] = 8;
  9710. rowy[0] = top;
  9711. for (i = 1; i < nrows; i++)
  9712. rowy[i] = rowy[i - 1] + rowh[i - 1];
  9713. if (!l->draw) {
  9714. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  9715. table_active = 0;
  9716. return;
  9717. }
  9718. for (i = 0; i < ncells; i++) {
  9719. struct br_style cs;
  9720. int col = tbl_cells[i].col;
  9721. int span = tbl_cells[i].colspan;
  9722. int row = tbl_cells[i].row;
  9723. int rspan = tbl_cells[i].rowspan;
  9724. int w = prefix[col + span] - prefix[col];
  9725. int h = 0;
  9726. int sl = l->left, sr = l->right, sy = l->y;
  9727. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  9728. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  9729. int sal = l->align;
  9730. int deco;
  9731. for (int j = 0; j < rspan; j++)
  9732. h += rowh[row + j];
  9733. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  9734. cs.width_kind = 0;
  9735. cs.max_width_kind = 0;
  9736. cs.box_sizing = 0;
  9737. deco = mp_px(&cs, 4, avail) +
  9738. mp_px(&cs, 6, avail) +
  9739. cs.border_w[0] + cs.border_w[2];
  9740. cs.height_kind = 1;
  9741. cs.height = h > deco ? h - deco : 0;
  9742. /* The block painter reads block_h[] from the measure pass; make
  9743. * the table cell fill its row/rowspan, not just its content. */
  9744. if (h > 0 && h < 65536)
  9745. block_h[tbl_cells[i].node] = (unsigned short)h;
  9746. l->left = prefix[col];
  9747. l->right = l->left + w;
  9748. l->y = rowy[row];
  9749. l->line_x = l->left;
  9750. l->run_x = l->left;
  9751. l->line_y = l->y;
  9752. l->line_h = 0;
  9753. l->nruns = 0;
  9754. l->space_pending = 0;
  9755. l->align = cs.align;
  9756. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  9757. l->left = sl;
  9758. l->right = sr;
  9759. l->y = sy;
  9760. l->line_x = slx;
  9761. l->run_x = srx;
  9762. l->line_y = sly;
  9763. l->line_h = slh;
  9764. l->nruns = snr;
  9765. l->space_pending = ssp;
  9766. l->align = sal;
  9767. }
  9768. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  9769. table_active = 0;
  9770. }
  9771. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  9772. * flow so they sit above it, like CSS painting order. Their flow origin is
  9773. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  9774. struct br_deferred {
  9775. unsigned int node;
  9776. int flow_y, flow_left, flow_right;
  9777. int parent_top; /* the parent box top, for sticky clamping */
  9778. unsigned short link;
  9779. signed short z_index;
  9780. unsigned char z_set;
  9781. unsigned int order;
  9782. };
  9783. /* Positioned boxes painted after the flow. News front pages have one or two
  9784. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  9785. * old 16 entries the rest fell back into the flow, so a hero image landed
  9786. * below its padding-top aspect box instead of on top of it. */
  9787. #define BR_MAX_DEFERRED 256
  9788. static struct br_deferred deferred[BR_MAX_DEFERRED];
  9789. static int ndeferred;
  9790. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  9791. * element's line. A block-level pseudo-element gets its own line; its box
  9792. * (margins, padding, background) is not drawn. */
  9793. static void emit_pseudo(struct lay *l, unsigned int node,
  9794. const struct br_style *st, int pe, unsigned short link)
  9795. {
  9796. char buf[160];
  9797. struct br_style ps;
  9798. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  9799. unsigned int i = 0;
  9800. int block, space_w;
  9801. if (!n)
  9802. return;
  9803. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  9804. if (block)
  9805. flush_line(l);
  9806. if (ps.uppercase)
  9807. for (i = 0; i < n; i++)
  9808. if (buf[i] >= 'a' && buf[i] <= 'z')
  9809. buf[i] = (char)(buf[i] - 'a' + 'A');
  9810. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  9811. if (space_w <= 0)
  9812. space_w = 8;
  9813. i = 0;
  9814. while (i < n) {
  9815. char word[28];
  9816. unsigned int k = 0;
  9817. int w;
  9818. if (buf[i] == ' ') {
  9819. l->space_pending = 1;
  9820. i++;
  9821. continue;
  9822. }
  9823. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  9824. word[k++] = buf[i++];
  9825. word[k] = '\0';
  9826. if (l->space_pending &&
  9827. (l->nruns > 0 || l->line_x > l->line_left) &&
  9828. l->line_x + space_w <= l->line_right)
  9829. l->line_x += space_w;
  9830. l->space_pending = 0;
  9831. w = (int)face_text_width(l->ui, &ps, word, k);
  9832. if (l->line_x + w > l->line_right &&
  9833. (l->nruns > 0 || l->line_x > l->line_left))
  9834. flush_line(l);
  9835. add_run(l, 0, 0, &ps, link, word);
  9836. }
  9837. if (block)
  9838. flush_line(l);
  9839. }
  9840. static void layout_children(struct lay *l, unsigned int parent,
  9841. const struct br_style *pst, int depth,
  9842. unsigned short link)
  9843. {
  9844. unsigned int n;
  9845. if (depth > 48)
  9846. return;
  9847. emit_pseudo(l, parent, pst, 1, link);
  9848. n = doc.nodes[parent].first;
  9849. while (n) {
  9850. struct br_node *nd = &doc.nodes[n];
  9851. struct br_style cs;
  9852. unsigned short lk = link;
  9853. if (nd->type == BR_NODE_TEXT) {
  9854. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  9855. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  9856. n = nd->next;
  9857. continue;
  9858. }
  9859. br_style_for(&doc, n, pst, &cs);
  9860. if (cs.display == BR_DISPLAY_NONE) {
  9861. n = nd->next;
  9862. continue;
  9863. }
  9864. if (cs.clear && l->float_active) {
  9865. flush_line(l);
  9866. if (l->y < l->float_bottom)
  9867. l->y = l->float_bottom;
  9868. l->float_active = 0;
  9869. l->line_x = l->left;
  9870. l->run_x = l->left;
  9871. l->line_left = l->left;
  9872. l->line_right = l->right;
  9873. l->line_y = l->y;
  9874. l->line_h = 0;
  9875. l->nruns = 0;
  9876. l->space_pending = 0;
  9877. }
  9878. if (nd->tag == BR_TAG_A && nd->href_off)
  9879. lk = (unsigned short)n;
  9880. if (cs.pos == 1 || cs.pos == 2 ||
  9881. ((cs.pos == 3 || cs.pos == 4) && cs.z_set)) {
  9882. if ((cs.pos == 3 || cs.pos == 4) && l->draw &&
  9883. ndeferred < BR_MAX_DEFERRED) {
  9884. /* Relative or sticky z-index (a sticky site
  9885. * header): measure and advance the flow without
  9886. * painting, then paint it in the deferred
  9887. * (stacked) pass, above the content after it. */
  9888. int fy = l->y, fl = l->left, fr = l->right;
  9889. int save_draw = l->draw;
  9890. l->draw = 0;
  9891. layout_block(l, n, &cs, depth + 1, lk);
  9892. l->draw = save_draw;
  9893. deferred[ndeferred].node = n;
  9894. deferred[ndeferred].parent_top = l->parent_top;
  9895. deferred[ndeferred].flow_y = fy;
  9896. deferred[ndeferred].flow_left = fl;
  9897. deferred[ndeferred].flow_right = fr;
  9898. deferred[ndeferred].link = lk;
  9899. deferred[ndeferred].z_index = cs.z_index;
  9900. deferred[ndeferred].z_set = cs.z_set;
  9901. deferred[ndeferred].order = (unsigned int)ndeferred;
  9902. ndeferred++;
  9903. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  9904. deferred[ndeferred].node = n;
  9905. deferred[ndeferred].parent_top = l->parent_top;
  9906. deferred[ndeferred].flow_y =
  9907. cs.pos == 1 ? l->cb_top : l->y;
  9908. deferred[ndeferred].flow_left =
  9909. cs.pos == 1 ? l->cb_left : l->left;
  9910. deferred[ndeferred].flow_right =
  9911. cs.pos == 1 ? l->cb_right : l->right;
  9912. deferred[ndeferred].link = lk;
  9913. deferred[ndeferred].z_index = cs.z_index;
  9914. deferred[ndeferred].z_set = cs.z_set;
  9915. deferred[ndeferred].order = (unsigned int)ndeferred;
  9916. ndeferred++;
  9917. } else if (l->draw && cs.pos == 1) {
  9918. /* Deferred list full: paint in place, but still
  9919. * against the containing block, not the flow. */
  9920. int fy = l->y, fl = l->left, fr = l->right;
  9921. l->y = l->cb_top;
  9922. l->left = l->cb_left;
  9923. l->right = l->cb_right;
  9924. layout_block(l, n, &cs, depth + 1, lk);
  9925. l->y = fy;
  9926. l->left = fl;
  9927. l->right = fr;
  9928. } else {
  9929. layout_block(l, n, &cs, depth + 1, lk);
  9930. }
  9931. if (cs.pos == 1 && block_h[n] &&
  9932. doc.nodes[n].class_off) {
  9933. const char *cl = doc.attrs +
  9934. doc.nodes[n].class_off;
  9935. if ((contains_ci(cl, "poster-wrapper") ||
  9936. contains_ci(cl, "ts-picture")) &&
  9937. !has_skeleton_sibling(n))
  9938. l->y += block_h[n];
  9939. }
  9940. n = nd->next;
  9941. continue;
  9942. }
  9943. if (nd->tag == BR_TAG_BR) {
  9944. flush_line(l);
  9945. n = nd->next;
  9946. continue;
  9947. }
  9948. if (nd->tag == BR_TAG_HR) {
  9949. flush_line(l);
  9950. if (l->draw)
  9951. ngui_fill_rect(l->ui,
  9952. (struct ngui_rect){l->left, l->y + 2,
  9953. l->right - l->left, 1}, BR_GRAY);
  9954. l->y += 8;
  9955. n = nd->next;
  9956. continue;
  9957. }
  9958. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  9959. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  9960. !button_has_elements(n)) {
  9961. if (!(nd->tag == BR_TAG_INPUT &&
  9962. s_eq(br_type(&doc, n), "hidden"))) {
  9963. form_fill_line = pst->display ==
  9964. BR_DISPLAY_FLEX &&
  9965. pst->flex_col;
  9966. add_form_run(l, n, &cs, lk);
  9967. form_fill_line = 0;
  9968. }
  9969. n = nd->next;
  9970. continue;
  9971. }
  9972. if (nd->tag == BR_TAG_IMG) {
  9973. add_image_run(l, n, &cs, lk);
  9974. n = nd->next;
  9975. continue;
  9976. }
  9977. if (nd->tag == BR_TAG_SVG &&
  9978. (cs.display == BR_DISPLAY_INLINE ||
  9979. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  9980. !cs.float_left) {
  9981. add_svg_run(l, n, &cs, lk);
  9982. n = nd->next;
  9983. continue;
  9984. }
  9985. if (nd->tag == BR_TAG_VIDEO) {
  9986. layout_block(l, n, &cs, depth + 1, lk);
  9987. n = nd->next;
  9988. continue;
  9989. }
  9990. if (cs.float_left) {
  9991. n = layout_float_group(l, n, pst, depth, lk);
  9992. continue;
  9993. }
  9994. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  9995. inline_block_flows(n, &cs, 0)) {
  9996. layout_children(l, n, &cs, depth + 1, lk);
  9997. n = nd->next;
  9998. continue;
  9999. }
  10000. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  10001. n = layout_inline_blocks(l, n, pst, depth, link);
  10002. continue;
  10003. }
  10004. /* A flex container is block-level like any block box even when
  10005. * the element is an inline tag such as <a> (a link card with
  10006. * display:flex is common on news sites). Without the block box
  10007. * its children were laid out in the parent flow with a 0x0 box
  10008. * of their own. */
  10009. /* inline-flex around inline content only ("| mehr" link
  10010. * tails, icon+label pills) stays in the text line. */
  10011. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  10012. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  10013. !flex_wants_row(n, &cs)) {
  10014. layout_children(l, n, &cs, depth + 1, lk);
  10015. } else if (cs.display == BR_DISPLAY_BLOCK ||
  10016. cs.display == BR_DISPLAY_FLEX ||
  10017. br_tag_is_block(nd->tag))
  10018. layout_block(l, n, &cs, depth + 1, lk);
  10019. else {
  10020. layout_children(l, n, &cs, depth + 1, lk);
  10021. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  10022. l->space_pending = 1;
  10023. }
  10024. n = nd->next;
  10025. }
  10026. emit_pseudo(l, parent, pst, 2, link);
  10027. }
  10028. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  10029. * runs and a recursive page can otherwise overflow the stack. */
  10030. static struct lay layout_state;
  10031. static int measure_page(int left, int right)
  10032. {
  10033. struct lay *l = &layout_state;
  10034. struct br_style base = base_style();
  10035. unsigned int i;
  10036. for (i = 0; i < BR_MAX_NODES; i++) {
  10037. block_h[i] = 0;
  10038. img_top[i] = 0;
  10039. block_top[i] = 0;
  10040. img_h[i] = 0;
  10041. layout_boxes[i].valid = 0;
  10042. }
  10043. memset(li_marker, 0, sizeof(li_marker));
  10044. l->draw = 0;
  10045. l->ui = &ui;
  10046. l->left = left;
  10047. l->right = right;
  10048. l->y = 0;
  10049. l->line_x = left;
  10050. l->run_x = left;
  10051. l->line_left = left;
  10052. l->line_right = right;
  10053. l->line_y = 0;
  10054. l->line_h = 0;
  10055. l->align = BR_ALIGN_LEFT;
  10056. l->cb_h = layout_view_h;
  10057. l->float_active = 0;
  10058. l->parent_top = 0;
  10059. l->cb_left = left;
  10060. l->cb_right = right;
  10061. l->cb_top = 0;
  10062. l->depth = 0;
  10063. l->nruns = 0;
  10064. l->space_pending = 0;
  10065. layout_children(l, doc.root, &base, 0, 0);
  10066. return l->y + 8;
  10067. }
  10068. static int deferred_cmp(const struct br_deferred *a,
  10069. const struct br_deferred *b)
  10070. {
  10071. int az = a->z_set ? a->z_index : 0;
  10072. int bz = b->z_set ? b->z_index : 0;
  10073. if (az != bz)
  10074. return az < bz ? -1 : 1;
  10075. if (a->order != b->order)
  10076. return a->order < b->order ? -1 : 1;
  10077. return 0;
  10078. }
  10079. static void sort_deferred(void)
  10080. {
  10081. int i;
  10082. for (i = 1; i < ndeferred; i++) {
  10083. struct br_deferred key = deferred[i];
  10084. int j = i;
  10085. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  10086. deferred[j] = deferred[j - 1];
  10087. j--;
  10088. }
  10089. deferred[j] = key;
  10090. }
  10091. }
  10092. static void render_page(int left, int right, int y0)
  10093. {
  10094. struct lay *l = &layout_state;
  10095. struct br_style base = base_style();
  10096. l->draw = 1;
  10097. l->ui = &ui;
  10098. l->left = left;
  10099. l->right = right;
  10100. l->y = y0;
  10101. l->line_x = left;
  10102. l->run_x = left;
  10103. l->line_left = left;
  10104. l->line_right = right;
  10105. l->line_y = y0;
  10106. l->line_h = 0;
  10107. l->align = BR_ALIGN_LEFT;
  10108. l->cb_h = layout_view_h;
  10109. l->float_active = 0;
  10110. l->parent_top = 0;
  10111. l->cb_left = left;
  10112. l->cb_right = right;
  10113. l->cb_top = y0;
  10114. l->depth = 0;
  10115. l->nruns = 0;
  10116. l->space_pending = 0;
  10117. nhits = 0;
  10118. ndeferred = 0;
  10119. layout_children(l, doc.root, &base, 0, 0);
  10120. sort_deferred();
  10121. {
  10122. int i;
  10123. for (i = 0; i < ndeferred; i++) {
  10124. struct br_style st;
  10125. br_style_for(&doc, deferred[i].node, &base, &st);
  10126. if (st.display == BR_DISPLAY_NONE)
  10127. continue;
  10128. l->draw = 1;
  10129. l->left = deferred[i].flow_left;
  10130. l->right = deferred[i].flow_right;
  10131. l->y = deferred[i].flow_y;
  10132. l->parent_top = deferred[i].parent_top;
  10133. l->line_x = l->left;
  10134. l->run_x = l->left;
  10135. l->line_y = l->y;
  10136. l->line_h = 0;
  10137. l->nruns = 0;
  10138. l->space_pending = 0;
  10139. l->align = st.align;
  10140. if (st.pos == 2 && block_h[deferred[i].node]) {
  10141. struct ngui_rect clip;
  10142. int ch = block_h[deferred[i].node] + 24;
  10143. clip.x = page_rect.x;
  10144. clip.y = page_rect.y;
  10145. clip.w = page_rect.w - 12;
  10146. if (ch > page_rect.h)
  10147. ch = page_rect.h;
  10148. clip.h = ch;
  10149. ngui_push_clip(&ui, clip);
  10150. if (st.has_bg)
  10151. ngui_fill_rect(&ui, clip, st.bg);
  10152. layout_block(l, deferred[i].node, &st, 0,
  10153. deferred[i].link);
  10154. ngui_pop_clip(&ui);
  10155. } else {
  10156. layout_block(l, deferred[i].node, &st, 0,
  10157. deferred[i].link);
  10158. }
  10159. }
  10160. }
  10161. }
  10162. /* ---- UI ---- */
  10163. static int find_hit(int x, int y)
  10164. {
  10165. int i;
  10166. for (i = nhits - 1; i >= 0; i--) {
  10167. struct hit *h = &hits[i];
  10168. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  10169. y < h->y + h->h)
  10170. return (int)h->node;
  10171. }
  10172. return 0;
  10173. }
  10174. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  10175. {
  10176. int x = r.x + 4, y = r.y + 4, h = 22;
  10177. int compact = r.w < 560;
  10178. int go_w = r.w < 420 ? 32 : 42;
  10179. int in_x, in_w, res;
  10180. ngui_fill_rect(&ui, r, ui.theme.panel);
  10181. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  10182. ui.theme.border);
  10183. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  10184. NGUI_ICON_CHEVRON_LEFT))
  10185. *action |= ACT_BACK;
  10186. x += 32;
  10187. if (!compact) {
  10188. if (ngui_icon_button(&ui, ID_FORWARD,
  10189. (struct ngui_rect){x, y, 28, h},
  10190. NGUI_ICON_CHEVRON_RIGHT))
  10191. *action |= ACT_FORWARD;
  10192. x += 32;
  10193. }
  10194. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  10195. NGUI_ICON_REFRESH))
  10196. *action |= ACT_RELOAD;
  10197. x += 32;
  10198. if (!compact) {
  10199. if (ngui_icon_button(&ui, ID_HOME,
  10200. (struct ngui_rect){x, y, 28, h},
  10201. NGUI_ICON_HOME))
  10202. *action |= ACT_HOME;
  10203. x += 32;
  10204. }
  10205. in_x = x + 2;
  10206. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  10207. if (in_w < 60)
  10208. in_w = 60;
  10209. res = ngui_text_input(&ui, ID_URL,
  10210. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  10211. if (res & NGUI_INPUT_SUBMIT)
  10212. *action |= ACT_NAV;
  10213. if (res & NGUI_INPUT_CANCEL)
  10214. ngui_set_focus(&ui, 0);
  10215. if (ngui_button(&ui, ID_GO,
  10216. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  10217. "Go"))
  10218. *action |= ACT_NAV;
  10219. }
  10220. static int page_hover_node(void)
  10221. {
  10222. if (!ui.inside)
  10223. return 0;
  10224. if (ui.mouse_x < page_rect.x ||
  10225. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  10226. ui.mouse_y < page_rect.y ||
  10227. ui.mouse_y >= page_rect.y + page_rect.h)
  10228. return 0;
  10229. return find_hit(ui.mouse_x, ui.mouse_y);
  10230. }
  10231. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  10232. {
  10233. int x, y, w = page.w, h = page.h;
  10234. if (!src || w <= 0 || h <= 0)
  10235. return;
  10236. for (y = 0; y < h; y++) {
  10237. unsigned short *s = src + (page.y + y) * sw + page.x;
  10238. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  10239. for (x = 0; x + 1 < w; x += 2) {
  10240. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  10241. }
  10242. if (x < w)
  10243. d[x] = s[x];
  10244. }
  10245. }
  10246. static void draw_page(struct ngui_rect page)
  10247. {
  10248. int left, right, ch;
  10249. int old_panel, old_dim;
  10250. unsigned short *saved_px;
  10251. unsigned short page_bg = ui.theme.bg;
  10252. int saved_w, saved_h, use_buf;
  10253. unsigned int t0 = u_ticks_ms();
  10254. page_rect = page;
  10255. {
  10256. unsigned int root = doc.nnode > 1 ?
  10257. br_find_tag(&doc, BR_TAG_HTML) : 0;
  10258. unsigned int body = doc.nnode > 1 ?
  10259. br_find_tag(&doc, BR_TAG_BODY) : 0;
  10260. struct br_style bs;
  10261. if (root) {
  10262. style_for_node(root - 1, &bs);
  10263. if (bs.has_bg)
  10264. page_bg = bs.bg;
  10265. }
  10266. if (body) {
  10267. style_for_node(body - 1, &bs);
  10268. if (bs.has_bg)
  10269. page_bg = bs.bg;
  10270. }
  10271. }
  10272. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  10273. page_cache_valid && layout_valid &&
  10274. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  10275. !(ui.scroll_y &&
  10276. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  10277. page_scroll.offset == page_cache_scroll &&
  10278. page_cache_nnode == doc.nnode &&
  10279. page_cache_x == page.x && page_cache_y == page.y &&
  10280. page_cache_w == page.w && page_cache_h == page.h) {
  10281. blit_page(page, page_backbuf, pagebuf_w);
  10282. if (img_stat_n)
  10283. img_stat_paint += u_ticks_ms() - t0;
  10284. return;
  10285. }
  10286. ngui_fill_rect(&ui, page, page_bg);
  10287. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  10288. const char *s = page_loading ? "Loading..." : "No page";
  10289. int w = (int)ngui_text_width_ui(&ui, s);
  10290. ngui_text(&ui, page.x + (page.w - w) / 2,
  10291. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  10292. page_scroll.content_h = 0;
  10293. page_scroll.view_h = page.h;
  10294. page_cache_valid = 0;
  10295. return;
  10296. }
  10297. if (page.w < 40 || page.h < 40) {
  10298. page_cache_valid = 0;
  10299. return;
  10300. }
  10301. saved_px = ui.px;
  10302. saved_w = ui.w;
  10303. saved_h = ui.h;
  10304. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  10305. if (use_buf) {
  10306. ui.px = page_backbuf;
  10307. ui.w = pagebuf_w;
  10308. ui.h = pagebuf_h;
  10309. ngui_fill_rect(&ui, page, page_bg);
  10310. }
  10311. left = page.x + 8;
  10312. right = page.x + page.w - 16;
  10313. if (!layout_valid || left != layout_left || right != layout_right ||
  10314. layout_nnode != doc.nnode) {
  10315. unsigned int tm = u_ticks_ms();
  10316. layout_view_h = page.h - 8;
  10317. layout_content_h = measure_page(left, right);
  10318. if (img_stat_n)
  10319. img_stat_reflow += u_ticks_ms() - tm;
  10320. layout_valid = 1;
  10321. layout_left = left;
  10322. layout_right = right;
  10323. layout_nnode = doc.nnode;
  10324. /* Scripts that measured before any layout (offsetWidth on
  10325. * mount) get a resize event once real boxes exist, and again
  10326. * whenever the page width changes. */
  10327. if (js_browser_active() && right - left != resize_sent_w)
  10328. resize_pending = 1;
  10329. }
  10330. ch = layout_content_h;
  10331. page_scroll.content_h = ch;
  10332. page_scroll.view_h = page.h;
  10333. t0 = u_ticks_ms();
  10334. ngui_scroll_begin(&ui, page, &page_scroll);
  10335. ngui_scroll_wheel(&ui, page, &page_scroll);
  10336. render_page(left, right, page.y + 4 - page_scroll.offset);
  10337. old_panel = ui.theme.panel_alt;
  10338. old_dim = ui.theme.text_dim;
  10339. ui.theme.panel_alt = 0xC618;
  10340. ui.theme.text_dim = 0x8410;
  10341. ngui_scroll_end(&ui, page, &page_scroll);
  10342. ui.theme.panel_alt = old_panel;
  10343. ui.theme.text_dim = old_dim;
  10344. if (use_buf) {
  10345. ui.px = saved_px;
  10346. ui.w = saved_w;
  10347. ui.h = saved_h;
  10348. blit_page(page, page_backbuf, pagebuf_w);
  10349. page_cache_valid = 1;
  10350. page_cache_scroll = page_scroll.offset;
  10351. page_cache_nnode = doc.nnode;
  10352. page_cache_x = page.x;
  10353. page_cache_y = page.y;
  10354. page_cache_w = page.w;
  10355. page_cache_h = page.h;
  10356. } else {
  10357. page_cache_valid = 0;
  10358. }
  10359. if (img_stat_n)
  10360. img_stat_paint += u_ticks_ms() - t0;
  10361. }
  10362. static void draw_status(struct ngui_rect r)
  10363. {
  10364. static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
  10365. unsigned int n = 0;
  10366. int hover = page_hover_node();
  10367. unsigned short color;
  10368. const char *kind;
  10369. ngui_fill_rect(&ui, r, ui.theme.panel);
  10370. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  10371. ui.theme.border);
  10372. if (hover) {
  10373. const char *href = br_href(&doc, (unsigned int)hover);
  10374. char url[BR_URL_MAX];
  10375. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  10376. s_append(msg, &n, "Link: ", sizeof(msg));
  10377. s_append(msg, &n, url, sizeof(msg));
  10378. } else {
  10379. s_copy(msg, "Link", sizeof(msg));
  10380. }
  10381. color = ui.theme.accent;
  10382. } else if (status_text[0]) {
  10383. s_copy(msg, status_text, sizeof(msg));
  10384. color = status_error ? ui.theme.error : ui.theme.text;
  10385. } else if (page_title[0]) {
  10386. s_copy(msg, page_title, sizeof(msg));
  10387. color = ui.theme.text;
  10388. } else {
  10389. s_copy(msg, "Ready", sizeof(msg));
  10390. color = ui.theme.text_dim;
  10391. }
  10392. kind = s_eq(page_url, "about:home") ? "HOME" :
  10393. page_is_local ? "FILE" :
  10394. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  10395. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  10396. {
  10397. int kw = (int)ngui_text_width_ui(&ui, kind);
  10398. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  10399. ui.theme.text_dim);
  10400. }
  10401. }
  10402. static void draw(unsigned int *action)
  10403. {
  10404. struct ngui_rect r = {0, 0, ui.w, ui.h};
  10405. struct ngui_rect toolbar, status, page;
  10406. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  10407. status = ngui_cut_bottom(&r, BR_STATUS_H);
  10408. page = r;
  10409. draw_toolbar(toolbar, action);
  10410. draw_page(page);
  10411. draw_status(status);
  10412. }
  10413. static void redraw_now(void)
  10414. {
  10415. unsigned int action = 0;
  10416. ngui_begin(&ui);
  10417. draw(&action);
  10418. ngui_end(&ui);
  10419. }
  10420. static void handle_keys(unsigned int *action)
  10421. {
  10422. int k, scrolled = 0;
  10423. if (form_focus >= doc.nnode)
  10424. form_focus = 0;
  10425. if (form_focus && !ngui_focus(&ui)) {
  10426. while ((k = ngui_key(&ui)) != 0)
  10427. form_key(k);
  10428. return;
  10429. }
  10430. /* Batch queued page keys: a slow full-page render must not make a
  10431. * held Page Down advance only once every few frames. */
  10432. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  10433. scrolled++;
  10434. if (scrolled)
  10435. ngui_invalidate(&ui);
  10436. if (ngui_focus(&ui))
  10437. return;
  10438. while ((k = ngui_key(&ui)) != 0) {
  10439. switch (k) {
  10440. case NGUI_KEY_ESC:
  10441. *action |= ACT_CLOSE;
  10442. break;
  10443. case NGUI_KEY_TAB:
  10444. case 0x0C: /* Ctrl+L */
  10445. ngui_set_focus(&ui, ID_URL);
  10446. break;
  10447. case 0x12: /* Ctrl+R */
  10448. *action |= ACT_RELOAD;
  10449. break;
  10450. case NGUI_KEY_BACKSPACE:
  10451. *action |= ACT_BACK;
  10452. break;
  10453. case NGUI_KEY_UP:
  10454. ngui_scroll_to(&page_scroll,
  10455. page_scroll.offset - 24);
  10456. ngui_invalidate(&ui);
  10457. break;
  10458. case NGUI_KEY_DOWN:
  10459. ngui_scroll_to(&page_scroll,
  10460. page_scroll.offset + 24);
  10461. ngui_invalidate(&ui);
  10462. break;
  10463. case NGUI_KEY_HOME:
  10464. ngui_scroll_to(&page_scroll, 0);
  10465. ngui_invalidate(&ui);
  10466. break;
  10467. case NGUI_KEY_END:
  10468. ngui_scroll_to(&page_scroll,
  10469. page_scroll.content_h -
  10470. page_scroll.view_h);
  10471. ngui_invalidate(&ui);
  10472. break;
  10473. default:
  10474. break;
  10475. }
  10476. }
  10477. }
  10478. static unsigned int form_ancestor(unsigned int node)
  10479. {
  10480. unsigned int p = node;
  10481. while (p && p < doc.nnode) {
  10482. if (doc.nodes[p].tag == BR_TAG_FORM &&
  10483. doc.nodes[p].type == BR_NODE_ELEM)
  10484. return p;
  10485. p = doc.nodes[p].parent;
  10486. }
  10487. return 0;
  10488. }
  10489. static int form_descendant(unsigned int node, unsigned int form)
  10490. {
  10491. unsigned int p = node;
  10492. while (p && p < doc.nnode) {
  10493. if (p == form)
  10494. return 1;
  10495. p = doc.nodes[p].parent;
  10496. }
  10497. return 0;
  10498. }
  10499. static void form_reset_form(unsigned int form)
  10500. {
  10501. unsigned int i;
  10502. for (i = 0; i < FORM_MAX; i++)
  10503. if (form_states[i].used &&
  10504. form_descendant(form_states[i].node, form))
  10505. form_states[i].used = 0;
  10506. form_focus = 0;
  10507. }
  10508. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  10509. const char *s)
  10510. {
  10511. static const char hex[] = "0123456789ABCDEF";
  10512. while (s && *s && *n + 1 < cap) {
  10513. unsigned char c = (unsigned char)*s++;
  10514. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  10515. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  10516. c == '.' || c == '~') {
  10517. dst[(*n)++] = (char)c;
  10518. } else if (c == ' ') {
  10519. dst[(*n)++] = '+';
  10520. } else if (*n + 3 < cap) {
  10521. dst[(*n)++] = '%';
  10522. dst[(*n)++] = hex[c >> 4];
  10523. dst[(*n)++] = hex[c & 15];
  10524. }
  10525. }
  10526. dst[*n] = '\0';
  10527. }
  10528. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  10529. const char *name, const char *value, int *first)
  10530. {
  10531. if (!name || !name[0])
  10532. return;
  10533. if (!*first && *n + 1 < cap)
  10534. dst[(*n)++] = '&';
  10535. *first = 0;
  10536. form_url_append(dst, n, cap, name);
  10537. if (*n + 1 < cap)
  10538. dst[(*n)++] = '=';
  10539. form_url_append(dst, n, cap, value ? value : "");
  10540. dst[*n] = '\0';
  10541. }
  10542. static int form_submit_form(unsigned int node, int fire_event)
  10543. {
  10544. unsigned int form = form_ancestor(node);
  10545. char action[BR_URL_MAX], query[2048];
  10546. unsigned int qn = 0, i;
  10547. int first = 1, is_post = 0;
  10548. const char *a, *method;
  10549. if (!form)
  10550. return 0;
  10551. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  10552. return 0;
  10553. method = br_find_attr(&doc, form, "method");
  10554. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  10555. is_post = 1;
  10556. a = br_find_attr(&doc, form, "action");
  10557. if (a && a[0]) {
  10558. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  10559. return 0;
  10560. } else {
  10561. s_copy(action, page_url, sizeof(action));
  10562. }
  10563. query[0] = '\0';
  10564. for (i = 0; i < doc.nnode; i++) {
  10565. struct br_node *nd = &doc.nodes[i];
  10566. struct form_state *fs;
  10567. const char *name;
  10568. const char *value = "";
  10569. if (nd->type != BR_NODE_ELEM || i == form ||
  10570. !form_descendant(i, form))
  10571. continue;
  10572. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  10573. nd->tag != BR_TAG_SELECT)
  10574. continue;
  10575. if (form_disabled(i))
  10576. continue;
  10577. name = br_find_attr(&doc, i, "name");
  10578. if (!name || !name[0])
  10579. continue;
  10580. fs = form_get(i, 1);
  10581. if (!fs)
  10582. continue;
  10583. if (nd->tag == BR_TAG_SELECT) {
  10584. char opt[64];
  10585. if (!form_option_text(i, fs->selected, opt,
  10586. sizeof(opt)))
  10587. s_copy(opt, "", sizeof(opt));
  10588. value = opt;
  10589. {
  10590. unsigned int c, oi = 0;
  10591. for (c = nd->first; c;
  10592. c = doc.nodes[c].next) {
  10593. if (doc.nodes[c].type != BR_NODE_ELEM ||
  10594. doc.nodes[c].tag != BR_TAG_OPTION)
  10595. continue;
  10596. if (oi == fs->selected) {
  10597. const char *v =
  10598. br_value(&doc, c);
  10599. if (v && v[0])
  10600. value = v;
  10601. break;
  10602. }
  10603. oi++;
  10604. }
  10605. }
  10606. } else if (nd->tag == BR_TAG_INPUT) {
  10607. int kind = form_kind_of(i);
  10608. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  10609. if (!fs->checked)
  10610. continue;
  10611. value = br_value(&doc, i);
  10612. if (!value || !value[0])
  10613. value = "on";
  10614. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  10615. kind == FORM_BUTTON) {
  10616. if (i != node)
  10617. continue;
  10618. value = fs->value;
  10619. } else {
  10620. value = fs->value;
  10621. }
  10622. } else {
  10623. value = fs->value;
  10624. }
  10625. form_add_param(query, &qn, sizeof(query), name, value, &first);
  10626. }
  10627. if (is_post) {
  10628. if (action[0] == '/') {
  10629. set_status("POST forms need an HTTP action URL", 1, 4000);
  10630. ngui_invalidate(&ui);
  10631. return 0;
  10632. }
  10633. if (qn >= sizeof(pending_post))
  10634. qn = sizeof(pending_post) - 1;
  10635. if (qn)
  10636. memcpy(pending_post, query, qn);
  10637. pending_post[qn] = '\0';
  10638. pending_post_len = qn;
  10639. pending_post_is = 1;
  10640. } else {
  10641. pending_post_len = 0;
  10642. pending_post_is = 0;
  10643. if (qn) {
  10644. unsigned int an = s_len(action);
  10645. if (an + qn + 2 < sizeof(action)) {
  10646. action[an++] = strchr(action, '?') ? '&' : '?';
  10647. action[an] = '\0';
  10648. s_copy(action + an, query,
  10649. sizeof(action) - an);
  10650. }
  10651. }
  10652. }
  10653. s_copy(pending_url, action, sizeof(pending_url));
  10654. pending_action |= ACT_NAV;
  10655. cancel_fetch = 1;
  10656. ngui_invalidate(&ui);
  10657. return 1;
  10658. }
  10659. static void form_reset_event(unsigned int form)
  10660. {
  10661. if (form && !js_browser_event(form, "reset", 1, 1))
  10662. return;
  10663. if (form)
  10664. form_reset_form(form);
  10665. else
  10666. form_reset_state();
  10667. form_dirty = 0;
  10668. layout_valid = 0;
  10669. ngui_invalidate(&ui);
  10670. }
  10671. static void form_blur(void)
  10672. {
  10673. unsigned int node = form_focus;
  10674. form_focus = 0;
  10675. if (node && form_dirty) {
  10676. form_dirty = 0;
  10677. js_browser_event(node, "change", 1, 0);
  10678. }
  10679. }
  10680. static void form_click(unsigned int node)
  10681. {
  10682. struct form_state *fs;
  10683. int kind, changed = 0;
  10684. if (!form_is_control(node) || form_disabled(node))
  10685. return;
  10686. if (form_focus != node)
  10687. form_blur();
  10688. if (!js_browser_event(node, "click", 1, 1))
  10689. return;
  10690. fs = form_get(node, 1);
  10691. if (!fs)
  10692. return;
  10693. kind = form_kind_of(node);
  10694. form_focus = node;
  10695. form_dirty = 0;
  10696. if (kind == FORM_CHECKBOX) {
  10697. fs->checked = !fs->checked;
  10698. changed = 1;
  10699. } else if (kind == FORM_RADIO) {
  10700. const char *name = br_find_attr(&doc, node, "name");
  10701. unsigned int i;
  10702. fs->checked = 1;
  10703. changed = 1;
  10704. if (name) {
  10705. for (i = 0; i < FORM_MAX; i++) {
  10706. struct form_state *o = &form_states[i];
  10707. if (!o->used || o->node == node)
  10708. continue;
  10709. if (form_kind_of(o->node) == FORM_RADIO) {
  10710. const char *on = br_find_attr(&doc,
  10711. o->node,
  10712. "name");
  10713. if (on && s_eq(on, name))
  10714. o->checked = 0;
  10715. }
  10716. }
  10717. }
  10718. } else if (kind == FORM_SELECT) {
  10719. unsigned int n = form_option_count(node);
  10720. if (n) {
  10721. fs->selected = (unsigned char)
  10722. ((fs->selected + 1) % n);
  10723. changed = 1;
  10724. }
  10725. } else if (kind == FORM_SUBMIT) {
  10726. form_submit_form(node, 1);
  10727. return;
  10728. } else if (kind == FORM_RESET) {
  10729. form_reset_event(form_ancestor(node));
  10730. return;
  10731. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  10732. kind == FORM_TEXTAREA) {
  10733. fs->caret = fs->len;
  10734. }
  10735. if (changed) {
  10736. js_browser_event(node, "input", 1, 0);
  10737. js_browser_event(node, "change", 1, 0);
  10738. }
  10739. layout_valid = 0;
  10740. ngui_invalidate(&ui);
  10741. }
  10742. static void form_focus_next(void)
  10743. {
  10744. unsigned int start = form_focus ? form_focus + 1 : 0;
  10745. unsigned int i;
  10746. form_blur();
  10747. for (i = start; i < doc.nnode; i++) {
  10748. if (form_is_control(i) && !form_disabled(i) &&
  10749. !s_eq(br_type(&doc, i), "hidden")) {
  10750. form_focus = i;
  10751. layout_valid = 0;
  10752. ngui_invalidate(&ui);
  10753. return;
  10754. }
  10755. }
  10756. form_focus = 0;
  10757. layout_valid = 0;
  10758. ngui_invalidate(&ui);
  10759. }
  10760. static void form_key(int k)
  10761. {
  10762. struct form_state *fs;
  10763. int kind;
  10764. if (!form_focus || form_focus >= doc.nnode) {
  10765. form_focus = 0;
  10766. return;
  10767. }
  10768. fs = form_get(form_focus, 1);
  10769. if (!fs || form_disabled(form_focus))
  10770. return;
  10771. kind = form_kind_of(form_focus);
  10772. if (kind == FORM_SELECT) {
  10773. unsigned int n = form_option_count(form_focus);
  10774. int changed = 0;
  10775. if (k == NGUI_KEY_UP && n) {
  10776. fs->selected = (unsigned char)
  10777. ((fs->selected + n - 1) % n);
  10778. changed = 1;
  10779. } else if (k == NGUI_KEY_DOWN && n) {
  10780. fs->selected = (unsigned char)
  10781. ((fs->selected + 1) % n);
  10782. changed = 1;
  10783. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  10784. form_blur();
  10785. layout_valid = 0;
  10786. ngui_invalidate(&ui);
  10787. return;
  10788. } else {
  10789. return;
  10790. }
  10791. if (changed) {
  10792. js_browser_event(form_focus, "input", 1, 0);
  10793. js_browser_event(form_focus, "change", 1, 0);
  10794. }
  10795. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  10796. if (k == ' ') {
  10797. form_click(form_focus);
  10798. return;
  10799. }
  10800. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  10801. form_blur();
  10802. layout_valid = 0;
  10803. ngui_invalidate(&ui);
  10804. }
  10805. return;
  10806. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  10807. kind == FORM_RESET) {
  10808. if (k == NGUI_KEY_ESC) {
  10809. form_blur();
  10810. layout_valid = 0;
  10811. ngui_invalidate(&ui);
  10812. } else if (k == '\r' || k == '\n' || k == ' ') {
  10813. form_click(form_focus);
  10814. }
  10815. return;
  10816. } else if (k == NGUI_KEY_TAB) {
  10817. form_focus_next();
  10818. return;
  10819. } else if (k == NGUI_KEY_ESC) {
  10820. form_blur();
  10821. layout_valid = 0;
  10822. ngui_invalidate(&ui);
  10823. return;
  10824. } else if (k == '\r' || k == '\n') {
  10825. unsigned int node = form_focus;
  10826. form_blur();
  10827. if (form_ancestor(node))
  10828. form_submit_form(node, 1);
  10829. layout_valid = 0;
  10830. ngui_invalidate(&ui);
  10831. return;
  10832. } else if (k == NGUI_KEY_BACKSPACE) {
  10833. if (fs->caret) {
  10834. unsigned int i = --fs->caret;
  10835. for (; i < fs->len; i++)
  10836. fs->value[i] = fs->value[i + 1];
  10837. if (fs->len)
  10838. fs->len--;
  10839. form_dirty = 1;
  10840. js_browser_event(form_focus, "input", 1, 0);
  10841. }
  10842. } else if (k == NGUI_KEY_DELETE) {
  10843. if (fs->caret < fs->len) {
  10844. unsigned int i;
  10845. for (i = fs->caret; i < fs->len; i++)
  10846. fs->value[i] = fs->value[i + 1];
  10847. fs->len--;
  10848. form_dirty = 1;
  10849. js_browser_event(form_focus, "input", 1, 0);
  10850. }
  10851. } else if (k == NGUI_KEY_LEFT) {
  10852. if (fs->caret)
  10853. fs->caret--;
  10854. } else if (k == NGUI_KEY_RIGHT) {
  10855. if (fs->caret < fs->len)
  10856. fs->caret++;
  10857. } else if (k == NGUI_KEY_HOME) {
  10858. fs->caret = 0;
  10859. } else if (k == NGUI_KEY_END) {
  10860. fs->caret = fs->len;
  10861. } else if (k >= 32 && k < 127) {
  10862. if (fs->len < FORM_VALUE_MAX) {
  10863. unsigned int i;
  10864. for (i = fs->len; i > fs->caret; i--)
  10865. fs->value[i] = fs->value[i - 1];
  10866. fs->value[fs->caret++] = (char)k;
  10867. fs->len++;
  10868. form_dirty = 1;
  10869. js_browser_event(form_focus, "input", 1, 0);
  10870. }
  10871. } else {
  10872. return;
  10873. }
  10874. fs->value[fs->len] = '\0';
  10875. layout_valid = 0;
  10876. ngui_invalidate(&ui);
  10877. }
  10878. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  10879. * a same-document navigation: update the URL and fire hashchange. Returns
  10880. * 1 when handled. */
  10881. static int link_fragment_nav(unsigned int node)
  10882. {
  10883. const char *href = br_href(&doc, node);
  10884. char url[BR_URL_MAX];
  10885. unsigned int n = 0;
  10886. if (!href || !href[0] || !js_browser_active())
  10887. return 0;
  10888. if (href[0] == '#') {
  10889. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  10890. url[n] = page_url[n];
  10891. n++;
  10892. }
  10893. url[n] = '\0';
  10894. s_append(url, &n, href, sizeof(url));
  10895. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  10896. return 0;
  10897. }
  10898. if (!same_doc_fragment(url))
  10899. return href[0] == '#';
  10900. page_set_fragment(url, 1);
  10901. js_browser_hashchange();
  10902. return 1;
  10903. }
  10904. /* The innermost laid-out box under a screen point: the smallest valid box
  10905. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  10906. * Used to deliver clicks to elements that are neither links nor controls
  10907. * (a Vue <div role="button">, a card with a click listener). */
  10908. static unsigned int find_box_hit(int x, int y)
  10909. {
  10910. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  10911. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  10912. const struct br_layout_box *b = &layout_boxes[i];
  10913. unsigned int area;
  10914. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  10915. x < b->x || y < b->y || x >= b->x + b->w ||
  10916. y >= b->y + b->h)
  10917. continue;
  10918. area = (unsigned int)b->w * (unsigned int)b->h;
  10919. if (area <= best_area) {
  10920. best = i;
  10921. best_area = area;
  10922. }
  10923. }
  10924. return best;
  10925. }
  10926. static void handle_page_click(unsigned int *action)
  10927. {
  10928. int node;
  10929. char url[BR_URL_MAX];
  10930. if (!ui.pressed)
  10931. return;
  10932. if (ui.press_x < page_rect.x ||
  10933. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  10934. ui.press_y < page_rect.y ||
  10935. ui.press_y >= page_rect.y + page_rect.h)
  10936. return;
  10937. node = find_hit(ui.press_x, ui.press_y);
  10938. if (!node) {
  10939. unsigned int box;
  10940. if (!js_browser_active())
  10941. return;
  10942. box = find_box_hit(ui.press_x, ui.press_y);
  10943. if (box) {
  10944. form_blur();
  10945. js_browser_event(box, "click", 1, 1);
  10946. }
  10947. return;
  10948. }
  10949. if (form_is_control((unsigned int)node)) {
  10950. form_click((unsigned int)node);
  10951. return;
  10952. }
  10953. form_blur();
  10954. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  10955. return;
  10956. if (link_fragment_nav((unsigned int)node))
  10957. return;
  10958. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  10959. sizeof(url)) != 0)
  10960. return;
  10961. s_copy(click_url, url, sizeof(click_url));
  10962. *action |= ACT_NAV;
  10963. }
  10964. void _start(const char *arg)
  10965. {
  10966. struct win_info wi;
  10967. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  10968. u_win_create(960, 640, "Browser", &wi) != 0 &&
  10969. u_win_create(780, 540, "Browser", &wi) != 0) {
  10970. u_puts("browser: no graphics window\n");
  10971. u_exit(1);
  10972. }
  10973. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  10974. url_in.placeholder = "http://...";
  10975. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  10976. ui.theme.accent);
  10977. br_set_viewport(wi.width);
  10978. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  10979. s_copy(cwd, "/", sizeof(cwd));
  10980. heap_clear();
  10981. origin_cache_load();
  10982. css_cache_init();
  10983. script_cache_init();
  10984. persist_restore();
  10985. page_scroll.offset = 0;
  10986. page_scroll.content_h = 0;
  10987. if (arg && arg[0]) {
  10988. navigate(arg, 1);
  10989. } else {
  10990. load_home(1);
  10991. /* Start ready to type: keep the home page, but leave the address
  10992. * bar empty instead of showing "about:home". */
  10993. ngui_input_set(&url_in, "");
  10994. ngui_set_focus(&ui, ID_URL);
  10995. }
  10996. for (;;) {
  10997. unsigned int action = 0;
  10998. unsigned int now;
  10999. click_url[0] = '\0';
  11000. if (pending_action) {
  11001. action |= pending_action & ACT_WAIT_NAV;
  11002. if (pending_url[0])
  11003. s_copy(click_url, pending_url, sizeof(click_url));
  11004. pending_action = 0;
  11005. pending_url[0] = '\0';
  11006. cancel_fetch = 0;
  11007. } else if (preload_active) {
  11008. if (preload_wait)
  11009. preload_wait = 0;
  11010. else
  11011. preload_step();
  11012. } else if ((preload_pending &&
  11013. page_scroll.offset != preload_scroll) ||
  11014. (preload_rescan && layout_valid)) {
  11015. preload_scroll = page_scroll.offset;
  11016. preload_rescan = 0;
  11017. preload_pending = 0;
  11018. preload_node = 0;
  11019. preload_active = 1;
  11020. }
  11021. js_browser_tick();
  11022. if (resize_pending && !pending_action) {
  11023. resize_pending = 0;
  11024. resize_sent_w = layout_right - layout_left;
  11025. js_browser_window_event("resize");
  11026. }
  11027. persist_tick();
  11028. if (pending_action)
  11029. continue;
  11030. now = u_ticks_ms();
  11031. if (status_until && (int)(now - status_until) >= 0) {
  11032. status_text[0] = '\0';
  11033. status_until = 0;
  11034. status_error = 0;
  11035. ngui_invalidate(&ui);
  11036. }
  11037. if (!ngui_begin(&ui)) {
  11038. /* A queued navigation (e.g. Enter in the URL bar during
  11039. * a slow fetch) must be handled even when this frame
  11040. * needs no redraw. */
  11041. if (!action) {
  11042. fetch_workers_stop_if_unfocused();
  11043. u_sleep_ms(10);
  11044. continue;
  11045. }
  11046. } else {
  11047. draw(&action);
  11048. handle_keys(&action);
  11049. handle_page_click(&action);
  11050. ngui_end(&ui);
  11051. }
  11052. if (action & ACT_NAV) {
  11053. if (click_url[0]) {
  11054. navigate(click_url, 1);
  11055. click_url[0] = '\0';
  11056. } else {
  11057. navigate(url_in.text, 1);
  11058. }
  11059. }
  11060. if (action & ACT_BACK) {
  11061. if (hist_pos > 0) {
  11062. hist_pos--;
  11063. if (same_doc_fragment(history[hist_pos])) {
  11064. page_set_fragment(history[hist_pos], 0);
  11065. js_browser_hashchange();
  11066. } else {
  11067. navigate(history[hist_pos], 0);
  11068. }
  11069. }
  11070. }
  11071. if (action & ACT_FORWARD) {
  11072. if (hist_pos + 1 < hist_len) {
  11073. hist_pos++;
  11074. if (same_doc_fragment(history[hist_pos])) {
  11075. page_set_fragment(history[hist_pos], 0);
  11076. js_browser_hashchange();
  11077. } else {
  11078. navigate(history[hist_pos], 0);
  11079. }
  11080. }
  11081. }
  11082. if (action & ACT_RELOAD) {
  11083. if (s_eq(page_url, "about:home"))
  11084. load_home(0);
  11085. else
  11086. navigate(page_url, 0);
  11087. }
  11088. if (action & ACT_HOME)
  11089. load_home(1);
  11090. if (action & ACT_CLOSE)
  11091. quit = 1;
  11092. if (quit)
  11093. break;
  11094. if (pending_action)
  11095. continue;
  11096. fetch_workers_stop_if_unfocused();
  11097. u_sleep_ms(10);
  11098. }
  11099. fetch_workers_stop_all();
  11100. u_win_close();
  11101. u_exit(0);
  11102. }