browser.c 406 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287
  1. /* browser: a small HTML/CSS browser built on ngui, the image library and the
  2. * shared uhttp client.
  3. *
  4. * Page scripts run on the vendored QuickJS engine (modern ECMAScript) through
  5. * the DOM layer in js_browser.c; forms render and submit natively. External CSS is loaded over uhttp, and images are
  6. * decoded with img.c and drawn inline. Page-scoped buffers (page body,
  7. * rules and image bitmaps) come from the ring-3 libc heap; each image gets an
  8. * exact-size decode arena that is freed as soon as the scaled bitmap exists.
  9. * The DOM and the image/CSS I/O scratch use fixed static arenas.
  10. */
  11. #include <stdlib.h>
  12. #include <stdio.h>
  13. #include <string.h>
  14. #include <math.h>
  15. #include <ucmd_heap.h>
  16. #include "ucmd_lib.h"
  17. #include "ngui.h"
  18. #include "browser_html.h"
  19. #include "js_browser.h"
  20. #include "uhttp.h"
  21. #include "uhttp_cookie.h"
  22. #include "img.h"
  23. #include "inflate.h"
  24. #include "ufont.h"
  25. #include "svg_raster.h"
  26. static void svg_cache_clear(void);
  27. static unsigned char *decode_arena; /* see decode_arena_get() */
  28. static unsigned int decode_arena_size;
  29. /* Start wide enough for the desktop nav; smaller screens fall back to
  30. * 960x640 and 780x540, which still fit a 1024x768 panel. */
  31. #define BR_W 1100
  32. #define BR_H 700
  33. #define BR_TOOLBAR_H 30
  34. #define BR_STATUS_H 18
  35. #define BR_PAGE_MAX (2u * 1024u * 1024u)
  36. #define BR_IMG_FILE_MAX (1024u * 1024u)
  37. #define BR_IMG_PIX_MAX (8u * 1024u * 1024u)
  38. #define BR_MAX_IMAGES 256
  39. /* Decoded display bitmaps share the page heap: cap their total pixels
  40. * (RGB565 plus an optional alpha plane) instead of their count. */
  41. #define BR_IMG_PIXEL_BUDGET (4u * 1024u * 1024u)
  42. #define BR_IMG_DISP_BUDGET (6u * 1024u * 1024u)
  43. #define BR_IMG_ARENA_MAX (24u * 1024u * 1024u)
  44. #define BR_IMG_LAYOUT_W 1000
  45. /* Decode completed image jobs for at most this long per main-loop pass, then
  46. * return to input/painting. One image per pass plus a 10 ms sleep made a
  47. * page of small icons trickle in. */
  48. #define BR_IMG_DECODE_BUDGET_MS 40u
  49. /* Coalesce image-driven repaints: each decode invalidates the page, and a
  50. * full repaint per image made loading superlinear on image-heavy pages. */
  51. #define BR_IMG_REPAINT_MS 100u
  52. #define BR_IMG_STAT_LOG 3584
  53. /* An image job may hold a fetch helper this long. The page/script
  54. * deadline (UHTTP_TOTAL_TIMEOUT_MS) is minutes; one unreachable image host
  55. * must not starve the other images of all four helpers that long. */
  56. #define BR_IMG_JOB_TIMEOUT_MS 30000u
  57. #define BR_CSS_MAX (832u * 1024u)
  58. #define BR_CSS_COMP_MAX (192u * 1024u)
  59. /* Scripts and ES modules: Vite bundles reach ~1.7 MB (the Cloudron
  60. * dashboard's main chunk); the helper's FETCH_MAX is the same 2 MB. */
  61. #define BR_SCRIPT_MAX (2u * 1024u * 1024u)
  62. #define FETCH_ABORT (-2)
  63. /* Session cache for remote stylesheets (per launch; cleared at startup). */
  64. #define CSS_CACHE_MAX 16
  65. #define CSS_CACHE_FILE_MAX (256u * 1024u)
  66. #define CSS_CACHE_PREFIX "bcss-"
  67. #define SCRIPT_CACHE_MAX 24
  68. #define SCRIPT_CACHE_FILE_MAX BR_SCRIPT_MAX
  69. #define SCRIPT_CACHE_PREFIX "bjs-"
  70. /* Web fonts cached for the boot; /share holds 64 entries / 16 MB in all. */
  71. #define FONT_CACHE_MAX 8
  72. #define FONT_CACHE_PREFIX "bfont-"
  73. /* The ufont arena (built-in faces, @font-face files and glyph masks); the
  74. * 512 KB default holds the built-in set but not a page's web fonts. */
  75. #define BR_FONT_ARENA (3u * 1024u * 1024u)
  76. #define BR_MAX_SHEETS 6
  77. #define BR_HISTORY 16
  78. #define BR_URL_MAX 4096 /* = UHTTP_PATH_MAX: google.com's JS URL is ~3.7 KB */
  79. #define BR_STATUS_MAX 200
  80. #define BR_IMG_RGB565(r, g, b) \
  81. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  82. #define BR_GRAY 0x8410
  83. enum {
  84. ID_URL = 1,
  85. ID_GO,
  86. ID_BACK,
  87. ID_FORWARD,
  88. ID_RELOAD,
  89. ID_HOME,
  90. ID_DOWNLOADS
  91. };
  92. #define ACT_NAV (1u << 0)
  93. #define ACT_BACK (1u << 1)
  94. #define ACT_FORWARD (1u << 2)
  95. #define ACT_RELOAD (1u << 3)
  96. #define ACT_HOME (1u << 4)
  97. #define ACT_CLOSE (1u << 5)
  98. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  99. ACT_HOME | ACT_CLOSE)
  100. /* ---- downloads --------------------------------------------------------
  101. * A context-menu download is one entry in dl_tab; one curl __serve helper
  102. * fetches at a time so the page's own workers keep their slots. The body
  103. * lands in /share/bf..., then the browser copies it to /data/DOWNLOAD (or
  104. * /share/DOWNLOAD without an installed disk). The list doubles as the
  105. * toolbar panel's history and is persisted best-effort next to the other
  106. * browser state. */
  107. #define DL_MAX 24
  108. #define DL_URL_MAX 1024
  109. #define DL_NAME_MAX 32
  110. #define DL_PATH_MAX 64
  111. #define DL_ERR_MAX 64
  112. #define DL_FILE_MAX (4u * 1024u * 1024u) /* the helper's FETCH_MAX */
  113. #define DL_PANEL_W 380
  114. #define DL_ROW_H 38
  115. #define DL_PANEL_ROWS 12
  116. #define DL_DIR_DATA "/data/DOWNLOAD"
  117. #define DL_DIR_SHARE "/share/DOWNLOAD"
  118. #define DL_SHARE_LIST "/share/bdownloads"
  119. #define DL_DATA_LIST "/data/BDOWN.DAT"
  120. enum { DL_QUEUED, DL_RUNNING, DL_SAVING, DL_DONE, DL_FAILED };
  121. struct dl_ent {
  122. unsigned char used;
  123. unsigned char state;
  124. char err[DL_ERR_MAX];
  125. char name[DL_NAME_MAX];
  126. char path[DL_PATH_MAX];
  127. char url[DL_URL_MAX];
  128. unsigned int got, total, size, stamp;
  129. };
  130. static struct dl_ent dl_tab[DL_MAX];
  131. static int dl_active = -1;
  132. static unsigned int dl_stamp = 1;
  133. static int dl_unseen;
  134. static int dl_panel_open;
  135. static struct ngui_rect dl_button_rect, dl_panel_rect, dl_clear_rect;
  136. static int dl_panel_rows;
  137. /* Context menu opened by a right click on the page. */
  138. #define CTX_MAX 3
  139. #define CTX_ROW_H 28
  140. #define CTX_LABEL_MAX 28
  141. static int ctx_open;
  142. static int ctx_x, ctx_y, ctx_w, ctx_h, ctx_n;
  143. static unsigned int ctx_action[CTX_MAX];
  144. static char ctx_label[CTX_MAX][CTX_LABEL_MAX];
  145. static char ctx_url[CTX_MAX][DL_URL_MAX];
  146. enum { CTX_SAVE_IMAGE, CTX_SAVE_LINK, CTX_SAVE_PAGE };
  147. struct br_image {
  148. int state; /* 0 empty, 1 ready */
  149. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  150. int native_w, native_h;
  151. unsigned int url_hash; /* <img> source, 0 = not shareable */
  152. char err[32];
  153. /* Display-size cache: the box an image is actually painted in. The
  154. * source bitmap above is deliberately capped at BR_IMG_LAYOUT_W so a
  155. * window resize can re-scale it; the cached copy is exactly dw x dh,
  156. * so every repaint is a 1:1 blit instead of a per-pixel resample. */
  157. struct img_image disp;
  158. unsigned int disp_pixels;
  159. unsigned int disp_last;
  160. };
  161. static struct ngui ui;
  162. static struct ngui_input url_in;
  163. static struct ngui_scroll page_scroll;
  164. static struct br_doc doc;
  165. static struct br_image images[BR_MAX_IMAGES];
  166. static int image_count;
  167. static unsigned int image_pixels;
  168. static unsigned int image_disp_pixels;
  169. static unsigned int image_disp_clock;
  170. /* Per-image pipeline timing for the status line and /share/IMGSTAT. The
  171. * numbers are what decides whether the next work is network, decode or
  172. * display; keep them cheap (one tick read per phase). */
  173. static unsigned int img_stat_start;
  174. static unsigned int img_stat_wall;
  175. static unsigned int img_stat_net;
  176. static unsigned int img_stat_open;
  177. static unsigned int img_stat_first;
  178. static unsigned int img_stat_io;
  179. static unsigned int img_stat_dec;
  180. static unsigned int img_stat_scale;
  181. static unsigned int img_stat_paint;
  182. static unsigned int img_stat_reflow;
  183. static unsigned int img_stat_bytes;
  184. static int img_stat_n;
  185. static unsigned int img_last_dec_ms;
  186. static unsigned int img_last_scale_ms;
  187. static char img_stat_log[BR_IMG_STAT_LOG];
  188. static unsigned int img_stat_log_len;
  189. static unsigned int img_repaint_ms;
  190. static int img_repaint_pending;
  191. /* Painted border boxes, in page/screen coordinates (layout starts at
  192. * page_rect.y - scroll). getBoundingClientRect() subtracts page_rect. */
  193. struct br_layout_box {
  194. int x, y;
  195. int w, h;
  196. unsigned char valid;
  197. };
  198. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  199. /* Inline boxes are built from their line runs in flush_line(): a box is
  200. * replaced when a new layout pass (or a re-layout at the same or an
  201. * earlier line) reaches it, and grown when its runs continue on the same
  202. * or a later line of the same pass. inline_box_parent[] is the enclosing
  203. * inline box (node + 1), so nested spans grow their ancestors too. */
  204. static unsigned int inline_box_pass_id;
  205. static unsigned int inline_box_flush_id;
  206. static unsigned int inline_box_pass[BR_MAX_NODES];
  207. static unsigned int inline_box_flush[BR_MAX_NODES];
  208. static int inline_box_y[BR_MAX_NODES];
  209. static unsigned short inline_box_parent[BR_MAX_NODES];
  210. /* Images are loaded one per main-loop iteration so the parsed page stays
  211. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  212. static int preload_active;
  213. static int preload_max_jobs;
  214. static int preload_pending;
  215. static int preload_wait;
  216. static unsigned int preload_node;
  217. static int preload_loaded;
  218. static int preload_scroll;
  219. static int preload_rescan;
  220. static char post_status_text[BR_STATUS_MAX];
  221. static int post_status_error;
  222. static unsigned int post_status_ttl;
  223. /* Content-relative position/height of each <img>, recorded by the measure
  224. * pass so image loading can be deferred until it is near the viewport. */
  225. static unsigned short img_top[BR_MAX_NODES];
  226. static unsigned short img_h[BR_MAX_NODES];
  227. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  228. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  229. * body. Decode arenas are allocated per image instead of living here. */
  230. static unsigned char *image_io_buf;
  231. static struct ufont_face *font_faces[BR_MAX_FACES];
  232. /* [family id - 1][bold * 2 + italic] -> 1-based face id, 0 = built-in. */
  233. static unsigned char font_pick[BR_MAX_FACES][4];
  234. #define image_file_buf (image_io_buf)
  235. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  236. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  237. static struct inflate image_inflate_ws;
  238. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  239. #error "CSS scratch must fit in image_io_buf"
  240. #endif
  241. static char page_url[BR_URL_MAX];
  242. static char page_title[BR_TITLE_MAX];
  243. static char cwd[64];
  244. static int page_is_local;
  245. static int page_loading;
  246. static char status_text[BR_STATUS_MAX];
  247. static unsigned int status_until;
  248. static int status_error;
  249. static char history[BR_HISTORY][BR_URL_MAX];
  250. static int hist_len, hist_pos;
  251. static char click_url[BR_URL_MAX];
  252. static char pending_url[BR_URL_MAX];
  253. #define BR_POST_MAX 4096
  254. static char pending_post[BR_POST_MAX];
  255. static unsigned int pending_post_len;
  256. /* The pending navigation is a POST even when its body is empty (a form
  257. * without fields, e.g. the OIDC consent auto-submit). */
  258. static int pending_post_is;
  259. /* window "resize" bookkeeping: the page width the last event was for. */
  260. static int resize_sent_w = -1;
  261. static int resize_pending;
  262. static unsigned int pending_action;
  263. static int cancel_fetch;
  264. static int quit;
  265. static struct ngui_rect page_rect;
  266. static unsigned short *page_backbuf;
  267. static int pagebuf_w, pagebuf_h;
  268. static int page_cache_valid;
  269. static int page_cache_scroll;
  270. static unsigned int page_cache_nnode;
  271. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  272. static int layout_valid, layout_left, layout_right;
  273. /* Height of the page viewport: what html/body height:100% resolves to. */
  274. static int layout_view_h;
  275. static unsigned int layout_nnode;
  276. static int layout_content_h;
  277. /* layout output */
  278. struct lay_run {
  279. unsigned int off;
  280. unsigned short len;
  281. unsigned short gap;
  282. unsigned short color;
  283. unsigned short href;
  284. char lit[28];
  285. short img;
  286. signed short dy; /* inline image vertical offset */
  287. unsigned short iw, ih;
  288. unsigned short w;
  289. unsigned char font_px, bold, italic, mono, underline, strike;
  290. unsigned char overline, font_face;
  291. unsigned char transform_scale;
  292. unsigned char origin_x_kind, origin_y_kind;
  293. signed short scale_x, scale_y, rotate_x100;
  294. signed short origin_x, origin_y;
  295. unsigned char has_lit;
  296. unsigned int form; /* node + 1, 0 = not a control */
  297. unsigned char form_kind;
  298. unsigned char form_disabled;
  299. /* RUN_PBOX: background colour, background image and its placement
  300. * inside the iw x ih box (relative offsets, drawn size). */
  301. unsigned char pb_has_bg;
  302. unsigned short pb_bg;
  303. short pb_img;
  304. short pb_x, pb_y, pb_w, pb_h;
  305. /* Innermost inline element (node + 1) whose box this run belongs
  306. * to, 0 = none; flush_line() unions the placed runs into
  307. * layout_boxes[] so getBoundingClientRect() sees inline boxes. */
  308. unsigned short box;
  309. };
  310. struct lay {
  311. int draw;
  312. struct ngui *ui;
  313. int left, right;
  314. int y;
  315. int line_x, line_y, line_h;
  316. int line_left, line_right;
  317. int parent_top;
  318. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  319. int cb_h; /* definite content height of the containing block for
  320. * percentage heights; 0 = indefinite (auto) */
  321. int run_x;
  322. int align;
  323. int depth;
  324. int space_pending;
  325. unsigned char float_active;
  326. int float_left, float_right, float_bottom;
  327. struct lay_run runs[96];
  328. int nruns;
  329. unsigned short box_owner; /* node + 1 of the open inline box */
  330. };
  331. struct hit {
  332. int x, y, w, h;
  333. unsigned short node;
  334. };
  335. /* Live form state; the DOM attributes stay the initial/default value. */
  336. #define FORM_MAX 64
  337. #define FORM_VALUE_MAX 63
  338. enum {
  339. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  340. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  341. };
  342. struct form_state {
  343. unsigned int node;
  344. char value[FORM_VALUE_MAX + 1];
  345. unsigned char len, caret, checked, selected, used;
  346. };
  347. static struct form_state form_states[FORM_MAX];
  348. static unsigned int form_focus;
  349. static unsigned int form_dirty;
  350. static int form_descendant(unsigned int node, unsigned int form);
  351. static int form_submit_form(unsigned int node, int fire_event);
  352. static int link_fragment_nav(unsigned int node);
  353. static void history_push(const char *url);
  354. static void form_reset_event(unsigned int form);
  355. static unsigned int s_len(const char *s);
  356. static int s_eq(const char *a, const char *b);
  357. static void form_key(int k);
  358. static void form_click(unsigned int node);
  359. static void style_for_node(unsigned int node, struct br_style *out);
  360. static int form_author_styled(const struct br_style *st);
  361. static int css_radius(const struct br_style *st, int corner, int w, int h);
  362. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  363. const struct br_style *st, int focused);
  364. static int form_disabled(unsigned int node)
  365. {
  366. struct br_node *n = &doc.nodes[node];
  367. if (n->attr_flags & BR_ATTR_DISABLED)
  368. return 1;
  369. return br_find_attr(&doc, node, "disabled") != 0;
  370. }
  371. static int form_kind_of(unsigned int node)
  372. {
  373. const char *type = br_type(&doc, node);
  374. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  375. return FORM_TEXTAREA;
  376. if (doc.nodes[node].tag == BR_TAG_SELECT)
  377. return FORM_SELECT;
  378. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  379. if (s_eq(type, "reset"))
  380. return FORM_RESET;
  381. if (s_eq(type, "button"))
  382. return FORM_BUTTON;
  383. return FORM_SUBMIT;
  384. }
  385. if (s_eq(type, "password"))
  386. return FORM_PASSWORD;
  387. if (s_eq(type, "checkbox"))
  388. return FORM_CHECKBOX;
  389. if (s_eq(type, "radio"))
  390. return FORM_RADIO;
  391. if (s_eq(type, "submit"))
  392. return FORM_SUBMIT;
  393. if (s_eq(type, "reset"))
  394. return FORM_RESET;
  395. if (s_eq(type, "button"))
  396. return FORM_BUTTON;
  397. return FORM_TEXT;
  398. }
  399. static unsigned int form_option_count(unsigned int node)
  400. {
  401. unsigned int c, n = 0;
  402. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  403. if (doc.nodes[c].type == BR_NODE_ELEM &&
  404. doc.nodes[c].tag == BR_TAG_OPTION)
  405. n++;
  406. return n;
  407. }
  408. static unsigned int form_option_selected(unsigned int node)
  409. {
  410. unsigned int c, i = 0;
  411. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  412. if (doc.nodes[c].type != BR_NODE_ELEM ||
  413. doc.nodes[c].tag != BR_TAG_OPTION)
  414. continue;
  415. if (br_find_attr(&doc, c, "selected"))
  416. return i;
  417. i++;
  418. }
  419. return 0;
  420. }
  421. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  422. char *out, unsigned int cap)
  423. {
  424. unsigned int c, i = 0;
  425. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  426. if (doc.nodes[c].type != BR_NODE_ELEM ||
  427. doc.nodes[c].tag != BR_TAG_OPTION)
  428. continue;
  429. if (i == idx)
  430. return br_text_content(&doc, c, out, cap);
  431. i++;
  432. }
  433. return 0;
  434. }
  435. static int form_is_control(unsigned int node);
  436. static struct form_state *form_get(unsigned int node, int create)
  437. {
  438. struct form_state *slot = 0;
  439. unsigned int i;
  440. for (i = 0; i < FORM_MAX; i++) {
  441. if (form_states[i].used) {
  442. if (form_states[i].node == node)
  443. return &form_states[i];
  444. } else if (!slot) {
  445. slot = &form_states[i];
  446. }
  447. }
  448. if (create && !slot) {
  449. /* Full: a client-side router (Docusaurus' React Router)
  450. * replaces page content without a navigation, so slots of
  451. * controls that left the document pile up until no new
  452. * control can be drawn or focused.
  453. * Reuse those first, then slots of nodes that are no longer
  454. * controls. */
  455. for (i = 0; i < FORM_MAX && !slot; i++)
  456. if (form_states[i].node != form_focus &&
  457. br_node_detached(&doc, form_states[i].node))
  458. slot = &form_states[i];
  459. for (i = 0; i < FORM_MAX && !slot; i++)
  460. if (form_states[i].node != form_focus &&
  461. !form_is_control(form_states[i].node))
  462. slot = &form_states[i];
  463. }
  464. if (!create || !slot)
  465. return 0;
  466. slot->node = node;
  467. slot->len = 0;
  468. slot->caret = 0;
  469. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  470. slot->selected = form_option_selected(node);
  471. slot->used = 1;
  472. {
  473. unsigned int n = 0;
  474. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  475. n = br_text_content(&doc, node, slot->value,
  476. FORM_VALUE_MAX + 1);
  477. } else {
  478. const char *v = br_value(&doc, node);
  479. if (v) {
  480. n = s_len(v);
  481. if (n > FORM_VALUE_MAX)
  482. n = FORM_VALUE_MAX;
  483. for (unsigned int j = 0; j < n; j++)
  484. slot->value[j] = v[j];
  485. }
  486. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  487. n = br_text_content(&doc, node, slot->value,
  488. FORM_VALUE_MAX + 1);
  489. }
  490. if (n > FORM_VALUE_MAX)
  491. n = FORM_VALUE_MAX;
  492. slot->value[n] = '\0';
  493. slot->len = (unsigned char)n;
  494. slot->caret = (unsigned char)n;
  495. }
  496. return slot;
  497. }
  498. static void form_reset_state(void)
  499. {
  500. unsigned int i;
  501. for (i = 0; i < FORM_MAX; i++)
  502. form_states[i].used = 0;
  503. form_focus = 0;
  504. }
  505. /* A <button> with element content (an icon <svg>/<img>, a <span> label)
  506. * is laid out like a normal element so that content shows; only a text or
  507. * empty button is drawn as a native control. Clicks still reach it
  508. * through the box hit test. */
  509. static int button_has_elements(unsigned int node)
  510. {
  511. unsigned int c;
  512. if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
  513. return 0;
  514. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  515. if (doc.nodes[c].type == BR_NODE_ELEM)
  516. return 1;
  517. /* An empty button whose icon is a ::before/::after box (Docusaurus'
  518. * sidebar caret) is laid out as an element so the box is drawn. */
  519. if (!doc.nodes[node].first && doc.npe_rules) {
  520. struct br_style st, ps;
  521. char buf[8];
  522. int pe;
  523. style_for_node(node, &st);
  524. for (pe = 1; pe <= 2; pe++)
  525. if (!br_pseudo(&doc, node, pe, &st, &ps, buf,
  526. sizeof(buf)) &&
  527. ps.content == BR_CONTENT_EMPTY &&
  528. ps.display != BR_DISPLAY_NONE)
  529. return 1;
  530. }
  531. return 0;
  532. }
  533. static int form_is_control(unsigned int node)
  534. {
  535. unsigned int tag;
  536. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  537. return 0;
  538. tag = doc.nodes[node].tag;
  539. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  540. tag == BR_TAG_SELECT ||
  541. (tag == BR_TAG_BUTTON && !button_has_elements(node));
  542. }
  543. #define HIT_MAX 96
  544. static struct hit hits[HIT_MAX];
  545. static int nhits;
  546. static unsigned short block_h[BR_MAX_NODES];
  547. /* Border-box height a flex container stretches an item to (align-items:
  548. * stretch in a row with a taller line or a definite height), 0 = none.
  549. * Written by the measure pass, read by both. */
  550. static unsigned short flex_stretch_h[BR_MAX_NODES];
  551. /* Measure-pass top of each block, in the same document coordinates as
  552. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  553. * paint, so it cannot drive the lazy background loader). */
  554. static unsigned short block_top[BR_MAX_NODES];
  555. static char li_marker[BR_MAX_NODES][12];
  556. /* one connection object; the browser fetches one resource at a time */
  557. /* ---- tiny strings ---- */
  558. static unsigned int s_len(const char *s)
  559. {
  560. unsigned int n = 0;
  561. while (s && s[n])
  562. n++;
  563. return n;
  564. }
  565. static void s_copy(char *d, const char *s, unsigned int cap)
  566. {
  567. unsigned int i = 0;
  568. if (!cap)
  569. return;
  570. while (s && s[i] && i + 1 < cap) {
  571. d[i] = s[i];
  572. i++;
  573. }
  574. d[i] = '\0';
  575. }
  576. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  577. {
  578. while (s && *s && *n + 1 < cap)
  579. d[(*n)++] = *s++;
  580. d[*n] = '\0';
  581. }
  582. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  583. unsigned int cap)
  584. {
  585. char tmp[12];
  586. unsigned int i = 0, j;
  587. do {
  588. tmp[i++] = (char)('0' + v % 10);
  589. v /= 10;
  590. } while (v && i < sizeof(tmp));
  591. for (j = 0; j < i && *n + 1 < cap; j++)
  592. d[(*n)++] = tmp[i - 1 - j];
  593. d[*n] = '\0';
  594. }
  595. static int s_eq(const char *a, const char *b)
  596. {
  597. while (*a && *b) {
  598. if (*a != *b)
  599. return 0;
  600. a++;
  601. b++;
  602. }
  603. return *a == *b;
  604. }
  605. static int starts_with(const char *s, const char *p)
  606. {
  607. unsigned int i = 0;
  608. while (p[i]) {
  609. if (s[i] != p[i])
  610. return 0;
  611. i++;
  612. }
  613. return 1;
  614. }
  615. static int contains_ci(const char *s, const char *p)
  616. {
  617. unsigned int i, j;
  618. for (i = 0; s[i]; i++) {
  619. for (j = 0; p[j]; j++) {
  620. char a = s[i + j];
  621. if (a >= 'A' && a <= 'Z')
  622. a = (char)(a - 'A' + 'a');
  623. if (a != p[j])
  624. break;
  625. }
  626. if (!p[j])
  627. return 1;
  628. }
  629. return 0;
  630. }
  631. static char *trim(char *s)
  632. {
  633. unsigned int n;
  634. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  635. s++;
  636. n = s_len(s);
  637. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  638. s[n - 1] == '\r' || s[n - 1] == '\n'))
  639. s[--n] = '\0';
  640. return s;
  641. }
  642. /* ---- per-process heap ---- */
  643. static int heap_start(void)
  644. {
  645. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  646. if (!image_io_buf)
  647. return -1;
  648. page_backbuf = (unsigned short *)malloc(
  649. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  650. pagebuf_w = page_backbuf ? ui.w : 0;
  651. pagebuf_h = page_backbuf ? ui.h : 0;
  652. page_cache_valid = 0;
  653. return 0;
  654. }
  655. static void heap_clear(void)
  656. {
  657. memset(font_faces, 0, sizeof(font_faces));
  658. memset(font_pick, 0, sizeof(font_pick));
  659. ngui_font_detach(&ui);
  660. svg_cache_clear();
  661. decode_arena = 0; /* lives in the page heap too */
  662. decode_arena_size = 0;
  663. heap_reset();
  664. /* The document arenas live in that heap; drop the stale pointers so
  665. * the next br_parse_plain() allocates fresh ones. */
  666. doc.nodes = 0;
  667. doc.text = 0;
  668. doc.attrs = 0;
  669. image_io_buf = 0;
  670. page_backbuf = 0;
  671. pagebuf_w = pagebuf_h = 0;
  672. page_cache_valid = 0;
  673. }
  674. static void browser_rules_alloc(void)
  675. {
  676. struct br_rule *rules;
  677. rules = (struct br_rule *)malloc(
  678. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  679. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  680. }
  681. /* ---- status ---- */
  682. static void set_status(const char *s, int err, unsigned int ttl_ms)
  683. {
  684. s_copy(status_text, s, sizeof(status_text));
  685. status_error = err;
  686. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  687. ngui_invalidate(&ui);
  688. }
  689. /* Update the status text without forcing a frame; the throttled image
  690. * repaint picks it up. Starting one helper per image used to invalidate the
  691. * whole page before every decode. */
  692. static void set_status_quiet(const char *s)
  693. {
  694. s_copy(status_text, s, sizeof(status_text));
  695. status_error = 0;
  696. status_until = 0;
  697. }
  698. /* ---- JavaScript ---- */
  699. static int resolve_link(const char *base, const char *href, char *out,
  700. unsigned int cap);
  701. static char js_last_status[BR_STATUS_MAX];
  702. static int js_last_error;
  703. static void js_host_status(const char *msg, int error)
  704. {
  705. s_copy(js_last_status, msg, sizeof(js_last_status));
  706. js_last_error = error;
  707. set_status(msg, error, 6000);
  708. }
  709. static void js_host_report(const char *msg)
  710. {
  711. u_puts("[js] ");
  712. u_puts(msg);
  713. u_putc('\n');
  714. s_copy(js_last_status, msg, sizeof(js_last_status));
  715. js_last_error = 1;
  716. set_status(msg, 1, 8000);
  717. }
  718. static void js_host_navigate(const char *url)
  719. {
  720. char resolved[BR_URL_MAX];
  721. if (!url || !url[0])
  722. return;
  723. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  724. return;
  725. s_copy(pending_url, resolved, sizeof(pending_url));
  726. pending_action |= ACT_NAV;
  727. cancel_fetch = 1;
  728. }
  729. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  730. * back/forward between fragments): the page URL, address bar and history
  731. * follow, nothing is reloaded. `push` adds a history entry. */
  732. static int page_set_fragment(const char *url, int push)
  733. {
  734. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  735. return -1;
  736. s_copy(page_url, url, sizeof(page_url));
  737. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  738. url_in.len = s_len(url_in.text);
  739. url_in.cursor = url_in.len;
  740. url_in.scroll = 0;
  741. if (push)
  742. history_push(page_url);
  743. ngui_invalidate(&ui);
  744. return 0;
  745. }
  746. static int js_host_set_hash(const char *url)
  747. {
  748. return page_set_fragment(url, 1);
  749. }
  750. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  751. * the page, so a hash router can react). */
  752. static int same_doc_fragment(const char *url)
  753. {
  754. unsigned int a = 0, b = 0;
  755. if (!js_browser_active() || !url)
  756. return 0;
  757. while (url[a] && url[a] != '#')
  758. a++;
  759. while (page_url[b] && page_url[b] != '#')
  760. b++;
  761. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  762. !s_eq(url, page_url);
  763. }
  764. static void js_host_changed(void)
  765. {
  766. /* Class/style/attribute mutations change computed styles, not just the
  767. * text: drop the per-node style cache before the next layout. */
  768. br_reset_styles(&doc);
  769. layout_valid = 0;
  770. /* Script-built content (Angular's ng-repeat cards) brings new images
  771. * and inline background styles: rescan once the main loop is idle. */
  772. preload_rescan = 1;
  773. ngui_invalidate(&ui);
  774. }
  775. static void js_force_layout(void);
  776. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  777. {
  778. if (node >= BR_MAX_NODES)
  779. return 0;
  780. /* A geometry read after a DOM change gets a synchronous layout, like
  781. * a browser's forced reflow: Bootstrap's tooltip inserts itself,
  782. * reads offsetWidth, then moves itself twice with $.offset(), which
  783. * reads its own current position each time. */
  784. if (!layout_valid)
  785. js_force_layout();
  786. if (!layout_boxes[node].valid)
  787. return 0;
  788. *x = layout_boxes[node].x - page_rect.x;
  789. *y = layout_boxes[node].y - page_rect.y;
  790. *w = layout_boxes[node].w;
  791. *h = layout_boxes[node].h;
  792. return 1;
  793. }
  794. static void form_copy_out(const char *s, char *buf, int cap)
  795. {
  796. int i = 0;
  797. if (!buf || cap <= 0)
  798. return;
  799. while (s && s[i] && i + 1 < cap) {
  800. buf[i] = s[i];
  801. i++;
  802. }
  803. buf[i] = '\0';
  804. }
  805. static int js_host_form_value(unsigned int node, char *buf, int cap)
  806. {
  807. struct form_state *fs;
  808. int kind;
  809. if (!form_is_control(node))
  810. return 0;
  811. kind = form_kind_of(node);
  812. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  813. return 0;
  814. if (kind == FORM_SELECT) {
  815. char opt[64] = "";
  816. unsigned int c, i = 0;
  817. fs = form_get(node, 1);
  818. if (!fs)
  819. return 0;
  820. form_option_text(node, fs->selected, opt, sizeof(opt));
  821. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  822. if (doc.nodes[c].type != BR_NODE_ELEM ||
  823. doc.nodes[c].tag != BR_TAG_OPTION)
  824. continue;
  825. if (i == fs->selected) {
  826. const char *v = br_value(&doc, c);
  827. if (v && v[0])
  828. form_copy_out(v, buf, cap);
  829. else
  830. form_copy_out(opt, buf, cap);
  831. return 1;
  832. }
  833. i++;
  834. }
  835. form_copy_out(opt, buf, cap);
  836. return 1;
  837. }
  838. fs = form_get(node, 1);
  839. if (!fs)
  840. return 0;
  841. form_copy_out(fs->value, buf, cap);
  842. return 1;
  843. }
  844. static int js_host_form_checked(unsigned int node)
  845. {
  846. struct form_state *fs;
  847. int kind;
  848. if (!form_is_control(node))
  849. return -1;
  850. kind = form_kind_of(node);
  851. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  852. return -1;
  853. fs = form_get(node, 1);
  854. return fs ? fs->checked : 0;
  855. }
  856. static int js_host_form_selected(unsigned int node)
  857. {
  858. struct form_state *fs;
  859. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  860. return -1;
  861. fs = form_get(node, 1);
  862. return fs ? fs->selected : 0;
  863. }
  864. static int js_host_form_set_value(unsigned int node, const char *value)
  865. {
  866. struct form_state *fs;
  867. unsigned int n;
  868. if (!form_is_control(node))
  869. return 0;
  870. fs = form_get(node, 1);
  871. if (!fs)
  872. return 0;
  873. n = s_len(value ? value : "");
  874. if (n > FORM_VALUE_MAX)
  875. n = FORM_VALUE_MAX;
  876. for (unsigned int i = 0; i < n; i++)
  877. fs->value[i] = value[i];
  878. fs->value[n] = '\0';
  879. fs->len = (unsigned char)n;
  880. fs->caret = (unsigned char)n;
  881. layout_valid = 0;
  882. ngui_invalidate(&ui);
  883. return 1;
  884. }
  885. static int js_host_form_set_checked(unsigned int node, int checked)
  886. {
  887. struct form_state *fs;
  888. int kind;
  889. if (!form_is_control(node))
  890. return 0;
  891. kind = form_kind_of(node);
  892. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  893. return 0;
  894. fs = form_get(node, 1);
  895. if (!fs)
  896. return 0;
  897. fs->checked = (unsigned char)(checked != 0);
  898. layout_valid = 0;
  899. ngui_invalidate(&ui);
  900. return 1;
  901. }
  902. static int js_host_form_set_selected(unsigned int node, int index)
  903. {
  904. struct form_state *fs;
  905. unsigned int n;
  906. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  907. return 0;
  908. fs = form_get(node, 1);
  909. if (!fs)
  910. return 0;
  911. n = form_option_count(node);
  912. if (index < 0)
  913. index = 0;
  914. if (n && (unsigned int)index >= n)
  915. index = (int)n - 1;
  916. fs->selected = (unsigned char)index;
  917. layout_valid = 0;
  918. ngui_invalidate(&ui);
  919. return 1;
  920. }
  921. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  922. {
  923. unsigned int i;
  924. int n = 0;
  925. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  926. doc.nodes[form].tag != BR_TAG_FORM)
  927. return 0;
  928. for (i = 0; i < doc.nnode && n < cap; i++) {
  929. struct br_node *nd = &doc.nodes[i];
  930. if (i == form || nd->type != BR_NODE_ELEM)
  931. continue;
  932. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  933. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  934. continue;
  935. if (!form_descendant(i, form))
  936. continue;
  937. out[n++] = i;
  938. }
  939. return n;
  940. }
  941. static int js_host_form_submit(unsigned int form)
  942. {
  943. form_submit_form(form, 0);
  944. return 1;
  945. }
  946. static int js_host_form_reset(unsigned int form)
  947. {
  948. form_reset_event(form);
  949. return 1;
  950. }
  951. static void css_computed_name(const char *p, char *out, int cap)
  952. {
  953. int n = 0;
  954. for (; p && *p && n + 2 < cap; p++) {
  955. char c = *p;
  956. if (c >= 'A' && c <= 'Z') {
  957. out[n++] = '-';
  958. c = (char)(c - 'A' + 'a');
  959. } else if (c == '_') {
  960. c = '-';
  961. } else if (c >= 'a' && c <= 'z') {
  962. /* keep */
  963. }
  964. out[n++] = c;
  965. }
  966. out[n] = '\0';
  967. if (!strcmp(out, "css-float"))
  968. strcpy(out, "float");
  969. }
  970. static void css_rgb(unsigned short c, char *buf, int cap)
  971. {
  972. int r = ((c >> 11) & 31) * 255 / 31;
  973. int g = ((c >> 5) & 63) * 255 / 63;
  974. int b = (c & 31) * 255 / 31;
  975. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  976. }
  977. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  978. int font_px)
  979. {
  980. if (unit == 4) {
  981. snprintf(buf, cap, "auto");
  982. } else if (unit == 0) {
  983. snprintf(buf, cap, "%dpx", raw);
  984. } else if (unit == 1) {
  985. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  986. } else if (unit == 2) {
  987. /* Chrome's getComputedStyle() reports used pixel values. */
  988. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  989. } else if (unit == 3) {
  990. snprintf(buf, cap, "%dpx",
  991. (int)br_root_font_px() * raw / 100);
  992. } else {
  993. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  994. raw / 100, raw % 100, px);
  995. }
  996. }
  997. static int js_host_computed(unsigned int node, const char *property,
  998. char *buf, int cap)
  999. {
  1000. struct br_style st;
  1001. char name[40];
  1002. /* Node 0 is a real element when the page starts with <html>. */
  1003. if (!buf || cap <= 0 || node >= doc.nnode ||
  1004. (node == 0 && doc.nodes[0].type != BR_NODE_ELEM))
  1005. return 0;
  1006. buf[0] = '\0';
  1007. css_computed_name(property, name, sizeof(name));
  1008. style_for_node(node, &st);
  1009. if (!strcmp(name, "display")) {
  1010. const char *v = "inline";
  1011. if (st.display == BR_DISPLAY_BLOCK)
  1012. v = "block";
  1013. else if (st.display == BR_DISPLAY_NONE)
  1014. v = "none";
  1015. else if (st.display == BR_DISPLAY_FLEX)
  1016. v = "flex";
  1017. else if (st.display == BR_DISPLAY_GRID)
  1018. v = "grid";
  1019. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  1020. v = "inline-block";
  1021. snprintf(buf, cap, "%s", v);
  1022. } else if (!strcmp(name, "position")) {
  1023. static const char *pos[] = {
  1024. "static", "absolute", "fixed", "relative", "sticky"
  1025. };
  1026. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  1027. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  1028. int is_w = name[0] == 'w';
  1029. int kind = is_w ? st.width_kind : st.height_kind;
  1030. int val = is_w ? st.width : st.height;
  1031. if (kind == 3) {
  1032. if (is_w)
  1033. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  1034. st.width_calc_pct / 100,
  1035. st.width_calc_pct % 100,
  1036. st.width_calc_px);
  1037. else
  1038. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  1039. st.height_calc_pct / 100,
  1040. st.height_calc_pct % 100,
  1041. st.height_calc_px);
  1042. } else if (kind == 1) {
  1043. snprintf(buf, cap, "%dpx", val);
  1044. } else if (kind == 2) {
  1045. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  1046. } else {
  1047. snprintf(buf, cap, "auto");
  1048. }
  1049. } else if (!strcmp(name, "color") ||
  1050. !strcmp(name, "background-color")) {
  1051. if (!strcmp(name, "background-color") && !st.has_bg)
  1052. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1053. else
  1054. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  1055. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  1056. int is_fill = name[0] == 'f';
  1057. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  1058. if (mode == BR_PAINT_COLOR)
  1059. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  1060. else if (mode == BR_PAINT_CURRENT)
  1061. css_rgb(st.color, buf, cap);
  1062. else if (mode == BR_PAINT_UNSET && is_fill)
  1063. snprintf(buf, cap, "rgb(0, 0, 0)");
  1064. else if (mode == BR_PAINT_URL)
  1065. snprintf(buf, cap, "url()");
  1066. else
  1067. snprintf(buf, cap, "none");
  1068. } else if (!strcmp(name, "font-size")) {
  1069. snprintf(buf, cap, "%dpx", st.font_px);
  1070. } else if (!strcmp(name, "font-weight")) {
  1071. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  1072. } else if (!strcmp(name, "font-style")) {
  1073. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  1074. } else if (!strcmp(name, "font-family")) {
  1075. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  1076. br_font_face_family(st.font_face)[0])
  1077. snprintf(buf, cap, "%s",
  1078. br_font_face_family(st.font_face));
  1079. else
  1080. snprintf(buf, cap, "%s",
  1081. st.mono ? "monospace" : "sans-serif");
  1082. } else if (!strcmp(name, "text-align")) {
  1083. static const char *al[] = { "left", "center", "right", "justify" };
  1084. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  1085. } else if (!strcmp(name, "float")) {
  1086. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  1087. st.float_left == 2 ? "right" : "none");
  1088. } else if (!strcmp(name, "clear")) {
  1089. static const char *cl[] = { "none", "left", "right", "both" };
  1090. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  1091. } else if (!strcmp(name, "opacity")) {
  1092. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  1093. } else if (!strcmp(name, "visibility")) {
  1094. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  1095. } else if (!strcmp(name, "overflow")) {
  1096. snprintf(buf, cap, "%s",
  1097. st.overflow_hidden ? "hidden" : "visible");
  1098. } else if (!strcmp(name, "white-space")) {
  1099. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  1100. } else if (!strcmp(name, "text-transform")) {
  1101. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  1102. } else if (!strcmp(name, "box-sizing")) {
  1103. snprintf(buf, cap, "%s",
  1104. st.box_sizing ? "border-box" : "content-box");
  1105. } else if (!strcmp(name, "line-height")) {
  1106. if (st.line_h_px)
  1107. snprintf(buf, cap, "%dpx", st.line_h_px);
  1108. else if (st.line_h_pct)
  1109. snprintf(buf, cap, "%d%%", st.line_h_pct);
  1110. else
  1111. snprintf(buf, cap, "normal");
  1112. } else if (!strcmp(name, "z-index")) {
  1113. if (st.z_set)
  1114. snprintf(buf, cap, "%d", st.z_index);
  1115. else
  1116. snprintf(buf, cap, "auto");
  1117. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  1118. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  1119. int set = name[0] == 't' ? st.top_set :
  1120. name[0] == 'l' ? st.left_set :
  1121. name[0] == 'r' ? st.right_set : st.bottom_set;
  1122. int v = name[0] == 't' ? st.top :
  1123. name[0] == 'l' ? st.left :
  1124. name[0] == 'r' ? st.right : st.bottom;
  1125. if (set)
  1126. snprintf(buf, cap, "%dpx", v);
  1127. else
  1128. snprintf(buf, cap, "auto");
  1129. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  1130. !strcmp(name, "margin-bottom") ||
  1131. !strcmp(name, "margin-left") ||
  1132. !strcmp(name, "padding-top") ||
  1133. !strcmp(name, "padding-right") ||
  1134. !strcmp(name, "padding-bottom") ||
  1135. !strcmp(name, "padding-left")) {
  1136. int is_pad = name[0] == 'p';
  1137. int side = name[strlen(name) - 1] == 'p' ? 0 :
  1138. name[strlen(name) - 1] == 't' ? 1 :
  1139. name[strlen(name) - 1] == 'm' ? 2 : 3;
  1140. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  1141. if (!strcmp(name, "margin-right") ||
  1142. !strcmp(name, "padding-right"))
  1143. side = 1;
  1144. else if (!strcmp(name, "margin-bottom") ||
  1145. !strcmp(name, "padding-bottom"))
  1146. side = 2;
  1147. else if (!strcmp(name, "margin-left") ||
  1148. !strcmp(name, "padding-left"))
  1149. side = 3;
  1150. else
  1151. side = 0;
  1152. side += is_pad ? 4 : 0;
  1153. css_mp_value(buf, cap,
  1154. side == 0 ? st.mt : side == 1 ? st.mr :
  1155. side == 2 ? st.mb : side == 3 ? st.ml :
  1156. side == 4 ? st.pt : side == 5 ? st.pr :
  1157. side == 6 ? st.pb : st.pl,
  1158. st.mp_unit[side], st.mp_calc_px[side],
  1159. st.font_px);
  1160. } else if (!strcmp(name, "border-top-width") ||
  1161. !strcmp(name, "border-right-width") ||
  1162. !strcmp(name, "border-bottom-width") ||
  1163. !strcmp(name, "border-left-width")) {
  1164. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1165. name[7] == 'b' ? 2 : 3;
  1166. snprintf(buf, cap, "%dpx", st.border_w[side]);
  1167. } else if (!strcmp(name, "border-top-color") ||
  1168. !strcmp(name, "border-right-color") ||
  1169. !strcmp(name, "border-bottom-color") ||
  1170. !strcmp(name, "border-left-color")) {
  1171. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1172. name[7] == 'b' ? 2 : 3;
  1173. if (st.border_w[side] && !st.border_t[side])
  1174. css_rgb(st.border_c[side], buf, cap);
  1175. else
  1176. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1177. } else if (!strcmp(name, "background-image")) {
  1178. if (st.bg_image)
  1179. snprintf(buf, cap, "url(\"%s\")",
  1180. br_bg_image_url(st.bg_image - 1));
  1181. else
  1182. snprintf(buf, cap, "none");
  1183. } else if (!strcmp(name, "background-repeat")) {
  1184. static const char *rp[] = {
  1185. "repeat", "no-repeat", "repeat-x", "repeat-y"
  1186. };
  1187. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  1188. st.bg_repeat : 0]);
  1189. } else if (!strcmp(name, "background-position")) {
  1190. if (st.bg_pos_x_kind == 1)
  1191. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  1192. st.bg_pos_y);
  1193. else
  1194. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1195. st.bg_pos_y);
  1196. } else if (!strcmp(name, "background-size")) {
  1197. if (st.bg_size_kind == 3)
  1198. snprintf(buf, cap, "cover");
  1199. else if (st.bg_size_kind == 4)
  1200. snprintf(buf, cap, "contain");
  1201. else if (st.bg_size_kind == 1)
  1202. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1203. st.bg_size_h);
  1204. else if (st.bg_size_kind == 2)
  1205. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1206. st.bg_size_h);
  1207. else
  1208. snprintf(buf, cap, "auto");
  1209. } else if (!strcmp(name, "transform")) {
  1210. char tmp[128];
  1211. unsigned int n = 0;
  1212. if (!st.transform_set) {
  1213. snprintf(buf, cap, "none");
  1214. } else {
  1215. tmp[0] = '\0';
  1216. if (st.tx || st.ty) {
  1217. snprintf(tmp + n, sizeof(tmp) - n,
  1218. "translate(%dpx, %dpx)", st.tx, st.ty);
  1219. n = (unsigned int)strlen(tmp);
  1220. }
  1221. if (st.transform_scale) {
  1222. snprintf(tmp + n, sizeof(tmp) - n,
  1223. "%sscale(%d.%02d, %d.%02d)",
  1224. n ? " " : "", st.scale_x / 100,
  1225. st.scale_x % 100, st.scale_y / 100,
  1226. st.scale_y % 100);
  1227. n = (unsigned int)strlen(tmp);
  1228. if (st.rotate_x100) {
  1229. snprintf(tmp + n, sizeof(tmp) - n,
  1230. " rotate(%d.%02ddeg)",
  1231. st.rotate_x100 / 100,
  1232. st.rotate_x100 % 100);
  1233. }
  1234. } else if (st.rotate_x100) {
  1235. snprintf(tmp + n, sizeof(tmp) - n,
  1236. "%srotate(%d.%02ddeg)",
  1237. n ? " " : "", st.rotate_x100 / 100,
  1238. st.rotate_x100 % 100);
  1239. }
  1240. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1241. }
  1242. } else {
  1243. return 0;
  1244. }
  1245. return buf[0] != '\0';
  1246. }
  1247. static int js_host_click(unsigned int node)
  1248. {
  1249. char url[BR_URL_MAX];
  1250. const char *href;
  1251. if (node >= doc.nnode)
  1252. return 0;
  1253. if (form_is_control(node)) {
  1254. form_click(node); /* dispatches its own click event */
  1255. return 1;
  1256. }
  1257. /* element.click() fires a bubbling, cancelable click before the
  1258. * default action, like a real click (delegated list handlers). */
  1259. if (!js_browser_event(node, "click", 1, 1))
  1260. return 1;
  1261. if (link_fragment_nav(node))
  1262. return 1;
  1263. href = br_href(&doc, node);
  1264. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1265. return 0;
  1266. s_copy(pending_url, url, sizeof(pending_url));
  1267. pending_action |= ACT_NAV;
  1268. cancel_fetch = 1;
  1269. ngui_invalidate(&ui);
  1270. return 1;
  1271. }
  1272. static int fetch_script_text(const char *url, unsigned char **out,
  1273. unsigned int *outlen, char *err,
  1274. unsigned int errcap);
  1275. struct fetch_worker;
  1276. static struct fetch_worker *fetch_worker_alloc(void);
  1277. static void fetch_worker_release(struct fetch_worker *w);
  1278. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1279. unsigned int cap, const char *post,
  1280. unsigned int post_len, unsigned int node,
  1281. int bg, char *err, unsigned int errcap);
  1282. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1283. unsigned int errcap);
  1284. static int fetch_worker_read_body(struct fetch_worker *w,
  1285. unsigned char *plain,
  1286. unsigned int plaincap,
  1287. unsigned char *comp,
  1288. unsigned int compcap,
  1289. int *truncated, char *err,
  1290. unsigned int errcap);
  1291. static void fetch_workers_stop_all(void);
  1292. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1293. unsigned int cap, const char *method,
  1294. const char *ctype, const char *post,
  1295. unsigned int post_len, unsigned int node,
  1296. int bg, unsigned int dec_w,
  1297. unsigned int dec_h, int download,
  1298. char *err, unsigned int errcap);
  1299. static int script_cache_has(const char *url);
  1300. static void script_cache_put(const char *url, const unsigned char *data,
  1301. unsigned int len);
  1302. static unsigned int script_cache_hash(const char *s);
  1303. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1304. unsigned int errcap);
  1305. static void fetch_workers_cancel_busy(void);
  1306. static void worker_wait_ui(void);
  1307. static int fetch_worker_status(const struct fetch_worker *w);
  1308. static void dl_poll(void);
  1309. static void dl_load(void);
  1310. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1311. * module load: the wait must not pump input, or a click would dispatch DOM
  1312. * events into the middle of the running script. */
  1313. static int fetch_wait_passive;
  1314. static void script_error(const char *what, const char *url, const char *why)
  1315. {
  1316. char msg[192];
  1317. unsigned int n = 0;
  1318. s_append(msg, &n, what, sizeof(msg));
  1319. if (url && url[0]) {
  1320. s_append(msg, &n, " ", sizeof(msg));
  1321. s_append(msg, &n, url, sizeof(msg));
  1322. }
  1323. if (why && why[0]) {
  1324. s_append(msg, &n, ": ", sizeof(msg));
  1325. s_append(msg, &n, why, sizeof(msg));
  1326. }
  1327. js_host_report(msg);
  1328. }
  1329. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1330. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1331. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1332. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1333. #define JS_HTTP_POST_MAX (16u * 1024u)
  1334. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1335. static int js_worker_http(const char *method, const char *url,
  1336. const char *ctype, const char *body,
  1337. unsigned int body_len, struct js_http_resp *r,
  1338. char *err, int errcap);
  1339. static int js_host_http(const char *method, const char *url,
  1340. const char *ctype, const char *body,
  1341. unsigned int body_len, struct js_http_resp *r,
  1342. char *err, int errcap)
  1343. {
  1344. if (pending_action) {
  1345. s_copy(err, "page is navigating", (unsigned int)errcap);
  1346. return -1;
  1347. }
  1348. if (url[0] == '/') {
  1349. /* Local file: GET only. */
  1350. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1351. int rv;
  1352. if (!buf) {
  1353. s_copy(err, "out of memory", (unsigned int)errcap);
  1354. return -1;
  1355. }
  1356. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1357. (int)JS_HTTP_MAX);
  1358. r->status = rv < 0 ? 404 : 200;
  1359. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1360. buf[r->len] = '\0';
  1361. r->body = (char *)buf;
  1362. s_copy(r->url, url, sizeof(r->url));
  1363. if (contains_ci(url, ".json"))
  1364. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1365. return 0;
  1366. }
  1367. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1368. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1369. return -1;
  1370. }
  1371. if (body_len > JS_HTTP_POST_MAX) {
  1372. s_copy(err, "request body too large", (unsigned int)errcap);
  1373. return -1;
  1374. }
  1375. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1376. errcap);
  1377. }
  1378. /* Module source for the engine's loader: the boot script cache first, then
  1379. * one blocking fetch with input pumping disabled (the loader runs inside
  1380. * JavaScript). */
  1381. static char *js_host_load_script(const char *url, unsigned int *len)
  1382. {
  1383. unsigned char *data = 0;
  1384. char err[64];
  1385. int rv;
  1386. fetch_wait_passive++;
  1387. set_status("Loading module...", 0, 0);
  1388. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1389. fetch_wait_passive--;
  1390. if (rv != 0) {
  1391. script_error("Cannot load module", url,
  1392. rv == FETCH_ABORT ? "navigation" : err);
  1393. return 0;
  1394. }
  1395. return (char *)data;
  1396. }
  1397. /* Web Storage lives in /share, outside the page heap that every navigation
  1398. * resets: localStorage per origin for the boot, sessionStorage per origin
  1399. * and browser window. */
  1400. #define JS_ORIGIN_MAX 160
  1401. /* scheme://host[:port] of the page (a local page's whole path). */
  1402. static void js_page_origin(char *origin, unsigned int cap)
  1403. {
  1404. unsigned int i = 0, slashes = 0;
  1405. while (page_url[i] && i + 1 < cap) {
  1406. if (page_url[i] == '/' && ++slashes == 3)
  1407. break;
  1408. origin[i] = page_url[i];
  1409. i++;
  1410. }
  1411. origin[i] = '\0';
  1412. }
  1413. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1414. {
  1415. unsigned int n = 0;
  1416. s_append(out, &n, "/share/bls", cap);
  1417. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1418. }
  1419. static void js_storage_path(int kind, char *out, unsigned int cap)
  1420. {
  1421. char origin[JS_ORIGIN_MAX];
  1422. unsigned int n = 0;
  1423. js_page_origin(origin, sizeof(origin));
  1424. if (!kind) {
  1425. js_origin_path(origin, out, cap);
  1426. return;
  1427. }
  1428. s_append(out, &n, "/share/bss", cap);
  1429. if (kind) {
  1430. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1431. s_append(out, &n, "-", cap);
  1432. }
  1433. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1434. }
  1435. static void persist_mark_origin(const char *origin);
  1436. static int persist_store_lookup(const char *origin, char *out, int cap);
  1437. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1438. {
  1439. char path[48], origin[JS_ORIGIN_MAX];
  1440. int rv;
  1441. js_storage_path(kind, path, sizeof(path));
  1442. if (set) {
  1443. if (kind) {
  1444. if (!set[0] || !strcmp(set, "{}")) {
  1445. u_syscall1(SYS_UNLINK, (int)path);
  1446. return 0;
  1447. }
  1448. } else {
  1449. /* localStorage keeps an explicit "{}" rather than no
  1450. * file: a missing /share file means "not loaded from
  1451. * /data yet", and a cleared store must not come back
  1452. * from the disk copy before it is flushed. */
  1453. if (!set[0])
  1454. set = "{}";
  1455. js_page_origin(origin, sizeof(origin));
  1456. persist_mark_origin(origin);
  1457. }
  1458. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1459. (int)strlen(set)) < 0 ? -1 : 0;
  1460. }
  1461. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1462. if (rv < 0 && !kind) {
  1463. /* First use this boot: the persistent copy on /data. */
  1464. js_page_origin(origin, sizeof(origin));
  1465. rv = persist_store_lookup(origin, out, cap);
  1466. if (rv >= 0)
  1467. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1468. }
  1469. if (rv < 0)
  1470. return -1;
  1471. out[rv] = '\0';
  1472. return rv;
  1473. }
  1474. /* ---- persistence on /data ----
  1475. *
  1476. * /share is the working copy (RAM, shared by every helper and window); the
  1477. * installed disk's /data volume keeps the cookie jar and localStorage
  1478. * across reboots when it is mounted. The browser owns the disk copies: at
  1479. * start it restores the jar into /share, and its main loop writes back
  1480. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1481. * setItem updates costs one FAT write. The helpers only touch /share (they
  1482. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1483. * /data mount every disk access simply fails. Both files are plaintext
  1484. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1485. #define PERSIST_MS 3000u
  1486. #define SHARE_COOKIES "/share/bcookies"
  1487. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1488. #define DATA_STORE "/data/BSTORE.DAT"
  1489. #define DATA_STORE_MAGIC "NBLS1\n"
  1490. #define DATA_STORE_MAX (192u * 1024u)
  1491. #define PERSIST_DIRTY_MAX 8
  1492. static unsigned int persist_due;
  1493. static unsigned int cookie_sum_saved;
  1494. static int cookie_sum_valid;
  1495. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1496. static int persist_ndirty;
  1497. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1498. {
  1499. unsigned int h = 2166136261u, i;
  1500. for (i = 0; i < n; i++)
  1501. h = (h ^ p[i]) * 16777619u;
  1502. return h;
  1503. }
  1504. /* Called once at startup, before any helper runs. */
  1505. static void persist_restore(void)
  1506. {
  1507. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1508. int n;
  1509. if (!jar)
  1510. return;
  1511. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1512. (int)sizeof(struct uhttp_jar));
  1513. if (n != (int)sizeof(struct uhttp_jar)) {
  1514. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1515. (int)sizeof(struct uhttp_jar));
  1516. if (n == (int)sizeof(struct uhttp_jar)) {
  1517. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1518. (int)jar, n);
  1519. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1520. cookie_sum_valid = 1;
  1521. }
  1522. }
  1523. free(jar);
  1524. persist_due = u_ticks_ms() + PERSIST_MS;
  1525. }
  1526. static void persist_mark_origin(const char *origin)
  1527. {
  1528. int i;
  1529. for (i = 0; i < persist_ndirty; i++)
  1530. if (s_eq(persist_dirty[i], origin))
  1531. return;
  1532. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1533. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1534. }
  1535. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1536. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1537. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1538. unsigned int *o_off, unsigned int *o_len,
  1539. unsigned int *d_off, unsigned int *d_len,
  1540. unsigned int *rec_end)
  1541. {
  1542. unsigned int p = *pos, v = 0;
  1543. if (p >= len)
  1544. return 0;
  1545. *o_off = p;
  1546. while (p < len && buf[p] != '\n')
  1547. p++;
  1548. if (p >= len)
  1549. return 0;
  1550. *o_len = p - *o_off;
  1551. p++;
  1552. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1553. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1554. if (p >= len || buf[p] != '\n')
  1555. return 0;
  1556. p++;
  1557. if (v > len - p)
  1558. return 0;
  1559. *d_off = p;
  1560. *d_len = v;
  1561. p += v;
  1562. if (p < len && buf[p] == '\n')
  1563. p++;
  1564. *rec_end = p;
  1565. *pos = p;
  1566. return 1;
  1567. }
  1568. static int store_load(char **out)
  1569. {
  1570. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1571. int n;
  1572. *out = buf;
  1573. if (!buf)
  1574. return -1;
  1575. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1576. (int)DATA_STORE_MAX);
  1577. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1578. !starts_with(buf, DATA_STORE_MAGIC))
  1579. return 0;
  1580. return n;
  1581. }
  1582. static int persist_store_lookup(const char *origin, char *out, int cap)
  1583. {
  1584. char *buf;
  1585. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1586. unsigned int olen = s_len(origin);
  1587. int n = store_load(&buf), rv = -1;
  1588. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1589. &dl, &e)) {
  1590. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1591. if ((int)dl < cap) {
  1592. memcpy(out, buf + d, dl);
  1593. out[dl] = '\0';
  1594. rv = (int)dl;
  1595. }
  1596. break;
  1597. }
  1598. }
  1599. free(buf);
  1600. return rv;
  1601. }
  1602. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1603. static void persist_store_flush(void)
  1604. {
  1605. char *old, *nb, path[48];
  1606. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1607. int n = store_load(&old), i, w;
  1608. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1609. if (n < 0 || !nb) {
  1610. free(old);
  1611. free(nb);
  1612. return;
  1613. }
  1614. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1615. /* Untouched origins first, in their old order. */
  1616. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1617. &dl, &e)) {
  1618. int dirty = 0;
  1619. for (i = 0; i < persist_ndirty; i++)
  1620. if (s_len(persist_dirty[i]) == ol &&
  1621. !memcmp(persist_dirty[i], old + oo, ol))
  1622. dirty = 1;
  1623. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1624. continue;
  1625. memcpy(nb + nn, old + oo, e - oo);
  1626. nn += e - oo;
  1627. }
  1628. /* Then the changed ones (an emptied store is dropped). */
  1629. for (i = 0; i < persist_ndirty; i++) {
  1630. char num[12];
  1631. unsigned int k = 0;
  1632. js_origin_path(persist_dirty[i], path, sizeof(path));
  1633. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1634. (int)DATA_STORE_MAX);
  1635. if (w <= 2) /* missing or "{}" */
  1636. continue;
  1637. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1638. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1639. DATA_STORE_MAX) {
  1640. set_status("Saved site data is full; a site's "
  1641. "localStorage was not saved", 1, 6000);
  1642. continue;
  1643. }
  1644. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1645. nb[nn++] = '\n';
  1646. s_append(nb, &nn, num, DATA_STORE_MAX);
  1647. nb[nn++] = '\n';
  1648. memcpy(nb + nn, old, (unsigned int)w);
  1649. nn += (unsigned int)w;
  1650. nb[nn++] = '\n';
  1651. }
  1652. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1653. persist_ndirty = 0;
  1654. free(old);
  1655. free(nb);
  1656. }
  1657. static void persist_cookies_flush(void)
  1658. {
  1659. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1660. unsigned int sum;
  1661. int n;
  1662. if (!jar)
  1663. return;
  1664. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1665. (int)sizeof(struct uhttp_jar));
  1666. if (n == (int)sizeof(struct uhttp_jar)) {
  1667. sum = persist_sum(jar, (unsigned int)n);
  1668. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1669. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1670. (int)jar, n) >= 0) {
  1671. cookie_sum_saved = sum;
  1672. cookie_sum_valid = 1;
  1673. }
  1674. }
  1675. }
  1676. free(jar);
  1677. }
  1678. /* ---- visit history (URL-bar autocomplete) ----
  1679. *
  1680. * Every page that finishes loading is recorded with its title, a visit
  1681. * count and a stamp: a counter that only grows and travels with the file,
  1682. * so it orders visits across windows and boots without a wall clock. The
  1683. * table lives in BSS, because the page heap is reset on every navigation.
  1684. * The boot's browser windows share it through /share/bhist (rewritten on
  1685. * every visit) and it is persisted to /data/BHIST.DAT from persist_tick()
  1686. * at most every PERSIST_MS, like the cookie jar. A save re-reads
  1687. * /share/bhist and merges it first, so two windows add to one history
  1688. * instead of overwriting each other. File format: "NBHIST1\n", then
  1689. * "<visits> <stamp> <url>\t<title>\n" per entry. Plaintext, like the
  1690. * other browser state on /data. */
  1691. #define HIST_MAX 128
  1692. #define HIST_URL_MAX 512
  1693. #define HIST_FILE_MAX (HIST_MAX * (HIST_URL_MAX + BR_TITLE_MAX + 24) + 16)
  1694. #define HIST_MAGIC "NBHIST1\n"
  1695. #define SHARE_HIST "/share/bhist"
  1696. #define DATA_HIST "/data/BHIST.DAT"
  1697. #define HIST_FORGET_MAX 16
  1698. struct hist_ent {
  1699. unsigned int visits;
  1700. unsigned int stamp;
  1701. char url[HIST_URL_MAX];
  1702. char title[BR_TITLE_MAX];
  1703. };
  1704. static struct hist_ent hist_tab[HIST_MAX];
  1705. static int hist_n;
  1706. static int hist_share_dirty, hist_data_dirty;
  1707. /* URLs removed in this process: a merge must not bring them back. */
  1708. static unsigned int hist_forgot[HIST_FORGET_MAX];
  1709. static int hist_nforgot;
  1710. static unsigned int hist_hash(const char *s)
  1711. {
  1712. return persist_sum((const unsigned char *)s, s_len(s));
  1713. }
  1714. static int hist_is_forgotten(const char *url)
  1715. {
  1716. unsigned int h = hist_hash(url);
  1717. int i;
  1718. for (i = 0; i < hist_nforgot; i++)
  1719. if (hist_forgot[i] == h)
  1720. return 1;
  1721. return 0;
  1722. }
  1723. static int hist_find(const char *url)
  1724. {
  1725. int i;
  1726. for (i = 0; i < hist_n; i++)
  1727. if (s_eq(hist_tab[i].url, url))
  1728. return i;
  1729. return -1;
  1730. }
  1731. static unsigned int hist_next_stamp(void)
  1732. {
  1733. unsigned int m = 0;
  1734. int i;
  1735. for (i = 0; i < hist_n; i++)
  1736. if (hist_tab[i].stamp > m)
  1737. m = hist_tab[i].stamp;
  1738. return m + 1;
  1739. }
  1740. /* Copy a title, turning tabs/newlines (the file separators) into spaces. */
  1741. static void hist_copy_title(char *d, const char *s, unsigned int n)
  1742. {
  1743. unsigned int i;
  1744. for (i = 0; i + 1 < BR_TITLE_MAX && i < n && s[i]; i++)
  1745. d[i] = (unsigned char)s[i] < 0x20 ? ' ' : s[i];
  1746. d[i] = '\0';
  1747. }
  1748. /* Insert or update an entry; the newer stamp wins the title, the larger
  1749. * visit count is kept. A full table evicts the least recent entry, unless
  1750. * the new one is older still. Returns NULL when nothing was stored. */
  1751. static struct hist_ent *hist_put(const char *url, const char *title,
  1752. unsigned int visits, unsigned int stamp)
  1753. {
  1754. struct hist_ent *e;
  1755. int i = hist_find(url);
  1756. if (i < 0) {
  1757. if (hist_n < HIST_MAX) {
  1758. i = hist_n++;
  1759. } else {
  1760. int j;
  1761. i = 0;
  1762. for (j = 1; j < hist_n; j++)
  1763. if (hist_tab[j].stamp < hist_tab[i].stamp)
  1764. i = j;
  1765. if (hist_tab[i].stamp >= stamp)
  1766. return 0;
  1767. }
  1768. e = &hist_tab[i];
  1769. e->visits = 0;
  1770. e->stamp = 0;
  1771. e->title[0] = '\0';
  1772. s_copy(e->url, url, sizeof(e->url));
  1773. }
  1774. e = &hist_tab[i];
  1775. if (visits > e->visits)
  1776. e->visits = visits;
  1777. if (stamp >= e->stamp) {
  1778. e->stamp = stamp;
  1779. if (title && title[0])
  1780. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1781. } else if (!e->title[0] && title) {
  1782. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1783. }
  1784. return e;
  1785. }
  1786. static unsigned int hist_parse_dec(const char *b, int n, int *pos)
  1787. {
  1788. unsigned int v = 0;
  1789. while (*pos < n && b[*pos] >= '0' && b[*pos] <= '9')
  1790. v = v * 10 + (unsigned int)(b[(*pos)++] - '0');
  1791. return v;
  1792. }
  1793. static void hist_merge_buf(const char *b, int n)
  1794. {
  1795. int pos = (int)s_len(HIST_MAGIC);
  1796. char url[HIST_URL_MAX], title[BR_TITLE_MAX];
  1797. if (n < pos || memcmp(b, HIST_MAGIC, (unsigned int)pos))
  1798. return;
  1799. while (pos < n) {
  1800. unsigned int visits, stamp, ul = 0;
  1801. int t0, t1;
  1802. visits = hist_parse_dec(b, n, &pos);
  1803. if (pos < n && b[pos] == ' ')
  1804. pos++;
  1805. stamp = hist_parse_dec(b, n, &pos);
  1806. if (pos < n && b[pos] == ' ')
  1807. pos++;
  1808. while (pos < n && b[pos] != '\t' && b[pos] != '\n') {
  1809. if (ul + 1 < sizeof(url))
  1810. url[ul++] = b[pos];
  1811. pos++;
  1812. }
  1813. url[ul] = '\0';
  1814. t0 = t1 = pos < n && b[pos] == '\t' ? pos + 1 : pos;
  1815. while (t1 < n && b[t1] != '\n')
  1816. t1++;
  1817. pos = t1 + 1;
  1818. hist_copy_title(title, b + t0, (unsigned int)(t1 - t0));
  1819. if (ul && ul + 1 < sizeof(url) && !hist_is_forgotten(url))
  1820. hist_put(url, title, visits, stamp);
  1821. }
  1822. }
  1823. static int hist_serialize(char *b, unsigned int cap)
  1824. {
  1825. unsigned int n = 0;
  1826. int i;
  1827. s_append(b, &n, HIST_MAGIC, cap);
  1828. for (i = 0; i < hist_n; i++) {
  1829. struct hist_ent *e = &hist_tab[i];
  1830. if (n + s_len(e->url) + s_len(e->title) + 26 >= cap)
  1831. break;
  1832. s_append_dec(b, &n, e->visits, cap);
  1833. b[n++] = ' ';
  1834. s_append_dec(b, &n, e->stamp, cap);
  1835. b[n++] = ' ';
  1836. s_append(b, &n, e->url, cap);
  1837. b[n++] = '\t';
  1838. s_append(b, &n, e->title, cap);
  1839. b[n++] = '\n';
  1840. }
  1841. return (int)n;
  1842. }
  1843. /* Merge /share/bhist, then write it back (and /data when asked). */
  1844. static void hist_sync(int to_data)
  1845. {
  1846. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1847. int n;
  1848. if (!b)
  1849. return;
  1850. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1851. (int)HIST_FILE_MAX);
  1852. if (n > 0)
  1853. hist_merge_buf(b, n);
  1854. n = hist_serialize(b, HIST_FILE_MAX);
  1855. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1856. hist_share_dirty = 0;
  1857. if (to_data) {
  1858. /* No /data mount: the write fails, and there is nothing to
  1859. * retry until the next visit. */
  1860. u_syscall3(SYS_WRITE_FILE, (int)DATA_HIST, (int)b, n);
  1861. hist_data_dirty = 0;
  1862. }
  1863. free(b);
  1864. }
  1865. /* Startup: the boot's shared copy, else the saved one from /data. */
  1866. static void hist_load(void)
  1867. {
  1868. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1869. int n;
  1870. if (!b)
  1871. return;
  1872. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1873. (int)HIST_FILE_MAX);
  1874. if (n <= 0) {
  1875. n = u_syscall3(SYS_READ_FILE, (int)DATA_HIST, (int)b,
  1876. (int)HIST_FILE_MAX);
  1877. if (n > 0)
  1878. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1879. }
  1880. if (n > 0)
  1881. hist_merge_buf(b, n);
  1882. free(b);
  1883. }
  1884. static void hist_visit(const char *url, const char *title)
  1885. {
  1886. struct hist_ent *e;
  1887. unsigned int i;
  1888. if (!url[0] || starts_with(url, "about:") ||
  1889. s_len(url) >= HIST_URL_MAX)
  1890. return;
  1891. for (i = 0; url[i]; i++)
  1892. if ((unsigned char)url[i] < 0x20)
  1893. return;
  1894. e = hist_put(url, title, 0, hist_next_stamp());
  1895. if (!e)
  1896. return;
  1897. e->visits++;
  1898. hist_data_dirty = 1;
  1899. hist_sync(0);
  1900. }
  1901. static void hist_forget(int i)
  1902. {
  1903. if (i < 0 || i >= hist_n)
  1904. return;
  1905. if (hist_nforgot < HIST_FORGET_MAX)
  1906. hist_forgot[hist_nforgot++] = hist_hash(hist_tab[i].url);
  1907. hist_n--;
  1908. for (; i < hist_n; i++)
  1909. hist_tab[i] = hist_tab[i + 1];
  1910. hist_data_dirty = 1;
  1911. hist_sync(0);
  1912. }
  1913. static void hist_tick(void)
  1914. {
  1915. if (hist_share_dirty || hist_data_dirty)
  1916. hist_sync(hist_data_dirty);
  1917. }
  1918. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1919. static void persist_tick(void)
  1920. {
  1921. unsigned int now = u_ticks_ms();
  1922. if ((int)(now - persist_due) < 0)
  1923. return;
  1924. persist_due = now + PERSIST_MS;
  1925. persist_cookies_flush();
  1926. if (persist_ndirty)
  1927. persist_store_flush();
  1928. hist_tick();
  1929. }
  1930. /* <link rel="modulepreload">: download the page's module graph on all
  1931. * helpers at once into the boot script cache, before any script runs. The
  1932. * engine's module loader is sequential (one blocking fetch per import), so
  1933. * without this a Vite app with a dozen chunks pays every round trip in a
  1934. * row. Failures are ignored; the loader fetches what is missing. */
  1935. #define MODULE_PRELOAD_MAX 24
  1936. static void prefetch_module_preloads(void)
  1937. {
  1938. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1939. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1940. unsigned int count = 0, next = 0, done = 0, i;
  1941. char err[64];
  1942. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1943. struct br_node *nd = &doc.nodes[i];
  1944. const char *rel, *href;
  1945. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1946. continue;
  1947. rel = br_rel(&doc, i);
  1948. href = br_href(&doc, i);
  1949. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1950. continue;
  1951. if (resolve_link(page_url, href, urls[count],
  1952. sizeof(urls[count])) != 0 ||
  1953. urls[count][0] == '/' || script_cache_has(urls[count]))
  1954. continue;
  1955. slot[count++] = 0;
  1956. }
  1957. if (!count)
  1958. return;
  1959. set_status("Loading modules...", 0, 0);
  1960. while (done < count) {
  1961. struct fetch_worker *w;
  1962. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1963. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1964. 0, 0, 0, err,
  1965. sizeof(err)) != 0) {
  1966. fetch_worker_release(w);
  1967. done++;
  1968. } else {
  1969. slot[next] = w;
  1970. }
  1971. next++;
  1972. }
  1973. worker_wait_ui();
  1974. if (cancel_fetch || pending_action) {
  1975. fetch_workers_cancel_busy();
  1976. return;
  1977. }
  1978. for (i = 0; i < next; i++) {
  1979. unsigned char *body;
  1980. int rv, tr = 0;
  1981. if (!slot[i])
  1982. continue;
  1983. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1984. if (rv == 0)
  1985. continue;
  1986. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1987. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1988. if (body) {
  1989. rv = fetch_worker_read_body(slot[i], body,
  1990. BR_SCRIPT_MAX, image_io_buf,
  1991. BR_PAGE_COMP_MAX, &tr, err,
  1992. sizeof(err));
  1993. if (rv > 0 && !tr)
  1994. script_cache_put(urls[i], body,
  1995. (unsigned int)rv);
  1996. free(body);
  1997. }
  1998. fetch_worker_release(slot[i]);
  1999. slot[i] = 0;
  2000. done++;
  2001. }
  2002. u_sleep_ms(10);
  2003. }
  2004. }
  2005. /* Script prefetch state: one entry per <script> block. Remote bodies are
  2006. * submitted to helper workers ahead of time, but scripts still execute in
  2007. * document order. */
  2008. #define SCRIPT_INLINE 0
  2009. #define SCRIPT_LOCAL 1
  2010. #define SCRIPT_REMOTE 2
  2011. #define SCRIPT_ERROR 3
  2012. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  2013. static unsigned char script_kind[BR_MAX_SCRIPTS];
  2014. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  2015. static void script_submit_window(unsigned int *next, char *err,
  2016. unsigned int errcap)
  2017. {
  2018. while (*next < doc.nscripts) {
  2019. struct fetch_worker *w;
  2020. if (script_kind[*next] != SCRIPT_REMOTE) {
  2021. (*next)++;
  2022. continue;
  2023. }
  2024. w = fetch_worker_alloc();
  2025. if (!w)
  2026. return;
  2027. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  2028. 0, 0, 0, 0, err, errcap) != 0) {
  2029. fetch_worker_release(w);
  2030. script_kind[*next] = SCRIPT_ERROR;
  2031. (*next)++;
  2032. continue;
  2033. }
  2034. script_slot[*next] = w;
  2035. (*next)++;
  2036. }
  2037. }
  2038. /* Run the page's scripts in document order. External bodies are prefetched
  2039. * in parallel so downloading script N+1 overlaps executing script N; inline
  2040. * bodies are copied because the engine needs NUL-terminated text. */
  2041. static void run_page_scripts(void)
  2042. {
  2043. struct js_browser_host host;
  2044. unsigned int i, next = 0;
  2045. char err[64], ferr[64];
  2046. if (!doc.nscripts)
  2047. return;
  2048. host.status = js_host_status;
  2049. host.report = js_host_report;
  2050. host.navigate = js_host_navigate;
  2051. host.changed = js_host_changed;
  2052. host.rect = js_host_rect;
  2053. host.form_value = js_host_form_value;
  2054. host.form_checked = js_host_form_checked;
  2055. host.form_selected = js_host_form_selected;
  2056. host.form_set_value = js_host_form_set_value;
  2057. host.form_set_checked = js_host_form_set_checked;
  2058. host.form_set_selected = js_host_form_set_selected;
  2059. host.form_elements = js_host_form_elements;
  2060. host.form_submit = js_host_form_submit;
  2061. host.form_reset = js_host_form_reset;
  2062. host.click = js_host_click;
  2063. host.computed = js_host_computed;
  2064. host.http = js_host_http;
  2065. host.load_script = js_host_load_script;
  2066. host.storage = js_host_storage;
  2067. host.set_hash = js_host_set_hash;
  2068. host.page_url = page_url;
  2069. host.width = ui.w;
  2070. host.height = ui.h;
  2071. if (js_browser_start(&doc, &host) != 0) {
  2072. js_host_status("JavaScript: out of memory", 1);
  2073. return;
  2074. }
  2075. resize_sent_w = -1;
  2076. resize_pending = 0;
  2077. prefetch_module_preloads();
  2078. for (i = 0; i < doc.nscripts; i++) {
  2079. struct br_script *script = &doc.scripts[i];
  2080. const char *src_attr = script->src_off ?
  2081. doc.attrs + script->src_off : "";
  2082. script_slot[i] = 0;
  2083. if (!script->src_off) {
  2084. script_kind[i] = SCRIPT_INLINE;
  2085. continue;
  2086. }
  2087. if (!src_attr[0] ||
  2088. resolve_link(page_url, src_attr, script_urls[i],
  2089. sizeof(script_urls[i])) != 0) {
  2090. script_urls[i][0] = '\0';
  2091. script_kind[i] = SCRIPT_ERROR;
  2092. continue;
  2093. }
  2094. if (script_urls[i][0] == '/' ||
  2095. script_cache_has(script_urls[i]))
  2096. script_kind[i] = SCRIPT_LOCAL;
  2097. else
  2098. script_kind[i] = SCRIPT_REMOTE;
  2099. }
  2100. script_submit_window(&next, ferr, sizeof(ferr));
  2101. for (i = 0; i < doc.nscripts; i++) {
  2102. struct br_script *script = &doc.scripts[i];
  2103. /* document.currentScript for classic scripts (null for modules) */
  2104. js_browser_set_current_script(script->module ? 0 : script->node);
  2105. if (script_kind[i] == SCRIPT_INLINE) {
  2106. unsigned int off = script->off;
  2107. unsigned int len = script->len;
  2108. unsigned int k;
  2109. char *src = (char *)malloc(len + 1);
  2110. if (!src) {
  2111. js_host_status("JavaScript: out of memory", 1);
  2112. break;
  2113. }
  2114. for (k = 0; k < len; k++)
  2115. src[k] = doc.script_src[off + k];
  2116. src[len] = '\0';
  2117. if (script->module) {
  2118. /* A distinct module name per inline module
  2119. * (QuickJS registers modules by name); the
  2120. * fragment keeps relative imports resolving
  2121. * against the page. */
  2122. char mname[BR_URL_MAX + 16];
  2123. unsigned int mn = 0;
  2124. s_append(mname, &mn, page_url, sizeof(mname));
  2125. s_append(mname, &mn, "#module", sizeof(mname));
  2126. s_append_dec(mname, &mn, i, sizeof(mname));
  2127. js_browser_run_module(src, mname);
  2128. } else {
  2129. js_browser_run(src, page_url);
  2130. }
  2131. free(src);
  2132. } else if (script->src_off) {
  2133. const char *src_attr = doc.attrs + script->src_off;
  2134. if (script_kind[i] == SCRIPT_ERROR) {
  2135. script_error("Cannot load script", src_attr,
  2136. script_urls[i][0] ?
  2137. "network busy" :
  2138. "unsupported URL");
  2139. continue;
  2140. }
  2141. if (script_kind[i] == SCRIPT_LOCAL) {
  2142. unsigned char *data = 0;
  2143. unsigned int len = 0;
  2144. int rv;
  2145. set_status("Loading script...", 0, 0);
  2146. rv = fetch_script_text(script_urls[i], &data,
  2147. &len, err, sizeof(err));
  2148. if (rv == FETCH_ABORT)
  2149. break;
  2150. if (rv != 0) {
  2151. script_error("Cannot load script",
  2152. script_urls[i], err);
  2153. continue;
  2154. }
  2155. if (script->module)
  2156. js_browser_run_module(
  2157. (const char *)data,
  2158. script_urls[i]);
  2159. else
  2160. js_browser_run((const char *)data,
  2161. script_urls[i]);
  2162. free(data);
  2163. } else {
  2164. struct fetch_worker *w = script_slot[i];
  2165. unsigned char *body = 0;
  2166. int tr = 0, rv;
  2167. if (!w) {
  2168. w = fetch_worker_alloc();
  2169. if (!w)
  2170. continue;
  2171. if (fetch_worker_submit(w,
  2172. script_urls[i],
  2173. BR_SCRIPT_MAX,
  2174. 0, 0, 0, 0, err,
  2175. sizeof(err)) != 0) {
  2176. fetch_worker_release(w);
  2177. script_kind[i] = SCRIPT_ERROR;
  2178. if (i == next)
  2179. next++;
  2180. continue;
  2181. }
  2182. script_slot[i] = w;
  2183. if (i == next)
  2184. next++;
  2185. }
  2186. set_status("Loading script...", 0, 0);
  2187. rv = fetch_worker_wait(w, err, sizeof(err));
  2188. if (rv == FETCH_ABORT) {
  2189. fetch_workers_stop_all();
  2190. break;
  2191. }
  2192. /* The body gets its own buffer (scripts are up
  2193. * to 2 MB); image_io_buf takes the gzip
  2194. * stream. */
  2195. body = rv == 0 ? (unsigned char *)malloc(
  2196. BR_SCRIPT_MAX + 1) : 0;
  2197. if (body)
  2198. rv = fetch_worker_read_body(w, body,
  2199. BR_SCRIPT_MAX, image_io_buf,
  2200. BR_PAGE_COMP_MAX, &tr, err,
  2201. sizeof(err));
  2202. else {
  2203. if (rv == 0)
  2204. s_copy(err, "out of memory",
  2205. sizeof(err));
  2206. rv = -1;
  2207. }
  2208. fetch_worker_release(w);
  2209. script_slot[i] = 0;
  2210. script_submit_window(&next, ferr, sizeof(ferr));
  2211. if (rv <= 0)
  2212. script_error("Cannot load script",
  2213. script_urls[i], err);
  2214. else if (tr || (unsigned int)rv >=
  2215. BR_SCRIPT_MAX)
  2216. script_error("Cannot load script",
  2217. script_urls[i],
  2218. "script is too large");
  2219. else {
  2220. body[rv] = '\0';
  2221. script_cache_put(script_urls[i], body,
  2222. (unsigned int)rv);
  2223. if (script->module)
  2224. js_browser_run_module(
  2225. (const char *)body,
  2226. script_urls[i]);
  2227. else
  2228. js_browser_run(
  2229. (const char *)body,
  2230. script_urls[i]);
  2231. }
  2232. free(body);
  2233. }
  2234. }
  2235. if (pending_action)
  2236. break;
  2237. }
  2238. js_browser_set_current_script(0);
  2239. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  2240. * load_home() stop it before the next navigation. */
  2241. if (doc.scripts_truncated && !js_last_error)
  2242. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  2243. 1);
  2244. }
  2245. /* ---- images ---- */
  2246. /* data: images that failed to decode (key = data_img_key()), so a layout
  2247. * pass does not retry them on every frame. */
  2248. #define DATA_IMG_FAIL_MAX 32
  2249. static unsigned int data_img_fail[DATA_IMG_FAIL_MAX];
  2250. static int data_img_nfail;
  2251. static void image_reset(void)
  2252. {
  2253. int i;
  2254. for (i = 0; i < BR_MAX_IMAGES; i++) {
  2255. images[i].state = 0;
  2256. images[i].native_w = images[i].native_h = 0;
  2257. images[i].err[0] = '\0';
  2258. /* heap_clear() ran before us, so these pointers are stale: drop
  2259. * them without calling free(). */
  2260. memset(&images[i].disp, 0, sizeof(images[i].disp));
  2261. images[i].disp_pixels = 0;
  2262. images[i].disp_last = 0;
  2263. }
  2264. image_count = 0;
  2265. data_img_nfail = 0;
  2266. image_pixels = 0;
  2267. image_disp_pixels = 0;
  2268. image_disp_clock = 0;
  2269. memset(img_stat_log, 0, sizeof(img_stat_log));
  2270. img_stat_log_len = 0;
  2271. img_stat_start = 0;
  2272. img_stat_wall = 0;
  2273. img_stat_net = img_stat_open = img_stat_first = 0;
  2274. img_stat_io = img_stat_dec = img_stat_scale = 0;
  2275. img_stat_paint = img_stat_reflow = 0;
  2276. img_stat_bytes = 0;
  2277. img_stat_n = 0;
  2278. img_last_dec_ms = img_last_scale_ms = 0;
  2279. img_repaint_ms = 0;
  2280. img_repaint_pending = 0;
  2281. preload_active = 0;
  2282. preload_pending = 0;
  2283. preload_wait = 0;
  2284. preload_node = 0;
  2285. preload_loaded = 0;
  2286. }
  2287. /* Ask for a repaint, but not more often than BR_IMG_REPAINT_MS while images
  2288. * are arriving. The main loop draws once per dirty frame; without this a
  2289. * page of N images did N full layout+paint passes. */
  2290. static void image_repaint(void)
  2291. {
  2292. unsigned int now = u_ticks_ms();
  2293. if (!img_repaint_ms || (now - img_repaint_ms) >= BR_IMG_REPAINT_MS) {
  2294. img_repaint_ms = now;
  2295. img_repaint_pending = 0;
  2296. ngui_invalidate(&ui);
  2297. } else {
  2298. img_repaint_pending = 1;
  2299. }
  2300. }
  2301. static void image_disp_drop(struct br_image *bi)
  2302. {
  2303. if (bi->disp.px)
  2304. free(bi->disp.px);
  2305. if (bi->disp.alpha)
  2306. free(bi->disp.alpha);
  2307. memset(&bi->disp, 0, sizeof(bi->disp));
  2308. if (bi->disp_pixels) {
  2309. if (image_disp_pixels >= bi->disp_pixels)
  2310. image_disp_pixels -= bi->disp_pixels;
  2311. bi->disp_pixels = 0;
  2312. }
  2313. }
  2314. /* Free the least recently used display caches until need pixels fit. The
  2315. * source bitmap (bi->img) is never evicted; a later draw rescales it again. */
  2316. static int image_disp_room(unsigned int need)
  2317. {
  2318. while (image_disp_pixels + need > BR_IMG_DISP_BUDGET) {
  2319. unsigned int oldest = ~0u;
  2320. int i, victim = -1;
  2321. for (i = 0; i < image_count; i++) {
  2322. if (!images[i].disp.px)
  2323. continue;
  2324. if (images[i].disp_last < oldest) {
  2325. oldest = images[i].disp_last;
  2326. victim = i;
  2327. }
  2328. }
  2329. if (victim < 0)
  2330. return -1;
  2331. image_disp_drop(&images[victim]);
  2332. }
  2333. return 0;
  2334. }
  2335. /* Return a bitmap at exactly dw x dh, building it once from the capped source
  2336. * bitmap. Callers then draw with scale 1 and img_draw's copy fast path. */
  2337. static struct img_image *image_display_get(struct br_image *bi, int dw, int dh)
  2338. {
  2339. struct img_blit b;
  2340. unsigned int px;
  2341. if (!bi || bi->state != 1 || !bi->img.px || dw < 1 || dh < 1)
  2342. return 0;
  2343. if (dw == (int)bi->img.w && dh == (int)bi->img.h)
  2344. return &bi->img;
  2345. if (dw > 4096 || dh > 4096)
  2346. return &bi->img;
  2347. if (bi->disp.px && bi->disp.w == (unsigned int)dw &&
  2348. bi->disp.h == (unsigned int)dh) {
  2349. bi->disp_last = ++image_disp_clock;
  2350. return &bi->disp;
  2351. }
  2352. px = (unsigned int)dw * (unsigned int)dh;
  2353. if (px > BR_IMG_DISP_BUDGET || image_disp_room(px) != 0)
  2354. return &bi->img;
  2355. image_disp_drop(bi);
  2356. bi->disp.px = (unsigned short *)malloc(px * 2u);
  2357. if (!bi->disp.px)
  2358. return &bi->img;
  2359. if (bi->img.alpha) {
  2360. bi->disp.alpha = (unsigned char *)malloc(px);
  2361. if (!bi->disp.alpha) {
  2362. free(bi->disp.px);
  2363. bi->disp.px = 0;
  2364. return &bi->img;
  2365. }
  2366. }
  2367. bi->disp.w = (unsigned int)dw;
  2368. bi->disp.h = (unsigned int)dh;
  2369. bi->disp.format = bi->img.format;
  2370. bi->disp.flags = 0;
  2371. memset(&b, 0, sizeof(b));
  2372. b.dst = bi->disp.px;
  2373. b.dst_w = dw;
  2374. b.dst_h = dh;
  2375. b.clip_w = dw;
  2376. b.clip_h = dh;
  2377. b.scale = ((unsigned int)dw << 16) / bi->img.w;
  2378. b.dst_a = bi->disp.alpha;
  2379. b.flags = bi->disp.alpha ? IMG_BLIT_SAVE_ALPHA : 0;
  2380. img_draw(&bi->img, &b);
  2381. bi->disp_pixels = px;
  2382. image_disp_pixels += px;
  2383. bi->disp_last = ++image_disp_clock;
  2384. return &bi->disp;
  2385. }
  2386. /* Decode into the shared arena, then copy/scale the result into a display
  2387. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  2388. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  2389. * pixels. Transparent edges are composited over white. */
  2390. /* One decode scratch arena per page, reused across images. Allocating and
  2391. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  2392. * each small display bitmap landed in the hole the previous arena left, so
  2393. * the next arena no longer fit and the heap ratcheted up until an app
  2394. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  2395. * still released right after their one image. */
  2396. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  2397. static unsigned char *decode_arena_get(unsigned int bytes)
  2398. {
  2399. if (decode_arena && decode_arena_size >= bytes)
  2400. return decode_arena;
  2401. free(decode_arena);
  2402. decode_arena = (unsigned char *)malloc(bytes);
  2403. decode_arena_size = decode_arena ? bytes : 0;
  2404. return decode_arena;
  2405. }
  2406. static void decode_arena_put(void)
  2407. {
  2408. if (decode_arena_size > DECODE_ARENA_KEEP) {
  2409. free(decode_arena);
  2410. decode_arena = 0;
  2411. decode_arena_size = 0;
  2412. }
  2413. }
  2414. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  2415. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  2416. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  2417. static int svg_text_sniff(const unsigned char *d, unsigned int len);
  2418. static int svg_decode_image(const unsigned char *data, unsigned int len,
  2419. struct br_image *bi, int box_w, int box_h);
  2420. static int decode_image_data(const unsigned char *data, unsigned int len,
  2421. struct br_image *bi, int box_w, int box_h,
  2422. int fit_w, int fit_h)
  2423. {
  2424. struct img_info info;
  2425. struct img_options opt;
  2426. struct img_mem mem;
  2427. struct img_image decoded;
  2428. unsigned char *arena;
  2429. unsigned int est, bytes, i;
  2430. unsigned int t0;
  2431. unsigned short *px;
  2432. unsigned char *alpha = 0;
  2433. int dw, dh, r;
  2434. bi->url_hash = 0;
  2435. img_last_dec_ms = 0;
  2436. img_last_scale_ms = 0;
  2437. if (img_sniff(data, len, &info) != 0) {
  2438. if (svg_text_sniff(data, len))
  2439. return svg_decode_image(data, len, bi,
  2440. box_w > 0 && box_h > 0 ? box_w : fit_w,
  2441. box_w > 0 && box_h > 0 ? box_h : fit_h);
  2442. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  2443. return -1;
  2444. }
  2445. est = img_estimate(&info);
  2446. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  2447. s_copy(bi->err, "image too large", sizeof(bi->err));
  2448. return -1;
  2449. }
  2450. arena = decode_arena_get(est);
  2451. if (!arena) {
  2452. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2453. return -1;
  2454. }
  2455. img_mem_init(&mem, arena, est);
  2456. opt.max_pixels = BR_IMG_PIX_MAX;
  2457. opt.max_w = fit_w > 0 ? (unsigned int)fit_w :
  2458. (box_w > 0 ? (unsigned int)box_w : 0);
  2459. opt.max_h = fit_h > 0 ? (unsigned int)fit_h :
  2460. (box_h > 0 ? (unsigned int)box_h : 0);
  2461. t0 = u_ticks_ms();
  2462. r = img_decode(data, len, &opt, &mem, &decoded);
  2463. img_last_dec_ms = u_ticks_ms() - t0;
  2464. if (r != 0) {
  2465. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  2466. goto fail;
  2467. }
  2468. if (decoded.w == 0 || decoded.h == 0) {
  2469. s_copy(bi->err, "empty image", sizeof(bi->err));
  2470. goto fail;
  2471. }
  2472. /* The JPEG decoder may have reduced the IDCT output; the layout still
  2473. * needs the intrinsic dimensions from the header. */
  2474. bi->native_w = info.width ? (int)info.width : (int)decoded.w;
  2475. bi->native_h = info.height ? (int)info.height : (int)decoded.h;
  2476. dw = (int)decoded.w;
  2477. dh = (int)decoded.h;
  2478. /* An <img> with a CSS/attribute box only ever needs a bitmap that big:
  2479. * decoding 1200x800 and then box-filtering it to 1000x666, only to
  2480. * paint it at 400x267, doubled the decode-time scaling work. cap both
  2481. * axes with one scale so the aspect ratio is preserved. */
  2482. if (fit_w > 0 || fit_h > 0) {
  2483. unsigned int scw = fit_w > 0 ?
  2484. ((unsigned int)fit_w << 16) / decoded.w : ~0u;
  2485. unsigned int sch = fit_h > 0 ?
  2486. ((unsigned int)fit_h << 16) / decoded.h : ~0u;
  2487. unsigned int sc = scw < sch ? scw : sch;
  2488. if (sc < 0x10000u) {
  2489. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2490. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2491. if (dw < 1)
  2492. dw = 1;
  2493. if (dh < 1)
  2494. dh = 1;
  2495. }
  2496. }
  2497. if (box_w > 0 && box_h > 0) {
  2498. /* cover: scale so both box sides are filled, never up */
  2499. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  2500. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  2501. unsigned int sc = sw > sh ? sw : sh;
  2502. if (sc < 0x10000u) {
  2503. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2504. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2505. }
  2506. }
  2507. if (dw > BR_IMG_LAYOUT_W) {
  2508. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  2509. dw = BR_IMG_LAYOUT_W;
  2510. }
  2511. if (dh < 1)
  2512. dh = 1;
  2513. if (dw < 1)
  2514. dw = 1;
  2515. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  2516. BR_IMG_PIXEL_BUDGET) {
  2517. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  2518. goto fail;
  2519. }
  2520. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  2521. px = (unsigned short *)malloc(bytes);
  2522. if (!px) {
  2523. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2524. goto fail;
  2525. }
  2526. /* Keep the alpha plane for the scaled image so transparent logos and
  2527. * icons composite over the page instead of the browser's dark theme
  2528. * background. Very large alpha images stay flattened to bound the
  2529. * heap use. */
  2530. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  2531. alpha = (unsigned char *)malloc((unsigned int)dw *
  2532. (unsigned int)dh);
  2533. if (alpha) {
  2534. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2535. alpha[i] = 255;
  2536. }
  2537. }
  2538. /* With an alpha plane the colour under transparent pixels only shows
  2539. * through partially covered edge pixels of the downscale: use white,
  2540. * as documented above, not the dark browser theme (which left a dark
  2541. * fringe around scaled app icons). */
  2542. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2543. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  2544. {
  2545. struct img_blit b;
  2546. b.dst = px;
  2547. b.dst_w = dw;
  2548. b.dst_h = dh;
  2549. b.clip_x = 0;
  2550. b.clip_y = 0;
  2551. b.clip_w = dw;
  2552. b.clip_h = dh;
  2553. b.x = 0;
  2554. b.y = 0;
  2555. b.scale = ((unsigned int)dw << 16) / decoded.w;
  2556. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  2557. b.bg2 = b.bg;
  2558. b.dst_a = alpha;
  2559. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  2560. t0 = u_ticks_ms();
  2561. img_draw(&decoded, &b);
  2562. img_last_scale_ms = u_ticks_ms() - t0;
  2563. }
  2564. bi->img.format = decoded.format;
  2565. bi->img.w = (unsigned int)dw;
  2566. bi->img.h = (unsigned int)dh;
  2567. bi->img.px = px;
  2568. bi->img.alpha = alpha;
  2569. bi->img.flags = 0;
  2570. bi->state = 1;
  2571. image_pixels += (unsigned int)dw * (unsigned int)dh;
  2572. decode_arena_put();
  2573. return 0;
  2574. fail:
  2575. decode_arena_put();
  2576. return -1;
  2577. }
  2578. /* ---- URL / local path handling ---- */
  2579. static int is_http(const char *s)
  2580. {
  2581. return starts_with(s, "http://") || starts_with(s, "https://");
  2582. }
  2583. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  2584. static int normalize_abs(const char *in, char *out, unsigned int cap)
  2585. {
  2586. char seg[64];
  2587. unsigned int i = 0, o = 1;
  2588. int depth = 0;
  2589. int trailing;
  2590. if (!in || in[0] != '/' || cap < 2)
  2591. return -1;
  2592. trailing = 0;
  2593. {
  2594. unsigned int n = s_len(in);
  2595. if (n > 1 && in[n - 1] == '/')
  2596. trailing = 1;
  2597. }
  2598. out[0] = '/';
  2599. while (in[i]) {
  2600. unsigned int n = 0;
  2601. while (in[i] == '/')
  2602. i++;
  2603. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  2604. if (n + 1 < sizeof(seg))
  2605. seg[n++] = in[i];
  2606. i++;
  2607. }
  2608. seg[n] = '\0';
  2609. if (n == 0)
  2610. break;
  2611. if (s_eq(seg, "."))
  2612. continue;
  2613. if (s_eq(seg, "..")) {
  2614. if (depth > 0) {
  2615. while (o > 1 && out[o - 1] != '/')
  2616. o--;
  2617. if (o > 1)
  2618. o--;
  2619. depth--;
  2620. }
  2621. continue;
  2622. }
  2623. if (o > 1) {
  2624. if (o + 1 >= cap)
  2625. return -1;
  2626. out[o++] = '/';
  2627. }
  2628. if (o + n + 1 >= cap)
  2629. return -1;
  2630. {
  2631. unsigned int j;
  2632. for (j = 0; j < n; j++)
  2633. out[o++] = seg[j];
  2634. }
  2635. depth++;
  2636. }
  2637. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2638. if (o + 1 >= cap)
  2639. return -1;
  2640. out[o++] = '/';
  2641. }
  2642. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2643. if (in[i] == '?' || in[i] == '#') {
  2644. while (in[i]) {
  2645. if (o + 1 >= cap)
  2646. return -1;
  2647. out[o++] = in[i++];
  2648. }
  2649. }
  2650. out[o] = '\0';
  2651. return 0;
  2652. }
  2653. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2654. {
  2655. char joined[BR_URL_MAX];
  2656. if (!in || !in[0]) {
  2657. s_copy(out, cwd[0] ? cwd : "/", cap);
  2658. return;
  2659. }
  2660. if (in[0] == '/') {
  2661. if (normalize_abs(in, out, cap) != 0)
  2662. s_copy(out, in, cap);
  2663. return;
  2664. }
  2665. {
  2666. unsigned int n = 0;
  2667. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2668. s_append(joined, &n, "/", sizeof(joined));
  2669. s_append(joined, &n, in, sizeof(joined));
  2670. }
  2671. if (normalize_abs(joined, out, cap) != 0)
  2672. s_copy(out, joined, cap);
  2673. }
  2674. /* ---- canonical origin cache ---- *
  2675. *
  2676. * Sites commonly redirect http://host to https://host and then to
  2677. * https://www.host. Remember the final scheme/host of the last navigation so
  2678. * a bare domain typed again goes straight there instead of paying for two
  2679. * more connections and TLS handshakes. Only default-port requests are
  2680. * rewritten; explicit ports are left alone. */
  2681. #define ORIGIN_CACHE_MAX 8
  2682. #define ORIGIN_FILE "/share/borigins"
  2683. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2684. UHTTP_HOST_MAX + 2))
  2685. struct origin_cache_entry {
  2686. char host[UHTTP_HOST_MAX];
  2687. char origin[UHTTP_HOST_MAX + 16];
  2688. };
  2689. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2690. static int origin_count;
  2691. static char origin_buf[ORIGIN_BUF_SIZE];
  2692. static int default_port(const struct uhttp_url *u)
  2693. {
  2694. return u->secure ? u->port == 443 : u->port == 80;
  2695. }
  2696. static void url_origin(const struct uhttp_url *u, char *out,
  2697. unsigned int cap)
  2698. {
  2699. unsigned int n = 0;
  2700. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2701. s_append(out, &n, u->host, cap);
  2702. if (!default_port(u)) {
  2703. s_append(out, &n, ":", cap);
  2704. s_append_dec(out, &n, u->port, cap);
  2705. }
  2706. }
  2707. static void origin_cache_apply(char *url, unsigned int cap)
  2708. {
  2709. struct uhttp_url u;
  2710. char out[BR_URL_MAX];
  2711. unsigned int n = 0;
  2712. int i;
  2713. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2714. return;
  2715. for (i = 0; i < origin_count; i++) {
  2716. if (!s_eq(u.host, origins[i].host))
  2717. continue;
  2718. s_append(out, &n, origins[i].origin, sizeof(out));
  2719. s_append(out, &n, u.path, sizeof(out));
  2720. s_copy(url, out, cap);
  2721. return;
  2722. }
  2723. }
  2724. static void origin_cache_save(void)
  2725. {
  2726. unsigned int n = 0;
  2727. int i;
  2728. for (i = 0; i < origin_count; i++) {
  2729. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2730. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2731. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2732. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2733. }
  2734. if (n)
  2735. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2736. (int)origin_buf, (int)n);
  2737. }
  2738. static void origin_cache_load(void)
  2739. {
  2740. char *p;
  2741. int rn;
  2742. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2743. (int)(sizeof(origin_buf) - 1));
  2744. if (rn <= 0)
  2745. return;
  2746. origin_buf[rn] = '\0';
  2747. p = origin_buf;
  2748. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2749. char *line = p, *origin;
  2750. while (*p && *p != '\n')
  2751. p++;
  2752. if (*p)
  2753. *p++ = '\0';
  2754. if (!line[0])
  2755. continue;
  2756. origin = line;
  2757. while (*origin && *origin != ' ')
  2758. origin++;
  2759. if (!*origin)
  2760. continue;
  2761. *origin++ = '\0';
  2762. if (!line[0] || !is_http(origin))
  2763. continue;
  2764. {
  2765. struct uhttp_url uo;
  2766. if (uhttp_parse_url(origin, &uo) != 0 ||
  2767. !s_eq(uo.path, "/"))
  2768. continue;
  2769. }
  2770. s_copy(origins[origin_count].host, line,
  2771. sizeof(origins[origin_count].host));
  2772. s_copy(origins[origin_count].origin, origin,
  2773. sizeof(origins[origin_count].origin));
  2774. origin_count++;
  2775. }
  2776. }
  2777. static int host_is_www_of(const char *host, const char *base)
  2778. {
  2779. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2780. host[3] == '.' && s_eq(host + 4, base);
  2781. }
  2782. static void origin_cache_learn(const char *requested, const char *final)
  2783. {
  2784. struct uhttp_url from, to;
  2785. char origin[UHTTP_HOST_MAX + 16];
  2786. int i;
  2787. if (!is_http(requested) || !is_http(final))
  2788. return;
  2789. if (uhttp_parse_url(requested, &from) != 0 ||
  2790. uhttp_parse_url(final, &to) != 0)
  2791. return;
  2792. if (!default_port(&from))
  2793. return;
  2794. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2795. from.port == to.port)
  2796. return;
  2797. /* Only remember origin-level canonicalisation: the same path, and
  2798. * either the same host or its www./apex sibling. A path- or
  2799. * host-specific redirect (a shortener, a login page) must not poison
  2800. * every request to the typed host. */
  2801. if (!s_eq(from.path, to.path))
  2802. return;
  2803. if (!s_eq(from.host, to.host) &&
  2804. !host_is_www_of(to.host, from.host) &&
  2805. !host_is_www_of(from.host, to.host))
  2806. return;
  2807. url_origin(&to, origin, sizeof(origin));
  2808. for (i = 0; i < origin_count; i++) {
  2809. if (s_eq(origins[i].host, from.host)) {
  2810. if (!s_eq(origins[i].origin, origin)) {
  2811. s_copy(origins[i].origin, origin,
  2812. sizeof(origins[i].origin));
  2813. origin_cache_save();
  2814. }
  2815. return;
  2816. }
  2817. }
  2818. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2819. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2820. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2821. origin_cache_save();
  2822. }
  2823. static int path_dir(const char *path, char *out, unsigned int cap)
  2824. {
  2825. unsigned int i, last = 0;
  2826. for (i = 0; path[i]; i++)
  2827. if (path[i] == '/')
  2828. last = i;
  2829. if (last == 0) {
  2830. if (cap < 2)
  2831. return -1;
  2832. out[0] = '/';
  2833. out[1] = '\0';
  2834. return 0;
  2835. }
  2836. if (last + 1 >= cap)
  2837. return -1;
  2838. {
  2839. unsigned int j;
  2840. for (j = 0; j < last; j++)
  2841. out[j] = path[j];
  2842. out[last] = '\0';
  2843. }
  2844. return 0;
  2845. }
  2846. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2847. static int resolve_link(const char *base, const char *href, char *out,
  2848. unsigned int cap)
  2849. {
  2850. static char joined[BR_URL_MAX]; /* leaf: off the stack */
  2851. if (!href || !href[0] || href[0] == '#')
  2852. return -1;
  2853. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2854. starts_with(href, "data:") || starts_with(href, "tel:"))
  2855. return -1;
  2856. if (starts_with(href, "about:")) {
  2857. s_copy(out, href, cap);
  2858. return 0;
  2859. }
  2860. if (is_http(href)) {
  2861. s_copy(out, href, cap);
  2862. return 0;
  2863. }
  2864. if (starts_with(href, "//")) {
  2865. if (is_http(base)) {
  2866. unsigned int n = 0;
  2867. s_append(out, &n, starts_with(base, "https:") ?
  2868. "https:" : "http:", cap);
  2869. s_append(out, &n, href, cap);
  2870. return 0;
  2871. }
  2872. return -1;
  2873. }
  2874. if (is_http(base)) {
  2875. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2876. }
  2877. /* local page */
  2878. if (href[0] == '/') {
  2879. if (normalize_abs(href, out, cap) != 0)
  2880. return -1;
  2881. return 0;
  2882. }
  2883. {
  2884. static char dir[BR_URL_MAX];
  2885. unsigned int n = 0;
  2886. if (s_eq(base, "about:home"))
  2887. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2888. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2889. s_copy(dir, "/", sizeof(dir));
  2890. s_append(joined, &n, dir, sizeof(joined));
  2891. if (n == 0 || joined[n - 1] != '/')
  2892. s_append(joined, &n, "/", sizeof(joined));
  2893. s_append(joined, &n, href, sizeof(joined));
  2894. }
  2895. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2896. }
  2897. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2898. * rest instead of failing when a page or stylesheet is larger than the
  2899. * buffer. The stream is still walked to the end, so a normal page is
  2900. * verified; a truncated compressed input still returns whatever was decoded
  2901. * so far. */
  2902. struct trunc_buf {
  2903. unsigned char *dst;
  2904. unsigned int cap, pos;
  2905. int full;
  2906. };
  2907. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2908. {
  2909. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2910. if (len > m->cap - m->pos) {
  2911. unsigned int room = m->cap - m->pos;
  2912. if (room) {
  2913. unsigned int i;
  2914. for (i = 0; i < room; i++)
  2915. m->dst[m->pos + i] = data[i];
  2916. m->pos += room;
  2917. }
  2918. m->full = 1;
  2919. return 0;
  2920. }
  2921. {
  2922. unsigned int i;
  2923. for (i = 0; i < len; i++)
  2924. m->dst[m->pos + i] = data[i];
  2925. }
  2926. m->pos += len;
  2927. return 0;
  2928. }
  2929. static void worker_wait_ui(void);
  2930. static void inflate_ui_pump(void *ctx)
  2931. {
  2932. static unsigned int last;
  2933. unsigned int now = u_ticks_ms();
  2934. (void)ctx;
  2935. if ((int)(now - last) >= 50) {
  2936. last = now;
  2937. worker_wait_ui();
  2938. }
  2939. }
  2940. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2941. unsigned char *dst, unsigned int cap,
  2942. unsigned int *outlen, int gzip, int *truncated)
  2943. {
  2944. struct inflate_src in;
  2945. struct inflate_sink sink;
  2946. struct trunc_buf m;
  2947. unsigned int got = 0;
  2948. int r;
  2949. in.p = src;
  2950. in.len = len;
  2951. in.more = 0;
  2952. in.ctx = 0;
  2953. m.dst = dst;
  2954. m.cap = cap;
  2955. m.pos = 0;
  2956. m.full = 0;
  2957. sink.write = trunc_write;
  2958. sink.ctx = &m;
  2959. inflate_init(&image_inflate_ws, &in, &sink);
  2960. image_inflate_ws.progress = inflate_ui_pump;
  2961. image_inflate_ws.progress_ctx = 0;
  2962. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2963. inflate_zlib(&image_inflate_ws, &got);
  2964. *outlen = m.pos;
  2965. *truncated = m.full || r != 0;
  2966. if (r != 0 && m.pos == 0)
  2967. return -1;
  2968. return 0;
  2969. }
  2970. /* ---- headless fetch workers ------------------------------------------ *
  2971. *
  2972. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2973. * writes the raw response, a small metadata file and a done marker under
  2974. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2975. * or a multi-megabyte body never freezes the UI and images download in
  2976. * parallel.
  2977. */
  2978. struct fetch_meta {
  2979. int status;
  2980. int error;
  2981. int trunc;
  2982. unsigned int len;
  2983. unsigned int open_ms;
  2984. unsigned int first_ms;
  2985. unsigned int total_ms;
  2986. /* Optional decoded bitmap produced by the helper (image jobs). */
  2987. unsigned int dw, dh, nw, nh;
  2988. unsigned int alpha;
  2989. unsigned int px_len;
  2990. unsigned int dec_ms;
  2991. int dec_err;
  2992. char encoding[16];
  2993. char ctype[64];
  2994. char final[BR_URL_MAX];
  2995. };
  2996. static void draw(unsigned int *action);
  2997. static void handle_keys(unsigned int *action);
  2998. static void handle_page_click(unsigned int *action);
  2999. #define FETCH_WORKERS 4
  3000. #define FETCH_PATH_MAX 32
  3001. /* One long-lived curl __serve helper per worker. Each worker has its own
  3002. * request/body/meta/done files under /share so several downloads can be in
  3003. * flight at once; the keep-alive connection stays in the helper process, so
  3004. * tls.c's per-process state remains valid. */
  3005. struct fetch_worker {
  3006. int pid;
  3007. int slot;
  3008. int busy;
  3009. int ready;
  3010. int image_job;
  3011. unsigned int seq;
  3012. unsigned int deadline;
  3013. int retried;
  3014. unsigned int dec_w, dec_h;
  3015. int dec_retried;
  3016. char req[FETCH_PATH_MAX];
  3017. char body[FETCH_PATH_MAX];
  3018. char meta[FETCH_PATH_MAX];
  3019. char done[FETCH_PATH_MAX];
  3020. char post[FETCH_PATH_MAX];
  3021. char px[FETCH_PATH_MAX];
  3022. char prog[FETCH_PATH_MAX];
  3023. /* Optional preload job attached to this worker. */
  3024. unsigned int node;
  3025. int bg;
  3026. char url[BR_URL_MAX];
  3027. struct fetch_meta m;
  3028. };
  3029. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  3030. /* One extra helper, outside the page pool, so a download survives a
  3031. * navigation that kills the image jobs. */
  3032. static struct fetch_worker dl_worker;
  3033. static int fetch_tty = -2;
  3034. static void fetch_tty_drain(void);
  3035. static unsigned int fetch_session;
  3036. static unsigned int fetch_seq;
  3037. static struct fetch_meta fetch_meta;
  3038. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  3039. * an HTTP-level error (helper died, timeout in the browser, ...). */
  3040. static int fetch_last_error;
  3041. static unsigned int meta_uint(char **pp)
  3042. {
  3043. char *p = *pp;
  3044. unsigned int v = 0;
  3045. while (*p >= '0' && *p <= '9') {
  3046. v = v * 10 + (unsigned int)(*p - '0');
  3047. p++;
  3048. }
  3049. while (*p && *p != '\n')
  3050. p++;
  3051. if (*p == '\n')
  3052. p++;
  3053. *pp = p;
  3054. return v;
  3055. }
  3056. static void meta_str(char **pp, char *out, unsigned int cap)
  3057. {
  3058. char *p = *pp;
  3059. unsigned int n = 0;
  3060. while (*p && *p != '\n' && n + 1 < cap)
  3061. out[n++] = *p++;
  3062. out[n] = '\0';
  3063. while (*p && *p != '\n')
  3064. p++;
  3065. if (*p == '\n')
  3066. p++;
  3067. *pp = p;
  3068. }
  3069. static void worker_wait_ui(void)
  3070. {
  3071. unsigned int action = 0;
  3072. dl_poll();
  3073. if (!ngui_begin(&ui))
  3074. return;
  3075. draw(&action);
  3076. handle_keys(&action);
  3077. handle_page_click(&action);
  3078. if (action & ACT_WAIT_NAV) {
  3079. pending_action |= action & ACT_WAIT_NAV;
  3080. if ((action & ACT_NAV) && click_url[0])
  3081. s_copy(pending_url, click_url, sizeof(pending_url));
  3082. click_url[0] = '\0';
  3083. cancel_fetch = 1;
  3084. }
  3085. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  3086. ngui_invalidate(&ui);
  3087. ngui_end(&ui);
  3088. }
  3089. static void fetch_path(char *out, unsigned int cap, const char *kind,
  3090. unsigned int session, int slot)
  3091. {
  3092. unsigned int n = 0;
  3093. s_append(out, &n, "/share/bf", cap);
  3094. s_append_dec(out, &n, session, cap);
  3095. s_append(out, &n, "_", cap);
  3096. s_append_dec(out, &n, (unsigned int)slot, cap);
  3097. s_append(out, &n, kind, cap);
  3098. }
  3099. static void fetch_pool_init(void)
  3100. {
  3101. static int ready;
  3102. int i;
  3103. if (ready)
  3104. return;
  3105. ready = 1;
  3106. fetch_session = ((unsigned int)u_getpid() << 16) ^
  3107. (u_ticks_ms() & 0xFFFFu);
  3108. if (!fetch_session)
  3109. fetch_session = 1;
  3110. for (i = 0; i < FETCH_WORKERS; i++) {
  3111. struct fetch_worker *w = &fetch_workers[i];
  3112. w->pid = -1;
  3113. w->slot = i;
  3114. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  3115. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  3116. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  3117. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  3118. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  3119. fetch_path(w->px, sizeof(w->px), "px", fetch_session, i);
  3120. fetch_path(w->prog, sizeof(w->prog), "prog", fetch_session, i);
  3121. }
  3122. dl_worker.pid = -1;
  3123. dl_worker.slot = FETCH_WORKERS;
  3124. fetch_path(dl_worker.req, sizeof(dl_worker.req), "req",
  3125. fetch_session, FETCH_WORKERS);
  3126. fetch_path(dl_worker.body, sizeof(dl_worker.body), "body",
  3127. fetch_session, FETCH_WORKERS);
  3128. fetch_path(dl_worker.meta, sizeof(dl_worker.meta), "meta",
  3129. fetch_session, FETCH_WORKERS);
  3130. fetch_path(dl_worker.done, sizeof(dl_worker.done), "done",
  3131. fetch_session, FETCH_WORKERS);
  3132. fetch_path(dl_worker.post, sizeof(dl_worker.post), "post",
  3133. fetch_session, FETCH_WORKERS);
  3134. fetch_path(dl_worker.px, sizeof(dl_worker.px), "px",
  3135. fetch_session, FETCH_WORKERS);
  3136. fetch_path(dl_worker.prog, sizeof(dl_worker.prog), "prog",
  3137. fetch_session, FETCH_WORKERS);
  3138. }
  3139. static void fetch_worker_stop(struct fetch_worker *w)
  3140. {
  3141. int i;
  3142. /* An abandoned image job leaves its node loadable again. */
  3143. if (w->busy && w->image_job && w->node < doc.nnode) {
  3144. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  3145. doc.nodes[w->node].bg_img_index = -1;
  3146. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  3147. doc.nodes[w->node].img_index = -1;
  3148. }
  3149. if (w->pid > 0) {
  3150. u_kill((unsigned int)w->pid);
  3151. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  3152. u_sleep_ms(5);
  3153. /* Let the reaper close the socket before we reuse the slot. */
  3154. u_sleep_ms(10);
  3155. }
  3156. w->pid = -1;
  3157. w->busy = 0;
  3158. w->ready = 0;
  3159. w->image_job = 0;
  3160. if (w->req[0]) {
  3161. u_syscall1(SYS_UNLINK, (int)w->done);
  3162. u_syscall1(SYS_UNLINK, (int)w->meta);
  3163. u_syscall1(SYS_UNLINK, (int)w->body);
  3164. u_syscall1(SYS_UNLINK, (int)w->post);
  3165. u_syscall1(SYS_UNLINK, (int)w->req);
  3166. u_syscall1(SYS_UNLINK, (int)w->prog);
  3167. }
  3168. }
  3169. static void fetch_workers_stop_all(void)
  3170. {
  3171. int i;
  3172. for (i = 0; i < FETCH_WORKERS; i++)
  3173. fetch_worker_stop(&fetch_workers[i]);
  3174. }
  3175. /* Abandon the transfers of the current page but keep idle helpers and their
  3176. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  3177. * because its response would otherwise land in a reused /share slot. */
  3178. static void fetch_workers_cancel_busy(void)
  3179. {
  3180. int i;
  3181. for (i = 0; i < FETCH_WORKERS; i++)
  3182. if (fetch_workers[i].busy)
  3183. fetch_worker_stop(&fetch_workers[i]);
  3184. }
  3185. static void fetch_workers_prepare_nav(const char *url)
  3186. {
  3187. int i;
  3188. (void)url;
  3189. for (i = 0; i < FETCH_WORKERS; i++) {
  3190. struct fetch_worker *w = &fetch_workers[i];
  3191. if (w->pid <= 0)
  3192. continue;
  3193. /* Only an in-flight transfer must be aborted. Idle helpers
  3194. * stay warm across origins: there are just FETCH_WORKERS of
  3195. * them, and uhttp_open drops the old connection when the
  3196. * next job is for another host. Killing and respawning all
  3197. * four on every navigation churned processes and sockets
  3198. * while images were still loading. */
  3199. if (w->busy)
  3200. fetch_worker_stop(w);
  3201. }
  3202. }
  3203. /* The browser is no longer the active window and no fetch is running: give
  3204. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  3205. static void fetch_workers_stop_if_unfocused(void)
  3206. {
  3207. int i;
  3208. fetch_tty_drain();
  3209. if (ui.focused || page_loading || preload_active)
  3210. return;
  3211. for (i = 0; i < FETCH_WORKERS; i++)
  3212. if (fetch_workers[i].pid > 0) {
  3213. fetch_workers_stop_all();
  3214. return;
  3215. }
  3216. }
  3217. /* The helpers (and this process, since u_tty_create() rebinds our own
  3218. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  3219. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  3220. * a dozen TLS connections every helper hung in its next log line, so the
  3221. * following cross-origin navigation sat at "Loading..." until it timed out.
  3222. * Drain and discard it from every wait/poll loop. */
  3223. static void fetch_tty_drain(void)
  3224. {
  3225. char sink[512];
  3226. int i;
  3227. if (fetch_tty <= 0)
  3228. return;
  3229. for (i = 0; i < 16; i++)
  3230. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  3231. break;
  3232. }
  3233. static int fetch_worker_start(struct fetch_worker *w, char *err,
  3234. unsigned int errcap)
  3235. {
  3236. char arg[40];
  3237. unsigned int n = 0;
  3238. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  3239. return 0;
  3240. w->pid = -1;
  3241. fetch_pool_init();
  3242. if (fetch_tty == -2) {
  3243. int t = u_tty_create();
  3244. fetch_tty = t > 0 ? t : 0;
  3245. }
  3246. s_append(arg, &n, "__serve ", sizeof(arg));
  3247. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  3248. s_append(arg, &n, " ", sizeof(arg));
  3249. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  3250. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  3251. if (w->pid <= 0) {
  3252. w->pid = -1;
  3253. s_copy(err, "cannot start network helper", errcap);
  3254. return -1;
  3255. }
  3256. return 0;
  3257. }
  3258. static struct fetch_worker *fetch_worker_alloc(void)
  3259. {
  3260. int i;
  3261. fetch_pool_init();
  3262. for (i = 0; i < FETCH_WORKERS; i++)
  3263. if (!fetch_workers[i].busy)
  3264. return &fetch_workers[i];
  3265. return 0;
  3266. }
  3267. /* A worker for a synchronous foreground fetch (the page, a module, a
  3268. * script's fetch()/XHR). When image prefetches hold every helper, the
  3269. * newest image job (least progress) is abandoned: fetch_worker_stop()
  3270. * re-arms its node, so a later scan loads it again. Failing instead made
  3271. * cloudron.io's catalogue XHR return status 0 while its icons loaded. */
  3272. static struct fetch_worker *fetch_worker_alloc_fg(void)
  3273. {
  3274. struct fetch_worker *w = fetch_worker_alloc(), *victim = 0;
  3275. int i;
  3276. if (w)
  3277. return w;
  3278. for (i = 0; i < FETCH_WORKERS; i++) {
  3279. struct fetch_worker *c = &fetch_workers[i];
  3280. if (c->busy && c->image_job &&
  3281. (!victim || (int)(c->seq - victim->seq) > 0))
  3282. victim = c;
  3283. }
  3284. if (victim)
  3285. fetch_worker_stop(victim);
  3286. return victim;
  3287. }
  3288. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3289. unsigned int cap, const char *method,
  3290. const char *ctype, const char *post,
  3291. unsigned int post_len, unsigned int node,
  3292. int bg, unsigned int dec_w,
  3293. unsigned int dec_h, int download,
  3294. char *err, unsigned int errcap);
  3295. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  3296. unsigned int cap, const char *post,
  3297. unsigned int post_len, unsigned int node,
  3298. int bg, char *err, unsigned int errcap)
  3299. {
  3300. /* A body pointer with no bytes is still a POST: the classic request
  3301. * line would turn it into a GET. */
  3302. if (post && !post_len)
  3303. return fetch_worker_submit_req(w, url, cap, "POST",
  3304. "application/x-www-form-urlencoded", post, 0, node,
  3305. bg, 0, 0, 0, err, errcap);
  3306. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  3307. node, bg, 0, 0, 0, err, errcap);
  3308. }
  3309. /* Image job: ask the helper to decode at these display bounds as well. */
  3310. static int fetch_worker_submit_image(struct fetch_worker *w, const char *url,
  3311. unsigned int cap, unsigned int node,
  3312. int bg, unsigned int dec_w,
  3313. unsigned int dec_h, char *err,
  3314. unsigned int errcap)
  3315. {
  3316. return fetch_worker_submit_req(w, url, cap, 0, 0, 0, 0, node, bg,
  3317. dec_w, dec_h, 0, err, errcap);
  3318. }
  3319. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  3320. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  3321. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3322. unsigned int cap, const char *method,
  3323. const char *ctype, const char *post,
  3324. unsigned int post_len, unsigned int node,
  3325. int bg, unsigned int dec_w,
  3326. unsigned int dec_h, int download,
  3327. char *err, unsigned int errcap)
  3328. {
  3329. static char req[BR_URL_MAX + 256];
  3330. unsigned int n = 0;
  3331. fetch_seq++;
  3332. if (!fetch_seq)
  3333. fetch_seq = 1;
  3334. w->seq = fetch_seq;
  3335. w->ready = 0;
  3336. w->image_job = 0;
  3337. w->retried = 0;
  3338. w->m.error = 0;
  3339. w->node = node;
  3340. w->bg = bg;
  3341. w->dec_w = dec_w;
  3342. w->dec_h = dec_h;
  3343. w->dec_retried = 0;
  3344. s_copy(w->url, url, sizeof(w->url));
  3345. s_append_dec(req, &n, w->seq, sizeof(req));
  3346. s_append(req, &n, " ", sizeof(req));
  3347. s_append_dec(req, &n, cap, sizeof(req));
  3348. s_append(req, &n, " ", sizeof(req));
  3349. if (dec_w || dec_h) {
  3350. s_append(req, &n, "D ", sizeof(req));
  3351. s_append_dec(req, &n, dec_w, sizeof(req));
  3352. s_append(req, &n, " ", sizeof(req));
  3353. s_append_dec(req, &n, dec_h, sizeof(req));
  3354. s_append(req, &n, " ", sizeof(req));
  3355. } else if (method) {
  3356. unsigned int k;
  3357. s_append(req, &n, "X ", sizeof(req));
  3358. s_append(req, &n, method, sizeof(req));
  3359. s_append(req, &n, " ", sizeof(req));
  3360. s_append_dec(req, &n, post_len, sizeof(req));
  3361. s_append(req, &n, " ", sizeof(req));
  3362. if (!ctype || !ctype[0])
  3363. s_append(req, &n, "-", sizeof(req));
  3364. /* One token on the request line: drop the spaces
  3365. * ("application/json; charset=utf-8" stays valid). */
  3366. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  3367. if (ctype[k] != ' ')
  3368. req[n++] = ctype[k];
  3369. req[n] = '\0';
  3370. s_append(req, &n, " ", sizeof(req));
  3371. } else if (post_len) {
  3372. s_append(req, &n, "POST ", sizeof(req));
  3373. s_append_dec(req, &n, post_len, sizeof(req));
  3374. s_append(req, &n, " ", sizeof(req));
  3375. }
  3376. if (download)
  3377. s_append(req, &n, "DL ", sizeof(req));
  3378. s_append(req, &n, url, sizeof(req));
  3379. s_append(req, &n, "\n", sizeof(req));
  3380. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  3381. (int)post, (int)post_len) < 0) {
  3382. s_copy(err, "cannot queue form body", errcap);
  3383. return -1;
  3384. }
  3385. u_syscall1(SYS_UNLINK, (int)w->done);
  3386. u_syscall1(SYS_UNLINK, (int)w->meta);
  3387. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  3388. s_copy(err, "cannot queue network request", errcap);
  3389. return -1;
  3390. }
  3391. if (fetch_worker_start(w, err, errcap) != 0)
  3392. return -1;
  3393. w->busy = 1;
  3394. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  3395. return 0;
  3396. }
  3397. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  3398. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  3399. unsigned int errcap)
  3400. {
  3401. static char meta[BR_URL_MAX + 1024];
  3402. char *p;
  3403. int rn, mseq;
  3404. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  3405. (int)(sizeof(meta) - 1));
  3406. if (rn <= 0) {
  3407. s_copy(err, "network helper failed", errcap);
  3408. return -1;
  3409. }
  3410. meta[rn] = '\0';
  3411. p = meta;
  3412. mseq = (int)meta_uint(&p);
  3413. if (mseq != (int)w->seq) {
  3414. s_copy(err, "stale network response", errcap);
  3415. return -1;
  3416. }
  3417. w->m.status = (int)meta_uint(&p);
  3418. w->m.error = (int)meta_uint(&p);
  3419. w->m.trunc = (int)meta_uint(&p);
  3420. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  3421. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  3422. meta_str(&p, w->m.final, sizeof(w->m.final));
  3423. w->m.len = meta_uint(&p);
  3424. w->m.open_ms = 0;
  3425. w->m.first_ms = 0;
  3426. w->m.total_ms = 0;
  3427. if (*p) {
  3428. w->m.open_ms = meta_uint(&p);
  3429. w->m.first_ms = meta_uint(&p);
  3430. w->m.total_ms = meta_uint(&p);
  3431. }
  3432. w->m.dw = w->m.dh = w->m.nw = w->m.nh = 0;
  3433. w->m.alpha = w->m.px_len = w->m.dec_ms = 0;
  3434. w->m.dec_err = 0;
  3435. if (*p) {
  3436. w->m.dw = meta_uint(&p);
  3437. w->m.dh = meta_uint(&p);
  3438. w->m.nw = meta_uint(&p);
  3439. w->m.nh = meta_uint(&p);
  3440. w->m.alpha = meta_uint(&p);
  3441. w->m.px_len = meta_uint(&p);
  3442. w->m.dec_err = (int)meta_uint(&p);
  3443. w->m.dec_ms = meta_uint(&p);
  3444. }
  3445. if (w->m.error) {
  3446. s_copy(err, uhttp_error_string(w->m.error), errcap);
  3447. return -1;
  3448. }
  3449. w->ready = 1;
  3450. return 0;
  3451. }
  3452. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  3453. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  3454. unsigned int errcap)
  3455. {
  3456. static char done[24];
  3457. char *p;
  3458. int rn, mseq;
  3459. fetch_tty_drain();
  3460. if (!w->busy)
  3461. return -1;
  3462. if (w->ready)
  3463. return 1;
  3464. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  3465. (int)(sizeof(done) - 1));
  3466. if (rn > 0) {
  3467. done[rn] = '\0';
  3468. p = done;
  3469. mseq = (int)meta_uint(&p);
  3470. if (mseq == (int)w->seq) {
  3471. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  3472. fetch_worker_stop(w);
  3473. return -1;
  3474. }
  3475. return 1;
  3476. }
  3477. }
  3478. if (!u_alive((unsigned int)w->pid)) {
  3479. w->pid = -1;
  3480. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  3481. w->retried = 1;
  3482. return 0;
  3483. }
  3484. s_copy(err, "network helper stopped", errcap);
  3485. fetch_worker_stop(w);
  3486. return -1;
  3487. }
  3488. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  3489. s_copy(err, "network request timed out", errcap);
  3490. fetch_worker_stop(w);
  3491. return -1;
  3492. }
  3493. return 0;
  3494. }
  3495. /* Copy the completed body, inflating it if the server ignored our identity
  3496. * request. Mirrors the old fetch_remote body path. */
  3497. static int fetch_worker_read_body(struct fetch_worker *w,
  3498. unsigned char *plain,
  3499. unsigned int plaincap,
  3500. unsigned char *comp,
  3501. unsigned int compcap,
  3502. int *truncated, char *err,
  3503. unsigned int errcap)
  3504. {
  3505. int rv, zr, was_trunc;
  3506. if (contains_ci(w->m.encoding, "gzip") ||
  3507. contains_ci(w->m.encoding, "deflate")) {
  3508. unsigned int comp_len = 0, plen = 0;
  3509. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  3510. (int)compcap);
  3511. if (rv < 0) {
  3512. s_copy(err, "empty response", errcap);
  3513. return -1;
  3514. }
  3515. comp_len = (unsigned int)rv;
  3516. if (comp_len < w->m.len) {
  3517. s_copy(err, "compressed response is too large", errcap);
  3518. return -1;
  3519. }
  3520. if (contains_ci(w->m.encoding, "deflate"))
  3521. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3522. &plen, 0, &was_trunc);
  3523. else
  3524. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3525. &plen, 1, &was_trunc);
  3526. if (zr != 0) {
  3527. s_copy(err, "compressed response is corrupt", errcap);
  3528. return -1;
  3529. }
  3530. *truncated = w->m.trunc || was_trunc;
  3531. return (int)plen;
  3532. }
  3533. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  3534. if (rv < 0) {
  3535. s_copy(err, "empty response", errcap);
  3536. return -1;
  3537. }
  3538. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  3539. return rv;
  3540. }
  3541. static void fetch_worker_release(struct fetch_worker *w)
  3542. {
  3543. u_syscall1(SYS_UNLINK, (int)w->done);
  3544. u_syscall1(SYS_UNLINK, (int)w->meta);
  3545. u_syscall1(SYS_UNLINK, (int)w->body);
  3546. u_syscall1(SYS_UNLINK, (int)w->post);
  3547. u_syscall1(SYS_UNLINK, (int)w->px);
  3548. u_syscall1(SYS_UNLINK, (int)w->req);
  3549. u_syscall1(SYS_UNLINK, (int)w->prog);
  3550. w->busy = 0;
  3551. w->ready = 0;
  3552. w->image_job = 0;
  3553. w->dec_w = 0;
  3554. w->dec_h = 0;
  3555. w->dec_retried = 0;
  3556. }
  3557. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  3558. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  3559. unsigned int errcap)
  3560. {
  3561. for (;;) {
  3562. int rv;
  3563. if (!fetch_wait_passive)
  3564. worker_wait_ui();
  3565. if (cancel_fetch || pending_action) {
  3566. fetch_workers_cancel_busy();
  3567. return FETCH_ABORT;
  3568. }
  3569. rv = fetch_worker_poll(w, err, errcap);
  3570. if (rv != 0)
  3571. return rv == 1 ? 0 : -1;
  3572. u_sleep_ms(10);
  3573. }
  3574. }
  3575. static int fetch_remote(const char *url, unsigned int cap,
  3576. const char *post, unsigned int post_len,
  3577. unsigned char *plain, unsigned int plaincap,
  3578. unsigned char *comp, unsigned int compcap,
  3579. struct fetch_meta *m, int *truncated,
  3580. char *err, unsigned int errcap)
  3581. {
  3582. struct fetch_worker *w = fetch_worker_alloc_fg();
  3583. int rv;
  3584. fetch_last_error = 0;
  3585. if (!w) {
  3586. s_copy(err, "network busy", errcap);
  3587. return -1;
  3588. }
  3589. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  3590. err, errcap) != 0) {
  3591. fetch_worker_release(w);
  3592. return -1;
  3593. }
  3594. rv = fetch_worker_wait(w, err, errcap);
  3595. if (rv == FETCH_ABORT) {
  3596. fetch_worker_release(w);
  3597. return FETCH_ABORT;
  3598. }
  3599. if (rv != 0) {
  3600. fetch_last_error = w->m.error;
  3601. fetch_worker_release(w);
  3602. return -1;
  3603. }
  3604. *m = w->m;
  3605. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  3606. truncated, err, errcap);
  3607. fetch_worker_release(w);
  3608. if (rv >= 0 && (cancel_fetch || pending_action))
  3609. return FETCH_ABORT;
  3610. return rv;
  3611. }
  3612. static int fetch_worker_status(const struct fetch_worker *w)
  3613. {
  3614. return w->m.status;
  3615. }
  3616. /* ---- download manager ------------------------------------------------- */
  3617. static char dl_dir[DL_PATH_MAX];
  3618. static unsigned int dl_last_prog_ms;
  3619. /* 8.3-safe uppercase name: FAT's directory reader also accepts these. */
  3620. static void dl_clean(char *dst, unsigned int cap, const char *src,
  3621. unsigned int len)
  3622. {
  3623. unsigned int i, n = 0;
  3624. for (i = 0; i < len && n + 1 < cap; i++) {
  3625. unsigned char c = (unsigned char)src[i];
  3626. if (c >= 'a' && c <= 'z')
  3627. c = (unsigned char)(c - 'a' + 'A');
  3628. if (!((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
  3629. c == '-' || c == '_'))
  3630. c = '_';
  3631. dst[n++] = (char)c;
  3632. }
  3633. dst[n] = '\0';
  3634. }
  3635. static const char *dl_ctype_ext(const char *ctype, char out[4])
  3636. {
  3637. static const struct {
  3638. const char *needle;
  3639. const char *ext;
  3640. } map[] = {
  3641. { "html", "HTM" }, { "xml", "XML" }, { "json", "JSN" },
  3642. { "javascript", "JS" }, { "css", "CSS" },
  3643. { "jpeg", "JPG" }, { "png", "PNG" }, { "gif", "GIF" },
  3644. { "bmp", "BMP" }, { "webp", "WBP" }, { "svg", "SVG" },
  3645. { "tiff", "TIF" }, { "pdf", "PDF" }, { "zip", "ZIP" },
  3646. { "mpeg", "MPG" }, { "mp4", "MP4" }, { "audio", "MP3" },
  3647. { "plain", "TXT" }, { "text", "TXT" },
  3648. };
  3649. unsigned int i;
  3650. out[0] = '\0';
  3651. for (i = 0; ctype && i < sizeof(map) / sizeof(map[0]); i++)
  3652. if (contains_ci(ctype, map[i].needle)) {
  3653. s_copy(out, map[i].ext, 4);
  3654. break;
  3655. }
  3656. return out;
  3657. }
  3658. /* Derive BASE[.EXT] from the URL basename. A URL that ends in '/' (or a
  3659. * host-only URL) uses the host as the base and lets the MIME type supply
  3660. * the extension. */
  3661. static void dl_url_name(const char *url, const char *ctype, char *base,
  3662. unsigned int basecap, char *ext, unsigned int extcap)
  3663. {
  3664. const char *p = url, *host = 0, *end, *dot = 0, *slash;
  3665. char raw[96];
  3666. unsigned int n;
  3667. int from_host = 0;
  3668. slash = strstr(url, "://");
  3669. if (slash) {
  3670. host = slash + 3;
  3671. p = strrchr(host, '/');
  3672. if (!p) {
  3673. p = host;
  3674. from_host = 1;
  3675. } else {
  3676. p++;
  3677. }
  3678. } else {
  3679. slash = strrchr(url, '/');
  3680. if (slash)
  3681. p = slash + 1;
  3682. }
  3683. end = p;
  3684. while (*end && *end != '?' && *end != '#')
  3685. end++;
  3686. if (end == p && host) {
  3687. p = host;
  3688. end = p;
  3689. while (*end && *end != '/' && *end != '?' && *end != '#')
  3690. end++;
  3691. from_host = 1;
  3692. }
  3693. n = (unsigned int)(end - p);
  3694. if (n >= sizeof(raw))
  3695. n = sizeof(raw) - 1;
  3696. memcpy(raw, p, n);
  3697. raw[n] = '\0';
  3698. if (from_host) {
  3699. char *dot = strchr(raw, '.');
  3700. if (dot)
  3701. *dot = '\0';
  3702. n = (unsigned int)strlen(raw);
  3703. }
  3704. if (!from_host) {
  3705. dot = strrchr(raw, '.');
  3706. if (dot == raw)
  3707. dot = 0;
  3708. }
  3709. if (dot) {
  3710. dl_clean(ext, extcap, dot + 1,
  3711. (unsigned int)strlen(dot + 1));
  3712. if (!ext[0])
  3713. dot = 0;
  3714. }
  3715. if (!dot)
  3716. dl_ctype_ext(ctype, ext);
  3717. dl_clean(base, basecap, raw, dot ? (unsigned int)(dot - raw) : n);
  3718. if (!base[0])
  3719. s_copy(base, "DOWNLOAD", basecap);
  3720. }
  3721. static int dl_path_taken(const char *path)
  3722. {
  3723. struct sys_stat st;
  3724. return u_syscall2(SYS_FS_STAT, (int)path, (int)&st) == 0;
  3725. }
  3726. static int dl_prepare_dir(void)
  3727. {
  3728. struct sys_stat st;
  3729. const char *want;
  3730. if (u_syscall2(SYS_FS_STAT, (int)"/data", (int)&st) == 0 && st.is_dir)
  3731. want = DL_DIR_DATA;
  3732. else
  3733. want = DL_DIR_SHARE;
  3734. s_copy(dl_dir, want, sizeof(dl_dir));
  3735. if (u_syscall2(SYS_FS_STAT, (int)dl_dir, (int)&st) == 0 && st.is_dir)
  3736. return 0;
  3737. u_syscall1(SYS_MKDIR, (int)dl_dir);
  3738. if (u_syscall2(SYS_FS_STAT, (int)dl_dir, (int)&st) == 0 && st.is_dir)
  3739. return 0;
  3740. if (strcmp(want, DL_DIR_DATA) == 0) {
  3741. s_copy(dl_dir, DL_DIR_SHARE, sizeof(dl_dir));
  3742. if (u_syscall2(SYS_FS_STAT, (int)dl_dir, (int)&st) == 0 &&
  3743. st.is_dir)
  3744. return 0;
  3745. u_syscall1(SYS_MKDIR, (int)dl_dir);
  3746. if (u_syscall2(SYS_FS_STAT, (int)dl_dir, (int)&st) == 0 &&
  3747. st.is_dir)
  3748. return 0;
  3749. }
  3750. return -1;
  3751. }
  3752. /* Pick an unused 8.3 name in dl_dir; fills name and path. */
  3753. static int dl_make_path(const char *url, const char *ctype, char *name,
  3754. unsigned int namecap, char *path,
  3755. unsigned int pathcap)
  3756. {
  3757. char base[16], ext[8], cand[DL_NAME_MAX];
  3758. unsigned int k, n = 0;
  3759. dl_url_name(url, ctype, base, sizeof(base), ext, sizeof(ext));
  3760. if (s_len(base) > 8)
  3761. base[8] = '\0';
  3762. if (s_len(ext) > 3)
  3763. ext[3] = '\0';
  3764. for (k = 0; k < 100; k++) {
  3765. int keep = k < 10 ? 6 : 5;
  3766. if (k == 0) {
  3767. if (ext[0])
  3768. snprintf(cand, sizeof(cand), "%s.%s", base, ext);
  3769. else
  3770. s_copy(cand, base, sizeof(cand));
  3771. } else {
  3772. char b[9];
  3773. s_copy(b, base, sizeof(b));
  3774. if (s_len(b) > (unsigned int)keep)
  3775. b[keep] = '\0';
  3776. if (ext[0])
  3777. snprintf(cand, sizeof(cand), "%s~%u.%s", b,
  3778. k, ext);
  3779. else
  3780. snprintf(cand, sizeof(cand), "%s~%u", b, k);
  3781. }
  3782. n = 0;
  3783. s_append(path, &n, dl_dir, pathcap);
  3784. s_append(path, &n, "/", pathcap);
  3785. s_append(path, &n, cand, pathcap);
  3786. if (!dl_path_taken(path)) {
  3787. s_copy(name, cand, namecap);
  3788. return 0;
  3789. }
  3790. }
  3791. return -1;
  3792. }
  3793. static void dl_ensure_name(struct dl_ent *e)
  3794. {
  3795. char base[16], ext[8];
  3796. if (e->name[0] || !e->url[0])
  3797. return;
  3798. dl_url_name(e->url, "", base, sizeof(base), ext, sizeof(ext));
  3799. if (s_len(base) > 8)
  3800. base[8] = '\0';
  3801. if (s_len(ext) > 3)
  3802. ext[3] = '\0';
  3803. if (ext[0])
  3804. snprintf(e->name, sizeof(e->name), "%s.%s", base, ext);
  3805. else
  3806. s_copy(e->name, base, sizeof(e->name));
  3807. }
  3808. static void dl_write_list(void)
  3809. {
  3810. static char buf[6144];
  3811. unsigned int n = 0, last = 0;
  3812. int out, i;
  3813. s_append(buf, &n, "NBDL1\n", sizeof(buf));
  3814. for (out = 0; out < DL_MAX; out++) {
  3815. int best = -1;
  3816. for (i = 0; i < DL_MAX; i++) {
  3817. struct dl_ent *e = &dl_tab[i];
  3818. if (!e->used || e->stamp <= last ||
  3819. (e->state != DL_DONE && e->state != DL_FAILED))
  3820. continue;
  3821. if (best < 0 || e->stamp < dl_tab[best].stamp)
  3822. best = i;
  3823. }
  3824. if (best < 0)
  3825. break;
  3826. last = dl_tab[best].stamp;
  3827. s_append_dec(buf, &n, dl_tab[best].state, sizeof(buf));
  3828. s_append(buf, &n, "\n", sizeof(buf));
  3829. s_append_dec(buf, &n, dl_tab[best].size, sizeof(buf));
  3830. s_append(buf, &n, "\n", sizeof(buf));
  3831. s_append(buf, &n, dl_tab[best].name, sizeof(buf));
  3832. s_append(buf, &n, "\n", sizeof(buf));
  3833. s_append(buf, &n, dl_tab[best].path, sizeof(buf));
  3834. s_append(buf, &n, "\n", sizeof(buf));
  3835. }
  3836. u_syscall3(SYS_WRITE_FILE, (int)DL_SHARE_LIST, (int)buf, (int)n);
  3837. u_syscall3(SYS_WRITE_FILE, (int)DL_DATA_LIST, (int)buf, (int)n);
  3838. }
  3839. static void dl_load(void)
  3840. {
  3841. static char buf[6144];
  3842. char *p;
  3843. int rn, i = 0;
  3844. rn = u_syscall3(SYS_READ_FILE, (int)DL_SHARE_LIST, (int)buf,
  3845. (int)(sizeof(buf) - 1));
  3846. if (rn < 6 || memcmp(buf, "NBDL1\n", 6) != 0)
  3847. rn = u_syscall3(SYS_READ_FILE, (int)DL_DATA_LIST, (int)buf,
  3848. (int)(sizeof(buf) - 1));
  3849. if (rn < 6 || memcmp(buf, "NBDL1\n", 6) != 0)
  3850. return;
  3851. buf[rn] = '\0';
  3852. p = buf + 6;
  3853. while (i < DL_MAX && *p) {
  3854. unsigned int state = meta_uint(&p);
  3855. unsigned int size = meta_uint(&p);
  3856. char name[DL_NAME_MAX], path[DL_PATH_MAX];
  3857. meta_str(&p, name, sizeof(name));
  3858. meta_str(&p, path, sizeof(path));
  3859. if ((state != DL_DONE && state != DL_FAILED) || !name[0])
  3860. continue;
  3861. dl_tab[i].used = 1;
  3862. dl_tab[i].state = (unsigned char)state;
  3863. dl_tab[i].size = size;
  3864. dl_tab[i].got = size;
  3865. dl_tab[i].total = size;
  3866. dl_tab[i].stamp = dl_stamp++;
  3867. s_copy(dl_tab[i].name, name, sizeof(dl_tab[i].name));
  3868. s_copy(dl_tab[i].path, path, sizeof(dl_tab[i].path));
  3869. i++;
  3870. }
  3871. }
  3872. static struct dl_ent *dl_active_ent(void)
  3873. {
  3874. return dl_active >= 0 ? &dl_tab[dl_active] : 0;
  3875. }
  3876. static int dl_percent(void)
  3877. {
  3878. struct dl_ent *e = dl_active_ent();
  3879. if (!e)
  3880. return -1;
  3881. if (e->state == DL_SAVING || e->state == DL_DONE)
  3882. return 100;
  3883. if (!e->total)
  3884. return -1;
  3885. if (e->got >= e->total)
  3886. return 100;
  3887. return (int)((unsigned long long)e->got * 100 / e->total);
  3888. }
  3889. static int dl_history_count(void)
  3890. {
  3891. int i, n = 0;
  3892. for (i = 0; i < DL_MAX; i++)
  3893. if (dl_tab[i].used && (dl_tab[i].state == DL_DONE ||
  3894. dl_tab[i].state == DL_FAILED))
  3895. n++;
  3896. return n;
  3897. }
  3898. static void dl_start_next(void);
  3899. static void dl_fail(int idx, const char *why, int stop_helper)
  3900. {
  3901. struct dl_ent *e = &dl_tab[idx];
  3902. char msg[DL_ERR_MAX + 24];
  3903. unsigned int n = 0;
  3904. e->state = DL_FAILED;
  3905. s_copy(e->err, why && why[0] ? why : "download failed",
  3906. sizeof(e->err));
  3907. dl_ensure_name(e);
  3908. e->got = 0;
  3909. if (stop_helper)
  3910. fetch_worker_stop(&dl_worker);
  3911. dl_active = -1;
  3912. s_append(msg, &n, "Download failed: ", sizeof(msg));
  3913. s_append(msg, &n, e->err, sizeof(msg));
  3914. set_status(msg, 1, 6000);
  3915. if (!dl_panel_open)
  3916. dl_unseen++;
  3917. dl_write_list();
  3918. ngui_invalidate(&ui);
  3919. dl_start_next();
  3920. }
  3921. static int dl_commit(int idx, const unsigned char *data, unsigned int len,
  3922. const char *ctype, int release_helper)
  3923. {
  3924. struct dl_ent *e = &dl_tab[idx];
  3925. char name[DL_NAME_MAX], path[DL_PATH_MAX];
  3926. int wr;
  3927. if (dl_prepare_dir() != 0) {
  3928. dl_fail(idx, "no writable download folder", release_helper);
  3929. return -1;
  3930. }
  3931. if (dl_make_path(e->url, ctype, name, sizeof(name), path,
  3932. sizeof(path)) != 0) {
  3933. dl_fail(idx, "cannot choose a file name", release_helper);
  3934. return -1;
  3935. }
  3936. if (release_helper) {
  3937. /* Keep the helper process, but drop its request files. */
  3938. fetch_worker_release(&dl_worker);
  3939. }
  3940. wr = u_syscall3(SYS_WRITE_FILE, (int)path, (int)data, (int)len);
  3941. if (wr < 0) {
  3942. dl_fail(idx, "cannot write the file", 0);
  3943. return -1;
  3944. }
  3945. e->state = DL_DONE;
  3946. e->size = len;
  3947. e->got = len;
  3948. e->total = len;
  3949. s_copy(e->name, name, sizeof(e->name));
  3950. s_copy(e->path, path, sizeof(e->path));
  3951. dl_active = -1;
  3952. if (!dl_panel_open)
  3953. dl_unseen++;
  3954. dl_write_list();
  3955. {
  3956. char msg[DL_PATH_MAX + 16];
  3957. unsigned int n = 0;
  3958. s_append(msg, &n, "Saved ", sizeof(msg));
  3959. s_append(msg, &n, e->path, sizeof(msg));
  3960. set_status(msg, 0, 5000);
  3961. }
  3962. ngui_invalidate(&ui);
  3963. dl_start_next();
  3964. return 0;
  3965. }
  3966. static void dl_local_read(int idx)
  3967. {
  3968. struct dl_ent *e = &dl_tab[idx];
  3969. struct sys_stat st;
  3970. unsigned char *buf;
  3971. int rn;
  3972. if (u_syscall2(SYS_FS_STAT, (int)e->url, (int)&st) != 0 || st.is_dir) {
  3973. dl_fail(idx, "not a readable file", 0);
  3974. return;
  3975. }
  3976. if (st.size > DL_FILE_MAX) {
  3977. dl_fail(idx, "file is over the 4 MB limit", 0);
  3978. return;
  3979. }
  3980. buf = (unsigned char *)malloc(st.size + 512);
  3981. if (!buf) {
  3982. dl_fail(idx, "out of memory", 0);
  3983. return;
  3984. }
  3985. rn = u_syscall3(SYS_READ_FILE, (int)e->url, (int)buf,
  3986. (int)(st.size ? st.size : 1));
  3987. if (rn < 0) {
  3988. free(buf);
  3989. dl_fail(idx, "cannot read the file", 0);
  3990. return;
  3991. }
  3992. e->got = e->total = (unsigned int)rn;
  3993. e->state = DL_SAVING;
  3994. dl_commit(idx, buf, (unsigned int)rn, "", 0);
  3995. free(buf);
  3996. }
  3997. static void dl_remote_read(int idx)
  3998. {
  3999. struct dl_ent *e = &dl_tab[idx];
  4000. unsigned char *buf;
  4001. int rn;
  4002. if (dl_worker.m.status < 200 || dl_worker.m.status >= 300) {
  4003. char why[32];
  4004. unsigned int n = 0;
  4005. s_append(why, &n, "HTTP ", sizeof(why));
  4006. s_append_dec(why, &n, (unsigned int)dl_worker.m.status,
  4007. sizeof(why));
  4008. dl_fail(idx, why, 1);
  4009. return;
  4010. }
  4011. if (dl_worker.m.trunc) {
  4012. dl_fail(idx, "file is over the 4 MB limit", 1);
  4013. return;
  4014. }
  4015. e->got = e->total = dl_worker.m.len;
  4016. e->state = DL_SAVING;
  4017. if (dl_worker.m.len > DL_FILE_MAX) {
  4018. dl_fail(idx, "file is over the 4 MB limit", 1);
  4019. return;
  4020. }
  4021. buf = (unsigned char *)malloc(dl_worker.m.len + 512);
  4022. if (!buf) {
  4023. dl_fail(idx, "out of memory", 1);
  4024. return;
  4025. }
  4026. rn = dl_worker.m.len ? u_syscall3(SYS_READ_FILE,
  4027. (int)dl_worker.body, (int)buf,
  4028. (int)dl_worker.m.len) : 0;
  4029. if (rn < 0 || (unsigned int)rn < dl_worker.m.len) {
  4030. free(buf);
  4031. dl_fail(idx, "cannot read the response body", 1);
  4032. return;
  4033. }
  4034. dl_commit(idx, buf, dl_worker.m.len, dl_worker.m.ctype, 1);
  4035. free(buf);
  4036. }
  4037. static void dl_read_progress(void)
  4038. {
  4039. static char buf[96];
  4040. char *p;
  4041. unsigned int seq;
  4042. struct dl_ent *e = dl_active_ent();
  4043. int rn;
  4044. if (!e || e->url[0] == '/')
  4045. return;
  4046. rn = u_syscall3(SYS_READ_FILE, (int)dl_worker.prog, (int)buf,
  4047. (int)(sizeof(buf) - 1));
  4048. if (rn <= 0)
  4049. return;
  4050. buf[rn] = '\0';
  4051. p = buf;
  4052. seq = meta_uint(&p);
  4053. if (seq != dl_worker.seq)
  4054. return;
  4055. e->got = meta_uint(&p);
  4056. e->total = meta_uint(&p);
  4057. ngui_invalidate(&ui);
  4058. }
  4059. static void dl_start_next(void)
  4060. {
  4061. int i, pick = -1;
  4062. struct dl_ent *e;
  4063. char err[64];
  4064. if (dl_active >= 0)
  4065. return;
  4066. for (i = 0; i < DL_MAX; i++) {
  4067. if (!dl_tab[i].used || dl_tab[i].state != DL_QUEUED)
  4068. continue;
  4069. if (pick < 0 || dl_tab[i].stamp < dl_tab[pick].stamp)
  4070. pick = i;
  4071. }
  4072. if (pick < 0)
  4073. return;
  4074. dl_active = pick;
  4075. e = &dl_tab[pick];
  4076. e->state = DL_RUNNING;
  4077. e->err[0] = '\0';
  4078. e->got = e->total = 0;
  4079. dl_last_prog_ms = u_ticks_ms();
  4080. ngui_invalidate(&ui);
  4081. if (e->url[0] == '/')
  4082. return; /* dl_poll reads local files */
  4083. err[0] = '\0';
  4084. if (fetch_worker_submit_req(&dl_worker, e->url, DL_FILE_MAX,
  4085. 0, 0, 0, 0, 0, 0, 0, 0, 1,
  4086. err, sizeof(err)) != 0) {
  4087. dl_fail(pick, err[0] ? err : "cannot start the download", 1);
  4088. }
  4089. }
  4090. static void dl_poll(void)
  4091. {
  4092. struct dl_ent *e;
  4093. unsigned int now;
  4094. char err[64];
  4095. int rv;
  4096. if (dl_active < 0) {
  4097. dl_start_next();
  4098. return;
  4099. }
  4100. e = &dl_tab[dl_active];
  4101. if (e->url[0] == '/') {
  4102. dl_local_read(dl_active);
  4103. return;
  4104. }
  4105. now = u_ticks_ms();
  4106. if ((unsigned int)(now - dl_last_prog_ms) >= 100) {
  4107. dl_last_prog_ms = now;
  4108. dl_read_progress();
  4109. }
  4110. err[0] = '\0';
  4111. rv = fetch_worker_poll(&dl_worker, err, sizeof(err));
  4112. if (rv == 0)
  4113. return;
  4114. if (rv < 0) {
  4115. dl_fail(dl_active, err[0] ? err : "download failed", 1);
  4116. return;
  4117. }
  4118. dl_remote_read(dl_active);
  4119. }
  4120. static int dl_queue(const char *url)
  4121. {
  4122. int i, pick = -1;
  4123. struct dl_ent *e;
  4124. if (!url || !url[0] || s_len(url) >= DL_URL_MAX) {
  4125. set_status("Cannot download: bad URL", 1, 4000);
  4126. return -1;
  4127. }
  4128. if (!is_http(url) && url[0] != '/') {
  4129. set_status("Cannot download this URL", 1, 4000);
  4130. return -1;
  4131. }
  4132. for (i = 0; i < DL_MAX; i++)
  4133. if (!dl_tab[i].used) {
  4134. pick = i;
  4135. break;
  4136. }
  4137. if (pick < 0) {
  4138. for (i = 0; i < DL_MAX; i++)
  4139. if (dl_tab[i].state == DL_DONE ||
  4140. dl_tab[i].state == DL_FAILED) {
  4141. if (pick < 0 ||
  4142. dl_tab[i].stamp < dl_tab[pick].stamp)
  4143. pick = i;
  4144. }
  4145. if (pick < 0) {
  4146. set_status("Download list is full", 1, 4000);
  4147. return -1;
  4148. }
  4149. }
  4150. e = &dl_tab[pick];
  4151. memset(e, 0, sizeof(*e));
  4152. e->used = 1;
  4153. e->state = DL_QUEUED;
  4154. e->stamp = dl_stamp++;
  4155. s_copy(e->url, url, sizeof(e->url));
  4156. dl_ensure_name(e);
  4157. set_status("Download started", 0, 3000);
  4158. ngui_invalidate(&ui);
  4159. dl_start_next();
  4160. return 0;
  4161. }
  4162. static void dl_clear_history(void)
  4163. {
  4164. int i;
  4165. for (i = 0; i < DL_MAX; i++)
  4166. if (dl_tab[i].used && (dl_tab[i].state == DL_DONE ||
  4167. dl_tab[i].state == DL_FAILED))
  4168. dl_tab[i].used = 0;
  4169. dl_unseen = 0;
  4170. dl_write_list();
  4171. ngui_invalidate(&ui);
  4172. }
  4173. /* fetch()/XHR through a helper: one request, the status and body come back
  4174. * whatever the HTTP status (a 401 is an answer, not a network error). */
  4175. static int js_worker_http(const char *method, const char *url,
  4176. const char *ctype, const char *body,
  4177. unsigned int body_len, struct js_http_resp *r,
  4178. char *err, int errcap)
  4179. {
  4180. struct fetch_worker *w = fetch_worker_alloc_fg();
  4181. unsigned char *plain;
  4182. int rv, tr = 0;
  4183. if (!w) {
  4184. s_copy(err, "network busy", (unsigned int)errcap);
  4185. return -1;
  4186. }
  4187. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  4188. body_len, 0, 0, 0, 0, 0, err,
  4189. (unsigned int)errcap) != 0) {
  4190. fetch_worker_release(w);
  4191. return -1;
  4192. }
  4193. fetch_wait_passive++;
  4194. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  4195. fetch_wait_passive--;
  4196. if (rv != 0) {
  4197. if (rv == FETCH_ABORT)
  4198. s_copy(err, "page is navigating", (unsigned int)errcap);
  4199. fetch_worker_release(w);
  4200. return -1;
  4201. }
  4202. r->status = w->m.status;
  4203. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  4204. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  4205. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  4206. if (!plain) {
  4207. fetch_worker_release(w);
  4208. s_copy(err, "out of memory", (unsigned int)errcap);
  4209. return -1;
  4210. }
  4211. if (w->m.len == 0) {
  4212. rv = 0; /* 204, an empty 200: no body file */
  4213. } else {
  4214. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  4215. image_io_buf, BR_PAGE_COMP_MAX,
  4216. &tr, err, (unsigned int)errcap);
  4217. }
  4218. fetch_worker_release(w);
  4219. if (rv < 0) {
  4220. free(plain);
  4221. return -1;
  4222. }
  4223. plain[rv] = '\0';
  4224. r->body = (char *)plain;
  4225. r->len = (unsigned int)rv;
  4226. return 0;
  4227. }
  4228. /* ---- HTTP / file fetch ---- */
  4229. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  4230. unsigned int *outlen, int *is_local, char *ctype,
  4231. unsigned int ctcap, char *final, unsigned int finalcap,
  4232. char *err, unsigned int errcap, int *truncated,
  4233. const char *post, unsigned int post_len)
  4234. {
  4235. unsigned char *buf;
  4236. unsigned int len;
  4237. int tr = 0;
  4238. int rv;
  4239. *out = 0;
  4240. *outlen = 0;
  4241. *truncated = 0;
  4242. if (final && finalcap)
  4243. final[0] = '\0';
  4244. if (ctype && ctcap)
  4245. ctype[0] = '\0';
  4246. if (url[0] == '/') {
  4247. char pathbuf[BR_URL_MAX];
  4248. const char *open_url = url;
  4249. unsigned int i = 0;
  4250. /* A local form GET keeps ?query in the address bar but the
  4251. * file lookup uses the path alone, like a real browser. */
  4252. while (url[i] && url[i] != '?' && url[i] != '#')
  4253. i++;
  4254. if (url[i]) {
  4255. s_copy(pathbuf, url, i + 1);
  4256. open_url = pathbuf;
  4257. }
  4258. buf = (unsigned char *)malloc(cap);
  4259. if (!buf) {
  4260. s_copy(err, "out of memory", errcap);
  4261. return -1;
  4262. }
  4263. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  4264. if (rv < 0) {
  4265. free(buf);
  4266. s_copy(err, "file not found", errcap);
  4267. return -1;
  4268. }
  4269. *out = buf;
  4270. *outlen = (unsigned int)rv;
  4271. *is_local = 1;
  4272. if (ctype)
  4273. s_copy(ctype, "text/html", ctcap);
  4274. if (final)
  4275. s_copy(final, url, finalcap);
  4276. if ((unsigned int)rv == cap)
  4277. *truncated = 1;
  4278. return 0;
  4279. }
  4280. buf = (unsigned char *)malloc(cap);
  4281. if (!buf) {
  4282. s_copy(err, "out of memory", errcap);
  4283. return -1;
  4284. }
  4285. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  4286. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  4287. if (rv == FETCH_ABORT) {
  4288. free(buf);
  4289. return FETCH_ABORT;
  4290. }
  4291. if (rv < 0) {
  4292. free(buf);
  4293. return -1;
  4294. }
  4295. len = (unsigned int)rv;
  4296. if (len == 0) {
  4297. free(buf);
  4298. s_copy(err, "empty response", errcap);
  4299. return -1;
  4300. }
  4301. if (ctype)
  4302. s_copy(ctype, fetch_meta.ctype, ctcap);
  4303. if (final && fetch_meta.final[0])
  4304. s_copy(final, fetch_meta.final, finalcap);
  4305. *is_local = 0;
  4306. *out = buf;
  4307. *outlen = len;
  4308. *truncated = tr;
  4309. return 0;
  4310. }
  4311. static unsigned int css_cache_hash(const char *s);
  4312. /* Remote fonts are cached under /share for the current boot like the
  4313. * stylesheets, as the raw response (a WOFF stays compressed). */
  4314. static int font_cache_count;
  4315. static void font_cache_path(const char *url, char *out, unsigned int cap)
  4316. {
  4317. unsigned int n = 0;
  4318. s_append(out, &n, "/share/" FONT_CACHE_PREFIX, cap);
  4319. s_append_dec(out, &n, css_cache_hash(url), cap);
  4320. }
  4321. static void font_cache_init(void)
  4322. {
  4323. struct sys_dirent d;
  4324. int i;
  4325. font_cache_count = 0;
  4326. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4327. (int)&d) == 1; i++)
  4328. if (starts_with(d.name, FONT_CACHE_PREFIX))
  4329. font_cache_count++;
  4330. }
  4331. /* Read one font file (local path, boot cache or network) into a fresh
  4332. * malloc'ed buffer. Returns its length, or -1. */
  4333. static int font_fetch(const char *abs, unsigned char **out)
  4334. {
  4335. unsigned char *buf;
  4336. char path[96];
  4337. int rv;
  4338. *out = 0;
  4339. buf = (unsigned char *)malloc(UFONT_MAX_FILE + 512u);
  4340. if (!buf)
  4341. return -1;
  4342. if (abs[0] == '/') {
  4343. struct sys_stat st;
  4344. /* FAT reads may write past the length: the 512 bytes of
  4345. * slack above cover the final partial sector. */
  4346. if (u_stat(abs, &st) != 0 || st.is_dir || st.size == 0 ||
  4347. st.size > UFONT_MAX_FILE) {
  4348. free(buf);
  4349. return -1;
  4350. }
  4351. rv = u_syscall3(SYS_READ_FILE, (int)abs, (int)buf,
  4352. (int)st.size);
  4353. if (rv != (int)st.size) {
  4354. free(buf);
  4355. return -1;
  4356. }
  4357. *out = buf;
  4358. return rv;
  4359. }
  4360. if (!is_http(abs)) {
  4361. free(buf);
  4362. return -1;
  4363. }
  4364. font_cache_path(abs, path, sizeof(path));
  4365. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)buf,
  4366. (int)UFONT_MAX_FILE);
  4367. if (rv > 0 && (unsigned int)rv < UFONT_MAX_FILE) {
  4368. *out = buf;
  4369. return rv;
  4370. }
  4371. {
  4372. char err[64];
  4373. int tr = 0;
  4374. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  4375. UFONT_MAX_FILE, image_io_buf,
  4376. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err,
  4377. sizeof(err));
  4378. /* An error page is not a font: never parse or cache it. */
  4379. if (rv > 0 && !tr && fetch_meta.status >= 300) {
  4380. snprintf(err, sizeof(err), "HTTP %d", fetch_meta.status);
  4381. rv = 0;
  4382. }
  4383. if (rv <= 0 || tr) {
  4384. u_puts("[font] failed: ");
  4385. u_puts(abs);
  4386. u_puts(rv <= 0 ? " " : " truncated ");
  4387. u_puts(rv <= 0 ? err : "");
  4388. u_putc('\n');
  4389. free(buf);
  4390. return -1;
  4391. }
  4392. }
  4393. if (font_cache_count < FONT_CACHE_MAX &&
  4394. u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, rv) >= 0)
  4395. font_cache_count++;
  4396. *out = buf;
  4397. return rv;
  4398. }
  4399. /* Open one @font-face entry: fetch, unwrap WOFF, parse into the ufont
  4400. * arena. A WOFF2 or CFF (OTTO) file is reported and left unloaded. */
  4401. static struct ufont_face *font_open_entry(int id)
  4402. {
  4403. const char *url = br_font_face_url(id);
  4404. const char *base = br_font_face_base(id);
  4405. char abs[BR_URL_MAX];
  4406. unsigned char *buf, *sfnt;
  4407. unsigned int slen = 0;
  4408. struct ufont_face *f = 0;
  4409. const char *why = 0;
  4410. int n;
  4411. if (!url || !url[0] ||
  4412. resolve_link(base && base[0] ? base : page_url, url, abs,
  4413. sizeof(abs)) != 0)
  4414. return 0;
  4415. n = font_fetch(abs, &buf);
  4416. if (n <= 0)
  4417. return 0;
  4418. sfnt = buf;
  4419. slen = (unsigned int)n;
  4420. if (ufont_is_woff2(buf, slen)) {
  4421. why = "WOFF2 not supported";
  4422. } else if (ufont_is_woff(buf, slen)) {
  4423. sfnt = ufont_woff_decode(buf, slen, &slen);
  4424. if (!sfnt)
  4425. why = "bad WOFF";
  4426. }
  4427. if (!why) {
  4428. f = ufont_face_open_mem(sfnt, slen);
  4429. if (!f)
  4430. why = (slen >= 4 && sfnt[0] == 'O' && sfnt[1] == 'T' &&
  4431. sfnt[2] == 'T' && sfnt[3] == 'O') ?
  4432. "CFF outlines not supported" :
  4433. "not a TrueType font or arena full";
  4434. }
  4435. if (sfnt && sfnt != buf)
  4436. free(sfnt);
  4437. free(buf);
  4438. u_puts(f ? "[font] loaded " : "[font] skipped ");
  4439. u_puts(br_font_face_family(id));
  4440. u_puts(": ");
  4441. u_puts(abs);
  4442. if (why) {
  4443. u_puts(" (");
  4444. u_puts(why);
  4445. u_putc(')');
  4446. }
  4447. u_putc('\n');
  4448. return f;
  4449. }
  4450. /* Distance of a face from the requested weight: 0 inside its range. A
  4451. * bold request prefers heavier faces and a normal one lighter faces, as
  4452. * the CSS font-matching steps do. */
  4453. static unsigned int font_weight_dist(const struct br_font_face_info *fi,
  4454. unsigned int want)
  4455. {
  4456. if (want >= fi->wmin && want <= fi->wmax)
  4457. return 0;
  4458. if (want > fi->wmax)
  4459. return (want - fi->wmax) * 2u + (want >= 500 ? 1u : 0u);
  4460. return (fi->wmin - want) * 2u + (want < 500 ? 1u : 0u);
  4461. }
  4462. /* Load the @font-face entries a font-family declaration named: per family
  4463. * the regular face first, then bold, italic and the rest, so a full arena
  4464. * drops the least common variants. Then precompute, for every family and
  4465. * (bold, italic) combination, the loaded face CSS font matching picks;
  4466. * layout reads only that table. A family with no loaded face keeps
  4467. * font_pick 0, and its text uses the built-in set. */
  4468. static void load_font_faces(void)
  4469. {
  4470. int n = br_font_face_count(), pass, id;
  4471. memset(font_faces, 0, sizeof(font_faces));
  4472. memset(font_pick, 0, sizeof(font_pick));
  4473. if (n > BR_MAX_FACES)
  4474. n = BR_MAX_FACES;
  4475. for (pass = 0; pass < 4; pass++) {
  4476. for (id = 1; id <= n; id++) {
  4477. struct br_font_face_info fi;
  4478. int cls;
  4479. if (br_font_face_info(id, &fi) != 0 || !fi.used)
  4480. continue;
  4481. if (!fi.italic && fi.wmin <= 400 && fi.wmax >= 400)
  4482. cls = 0;
  4483. else if (!fi.italic && fi.wmin <= 700 &&
  4484. fi.wmax >= 700)
  4485. cls = 1;
  4486. else if (fi.italic && fi.wmin <= 400 &&
  4487. fi.wmax >= 400)
  4488. cls = 2;
  4489. else
  4490. cls = 3;
  4491. if (cls == pass)
  4492. font_faces[id - 1] = font_open_entry(id);
  4493. }
  4494. }
  4495. for (id = 1; id <= n; id++) {
  4496. struct br_font_face_info fam;
  4497. int combo;
  4498. if (br_font_face_info(id, &fam) != 0 || fam.family_id != id)
  4499. continue;
  4500. for (combo = 0; combo < 4; combo++) {
  4501. unsigned int want = (combo & 2) ? 700u : 400u;
  4502. int italic = combo & 1, k, best = 0;
  4503. unsigned int best_score = 0;
  4504. for (k = 1; k <= n; k++) {
  4505. struct br_font_face_info fi;
  4506. unsigned int score;
  4507. if (!font_faces[k - 1] ||
  4508. br_font_face_info(k, &fi) != 0 ||
  4509. fi.family_id != id)
  4510. continue;
  4511. score = font_weight_dist(&fi, want) +
  4512. ((fi.italic != 0) != (italic != 0) ?
  4513. 100000u : 0u);
  4514. if (!best || score < best_score) {
  4515. best = k;
  4516. best_score = score;
  4517. }
  4518. }
  4519. font_pick[id - 1][combo] = (unsigned char)best;
  4520. }
  4521. }
  4522. }
  4523. /* Remote scripts are cached under /share for the current boot, like the
  4524. * stylesheet cache, so reloads and later visits skip the network. */
  4525. static int script_cache_count;
  4526. static unsigned int script_cache_hash(const char *s)
  4527. {
  4528. unsigned int h = 2166136261u;
  4529. while (*s) {
  4530. h ^= (unsigned char)*s++;
  4531. h *= 16777619u;
  4532. }
  4533. return h;
  4534. }
  4535. static void script_cache_path(const char *url, char *out, unsigned int cap)
  4536. {
  4537. unsigned int n = 0;
  4538. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  4539. s_append_dec(out, &n, script_cache_hash(url), cap);
  4540. }
  4541. static void script_cache_clear(void)
  4542. {
  4543. struct sys_dirent d;
  4544. char path[96];
  4545. for (;;) {
  4546. int i, found = 0;
  4547. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4548. (int)&d) == 1; i++) {
  4549. unsigned int n = 0;
  4550. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  4551. continue;
  4552. s_append(path, &n, "/share/", sizeof(path));
  4553. s_append(path, &n, d.name, sizeof(path));
  4554. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  4555. return;
  4556. found = 1;
  4557. break;
  4558. }
  4559. if (!found)
  4560. break;
  4561. }
  4562. script_cache_count = 0;
  4563. }
  4564. static void script_cache_init(void)
  4565. {
  4566. struct sys_dirent d;
  4567. int i, count = 0;
  4568. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4569. (int)&d) == 1; i++)
  4570. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  4571. count++;
  4572. if (count >= SCRIPT_CACHE_MAX) {
  4573. script_cache_clear();
  4574. return;
  4575. }
  4576. script_cache_count = count;
  4577. }
  4578. static int script_cache_get(const char *url, unsigned char **out,
  4579. unsigned int *outlen)
  4580. {
  4581. char path[96];
  4582. struct sys_stat st;
  4583. unsigned char *buf;
  4584. int rn;
  4585. script_cache_path(url, path, sizeof(path));
  4586. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  4587. st.size >= SCRIPT_CACHE_FILE_MAX)
  4588. return 0;
  4589. buf = (unsigned char *)malloc(st.size + 1);
  4590. if (!buf)
  4591. return 0;
  4592. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  4593. if (rn != (int)st.size) {
  4594. free(buf);
  4595. return 0;
  4596. }
  4597. buf[st.size] = '\0';
  4598. *out = buf;
  4599. *outlen = st.size;
  4600. return 1;
  4601. }
  4602. static void script_cache_put(const char *url, const unsigned char *data,
  4603. unsigned int len)
  4604. {
  4605. char path[96];
  4606. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  4607. len >= SCRIPT_CACHE_FILE_MAX)
  4608. return;
  4609. script_cache_path(url, path, sizeof(path));
  4610. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  4611. (int)len) >= 0)
  4612. script_cache_count++;
  4613. }
  4614. static int script_cache_has(const char *url)
  4615. {
  4616. char path[96];
  4617. struct sys_stat st;
  4618. script_cache_path(url, path, sizeof(path));
  4619. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  4620. st.size < SCRIPT_CACHE_FILE_MAX;
  4621. }
  4622. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  4623. static int fetch_script_text(const char *url, unsigned char **out,
  4624. unsigned int *outlen, char *err,
  4625. unsigned int errcap)
  4626. {
  4627. unsigned char *buf;
  4628. unsigned int len;
  4629. int local, truncated = 0;
  4630. char ctype[64], final[BR_URL_MAX];
  4631. int rv;
  4632. *out = 0;
  4633. *outlen = 0;
  4634. if (url[0] != '/' && script_cache_get(url, out, outlen))
  4635. return 0;
  4636. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  4637. sizeof(ctype), final, sizeof(final), err, errcap,
  4638. &truncated, 0, 0);
  4639. if (rv != 0)
  4640. return rv;
  4641. if (truncated || len >= BR_SCRIPT_MAX) {
  4642. free(buf);
  4643. s_copy(err, "script is too large", errcap);
  4644. return -1;
  4645. }
  4646. buf[len] = '\0';
  4647. if (!local)
  4648. script_cache_put(url, buf, len);
  4649. *out = buf;
  4650. *outlen = len;
  4651. return 0;
  4652. }
  4653. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  4654. * the heap, so images must not allocate their file body from it as well. */
  4655. static int fetch_image(const char *url, unsigned int cap,
  4656. unsigned char **out, unsigned int *outlen,
  4657. char *err, unsigned int errcap)
  4658. {
  4659. unsigned int len;
  4660. int tr = 0;
  4661. int rv;
  4662. *out = 0;
  4663. *outlen = 0;
  4664. if (cap > BR_IMG_FILE_MAX)
  4665. cap = BR_IMG_FILE_MAX;
  4666. if (url[0] == '/') {
  4667. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  4668. (int)cap);
  4669. if (rv < 0) {
  4670. s_copy(err, "file not found", errcap);
  4671. return -1;
  4672. }
  4673. *out = image_file_buf;
  4674. *outlen = (unsigned int)rv;
  4675. return 0;
  4676. }
  4677. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  4678. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  4679. if (rv == FETCH_ABORT)
  4680. return FETCH_ABORT;
  4681. if (rv < 0)
  4682. return -1;
  4683. len = (unsigned int)rv;
  4684. if (len == 0) {
  4685. s_copy(err, "empty image", errcap);
  4686. return -1;
  4687. }
  4688. *out = image_file_buf;
  4689. *outlen = len;
  4690. return 0;
  4691. }
  4692. /* Remote stylesheets are immutable enough for the current boot: keep
  4693. * successful responses under /share so a reload, a second visit or a fresh
  4694. * browser launch does not fetch the same five sheets over the network again.
  4695. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  4696. static int css_cache_count;
  4697. static unsigned int css_cache_hash(const char *s)
  4698. {
  4699. unsigned int h = 2166136261u;
  4700. while (*s) {
  4701. h ^= (unsigned char)*s++;
  4702. h *= 16777619u;
  4703. }
  4704. return h;
  4705. }
  4706. static void css_cache_path(const char *url, char *out, unsigned int cap)
  4707. {
  4708. unsigned int n = 0;
  4709. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  4710. s_append_dec(out, &n, css_cache_hash(url), cap);
  4711. }
  4712. static void css_cache_clear(void)
  4713. {
  4714. struct sys_dirent d;
  4715. char path[96];
  4716. for (;;) {
  4717. int i, found = 0;
  4718. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4719. (int)&d) == 1; i++) {
  4720. unsigned int n = 0;
  4721. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  4722. continue;
  4723. s_append(path, &n, "/share/", sizeof(path));
  4724. s_append(path, &n, d.name, sizeof(path));
  4725. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  4726. return;
  4727. found = 1;
  4728. break;
  4729. }
  4730. if (!found)
  4731. break;
  4732. }
  4733. css_cache_count = 0;
  4734. }
  4735. static void css_cache_init(void)
  4736. {
  4737. struct sys_dirent d;
  4738. int i, count = 0;
  4739. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4740. (int)&d) == 1; i++)
  4741. if (starts_with(d.name, CSS_CACHE_PREFIX))
  4742. count++;
  4743. if (count >= CSS_CACHE_MAX) {
  4744. css_cache_clear();
  4745. return;
  4746. }
  4747. css_cache_count = count;
  4748. }
  4749. static int css_cache_get(const char *url, unsigned char **out,
  4750. unsigned int *outlen)
  4751. {
  4752. char path[96];
  4753. int rn;
  4754. css_cache_path(url, path, sizeof(path));
  4755. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  4756. (int)CSS_CACHE_FILE_MAX);
  4757. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  4758. return 0;
  4759. *out = image_io_buf;
  4760. *outlen = (unsigned int)rn;
  4761. return 1;
  4762. }
  4763. static void css_cache_put(const char *url, const unsigned char *data,
  4764. unsigned int len)
  4765. {
  4766. char path[96];
  4767. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  4768. len >= CSS_CACHE_FILE_MAX)
  4769. return;
  4770. css_cache_path(url, path, sizeof(path));
  4771. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  4772. (int)len) >= 0)
  4773. css_cache_count++;
  4774. }
  4775. static int css_cache_has(const char *url)
  4776. {
  4777. char path[96];
  4778. struct sys_stat st;
  4779. css_cache_path(url, path, sizeof(path));
  4780. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  4781. st.size < CSS_CACHE_FILE_MAX;
  4782. }
  4783. /* Read one stylesheet into the shared static buffer. CSS is parsed
  4784. * immediately, so it does not need the page heap; this leaves the heap for
  4785. * the 2 MB page body, the rules and the scaled image bitmaps. */
  4786. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  4787. char *err, unsigned int errcap)
  4788. {
  4789. unsigned int len;
  4790. int tr = 0;
  4791. int rv;
  4792. *out = 0;
  4793. *outlen = 0;
  4794. if (url[0] == '/') {
  4795. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  4796. (int)BR_CSS_MAX);
  4797. if (rv < 0) {
  4798. s_copy(err, "stylesheet not found", errcap);
  4799. return -1;
  4800. }
  4801. *out = image_io_buf;
  4802. *outlen = (unsigned int)rv;
  4803. return 0;
  4804. }
  4805. if (css_cache_get(url, out, outlen))
  4806. return 0;
  4807. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  4808. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  4809. &fetch_meta, &tr, err, errcap);
  4810. if (rv == FETCH_ABORT)
  4811. return FETCH_ABORT;
  4812. if (rv < 0)
  4813. return -1;
  4814. len = (unsigned int)rv;
  4815. if (len == 0) {
  4816. s_copy(err, "empty stylesheet", errcap);
  4817. return -1;
  4818. }
  4819. *out = image_io_buf;
  4820. *outlen = len;
  4821. css_cache_put(url, image_io_buf, len);
  4822. return 0;
  4823. }
  4824. static void redraw_now(void);
  4825. static char error_page[1024];
  4826. static void show_error(const char *title, const char *detail)
  4827. {
  4828. char *page = error_page;
  4829. unsigned int n = 0;
  4830. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  4831. s_append(page, &n, title, sizeof(error_page));
  4832. s_append(page, &n, "</h2><p>", sizeof(error_page));
  4833. {
  4834. const char *p = detail;
  4835. while (*p && n + 1 < sizeof(error_page)) {
  4836. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  4837. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  4838. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  4839. else page[n++] = *p;
  4840. p++;
  4841. }
  4842. }
  4843. page[n] = '\0';
  4844. s_append(page, &n, "</p><p>", sizeof(error_page));
  4845. s_append(page, &n, page_url, sizeof(error_page));
  4846. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  4847. sizeof(error_page));
  4848. br_parse(&doc, page, n);
  4849. layout_valid = 0;
  4850. preload_active = 0;
  4851. preload_pending = 0;
  4852. preload_wait = 0;
  4853. fetch_workers_cancel_busy();
  4854. s_copy(page_title, title, sizeof(page_title));
  4855. page_loading = 0;
  4856. set_status(title, 1, 0);
  4857. ngui_invalidate(&ui);
  4858. }
  4859. static int decode_direct_image(const unsigned char *data, unsigned int len,
  4860. unsigned int node)
  4861. {
  4862. if (image_count >= BR_MAX_IMAGES)
  4863. return -1;
  4864. if (decode_image_data(data, len, &images[0], 0, 0, 0, 0) != 0)
  4865. return -1;
  4866. doc.nodes[node].img_index = 0;
  4867. image_count = 1;
  4868. return 0;
  4869. }
  4870. static int ancestor_is(unsigned int node, unsigned int tag)
  4871. {
  4872. unsigned int p = doc.nodes[node].parent;
  4873. while (p) {
  4874. if (doc.nodes[p].tag == tag)
  4875. return 1;
  4876. p = doc.nodes[p].parent;
  4877. }
  4878. return 0;
  4879. }
  4880. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  4881. * parallel but parsed in document order, so the cascade is unchanged. */
  4882. static int load_stylesheets(void)
  4883. {
  4884. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  4885. static unsigned char remote[BR_MAX_SHEETS];
  4886. struct fetch_worker *slot[BR_MAX_SHEETS];
  4887. unsigned int i, n = 0, next = 0, k;
  4888. char err[64];
  4889. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  4890. struct br_node *nd = &doc.nodes[i];
  4891. const char *rel, *href;
  4892. char url[BR_URL_MAX];
  4893. int dup = 0;
  4894. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  4895. continue;
  4896. rel = br_rel(&doc, i);
  4897. if (!contains_ci(rel, "stylesheet"))
  4898. continue;
  4899. href = br_href(&doc, i);
  4900. if (!href[0])
  4901. continue;
  4902. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  4903. continue;
  4904. for (k = 0; k < n; k++)
  4905. if (s_eq(urls[k], url)) {
  4906. dup = 1;
  4907. break;
  4908. }
  4909. if (dup)
  4910. continue;
  4911. s_copy(urls[n], url, BR_URL_MAX);
  4912. remote[n] = url[0] != '/' && !css_cache_has(url);
  4913. n++;
  4914. }
  4915. for (i = 0; i < BR_MAX_SHEETS; i++)
  4916. slot[i] = 0;
  4917. /* Start as many remote sheets as there are free workers. */
  4918. for (; next < n; next++) {
  4919. struct fetch_worker *w;
  4920. if (!remote[next])
  4921. continue;
  4922. w = fetch_worker_alloc();
  4923. if (!w)
  4924. break;
  4925. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  4926. err, sizeof(err)) != 0) {
  4927. fetch_worker_release(w);
  4928. remote[next] = 0;
  4929. continue;
  4930. }
  4931. slot[next] = w;
  4932. }
  4933. for (i = 0; i < n; i++) {
  4934. unsigned char *data = 0;
  4935. unsigned int len = 0;
  4936. int rv;
  4937. if (!remote[i]) {
  4938. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  4939. if (rv == FETCH_ABORT) {
  4940. fetch_workers_stop_all();
  4941. return FETCH_ABORT;
  4942. }
  4943. if (rv != 0 || !len)
  4944. continue;
  4945. } else {
  4946. struct fetch_worker *w = slot[i];
  4947. int tr = 0;
  4948. if (!w) {
  4949. w = fetch_worker_alloc();
  4950. if (!w) {
  4951. rv = -1;
  4952. goto css_failed;
  4953. }
  4954. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  4955. 0, 0, 0, 0, err,
  4956. sizeof(err)) != 0) {
  4957. fetch_worker_release(w);
  4958. remote[i] = 0;
  4959. if (i == next)
  4960. next++;
  4961. continue;
  4962. }
  4963. slot[i] = w;
  4964. if (i == next)
  4965. next++;
  4966. }
  4967. rv = fetch_worker_wait(w, err, sizeof(err));
  4968. if (rv == FETCH_ABORT) {
  4969. fetch_workers_stop_all();
  4970. return FETCH_ABORT;
  4971. }
  4972. if (rv == 0)
  4973. rv = fetch_worker_read_body(w, image_io_buf,
  4974. BR_CSS_MAX,
  4975. image_io_buf + BR_CSS_MAX,
  4976. BR_CSS_COMP_MAX, &tr,
  4977. err, sizeof(err));
  4978. else
  4979. rv = -1;
  4980. fetch_worker_release(w);
  4981. slot[i] = 0;
  4982. /* Refill the worker window before parsing this sheet. */
  4983. for (; next < n; next++) {
  4984. struct fetch_worker *nw;
  4985. if (!remote[next])
  4986. continue;
  4987. nw = fetch_worker_alloc();
  4988. if (!nw)
  4989. break;
  4990. if (fetch_worker_submit(nw, urls[next],
  4991. BR_CSS_MAX, 0, 0, 0, 0,
  4992. err, sizeof(err)) != 0) {
  4993. fetch_worker_release(nw);
  4994. remote[next] = 0;
  4995. continue;
  4996. }
  4997. slot[next] = nw;
  4998. }
  4999. css_failed:
  5000. if (rv <= 0) {
  5001. /* One synchronous retry: a dropped sheet leaves the
  5002. * whole page unstyled (seen intermittently on
  5003. * arstechnica's CDN). */
  5004. u_puts("[css] retry ");
  5005. u_puts(urls[i]);
  5006. u_puts(": ");
  5007. u_puts(err[0] ? err : "no worker/empty body");
  5008. u_putc('\n');
  5009. err[0] = '\0';
  5010. rv = fetch_css(urls[i], &data, &len, err,
  5011. sizeof(err));
  5012. if (rv == FETCH_ABORT) {
  5013. fetch_workers_stop_all();
  5014. return FETCH_ABORT;
  5015. }
  5016. if (rv != 0 || !len) {
  5017. u_puts("[css] failed: ");
  5018. u_puts(err);
  5019. u_putc('\n');
  5020. continue;
  5021. }
  5022. } else {
  5023. len = (unsigned int)rv;
  5024. data = image_io_buf;
  5025. css_cache_put(urls[i], data, len);
  5026. }
  5027. }
  5028. if (len) {
  5029. br_set_font_base(urls[i]);
  5030. br_parse_css_text(&doc, (const char *)data, len);
  5031. }
  5032. }
  5033. br_set_font_base(page_url);
  5034. br_parse_inline_css(&doc);
  5035. load_font_faces();
  5036. br_reset_styles(&doc);
  5037. layout_valid = 0;
  5038. return 0;
  5039. }
  5040. static void preload_begin(void)
  5041. {
  5042. preload_active = 1;
  5043. preload_pending = 0;
  5044. preload_wait = 1;
  5045. preload_max_jobs = FETCH_WORKERS;
  5046. preload_node = 0;
  5047. preload_loaded = 0;
  5048. preload_scroll = 0;
  5049. img_stat_start = u_ticks_ms();
  5050. img_stat_wall = 0;
  5051. img_stat_net = img_stat_open = img_stat_first = 0;
  5052. img_stat_io = img_stat_dec = img_stat_scale = 0;
  5053. img_stat_paint = img_stat_reflow = 0;
  5054. img_stat_bytes = 0;
  5055. img_stat_n = 0;
  5056. img_stat_log_len = 0;
  5057. if (img_stat_log[0])
  5058. img_stat_log[0] = '\0';
  5059. img_repaint_ms = 0;
  5060. img_repaint_pending = 0;
  5061. }
  5062. /* Styles are computed top-down during layout, but images inside a hidden
  5063. * menu/carousel are never visited and keep img_top == 0. Without this check
  5064. * the preloader walks the DOM in node order and spends the whole image
  5065. * budget on logos and off-canvas thumbnails the reader cannot see. */
  5066. static struct br_style base_style(void);
  5067. static int node_hidden(unsigned int node)
  5068. {
  5069. unsigned int path[32], n = 0, p = node, i;
  5070. struct br_style st, parent;
  5071. while (p && n < sizeof(path) / sizeof(path[0])) {
  5072. path[n++] = p;
  5073. p = doc.nodes[p].parent;
  5074. }
  5075. /* Node 0 is the <html> element when the page starts with one: it
  5076. * is an ancestor too. Styles are cached per node, so the chain
  5077. * must start from the same base as style_for_node(); seeding it
  5078. * with a zeroed style left <body> cached with black text and no
  5079. * line-height once an image job ran (docs.cloudron.io). */
  5080. if (!p && n && n < sizeof(path) / sizeof(path[0]) &&
  5081. doc.nodes[0].type == BR_NODE_ELEM &&
  5082. doc.nodes[0].tag == BR_TAG_HTML &&
  5083. !(doc.nodes[path[n - 1]].flags & BR_NODE_DETACHED))
  5084. path[n++] = 0;
  5085. parent = base_style();
  5086. for (i = n; i > 0; i--) {
  5087. br_style_for(&doc, path[i - 1], &parent, &st);
  5088. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  5089. st.opacity_hidden)
  5090. return 1;
  5091. parent = st;
  5092. }
  5093. return 0;
  5094. }
  5095. static struct br_style base_style(void);
  5096. static int style_width_px(const struct br_style *st, int base);
  5097. static int style_height_px(const struct br_style *st, int base);
  5098. static void style_for_node(unsigned int node, struct br_style *out)
  5099. {
  5100. unsigned int p = doc.nodes[node].parent;
  5101. struct br_style parent;
  5102. /* Parent index 0 is ambiguous: it is the <html> element when the page
  5103. * starts with one (see root_style()), but also the parent field of a
  5104. * detached subtree root. */
  5105. if (p || (node != 0 && doc.nodes[0].type == BR_NODE_ELEM &&
  5106. doc.nodes[0].tag == BR_TAG_HTML &&
  5107. !(doc.nodes[node].flags & BR_NODE_DETACHED))) {
  5108. style_for_node(p, &parent);
  5109. br_style_for(&doc, node, &parent, out);
  5110. } else {
  5111. parent = base_style();
  5112. br_style_for(&doc, node, &parent, out);
  5113. }
  5114. }
  5115. /* ---- parallel image preloading ---- *
  5116. *
  5117. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  5118. * preload_step() only starts jobs and harvests completed ones; the browser
  5119. * main loop keeps drawing between calls, instead of blocking on one fetch.
  5120. */
  5121. static int preload_active_jobs(void)
  5122. {
  5123. int i, n = 0;
  5124. for (i = 0; i < FETCH_WORKERS; i++)
  5125. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  5126. n++;
  5127. return n;
  5128. }
  5129. static void preload_job_error(struct fetch_worker *w)
  5130. {
  5131. if (w->node < doc.nnode) {
  5132. if (w->bg)
  5133. doc.nodes[w->node].bg_img_index = -2;
  5134. else
  5135. doc.nodes[w->node].img_index = -2;
  5136. image_repaint();
  5137. }
  5138. }
  5139. /* Is the image's box anywhere near the visible page? A decode below the
  5140. * fold changes the layout (scroll extent) but not a single on-screen pixel,
  5141. * so it does not need a repaint. top/h come from the last layout; treat an
  5142. * unknown box as visible to stay safe. */
  5143. static int image_preload_visible(unsigned int node, int bg)
  5144. {
  5145. int top, h, scroll;
  5146. if (node >= BR_MAX_NODES || node >= doc.nnode || page_rect.h <= 0)
  5147. return 1;
  5148. if (bg) {
  5149. top = (int)block_top[node];
  5150. h = (int)block_h[node];
  5151. } else {
  5152. top = (int)img_top[node];
  5153. h = (int)img_h[node];
  5154. }
  5155. if (!top && !h)
  5156. return 1;
  5157. scroll = (int)page_scroll.offset;
  5158. if (top > scroll + page_rect.h + 160)
  5159. return 0;
  5160. if (top + h + 160 < scroll)
  5161. return 0;
  5162. return 1;
  5163. }
  5164. /* Upper bounds for the bitmap an <img> will paint. Zero means "unbounded";
  5165. * decode_image_data applies one scale to both axes so the aspect ratio is
  5166. * preserved. This is what keeps a 1200x800 photo that CSS paints at 400 px
  5167. * from being decoded and box-filtered to the 1000 px layout cap first. */
  5168. static void image_fit_size(unsigned int node, int *out_w, int *out_h)
  5169. {
  5170. struct br_style st;
  5171. struct br_node *nd;
  5172. unsigned int p;
  5173. int cw, w = 0, h = 0;
  5174. *out_w = *out_h = 0;
  5175. if (node >= doc.nnode)
  5176. return;
  5177. nd = &doc.nodes[node];
  5178. style_for_node(node, &st);
  5179. cw = page_rect.w > 24 ? page_rect.w - 24 : 0;
  5180. p = doc.nodes[node].parent;
  5181. if (p && p < BR_MAX_NODES && layout_boxes[p].valid &&
  5182. layout_boxes[p].w > 0 && layout_boxes[p].w < cw)
  5183. cw = layout_boxes[p].w;
  5184. if (st.width_kind)
  5185. w = style_width_px(&st, cw);
  5186. else if (nd->width_attr)
  5187. w = nd->width_pct ? cw * (int)nd->width_attr / 100 :
  5188. (int)nd->width_attr;
  5189. if (st.height_kind)
  5190. h = style_height_px(&st, cw);
  5191. else if (nd->height_attr)
  5192. h = nd->height_pct ? cw * (int)nd->height_attr / 100 :
  5193. (int)nd->height_attr;
  5194. if (st.max_width_kind) {
  5195. int mw = st.max_width_kind == 3 ?
  5196. cw * st.max_width_calc_pct / 100 +
  5197. st.max_width_calc_px :
  5198. st.max_width_kind == 2 ?
  5199. cw * (int)st.max_width / 100 :
  5200. (int)st.max_width;
  5201. if (mw > 0 && (w == 0 || w > mw))
  5202. w = mw;
  5203. }
  5204. if (st.max_height_kind) {
  5205. int mh = st.max_height_kind == 3 ?
  5206. cw * st.max_height_calc_pct / 100 +
  5207. st.max_height_calc_px :
  5208. st.max_height_kind == 2 ?
  5209. cw * (int)st.max_height / 100 :
  5210. (int)st.max_height;
  5211. if (mh > 0 && (h == 0 || h > mh))
  5212. h = mh;
  5213. }
  5214. if (w > BR_IMG_LAYOUT_W)
  5215. w = BR_IMG_LAYOUT_W;
  5216. if (h > 4096)
  5217. h = 4096;
  5218. if (w < 0)
  5219. w = 0;
  5220. if (h < 0)
  5221. h = 0;
  5222. *out_w = w;
  5223. *out_h = h;
  5224. }
  5225. static void preload_accept_image(unsigned int node, int bg, const char *url)
  5226. {
  5227. /* An <img> bitmap only depends on its URL, so the next <img> with the
  5228. * same source reuses it (heise repeats one comment icon 85 times).
  5229. * Backgrounds are scaled to their box and are not shared. */
  5230. images[image_count].url_hash =
  5231. !bg && url ? script_cache_hash(url) | 1u : 0;
  5232. if (bg)
  5233. doc.nodes[node].bg_img_index = (short)image_count;
  5234. else
  5235. doc.nodes[node].img_index = (short)image_count;
  5236. image_count++;
  5237. preload_loaded++;
  5238. /* A background bitmap never changes its box, so keep the (expensive)
  5239. * measured layout and only repaint the pixels. */
  5240. if (bg)
  5241. page_cache_valid = 0;
  5242. else
  5243. layout_valid = 0;
  5244. if (image_preload_visible(node, bg))
  5245. image_repaint();
  5246. }
  5247. /* Install a bitmap decoded by the fetch helper. The helper already applied
  5248. * the display bounds (and the JPEG reduced IDCT), so this is a read + copy
  5249. * on the UI thread instead of a decode. */
  5250. static int preload_store_helper(unsigned int node, int bg,
  5251. unsigned char *px, unsigned int pxlen,
  5252. unsigned int dw, unsigned int dh,
  5253. int alpha, unsigned int nw, unsigned int nh,
  5254. const char *url)
  5255. {
  5256. struct br_image *bi;
  5257. unsigned int npx;
  5258. if (image_count >= BR_MAX_IMAGES || !px || !dw || !dh ||
  5259. dw > 4096 || dh > 4096) {
  5260. free(px);
  5261. return -1;
  5262. }
  5263. npx = dw * dh;
  5264. if (image_pixels + npx > BR_IMG_PIXEL_BUDGET ||
  5265. pxlen < npx * 2u + (alpha ? npx : 0)) {
  5266. free(px);
  5267. return -1;
  5268. }
  5269. bi = &images[image_count];
  5270. bi->img.format = 0;
  5271. bi->img.w = dw;
  5272. bi->img.h = dh;
  5273. bi->img.px = (unsigned short *)px;
  5274. bi->img.alpha = alpha ? px + npx * 2u : 0;
  5275. bi->img.flags = 0;
  5276. bi->native_w = nw ? (int)nw : (int)dw;
  5277. bi->native_h = nh ? (int)nh : (int)dh;
  5278. bi->state = 1;
  5279. image_pixels += npx;
  5280. preload_accept_image(node, bg, url);
  5281. return 0;
  5282. }
  5283. static void preload_decode(unsigned int node, int bg,
  5284. const unsigned char *data, unsigned int len,
  5285. const char *url)
  5286. {
  5287. int fit_w = 0, fit_h = 0;
  5288. if (image_count >= BR_MAX_IMAGES) {
  5289. if (bg)
  5290. doc.nodes[node].bg_img_index = -2;
  5291. else
  5292. doc.nodes[node].img_index = -2;
  5293. return;
  5294. }
  5295. if (!bg)
  5296. image_fit_size(node, &fit_w, &fit_h);
  5297. if (decode_image_data(data, len, &images[image_count],
  5298. bg && node < BR_MAX_NODES &&
  5299. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  5300. bg && node < BR_MAX_NODES &&
  5301. layout_boxes[node].valid ? layout_boxes[node].h : 0,
  5302. fit_w, fit_h) == 0) {
  5303. preload_accept_image(node, bg, url);
  5304. } else {
  5305. if (bg)
  5306. doc.nodes[node].bg_img_index = -2;
  5307. else
  5308. doc.nodes[node].img_index = -2;
  5309. layout_valid = 0;
  5310. }
  5311. if (image_preload_visible(node, bg))
  5312. image_repaint();
  5313. }
  5314. /* ---- data: URLs ----
  5315. *
  5316. * `data:[<type>][;base64],<payload>` decoded to bytes from the page heap
  5317. * (the caller frees them). The payload is percent-decoded, then base64-
  5318. * decoded when the header says so. Infima's menu chevron and many icon
  5319. * fonts' fallbacks are inline SVGs written this way. */
  5320. static int b64_val(int c)
  5321. {
  5322. if (c >= 'A' && c <= 'Z') return c - 'A';
  5323. if (c >= 'a' && c <= 'z') return c - 'a' + 26;
  5324. if (c >= '0' && c <= '9') return c - '0' + 52;
  5325. if (c == '+' || c == '-') return 62;
  5326. if (c == '/' || c == '_') return 63;
  5327. return -1;
  5328. }
  5329. static int hex_val(int c)
  5330. {
  5331. if (c >= '0' && c <= '9') return c - '0';
  5332. c |= 32;
  5333. if (c >= 'a' && c <= 'f') return c - 'a' + 10;
  5334. return -1;
  5335. }
  5336. static int data_url_decode(const char *url, unsigned char **out,
  5337. unsigned int *out_len)
  5338. {
  5339. const char *comma, *p;
  5340. unsigned int n = 0, len, i;
  5341. unsigned char *buf;
  5342. int base64 = 0;
  5343. *out = 0;
  5344. *out_len = 0;
  5345. if (!starts_with(url, "data:"))
  5346. return -1;
  5347. comma = url + 5;
  5348. while (*comma && *comma != ',')
  5349. comma++;
  5350. if (!*comma)
  5351. return -1;
  5352. for (p = url + 5; p + 7 <= comma; p++)
  5353. if (!strncmp(p, ";base64", 7))
  5354. base64 = 1;
  5355. len = s_len(comma + 1);
  5356. buf = (unsigned char *)malloc(len + 1);
  5357. if (!buf)
  5358. return -1;
  5359. for (i = 0, p = comma + 1; i < len; i++) {
  5360. int c = (unsigned char)p[i];
  5361. if (c == '%' && i + 2 < len &&
  5362. hex_val(p[i + 1]) >= 0 && hex_val(p[i + 2]) >= 0) {
  5363. c = hex_val(p[i + 1]) * 16 + hex_val(p[i + 2]);
  5364. i += 2;
  5365. }
  5366. buf[n++] = (unsigned char)c;
  5367. }
  5368. if (base64) {
  5369. unsigned int acc = 0, o = 0;
  5370. int bits = 0;
  5371. for (i = 0; i < n; i++) {
  5372. int v = b64_val(buf[i]);
  5373. if (v < 0)
  5374. continue; /* padding, whitespace */
  5375. acc = (acc << 6) | (unsigned int)v;
  5376. bits += 6;
  5377. if (bits >= 8) {
  5378. bits -= 8;
  5379. buf[o++] = (unsigned char)(acc >> bits);
  5380. }
  5381. }
  5382. n = o;
  5383. }
  5384. buf[n] = 0;
  5385. *out = buf;
  5386. *out_len = n;
  5387. return 0;
  5388. }
  5389. static unsigned int data_img_key(const char *url, int w, int h)
  5390. {
  5391. return (script_cache_hash(url) ^ ((unsigned int)w * 2654435761u) ^
  5392. ((unsigned int)h * 40503u)) | 1u;
  5393. }
  5394. /* The image index of a data: URL decoded for a w x h box (an SVG is
  5395. * rasterized at that size), decoding it on first use; -1 on failure.
  5396. * Decoded bitmaps are found again through url_hash, which is distinct
  5397. * from the <img> sharing hash because it mixes in the size. */
  5398. static int data_url_image(const char *url, int w, int h)
  5399. {
  5400. unsigned int key, len;
  5401. unsigned char *data;
  5402. int i;
  5403. if (!starts_with(url, "data:") || w <= 0 || h <= 0)
  5404. return -1;
  5405. key = data_img_key(url, w, h);
  5406. for (i = 0; i < image_count; i++)
  5407. if (images[i].state == 1 && images[i].url_hash == key)
  5408. return i;
  5409. for (i = 0; i < data_img_nfail; i++)
  5410. if (data_img_fail[i] == key)
  5411. return -1;
  5412. if (image_count < BR_MAX_IMAGES &&
  5413. data_url_decode(url, &data, &len) == 0) {
  5414. int r = decode_image_data(data, len, &images[image_count],
  5415. w, h, w, h);
  5416. free(data);
  5417. if (r == 0) {
  5418. images[image_count].url_hash = key;
  5419. return image_count++;
  5420. }
  5421. }
  5422. if (data_img_nfail < DATA_IMG_FAIL_MAX)
  5423. data_img_fail[data_img_nfail++] = key;
  5424. return -1;
  5425. }
  5426. /* A local file image bypasses the helpers: count its decode so a page opened
  5427. * from /share or /data still produces the same timing breakdown. */
  5428. static void img_stat_local(int before, unsigned int bytes, unsigned int io_ms)
  5429. {
  5430. img_stat_n++;
  5431. img_stat_bytes += bytes;
  5432. img_stat_io += io_ms;
  5433. if (image_count > before) {
  5434. struct br_image *bi = &images[image_count - 1];
  5435. img_stat_dec += img_last_dec_ms;
  5436. img_stat_scale += img_last_scale_ms;
  5437. if (img_stat_log_len + 100 < sizeof(img_stat_log)) {
  5438. unsigned int n = img_stat_log_len;
  5439. s_append(img_stat_log, &n, "local ", sizeof(img_stat_log));
  5440. s_append_dec(img_stat_log, &n, bytes,
  5441. sizeof(img_stat_log));
  5442. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5443. s_append_dec(img_stat_log, &n, img_last_dec_ms,
  5444. sizeof(img_stat_log));
  5445. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5446. s_append_dec(img_stat_log, &n, img_last_scale_ms,
  5447. sizeof(img_stat_log));
  5448. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5449. s_append_dec(img_stat_log, &n,
  5450. (unsigned int)bi->native_w,
  5451. sizeof(img_stat_log));
  5452. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  5453. s_append_dec(img_stat_log, &n,
  5454. (unsigned int)bi->native_h,
  5455. sizeof(img_stat_log));
  5456. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5457. s_append_dec(img_stat_log, &n, bi->img.w,
  5458. sizeof(img_stat_log));
  5459. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  5460. s_append_dec(img_stat_log, &n, bi->img.h,
  5461. sizeof(img_stat_log));
  5462. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  5463. s_append_dec(img_stat_log, &n,
  5464. bi->img.alpha ? 1u : 0u,
  5465. sizeof(img_stat_log));
  5466. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  5467. img_stat_log_len = n;
  5468. }
  5469. }
  5470. }
  5471. /* Harvest one completed worker. Returns 1 when a job was finished. */
  5472. static int preload_finish_worker(struct fetch_worker *w)
  5473. {
  5474. char err[64];
  5475. int rv, tr = 0;
  5476. unsigned int t0, io_ms;
  5477. int before;
  5478. int used_px = 0;
  5479. rv = fetch_worker_poll(w, err, sizeof(err));
  5480. if (rv < 0) {
  5481. /* A helper from an older pack does not understand the image
  5482. * decode request; retry once without it and decode in-process. */
  5483. if (w->image_job && w->dec_w && !w->dec_retried &&
  5484. fetch_worker_submit_req(w, w->url, BR_IMG_FILE_MAX,
  5485. 0, 0, 0, 0, w->node, w->bg,
  5486. 0, 0, 0, err, sizeof(err)) == 0) {
  5487. w->image_job = 1;
  5488. w->dec_retried = 1;
  5489. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  5490. return 0;
  5491. }
  5492. preload_job_error(w);
  5493. if (img_stat_log_len + 64 < sizeof(img_stat_log)) {
  5494. unsigned int n = img_stat_log_len;
  5495. char u[48];
  5496. s_copy(u, w->url, sizeof(u));
  5497. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  5498. s_append(img_stat_log, &n, " error\n",
  5499. sizeof(img_stat_log));
  5500. img_stat_log_len = n;
  5501. }
  5502. img_stat_n++;
  5503. fetch_worker_release(w);
  5504. return 1;
  5505. }
  5506. if (rv == 0)
  5507. return 0;
  5508. t0 = u_ticks_ms();
  5509. rv = -1;
  5510. before = image_count;
  5511. if (w->m.px_len && !w->m.dec_err && w->m.dw && w->m.dh &&
  5512. w->m.px_len <= 8u * 1024u * 1024u) {
  5513. unsigned char *px = (unsigned char *)malloc(w->m.px_len);
  5514. int pr = -1;
  5515. if (px)
  5516. pr = u_syscall3(SYS_READ_FILE, (int)w->px, (int)px,
  5517. (int)w->m.px_len);
  5518. if (pr == (int)w->m.px_len) {
  5519. if (preload_store_helper(w->node, w->bg, px,
  5520. w->m.px_len, w->m.dw,
  5521. w->m.dh, (int)w->m.alpha,
  5522. w->m.nw, w->m.nh,
  5523. w->url) == 0) {
  5524. rv = (int)w->m.len;
  5525. img_last_dec_ms = w->m.dec_ms;
  5526. img_last_scale_ms = 0;
  5527. used_px = 1;
  5528. } else {
  5529. px = 0; /* the helper freed it */
  5530. }
  5531. }
  5532. if (px && !(pr == (int)w->m.px_len))
  5533. free(px);
  5534. }
  5535. io_ms = u_ticks_ms() - t0;
  5536. if (rv < 0) {
  5537. t0 = u_ticks_ms();
  5538. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  5539. image_comp_buf, BR_IMG_FILE_MAX,
  5540. &tr, err, sizeof(err));
  5541. io_ms += u_ticks_ms() - t0;
  5542. before = image_count;
  5543. if (rv >= 0)
  5544. preload_decode(w->node, w->bg, image_file_buf,
  5545. (unsigned int)rv, w->url);
  5546. else
  5547. preload_job_error(w);
  5548. }
  5549. img_stat_n++;
  5550. img_stat_net += w->m.total_ms;
  5551. img_stat_open += w->m.open_ms;
  5552. img_stat_first += w->m.first_ms;
  5553. img_stat_io += io_ms;
  5554. img_stat_bytes += rv > 0 ? (unsigned int)rv : 0;
  5555. img_stat_dec += w->m.dec_ms;
  5556. if (rv >= 0 && !used_px) {
  5557. img_stat_dec += img_last_dec_ms;
  5558. img_stat_scale += img_last_scale_ms;
  5559. }
  5560. if (img_stat_log_len + 160 < sizeof(img_stat_log)) {
  5561. unsigned int n = img_stat_log_len;
  5562. char u[48];
  5563. s_copy(u, w->url, sizeof(u));
  5564. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  5565. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5566. s_append_dec(img_stat_log, &n,
  5567. rv > 0 ? (unsigned int)rv : 0,
  5568. sizeof(img_stat_log));
  5569. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5570. s_append_dec(img_stat_log, &n, w->m.open_ms,
  5571. sizeof(img_stat_log));
  5572. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5573. s_append_dec(img_stat_log, &n, w->m.first_ms,
  5574. sizeof(img_stat_log));
  5575. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5576. s_append_dec(img_stat_log, &n, w->m.total_ms,
  5577. sizeof(img_stat_log));
  5578. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5579. s_append_dec(img_stat_log, &n, io_ms, sizeof(img_stat_log));
  5580. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5581. s_append_dec(img_stat_log, &n,
  5582. rv >= 0 ? img_last_dec_ms : 0,
  5583. sizeof(img_stat_log));
  5584. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5585. s_append_dec(img_stat_log, &n,
  5586. rv >= 0 ? img_last_scale_ms : 0,
  5587. sizeof(img_stat_log));
  5588. if (image_count > before) {
  5589. struct br_image *bi = &images[image_count - 1];
  5590. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5591. s_append_dec(img_stat_log, &n,
  5592. (unsigned int)bi->native_w,
  5593. sizeof(img_stat_log));
  5594. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  5595. s_append_dec(img_stat_log, &n,
  5596. (unsigned int)bi->native_h,
  5597. sizeof(img_stat_log));
  5598. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  5599. s_append_dec(img_stat_log, &n, bi->img.w,
  5600. sizeof(img_stat_log));
  5601. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  5602. s_append_dec(img_stat_log, &n, bi->img.h,
  5603. sizeof(img_stat_log));
  5604. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  5605. s_append_dec(img_stat_log, &n,
  5606. bi->img.alpha ? 1u : 0u,
  5607. sizeof(img_stat_log));
  5608. }
  5609. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  5610. img_stat_log_len = n;
  5611. }
  5612. fetch_worker_release(w);
  5613. return 1;
  5614. }
  5615. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  5616. * the number of jobs started. */
  5617. static int preload_fill_jobs(void)
  5618. {
  5619. int started = 0;
  5620. char err[64];
  5621. while (preload_active && preload_node < doc.nnode) {
  5622. unsigned int i = preload_node;
  5623. struct br_node *nd = &doc.nodes[i];
  5624. const char *src;
  5625. char url[BR_URL_MAX];
  5626. struct fetch_worker *w;
  5627. if (preload_active_jobs() >= preload_max_jobs)
  5628. break;
  5629. if (nd->type != BR_NODE_ELEM) {
  5630. preload_node++;
  5631. continue;
  5632. }
  5633. if (nd->tag != BR_TAG_IMG) {
  5634. if (nd->bg_img_index == -1) {
  5635. struct br_style bs;
  5636. style_for_node(i, &bs);
  5637. if (bs.display != BR_DISPLAY_NONE &&
  5638. !bs.vis_hidden && bs.bg_image) {
  5639. const char *bsrc =
  5640. br_bg_image_url(bs.bg_image - 1);
  5641. /* Lazy like <img>: a background box
  5642. * below the viewport (or not laid
  5643. * out yet) waits for the next scan. */
  5644. if (bsrc[0] &&
  5645. (!layout_boxes[i].valid ||
  5646. block_top[i] >
  5647. (unsigned int)(page_scroll.offset +
  5648. page_rect.h + 160))) {
  5649. preload_pending = 1;
  5650. preload_node++;
  5651. continue;
  5652. }
  5653. if (starts_with(bsrc, "data:")) {
  5654. /* Inline image: decode now,
  5655. * no fetch helper. */
  5656. unsigned char *data;
  5657. unsigned int len;
  5658. preload_node = i + 1;
  5659. if (data_url_decode(bsrc, &data,
  5660. &len) == 0) {
  5661. preload_decode(i, 1, data,
  5662. len, 0);
  5663. free(data);
  5664. } else {
  5665. nd->bg_img_index = -2;
  5666. }
  5667. continue;
  5668. }
  5669. if (bsrc[0] &&
  5670. resolve_link(page_url, bsrc, url,
  5671. sizeof(url)) == 0) {
  5672. if (image_count +
  5673. preload_active_jobs() >=
  5674. BR_MAX_IMAGES) {
  5675. preload_node = doc.nnode;
  5676. break;
  5677. }
  5678. if (url[0] == '/') {
  5679. unsigned char *data = 0;
  5680. unsigned int len = 0;
  5681. unsigned int t0;
  5682. int before;
  5683. preload_node = i + 1;
  5684. before = image_count;
  5685. t0 = u_ticks_ms();
  5686. if (fetch_image(url,
  5687. BR_IMG_FILE_MAX,
  5688. &data, &len,
  5689. err,
  5690. sizeof(err)) == 0) {
  5691. preload_decode(i, 1, data, len, 0);
  5692. img_stat_local(before, len,
  5693. u_ticks_ms() - t0);
  5694. } else {
  5695. nd->bg_img_index = -2;
  5696. }
  5697. continue;
  5698. }
  5699. w = fetch_worker_alloc();
  5700. if (!w)
  5701. return started;
  5702. preload_node = i + 1;
  5703. if (fetch_worker_submit(w, url,
  5704. BR_IMG_FILE_MAX,
  5705. 0, 0, i, 1,
  5706. err,
  5707. sizeof(err)) != 0) {
  5708. nd->bg_img_index = -2;
  5709. fetch_worker_release(w);
  5710. continue;
  5711. }
  5712. w->image_job = 1;
  5713. w->deadline = u_ticks_ms() +
  5714. BR_IMG_JOB_TIMEOUT_MS;
  5715. /* in flight: rescans skip it */
  5716. nd->bg_img_index = -3;
  5717. started++;
  5718. continue;
  5719. }
  5720. }
  5721. nd->bg_img_index = -2;
  5722. }
  5723. preload_node++;
  5724. continue;
  5725. }
  5726. if (nd->img_index != -1) {
  5727. preload_node++;
  5728. continue;
  5729. }
  5730. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  5731. preload_node++;
  5732. continue;
  5733. }
  5734. src = br_src(&doc, i);
  5735. if (starts_with(src, "data:")) {
  5736. unsigned char *data;
  5737. unsigned int len;
  5738. preload_node = i + 1;
  5739. if (data_url_decode(src, &data, &len) == 0) {
  5740. preload_decode(i, 0, data, len, 0);
  5741. free(data);
  5742. } else {
  5743. doc.nodes[i].img_index = -2;
  5744. }
  5745. continue;
  5746. }
  5747. if (!src[0]) {
  5748. preload_node++;
  5749. continue;
  5750. }
  5751. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  5752. preload_node++;
  5753. continue;
  5754. }
  5755. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  5756. preload_node = doc.nnode;
  5757. break;
  5758. }
  5759. /* Do not stop at the first below-fold image: DOM order is
  5760. * not visual order, and a footer/ad image early in the DOM
  5761. * used to hide every later article image from the loader. */
  5762. if (img_top[i] >
  5763. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  5764. preload_pending = 1;
  5765. preload_node++;
  5766. continue;
  5767. }
  5768. {
  5769. unsigned int uh = script_cache_hash(url) | 1u;
  5770. int k;
  5771. for (k = 0; k < image_count; k++)
  5772. if (images[k].state == 1 &&
  5773. images[k].url_hash == uh)
  5774. break;
  5775. if (k < image_count) {
  5776. nd->img_index = (short)k;
  5777. layout_valid = 0;
  5778. preload_node = i + 1;
  5779. image_repaint();
  5780. continue;
  5781. }
  5782. }
  5783. if (url[0] == '/') {
  5784. unsigned char *data = 0;
  5785. unsigned int len = 0;
  5786. unsigned int t0;
  5787. int before;
  5788. preload_node = i + 1;
  5789. before = image_count;
  5790. t0 = u_ticks_ms();
  5791. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  5792. err, sizeof(err)) == 0) {
  5793. preload_decode(i, 0, data, len, url);
  5794. img_stat_local(before, len, u_ticks_ms() - t0);
  5795. } else {
  5796. nd->img_index = -2;
  5797. }
  5798. continue;
  5799. }
  5800. w = fetch_worker_alloc();
  5801. if (!w)
  5802. return started;
  5803. preload_node = i + 1;
  5804. {
  5805. char msg[64];
  5806. unsigned int n = 0;
  5807. s_append(msg, &n, "Loading images ", sizeof(msg));
  5808. s_append_dec(msg, &n,
  5809. (unsigned int)preload_loaded + 1,
  5810. sizeof(msg));
  5811. s_append(msg, &n, "...", sizeof(msg));
  5812. set_status_quiet(msg);
  5813. image_repaint();
  5814. }
  5815. {
  5816. int fit_w = 0, fit_h = 0;
  5817. image_fit_size(i, &fit_w, &fit_h);
  5818. if (!fit_w)
  5819. fit_w = BR_IMG_LAYOUT_W;
  5820. if (fetch_worker_submit_image(w, url, BR_IMG_FILE_MAX,
  5821. i, 0,
  5822. (unsigned int)fit_w,
  5823. (unsigned int)fit_h,
  5824. err, sizeof(err)) != 0) {
  5825. nd->img_index = -2;
  5826. fetch_worker_release(w);
  5827. continue;
  5828. }
  5829. }
  5830. w->image_job = 1;
  5831. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  5832. nd->img_index = -3; /* in flight: rescans skip it */
  5833. started++;
  5834. }
  5835. return started;
  5836. }
  5837. /* Report where the image batch spent its time: status bar for the headline,
  5838. * /share/IMGSTAT for the per-image breakdown (cat it from a terminal). */
  5839. static void img_stats_report(void)
  5840. {
  5841. char msg[80];
  5842. static char out[BR_IMG_STAT_LOG + 512];
  5843. unsigned int n = 0, o = 0;
  5844. if (!img_stat_n)
  5845. return;
  5846. img_stat_wall = img_stat_start ?
  5847. u_ticks_ms() - img_stat_start : 1;
  5848. if (!img_stat_wall)
  5849. img_stat_wall = 1;
  5850. /* Compact on-screen form; /share/IMGSTAT has the full breakdown. */
  5851. s_append(msg, &n, "img ", sizeof(msg));
  5852. s_append_dec(msg, &n, (unsigned int)img_stat_n, sizeof(msg));
  5853. s_append(msg, &n, " ", sizeof(msg));
  5854. s_append_dec(msg, &n, img_stat_wall, sizeof(msg));
  5855. s_append(msg, &n, "ms net ", sizeof(msg));
  5856. s_append_dec(msg, &n, img_stat_net, sizeof(msg));
  5857. s_append(msg, &n, " dec ", sizeof(msg));
  5858. s_append_dec(msg, &n, img_stat_dec, sizeof(msg));
  5859. s_append(msg, &n, " sc ", sizeof(msg));
  5860. s_append_dec(msg, &n, img_stat_scale, sizeof(msg));
  5861. s_append(msg, &n, " paint ", sizeof(msg));
  5862. s_append_dec(msg, &n, img_stat_paint, sizeof(msg));
  5863. /* Keep the page's phase breakdown and append the image summary when
  5864. * it fits; never hide a JS error or a truncation notice. */
  5865. if (!post_status_error && !contains_ci(post_status_text, "truncated")) {
  5866. unsigned int plen = s_len(post_status_text);
  5867. if (!plen) {
  5868. s_copy(post_status_text, msg, sizeof(post_status_text));
  5869. } else if (plen + s_len(msg) + 4 < sizeof(post_status_text)) {
  5870. unsigned int pn = plen;
  5871. s_append(post_status_text, &pn, " | ",
  5872. sizeof(post_status_text));
  5873. s_append(post_status_text, &pn, msg,
  5874. sizeof(post_status_text));
  5875. } else {
  5876. s_copy(post_status_text, msg, sizeof(post_status_text));
  5877. }
  5878. post_status_ttl = 12000;
  5879. }
  5880. s_append(out, &o, "browser image stats\n", sizeof(out));
  5881. s_append(out, &o, "n=", sizeof(out));
  5882. s_append_dec(out, &o, (unsigned int)img_stat_n, sizeof(out));
  5883. s_append(out, &o, " wall=", sizeof(out));
  5884. s_append_dec(out, &o, img_stat_wall, sizeof(out));
  5885. s_append(out, &o, " net=", sizeof(out));
  5886. s_append_dec(out, &o, img_stat_net, sizeof(out));
  5887. s_append(out, &o, " open=", sizeof(out));
  5888. s_append_dec(out, &o, img_stat_open, sizeof(out));
  5889. s_append(out, &o, " first=", sizeof(out));
  5890. s_append_dec(out, &o, img_stat_first, sizeof(out));
  5891. s_append(out, &o, " io=", sizeof(out));
  5892. s_append_dec(out, &o, img_stat_io, sizeof(out));
  5893. s_append(out, &o, " dec=", sizeof(out));
  5894. s_append_dec(out, &o, img_stat_dec, sizeof(out));
  5895. s_append(out, &o, " scale=", sizeof(out));
  5896. s_append_dec(out, &o, img_stat_scale, sizeof(out));
  5897. s_append(out, &o, " paint=", sizeof(out));
  5898. s_append_dec(out, &o, img_stat_paint, sizeof(out));
  5899. s_append(out, &o, " reflow=", sizeof(out));
  5900. s_append_dec(out, &o, img_stat_reflow, sizeof(out));
  5901. s_append(out, &o, " bytes=", sizeof(out));
  5902. s_append_dec(out, &o, img_stat_bytes, sizeof(out));
  5903. s_append(out, &o, "\nurl bytes open first total io dec scale native bitmap\n",
  5904. sizeof(out));
  5905. s_append(out, &o, img_stat_log, sizeof(out));
  5906. u_syscall3(SYS_WRITE_FILE, (int)"/share/IMGSTAT", (int)out,
  5907. (int)s_len(out));
  5908. }
  5909. static void preload_step(void)
  5910. {
  5911. int i;
  5912. unsigned int t0;
  5913. if (!preload_active)
  5914. return;
  5915. if (cancel_fetch || pending_action) {
  5916. preload_active = 0;
  5917. preload_pending = 0;
  5918. fetch_workers_cancel_busy();
  5919. return;
  5920. }
  5921. preload_fill_jobs();
  5922. /* Decode completed images in a short batch instead of one per pass.
  5923. * A pass used to decode one image and then sleep 10 ms, so a page of
  5924. * small icons trickled in at the decode rate. The budget keeps a
  5925. * single huge JPEG from monopolising the UI while small images
  5926. * finish together. */
  5927. t0 = u_ticks_ms();
  5928. for (i = 0; i < FETCH_WORKERS; i++) {
  5929. if (!fetch_workers[i].busy)
  5930. continue;
  5931. if (preload_finish_worker(&fetch_workers[i]) &&
  5932. u_ticks_ms() - t0 >= BR_IMG_DECODE_BUDGET_MS)
  5933. break;
  5934. }
  5935. if (preload_active && preload_node >= doc.nnode &&
  5936. preload_active_jobs() == 0) {
  5937. preload_active = 0;
  5938. if (preload_pending)
  5939. preload_scroll = page_scroll.offset;
  5940. else
  5941. preload_pending = 0;
  5942. /* Keep the now idle helpers and their connections; a later
  5943. * navigation reuses them. They exit after ten idle seconds,
  5944. * and losing window focus stops them at once. */
  5945. if (img_repaint_pending) {
  5946. img_repaint_pending = 0;
  5947. ngui_invalidate(&ui);
  5948. }
  5949. img_stats_report();
  5950. set_status(post_status_text, post_status_error, post_status_ttl);
  5951. ngui_invalidate(&ui);
  5952. }
  5953. }
  5954. /* Set by navigate() when it turned a typed bare host into https://; the next
  5955. * load_page() consumes it and may retry over http. */
  5956. static int nav_https_upgraded;
  5957. /* Errors that mean "https is not served here" rather than "the site is
  5958. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  5959. static int https_fallback_error(int e)
  5960. {
  5961. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  5962. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  5963. e == UHTTP_ERR_RESET;
  5964. }
  5965. static void history_push(const char *url)
  5966. {
  5967. if (!url || !url[0])
  5968. return;
  5969. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  5970. s_eq(history[hist_pos], url))
  5971. return;
  5972. if (hist_len > 0 && hist_pos + 1 < hist_len)
  5973. hist_len = hist_pos + 1;
  5974. if (hist_len < BR_HISTORY) {
  5975. s_copy(history[hist_len], url, BR_URL_MAX);
  5976. hist_pos = hist_len;
  5977. hist_len++;
  5978. } else {
  5979. int i;
  5980. for (i = 1; i < BR_HISTORY; i++)
  5981. s_copy(history[i - 1], history[i], BR_URL_MAX);
  5982. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  5983. hist_pos = BR_HISTORY - 1;
  5984. }
  5985. }
  5986. static void load_page(const char *url, int local, int push)
  5987. {
  5988. unsigned char *body = 0;
  5989. unsigned int len = 0;
  5990. int truncated = 0;
  5991. struct img_info image_info;
  5992. char ctype[64];
  5993. char final[BR_URL_MAX];
  5994. char err[80];
  5995. const char *detail = 0;
  5996. const char *post = pending_post_is ? pending_post : 0;
  5997. unsigned int post_len = pending_post_len;
  5998. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  5999. /* Phase timings for the status line: where a slow load spends it. */
  6000. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  6001. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  6002. int upgraded = nav_https_upgraded;
  6003. int retried = 0;
  6004. int rv;
  6005. nav_https_upgraded = 0;
  6006. final[0] = '\0';
  6007. pending_post_len = 0;
  6008. pending_post_is = 0;
  6009. cancel_fetch = 0;
  6010. preload_active = 0;
  6011. preload_pending = 0;
  6012. fetch_workers_prepare_nav(url);
  6013. js_browser_stop();
  6014. js_last_status[0] = '\0';
  6015. js_last_error = 0;
  6016. heap_clear();
  6017. image_reset();
  6018. form_reset_state();
  6019. layout_valid = 0;
  6020. page_scroll.offset = 0;
  6021. page_scroll.dragging = 0;
  6022. page_title[0] = '\0';
  6023. page_loading = 1;
  6024. page_is_local = local;
  6025. s_copy(page_url, url, sizeof(page_url));
  6026. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  6027. url_in.len = s_len(url_in.text);
  6028. url_in.cursor = url_in.len;
  6029. url_in.scroll = 0;
  6030. ngui_set_focus(&ui, 0);
  6031. if (final[0])
  6032. final[0] = '\0';
  6033. if (push)
  6034. history_push(url);
  6035. set_status("Loading...", 0, 0);
  6036. ngui_invalidate(&ui);
  6037. /* heap_clear() detaches the fonts, so attach them again before the
  6038. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  6039. if (heap_start() != 0) {
  6040. show_error("Out of memory", "Cannot allocate the page buffer");
  6041. return;
  6042. }
  6043. br_parse_plain(&doc, "", 0); /* blank while loading */
  6044. ngui_font_attach(&ui);
  6045. redraw_now();
  6046. browser_rules_alloc();
  6047. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  6048. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  6049. &truncated, post, post_len);
  6050. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  6051. fetch_last_error == UHTTP_ERR_DNS) {
  6052. /* A busy previous page can leave the receiver ring full just
  6053. * long enough to lose a DNS reply. Tear the old helpers down
  6054. * and try once more before giving up. */
  6055. retried = 1;
  6056. fetch_workers_stop_all();
  6057. u_sleep_ms(500);
  6058. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  6059. sizeof(ctype), final, sizeof(final), err,
  6060. sizeof(err), &truncated, post, post_len);
  6061. }
  6062. if (rv == FETCH_ABORT)
  6063. return;
  6064. t_fetch = u_ticks_ms() - t_start;
  6065. /* Capture the page timing before CSS/script/image fetches overwrite the
  6066. * shared fetch_meta block. */
  6067. if (rv == 0 && !local) {
  6068. page_open_ms = fetch_meta.open_ms;
  6069. page_first_ms = fetch_meta.first_ms;
  6070. page_total_ms = fetch_meta.total_ms;
  6071. }
  6072. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  6073. https_fallback_error(fetch_last_error)) {
  6074. char http_url[BR_URL_MAX];
  6075. unsigned int n = 0;
  6076. s_append(http_url, &n, "http://", sizeof(http_url));
  6077. s_append(http_url, &n, url + 8, sizeof(http_url));
  6078. /* Replace the https entry instead of adding a second one. */
  6079. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  6080. s_eq(history[hist_pos], url))
  6081. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  6082. load_page(http_url, 0, 0);
  6083. return;
  6084. }
  6085. if (rv != 0) {
  6086. detail = err;
  6087. show_error("Cannot load this page", detail);
  6088. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  6089. url_in.len = s_len(url_in.text);
  6090. url_in.cursor = url_in.len;
  6091. url_in.scroll = 0;
  6092. return;
  6093. }
  6094. if (!local)
  6095. origin_cache_learn(url, final[0] ? final : url);
  6096. page_is_local = local;
  6097. if (final[0]) {
  6098. s_copy(page_url, final, sizeof(page_url));
  6099. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  6100. url_in.len = s_len(url_in.text);
  6101. url_in.cursor = url_in.len;
  6102. url_in.scroll = 0;
  6103. }
  6104. if (contains_ci(ctype, "text/plain")) {
  6105. br_parse_plain(&doc, (const char *)body, len);
  6106. } else if (contains_ci(ctype, "image/") ||
  6107. (!contains_ci(ctype, "text/html") &&
  6108. img_sniff(body, len, &image_info) == 0)) {
  6109. unsigned int node = br_parse_image_doc(&doc, page_url);
  6110. if (node)
  6111. decode_direct_image(body, len, node);
  6112. s_copy(page_title, "Image", sizeof(page_title));
  6113. } else {
  6114. br_set_viewport(ui.w);
  6115. t_mark = u_ticks_ms();
  6116. br_parse(&doc, (const char *)body, len);
  6117. t_parse = u_ticks_ms() - t_mark;
  6118. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  6119. sizeof(page_title));
  6120. t_mark = u_ticks_ms();
  6121. if (load_stylesheets() == FETCH_ABORT)
  6122. return;
  6123. t_css = u_ticks_ms() - t_mark;
  6124. if (pending_action)
  6125. return;
  6126. }
  6127. preload_begin();
  6128. page_loading = 0;
  6129. hist_visit(page_url, page_title);
  6130. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  6131. url_in.len = s_len(url_in.text);
  6132. url_in.cursor = url_in.len;
  6133. url_in.scroll = 0;
  6134. ngui_set_focus(&ui, 0);
  6135. /* Paint the parsed page before fetching/running scripts. A slow
  6136. * remote <script src> then does not hide the page behind the loading
  6137. * screen; the fetch helper pumps this UI while it waits. */
  6138. set_status("Loading scripts...", 0, 0);
  6139. t_mark = u_ticks_ms();
  6140. redraw_now();
  6141. t_paint = u_ticks_ms() - t_mark;
  6142. /* Start one image download before the scripts. The other workers
  6143. * fetch the external script bodies in parallel, and the remaining
  6144. * images start as soon as the script phase ends. */
  6145. preload_max_jobs = 1;
  6146. preload_fill_jobs();
  6147. preload_wait = 0;
  6148. t_mark = u_ticks_ms();
  6149. run_page_scripts();
  6150. t_js = u_ticks_ms() - t_mark;
  6151. preload_max_jobs = FETCH_WORKERS;
  6152. if (pending_action)
  6153. return;
  6154. post_status_text[0] = '\0';
  6155. post_status_error = 0;
  6156. post_status_ttl = 0;
  6157. if (js_last_status[0]) {
  6158. s_copy(post_status_text, js_last_status,
  6159. sizeof(post_status_text));
  6160. post_status_error = js_last_error;
  6161. post_status_ttl = 8000;
  6162. } else if (truncated) {
  6163. s_copy(post_status_text, "Page truncated at the buffer limit",
  6164. sizeof(post_status_text));
  6165. post_status_ttl = 6000;
  6166. } else if (doc.truncated) {
  6167. s_copy(post_status_text, "Page truncated by the parser",
  6168. sizeof(post_status_text));
  6169. post_status_ttl = 6000;
  6170. } else if (page_total_ms) {
  6171. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  6172. * paint 220, js 1750" -- the phases of this load. */
  6173. unsigned int n = 0;
  6174. static const char *const names[] = {
  6175. ", parse ", ", css ", ", paint ", ", js "
  6176. };
  6177. unsigned int vals[4];
  6178. int k;
  6179. vals[0] = t_parse;
  6180. vals[1] = t_css;
  6181. vals[2] = t_paint;
  6182. vals[3] = t_js;
  6183. (void)page_first_ms;
  6184. if (starts_with(page_url, "https://"))
  6185. s_append(post_status_text, &n,
  6186. "HTTPS (not verified), ",
  6187. sizeof(post_status_text));
  6188. s_append(post_status_text, &n, "Loaded in ",
  6189. sizeof(post_status_text));
  6190. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  6191. sizeof(post_status_text));
  6192. s_append(post_status_text, &n, " ms: page ",
  6193. sizeof(post_status_text));
  6194. s_append_dec(post_status_text, &n, t_fetch,
  6195. sizeof(post_status_text));
  6196. s_append(post_status_text, &n, " (headers ",
  6197. sizeof(post_status_text));
  6198. s_append_dec(post_status_text, &n, page_open_ms,
  6199. sizeof(post_status_text));
  6200. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  6201. for (k = 0; k < 4; k++) {
  6202. s_append(post_status_text, &n, names[k],
  6203. sizeof(post_status_text));
  6204. s_append_dec(post_status_text, &n, vals[k],
  6205. sizeof(post_status_text));
  6206. }
  6207. post_status_ttl = 12000;
  6208. } else if (starts_with(page_url, "https://")) {
  6209. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  6210. sizeof(post_status_text));
  6211. post_status_ttl = 6000;
  6212. }
  6213. set_status(post_status_text, post_status_error, post_status_ttl);
  6214. ngui_invalidate(&ui);
  6215. }
  6216. static void load_home(int push)
  6217. {
  6218. pending_post_len = 0;
  6219. pending_post_is = 0;
  6220. cancel_fetch = 0;
  6221. preload_active = 0;
  6222. preload_pending = 0;
  6223. js_browser_stop();
  6224. js_last_status[0] = '\0';
  6225. js_last_error = 0;
  6226. heap_clear();
  6227. image_reset();
  6228. form_reset_state();
  6229. layout_valid = 0;
  6230. page_scroll.offset = 0;
  6231. page_scroll.dragging = 0;
  6232. page_loading = 1;
  6233. page_is_local = 0;
  6234. s_copy(page_url, "about:home", sizeof(page_url));
  6235. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  6236. url_in.len = s_len(url_in.text);
  6237. url_in.cursor = url_in.len;
  6238. url_in.scroll = 0;
  6239. ngui_set_focus(&ui, 0);
  6240. if (push)
  6241. history_push(page_url);
  6242. ngui_invalidate(&ui);
  6243. /* See load_page(): reattach the fonts before the first redraw. */
  6244. if (heap_start() != 0) {
  6245. show_error("Out of memory", "Cannot allocate the browser heap");
  6246. return;
  6247. }
  6248. br_parse_plain(&doc, "", 0);
  6249. ngui_font_attach(&ui);
  6250. redraw_now();
  6251. browser_rules_alloc();
  6252. {
  6253. static const char home[] =
  6254. "<html><head><title>NebOS Browser</title><style>"
  6255. "body { margin: 10px; color: #e4e6f0; }"
  6256. "h1 { color: #7fb0ff; }"
  6257. ".box { background-color: #262b3a; margin: 12px; "
  6258. "padding: 10px; }"
  6259. "a { color: #7fb0ff; }"
  6260. "pre { background-color: #32384a; }"
  6261. "</style></head><body>"
  6262. "<h1>NebOS Browser</h1>"
  6263. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  6264. "shared HTTP client and the image library.</p>"
  6265. "<div class=\"box\"><b>Try:</b>"
  6266. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  6267. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  6268. "<li><a href=\"/floppy1/JS.HTM\">/"
  6269. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  6270. "<li><a href=\"http://10.0.2.2:8000/\">"
  6271. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  6272. "<li><a href=\"https://example.com/\">"
  6273. "https://example.com/</a> (TLS, not verified)</li>"
  6274. "</ul></div>"
  6275. "<p>Type a URL in the bar above. Esc closes the "
  6276. "window, Ctrl+L focuses the address bar.</p>"
  6277. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  6278. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  6279. "</body></html>";
  6280. br_set_viewport(ui.w);
  6281. br_parse(&doc, home, sizeof(home) - 1);
  6282. br_parse_inline_css(&doc);
  6283. br_reset_styles(&doc);
  6284. s_copy(page_title, doc.title, sizeof(page_title));
  6285. }
  6286. post_status_text[0] = '\0';
  6287. post_status_error = 0;
  6288. post_status_ttl = 0;
  6289. page_loading = 0;
  6290. set_status("", 0, 0);
  6291. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  6292. url_in.len = s_len(url_in.text);
  6293. url_in.cursor = url_in.len;
  6294. url_in.scroll = 0;
  6295. ngui_set_focus(&ui, 0);
  6296. ngui_invalidate(&ui);
  6297. }
  6298. /* Extensions the browser opens from the local filesystem. A dotted input
  6299. * with one of these still resolves relative to the cwd. */
  6300. static int local_file_ext(const char *s)
  6301. {
  6302. static const char *const exts[] = {
  6303. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  6304. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  6305. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  6306. "cfg", "conf", 0
  6307. };
  6308. unsigned int i = 0, start = 0, len = 0, e;
  6309. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  6310. s[i] != '#') {
  6311. if (s[i] == '.') {
  6312. start = i + 1;
  6313. len = 0;
  6314. } else if (start) {
  6315. len++;
  6316. }
  6317. i++;
  6318. }
  6319. if (!len)
  6320. return 0;
  6321. for (e = 0; exts[e]; e++) {
  6322. const char *x = exts[e];
  6323. unsigned int xn = s_len(x), k;
  6324. if (xn != len)
  6325. continue;
  6326. for (k = 0; k < len; k++) {
  6327. char a = s[start + k];
  6328. if (a >= 'A' && a <= 'Z')
  6329. a = (char)(a - 'A' + 'a');
  6330. if (a != x[k])
  6331. break;
  6332. }
  6333. if (k == len)
  6334. return 1;
  6335. }
  6336. return 0;
  6337. }
  6338. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  6339. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  6340. * Enter to the first network request. */
  6341. static int looks_like_host(const char *s)
  6342. {
  6343. unsigned int i = 0;
  6344. int dot = 0;
  6345. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  6346. s[i] != ':') {
  6347. char c = s[i];
  6348. if (c == '.') {
  6349. dot = 1;
  6350. } else if (!((c >= 'a' && c <= 'z') ||
  6351. (c >= 'A' && c <= 'Z') ||
  6352. (c >= '0' && c <= '9') ||
  6353. c == '-' || c == '_')) {
  6354. return 0;
  6355. }
  6356. i++;
  6357. }
  6358. return dot && i > 0 && !local_file_ext(s);
  6359. }
  6360. static void load_remote(const char *url, int push)
  6361. {
  6362. char canon[BR_URL_MAX];
  6363. s_copy(canon, url, sizeof(canon));
  6364. origin_cache_apply(canon, sizeof(canon));
  6365. load_page(canon, 0, push);
  6366. }
  6367. static void navigate(const char *input, int push)
  6368. {
  6369. char target[BR_URL_MAX];
  6370. char *t;
  6371. if (!input)
  6372. return;
  6373. ctx_open = 0;
  6374. dl_panel_open = 0;
  6375. s_copy(target, input, sizeof(target));
  6376. t = trim(target);
  6377. if (!t[0])
  6378. return;
  6379. if (s_eq(t, "about:home")) {
  6380. load_home(push);
  6381. return;
  6382. }
  6383. if (starts_with(t, "file://")) {
  6384. make_abs_local(t + 7, target, sizeof(target));
  6385. load_page(target, 1, push);
  6386. return;
  6387. }
  6388. if (is_http(t)) {
  6389. load_remote(t, push);
  6390. return;
  6391. }
  6392. if (t[0] == '/') {
  6393. make_abs_local(t, target, sizeof(target));
  6394. load_page(target, 1, push);
  6395. return;
  6396. }
  6397. if (!looks_like_host(t)) {
  6398. struct sys_stat st;
  6399. if (u_stat(t, &st) == 0 && !st.is_dir) {
  6400. make_abs_local(t, target, sizeof(target));
  6401. load_page(target, 1, push);
  6402. return;
  6403. }
  6404. }
  6405. {
  6406. /* A typed bare host tries https first: nearly every site
  6407. * redirects http -> https anyway, and that hop costs a whole
  6408. * extra connection. load_page() falls back to http when the
  6409. * https connection itself fails. */
  6410. char with_scheme[BR_URL_MAX];
  6411. unsigned int n = 0;
  6412. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  6413. s_append(with_scheme, &n, t, sizeof(with_scheme));
  6414. nav_https_upgraded = 1;
  6415. load_remote(with_scheme, push);
  6416. }
  6417. }
  6418. /* ---- layout ---- */
  6419. static struct ufont_face *face_for(unsigned int family, int bold, int italic)
  6420. {
  6421. unsigned int id;
  6422. if (!family || family > BR_MAX_FACES)
  6423. return 0;
  6424. id = font_pick[family - 1][(bold ? 2 : 0) | (italic ? 1 : 0)];
  6425. return id ? font_faces[id - 1] : 0;
  6426. }
  6427. static struct ufont_face *style_face(const struct br_style *st)
  6428. {
  6429. return st ? face_for(st->font_face, st->bold, st->italic) : 0;
  6430. }
  6431. static struct ufont_face *run_face(const struct lay_run *r)
  6432. {
  6433. return face_for(r->font_face, r->bold, r->italic);
  6434. }
  6435. static unsigned int face_text_width(struct ngui *gui,
  6436. const struct br_style *st,
  6437. const char *s, unsigned int n)
  6438. {
  6439. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  6440. st->bold, st->italic, st->mono);
  6441. }
  6442. static int face_line_height(struct ngui *gui, const struct br_style *st)
  6443. {
  6444. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  6445. st->mono);
  6446. }
  6447. static unsigned int run_text_width(struct ngui *gui,
  6448. const struct lay_run *r,
  6449. const char *s, unsigned int n)
  6450. {
  6451. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  6452. r->bold, r->italic, r->mono);
  6453. }
  6454. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  6455. {
  6456. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  6457. r->mono);
  6458. }
  6459. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  6460. {
  6461. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  6462. }
  6463. static struct br_style base_style(void)
  6464. {
  6465. struct br_style s = { 0 };
  6466. s.color = ui.theme.text;
  6467. s.bg = ui.theme.bg;
  6468. s.has_bg = 0;
  6469. for (int i = 0; i < 4; i++) {
  6470. s.border_c[i] = 0;
  6471. s.border_w[i] = 0;
  6472. s.border_s[i] = BR_BORDER_SOLID;
  6473. }
  6474. s.font_px = 16;
  6475. s.bold = 0;
  6476. s.italic = 0;
  6477. s.mono = 0;
  6478. s.underline = 0;
  6479. s.strike = 0;
  6480. s.overline = 0;
  6481. s.align = BR_ALIGN_LEFT;
  6482. s.display = BR_DISPLAY_BLOCK;
  6483. s.no_bullet = 0;
  6484. s.list_style = BR_LIST_AUTO;
  6485. s.uppercase = 0;
  6486. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  6487. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  6488. s.width = s.max_width = s.min_width = 0;
  6489. s.height = s.min_height = s.max_height = 0;
  6490. s.box_sizing = 0;
  6491. s.ml_auto = s.mr_auto = 0;
  6492. s.line_h_pct = 0;
  6493. s.line_h_px = 0;
  6494. s.mt = s.mb = s.ml = s.mr = 0;
  6495. s.pt = s.pb = s.pl = s.pr = 0;
  6496. return s;
  6497. }
  6498. /* The style node 0's children inherit. Node 0 is the first parsed node:
  6499. * a minified page that starts `<!doctype html><html ...>` makes it the
  6500. * <html> element itself, and the layout walks only its children, so its
  6501. * own cascade (html { color; font } -- Docusaurus/Infima put the page
  6502. * colour and font there) used to be skipped and the theme defaults showed
  6503. * through. Only inherited properties are taken: the root's box (margins,
  6504. * display, background) is not a container style for its children here. */
  6505. static struct br_style root_style(void)
  6506. {
  6507. struct br_style base = base_style(), st;
  6508. if (!doc.nnode || doc.nodes[doc.root].type != BR_NODE_ELEM ||
  6509. doc.nodes[doc.root].tag != BR_TAG_HTML)
  6510. return base;
  6511. br_style_for(&doc, doc.root, &base, &st);
  6512. base.color = st.color;
  6513. base.font_px = st.font_px;
  6514. base.bold = st.bold;
  6515. base.italic = st.italic;
  6516. base.mono = st.mono;
  6517. base.font_face = st.font_face;
  6518. base.align = st.align;
  6519. base.line_h_pct = st.line_h_pct;
  6520. base.line_h_px = st.line_h_px;
  6521. base.nowrap = st.nowrap;
  6522. base.uppercase = st.uppercase;
  6523. base.cursor = st.cursor;
  6524. base.vis_hidden = st.vis_hidden;
  6525. base.fill_mode = st.fill_mode;
  6526. base.fill = st.fill;
  6527. base.stroke_mode = st.stroke_mode;
  6528. base.stroke = st.stroke;
  6529. base.stroke_w = st.stroke_w;
  6530. base.fill_evenodd = st.fill_evenodd;
  6531. return base;
  6532. }
  6533. /* Resolve a margin/padding raw value. Percentages use the containing
  6534. * block width for all four sides, as CSS specifies. */
  6535. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  6536. {
  6537. if (unit == 1)
  6538. return base * v / 10000;
  6539. if (unit == 2)
  6540. return st->font_px * v / 100;
  6541. if (unit == 3)
  6542. return (int)br_root_font_px() * v / 100;
  6543. if (unit == 4)
  6544. return 0;
  6545. return v;
  6546. }
  6547. static int mp_px(const struct br_style *st, int side, int base)
  6548. {
  6549. int raw;
  6550. switch (side) {
  6551. case 0: raw = st->mt; break;
  6552. case 1: raw = st->mr; break;
  6553. case 2: raw = st->mb; break;
  6554. case 3: raw = st->ml; break;
  6555. case 4: raw = st->pt; break;
  6556. case 5: raw = st->pr; break;
  6557. case 6: raw = st->pb; break;
  6558. default: raw = st->pl; break;
  6559. }
  6560. if (st->mp_unit[side] == 5)
  6561. return base * raw / 100 + st->mp_calc_px[side];
  6562. return css_mp_px(st, raw, st->mp_unit[side], base);
  6563. }
  6564. static int style_width_px(const struct br_style *st, int base)
  6565. {
  6566. if (st->width_kind == 1)
  6567. return st->width;
  6568. if (st->width_kind == 2)
  6569. return base * (int)st->width / 100;
  6570. if (st->width_kind == 3)
  6571. return base * st->width_calc_pct / 100 + st->width_calc_px;
  6572. return 0;
  6573. }
  6574. static int style_height_px(const struct br_style *st, int base)
  6575. {
  6576. if (st->height_kind == 1)
  6577. return st->height;
  6578. if (st->height_kind == 2)
  6579. return base * (int)st->height / 100;
  6580. if (st->height_kind == 3)
  6581. return base * st->height_calc_pct / 100 + st->height_calc_px;
  6582. return 0;
  6583. }
  6584. static int css_size(unsigned char kind, int val, int base)
  6585. {
  6586. if (kind == 1)
  6587. return val;
  6588. if (kind == 2)
  6589. return base * val / 100;
  6590. return -1;
  6591. }
  6592. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  6593. int thick, int horizontal, unsigned short color,
  6594. unsigned char style)
  6595. {
  6596. int pos;
  6597. if (len <= 0 || thick <= 0)
  6598. return;
  6599. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  6600. if (horizontal)
  6601. ngui_fill_rect(ui, (struct ngui_rect){
  6602. x, y, len, thick}, color);
  6603. else
  6604. ngui_fill_rect(ui, (struct ngui_rect){
  6605. x, y, thick, len}, color);
  6606. return;
  6607. }
  6608. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  6609. int seg = len - pos;
  6610. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  6611. seg = style == BR_BORDER_DASHED ? 4 : 2;
  6612. if (horizontal)
  6613. ngui_fill_rect(ui, (struct ngui_rect){
  6614. x + pos, y, seg, thick}, color);
  6615. else
  6616. ngui_fill_rect(ui, (struct ngui_rect){
  6617. x, y + pos, thick, seg}, color);
  6618. }
  6619. }
  6620. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  6621. const struct br_style *st)
  6622. {
  6623. int top = st->border_w[0], right = st->border_w[1];
  6624. int bottom = st->border_w[2], left = st->border_w[3];
  6625. if (r.w <= 0 || r.h <= 0)
  6626. return;
  6627. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  6628. int i;
  6629. for (i = 0; i < 4; i++)
  6630. if (st->border_w[i] && !st->border_t[i]) {
  6631. ngui_fill_rect(ui, r, st->border_c[i]);
  6632. break;
  6633. }
  6634. return;
  6635. }
  6636. if (top && !st->border_t[0])
  6637. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  6638. st->border_c[0], st->border_s[0]);
  6639. if (bottom && !st->border_t[2])
  6640. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  6641. st->border_c[2], st->border_s[2]);
  6642. if (left && !st->border_t[3])
  6643. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  6644. left, 0, st->border_c[3], st->border_s[3]);
  6645. if (right && !st->border_t[1])
  6646. draw_border_side(ui, r.x + r.w - right, r.y + top,
  6647. r.h - top - bottom, right, 0,
  6648. st->border_c[1], st->border_s[1]);
  6649. }
  6650. static void transform_origin(const struct br_style *st, int w, int h,
  6651. int *ox, int *oy)
  6652. {
  6653. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  6654. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  6655. }
  6656. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  6657. unsigned int a)
  6658. {
  6659. unsigned int dr, dg, db, sr, sg, sb;
  6660. if (a >= 255)
  6661. return s;
  6662. dr = (d >> 11) & 31;
  6663. dg = (d >> 5) & 63;
  6664. db = d & 31;
  6665. sr = (s >> 11) & 31;
  6666. sg = (s >> 5) & 63;
  6667. sb = s & 31;
  6668. dr = (dr * (255 - a) + sr * a) / 255;
  6669. dg = (dg * (255 - a) + sg * a) / 255;
  6670. db = (db * (255 - a) + sb * a) / 255;
  6671. return (unsigned short)((dr << 11) | (dg << 5) | db);
  6672. }
  6673. /* Paint a solid box through scale()/rotate() around transform-origin. This
  6674. * transforms the element's own background box; text and descendants keep
  6675. * their layout (documented approximation). */
  6676. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  6677. unsigned short color,
  6678. const struct br_style *st)
  6679. {
  6680. double sx = st->scale_x / 100.0;
  6681. double sy = st->scale_y / 100.0;
  6682. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  6683. double c = cos(th), sn = sin(th);
  6684. int ox, oy, minx, miny, maxx, maxy, x, y;
  6685. double ax, ay;
  6686. double px[4], py[4];
  6687. int cx1, cy1, cx2, cy2, i;
  6688. if (sx == 0)
  6689. sx = 0.01;
  6690. if (sy == 0)
  6691. sy = 0.01;
  6692. transform_origin(st, box.w, box.h, &ox, &oy);
  6693. ax = box.x + ox;
  6694. ay = box.y + oy;
  6695. px[0] = -ox; py[0] = -oy;
  6696. px[1] = box.w - ox; py[1] = -oy;
  6697. px[2] = box.w - ox; py[2] = box.h - oy;
  6698. px[3] = -ox; py[3] = box.h - oy;
  6699. minx = miny = 1000000;
  6700. maxx = maxy = -1000000;
  6701. for (i = 0; i < 4; i++) {
  6702. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  6703. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  6704. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  6705. if (dx < minx) minx = dx;
  6706. if (dx > maxx) maxx = dx;
  6707. if (dy < miny) miny = dy;
  6708. if (dy > maxy) maxy = dy;
  6709. }
  6710. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  6711. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  6712. cx2 = page_rect.x + page_rect.w - 12;
  6713. cy2 = page_rect.y + page_rect.h;
  6714. if (cx2 > gui->w) cx2 = gui->w;
  6715. if (cy2 > gui->h) cy2 = gui->h;
  6716. if (minx < cx1) minx = cx1;
  6717. if (miny < cy1) miny = cy1;
  6718. if (maxx > cx2 - 1) maxx = cx2 - 1;
  6719. if (maxy > cy2 - 1) maxy = cy2 - 1;
  6720. for (y = miny; y <= maxy; y++) {
  6721. for (x = minx; x <= maxx; x++) {
  6722. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  6723. double rx = dx * c + dy * sn;
  6724. double ry = -dx * sn + dy * c;
  6725. double bx = rx / sx + ox;
  6726. double by = ry / sy + oy;
  6727. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  6728. gui->px[y * gui->w + x] = color;
  6729. }
  6730. }
  6731. }
  6732. static void draw_image_transformed(struct ngui *gui,
  6733. const struct img_image *im,
  6734. int x, int y, int w, int h,
  6735. int sx100, int sy100, int rot100,
  6736. int origin_x, int origin_y,
  6737. int origin_x_kind, int origin_y_kind)
  6738. {
  6739. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  6740. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  6741. double c = cos(th), sn = sin(th);
  6742. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  6743. double ax, ay;
  6744. double bx[4], by[4];
  6745. int cx1, cy1, cx2, cy2;
  6746. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  6747. return;
  6748. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  6749. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  6750. ax = x + ox;
  6751. ay = y + oy;
  6752. bx[0] = -ox; by[0] = -oy;
  6753. bx[1] = w - ox; by[1] = -oy;
  6754. bx[2] = w - ox; by[2] = h - oy;
  6755. bx[3] = -ox; by[3] = h - oy;
  6756. minx = miny = 1000000;
  6757. maxx = maxy = -1000000;
  6758. for (i = 0; i < 4; i++) {
  6759. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  6760. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  6761. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  6762. if (dx < minx) minx = dx;
  6763. if (dx > maxx) maxx = dx;
  6764. if (dy < miny) miny = dy;
  6765. if (dy > maxy) maxy = dy;
  6766. }
  6767. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  6768. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  6769. cx2 = page_rect.x + page_rect.w - 12;
  6770. cy2 = page_rect.y + page_rect.h;
  6771. if (cx2 > gui->w) cx2 = gui->w;
  6772. if (cy2 > gui->h) cy2 = gui->h;
  6773. if (minx < cx1) minx = cx1;
  6774. if (miny < cy1) miny = cy1;
  6775. if (maxx > cx2 - 1) maxx = cx2 - 1;
  6776. if (maxy > cy2 - 1) maxy = cy2 - 1;
  6777. for (py = miny; py <= maxy; py++) {
  6778. for (px = minx; px <= maxx; px++) {
  6779. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  6780. double rx = dx * c + dy * sn;
  6781. double ry = -dx * sn + dy * c;
  6782. double fx = rx / sx + ox;
  6783. double fy = ry / sy + oy;
  6784. int ix, iy;
  6785. unsigned int si, a;
  6786. unsigned short src;
  6787. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  6788. continue;
  6789. ix = (int)(fx * (double)im->w / w);
  6790. iy = (int)(fy * (double)im->h / h);
  6791. if (ix < 0 || ix >= (int)im->w ||
  6792. iy < 0 || iy >= (int)im->h)
  6793. continue;
  6794. si = (unsigned int)iy * im->w + (unsigned int)ix;
  6795. src = im->px[si];
  6796. a = im->alpha ? im->alpha[si] : 255;
  6797. gui->px[py * gui->w + px] =
  6798. a >= 255 ? src :
  6799. blend_rgb565(gui->px[py * gui->w + px],
  6800. src, a);
  6801. }
  6802. }
  6803. }
  6804. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  6805. unsigned int node, const struct br_style *st);
  6806. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  6807. * first and every pixel outside a corner's arc is restored afterwards. */
  6808. #define BG_ROUND_MAX 64
  6809. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  6810. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  6811. unsigned int node, const struct br_style *st,
  6812. int rtl, int rtr, int rbr, int rbl)
  6813. {
  6814. struct ngui *ui = l->ui;
  6815. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  6816. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  6817. if (ui->nclip > 0)
  6818. clip = ui->clip[ui->nclip - 1];
  6819. for (c = 0; c < 4; c++) {
  6820. if (r[c] > BG_ROUND_MAX)
  6821. r[c] = BG_ROUND_MAX;
  6822. if (r[c] > box.w / 2)
  6823. r[c] = box.w / 2;
  6824. if (r[c] > box.h / 2)
  6825. r[c] = box.h / 2;
  6826. }
  6827. for (c = 0; c < 4; c++) {
  6828. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  6829. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  6830. for (dy = 0; dy < r[c]; dy++)
  6831. for (dx = 0; dx < r[c]; dx++) {
  6832. int px = ox + dx, py = oy + dy;
  6833. if (px >= clip.x && py >= clip.y &&
  6834. px < clip.x + clip.w && py < clip.y + clip.h)
  6835. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  6836. ui->px[py * ui->w + px];
  6837. }
  6838. }
  6839. draw_bg_image(l, box, node, st);
  6840. for (c = 0; c < 4; c++) {
  6841. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  6842. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  6843. /* arc centre, in corner-square coordinates */
  6844. int cx = (c == 1 || c == 2) ? 0 : r[c];
  6845. int cy = (c >= 2) ? 0 : r[c];
  6846. for (dy = 0; dy < r[c]; dy++)
  6847. for (dx = 0; dx < r[c]; dx++) {
  6848. int px = ox + dx, py = oy + dy;
  6849. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  6850. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  6851. continue;
  6852. if (px >= clip.x && py >= clip.y &&
  6853. px < clip.x + clip.w && py < clip.y + clip.h)
  6854. ui->px[py * ui->w + px] =
  6855. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  6856. }
  6857. }
  6858. }
  6859. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  6860. unsigned int node, const struct br_style *st)
  6861. {
  6862. struct br_image *bi;
  6863. struct img_blit b;
  6864. int tw, th, x, y, rep_x, rep_y, posx, posy;
  6865. unsigned int scale = 65536;
  6866. int legacy, tiles = 0, rows = 0;
  6867. int cx1, cy1, cx2, cy2;
  6868. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  6869. return;
  6870. if (doc.nodes[node].bg_img_index < 0 ||
  6871. doc.nodes[node].bg_img_index >= image_count)
  6872. return;
  6873. bi = &images[doc.nodes[node].bg_img_index];
  6874. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  6875. return;
  6876. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  6877. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  6878. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  6879. if (legacy) {
  6880. scale = ((unsigned int)box.w << 16) / bi->img.w;
  6881. tw = box.w;
  6882. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6883. x = box.x;
  6884. y = box.y;
  6885. rep_x = rep_y = 0;
  6886. } else {
  6887. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  6888. unsigned int sx = ((unsigned int)box.w << 16) /
  6889. bi->img.w;
  6890. unsigned int sy = ((unsigned int)box.h << 16) /
  6891. bi->img.h;
  6892. scale = st->bg_size_kind == 3 ?
  6893. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  6894. } else if (st->bg_size_kind == 1 ||
  6895. st->bg_size_kind == 2) {
  6896. int w = st->bg_size_w;
  6897. int h = st->bg_size_h;
  6898. if (st->bg_size_kind == 2) {
  6899. if (w)
  6900. w = box.w * w / 100;
  6901. if (h)
  6902. h = box.h * h / 100;
  6903. }
  6904. if (w)
  6905. scale = ((unsigned int)w << 16) / bi->img.w;
  6906. else if (h)
  6907. scale = ((unsigned int)h << 16) / bi->img.h;
  6908. }
  6909. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  6910. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6911. if (tw < 1)
  6912. tw = 1;
  6913. if (th < 1)
  6914. th = 1;
  6915. posx = st->bg_pos_x_kind == 1 ?
  6916. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  6917. posy = st->bg_pos_y_kind == 1 ?
  6918. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  6919. x = box.x + posx;
  6920. y = box.y + posy;
  6921. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  6922. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  6923. if (rep_x) {
  6924. int m = (x - box.x) % tw;
  6925. if (m > 0)
  6926. m -= tw;
  6927. x = box.x + m;
  6928. }
  6929. if (rep_y) {
  6930. int m = (y - box.y) % th;
  6931. if (m > 0)
  6932. m -= th;
  6933. y = box.y + m;
  6934. }
  6935. }
  6936. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  6937. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  6938. cx2 = box.x + box.w;
  6939. cy2 = box.y + box.h;
  6940. if (cx2 > page_rect.x + page_rect.w - 12)
  6941. cx2 = page_rect.x + page_rect.w - 12;
  6942. if (cy2 > page_rect.y + page_rect.h)
  6943. cy2 = page_rect.y + page_rect.h;
  6944. if (cx1 >= cx2 || cy1 >= cy2)
  6945. return;
  6946. b.dst = l->ui->px;
  6947. b.dst_w = l->ui->w;
  6948. b.dst_h = l->ui->h;
  6949. b.clip_x = cx1;
  6950. b.clip_y = cy1;
  6951. b.clip_w = cx2 - cx1;
  6952. b.clip_h = cy2 - cy1;
  6953. b.bg = ui.theme.bg;
  6954. b.bg2 = ui.theme.bg;
  6955. b.dst_a = 0;
  6956. {
  6957. struct img_image *src = image_display_get(bi, tw, th);
  6958. int row_x;
  6959. if (!src)
  6960. src = &bi->img;
  6961. b.scale = ((unsigned int)tw << 16) / src->w;
  6962. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  6963. row_x = x;
  6964. for (;;) {
  6965. for (;;) {
  6966. b.x = x;
  6967. b.y = y;
  6968. img_draw(src, &b);
  6969. if (!rep_x || ++tiles > 512)
  6970. break;
  6971. x += tw;
  6972. if (x >= box.x + box.w)
  6973. break;
  6974. }
  6975. if (!rep_y || ++rows > 64)
  6976. break;
  6977. y += th;
  6978. if (y >= box.y + box.h)
  6979. break;
  6980. x = row_x;
  6981. }
  6982. }
  6983. }
  6984. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  6985. int *out_w, int *out_h);
  6986. static void svg_paint_box(struct ngui *ui, unsigned int node,
  6987. const struct br_style *st, int x, int y, int w,
  6988. int h);
  6989. /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
  6990. * RUN_SVG an inline <svg> icon (its node in off), RUN_PBOX an empty
  6991. * ::before/::after box with a background (Infima's menu chevrons). */
  6992. #define RUN_SVG (-3)
  6993. #define RUN_PBOX (-4)
  6994. static int run_width(const struct lay_run *r)
  6995. {
  6996. if (r->img >= 0)
  6997. return r->iw;
  6998. if (r->img == -2 || r->img == RUN_SVG || r->img == RUN_PBOX)
  6999. return r->iw;
  7000. return (int)r->w;
  7001. }
  7002. static void start_line(struct lay *l, const struct br_style *st)
  7003. {
  7004. (void)st;
  7005. if (l->nruns == 0) {
  7006. l->line_y = l->y;
  7007. l->line_h = 0;
  7008. }
  7009. l->line_left = l->left;
  7010. l->line_right = l->right;
  7011. if (l->float_active && l->line_y < l->float_bottom) {
  7012. if (l->float_left > l->line_left)
  7013. l->line_left = l->float_left;
  7014. if (l->float_right < l->line_right)
  7015. l->line_right = l->float_right;
  7016. }
  7017. if (l->line_right < l->line_left + 8)
  7018. l->line_right = l->line_left + 8;
  7019. l->line_x = l->line_left;
  7020. l->run_x = l->line_left;
  7021. }
  7022. static void inline_box_add(const struct lay *l, unsigned int owner, int x,
  7023. int w)
  7024. {
  7025. int y = l->line_y;
  7026. int h = l->line_h ? l->line_h : 16;
  7027. int depth = 0;
  7028. while (owner && owner <= BR_MAX_NODES && depth++ < 16) {
  7029. unsigned int node = owner - 1;
  7030. struct br_layout_box *b = &layout_boxes[node];
  7031. if (b->valid && inline_box_pass[node] == inline_box_pass_id &&
  7032. (inline_box_flush[node] == inline_box_flush_id ||
  7033. inline_box_y[node] < y)) {
  7034. int x1 = b->x + b->w, y1 = b->y + b->h;
  7035. if (x < b->x)
  7036. b->x = x;
  7037. if (y < b->y)
  7038. b->y = y;
  7039. if (x + w > x1)
  7040. x1 = x + w;
  7041. if (y + h > y1)
  7042. y1 = y + h;
  7043. b->w = x1 - b->x;
  7044. b->h = y1 - b->y;
  7045. } else {
  7046. b->x = x;
  7047. b->y = y;
  7048. b->w = w;
  7049. b->h = h;
  7050. b->valid = 1;
  7051. }
  7052. inline_box_pass[node] = inline_box_pass_id;
  7053. inline_box_flush[node] = inline_box_flush_id;
  7054. inline_box_y[node] = y;
  7055. owner = inline_box_parent[node];
  7056. }
  7057. }
  7058. static void flush_line(struct lay *l)
  7059. {
  7060. int total, x, i, vis;
  7061. inline_box_flush_id++;
  7062. if (!l->nruns && l->line_x == l->line_left) {
  7063. l->line_h = 0;
  7064. return;
  7065. }
  7066. total = l->line_x - l->line_left;
  7067. x = l->line_left;
  7068. vis = 1;
  7069. if (l->draw) {
  7070. int lh = l->line_h ? l->line_h : 16;
  7071. vis = l->line_y + lh >= page_rect.y &&
  7072. l->line_y <= page_rect.y + page_rect.h;
  7073. }
  7074. if (l->align == BR_ALIGN_CENTER)
  7075. x += (l->line_right - l->line_left - total) / 2;
  7076. else if (l->align == BR_ALIGN_RIGHT)
  7077. x = l->line_right - total;
  7078. if (x < l->line_left)
  7079. x = l->line_left;
  7080. for (i = 0; i < l->nruns; i++) {
  7081. struct lay_run *r = &l->runs[i];
  7082. int w = run_width(r);
  7083. int ry = l->line_y + r->dy;
  7084. x += r->gap;
  7085. if (l->draw && vis) {
  7086. if (r->form) {
  7087. unsigned int node = r->form - 1;
  7088. struct form_state *fs = form_get(node, 1);
  7089. int hh = r->ih ? r->ih : 20;
  7090. int focused = form_focus == node;
  7091. int disabled = r->form_disabled;
  7092. unsigned short bg = l->ui->theme.panel_alt;
  7093. unsigned short fg = disabled ? 0x8410 : r->color;
  7094. struct ngui_rect box = {x, ry, w, hh};
  7095. if (r->form_kind == FORM_CHECKBOX ||
  7096. r->form_kind == FORM_RADIO) {
  7097. ngui_fill_rect(l->ui, box, bg);
  7098. ngui_frame(l->ui, box,
  7099. focused ? l->ui->theme.accent :
  7100. l->ui->theme.border);
  7101. if (fs && fs->checked) {
  7102. struct ngui_rect dot = {
  7103. x + 4, ry + 4,
  7104. w > 8 ? w - 8 : 1,
  7105. hh > 8 ? hh - 8 : 1
  7106. };
  7107. if (r->form_kind == FORM_RADIO)
  7108. ngui_fill_round_rect(
  7109. l->ui, dot, 4,
  7110. 4, 4, 4,
  7111. l->ui->theme.accent);
  7112. else
  7113. ngui_fill_rect(l->ui,
  7114. dot,
  7115. l->ui->theme.accent);
  7116. }
  7117. } else {
  7118. int editable =
  7119. r->form_kind == FORM_TEXT ||
  7120. r->form_kind == FORM_PASSWORD ||
  7121. r->form_kind == FORM_TEXTAREA;
  7122. int scroll = 0;
  7123. /* Editable fields draw the live value
  7124. * (r->lit is a short copy). */
  7125. static char shown[FORM_VALUE_MAX + 1];
  7126. const char *txt = r->lit;
  7127. unsigned int tl = s_len(r->lit);
  7128. if (editable && fs && fs->len) {
  7129. unsigned int k;
  7130. if (r->form_kind == FORM_PASSWORD) {
  7131. for (k = 0; k < fs->len; k++)
  7132. shown[k] = '*';
  7133. shown[k] = '\0';
  7134. txt = shown;
  7135. } else {
  7136. txt = fs->value;
  7137. }
  7138. tl = fs->len;
  7139. }
  7140. struct br_style fst;
  7141. int author, tx = x + 6, pr = 6;
  7142. style_for_node(node, &fst);
  7143. author = form_author_styled(&fst);
  7144. if (author) {
  7145. /* The page styled the control:
  7146. * its background, border, radius
  7147. * and text colour. */
  7148. form_paint_author(l->ui, box, &fst,
  7149. focused);
  7150. tx = x + fst.border_w[3] +
  7151. mp_px(&fst, 7, w);
  7152. pr = fst.border_w[1] +
  7153. mp_px(&fst, 5, w);
  7154. if (tx < x + 2 && !editable)
  7155. tx = x + 2;
  7156. if (!disabled)
  7157. fg = editable && fs &&
  7158. !fs->len ?
  7159. 0x8410 : fst.color;
  7160. if (!editable) {
  7161. int tw0 = (int)
  7162. run_text_width(l->ui,
  7163. r, txt, tl);
  7164. tx = x + (w - tw0) / 2;
  7165. }
  7166. } else {
  7167. /* The box is drawn in theme colours, so
  7168. * the text is too: the page's CSS colour
  7169. * (dark on a light page) would vanish on
  7170. * the dark field. */
  7171. if (!disabled)
  7172. fg = editable && fs && !fs->len ?
  7173. l->ui->theme.text_dim :
  7174. l->ui->theme.text;
  7175. ngui_fill_rect(l->ui, box, bg);
  7176. ngui_frame(l->ui, box,
  7177. focused ? l->ui->theme.accent :
  7178. l->ui->theme.border);
  7179. }
  7180. /* A value wider than the field shows its
  7181. * tail (where typing happens). */
  7182. if (editable && fs && fs->len &&
  7183. w > (tx - x) + pr) {
  7184. int tw = (int)run_text_width(l->ui,
  7185. r, txt, tl);
  7186. int room = w - (tx - x) - pr;
  7187. if (tw > room)
  7188. scroll = tw - room;
  7189. }
  7190. ngui_push_clip(l->ui, (struct ngui_rect){
  7191. x + 1, ry + 1,
  7192. w > 2 ? w - 2 : 1,
  7193. hh > 2 ? hh - 2 : 1 });
  7194. ngui_text_px_face(l->ui, run_face(r),
  7195. tx - scroll,
  7196. ry + (hh - r->font_px) / 2 - 1,
  7197. txt, tl, fg, r->font_px,
  7198. r->bold, r->italic, r->mono);
  7199. if (focused && fs && editable) {
  7200. int cw = 0;
  7201. if (fs->len && fs->caret)
  7202. cw = (int)run_text_width(
  7203. l->ui, r, txt,
  7204. fs->caret < fs->len ?
  7205. fs->caret : fs->len);
  7206. ngui_fill_rect(l->ui,
  7207. (struct ngui_rect){
  7208. tx + cw - scroll,
  7209. ry + 4, 1,
  7210. hh > 8 ? hh - 8 : 1
  7211. },
  7212. l->ui->theme.accent);
  7213. }
  7214. ngui_pop_clip(l->ui);
  7215. if (r->form_kind == FORM_SELECT) {
  7216. ngui_text_px(l->ui, x + w - 12,
  7217. ry + 2, "v", 1, fg,
  7218. r->font_px, 0, 0, 0);
  7219. }
  7220. }
  7221. } else if (r->img == RUN_PBOX) {
  7222. struct ngui_rect bx = { x, ry, w, r->ih };
  7223. ngui_push_clip(l->ui, bx);
  7224. if (r->pb_has_bg)
  7225. ngui_fill_rect(l->ui, bx, r->pb_bg);
  7226. if (r->pb_img >= 0 && r->pb_img < image_count &&
  7227. images[r->pb_img].state == 1) {
  7228. /* Rotate about the box centre: the
  7229. * image is centred in it here. */
  7230. draw_image_transformed(l->ui,
  7231. &images[r->pb_img].img,
  7232. x + r->pb_x, ry + r->pb_y,
  7233. r->pb_w, r->pb_h,
  7234. r->transform_scale ?
  7235. r->scale_x : 100,
  7236. r->transform_scale ?
  7237. r->scale_y : 100,
  7238. r->transform_scale ?
  7239. r->rotate_x100 : 0,
  7240. 50, 50, 1, 1);
  7241. }
  7242. ngui_pop_clip(l->ui);
  7243. } else if (r->img == RUN_SVG) {
  7244. struct br_style sst;
  7245. style_for_node(r->off, &sst);
  7246. svg_paint_box(l->ui, r->off, &sst, x, ry, w,
  7247. r->ih);
  7248. } else if (r->img == -2) {
  7249. int hh = r->ih ? r->ih : 20;
  7250. ngui_fill_rect(l->ui,
  7251. (struct ngui_rect){x, ry, w, hh},
  7252. l->ui->theme.panel_alt);
  7253. ngui_frame(l->ui,
  7254. (struct ngui_rect){x, ry, w, hh},
  7255. l->ui->theme.border);
  7256. ngui_text_px_face(l->ui, run_face(r),
  7257. x + 6, ry + 2, r->lit,
  7258. s_len(r->lit), r->color,
  7259. r->font_px, r->bold, r->italic,
  7260. r->mono);
  7261. } else if (r->img >= 0) {
  7262. struct br_image *bi = &images[r->img];
  7263. if (bi->state == 1 && r->transform_scale) {
  7264. draw_image_transformed(l->ui, &bi->img,
  7265. x, ry, r->iw, r->ih,
  7266. r->scale_x, r->scale_y,
  7267. r->rotate_x100, r->origin_x,
  7268. r->origin_y, r->origin_x_kind,
  7269. r->origin_y_kind);
  7270. } else if (bi->state == 1) {
  7271. struct img_image *src =
  7272. image_display_get(bi, r->iw, r->ih);
  7273. struct img_blit b;
  7274. if (!src)
  7275. src = &bi->img;
  7276. b.dst = l->ui->px;
  7277. b.dst_w = l->ui->w;
  7278. b.dst_h = l->ui->h;
  7279. b.clip_x = page_rect.x;
  7280. b.clip_y = page_rect.y;
  7281. b.clip_w = page_rect.w - 12;
  7282. b.clip_h = page_rect.h;
  7283. b.x = x;
  7284. b.y = ry;
  7285. b.scale = ((unsigned int)r->iw << 16) /
  7286. src->w;
  7287. b.bg = ui.theme.bg;
  7288. b.bg2 = ui.theme.bg;
  7289. b.dst_a = 0;
  7290. b.flags = src->alpha ?
  7291. IMG_BLIT_OVER_DST : 0;
  7292. img_draw(src, &b);
  7293. }
  7294. } else {
  7295. const char *s = r->has_lit ? r->lit :
  7296. doc.text + r->off;
  7297. unsigned int n = r->has_lit ? s_len(r->lit) :
  7298. r->len;
  7299. ngui_text_px_face(l->ui, run_face(r), x, ry,
  7300. s, n, r->color, r->font_px,
  7301. r->bold, r->italic, r->mono);
  7302. if (r->underline)
  7303. ngui_fill_rect(l->ui,
  7304. (struct ngui_rect){x,
  7305. ry + run_ascent(l->ui, r) + 2,
  7306. w, 1}, r->color);
  7307. if (r->strike)
  7308. ngui_fill_rect(l->ui,
  7309. (struct ngui_rect){x,
  7310. ry + run_ascent(l->ui, r) -
  7311. (r->font_px > 3 ?
  7312. r->font_px / 3 : 1),
  7313. w, 1}, r->color);
  7314. if (r->overline)
  7315. ngui_fill_rect(l->ui,
  7316. (struct ngui_rect){x, ry,
  7317. w, 1}, r->color);
  7318. }
  7319. if (r->form || r->href) {
  7320. if (nhits < HIT_MAX) {
  7321. struct hit *h = &hits[nhits];
  7322. unsigned int target = r->form ?
  7323. r->form - 1 : r->href;
  7324. int hh = (r->form || r->img >= 0 ||
  7325. r->img == RUN_SVG) ?
  7326. r->ih :
  7327. run_line_height(l->ui, r);
  7328. int merge = nhits > 0 &&
  7329. hits[nhits - 1].node == target &&
  7330. hits[nhits - 1].y == ry &&
  7331. hits[nhits - 1].h == hh &&
  7332. x <= hits[nhits - 1].x +
  7333. hits[nhits - 1].w + 2;
  7334. if (merge) {
  7335. struct hit *p = &hits[nhits - 1];
  7336. int end = x + w;
  7337. if (end > p->x + p->w)
  7338. p->w = end - p->x;
  7339. } else {
  7340. h->x = x;
  7341. h->y = ry;
  7342. h->w = w;
  7343. h->h = hh;
  7344. h->node = (unsigned short)target;
  7345. nhits++;
  7346. }
  7347. }
  7348. }
  7349. }
  7350. if (r->box)
  7351. inline_box_add(l, r->box, x, w);
  7352. x += w;
  7353. }
  7354. l->y += l->line_h + 2;
  7355. if (l->float_active && l->y >= l->float_bottom)
  7356. l->float_active = 0;
  7357. l->nruns = 0;
  7358. l->line_x = l->left;
  7359. l->run_x = l->left;
  7360. l->line_left = l->left;
  7361. l->line_right = l->right;
  7362. l->line_h = 0;
  7363. l->space_pending = 0;
  7364. }
  7365. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  7366. const struct br_style *st, unsigned short href,
  7367. const char *lit)
  7368. {
  7369. unsigned int n = lit ? s_len(lit) : len;
  7370. const char *tp = lit ? lit : doc.text + off;
  7371. int w = (int)face_text_width(l->ui, st, tp, n);
  7372. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  7373. flush_line(l);
  7374. if (l->nruns == 0) {
  7375. l->line_y = l->y;
  7376. l->line_h = 0;
  7377. start_line(l, st);
  7378. }
  7379. {
  7380. struct lay_run *r = &l->runs[l->nruns++];
  7381. int gap = l->line_x - l->run_x;
  7382. if (gap < 0)
  7383. gap = 0;
  7384. r->box = l->box_owner;
  7385. r->gap = (unsigned short)gap;
  7386. r->off = off;
  7387. r->len = len;
  7388. r->color = st->color;
  7389. r->href = href;
  7390. r->dy = 0;
  7391. r->has_lit = 0;
  7392. r->form = 0;
  7393. r->form_kind = 0;
  7394. r->form_disabled = 0;
  7395. r->lit[0] = '\0';
  7396. if (lit && lit[0]) {
  7397. unsigned int i;
  7398. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  7399. r->lit[i] = lit[i];
  7400. r->lit[i] = '\0';
  7401. r->has_lit = 1;
  7402. }
  7403. r->img = -1;
  7404. r->iw = r->ih = 0;
  7405. r->font_px = st->font_px;
  7406. r->bold = st->bold;
  7407. r->italic = st->italic;
  7408. r->mono = st->mono;
  7409. r->font_face = st->font_face;
  7410. /* A control with its own background is a button, not body copy;
  7411. * an inherited link underline would strike through the fill. */
  7412. r->underline = st->underline && !st->has_bg;
  7413. r->strike = st->strike && !st->has_bg;
  7414. r->overline = st->overline && !st->has_bg;
  7415. r->w = (unsigned short)w;
  7416. if (r->has_lit)
  7417. r->w = (unsigned short)run_text_width(
  7418. l->ui, r, r->lit, s_len(r->lit));
  7419. w = r->w;
  7420. }
  7421. l->line_x += w;
  7422. l->run_x = l->line_x;
  7423. {
  7424. int lh = face_line_height(l->ui, st);
  7425. if (st->line_h_px)
  7426. lh = st->line_h_px;
  7427. else if (st->line_h_pct)
  7428. lh = st->font_px * st->line_h_pct / 100;
  7429. if (lh < face_line_height(l->ui, st))
  7430. lh = face_line_height(l->ui, st);
  7431. if (l->line_h < lh)
  7432. l->line_h = lh;
  7433. }
  7434. }
  7435. static void add_image_run(struct lay *l, unsigned int node,
  7436. const struct br_style *st, unsigned short href)
  7437. {
  7438. struct br_image *bi = 0;
  7439. int idx = doc.nodes[node].img_index;
  7440. int dw, dh, maxw;
  7441. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  7442. bi = &images[idx];
  7443. if (l->nruns == 0)
  7444. start_line(l, st);
  7445. if (l->space_pending &&
  7446. (l->nruns > 0 || l->line_x > l->line_left)) {
  7447. int sp = (int)face_text_width(l->ui, st, " ", 1);
  7448. if (l->line_x + sp <= l->line_right)
  7449. l->line_x += sp;
  7450. }
  7451. l->space_pending = 0;
  7452. if (!bi) {
  7453. const char *alt = br_alt(&doc, node);
  7454. struct br_style gs = *st;
  7455. char tmp[96];
  7456. unsigned int n = 0;
  7457. int w;
  7458. gs.color = BR_GRAY;
  7459. gs.underline = 0;
  7460. s_append(tmp, &n, "[", sizeof(tmp));
  7461. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  7462. s_append(tmp, &n, "]", sizeof(tmp));
  7463. w = (int)face_text_width(l->ui, &gs, tmp, n);
  7464. if (l->line_x + w > l->line_right &&
  7465. (l->nruns > 0 || l->line_x > l->line_left))
  7466. flush_line(l);
  7467. add_run(l, 0, 0, &gs, href, tmp);
  7468. if (!l->draw) {
  7469. int t = l->line_y < 0 ? 0 : l->line_y;
  7470. int hh = face_line_height(l->ui, &gs);
  7471. if (t > 65535)
  7472. t = 65535;
  7473. if (hh > 65535)
  7474. hh = 65535;
  7475. img_top[node] = (unsigned short)t;
  7476. img_h[node] = (unsigned short)hh;
  7477. }
  7478. return;
  7479. }
  7480. maxw = l->line_right - l->line_left;
  7481. if (maxw < 8)
  7482. maxw = 8;
  7483. {
  7484. int iw = bi->native_w, ih = bi->native_h;
  7485. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  7486. if (iw <= 0 || ih <= 0) {
  7487. iw = (int)bi->img.w;
  7488. ih = (int)bi->img.h;
  7489. }
  7490. dw = iw;
  7491. dh = ih;
  7492. if (doc.nodes[node].width_attr) {
  7493. int want = doc.nodes[node].width_attr;
  7494. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  7495. have_w = 1;
  7496. }
  7497. if (doc.nodes[node].height_attr) {
  7498. int want = doc.nodes[node].height_attr;
  7499. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  7500. have_h = 1;
  7501. }
  7502. if (have_w && !have_h)
  7503. dh = ih ? ih * dw / iw : 0;
  7504. if (have_h && !have_w)
  7505. dw = iw ? iw * dh / ih : 0;
  7506. if (st->width_kind) {
  7507. css_w = 1;
  7508. if (st->width_kind == 3)
  7509. dw = maxw * st->width_calc_pct / 100 +
  7510. st->width_calc_px;
  7511. else
  7512. dw = st->width_kind == 2 ?
  7513. maxw * (int)st->width / 100 :
  7514. (int)st->width;
  7515. }
  7516. /* Percentage heights resolve against the containing block's
  7517. * definite height (Docusaurus' logo: `.navbar__logo { height:
  7518. * 2rem }` holding an `img { height: 100% }`), and are auto
  7519. * when it has none; they used to use the width. */
  7520. if (st->height_kind == 1 ||
  7521. ((st->height_kind == 2 || st->height_kind == 3) &&
  7522. l->cb_h > 0)) {
  7523. css_h = 1;
  7524. if (st->height_kind == 3)
  7525. dh = l->cb_h * st->height_calc_pct / 100 +
  7526. st->height_calc_px;
  7527. else
  7528. dh = st->height_kind == 2 ?
  7529. l->cb_h * (int)st->height / 100 :
  7530. (int)st->height;
  7531. }
  7532. if (css_w && !css_h)
  7533. dh = ih ? ih * dw / iw : 0;
  7534. if (css_h && !css_w)
  7535. dw = iw ? iw * dh / ih : 0;
  7536. if (st->max_width_kind) {
  7537. int mw = st->max_width_kind == 3 ?
  7538. maxw * st->max_width_calc_pct / 100 +
  7539. st->max_width_calc_px :
  7540. st->max_width_kind == 2 ?
  7541. maxw * (int)st->max_width / 100 :
  7542. (int)st->max_width;
  7543. if (mw > 0 && dw > mw) {
  7544. dh = iw ? ih * mw / iw : 0;
  7545. dw = mw;
  7546. }
  7547. }
  7548. }
  7549. if (dw < 8)
  7550. dw = 8;
  7551. if (dh < 8)
  7552. dh = 8;
  7553. if (dw > maxw) {
  7554. dh = dw ? dh * maxw / dw : dh;
  7555. dw = maxw;
  7556. }
  7557. if (!l->draw) {
  7558. int t = l->line_y < 0 ? 0 : l->line_y;
  7559. if (t > 65535)
  7560. t = 65535;
  7561. if (dh > 65535)
  7562. dh = 65535;
  7563. img_top[node] = (unsigned short)t;
  7564. img_h[node] = (unsigned short)dh;
  7565. }
  7566. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  7567. l->line_x > l->line_left))
  7568. flush_line(l);
  7569. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  7570. flush_line(l);
  7571. if (l->nruns == 0) {
  7572. l->line_y = l->y;
  7573. l->line_h = 0;
  7574. start_line(l, st);
  7575. }
  7576. {
  7577. struct lay_run *r = &l->runs[l->nruns++];
  7578. int gap = l->line_x - l->run_x;
  7579. if (gap < 0)
  7580. gap = 0;
  7581. r->box = l->box_owner;
  7582. r->gap = (unsigned short)gap;
  7583. r->off = 0;
  7584. r->len = 0;
  7585. r->color = 0;
  7586. r->href = href;
  7587. r->form = 0;
  7588. r->form_kind = 0;
  7589. r->form_disabled = 0;
  7590. /* Inline replaced elements honour their vertical margins; this
  7591. * is how Bootstrap's negative logo margins centre the wordmark. */
  7592. {
  7593. int idy = mp_px(st, 0, l->right - l->left);
  7594. if (idy < -2048)
  7595. idy = -2048;
  7596. if (idy > 2048)
  7597. idy = 2048;
  7598. r->dy = (signed short)idy;
  7599. }
  7600. r->has_lit = 0;
  7601. r->lit[0] = '\0';
  7602. r->img = (short)idx;
  7603. r->iw = (unsigned short)dw;
  7604. r->ih = (unsigned short)dh;
  7605. r->w = (unsigned short)dw;
  7606. r->font_px = st->font_px;
  7607. r->bold = st->bold;
  7608. r->italic = st->italic;
  7609. r->mono = st->mono;
  7610. r->font_face = st->font_face;
  7611. r->transform_scale = st->transform_scale;
  7612. r->scale_x = st->scale_x;
  7613. r->scale_y = st->scale_y;
  7614. r->rotate_x100 = st->rotate_x100;
  7615. r->origin_x = st->origin_x;
  7616. r->origin_y = st->origin_y;
  7617. r->origin_x_kind = st->origin_x_kind;
  7618. r->origin_y_kind = st->origin_y_kind;
  7619. r->underline = 0;
  7620. }
  7621. if (node < BR_MAX_NODES) {
  7622. layout_boxes[node].x = l->line_x;
  7623. layout_boxes[node].y = l->line_y +
  7624. mp_px(st, 0, l->right - l->left);
  7625. layout_boxes[node].w = dw;
  7626. layout_boxes[node].h = dh;
  7627. layout_boxes[node].valid = 1;
  7628. }
  7629. l->line_x += dw;
  7630. l->run_x = l->line_x;
  7631. if (l->line_h < dh)
  7632. l->line_h = dh;
  7633. }
  7634. /* An inline (or inline-block) <svg> is a replaced element in the text
  7635. * line, like an <img>: comment bubbles and arrows sit next to their label
  7636. * instead of starting a block of their own. */
  7637. static void add_svg_run(struct lay *l, unsigned int node,
  7638. const struct br_style *st, unsigned short href)
  7639. {
  7640. struct lay_run *r;
  7641. int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
  7642. if (lw < 8)
  7643. lw = 8;
  7644. cw = st->width_kind ? style_width_px(st, lw) : lw;
  7645. if (cw < 1)
  7646. cw = 1;
  7647. svg_size(node, st, cw, &dw, &dh);
  7648. if (dw > lw)
  7649. dw = lw;
  7650. ml = mp_px(st, 3, lw);
  7651. mr = mp_px(st, 1, lw);
  7652. if (ml < 0)
  7653. ml = 0;
  7654. if (mr < 0)
  7655. mr = 0;
  7656. if (l->line_x + ml + dw > l->line_right &&
  7657. (l->nruns > 0 || l->line_x > l->line_left))
  7658. flush_line(l);
  7659. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  7660. flush_line(l);
  7661. if (l->nruns == 0) {
  7662. l->line_y = l->y;
  7663. l->line_h = 0;
  7664. start_line(l, st);
  7665. }
  7666. l->line_x += ml;
  7667. r = &l->runs[l->nruns++];
  7668. memset(r, 0, sizeof(*r));
  7669. r->box = l->box_owner;
  7670. r->gap = (unsigned short)(l->line_x > l->run_x ?
  7671. l->line_x - l->run_x : 0);
  7672. r->off = node;
  7673. r->color = st->color;
  7674. r->href = href;
  7675. r->img = RUN_SVG;
  7676. r->iw = (unsigned short)dw;
  7677. r->ih = (unsigned short)dh;
  7678. r->w = (unsigned short)dw;
  7679. r->font_px = st->font_px;
  7680. if (node < BR_MAX_NODES) {
  7681. layout_boxes[node].x = l->line_x;
  7682. layout_boxes[node].y = l->line_y;
  7683. layout_boxes[node].w = dw;
  7684. layout_boxes[node].h = dh;
  7685. layout_boxes[node].valid = 1;
  7686. }
  7687. l->line_x += dw + mr;
  7688. l->run_x = l->line_x;
  7689. if (l->line_h < dh)
  7690. l->line_h = dh;
  7691. }
  7692. static int text_width(struct lay *l, const char *s, unsigned int n,
  7693. const struct br_style *st)
  7694. {
  7695. return (int)face_text_width(l->ui, st, s, n);
  7696. }
  7697. /* Longest prefix that fits in maxw, at least one byte. */
  7698. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  7699. const struct br_style *st, int maxw)
  7700. {
  7701. unsigned int take = 0;
  7702. while (take < n) {
  7703. if (text_width(l, s, take + 1, st) > maxw)
  7704. break;
  7705. take++;
  7706. }
  7707. return take ? take : 1;
  7708. }
  7709. static void emit_word(struct lay *l, const char *s, unsigned int start,
  7710. unsigned int n, unsigned int base,
  7711. const struct br_style *st, unsigned short href)
  7712. {
  7713. int avail;
  7714. int w = text_width(l, s + start, n, st);
  7715. unsigned int off = start;
  7716. if (l->nruns == 0)
  7717. start_line(l, st);
  7718. avail = l->line_right - l->line_left;
  7719. if (st->nowrap) {
  7720. if (n)
  7721. add_run(l, base + start,
  7722. (unsigned short)n, st, href, 0);
  7723. return;
  7724. }
  7725. /* A padded/bordered one-word button can be a few pixels wider than
  7726. * the content box; keep it on one line instead of splitting it. */
  7727. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  7728. add_run(l, base + start,
  7729. (unsigned short)n, st, href, 0);
  7730. return;
  7731. }
  7732. if (l->line_x + w > l->line_right &&
  7733. (l->nruns > 0 || l->line_x > l->line_left)) {
  7734. flush_line(l);
  7735. start_line(l, st);
  7736. avail = l->line_right - l->line_left;
  7737. }
  7738. if (w <= avail) {
  7739. if (n)
  7740. add_run(l, base + start,
  7741. (unsigned short)n, st, href, 0);
  7742. return;
  7743. }
  7744. while (n > 0) {
  7745. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  7746. add_run(l, base + off,
  7747. (unsigned short)take, st, href, 0);
  7748. off += take;
  7749. n -= take;
  7750. if (n) {
  7751. flush_line(l);
  7752. start_line(l, st);
  7753. avail = l->line_right - l->line_left;
  7754. }
  7755. }
  7756. }
  7757. static void emit_text(struct lay *l, const char *s, unsigned int len,
  7758. const struct br_style *st, unsigned short href, int pre)
  7759. {
  7760. unsigned int i = 0;
  7761. unsigned int base;
  7762. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  7763. if (!s || !len)
  7764. return;
  7765. if (space_w <= 0)
  7766. space_w = 8;
  7767. if (l->nruns == 0)
  7768. start_line(l, st);
  7769. base = (unsigned int)(s - doc.text);
  7770. if (st->uppercase) {
  7771. char *p = (char *)s;
  7772. unsigned int j;
  7773. for (j = 0; j < len; j++)
  7774. if (p[j] >= 'a' && p[j] <= 'z')
  7775. p[j] = (char)(p[j] - 'a' + 'A');
  7776. }
  7777. if (pre) {
  7778. while (i < len) {
  7779. unsigned int start;
  7780. if (s[i] == '\n') {
  7781. flush_line(l);
  7782. start_line(l, st);
  7783. i++;
  7784. continue;
  7785. }
  7786. if (s[i] == ' ') {
  7787. if (l->line_x + space_w > l->line_right &&
  7788. (l->nruns > 0 || l->line_x > l->line_left)) {
  7789. flush_line(l);
  7790. start_line(l, st);
  7791. } else {
  7792. l->line_x += space_w;
  7793. }
  7794. i++;
  7795. continue;
  7796. }
  7797. start = i;
  7798. while (i < len && s[i] != ' ' && s[i] != '\n')
  7799. i++;
  7800. emit_word(l, s, start, i - start, base, st, href);
  7801. }
  7802. return;
  7803. }
  7804. while (i < len) {
  7805. unsigned int start, n;
  7806. if (s[i] == ' ') {
  7807. l->space_pending = 1;
  7808. i++;
  7809. continue;
  7810. }
  7811. start = i;
  7812. while (i < len && s[i] != ' ')
  7813. i++;
  7814. n = i - start;
  7815. if (l->space_pending &&
  7816. (l->nruns > 0 || l->line_x > l->line_left)) {
  7817. if (st->nowrap ||
  7818. l->line_x + space_w <= l->line_right)
  7819. l->line_x += space_w;
  7820. }
  7821. l->space_pending = 0;
  7822. emit_word(l, s, start, n, base, st, href);
  7823. }
  7824. }
  7825. static int list_index(unsigned int parent, unsigned int node)
  7826. {
  7827. unsigned int n = 0, i;
  7828. for (i = doc.nodes[parent].first; i && i != node;
  7829. i = doc.nodes[i].next)
  7830. if (doc.nodes[i].tag == BR_TAG_LI)
  7831. n++;
  7832. return (int)n + 1;
  7833. }
  7834. static void list_roman(char *m, unsigned int *n, int v, int upper,
  7835. unsigned int cap)
  7836. {
  7837. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  7838. 50, 40, 10, 9, 5, 4, 1 };
  7839. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  7840. "l", "xl", "x", "ix", "v", "iv", "i" };
  7841. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  7842. "L", "XL", "X", "IX", "V", "IV", "I" };
  7843. unsigned int i;
  7844. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  7845. while (v >= val[i] && *n + 1 < cap) {
  7846. const char *s = upper ? up[i] : lo[i];
  7847. while (*s && *n + 1 < cap)
  7848. m[(*n)++] = *s++;
  7849. v -= val[i];
  7850. }
  7851. }
  7852. }
  7853. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  7854. {
  7855. unsigned int n = 0;
  7856. if (style == BR_LIST_DISC) {
  7857. m[n++] = '-';
  7858. } else if (style == BR_LIST_CIRCLE) {
  7859. m[n++] = 'o';
  7860. } else if (style == BR_LIST_SQUARE) {
  7861. m[n++] = '+';
  7862. } else if (style == BR_LIST_LOWER_ALPHA ||
  7863. style == BR_LIST_UPPER_ALPHA) {
  7864. if (idx >= 1 && idx <= 26)
  7865. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  7866. 'A' : 'a') + idx - 1);
  7867. else
  7868. m[n++] = '?';
  7869. m[n++] = '.';
  7870. } else if (style == BR_LIST_LOWER_ROMAN ||
  7871. style == BR_LIST_UPPER_ROMAN) {
  7872. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  7873. if (n + 1 < cap)
  7874. m[n++] = '.';
  7875. } else {
  7876. s_append_dec(m, &n, (unsigned int)idx, cap);
  7877. if (n + 1 < cap)
  7878. m[n++] = '.';
  7879. }
  7880. m[n] = '\0';
  7881. }
  7882. /* A control the page styled itself (background, border or radius in author
  7883. * CSS -- `background:transparent;border:none` counts) is painted with that
  7884. * style, sized from its padding/height and keeps the page's text colour.
  7885. * Unstyled controls keep the ngui theme look. */
  7886. static int form_author_styled(const struct br_style *st)
  7887. {
  7888. int i;
  7889. if (st->bg_set)
  7890. return 1;
  7891. for (i = 0; i < 4; i++)
  7892. if (st->border_w[i] || st->radius[i])
  7893. return 1;
  7894. return 0;
  7895. }
  7896. /* Set by the layout when the control is stretched to its line: a flex item
  7897. * (its box width was assigned by the flex row) or a child of a flex column,
  7898. * whose default align-items: stretch makes inputs full width. */
  7899. static int form_fill_line;
  7900. static void add_form_run(struct lay *l, unsigned int node,
  7901. const struct br_style *st, unsigned short href)
  7902. {
  7903. struct form_state *fs = form_get(node, 1);
  7904. char shown[FORM_VALUE_MAX + 1];
  7905. char opt[64];
  7906. const char *text = "";
  7907. struct lay_run *r;
  7908. int kind = form_kind_of(node);
  7909. int disabled = form_disabled(node);
  7910. int author = form_author_styled(st);
  7911. int tw, w = 120, h = 20, i, line_w, pad_x, pad_y;
  7912. int ml = 0, mr = 0, mt = 0, mb = 0;
  7913. if (!fs)
  7914. return;
  7915. if (l->nruns == 0)
  7916. start_line(l, st);
  7917. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  7918. text = "";
  7919. w = 16;
  7920. h = 16;
  7921. } else if (kind == FORM_SELECT) {
  7922. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  7923. s_copy(opt, "Select", sizeof(opt));
  7924. text = opt;
  7925. w = 120;
  7926. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  7927. kind == FORM_RESET) {
  7928. if (fs->len)
  7929. text = fs->value;
  7930. else if (doc.nodes[node].tag == BR_TAG_BUTTON)
  7931. /* A <button>'s label is its content: an empty one
  7932. * (Docusaurus' sidebar caret, drawn by a CSS
  7933. * ::before icon) shows none. Only <input> buttons
  7934. * get the UA's default label. */
  7935. text = "";
  7936. else
  7937. text = kind == FORM_SUBMIT ? "Submit" :
  7938. kind == FORM_RESET ? "Reset" : "Button";
  7939. } else if (kind == FORM_PASSWORD) {
  7940. for (i = 0; i < fs->len; i++)
  7941. shown[i] = '*';
  7942. shown[fs->len] = '\0';
  7943. text = fs->len ? shown : br_placeholder(&doc, node);
  7944. } else {
  7945. if (fs->len)
  7946. text = fs->value;
  7947. else
  7948. text = br_placeholder(&doc, node);
  7949. if (kind == FORM_TEXTAREA) {
  7950. w = 180;
  7951. h = 40;
  7952. }
  7953. }
  7954. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  7955. line_w = l->line_right - l->line_left;
  7956. pad_x = mp_px(st, 7, line_w) + mp_px(st, 5, line_w) +
  7957. st->border_w[1] + st->border_w[3];
  7958. pad_y = mp_px(st, 4, line_w) + mp_px(st, 6, line_w) +
  7959. st->border_w[0] + st->border_w[2];
  7960. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  7961. /* Buttons are border-box in every UA stylesheet: an
  7962. * explicit width/height is the whole box. */
  7963. if (author || pad_x) {
  7964. w = tw + pad_x;
  7965. } else {
  7966. w = tw + 18;
  7967. if (w < 64)
  7968. w = 64;
  7969. }
  7970. if (st->width_kind)
  7971. w = style_width_px(st, line_w);
  7972. if (st->min_width_kind == 1 && w < (int)st->min_width)
  7973. w = st->min_width;
  7974. if (st->height_kind == 1)
  7975. h = st->height;
  7976. else if (author)
  7977. h = st->font_px + 6 + pad_y;
  7978. else
  7979. h = 22;
  7980. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  7981. kind == FORM_TEXTAREA) {
  7982. int fill = form_fill_line || st->display == BR_DISPLAY_BLOCK ||
  7983. st->display == BR_DISPLAY_FLEX;
  7984. int boxed = st->box_sizing ? 0 : pad_x;
  7985. if (st->width_kind)
  7986. w = style_width_px(st, line_w) + boxed;
  7987. else if (fill)
  7988. w = line_w - (l->line_x - l->line_left);
  7989. else
  7990. w = kind == FORM_TEXTAREA ? 180 : 120;
  7991. if (kind == FORM_TEXTAREA) {
  7992. const char *ra = br_find_attr(&doc, node, "rows");
  7993. int rows = 0;
  7994. int lh = st->line_h_px ? st->line_h_px :
  7995. st->font_px * 5 / 4;
  7996. while (ra && *ra >= '0' && *ra <= '9')
  7997. rows = rows * 10 + (*ra++ - '0');
  7998. if (rows < 1 || rows > 40)
  7999. rows = 2;
  8000. h = author ? rows * lh + pad_y : 40;
  8001. } else if (author) {
  8002. h = st->font_px + 8 + pad_y;
  8003. } else if (st->font_px + 8 > h) {
  8004. /* Taller fields for large text (min-height/padding
  8005. * on login pages): keep the box around the glyphs. */
  8006. h = st->font_px + 8;
  8007. }
  8008. if (st->height_kind == 1)
  8009. h = st->height + (st->box_sizing ? 0 : pad_y);
  8010. if (st->min_height_kind == 1 && h < (int)st->min_height)
  8011. h = st->min_height;
  8012. } else if (kind == FORM_SELECT) {
  8013. w = st->width_kind == 1 ? st->width : 120;
  8014. }
  8015. if (author) {
  8016. /* Inline margins (Google's `margin:11px 4px` between its
  8017. * two submit buttons). */
  8018. ml = mp_px(st, 3, line_w);
  8019. mr = mp_px(st, 1, line_w);
  8020. mt = mp_px(st, 0, line_w);
  8021. mb = mp_px(st, 2, line_w);
  8022. if (ml < 0 || ml > 64) ml = 0;
  8023. if (mr < 0 || mr > 64) mr = 0;
  8024. if (mt < 0 || mt > 64) mt = 0;
  8025. if (mb < 0 || mb > 64) mb = 0;
  8026. }
  8027. if (w > line_w - ml - mr)
  8028. w = line_w - ml - mr;
  8029. if (w < 8)
  8030. w = 8;
  8031. if (h > 400)
  8032. h = 400;
  8033. if (l->line_x + ml + w > l->line_right &&
  8034. (l->nruns > 0 || l->line_x > l->line_left))
  8035. flush_line(l);
  8036. if (l->nruns >= 96)
  8037. return;
  8038. if (l->nruns == 0) {
  8039. l->line_y = l->y;
  8040. l->line_h = 0;
  8041. start_line(l, st);
  8042. }
  8043. l->line_x += ml;
  8044. r = &l->runs[l->nruns++];
  8045. r->box = l->box_owner;
  8046. r->gap = (unsigned short)(l->line_x - l->run_x);
  8047. r->off = r->len = 0;
  8048. r->color = st->color;
  8049. r->href = href;
  8050. r->dy = (signed short)mt;
  8051. r->has_lit = 1;
  8052. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  8053. r->lit[i] = text[i];
  8054. r->lit[i] = '\0';
  8055. r->img = -2;
  8056. r->iw = (unsigned short)w;
  8057. r->ih = (unsigned short)h;
  8058. r->w = (unsigned short)w;
  8059. r->font_px = st->font_px;
  8060. r->bold = st->bold;
  8061. r->italic = st->italic;
  8062. r->mono = st->mono;
  8063. r->font_face = st->font_face;
  8064. r->underline = 0;
  8065. r->form = node + 1;
  8066. r->form_kind = (unsigned char)kind;
  8067. r->form_disabled = (unsigned char)disabled;
  8068. if (node < BR_MAX_NODES) {
  8069. layout_boxes[node].x = l->line_x;
  8070. layout_boxes[node].y = l->line_y + mt;
  8071. layout_boxes[node].w = w;
  8072. layout_boxes[node].h = h;
  8073. layout_boxes[node].valid = 1;
  8074. }
  8075. l->line_x += w;
  8076. l->run_x = l->line_x;
  8077. l->line_x += mr;
  8078. if (l->line_h < h + mt + mb)
  8079. l->line_h = h + mt + mb;
  8080. }
  8081. /* Background, border and corner radius of an author-styled control, the
  8082. * same decoration rules as a block box. */
  8083. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  8084. const struct br_style *st, int focused)
  8085. {
  8086. int rtl = css_radius(st, 0, box.w, box.h);
  8087. int rtr = css_radius(st, 1, box.w, box.h);
  8088. int rbr = css_radius(st, 2, box.w, box.h);
  8089. int rbl = css_radius(st, 3, box.w, box.h);
  8090. int bw = st->border_t[0] ? 0 : st->border_w[0];
  8091. (void)focused;
  8092. if (box.w <= 0 || box.h <= 0)
  8093. return;
  8094. if (rtl || rtr || rbr || rbl) {
  8095. if (bw > 0 && st->has_bg && st->border_c[0] != st->bg &&
  8096. box.w > bw * 2 && box.h > bw * 2) {
  8097. struct ngui_rect in = { box.x + bw, box.y + bw,
  8098. box.w - bw * 2,
  8099. box.h - bw * 2 };
  8100. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  8101. st->border_c[0]);
  8102. ngui_fill_round_rect(ui, in,
  8103. rtl > bw ? rtl - bw : 0,
  8104. rtr > bw ? rtr - bw : 0,
  8105. rbr > bw ? rbr - bw : 0,
  8106. rbl > bw ? rbl - bw : 0, st->bg);
  8107. } else if (st->has_bg) {
  8108. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  8109. st->bg);
  8110. } else if (bw > 0) {
  8111. ngui_frame_round(ui, box, rtl, rtr, rbr, rbl, bw,
  8112. st->border_c[0]);
  8113. }
  8114. return;
  8115. }
  8116. if (st->has_bg)
  8117. ngui_fill_rect(ui, box, st->bg);
  8118. if (st->border_w[0] || st->border_w[1] || st->border_w[2] ||
  8119. st->border_w[3])
  8120. draw_border_box(ui, box, st);
  8121. }
  8122. /* A poster wrapper is absolutely positioned over the media slot; the
  8123. * measured height of its picture is normally added back to the flow. When a
  8124. * loading-skeleton sibling already reserves that slot, adding both doubles
  8125. * the media height and pushes the article text a full screen down. */
  8126. static int has_skeleton_sibling(unsigned int node)
  8127. {
  8128. unsigned int p = doc.nodes[node].parent, c;
  8129. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  8130. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  8131. continue;
  8132. if (doc.nodes[c].class_off &&
  8133. contains_ci(doc.attrs + doc.nodes[c].class_off,
  8134. "skeleton"))
  8135. return 1;
  8136. }
  8137. return 0;
  8138. }
  8139. static void layout_children(struct lay *l, unsigned int parent,
  8140. const struct br_style *pst, int depth,
  8141. unsigned short link);
  8142. static void layout_flex_children(struct lay *l, unsigned int parent,
  8143. const struct br_style *pst, int depth,
  8144. unsigned short link);
  8145. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  8146. struct br_style *ps, int base);
  8147. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  8148. const struct br_style *ps, unsigned short link);
  8149. static void layout_grid_children(struct lay *l, unsigned int parent,
  8150. const struct br_style *pst, int depth,
  8151. unsigned short link);
  8152. static void layout_grid_auto(struct lay *l, unsigned int parent,
  8153. const struct br_style *pst, int depth,
  8154. unsigned short link);
  8155. static int flex_item_width(struct lay *l, unsigned int n,
  8156. const struct br_style *cs, int avail);
  8157. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  8158. const struct br_style *pst, int depth,
  8159. unsigned short link);
  8160. static void layout_table_row(struct lay *l, unsigned int row,
  8161. const struct br_style *pst, int depth,
  8162. unsigned short link);
  8163. static int table_has_rowspan(unsigned int table);
  8164. static void layout_table(struct lay *l, unsigned int table,
  8165. const struct br_style *st, int depth,
  8166. unsigned short link);
  8167. /* A flex container whose items are only inline spans is usually just a
  8168. * heading/icon pair. Our flex row positions such items without emitting
  8169. * their inline text in some deep page contexts; normal inline flow renders
  8170. * the same content correctly. */
  8171. static int layout_out_of_flow(struct lay *l, unsigned int n,
  8172. const struct br_style *cs, int depth,
  8173. unsigned short lk);
  8174. static void layout_flex_column(struct lay *l, unsigned int parent,
  8175. const struct br_style *pst, int depth,
  8176. unsigned short link);
  8177. static void emit_pseudo(struct lay *l, unsigned int node,
  8178. const struct br_style *st, int pe, unsigned short link);
  8179. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  8180. {
  8181. unsigned int c;
  8182. int items = 0;
  8183. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  8184. struct br_node *nd = &doc.nodes[c];
  8185. struct br_style cs;
  8186. if (nd->type == BR_NODE_TEXT)
  8187. continue;
  8188. br_style_for(&doc, c, pst, &cs);
  8189. if (cs.display == BR_DISPLAY_NONE)
  8190. continue;
  8191. /* `justify-content: space-between` spreads even two plain
  8192. * inline items (a "Password ... Reset password" label row)
  8193. * across the line; inline flow would set them side by side. */
  8194. if (++items >= 2 && pst->justify >= 3)
  8195. return 1;
  8196. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  8197. cs.width_kind || cs.has_bg ||
  8198. cs.border_w[0] || cs.border_w[1] ||
  8199. cs.border_w[2] || cs.border_w[3] ||
  8200. nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG)
  8201. return 1;
  8202. }
  8203. return 0;
  8204. }
  8205. static int css_radius(const struct br_style *st, int corner,
  8206. int w, int h)
  8207. {
  8208. int r = st->radius[corner];
  8209. if (r <= 0)
  8210. return 0;
  8211. if (r > w / 2)
  8212. r = w / 2;
  8213. if (r > h / 2)
  8214. r = h / 2;
  8215. return r;
  8216. }
  8217. /* ---- inline SVG ----
  8218. *
  8219. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  8220. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  8221. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  8222. * opacity and solid paint; a gradient paints the average of its stops) and
  8223. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  8224. #define SVG_CACHE_MAX 48
  8225. #define SVG_CACHE_PIXELS (640 * 1024)
  8226. #define SVG_MAX_POINTS 24576
  8227. struct svg_cache_ent {
  8228. unsigned int node;
  8229. int w, h;
  8230. unsigned short *px;
  8231. unsigned char *a;
  8232. unsigned int stamp;
  8233. };
  8234. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  8235. static unsigned int svg_cache_pixels, svg_cache_clock;
  8236. static struct svgr svg_geom;
  8237. static void *svg_geom_buf;
  8238. /* Current viewport in user units: percentage lengths resolve against it
  8239. * (the viewBox size, not the device pixels). */
  8240. static double svg_vp_w = 300, svg_vp_h = 150;
  8241. /* The layers live in the page heap: forget them before heap_reset(). */
  8242. static void svg_cache_clear(void)
  8243. {
  8244. memset(svg_cache, 0, sizeof(svg_cache));
  8245. svg_cache_pixels = 0;
  8246. svg_geom_buf = 0;
  8247. }
  8248. static int svg_name_is(const char *a, const char *b)
  8249. {
  8250. while (*a && *b) {
  8251. char x = *a, y = *b;
  8252. if (x >= 'A' && x <= 'Z')
  8253. x = (char)(x - 'A' + 'a');
  8254. if (x != y)
  8255. return 0;
  8256. a++;
  8257. b++;
  8258. }
  8259. return *a == *b;
  8260. }
  8261. static const char *svg_elem_name(unsigned int node)
  8262. {
  8263. const struct br_node *nd = &doc.nodes[node];
  8264. if (nd->name_off)
  8265. return doc.attrs + nd->name_off;
  8266. return br_tag_name(nd->tag);
  8267. }
  8268. /* A numeric attribute; a percentage resolves against `base`. */
  8269. static double svg_attr_num(unsigned int node, const char *name, double def,
  8270. double base)
  8271. {
  8272. const char *v = br_find_attr(&doc, node, name);
  8273. const char *p = v;
  8274. int ok = 0;
  8275. double x;
  8276. if (!v)
  8277. return def;
  8278. x = svgr_num(&p, &ok);
  8279. if (!ok)
  8280. return def;
  8281. if (*p == '%')
  8282. x = x * base / 100.0;
  8283. return x;
  8284. }
  8285. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  8286. static int svg_viewbox4(unsigned int node, double vb[4])
  8287. {
  8288. const char *v = br_find_attr(&doc, node, "viewbox");
  8289. const char *p = v;
  8290. int i, ok = 1;
  8291. if (!v)
  8292. return 0;
  8293. for (i = 0; i < 4 && ok; i++)
  8294. vb[i] = svgr_num(&p, &ok);
  8295. return ok && vb[2] > 0 && vb[3] > 0;
  8296. }
  8297. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  8298. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  8299. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  8300. double w, double h, double m[6])
  8301. {
  8302. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  8303. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  8304. int ax = 1, ay = 1;
  8305. if (par && contains_ci(par, "none")) {
  8306. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  8307. m[4] = -vb[0] * sx;
  8308. m[5] = -vb[1] * sy;
  8309. return;
  8310. }
  8311. if (par) {
  8312. if (contains_ci(par, "xmin"))
  8313. ax = 0;
  8314. else if (contains_ci(par, "xmax"))
  8315. ax = 2;
  8316. if (contains_ci(par, "ymin"))
  8317. ay = 0;
  8318. else if (contains_ci(par, "ymax"))
  8319. ay = 2;
  8320. }
  8321. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  8322. (sx < sy ? sx : sy);
  8323. tx = (w - vb[2] * s) * ax / 2.0;
  8324. ty = (h - vb[3] * s) * ay / 2.0;
  8325. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  8326. m[4] = tx - vb[0] * s;
  8327. m[5] = ty - vb[1] * s;
  8328. }
  8329. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  8330. * the paint attribute, then average the gradient's stops. */
  8331. static int svg_url_paint(unsigned int node, const char *attr,
  8332. unsigned short *color, unsigned int *alpha)
  8333. {
  8334. const char *v = 0, *h;
  8335. char id[64];
  8336. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  8337. for (k = 0; node && k < 32 && !v; k++) {
  8338. v = br_find_attr(&doc, node, attr);
  8339. if (!v) {
  8340. const char *style = br_find_attr(&doc, node, "style");
  8341. if (style && contains_ci(style, "url(#"))
  8342. v = strstr(style, "url(#");
  8343. }
  8344. if (v && !contains_ci(v, "url("))
  8345. v = 0;
  8346. node = doc.nodes[node].parent;
  8347. }
  8348. if (!v || !(h = strstr(v, "#")))
  8349. return 0;
  8350. h++;
  8351. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  8352. id[n++] = *h++;
  8353. id[n] = '\0';
  8354. g = br_find_id(&doc, id);
  8355. /* Follow href chains (a gradient that only references another one's
  8356. * stops), at most a few hops. */
  8357. for (k = 0; g && k < 4; k++) {
  8358. unsigned int gi = g - 1;
  8359. const char *ref;
  8360. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  8361. const char *nm, *sc, *so;
  8362. unsigned short col = 0;
  8363. double op = 1;
  8364. if (doc.nodes[c].type != BR_NODE_ELEM)
  8365. continue;
  8366. nm = svg_elem_name(c);
  8367. if (!svg_name_is(nm, "stop"))
  8368. continue;
  8369. sc = br_find_attr(&doc, c, "stop-color");
  8370. so = br_find_attr(&doc, c, "stop-opacity");
  8371. {
  8372. const char *st = br_find_attr(&doc, c, "style");
  8373. const char *q;
  8374. if (st && (q = strstr(st, "stop-color:")) != 0)
  8375. sc = q + 11;
  8376. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  8377. so = q + 13;
  8378. }
  8379. if (sc) {
  8380. unsigned int L = 0;
  8381. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  8382. L++;
  8383. if (!br_parse_color(sc, L, &col))
  8384. col = 0;
  8385. }
  8386. if (so) {
  8387. const char *p = so;
  8388. int ok = 0;
  8389. double x = svgr_num(&p, &ok);
  8390. if (ok)
  8391. op = x < 0 ? 0 : x > 1 ? 1 : x;
  8392. }
  8393. sr += (col >> 11) & 31;
  8394. sg += (col >> 5) & 63;
  8395. sb += col & 31;
  8396. sa += (unsigned int)(op * 255);
  8397. cnt++;
  8398. }
  8399. if (cnt)
  8400. break;
  8401. ref = br_find_attr(&doc, gi, "href");
  8402. if (!ref)
  8403. ref = br_find_attr(&doc, gi, "xlink:href");
  8404. if (!ref || ref[0] != '#')
  8405. break;
  8406. g = br_find_id(&doc, ref + 1);
  8407. }
  8408. if (!cnt)
  8409. return 0;
  8410. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  8411. (sb / cnt));
  8412. *alpha = sa / cnt;
  8413. return 1;
  8414. }
  8415. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  8416. unsigned short *color, unsigned int *alpha)
  8417. {
  8418. int mode = fill ? st->fill_mode : st->stroke_mode;
  8419. const char *op = br_find_attr(&doc, node,
  8420. fill ? "fill-opacity" : "stroke-opacity");
  8421. *alpha = 255;
  8422. switch (mode) {
  8423. case BR_PAINT_UNSET:
  8424. if (!fill)
  8425. return 0;
  8426. *color = 0;
  8427. break;
  8428. case BR_PAINT_COLOR:
  8429. *color = fill ? st->fill : st->stroke;
  8430. break;
  8431. case BR_PAINT_CURRENT:
  8432. *color = st->color;
  8433. break;
  8434. case BR_PAINT_URL:
  8435. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  8436. alpha))
  8437. return 0;
  8438. break;
  8439. default:
  8440. return 0;
  8441. }
  8442. if (op) {
  8443. const char *p = op;
  8444. int ok = 0;
  8445. double x = svgr_num(&p, &ok);
  8446. if (ok)
  8447. *alpha = (unsigned int)(*alpha *
  8448. (x < 0 ? 0 : x > 1 ? 1 : x));
  8449. }
  8450. return *alpha > 0;
  8451. }
  8452. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  8453. const double m[6], const struct br_style *pst,
  8454. unsigned int alpha, int depth);
  8455. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  8456. const double m[6], const struct br_style *st,
  8457. unsigned int alpha, int depth)
  8458. {
  8459. unsigned int c;
  8460. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  8461. if (doc.nodes[c].type == BR_NODE_ELEM)
  8462. svg_draw_node(L, c, m, st, alpha, depth + 1);
  8463. }
  8464. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  8465. const double pm[6], const struct br_style *pst,
  8466. unsigned int alpha, int depth)
  8467. {
  8468. struct br_style st;
  8469. const char *nm = svg_elem_name(node);
  8470. const char *tf;
  8471. double m[6];
  8472. unsigned short color;
  8473. unsigned int pa;
  8474. int shape = 0, fillable = 1;
  8475. if (depth > 24 || !nm)
  8476. return;
  8477. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  8478. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  8479. svg_name_is(nm, "lineargradient") ||
  8480. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  8481. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  8482. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  8483. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  8484. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  8485. svg_name_is(nm, "foreignobject"))
  8486. return;
  8487. br_style_for(&doc, node, pst, &st);
  8488. if (st.display == BR_DISPLAY_NONE)
  8489. return;
  8490. memcpy(m, pm, sizeof(m));
  8491. tf = br_find_attr(&doc, node, "transform");
  8492. if (tf)
  8493. svgr_transform(m, tf);
  8494. {
  8495. const char *op = br_find_attr(&doc, node, "opacity");
  8496. if (op) {
  8497. const char *p = op;
  8498. int ok = 0;
  8499. double x = svgr_num(&p, &ok);
  8500. if (ok)
  8501. alpha = (unsigned int)(alpha *
  8502. (x < 0 ? 0 :
  8503. x > 1 ? 1 : x));
  8504. }
  8505. }
  8506. if (!alpha)
  8507. return;
  8508. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  8509. svg_name_is(nm, "switch")) {
  8510. svg_draw_children(L, node, m, &st, alpha, depth);
  8511. return;
  8512. }
  8513. if (svg_name_is(nm, "svg")) {
  8514. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  8515. y = svg_attr_num(node, "y", 0, 0);
  8516. double t[6] = { 1, 0, 0, 1, 0, 0 };
  8517. t[4] = x;
  8518. t[5] = y;
  8519. svgr_mat_mul(m, m, t);
  8520. double ow = svg_vp_w, oh = svg_vp_h;
  8521. if (svg_viewbox4(node, vb)) {
  8522. double w = svg_attr_num(node, "width", vb[2], ow);
  8523. double h = svg_attr_num(node, "height", vb[3], oh);
  8524. double vm[6];
  8525. svg_viewport_matrix(node, vb, w, h, vm);
  8526. svgr_mat_mul(m, m, vm);
  8527. svg_vp_w = vb[2];
  8528. svg_vp_h = vb[3];
  8529. }
  8530. svg_draw_children(L, node, m, &st, alpha, depth);
  8531. svg_vp_w = ow;
  8532. svg_vp_h = oh;
  8533. return;
  8534. }
  8535. if (svg_name_is(nm, "use")) {
  8536. const char *ref = br_find_attr(&doc, node, "href");
  8537. unsigned int tgt;
  8538. double t[6] = { 1, 0, 0, 1, 0, 0 };
  8539. if (!ref)
  8540. ref = br_find_attr(&doc, node, "xlink:href");
  8541. if (!ref || ref[0] != '#')
  8542. return;
  8543. tgt = br_find_id(&doc, ref + 1);
  8544. if (!tgt || tgt - 1 == node)
  8545. return;
  8546. tgt--;
  8547. t[4] = svg_attr_num(node, "x", 0, 0);
  8548. t[5] = svg_attr_num(node, "y", 0, 0);
  8549. svgr_mat_mul(m, m, t);
  8550. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  8551. double vb[4];
  8552. double ow = svg_vp_w, oh = svg_vp_h;
  8553. if (svg_viewbox4(tgt, vb)) {
  8554. /* A <use> without width/height sizes the
  8555. * symbol to 100% of the viewport: Docusaurus'
  8556. * 13.5px external-link icon references a
  8557. * 24-unit symbol and showed only its corner. */
  8558. double w = svg_attr_num(node, "width",
  8559. ow > 0 ? ow : vb[2], ow);
  8560. double h = svg_attr_num(node, "height",
  8561. oh > 0 ? oh : vb[3], oh);
  8562. double vm[6];
  8563. svg_viewport_matrix(tgt, vb, w, h, vm);
  8564. svgr_mat_mul(m, m, vm);
  8565. svg_vp_w = vb[2];
  8566. svg_vp_h = vb[3];
  8567. }
  8568. svg_draw_children(L, tgt, m, &st, alpha, depth);
  8569. svg_vp_w = ow;
  8570. svg_vp_h = oh;
  8571. } else {
  8572. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  8573. }
  8574. return;
  8575. }
  8576. svgr_reset(&svg_geom, m);
  8577. if (svg_name_is(nm, "path")) {
  8578. const char *d = br_find_attr(&doc, node, "d");
  8579. if (d) {
  8580. svgr_path(&svg_geom, d);
  8581. shape = 1;
  8582. }
  8583. } else if (svg_name_is(nm, "rect")) {
  8584. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  8585. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  8586. double rx = svg_attr_num(node, "rx", -1, w);
  8587. double ry = svg_attr_num(node, "ry", -1, h);
  8588. if (rx < 0)
  8589. rx = ry < 0 ? 0 : ry;
  8590. if (ry < 0)
  8591. ry = rx;
  8592. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  8593. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  8594. shape = 1;
  8595. } else if (svg_name_is(nm, "circle")) {
  8596. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  8597. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  8598. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  8599. shape = 1;
  8600. } else if (svg_name_is(nm, "ellipse")) {
  8601. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  8602. svg_attr_num(node, "cy", 0, svg_vp_h),
  8603. svg_attr_num(node, "rx", 0, svg_vp_w),
  8604. svg_attr_num(node, "ry", 0, svg_vp_h));
  8605. shape = 1;
  8606. } else if (svg_name_is(nm, "line")) {
  8607. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  8608. svg_attr_num(node, "y1", 0, svg_vp_h));
  8609. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  8610. svg_attr_num(node, "y2", 0, svg_vp_h));
  8611. shape = 1;
  8612. fillable = 0;
  8613. } else if (svg_name_is(nm, "polyline") ||
  8614. svg_name_is(nm, "polygon")) {
  8615. const char *pts = br_find_attr(&doc, node, "points");
  8616. if (pts) {
  8617. svgr_points(&svg_geom, pts,
  8618. svg_name_is(nm, "polygon"));
  8619. shape = 1;
  8620. }
  8621. }
  8622. if (!shape)
  8623. return;
  8624. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  8625. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  8626. st.fill_evenodd);
  8627. if (svg_paint(node, &st, 0, &color, &pa)) {
  8628. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  8629. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  8630. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  8631. }
  8632. }
  8633. /* <text> elements: drawn straight onto the page every frame (the glyph
  8634. * renderer targets the ngui canvas, not a layer). x/y map through the
  8635. * accumulated transform; the font size scales with it. */
  8636. static void svg_draw_text(struct ngui *ui, unsigned int node,
  8637. const double pm[6], const struct br_style *pst,
  8638. int ox, int oy, int depth)
  8639. {
  8640. unsigned int c;
  8641. if (depth > 24)
  8642. return;
  8643. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8644. struct br_style st;
  8645. const char *nm, *tf;
  8646. double m[6];
  8647. if (doc.nodes[c].type != BR_NODE_ELEM)
  8648. continue;
  8649. nm = svg_elem_name(c);
  8650. if (!nm || svg_name_is(nm, "defs") ||
  8651. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  8652. svg_name_is(nm, "clippath"))
  8653. continue;
  8654. br_style_for(&doc, c, pst, &st);
  8655. if (st.display == BR_DISPLAY_NONE)
  8656. continue;
  8657. memcpy(m, pm, sizeof(m));
  8658. tf = br_find_attr(&doc, c, "transform");
  8659. if (tf)
  8660. svgr_transform(m, tf);
  8661. if (svg_name_is(nm, "text")) {
  8662. unsigned int t = doc.nodes[c].first;
  8663. const char *s;
  8664. unsigned int n, tw;
  8665. double x = svg_attr_num(c, "x", 0, 0),
  8666. y = svg_attr_num(c, "y", 0, 0);
  8667. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  8668. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  8669. int tx, ty, anchor;
  8670. unsigned short col;
  8671. unsigned int pa;
  8672. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  8673. continue;
  8674. if (px < 6)
  8675. px = 6;
  8676. if (px > 72)
  8677. px = 72;
  8678. if (!svg_paint(c, &st, 1, &col, &pa))
  8679. continue;
  8680. s = doc.text + doc.nodes[t].text_off;
  8681. n = doc.nodes[t].text_len;
  8682. st.font_px = (unsigned char)px;
  8683. tw = face_text_width(ui, &st, s, n);
  8684. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  8685. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  8686. ngui_text_ascent_face(ui, style_face(&st), px,
  8687. st.mono);
  8688. anchor = st.align;
  8689. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  8690. anchor = BR_ALIGN_CENTER;
  8691. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  8692. anchor = BR_ALIGN_RIGHT;
  8693. if (anchor == BR_ALIGN_CENTER)
  8694. tx -= (int)tw / 2;
  8695. else if (anchor == BR_ALIGN_RIGHT)
  8696. tx -= (int)tw;
  8697. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  8698. col, px, st.bold, st.italic,
  8699. st.mono);
  8700. } else {
  8701. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  8702. }
  8703. }
  8704. }
  8705. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  8706. {
  8707. double vb[4];
  8708. if (svg_viewbox4(node, vb)) {
  8709. svg_viewport_matrix(node, vb, w, h, m);
  8710. } else {
  8711. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  8712. }
  8713. }
  8714. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  8715. const struct br_style *st)
  8716. {
  8717. struct svg_cache_ent *e = 0;
  8718. struct svgr_layer L;
  8719. double m[6];
  8720. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  8721. svg_cache_clock++;
  8722. for (i = 0; i < SVG_CACHE_MAX; i++)
  8723. if (svg_cache[i].px && svg_cache[i].node == node &&
  8724. svg_cache[i].w == w && svg_cache[i].h == h) {
  8725. svg_cache[i].stamp = svg_cache_clock;
  8726. return &svg_cache[i];
  8727. }
  8728. if (need > SVG_CACHE_PIXELS)
  8729. return 0;
  8730. /* Evict least recently used layers until this one fits. */
  8731. for (;;) {
  8732. struct svg_cache_ent *lru = 0, *free_slot = 0;
  8733. for (i = 0; i < SVG_CACHE_MAX; i++) {
  8734. if (!svg_cache[i].px) {
  8735. if (!free_slot)
  8736. free_slot = &svg_cache[i];
  8737. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  8738. lru = &svg_cache[i];
  8739. }
  8740. }
  8741. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  8742. e = free_slot;
  8743. break;
  8744. }
  8745. if (!lru)
  8746. return 0;
  8747. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  8748. free(lru->px);
  8749. free(lru->a);
  8750. memset(lru, 0, sizeof(*lru));
  8751. }
  8752. if (!svg_geom_buf) {
  8753. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  8754. if (!svg_geom_buf)
  8755. return 0;
  8756. }
  8757. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  8758. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  8759. e->a = (unsigned char *)calloc(need, 1);
  8760. if (!e->px || !e->a) {
  8761. free(e->px);
  8762. free(e->a);
  8763. memset(e, 0, sizeof(*e));
  8764. return 0;
  8765. }
  8766. e->node = node;
  8767. e->w = w;
  8768. e->h = h;
  8769. e->stamp = svg_cache_clock;
  8770. svg_cache_pixels += need;
  8771. L.px = e->px;
  8772. L.a = e->a;
  8773. L.w = w;
  8774. L.h = h;
  8775. svg_root_matrix(node, w, h, m);
  8776. {
  8777. double vb[4];
  8778. if (svg_viewbox4(node, vb)) {
  8779. svg_vp_w = vb[2];
  8780. svg_vp_h = vb[3];
  8781. } else {
  8782. svg_vp_w = w;
  8783. svg_vp_h = h;
  8784. }
  8785. }
  8786. svg_draw_children(&L, node, m, st, 255, 0);
  8787. return e;
  8788. }
  8789. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  8790. *
  8791. * The markup is parsed into a detached subtree of the page document and
  8792. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  8793. * bitmap, which then behaves like any decoded image. currentColor is
  8794. * black (an image has no inherited text colour); <text> is not drawn. */
  8795. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  8796. {
  8797. unsigned int i = 0;
  8798. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  8799. i = 3;
  8800. while (i < len) {
  8801. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  8802. d[i] == '\r' || d[i] == '\n'))
  8803. i++;
  8804. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  8805. return 1;
  8806. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  8807. i += 4;
  8808. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  8809. i++;
  8810. i += 3;
  8811. continue;
  8812. }
  8813. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  8814. while (i < len && d[i] != '>')
  8815. i++;
  8816. i++;
  8817. continue;
  8818. }
  8819. return 0;
  8820. }
  8821. return 0;
  8822. }
  8823. static int svg_len_attr(unsigned int node, const char *name)
  8824. {
  8825. const char *v = br_find_attr(&doc, node, name);
  8826. int n = 0, any = 0;
  8827. if (!v)
  8828. return 0;
  8829. while (*v == ' ')
  8830. v++;
  8831. while (*v >= '0' && *v <= '9') {
  8832. n = n * 10 + (*v++ - '0');
  8833. any = 1;
  8834. }
  8835. if (*v == '.')
  8836. while (*++v >= '0' && *v <= '9')
  8837. ;
  8838. if (!any || *v == '%')
  8839. return 0;
  8840. return n;
  8841. }
  8842. static int svg_decode_image(const unsigned char *data, unsigned int len,
  8843. struct br_image *bi, int box_w, int box_h)
  8844. {
  8845. unsigned int holder, svg = 0, c, need, i;
  8846. struct br_style base = base_style(), st;
  8847. struct svgr_layer L;
  8848. double vb[4], m[6];
  8849. int w, h, have_vb, nat_w, nat_h;
  8850. holder = br_create_element(&doc, "div", 3);
  8851. if (!holder) {
  8852. s_copy(bi->err, "page is full", sizeof(bi->err));
  8853. return -1;
  8854. }
  8855. holder--;
  8856. br_set_inner_html(&doc, holder, (const char *)data, len);
  8857. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  8858. if (doc.nodes[c].type == BR_NODE_ELEM &&
  8859. doc.nodes[c].tag == BR_TAG_SVG) {
  8860. svg = c;
  8861. break;
  8862. }
  8863. if (!svg) {
  8864. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  8865. return -1;
  8866. }
  8867. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  8868. w = svg_len_attr(svg, "width");
  8869. h = svg_len_attr(svg, "height");
  8870. if (box_w > 0 && box_h > 0) {
  8871. w = box_w;
  8872. h = box_h;
  8873. } else if (!w && !h) {
  8874. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  8875. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  8876. } else if (!w) {
  8877. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  8878. } else if (!h) {
  8879. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  8880. }
  8881. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  8882. * so CSS scaling stays crisp. */
  8883. nat_w = w;
  8884. nat_h = h;
  8885. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  8886. w *= 2;
  8887. h *= 2;
  8888. }
  8889. if (w > BR_IMG_LAYOUT_W) {
  8890. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  8891. w = BR_IMG_LAYOUT_W;
  8892. }
  8893. if (h > 2048)
  8894. h = 2048;
  8895. if (w < 1)
  8896. w = 1;
  8897. if (h < 1)
  8898. h = 1;
  8899. need = (unsigned int)w * (unsigned int)h;
  8900. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  8901. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  8902. return -1;
  8903. }
  8904. if (!svg_geom_buf) {
  8905. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  8906. if (!svg_geom_buf) {
  8907. s_copy(bi->err, "out of memory", sizeof(bi->err));
  8908. return -1;
  8909. }
  8910. }
  8911. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  8912. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  8913. L.a = (unsigned char *)calloc(need, 1);
  8914. if (!L.px || !L.a) {
  8915. free(L.px);
  8916. free(L.a);
  8917. s_copy(bi->err, "out of memory", sizeof(bi->err));
  8918. return -1;
  8919. }
  8920. for (i = 0; i < need; i++)
  8921. L.px[i] = 0xFFFF;
  8922. L.w = w;
  8923. L.h = h;
  8924. base.color = 0x0000;
  8925. br_style_for(&doc, svg, &base, &st);
  8926. svg_root_matrix(svg, w, h, m);
  8927. if (!have_vb && nat_w > 0 && nat_h > 0) {
  8928. /* No viewBox: user units are CSS pixels of the natural size,
  8929. * so the up-to-4x raster (and a box size) must scale them.
  8930. * A 40x20 icon used to fill only the top-left quarter of its
  8931. * 160x80 bitmap and was drawn at a quarter of its size. */
  8932. m[0] = (double)w / nat_w;
  8933. m[3] = (double)h / nat_h;
  8934. }
  8935. svg_vp_w = have_vb ? vb[2] : nat_w;
  8936. svg_vp_h = have_vb ? vb[3] : nat_h;
  8937. svg_draw_children(&L, svg, m, &st, 255, 0);
  8938. bi->native_w = nat_w;
  8939. bi->native_h = nat_h;
  8940. bi->img.format = 0;
  8941. bi->img.w = (unsigned int)w;
  8942. bi->img.h = (unsigned int)h;
  8943. bi->img.px = L.px;
  8944. bi->img.alpha = L.a;
  8945. bi->img.flags = 0;
  8946. bi->state = 1;
  8947. image_pixels += need;
  8948. return 0;
  8949. }
  8950. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  8951. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  8952. int *out_w, int *out_h)
  8953. {
  8954. double vb[4];
  8955. int has_vb = svg_viewbox4(node, vb);
  8956. double aw = svg_attr_num(node, "width", -1, cw);
  8957. double ah = svg_attr_num(node, "height", -1, 0);
  8958. int w, h;
  8959. if (st->width_kind)
  8960. w = cw;
  8961. else if (aw > 0)
  8962. w = (int)(aw + 0.5);
  8963. else if (st->height_kind == 1 && has_vb)
  8964. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  8965. else if (ah > 0 && has_vb)
  8966. w = (int)(ah * vb[2] / vb[3] + 0.5);
  8967. else if (has_vb)
  8968. w = cw;
  8969. else
  8970. w = 300;
  8971. if (st->max_width_kind == 1 && w > st->max_width)
  8972. w = st->max_width;
  8973. if (w > cw && cw > 0 && !(aw > 0))
  8974. w = cw;
  8975. if (w < 1)
  8976. w = 1;
  8977. if (w > 2000)
  8978. w = 2000;
  8979. if (st->height_kind == 1)
  8980. h = st->height;
  8981. else if (ah > 0)
  8982. h = (int)(ah + 0.5);
  8983. else if (has_vb)
  8984. h = (int)(w * vb[3] / vb[2] + 0.5);
  8985. else
  8986. h = 150;
  8987. if (h < 1)
  8988. h = 1;
  8989. if (h > 1400)
  8990. h = 1400;
  8991. *out_w = w;
  8992. *out_h = h;
  8993. }
  8994. static void svg_paint_box(struct ngui *ui, unsigned int node,
  8995. const struct br_style *st, int x, int y, int w, int h)
  8996. {
  8997. struct svg_cache_ent *e;
  8998. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  8999. int cx0, cy0, cx1, cy1, px, py;
  9000. double m[6];
  9001. if (ui->nclip > 0)
  9002. clip = ui->clip[ui->nclip - 1];
  9003. cx0 = r.x > clip.x ? r.x : clip.x;
  9004. cy0 = r.y > clip.y ? r.y : clip.y;
  9005. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  9006. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  9007. if (cx0 >= cx1 || cy0 >= cy1)
  9008. return;
  9009. e = svg_layer(node, w, h, st);
  9010. if (e) {
  9011. for (py = cy0; py < cy1; py++) {
  9012. unsigned int srow = (unsigned int)(py - y) *
  9013. (unsigned int)w;
  9014. unsigned short *dst = ui->px + py * ui->w;
  9015. for (px = cx0; px < cx1; px++) {
  9016. unsigned int si = srow + (unsigned int)(px - x);
  9017. unsigned int a = e->a[si];
  9018. if (!a)
  9019. continue;
  9020. dst[px] = a >= 255 ? e->px[si] :
  9021. blend_rgb565(dst[px], e->px[si], a);
  9022. }
  9023. }
  9024. }
  9025. svg_root_matrix(node, w, h, m);
  9026. ngui_push_clip(ui, r);
  9027. svg_draw_text(ui, node, m, st, x, y, 0);
  9028. ngui_pop_clip(ui);
  9029. }
  9030. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  9031. * keep using add_image_run(); this covers the CSS `position:absolute;
  9032. * width:100%` poster pattern used by news sites. */
  9033. static void image_block_size(unsigned int node, const struct br_style *st,
  9034. int cbw, int *out_w, int *out_h)
  9035. {
  9036. struct br_node *nd = &doc.nodes[node];
  9037. int idx = nd->img_index;
  9038. int iw = 0, ih = 0, w, h, aw, ah;
  9039. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  9040. iw = (int)images[idx].img.w;
  9041. ih = (int)images[idx].img.h;
  9042. if (iw <= 0 || ih <= 0) {
  9043. iw = (int)images[idx].native_w;
  9044. ih = (int)images[idx].native_h;
  9045. }
  9046. }
  9047. if (st->width_kind)
  9048. w = style_width_px(st, cbw);
  9049. else if (nd->width_attr)
  9050. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  9051. (int)nd->width_attr;
  9052. else if (nd->height_attr && !nd->height_pct && iw && ih)
  9053. w = iw * (int)nd->height_attr / ih;
  9054. else if (iw)
  9055. w = iw;
  9056. else
  9057. w = 64;
  9058. /* max-width/min-width against the containing block: Tailwind's
  9059. * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
  9060. * 300x300 thumbnail to its 75 px avatar box. */
  9061. if (st->max_width_kind) {
  9062. int mw = st->max_width_kind == 3 ?
  9063. cbw * st->max_width_calc_pct / 100 +
  9064. st->max_width_calc_px :
  9065. st->max_width_kind == 2 ?
  9066. cbw * (int)st->max_width / 100 : (int)st->max_width;
  9067. if (mw > 0 && w > mw)
  9068. w = mw;
  9069. }
  9070. if (st->min_width_kind) {
  9071. int mn = st->min_width_kind == 3 ?
  9072. cbw * st->min_width_calc_pct / 100 +
  9073. st->min_width_calc_px :
  9074. st->min_width_kind == 2 ?
  9075. cbw * (int)st->min_width / 100 : (int)st->min_width;
  9076. if (mn > w)
  9077. w = mn;
  9078. }
  9079. if (w < 8)
  9080. w = 8;
  9081. if (cbw > 0 && w > cbw)
  9082. w = cbw;
  9083. /* Without a CSS height the attributes (or the bitmap) only give the
  9084. * aspect ratio: a width clamped by max-width scales the height too,
  9085. * instead of letterboxing the image into its attribute height. */
  9086. aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
  9087. ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
  9088. if (st->height_kind)
  9089. h = style_height_px(st, cbw);
  9090. else if (aw > 0 && ah > 0)
  9091. h = w * ah / aw;
  9092. else if (nd->height_attr)
  9093. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  9094. (int)nd->height_attr;
  9095. else
  9096. h = 64;
  9097. if (h < 8)
  9098. h = 8;
  9099. *out_w = w;
  9100. *out_h = h;
  9101. }
  9102. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  9103. int dw, int dh)
  9104. {
  9105. int idx = doc.nodes[node].img_index;
  9106. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  9107. struct img_image *src = image_display_get(&images[idx], dw, dh);
  9108. struct img_blit b;
  9109. if (!src)
  9110. src = &images[idx].img;
  9111. b.dst = l->ui->px;
  9112. b.dst_w = l->ui->w;
  9113. b.dst_h = l->ui->h;
  9114. b.clip_x = page_rect.x;
  9115. b.clip_y = page_rect.y;
  9116. b.clip_w = page_rect.w - 12;
  9117. b.clip_h = page_rect.h;
  9118. b.x = x;
  9119. b.y = y;
  9120. b.scale = ((unsigned int)dw << 16) / src->w;
  9121. b.bg = ui.theme.bg;
  9122. b.bg2 = ui.theme.bg;
  9123. b.dst_a = 0;
  9124. /* OVER_DST is only needed for an alpha source; an opaque one can
  9125. * take img_draw's 1:1 copy path. */
  9126. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  9127. img_draw(src, &b);
  9128. } else if (l->draw) {
  9129. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  9130. 0xD69A);
  9131. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  9132. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  9133. }
  9134. }
  9135. static int intrinsic_width(struct ngui *ui, unsigned int node,
  9136. const struct br_style *pst, int depth, int base);
  9137. static void layout_block(struct lay *l, unsigned int node,
  9138. const struct br_style *st, int depth,
  9139. unsigned short link)
  9140. {
  9141. int old_left = l->left, old_right = l->right, old_align = l->align;
  9142. int parent_cb_h = l->cb_h;
  9143. int saved_parent_top = l->parent_top;
  9144. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  9145. int saved_cb_top = l->cb_top;
  9146. int top, l0, r0;
  9147. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  9148. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  9149. int deco_w, deco_h, content_w, content_h, box_h;
  9150. int img_dh = 0;
  9151. int definite_w = 0;
  9152. int normal_top = 0;
  9153. int rel_dx = 0, rel_dy = 0;
  9154. int clip_pushed = 0;
  9155. struct ngui_rect clip_rect;
  9156. /* A DOM level costs about two depth units (layout_block ->
  9157. * layout_children), so 48 covers a ~24-level page. Real news pages
  9158. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  9159. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  9160. return;
  9161. flow_y = l->y;
  9162. flow_left = l->left;
  9163. flow_right = l->right;
  9164. positioned = st->pos == 1 || st->pos == 2;
  9165. relative = st->pos == 3;
  9166. sticky = st->pos == 4;
  9167. shifted = relative || sticky || st->transform_set;
  9168. if (positioned) {
  9169. int def_w = st->width_kind == 1 ? st->width : -1;
  9170. if (st->pos == 2) {
  9171. int avail_w = page_rect.w - 12;
  9172. if (st->right_set && def_w >= 0)
  9173. l->left = page_rect.x + avail_w - st->right -
  9174. def_w;
  9175. else if (!st->left_set && !st->right_set)
  9176. l->left = flow_left; /* static position */
  9177. else
  9178. l->left = page_rect.x +
  9179. (st->left_set ? st->left : 0);
  9180. l->right = def_w >= 0 ? l->left + def_w :
  9181. st->width_kind == 2 ?
  9182. l->left + avail_w * (int)st->width / 100 :
  9183. page_rect.x + avail_w;
  9184. /* Placed by `bottom` (a page footer): an auto
  9185. * height is the measured one. */
  9186. if (st->bottom_set && st->height_kind)
  9187. l->y = page_rect.y + page_rect.h -
  9188. st->bottom -
  9189. style_height_px(st, page_rect.w);
  9190. else if (st->bottom_set && !st->top_set &&
  9191. block_h[node])
  9192. l->y = page_rect.y + page_rect.h -
  9193. st->bottom - (int)block_h[node] -
  9194. mp_px(st, 0, avail_w) -
  9195. mp_px(st, 2, avail_w);
  9196. else
  9197. l->y = page_rect.y +
  9198. (st->top_set ? st->top : 0);
  9199. } else {
  9200. int left = flow_left + (st->left_set ? st->left : 0);
  9201. unsigned int parent = doc.nodes[node].parent;
  9202. if (st->right_set && def_w >= 0)
  9203. left = flow_right - st->right - def_w;
  9204. l->left = left;
  9205. l->right = def_w >= 0 ? left + def_w :
  9206. flow_right +
  9207. (st->left_set ? st->left : 0);
  9208. l->y = flow_y + (st->top_set ? st->top : 0);
  9209. if (st->bottom_set && st->height_kind &&
  9210. parent < BR_MAX_NODES && block_h[parent] > 0)
  9211. l->y = flow_y + block_h[parent] - st->bottom -
  9212. style_height_px(st, old_right - old_left);
  9213. else if (st->bottom_set && !st->top_set &&
  9214. parent < BR_MAX_NODES && block_h[parent] > 0 &&
  9215. block_h[node] > 0)
  9216. l->y = flow_y + block_h[parent] - st->bottom -
  9217. (int)block_h[node] -
  9218. mp_px(st, 0, old_right - old_left) -
  9219. mp_px(st, 2, old_right - old_left);
  9220. }
  9221. /* An auto width placed by one horizontal offset is
  9222. * shrink-to-fit (CSS 2.1 10.3.7): a Bootstrap tooltip or a
  9223. * dropdown is as wide as its content, not its containing
  9224. * block. With neither offset the box keeps the containing
  9225. * width, since `inset: 0` overlays are not parsed and only
  9226. * stretch that way; an empty measure keeps it too. */
  9227. if (st->width_kind == 0 && st->left_set != st->right_set) {
  9228. int cb_l = st->pos == 2 ? page_rect.x : flow_left;
  9229. int cb_r = st->pos == 2 ? page_rect.x +
  9230. page_rect.w - 12 : flow_right;
  9231. int avail = cb_r - cb_l - (st->left_set ? st->left :
  9232. st->right);
  9233. int w = intrinsic_width(l->ui, node, st, 0,
  9234. cb_r - cb_l);
  9235. if (w > 0) {
  9236. w += mp_px(st, 7, cb_r - cb_l) +
  9237. mp_px(st, 5, cb_r - cb_l) +
  9238. mp_px(st, 3, cb_r - cb_l) +
  9239. mp_px(st, 1, cb_r - cb_l) +
  9240. st->border_w[1] + st->border_w[3];
  9241. if (st->max_width_kind == 1 &&
  9242. w > (int)st->max_width)
  9243. w = (int)st->max_width;
  9244. if (avail > 8 && w > avail)
  9245. w = avail;
  9246. if (st->right_set) {
  9247. l->right = cb_r - st->right;
  9248. l->left = l->right - w;
  9249. } else {
  9250. l->right = l->left + w;
  9251. }
  9252. }
  9253. }
  9254. /* `left: 100%` parks a box (Docusaurus' "Skip to main
  9255. * content" link) past the containing block's right edge
  9256. * until it is focused. An auto width then has no room: it
  9257. * used to collapse to 8 px and wrap one word per line into a
  9258. * tall column painted over the page. Lay it out at the
  9259. * containing block's width so it stays one line and
  9260. * overflows (off-screen) like in a real browser. */
  9261. if (def_w < 0 && l->right - l->left < 8) {
  9262. int avail = st->pos == 2 ? page_rect.w - 12 :
  9263. flow_right - flow_left;
  9264. l->right = l->left + (avail > 8 ? avail : 8);
  9265. }
  9266. old_left = l->left;
  9267. old_right = l->right;
  9268. } else if (relative) {
  9269. rel_dx = st->left_set ? st->left :
  9270. (st->right_set ? -st->right : 0);
  9271. rel_dy = st->top_set ? st->top :
  9272. (st->bottom_set ? -st->bottom : 0);
  9273. }
  9274. if (st->transform_set) {
  9275. rel_dx += st->tx;
  9276. rel_dy += st->ty;
  9277. }
  9278. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  9279. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  9280. doc.nodes[node].tag == BR_TAG_SELECT ||
  9281. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  9282. !button_has_elements(node)) {
  9283. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  9284. s_eq(br_type(&doc, node), "hidden"))
  9285. return;
  9286. /* Reached as a block-level box (a flex item): the control
  9287. * fills the box the caller assigned, and its line is flushed
  9288. * here; flex layout resets the run list for the next item, so
  9289. * a queued run would never be drawn. */
  9290. form_fill_line = 1;
  9291. add_form_run(l, node, st, link);
  9292. form_fill_line = 0;
  9293. flush_line(l);
  9294. return;
  9295. }
  9296. flush_line(l);
  9297. cbw = old_right - old_left;
  9298. if (cbw < 8)
  9299. cbw = 8;
  9300. l->y += mp_px(st, 0, cbw);
  9301. top = l->y;
  9302. ml = mp_px(st, 3, cbw);
  9303. mr = mp_px(st, 1, cbw);
  9304. bl = st->border_w[3];
  9305. br = st->border_w[1];
  9306. pl = mp_px(st, 7, cbw);
  9307. pr = mp_px(st, 5, cbw);
  9308. bt = st->border_w[0];
  9309. bb = st->border_w[2];
  9310. pt = mp_px(st, 4, cbw);
  9311. pb = mp_px(st, 6, cbw);
  9312. deco_w = bl + br + pl + pr;
  9313. deco_h = bt + bb + pt + pb;
  9314. if (st->width_kind) {
  9315. int w;
  9316. if (st->width_kind == 3)
  9317. w = cbw * st->width_calc_pct / 100 +
  9318. st->width_calc_px;
  9319. else
  9320. w = css_size(st->width_kind, st->width, cbw);
  9321. if (w < 0)
  9322. w = 0;
  9323. content_w = st->box_sizing ? w - deco_w : w;
  9324. definite_w = 1;
  9325. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  9326. doc.nodes[node].tag == BR_TAG_TD ||
  9327. doc.nodes[node].tag == BR_TAG_TH) &&
  9328. doc.nodes[node].width_attr) {
  9329. /* Legacy table/cell width attributes: percentages resolve
  9330. * against the containing block, bare numbers are pixels. */
  9331. int w = doc.nodes[node].width_pct ?
  9332. cbw * doc.nodes[node].width_attr / 100 :
  9333. doc.nodes[node].width_attr;
  9334. if (w < 0)
  9335. w = 0;
  9336. content_w = st->box_sizing ? w - deco_w : w;
  9337. definite_w = 1;
  9338. } else {
  9339. content_w = cbw - ml - mr - deco_w;
  9340. }
  9341. if (content_w < 0)
  9342. content_w = 0;
  9343. if (st->max_width_kind) {
  9344. int mw = st->max_width_kind == 3 ?
  9345. cbw * st->max_width_calc_pct / 100 +
  9346. st->max_width_calc_px :
  9347. css_size(st->max_width_kind, st->max_width, cbw);
  9348. int max_box = st->box_sizing ? mw : mw + deco_w;
  9349. /* A clamped auto width is used as the width, so auto
  9350. * margins share the rest (Google's 688 px search box). */
  9351. if (content_w + deco_w > max_box) {
  9352. content_w = max_box - deco_w;
  9353. definite_w = 1;
  9354. }
  9355. }
  9356. if (st->min_width_kind) {
  9357. int mw = st->min_width_kind == 3 ?
  9358. cbw * st->min_width_calc_pct / 100 +
  9359. st->min_width_calc_px :
  9360. css_size(st->min_width_kind, st->min_width, cbw);
  9361. int min_box = st->box_sizing ? mw : mw + deco_w;
  9362. if (content_w + deco_w < min_box) {
  9363. content_w = min_box - deco_w;
  9364. definite_w = 1;
  9365. }
  9366. }
  9367. if (content_w < 8)
  9368. content_w = 8;
  9369. if (definite_w) {
  9370. int free_w = cbw - ml - mr - deco_w - content_w;
  9371. if (free_w < 0)
  9372. free_w = 0;
  9373. if (st->ml_auto && st->mr_auto) {
  9374. ml = free_w / 2;
  9375. mr = free_w - ml;
  9376. } else if (st->ml_auto) {
  9377. ml = free_w;
  9378. } else if (st->mr_auto) {
  9379. mr = free_w;
  9380. }
  9381. }
  9382. if (doc.nodes[node].tag == BR_TAG_IMG) {
  9383. int iw, ih;
  9384. image_block_size(node, st, cbw, &iw, &ih);
  9385. content_w = iw;
  9386. img_dh = ih;
  9387. }
  9388. l0 = old_left + ml;
  9389. r0 = l0 + deco_w + content_w;
  9390. if (r0 < l0 + 8)
  9391. r0 = l0 + 8;
  9392. normal_top = top;
  9393. if (sticky) {
  9394. if (st->top_set) {
  9395. int stick = page_rect.y + st->top;
  9396. if (normal_top < stick)
  9397. rel_dy += stick - normal_top;
  9398. } else if (st->bottom_set && block_h[node]) {
  9399. int stick = page_rect.y + page_rect.h - st->bottom -
  9400. block_h[node];
  9401. if (normal_top > stick)
  9402. rel_dy += stick - normal_top;
  9403. }
  9404. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  9405. block_h[doc.nodes[node].parent]) {
  9406. unsigned int p = doc.nodes[node].parent;
  9407. int ptop = l->parent_top;
  9408. int pbottom = ptop + block_h[p];
  9409. int eh = block_h[node];
  9410. int moved_top = normal_top + rel_dy;
  9411. int moved_bottom = moved_top + eh;
  9412. if (moved_bottom > pbottom)
  9413. rel_dy -= moved_bottom - pbottom;
  9414. moved_top = normal_top + rel_dy;
  9415. if (moved_top < ptop)
  9416. rel_dy += ptop - moved_top;
  9417. }
  9418. }
  9419. if (shifted && l->draw) {
  9420. top += rel_dy;
  9421. l0 += rel_dx;
  9422. r0 += rel_dx;
  9423. }
  9424. l->parent_top = top;
  9425. if (st->pos != 0) {
  9426. /* Positioned boxes establish the containing block for their
  9427. * absolutely positioned descendants. */
  9428. l->cb_left = l0;
  9429. l->cb_right = r0;
  9430. l->cb_top = top;
  9431. }
  9432. if (l->draw && block_h[node] &&
  9433. top < page_rect.y + page_rect.h &&
  9434. top + block_h[node] > page_rect.y) {
  9435. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  9436. int rtl = css_radius(st, 0, box.w, box.h);
  9437. int rtr = css_radius(st, 1, box.w, box.h);
  9438. int rbr = css_radius(st, 2, box.w, box.h);
  9439. int rbl = css_radius(st, 3, box.w, box.h);
  9440. if (st->transform_scale) {
  9441. if (st->has_bg)
  9442. fill_transformed_rect(l->ui, box, st->bg, st);
  9443. } else if (rtl || rtr || rbr || rbl) {
  9444. if (st->has_bg) {
  9445. int bw = st->border_w[0];
  9446. if (bw > 0 && !st->border_t[0] &&
  9447. st->border_c[0] != st->bg &&
  9448. box.w > bw * 2 && box.h > bw * 2) {
  9449. struct ngui_rect inner = {
  9450. box.x + bw, box.y + bw,
  9451. box.w - bw * 2, box.h - bw * 2
  9452. };
  9453. int itl = rtl > bw ? rtl - bw : 0;
  9454. int itr = rtr > bw ? rtr - bw : 0;
  9455. int ibr = rbr > bw ? rbr - bw : 0;
  9456. int ibl = rbl > bw ? rbl - bw : 0;
  9457. ngui_fill_round_rect(l->ui, box, rtl,
  9458. rtr, rbr, rbl,
  9459. st->border_c[0]);
  9460. ngui_fill_round_rect(l->ui, inner,
  9461. itl, itr, ibr,
  9462. ibl, st->bg);
  9463. } else {
  9464. ngui_fill_round_rect(l->ui, box, rtl,
  9465. rtr, rbr, rbl,
  9466. st->bg);
  9467. }
  9468. } else if (st->border_w[0] && !st->border_t[0]) {
  9469. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  9470. rbl, st->border_w[0],
  9471. st->border_c[0]);
  9472. }
  9473. /* Rounded boxes paint their background image too
  9474. * (app icons are rounded squares), kept inside the
  9475. * corner arcs. */
  9476. if (st->bg_image)
  9477. draw_bg_image_round(l, box, node, st, rtl, rtr,
  9478. rbr, rbl);
  9479. } else {
  9480. if (st->has_bg)
  9481. ngui_fill_rect(l->ui, box, st->bg);
  9482. if (st->bg_image)
  9483. draw_bg_image(l, box, node, st);
  9484. if (st->border_w[0] || st->border_w[1] ||
  9485. st->border_w[2] || st->border_w[3])
  9486. draw_border_box(l->ui, box, st);
  9487. }
  9488. }
  9489. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  9490. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  9491. content_w, img_dh);
  9492. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  9493. l->ui && l->ui->nclip < 4) {
  9494. clip_rect.x = l0 + bl;
  9495. clip_rect.y = top + bt;
  9496. clip_rect.w = (r0 - l0) - bl - br;
  9497. clip_rect.h = (int)block_h[node] - bt - bb;
  9498. if (clip_rect.w > 0 && clip_rect.h > 0) {
  9499. ngui_push_clip(l->ui, clip_rect);
  9500. clip_pushed = 1;
  9501. }
  9502. }
  9503. l->left = l0 + bl + pl;
  9504. l->right = l->left + content_w;
  9505. if (l->right < l->left + 8)
  9506. l->right = l->left + 8;
  9507. l->align = st->align;
  9508. l->line_left = l->left;
  9509. l->line_right = l->right;
  9510. l->y = top + bt + pt;
  9511. if (doc.nodes[node].tag == BR_TAG_HR) {
  9512. if (l->draw)
  9513. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  9514. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  9515. l->y += 8;
  9516. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  9517. int vw = l->right - l->left;
  9518. int vh;
  9519. if (doc.nodes[node].width_pct)
  9520. vw = vw * doc.nodes[node].width_attr / 100;
  9521. else if (doc.nodes[node].width_attr)
  9522. vw = doc.nodes[node].width_attr;
  9523. if (vw > l->right - l->left)
  9524. vw = l->right - l->left;
  9525. if (vw < 8)
  9526. vw = 8;
  9527. vh = vw * 9 / 16;
  9528. if (vh > 240)
  9529. vh = 240;
  9530. if (vh < 80)
  9531. vh = 80;
  9532. if (l->draw) {
  9533. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  9534. vw, vh}, 0xD69A);
  9535. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  9536. vw, vh}, 0x8410);
  9537. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  9538. 0x4208);
  9539. }
  9540. l->y += vh + 4;
  9541. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  9542. int dw, dh, cw = l->right - l->left;
  9543. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  9544. if (l->draw && l->y < page_rect.y + page_rect.h &&
  9545. l->y + dh > page_rect.y)
  9546. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  9547. l->y += dh;
  9548. } else {
  9549. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  9550. !st->no_bullet) {
  9551. char *m = li_marker[node];
  9552. if (!m[0]) {
  9553. unsigned int parent = doc.nodes[node].parent;
  9554. int style = st->list_style;
  9555. int idx = parent ? list_index(parent, node) : 1;
  9556. if (style == BR_LIST_AUTO)
  9557. style = (parent &&
  9558. doc.nodes[parent].tag ==
  9559. BR_TAG_OL) ?
  9560. BR_LIST_DECIMAL : BR_LIST_DISC;
  9561. list_marker_text(m, sizeof(li_marker[node]),
  9562. style, idx);
  9563. }
  9564. if (l->draw && m[0]) {
  9565. int mw = (int)ngui_text_width_ui(l->ui, m);
  9566. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  9567. st->color);
  9568. }
  9569. }
  9570. /* This box's definite content height, for its children's
  9571. * percentage heights. */
  9572. if (doc.nodes[node].tag == BR_TAG_HTML ||
  9573. doc.nodes[node].tag == BR_TAG_BODY)
  9574. l->cb_h = layout_view_h;
  9575. else if (st->height_kind == 1)
  9576. l->cb_h = (int)st->height -
  9577. (st->box_sizing ? deco_h : 0);
  9578. else if (st->height_kind == 2 && parent_cb_h > 0)
  9579. l->cb_h = parent_cb_h * (int)st->height / 100 -
  9580. (st->box_sizing ? deco_h : 0);
  9581. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  9582. l->cb_h = content_w * (int)st->aspect_h /
  9583. (int)st->aspect_w;
  9584. else if (!st->height_kind && node < BR_MAX_NODES &&
  9585. flex_stretch_h[node] > deco_h)
  9586. l->cb_h = flex_stretch_h[node] - deco_h;
  9587. else
  9588. l->cb_h = 0;
  9589. if (l->cb_h < 0)
  9590. l->cb_h = 0;
  9591. if (doc.nodes[node].tag == BR_TAG_TR)
  9592. layout_table_row(l, node, st, depth + 1, link);
  9593. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  9594. table_has_rowspan(node))
  9595. layout_table(l, node, st, depth + 1, link);
  9596. else if (st->grid_auto)
  9597. layout_grid_auto(l, node, st, depth + 1, link);
  9598. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  9599. st->grid_gap > 0)
  9600. layout_grid_children(l, node, st, depth + 1, link);
  9601. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  9602. flex_wants_row(node, st))
  9603. layout_flex_children(l, node, st, depth + 1, link);
  9604. else if (st->display == BR_DISPLAY_FLEX && st->flex_col)
  9605. layout_flex_column(l, node, st, depth + 1, link);
  9606. else
  9607. layout_children(l, node, st, depth + 1, link);
  9608. l->cb_h = parent_cb_h;
  9609. }
  9610. flush_line(l);
  9611. if (clip_pushed)
  9612. ngui_pop_clip(l->ui);
  9613. if (l->float_active) {
  9614. if (l->y < l->float_bottom)
  9615. l->y = l->float_bottom;
  9616. l->float_active = 0;
  9617. }
  9618. if (doc.nodes[node].tag == BR_TAG_IMG) {
  9619. content_h = img_dh;
  9620. } else if (st->height_kind == 2 &&
  9621. doc.nodes[node].tag != BR_TAG_HTML &&
  9622. doc.nodes[node].tag != BR_TAG_BODY) {
  9623. /* A percentage of the containing block's definite height, or
  9624. * auto when it has none (it used to resolve against the
  9625. * width). The result is a minimum: without scrollable inner
  9626. * boxes, an app shell's height:100%; overflow:hidden column
  9627. * would otherwise clip everything past the first screen. */
  9628. int auto_h = l->y - (top + bt + pt);
  9629. content_h = parent_cb_h > 0 ?
  9630. parent_cb_h * (int)st->height / 100 -
  9631. (st->box_sizing ? deco_h : 0) : 0;
  9632. if (content_h < auto_h)
  9633. content_h = auto_h;
  9634. } else if (st->height_kind &&
  9635. !((doc.nodes[node].tag == BR_TAG_HTML ||
  9636. doc.nodes[node].tag == BR_TAG_BODY) &&
  9637. st->height_kind == 2)) {
  9638. content_h = style_height_px(st, cbw);
  9639. if (st->box_sizing)
  9640. content_h -= deco_h;
  9641. } else {
  9642. /* Percentage heights on html/body resolve against the
  9643. * viewport, but their content still defines the document
  9644. * scroll height. Treating them as auto avoids collapsing
  9645. * the measured page to the containing block width. */
  9646. content_h = l->y - (top + bt + pt);
  9647. /* aspect-ratio: the preferred height of an auto-height box
  9648. * (Tailwind aspect-video image frames); content can still
  9649. * make it taller, as with min-height: auto. */
  9650. if (st->aspect_w && st->aspect_h && content_w > 0) {
  9651. int ah = content_w * (int)st->aspect_h /
  9652. (int)st->aspect_w;
  9653. if (content_h < ah)
  9654. content_h = ah;
  9655. }
  9656. }
  9657. if (content_h < 0)
  9658. content_h = 0;
  9659. if (!st->height_kind && node < BR_MAX_NODES &&
  9660. content_h + deco_h < flex_stretch_h[node])
  9661. content_h = flex_stretch_h[node] - deco_h;
  9662. if (st->max_height_kind) {
  9663. int mh = st->max_height_kind == 3 ?
  9664. cbw * st->max_height_calc_pct / 100 +
  9665. st->max_height_calc_px :
  9666. css_size(st->max_height_kind, st->max_height, cbw);
  9667. int max_box = st->box_sizing ? mh : mh + deco_h;
  9668. if (content_h + deco_h > max_box)
  9669. content_h = max_box - deco_h;
  9670. }
  9671. if (st->min_height_kind &&
  9672. !((doc.nodes[node].tag == BR_TAG_HTML ||
  9673. doc.nodes[node].tag == BR_TAG_BODY) &&
  9674. st->min_height_kind == 2)) {
  9675. int mh = st->min_height_kind == 3 ?
  9676. cbw * st->min_height_calc_pct / 100 +
  9677. st->min_height_calc_px :
  9678. css_size(st->min_height_kind, st->min_height, cbw);
  9679. int min_box = st->box_sizing ? mh : mh + deco_h;
  9680. if (content_h + deco_h < min_box)
  9681. content_h = min_box - deco_h;
  9682. }
  9683. if (content_h < 0)
  9684. content_h = 0;
  9685. box_h = deco_h + content_h;
  9686. if (box_h < 0)
  9687. box_h = 0;
  9688. l->y = (shifted ? normal_top : top) + box_h;
  9689. if (node < BR_MAX_NODES) {
  9690. layout_boxes[node].x = l0;
  9691. layout_boxes[node].y = top;
  9692. layout_boxes[node].w = r0 - l0;
  9693. layout_boxes[node].h = box_h;
  9694. layout_boxes[node].valid = r0 > l0;
  9695. }
  9696. l->left = old_left;
  9697. l->right = old_right;
  9698. l->align = old_align;
  9699. l->y += mp_px(st, 2, cbw);
  9700. if (!l->draw) {
  9701. if (box_h > 65535)
  9702. box_h = 65535;
  9703. block_h[node] = (unsigned short)box_h;
  9704. block_top[node] = (unsigned short)(top < 0 ? 0 :
  9705. top > 65535 ? 65535 : top);
  9706. }
  9707. if (positioned) {
  9708. l->y = flow_y;
  9709. l->left = flow_left;
  9710. l->right = flow_right;
  9711. }
  9712. l->parent_top = saved_parent_top;
  9713. l->cb_left = saved_cb_left;
  9714. l->cb_right = saved_cb_right;
  9715. l->cb_top = saved_cb_top;
  9716. }
  9717. static int text_node_blank(const struct br_node *nd)
  9718. {
  9719. const char *t = doc.text + nd->text_off;
  9720. unsigned int i;
  9721. for (i = 0; i < nd->text_len; i++)
  9722. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  9723. t[i] != '\r')
  9724. return 0;
  9725. return 1;
  9726. }
  9727. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  9728. * text/image widths in the subtree, plus padding and margins. This keeps
  9729. * Bootstrap's floated nav items on one line instead of giving each the whole
  9730. * row. */
  9731. static int text_space(char c)
  9732. {
  9733. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  9734. }
  9735. static int intrinsic_width(struct ngui *ui, unsigned int node,
  9736. const struct br_style *pst, int depth, int base)
  9737. {
  9738. unsigned int c;
  9739. int line_w = 0, max_w = 0;
  9740. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  9741. if (depth > 32)
  9742. return 0;
  9743. if (doc.npe_rules) {
  9744. struct br_style ps;
  9745. /* Icon boxes (::before/::after with a size) are inline
  9746. * content of the element. */
  9747. line_w += pseudo_box_w(node, pst, 1, &ps, base) +
  9748. pseudo_box_w(node, pst, 2, &ps, base);
  9749. }
  9750. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9751. struct br_node *nd = &doc.nodes[c];
  9752. struct br_style cs;
  9753. if (nd->type == BR_NODE_TEXT) {
  9754. const char *t = doc.text + nd->text_off;
  9755. unsigned int tn = nd->text_len;
  9756. if (doc.nodes[node].tag == BR_TAG_PRE) {
  9757. line_w += (int)face_text_width(ui, pst, t, tn);
  9758. } else {
  9759. unsigned int ti = 0;
  9760. int first = 1;
  9761. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  9762. int sp = (int)face_text_width(ui, pst, " ", 1);
  9763. while (ti < tn) {
  9764. unsigned int ts;
  9765. while (ti < tn && text_space(t[ti]))
  9766. ti++;
  9767. ts = ti;
  9768. while (ti < tn && !text_space(t[ti]))
  9769. ti++;
  9770. if (ti == ts)
  9771. break;
  9772. if (!first || lead)
  9773. line_w += sp;
  9774. lead = 0;
  9775. line_w += (int)face_text_width(ui, pst,
  9776. t + ts, ti - ts);
  9777. first = 0;
  9778. }
  9779. }
  9780. continue;
  9781. }
  9782. br_style_for(&doc, c, pst, &cs);
  9783. /* Absolute/fixed children take no room in the parent's
  9784. * shrink-to-fit width: a shown Bootstrap tooltip widened the
  9785. * floated navbar list and slid the hovered item away. */
  9786. if (cs.display == BR_DISPLAY_NONE || cs.pos == 1 ||
  9787. cs.pos == 2)
  9788. continue;
  9789. if (nd->tag == BR_TAG_BR) {
  9790. if (line_w > max_w)
  9791. max_w = line_w;
  9792. line_w = 0;
  9793. continue;
  9794. }
  9795. if (nd->tag == BR_TAG_IMG) {
  9796. /* Measure the image as layout will draw it: a CSS or
  9797. * attribute height keeps the intrinsic aspect ratio, and
  9798. * a CSS width overrides the native pixel width. Bootstrap
  9799. * sizes the Cloudron logo with height:40px only. */
  9800. int idx = nd->img_index;
  9801. int iw = 0, ih = 0;
  9802. if (idx >= 0 && idx < image_count &&
  9803. images[idx].state == 1) {
  9804. iw = (int)images[idx].native_w;
  9805. ih = (int)images[idx].native_h;
  9806. if (iw <= 0 || ih <= 0) {
  9807. iw = (int)images[idx].img.w;
  9808. ih = (int)images[idx].img.h;
  9809. }
  9810. }
  9811. if (cs.width_kind) {
  9812. int ww = style_width_px(&cs, base);
  9813. line_w += ww > 0 ? ww : 64;
  9814. } else if (nd->width_attr) {
  9815. line_w += nd->width_attr;
  9816. } else if (nd->height_attr && iw && ih) {
  9817. line_w += iw * (int)nd->height_attr / ih;
  9818. } else if (cs.height_kind && iw && ih) {
  9819. /* A percentage height needs the parent's
  9820. * definite height (the logo's 2rem box), as in
  9821. * add_image_run(); otherwise it is auto. */
  9822. int hh = cs.height_kind == 1 ?
  9823. style_height_px(&cs, base) :
  9824. cs.height_kind == 2 &&
  9825. pst->height_kind == 1 ?
  9826. (int)pst->height * (int)cs.height / 100 :
  9827. 0;
  9828. line_w += hh > 0 ? iw * hh / ih : iw;
  9829. } else if (iw) {
  9830. line_w += iw;
  9831. } else {
  9832. line_w += 64;
  9833. }
  9834. continue;
  9835. }
  9836. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  9837. nd->tag == BR_TAG_TEXTAREA) &&
  9838. !s_eq(br_type(&doc, c), "hidden")) {
  9839. /* Form controls are replaced: CSS width applies even
  9840. * when they are inline (add_form_run's sizes). */
  9841. int fw = cs.width_kind ? style_width_px(&cs, base) :
  9842. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  9843. if (s_eq(br_type(&doc, c), "checkbox") ||
  9844. s_eq(br_type(&doc, c), "radio"))
  9845. fw = 16;
  9846. line_w += (fw > 0 ? fw : 120) +
  9847. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  9848. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  9849. continue;
  9850. }
  9851. if (nd->tag == BR_TAG_SVG) {
  9852. /* A replaced element: its own size, like add_svg_run()
  9853. * (its path children have no width). */
  9854. int sw, sh, sb = cs.width_kind ?
  9855. style_width_px(&cs, base) : base;
  9856. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  9857. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  9858. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  9859. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  9860. line_w += sw;
  9861. } else {
  9862. if (line_w > max_w)
  9863. max_w = line_w;
  9864. line_w = 0;
  9865. if (sw > max_w)
  9866. max_w = sw;
  9867. }
  9868. continue;
  9869. }
  9870. {
  9871. int cw = mp_px(&cs, 7, base) +
  9872. mp_px(&cs, 5, base) +
  9873. mp_px(&cs, 3, base) +
  9874. mp_px(&cs, 1, base) +
  9875. cs.border_w[1] + cs.border_w[3];
  9876. /* width/height do not apply to non-replaced inline
  9877. * boxes. The tagesschau home label is an inline span
  9878. * with width:1px for the mobile icon-only header; using
  9879. * that width made the whole subnav collapse to a
  9880. * one-character column. */
  9881. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  9882. cw += cs.width_kind == 1 ? cs.width :
  9883. style_width_px(&cs, base);
  9884. else
  9885. cw += intrinsic_width(ui, c, &cs, depth + 1,
  9886. base);
  9887. if (flex_row || cs.float_left ||
  9888. cs.display == BR_DISPLAY_INLINE ||
  9889. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  9890. line_w += cw;
  9891. } else {
  9892. if (line_w > max_w)
  9893. max_w = line_w;
  9894. line_w = 0;
  9895. if (cw > max_w)
  9896. max_w = cw;
  9897. }
  9898. }
  9899. if (line_w > 4096 || max_w > 4096)
  9900. break;
  9901. }
  9902. return line_w > max_w ? line_w : max_w;
  9903. }
  9904. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  9905. * the main user: .row > .col-md-* with float:left and a percentage width.
  9906. * Each column is laid out with its own left/right edge and the row advances
  9907. * to the tallest column. Returns the first child not consumed. */
  9908. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  9909. const struct br_style *pst, int depth,
  9910. unsigned short link)
  9911. {
  9912. unsigned int n = first;
  9913. int row_left = l->left, row_right = l->right;
  9914. int row_top, row_bottom, xl, xr, any = 0;
  9915. int fl_left = row_left, fl_right = row_right, fl_bottom;
  9916. flush_line(l);
  9917. row_top = l->y;
  9918. row_bottom = l->y;
  9919. fl_bottom = row_top;
  9920. xl = row_left;
  9921. xr = row_right;
  9922. while (n) {
  9923. struct br_node *nd = &doc.nodes[n];
  9924. struct br_style cs;
  9925. unsigned short lk = link;
  9926. int colw, right;
  9927. if (nd->type == BR_NODE_TEXT) {
  9928. if (text_node_blank(nd)) {
  9929. n = nd->next;
  9930. continue;
  9931. }
  9932. break;
  9933. }
  9934. br_style_for(&doc, n, pst, &cs);
  9935. if (cs.display == BR_DISPLAY_NONE) {
  9936. n = nd->next;
  9937. continue;
  9938. }
  9939. /* A float blockifies its box: Bootstrap floats inline
  9940. * anchors too (the navbar brand and its text links), and
  9941. * their padding must be honoured. */
  9942. /* An absolute/fixed sibling is out of flow and does not end
  9943. * the row: Bootstrap inserts its tooltip right after the
  9944. * hovered navbar <li>, and the row used to break there. */
  9945. if (!cs.float_left && (cs.pos == 1 || cs.pos == 2)) {
  9946. int sy = l->y, sl = l->left, sr = l->right;
  9947. layout_out_of_flow(l, n, &cs, depth, lk);
  9948. l->y = sy;
  9949. l->left = sl;
  9950. l->right = sr;
  9951. n = nd->next;
  9952. continue;
  9953. }
  9954. if (!cs.float_left)
  9955. break;
  9956. if (nd->tag == BR_TAG_A && nd->href_off)
  9957. lk = (unsigned short)n;
  9958. right = cs.float_left == 2;
  9959. if (cs.width_kind == 1 || cs.width_kind == 2 ||
  9960. cs.width_kind == 3) {
  9961. /* The column is the margin box: `width` is the
  9962. * content (or, with border-box, the border) box,
  9963. * and layout_block() takes margins, padding and
  9964. * borders back out of the column. A 200px float
  9965. * with margin-right:20px used to get 180px of
  9966. * content. */
  9967. int base = row_right - row_left;
  9968. colw = cs.width_kind == 1 ? (int)cs.width :
  9969. style_width_px(&cs, base);
  9970. colw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  9971. if (!cs.box_sizing)
  9972. colw += mp_px(&cs, 7, base) +
  9973. mp_px(&cs, 5, base) +
  9974. cs.border_w[1] + cs.border_w[3];
  9975. } else {
  9976. int base = row_right - row_left;
  9977. /* Shrink-to-fit outer width: borders too (Google's
  9978. * 1px-bordered "Anmelden" pill wrapped otherwise). */
  9979. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  9980. mp_px(&cs, 7, base) +
  9981. mp_px(&cs, 5, base) +
  9982. mp_px(&cs, 3, base) +
  9983. mp_px(&cs, 1, base) +
  9984. cs.border_w[1] + cs.border_w[3];
  9985. if (colw < 8)
  9986. colw = 8;
  9987. }
  9988. if (colw < 8)
  9989. colw = 8;
  9990. if (colw > row_right - row_left)
  9991. colw = row_right - row_left;
  9992. /* The float column width is already resolved. */
  9993. cs.width_kind = 0;
  9994. cs.max_width_kind = 0;
  9995. if (right) {
  9996. if (any && xr - colw < xl) {
  9997. row_top = row_bottom;
  9998. row_bottom = row_top;
  9999. xl = row_left;
  10000. xr = row_right;
  10001. }
  10002. if (xr - colw < xl)
  10003. colw = xr - xl;
  10004. if (colw < 8)
  10005. colw = 8;
  10006. l->left = xr - colw;
  10007. if (l->left < row_left)
  10008. l->left = row_left;
  10009. l->right = xr;
  10010. xr = l->left;
  10011. if (xr < fl_right)
  10012. fl_right = xr;
  10013. } else {
  10014. if (any && xl + colw > xr) {
  10015. row_top = row_bottom;
  10016. row_bottom = row_top;
  10017. xl = row_left;
  10018. xr = row_right;
  10019. }
  10020. l->left = xl;
  10021. l->right = xl + colw;
  10022. xl += colw;
  10023. if (xl > fl_left)
  10024. fl_left = xl;
  10025. }
  10026. if (l->right < l->left + 8)
  10027. l->right = l->left + 8;
  10028. l->y = row_top;
  10029. l->line_left = l->line_x = l->left;
  10030. l->run_x = l->left;
  10031. l->line_y = l->y;
  10032. l->line_h = 0;
  10033. l->nruns = 0;
  10034. l->space_pending = 0;
  10035. l->align = cs.align;
  10036. layout_block(l, n, &cs, depth + 1, lk);
  10037. if (l->y > row_bottom)
  10038. row_bottom = l->y;
  10039. if (l->y > fl_bottom)
  10040. fl_bottom = l->y;
  10041. any = 1;
  10042. n = nd->next;
  10043. }
  10044. l->left = row_left;
  10045. l->right = row_right;
  10046. if (n && any) {
  10047. struct br_node *nd = &doc.nodes[n];
  10048. int inline_next = 0;
  10049. if (nd->type == BR_NODE_TEXT) {
  10050. inline_next = 1;
  10051. } else if (nd->type == BR_NODE_ELEM) {
  10052. struct br_style cs;
  10053. br_style_for(&doc, n, pst, &cs);
  10054. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  10055. cs.display != BR_DISPLAY_NONE &&
  10056. !br_tag_is_block(nd->tag);
  10057. }
  10058. if (inline_next) {
  10059. if (l->float_active) {
  10060. if (l->float_left > fl_left)
  10061. fl_left = l->float_left;
  10062. if (l->float_right < fl_right)
  10063. fl_right = l->float_right;
  10064. if (l->float_bottom > fl_bottom)
  10065. fl_bottom = l->float_bottom;
  10066. }
  10067. l->float_active = 1;
  10068. l->float_left = fl_left;
  10069. l->float_right = fl_right;
  10070. l->float_bottom = fl_bottom;
  10071. l->y = row_top;
  10072. } else {
  10073. l->float_active = 0;
  10074. l->y = row_bottom;
  10075. }
  10076. } else {
  10077. l->float_active = 0;
  10078. l->y = row_bottom;
  10079. }
  10080. l->line_x = l->left;
  10081. l->run_x = l->left;
  10082. l->line_left = l->left;
  10083. l->line_right = l->right;
  10084. l->line_y = l->y;
  10085. l->line_h = 0;
  10086. l->nruns = 0;
  10087. l->space_pending = 0;
  10088. return n;
  10089. }
  10090. static int flex_item_width(struct lay *l, unsigned int n,
  10091. const struct br_style *cs, int avail)
  10092. {
  10093. struct br_node *nd = &doc.nodes[n];
  10094. (void)l;
  10095. int w;
  10096. if (cs->width_kind == 2 || cs->width_kind == 3)
  10097. w = style_width_px(cs, avail);
  10098. else if (cs->width_kind == 1)
  10099. w = (int)cs->width;
  10100. else if (nd->tag == BR_TAG_IMG) {
  10101. int idx = nd->img_index;
  10102. if (idx >= 0 && idx < image_count &&
  10103. images[idx].state == 1)
  10104. w = (int)images[idx].img.w;
  10105. else if (nd->width_attr)
  10106. w = (int)nd->width_attr;
  10107. else
  10108. w = 64;
  10109. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  10110. nd->tag == BR_TAG_TEXTAREA) {
  10111. /* A control has no content to measure: its default size
  10112. * (a search field in a filter bar). */
  10113. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  10114. } else {
  10115. w = intrinsic_width(l->ui, n, cs, 0, avail);
  10116. }
  10117. /* Explicit widths are content-box sizes; the flex item's outer width
  10118. * must include padding, borders and margins. */
  10119. w += mp_px(cs, 7, avail);
  10120. w += mp_px(cs, 5, avail);
  10121. w += mp_px(cs, 3, avail);
  10122. w += mp_px(cs, 1, avail);
  10123. w += cs->border_w[1] + cs->border_w[3];
  10124. if (w < 24)
  10125. w = 24;
  10126. if (w > avail)
  10127. w = avail;
  10128. return w;
  10129. }
  10130. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  10131. int depth);
  10132. /* An inline child of a text-only inline-block: the same test minus the
  10133. * display check (an inline <span> may have padding/background in CSS, but
  10134. * the inline path paints those for spans anyway). */
  10135. static int inline_block_flows_inline(unsigned int node,
  10136. const struct br_style *cs, int depth)
  10137. {
  10138. unsigned int c;
  10139. if (depth > 3 || cs->pos)
  10140. return 0;
  10141. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  10142. const struct br_node *nd = &doc.nodes[c];
  10143. struct br_style ch;
  10144. if (nd->type != BR_NODE_ELEM)
  10145. continue;
  10146. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  10147. br_tag_is_block(nd->tag))
  10148. return 0;
  10149. br_style_for(&doc, c, cs, &ch);
  10150. if (ch.display == BR_DISPLAY_NONE)
  10151. continue;
  10152. if (ch.display != BR_DISPLAY_INLINE ||
  10153. !inline_block_flows_inline(c, &ch, depth + 1))
  10154. return 0;
  10155. }
  10156. return 1;
  10157. }
  10158. /* An inline-block that is only text in a line (a <time> in a byline, a
  10159. * label) with no box of its own -- no size, background, border or padding
  10160. * -- lays out exactly like an inline element, so it stays in the text line
  10161. * instead of ending it. Boxes with any of those keep the row path. */
  10162. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  10163. int depth)
  10164. {
  10165. unsigned int c;
  10166. int i;
  10167. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  10168. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  10169. cs->pos || depth > 3)
  10170. return 0;
  10171. for (i = 0; i < 4; i++)
  10172. if (cs->border_w[i])
  10173. return 0;
  10174. for (i = 4; i < 8; i++)
  10175. if (mp_px(cs, i, 0) > 0)
  10176. return 0;
  10177. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  10178. const struct br_node *nd = &doc.nodes[c];
  10179. struct br_style ch;
  10180. if (nd->type != BR_NODE_ELEM)
  10181. continue;
  10182. if (nd->tag == BR_TAG_SVG) {
  10183. /* An icon box (Docusaurus' admonition heading:
  10184. * `<span inline-block><svg/></span>Note`): the SVG
  10185. * is an inline replaced run, so the box can stay in
  10186. * the text line. */
  10187. br_style_for(&doc, c, cs, &ch);
  10188. if (ch.display == BR_DISPLAY_NONE ||
  10189. ch.display == BR_DISPLAY_INLINE ||
  10190. ch.display == BR_DISPLAY_INLINE_BLOCK)
  10191. continue;
  10192. return 0;
  10193. }
  10194. if (nd->tag == BR_TAG_IMG || br_tag_is_block(nd->tag))
  10195. return 0;
  10196. br_style_for(&doc, c, cs, &ch);
  10197. if (ch.display == BR_DISPLAY_NONE)
  10198. continue;
  10199. if (ch.display != BR_DISPLAY_INLINE ||
  10200. !inline_block_flows_inline(c, &ch, depth + 1))
  10201. return 0;
  10202. }
  10203. return 1;
  10204. }
  10205. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  10206. * on one line, not one full-width block each. Place intrinsic widths from
  10207. * left to right and wrap when the row is full. */
  10208. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  10209. const struct br_style *pst, int depth,
  10210. unsigned short link)
  10211. {
  10212. unsigned int n = first;
  10213. int row_left = l->left, row_right = l->right;
  10214. int avail = row_right - row_left;
  10215. int x = row_left, y = l->y, row_h = 0, any = 0;
  10216. /* Each box sets l->align from its own style; the text after the row
  10217. * must keep the container's (a centred .fa-fw icon centred the menu
  10218. * label that followed it). */
  10219. unsigned char row_align = l->align;
  10220. flush_line(l);
  10221. y = l->y;
  10222. while (n) {
  10223. struct br_node *nd = &doc.nodes[n];
  10224. struct br_style cs;
  10225. unsigned short lk = link;
  10226. int colw, h;
  10227. if (nd->type == BR_NODE_TEXT) {
  10228. if (!text_node_blank(nd))
  10229. break;
  10230. if (any)
  10231. x += 4;
  10232. n = nd->next;
  10233. continue;
  10234. }
  10235. br_style_for(&doc, n, pst, &cs);
  10236. if (cs.display == BR_DISPLAY_NONE) {
  10237. n = nd->next;
  10238. continue;
  10239. }
  10240. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  10241. break;
  10242. if (nd->tag == BR_TAG_A && nd->href_off)
  10243. lk = (unsigned short)n;
  10244. colw = flex_item_width(l, n, &cs, avail);
  10245. /* A few pixels of slack keep a single long token (boot.S)
  10246. * from wrapping at the exact content width. */
  10247. colw += 8;
  10248. if (colw > avail)
  10249. colw = avail;
  10250. cs.width_kind = 0;
  10251. cs.max_width_kind = 0;
  10252. if (any && x + colw > row_right) {
  10253. y += row_h + 2;
  10254. x = row_left;
  10255. row_h = 0;
  10256. any = 0;
  10257. }
  10258. if (any && x > row_left)
  10259. x += 4;
  10260. l->left = x;
  10261. l->right = x + colw;
  10262. if (l->right < l->left + 8)
  10263. l->right = l->left + 8;
  10264. l->y = y;
  10265. l->line_left = l->line_x = l->left;
  10266. l->run_x = l->left;
  10267. l->line_y = l->y;
  10268. l->line_h = 0;
  10269. l->nruns = 0;
  10270. l->space_pending = 0;
  10271. l->align = cs.align;
  10272. layout_block(l, n, &cs, depth + 1, lk);
  10273. h = l->y - y;
  10274. if (h > row_h)
  10275. row_h = h;
  10276. x += colw;
  10277. any = 1;
  10278. n = nd->next;
  10279. }
  10280. if (any)
  10281. y += row_h;
  10282. l->left = row_left;
  10283. l->right = row_right;
  10284. l->align = row_align;
  10285. l->y = y;
  10286. l->line_left = l->line_x = l->left;
  10287. l->run_x = l->left;
  10288. l->line_y = l->y;
  10289. l->line_h = 0;
  10290. l->nruns = 0;
  10291. l->space_pending = 0;
  10292. return n;
  10293. }
  10294. struct flex_item {
  10295. unsigned int node;
  10296. unsigned short link;
  10297. int w;
  10298. };
  10299. /* An item's min-width/max-width as outer (margin-box) widths in the flex
  10300. * row, or -1 when unset. Percentages and calc() resolve against the
  10301. * container width. */
  10302. static int flex_limit_w(const struct br_style *cs, int which_max, int avail)
  10303. {
  10304. unsigned char kind = which_max ? cs->max_width_kind :
  10305. cs->min_width_kind;
  10306. int w;
  10307. if (kind == 3)
  10308. w = which_max ?
  10309. avail * cs->max_width_calc_pct / 100 +
  10310. cs->max_width_calc_px :
  10311. avail * cs->min_width_calc_pct / 100 +
  10312. cs->min_width_calc_px;
  10313. else
  10314. w = css_size(kind, which_max ? cs->max_width : cs->min_width,
  10315. avail);
  10316. if (w < 0)
  10317. return -1;
  10318. if (!cs->box_sizing)
  10319. w += mp_px(cs, 7, avail) + mp_px(cs, 5, avail) +
  10320. cs->border_w[1] + cs->border_w[3];
  10321. return w + mp_px(cs, 3, avail) + mp_px(cs, 1, avail);
  10322. }
  10323. static int flex_clamp_w(const struct br_style *cs, int w, int avail)
  10324. {
  10325. int mx = flex_limit_w(cs, 1, avail), mn = flex_limit_w(cs, 0, avail);
  10326. if (mx >= 0 && w > mx)
  10327. w = mx;
  10328. if (mn >= 0 && w < mn)
  10329. w = mn;
  10330. return w;
  10331. }
  10332. /* Does a flex row stretch this item to the line height? Only items with
  10333. * no height of their own and align-self/align-items stretch; replaced
  10334. * content (images, icons) keeps its aspect ratio. */
  10335. static int flex_item_stretches(unsigned int node, const struct br_style *cs,
  10336. const struct br_style *pst)
  10337. {
  10338. int ai = cs->align_self ? cs->align_self - 1 : pst->align_items;
  10339. unsigned char tag = doc.nodes[node].tag;
  10340. return ai == 0 && !cs->height_kind && !cs->max_height_kind &&
  10341. tag != BR_TAG_IMG && tag != BR_TAG_SVG && tag != BR_TAG_INPUT &&
  10342. tag != BR_TAG_SELECT && tag != BR_TAG_TEXTAREA &&
  10343. tag != BR_TAG_BUTTON;
  10344. }
  10345. static void flex_set_stretch(unsigned int node, const struct br_style *cs,
  10346. int line_h, int cbw)
  10347. {
  10348. int h = line_h - mp_px(cs, 0, cbw) - mp_px(cs, 2, cbw);
  10349. if (node >= BR_MAX_NODES || h <= 0)
  10350. return;
  10351. if (h > 65535)
  10352. h = 65535;
  10353. flex_stretch_h[node] = (unsigned short)h;
  10354. if (block_h[node] < h)
  10355. block_h[node] = (unsigned short)h;
  10356. }
  10357. static void layout_flex_children(struct lay *l, unsigned int parent,
  10358. const struct br_style *pst, int depth,
  10359. unsigned short link)
  10360. {
  10361. struct flex_item it[32];
  10362. unsigned int c;
  10363. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  10364. int grow_need = 0; /* growing items at their content width */
  10365. int row_left = l->left, row_right = l->right;
  10366. int avail = row_right - row_left;
  10367. int idx, row_top;
  10368. unsigned char row_align = l->align;
  10369. int box_left = l->left, box_right = l->right, row_top0 = l->y;
  10370. int bw = 0, aw = 0, first_h = -1;
  10371. int cont_h = l->cb_h; /* the container's definite content height */
  10372. struct br_style bps, aps;
  10373. if (avail < 8 || depth > 48) {
  10374. layout_children(l, parent, pst, depth, link);
  10375. return;
  10376. }
  10377. /* If direct text is not just whitespace, normal block flow handles it
  10378. * better than pretending it is a flex item. */
  10379. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10380. struct br_node *nd = &doc.nodes[c];
  10381. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  10382. layout_children(l, parent, pst, depth, link);
  10383. return;
  10384. }
  10385. }
  10386. /* ::before/::after icon boxes are the row's first and last items
  10387. * (Docusaurus' sidebar chevron): reserve their columns. */
  10388. if (doc.npe_rules) {
  10389. bw = pseudo_box_w(parent, pst, 1, &bps, avail);
  10390. aw = pseudo_box_w(parent, pst, 2, &aps, avail);
  10391. if (bw + aw > avail - 8) {
  10392. bw = 0;
  10393. aw = 0;
  10394. }
  10395. row_left += bw;
  10396. row_right -= aw;
  10397. avail = row_right - row_left;
  10398. }
  10399. for (c = doc.nodes[parent].first;
  10400. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  10401. c = doc.nodes[c].next) {
  10402. struct br_node *nd = &doc.nodes[c];
  10403. struct br_style cs;
  10404. if (nd->type == BR_NODE_TEXT)
  10405. continue;
  10406. br_style_for(&doc, c, pst, &cs);
  10407. if (cs.display == BR_DISPLAY_NONE)
  10408. continue;
  10409. if ((cs.pos == 1 || cs.pos == 2) &&
  10410. layout_out_of_flow(l, c, &cs, depth,
  10411. (nd->tag == BR_TAG_A && nd->href_off) ?
  10412. (unsigned short)c : link))
  10413. continue; /* absolutely positioned: not an item */
  10414. it[nitem].node = c;
  10415. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  10416. (unsigned short)c : link;
  10417. it[nitem].w = 0;
  10418. if (cs.flex_grow && !cs.width_kind) {
  10419. grow_count++;
  10420. grow_need += flex_item_width(l, c, &cs, avail);
  10421. } else
  10422. fixed += flex_clamp_w(&cs,
  10423. flex_item_width(l, c, &cs, avail),
  10424. avail);
  10425. nitem++;
  10426. }
  10427. /* A narrow container (an icon row sized to its content, Google's
  10428. * mic + lens buttons) is still a row when its items fit; only a
  10429. * narrow one that would overflow or squeeze growing items falls
  10430. * back to block flow. */
  10431. if (avail < 160 && fixed + grow_need > avail) {
  10432. layout_children(l, parent, pst, depth, link);
  10433. return;
  10434. }
  10435. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  10436. /* A growing item capped by max-width (Docusaurus' doc column,
  10437. * `max-width: 75%`; its main container, `calc(100% - 300px)`)
  10438. * keeps its cap and leaves the rest of the free space to the other
  10439. * growing items. */
  10440. if (grow_count) {
  10441. int pass, capped[32] = { 0 };
  10442. for (pass = 0; pass < nitem; pass++) {
  10443. int changed = 0;
  10444. for (idx = 0; idx < nitem; idx++) {
  10445. struct br_style cs;
  10446. int lim;
  10447. if (capped[idx])
  10448. continue;
  10449. br_style_for(&doc, it[idx].node, pst, &cs);
  10450. if (!cs.flex_grow || cs.width_kind)
  10451. continue;
  10452. lim = flex_clamp_w(&cs, grow_w, avail);
  10453. if (lim == grow_w)
  10454. continue;
  10455. capped[idx] = lim + 1;
  10456. fixed += lim;
  10457. grow_count--;
  10458. changed = 1;
  10459. }
  10460. if (!changed || !grow_count)
  10461. break;
  10462. grow_w = (avail - fixed) / grow_count;
  10463. }
  10464. for (idx = 0; idx < nitem; idx++)
  10465. it[idx].w = capped[idx] ? capped[idx] - 1 : 0;
  10466. }
  10467. if (grow_w < 96 && avail >= 160)
  10468. grow_w = 96;
  10469. for (idx = 0; idx < nitem; idx++) {
  10470. struct br_style cs;
  10471. if (it[idx].w)
  10472. continue; /* capped growing item */
  10473. br_style_for(&doc, it[idx].node, pst, &cs);
  10474. if (cs.flex_grow && !cs.width_kind)
  10475. it[idx].w = grow_w;
  10476. else
  10477. it[idx].w = flex_clamp_w(&cs,
  10478. flex_item_width(l,
  10479. it[idx].node,
  10480. &cs, avail),
  10481. avail);
  10482. if (it[idx].w > avail)
  10483. it[idx].w = avail;
  10484. if (it[idx].w < 8)
  10485. it[idx].w = 8;
  10486. }
  10487. row_top = l->y;
  10488. idx = 0;
  10489. while (idx < nitem) {
  10490. int start = idx, count = 0, row_w = 0;
  10491. int free_w, x, extra = 0, row_h = 0, k;
  10492. while (idx < nitem) {
  10493. int add = it[idx].w + (count ? gap : 0);
  10494. /* CSS default is nowrap; only flex-wrap: wrap (1)
  10495. * starts a new row. */
  10496. if (count && pst->flex_wrap == 1 &&
  10497. row_w + add > avail)
  10498. break;
  10499. row_w += add;
  10500. count++;
  10501. idx++;
  10502. }
  10503. if (!count) {
  10504. count = 1;
  10505. row_w = it[start].w;
  10506. idx = start + 1;
  10507. }
  10508. free_w = avail - row_w;
  10509. if (free_w < 0)
  10510. free_w = 0;
  10511. x = row_left;
  10512. if (pst->justify == 1) {
  10513. x += free_w / 2;
  10514. } else if (pst->justify == 2) {
  10515. x += free_w;
  10516. } else if (pst->justify == 3) {
  10517. extra = count > 1 ? free_w / (count - 1) : 0;
  10518. } else if (pst->justify == 4) {
  10519. extra = count ? free_w / count : 0;
  10520. x += extra / 2;
  10521. } else if (pst->justify == 5) {
  10522. extra = count ? free_w / (count + 1) : 0;
  10523. x += extra;
  10524. }
  10525. for (k = 0; k < count; k++) {
  10526. int node = (int)it[start + k].node;
  10527. int h = block_h[node];
  10528. if (h > row_h)
  10529. row_h = h;
  10530. }
  10531. /* A single line fills a definite container height (an app
  10532. * shell's `height: 100%` sidebar + content row). */
  10533. if (pst->flex_wrap != 1 && cont_h > row_h)
  10534. row_h = cont_h;
  10535. else if (pst->height_kind == 1 && (int)pst->height > row_h)
  10536. row_h = pst->height;
  10537. for (k = 0; k < count; k++) {
  10538. struct br_style cs;
  10539. int node = (int)it[start + k].node;
  10540. int yoff = 0;
  10541. br_style_for(&doc, node, pst, &cs);
  10542. cs.width_kind = 0;
  10543. cs.max_width_kind = 0;
  10544. /* align-items: stretch. With a definite line height
  10545. * the item is laid out at it, so its own children see
  10546. * a definite height; otherwise the measure pass
  10547. * stretches it once the line is known (below). */
  10548. if (!l->draw && row_h > 0 && flex_item_stretches(node,
  10549. &cs, pst))
  10550. flex_set_stretch(node, &cs, row_h, avail);
  10551. {
  10552. int ai = cs.align_self ? cs.align_self - 1 :
  10553. pst->align_items;
  10554. if (l->draw && ai && row_h > block_h[node]) {
  10555. if (ai == 1)
  10556. yoff = (row_h -
  10557. block_h[node]) / 2;
  10558. else if (ai == 2)
  10559. yoff = row_h - block_h[node];
  10560. }
  10561. }
  10562. l->left = x;
  10563. l->right = x + it[start + k].w;
  10564. if (l->right < l->left + 8)
  10565. l->right = l->left + 8;
  10566. l->y = row_top + yoff;
  10567. /* line_left too: a stale one from the previous item
  10568. * made flush_line() see a non-empty line and push
  10569. * every later item down by an empty line's height. */
  10570. l->line_left = l->line_x = l->run_x = l->left;
  10571. l->line_right = l->right;
  10572. l->line_y = l->y;
  10573. l->line_h = 0;
  10574. l->nruns = 0;
  10575. l->space_pending = 0;
  10576. l->align = cs.align;
  10577. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  10578. {
  10579. /* Both passes: a form control item has no
  10580. * block_h of its own, so the draw pass would
  10581. * otherwise end a row of only an <input> at
  10582. * height 0 and pull the content below up. */
  10583. int h = l->y - row_top;
  10584. if (h > row_h)
  10585. row_h = h;
  10586. }
  10587. x += it[start + k].w;
  10588. if (k + 1 < count)
  10589. x += gap + extra;
  10590. }
  10591. if (!l->draw) {
  10592. for (k = 0; k < count; k++) {
  10593. struct br_style cs;
  10594. int node = (int)it[start + k].node;
  10595. br_style_for(&doc, node, pst, &cs);
  10596. if (!flex_item_stretches(node, &cs, pst))
  10597. continue;
  10598. /* To the line's bottom edge from where the
  10599. * item really starts (its top margin, or a
  10600. * line box above it). */
  10601. if (layout_boxes[node].valid)
  10602. flex_set_stretch(node, &cs,
  10603. row_top + row_h -
  10604. layout_boxes[node].y +
  10605. mp_px(&cs, 0, avail), avail);
  10606. else
  10607. flex_set_stretch(node, &cs, row_h, avail);
  10608. }
  10609. }
  10610. if (first_h < 0)
  10611. first_h = row_h;
  10612. row_top += row_h;
  10613. }
  10614. if (bw || aw) {
  10615. int pass;
  10616. for (pass = 0; pass < 2; pass++) {
  10617. const struct br_style *ps = pass ? &aps : &bps;
  10618. int a = pass ? row_right : box_left;
  10619. int b = pass ? box_right : row_left;
  10620. int h = ps->height_kind ?
  10621. style_height_px(ps, box_right - box_left) : 0;
  10622. if (!(pass ? aw : bw))
  10623. continue;
  10624. l->left = l->line_left = l->line_x = l->run_x = a;
  10625. l->right = l->line_right = b;
  10626. l->y = row_top0;
  10627. if (pst->align_items == 1 && first_h > h)
  10628. l->y += (first_h - h) / 2;
  10629. l->line_y = l->y;
  10630. l->line_h = 0;
  10631. l->nruns = 0;
  10632. l->space_pending = 0;
  10633. emit_pseudo_box(l, pst, ps, link);
  10634. flush_line(l);
  10635. /* The box sits inside the first row; it only makes
  10636. * the row taller when it is taller itself. */
  10637. if (row_top0 + h > row_top)
  10638. row_top = row_top0 + h;
  10639. }
  10640. }
  10641. l->left = box_left;
  10642. l->right = box_right;
  10643. l->align = row_align;
  10644. l->y = row_top;
  10645. l->line_left = l->line_x = l->run_x = l->left;
  10646. l->line_right = l->right;
  10647. l->line_y = l->y;
  10648. l->line_h = 0;
  10649. l->nruns = 0;
  10650. l->space_pending = 0;
  10651. }
  10652. /* flex-direction: column. Items stack in order with the gap and never
  10653. * collapse margins. In the draw pass justify-content shares out the free
  10654. * height of the container's measured box (a definite or min-height, or a
  10655. * row stretch), and align-items places each item: stretch (the default)
  10656. * fills the line, start/center/end shrink an item to its content width
  10657. * (a login form's "Log in" button, a centred logo and name). */
  10658. static void layout_flex_column(struct lay *l, unsigned int parent,
  10659. const struct br_style *pst, int depth,
  10660. unsigned short link)
  10661. {
  10662. unsigned int c;
  10663. int box_left = l->left, box_right = l->right;
  10664. int avail = box_right - box_left;
  10665. int gap = pst->grid_gap, y0 = l->y;
  10666. int n = 0, k = 0, total = 0, lead = 0, extra = 0;
  10667. unsigned char row_align = l->align;
  10668. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10669. struct br_node *nd = &doc.nodes[c];
  10670. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd))
  10671. break;
  10672. }
  10673. if (c || avail < 8 || depth > 48) {
  10674. /* Loose text: block flow, with centred lines standing in
  10675. * for align-items: center. */
  10676. struct br_style cst = *pst;
  10677. if (pst->align_items == 1) {
  10678. cst.align = BR_ALIGN_CENTER;
  10679. l->align = BR_ALIGN_CENTER;
  10680. }
  10681. layout_children(l, parent, &cst, depth, link);
  10682. return;
  10683. }
  10684. emit_pseudo(l, parent, pst, 1, link);
  10685. flush_line(l);
  10686. y0 = l->y;
  10687. if (l->draw && parent < BR_MAX_NODES && block_h[parent]) {
  10688. int inner = (int)block_h[parent] - pst->border_w[0] -
  10689. pst->border_w[2] - mp_px(pst, 4, avail) -
  10690. mp_px(pst, 6, avail) - (y0 - l->parent_top -
  10691. pst->border_w[0] - mp_px(pst, 4, avail));
  10692. int free_h;
  10693. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10694. struct br_style cs;
  10695. if (doc.nodes[c].type != BR_NODE_ELEM)
  10696. continue;
  10697. br_style_for(&doc, c, pst, &cs);
  10698. if (cs.display == BR_DISPLAY_NONE || cs.pos == 1 ||
  10699. cs.pos == 2)
  10700. continue;
  10701. total += block_h[c] + mp_px(&cs, 0, avail) +
  10702. mp_px(&cs, 2, avail);
  10703. n++;
  10704. }
  10705. if (n > 1)
  10706. total += gap * (n - 1);
  10707. free_h = inner - total;
  10708. if (n && free_h > 0) {
  10709. if (pst->justify == 1) {
  10710. lead = free_h / 2;
  10711. } else if (pst->justify == 2) {
  10712. lead = free_h;
  10713. } else if (pst->justify == 3) {
  10714. extra = n > 1 ? free_h / (n - 1) : 0;
  10715. } else if (pst->justify == 4) {
  10716. extra = free_h / n;
  10717. lead = extra / 2;
  10718. } else if (pst->justify == 5) {
  10719. extra = free_h / (n + 1);
  10720. lead = extra;
  10721. }
  10722. }
  10723. }
  10724. l->y = y0 + lead;
  10725. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10726. struct br_node *nd = &doc.nodes[c];
  10727. unsigned short lk = (nd->tag == BR_TAG_A && nd->href_off) ?
  10728. (unsigned short)c : link;
  10729. struct br_style cs;
  10730. int ai, left = box_left, right = box_right;
  10731. if (nd->type != BR_NODE_ELEM)
  10732. continue;
  10733. br_style_for(&doc, c, pst, &cs);
  10734. if (cs.display == BR_DISPLAY_NONE)
  10735. continue;
  10736. if ((cs.pos == 1 || cs.pos == 2) &&
  10737. layout_out_of_flow(l, c, &cs, depth, lk))
  10738. continue;
  10739. if (k++)
  10740. l->y += gap + extra;
  10741. ai = cs.align_self ? cs.align_self - 1 : pst->align_items;
  10742. if (ai) {
  10743. int w = flex_clamp_w(&cs, flex_item_width(l, c, &cs,
  10744. avail),
  10745. avail);
  10746. if (ai == 1)
  10747. left += (avail - w) / 2;
  10748. else if (ai == 2)
  10749. left += avail - w;
  10750. right = left + w;
  10751. cs.width_kind = 0;
  10752. cs.max_width_kind = 0;
  10753. }
  10754. l->left = l->line_left = l->line_x = l->run_x = left;
  10755. l->right = l->line_right = right;
  10756. l->line_y = l->y;
  10757. l->line_h = 0;
  10758. l->nruns = 0;
  10759. l->space_pending = 0;
  10760. l->align = cs.align;
  10761. layout_block(l, c, &cs, depth + 1, lk);
  10762. }
  10763. l->left = l->line_left = l->line_x = l->run_x = box_left;
  10764. l->right = l->line_right = box_right;
  10765. l->align = row_align;
  10766. l->line_y = l->y;
  10767. l->line_h = 0;
  10768. l->nruns = 0;
  10769. l->space_pending = 0;
  10770. emit_pseudo(l, parent, pst, 2, link);
  10771. }
  10772. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  10773. * plus the grid-area hints used by site shells (site notice/footer full
  10774. * width, column-start left, page-content right). Anything more elaborate
  10775. * falls back to normal block flow. */
  10776. static int grid_track_width(unsigned char kind, unsigned short val,
  10777. int avail, int other)
  10778. {
  10779. if (kind == 2)
  10780. return avail * (int)val / 100;
  10781. if (kind == 1)
  10782. return val;
  10783. return other;
  10784. }
  10785. static void layout_grid_children(struct lay *l, unsigned int parent,
  10786. const struct br_style *pst, int depth,
  10787. unsigned short link)
  10788. {
  10789. unsigned int n;
  10790. int row_left = l->left, row_right = l->right;
  10791. int avail = row_right - row_left;
  10792. int gap = pst->grid_gap;
  10793. int track_total = avail - gap;
  10794. int col0, col1, x0, x1;
  10795. int row_y, row_bottom, have_left = 0, have_right = 0;
  10796. unsigned int c;
  10797. if (avail < 32 || depth > 48)
  10798. return;
  10799. if (track_total < 16)
  10800. track_total = 16;
  10801. col0 = grid_track_width((unsigned char)(pst->width_kind),
  10802. pst->width, track_total, 0);
  10803. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  10804. pst->max_width, track_total, 0);
  10805. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  10806. int w0 = pst->width ? pst->width : 1;
  10807. int w1 = pst->max_width ? pst->max_width : 1;
  10808. col0 = track_total * w0 / (w0 + w1);
  10809. col1 = track_total - col0;
  10810. } else if (pst->width_kind == 3) {
  10811. col0 = track_total - col1;
  10812. if (col0 < 24)
  10813. col0 = 24;
  10814. } else if (pst->max_width_kind == 3) {
  10815. col1 = track_total - col0;
  10816. if (col1 < 24)
  10817. col1 = 24;
  10818. }
  10819. if (col0 < 24)
  10820. col0 = 24;
  10821. if (col1 < 24)
  10822. col1 = 24;
  10823. if (col0 + col1 > track_total) {
  10824. col1 = track_total - col0;
  10825. if (col1 < 24)
  10826. col1 = 24;
  10827. }
  10828. x0 = row_left;
  10829. x1 = row_left + col0 + gap;
  10830. /* Direct text makes a grid ambiguous; use block flow instead. */
  10831. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10832. struct br_node *nd = &doc.nodes[c];
  10833. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  10834. layout_children(l, parent, pst, depth, link);
  10835. return;
  10836. }
  10837. }
  10838. row_y = row_bottom = l->y;
  10839. n = doc.nodes[parent].first;
  10840. while (n) {
  10841. struct br_node *nd = &doc.nodes[n];
  10842. struct br_style cs;
  10843. unsigned short lk = link;
  10844. int slot, x, w;
  10845. if (nd->type == BR_NODE_TEXT) {
  10846. n = nd->next;
  10847. continue;
  10848. }
  10849. br_style_for(&doc, n, pst, &cs);
  10850. if (cs.display == BR_DISPLAY_NONE) {
  10851. n = nd->next;
  10852. continue;
  10853. }
  10854. if (nd->tag == BR_TAG_A && nd->href_off)
  10855. lk = (unsigned short)n;
  10856. slot = cs.grid_slot;
  10857. if (!slot) {
  10858. if (!have_left)
  10859. slot = 2;
  10860. else if (!have_right)
  10861. slot = 3;
  10862. else
  10863. slot = 2;
  10864. }
  10865. if (slot == 1) {
  10866. if (have_left || have_right) {
  10867. row_y = row_bottom;
  10868. have_left = have_right = 0;
  10869. }
  10870. x = row_left;
  10871. w = avail;
  10872. } else if (slot == 2) {
  10873. if (have_left) {
  10874. row_y = row_bottom;
  10875. have_left = have_right = 0;
  10876. }
  10877. x = x0;
  10878. w = col0;
  10879. have_left = 1;
  10880. } else {
  10881. if (have_right) {
  10882. row_y = row_bottom;
  10883. have_left = have_right = 0;
  10884. }
  10885. x = x1;
  10886. w = col1;
  10887. have_right = 1;
  10888. }
  10889. cs.width_kind = 0;
  10890. cs.max_width_kind = 0;
  10891. l->left = x;
  10892. l->right = x + w;
  10893. if (l->right < l->left + 8)
  10894. l->right = l->left + 8;
  10895. l->y = row_y;
  10896. l->line_left = l->line_x = l->left;
  10897. l->run_x = l->left;
  10898. l->line_y = l->y;
  10899. l->line_h = 0;
  10900. l->nruns = 0;
  10901. l->space_pending = 0;
  10902. l->align = cs.align;
  10903. layout_block(l, n, &cs, depth + 1, lk);
  10904. if (l->y > row_bottom)
  10905. row_bottom = l->y;
  10906. n = nd->next;
  10907. }
  10908. l->left = row_left;
  10909. l->right = row_right;
  10910. l->y = row_bottom;
  10911. l->line_left = l->line_x = l->left;
  10912. l->run_x = l->left;
  10913. l->line_y = l->y;
  10914. l->line_h = 0;
  10915. l->nruns = 0;
  10916. l->space_pending = 0;
  10917. }
  10918. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  10919. * capped at four. Used by the project docs' card grids. A fixed
  10920. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  10921. static void layout_grid_auto(struct lay *l, unsigned int parent,
  10922. const struct br_style *pst, int depth,
  10923. unsigned short link)
  10924. {
  10925. unsigned int n, c;
  10926. int row_left = l->left, row_right = l->right;
  10927. int avail = row_right - row_left;
  10928. int gap = pst->grid_gap;
  10929. int minw = pst->width_kind == 1 ? pst->width : 200;
  10930. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  10931. if (avail < 32 || depth > 48) {
  10932. layout_children(l, parent, pst, depth, link);
  10933. return;
  10934. }
  10935. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10936. struct br_node *nd = &doc.nodes[c];
  10937. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  10938. layout_children(l, parent, pst, depth, link);
  10939. return;
  10940. }
  10941. }
  10942. if (minw < 80)
  10943. minw = 80;
  10944. ncols = (avail + gap) / (minw + gap);
  10945. if (ncols < 1)
  10946. ncols = 1;
  10947. if (ncols > 4)
  10948. ncols = 4;
  10949. if (pst->grid_auto > BR_GRID_FIXED) {
  10950. /* grid-template-columns: repeat(N, 1fr) */
  10951. ncols = pst->grid_auto - BR_GRID_FIXED;
  10952. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  10953. ncols--;
  10954. }
  10955. colw = (avail - gap * (ncols - 1)) / ncols;
  10956. if (colw < 24)
  10957. colw = 24;
  10958. x = row_left;
  10959. n = doc.nodes[parent].first;
  10960. while (n) {
  10961. struct br_node *nd = &doc.nodes[n];
  10962. struct br_style cs;
  10963. unsigned short lk = link;
  10964. int h;
  10965. if (nd->type == BR_NODE_TEXT) {
  10966. n = nd->next;
  10967. continue;
  10968. }
  10969. br_style_for(&doc, n, pst, &cs);
  10970. if (cs.display == BR_DISPLAY_NONE) {
  10971. n = nd->next;
  10972. continue;
  10973. }
  10974. if (nd->tag == BR_TAG_A && nd->href_off)
  10975. lk = (unsigned short)n;
  10976. cs.width_kind = 0;
  10977. cs.max_width_kind = 0;
  10978. l->left = x;
  10979. l->right = x + colw;
  10980. if (l->right < l->left + 8)
  10981. l->right = l->left + 8;
  10982. l->y = y;
  10983. l->line_left = l->line_x = l->left;
  10984. l->run_x = l->left;
  10985. l->line_y = l->y;
  10986. l->line_h = 0;
  10987. l->nruns = 0;
  10988. l->space_pending = 0;
  10989. l->align = cs.align;
  10990. layout_block(l, n, &cs, depth + 1, lk);
  10991. h = l->y - y;
  10992. if (h > row_h)
  10993. row_h = h;
  10994. col++;
  10995. n = nd->next;
  10996. if (col == ncols) {
  10997. y += row_h + gap;
  10998. x = row_left;
  10999. row_h = 0;
  11000. col = 0;
  11001. } else {
  11002. x += colw + gap;
  11003. }
  11004. }
  11005. if (col)
  11006. y += row_h;
  11007. else if (y > start_y)
  11008. y -= gap;
  11009. l->left = row_left;
  11010. l->right = row_right;
  11011. l->y = y;
  11012. l->line_left = l->line_x = l->left;
  11013. l->run_x = l->left;
  11014. l->line_y = l->y;
  11015. l->line_h = 0;
  11016. l->nruns = 0;
  11017. l->space_pending = 0;
  11018. }
  11019. /* Column widths are the widest cell in each column across every row, so all
  11020. * rows line up. The table model is still deliberately basic: no colspan,
  11021. * border-collapse or percentage columns. */
  11022. static void table_columns(struct lay *l, unsigned int table,
  11023. const struct br_style *pst, int avail,
  11024. int *raw, int maxcols, int *out_cols,
  11025. int *out_total)
  11026. {
  11027. unsigned int r, c;
  11028. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  11029. int fixed[12];
  11030. for (c = 0; c < (unsigned int)maxcols; c++) {
  11031. raw[c] = 0;
  11032. fixed[c] = 0;
  11033. }
  11034. /* Intrinsic widths of single-column cells. */
  11035. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  11036. struct br_node *rn = &doc.nodes[r];
  11037. int col = 0;
  11038. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  11039. continue;
  11040. for (c = rn->first; c; c = doc.nodes[c].next) {
  11041. struct br_node *cn = &doc.nodes[c];
  11042. struct br_style cs;
  11043. int w, span;
  11044. if (cn->type != BR_NODE_ELEM ||
  11045. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  11046. continue;
  11047. span = cn->colspan ? cn->colspan : 1;
  11048. br_style_for(&doc, c, pst, &cs);
  11049. if (cs.display == BR_DISPLAY_NONE)
  11050. continue;
  11051. if (col + span > maxcols)
  11052. span = maxcols - col;
  11053. if (span < 1)
  11054. break;
  11055. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  11056. mp_px(&cs, 7, avail) +
  11057. mp_px(&cs, 5, avail) +
  11058. mp_px(&cs, 3, avail) +
  11059. mp_px(&cs, 1, avail) +
  11060. cs.border_w[0] + cs.border_w[1] +
  11061. cs.border_w[2] + cs.border_w[3];
  11062. if (w < 24)
  11063. w = 24;
  11064. if (span == 1) {
  11065. if (w > raw[col])
  11066. raw[col] = w;
  11067. }
  11068. if (col + span > cols)
  11069. cols = col + span;
  11070. col += span;
  11071. }
  11072. }
  11073. /* A colspan cell only has to be as wide as the sum of its columns. */
  11074. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  11075. struct br_node *rn = &doc.nodes[r];
  11076. int col = 0;
  11077. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  11078. continue;
  11079. for (c = rn->first; c; c = doc.nodes[c].next) {
  11080. struct br_node *cn = &doc.nodes[c];
  11081. struct br_style cs;
  11082. int span, w, sum, i;
  11083. if (cn->type != BR_NODE_ELEM ||
  11084. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  11085. continue;
  11086. span = cn->colspan ? cn->colspan : 1;
  11087. if (col + span > maxcols)
  11088. span = maxcols - col;
  11089. if (span < 1)
  11090. break;
  11091. if (span > 1) {
  11092. br_style_for(&doc, c, pst, &cs);
  11093. if (cs.display != BR_DISPLAY_NONE) {
  11094. w = intrinsic_width(l->ui, c, &cs,
  11095. 0, avail) +
  11096. mp_px(&cs, 7, avail) +
  11097. mp_px(&cs, 5, avail) +
  11098. mp_px(&cs, 3, avail) +
  11099. mp_px(&cs, 1, avail) +
  11100. cs.border_w[0] + cs.border_w[1] +
  11101. cs.border_w[2] + cs.border_w[3];
  11102. sum = 0;
  11103. for (i = 0; i < span; i++)
  11104. sum += raw[col + i];
  11105. if (w > sum)
  11106. raw[col + span - 1] += w - sum;
  11107. }
  11108. }
  11109. col += span;
  11110. }
  11111. }
  11112. /* Explicit and percentage widths override intrinsic widths. */
  11113. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  11114. struct br_node *rn = &doc.nodes[r];
  11115. int col = 0;
  11116. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  11117. continue;
  11118. for (c = rn->first; c; c = doc.nodes[c].next) {
  11119. struct br_node *cn = &doc.nodes[c];
  11120. struct br_style cs;
  11121. int span;
  11122. if (cn->type != BR_NODE_ELEM ||
  11123. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  11124. continue;
  11125. span = cn->colspan ? cn->colspan : 1;
  11126. if (col + span > maxcols)
  11127. span = maxcols - col;
  11128. if (span < 1)
  11129. break;
  11130. if (span == 1) {
  11131. br_style_for(&doc, c, pst, &cs);
  11132. if (cs.display != BR_DISPLAY_NONE) {
  11133. if (cs.width_kind == 1) {
  11134. raw[col] = cs.width;
  11135. fixed[col] = 1;
  11136. } else if (cs.width_kind == 2 ||
  11137. cs.width_kind == 3) {
  11138. raw[col] = style_width_px(&cs,
  11139. avail);
  11140. fixed[col] = 1;
  11141. }
  11142. }
  11143. }
  11144. col += span;
  11145. }
  11146. }
  11147. for (c = 0; c < (unsigned int)cols; c++) {
  11148. if (raw[c] < 8)
  11149. raw[c] = 8;
  11150. total += raw[c];
  11151. if (fixed[c])
  11152. fixed_sum += raw[c];
  11153. else {
  11154. free_raw += raw[c];
  11155. free_cols++;
  11156. }
  11157. }
  11158. if (fixed_sum > 0 && fixed_sum < avail) {
  11159. int free_avail = avail - fixed_sum;
  11160. int i;
  11161. if (free_raw > 0) {
  11162. for (i = 0; i < cols; i++)
  11163. if (!fixed[i])
  11164. raw[i] = free_avail * raw[i] /
  11165. free_raw;
  11166. } else if (free_cols > 0) {
  11167. for (i = 0; i < cols; i++)
  11168. if (!fixed[i])
  11169. raw[i] = free_avail / free_cols;
  11170. }
  11171. total = 0;
  11172. for (i = 0; i < cols; i++)
  11173. total += raw[i];
  11174. } else if (total < avail && total > 0) {
  11175. int i;
  11176. for (i = 0; i < cols; i++)
  11177. raw[i] = raw[i] * avail / total;
  11178. total = 0;
  11179. for (i = 0; i < cols; i++)
  11180. total += raw[i];
  11181. }
  11182. *out_cols = cols;
  11183. *out_total = total;
  11184. }
  11185. static void layout_table_row(struct lay *l, unsigned int row,
  11186. const struct br_style *pst, int depth,
  11187. unsigned short link)
  11188. {
  11189. unsigned int n, cell[12];
  11190. int raw[12], colstart[12], colspan[12];
  11191. int prefix[13];
  11192. int ncell = 0, total = 0, cols = 0, col = 0;
  11193. int row_left = l->left, row_right = l->right;
  11194. int avail = row_right - row_left;
  11195. int y = l->y, bottom = l->y;
  11196. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  11197. struct br_node *nd = &doc.nodes[n];
  11198. struct br_style cs;
  11199. int span;
  11200. if (nd->type == BR_NODE_TEXT) {
  11201. if (text_node_blank(nd))
  11202. continue;
  11203. layout_children(l, row, pst, depth, link);
  11204. return;
  11205. }
  11206. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  11207. layout_children(l, row, pst, depth, link);
  11208. return;
  11209. }
  11210. br_style_for(&doc, n, pst, &cs);
  11211. if (cs.display == BR_DISPLAY_NONE)
  11212. continue;
  11213. if (ncell >= 12) {
  11214. layout_children(l, row, pst, depth, link);
  11215. return;
  11216. }
  11217. span = nd->colspan ? nd->colspan : 1;
  11218. if (span > 12 - col)
  11219. span = 12 - col;
  11220. if (span < 1)
  11221. continue;
  11222. cell[ncell] = n;
  11223. colstart[ncell] = col;
  11224. colspan[ncell] = span;
  11225. col += span;
  11226. ncell++;
  11227. }
  11228. if (ncell < 1 || avail < 32) {
  11229. layout_children(l, row, pst, depth, link);
  11230. return;
  11231. }
  11232. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  11233. &total);
  11234. if (cols < 2 || total <= 0) {
  11235. int c;
  11236. total = 0;
  11237. for (c = 0; c < ncell; c++) {
  11238. struct br_style cs;
  11239. br_style_for(&doc, cell[c], pst, &cs);
  11240. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  11241. avail) +
  11242. mp_px(&cs, 7, avail) +
  11243. mp_px(&cs, 5, avail) +
  11244. mp_px(&cs, 3, avail) +
  11245. mp_px(&cs, 1, avail);
  11246. if (raw[c] < 24)
  11247. raw[c] = 24;
  11248. total += raw[c];
  11249. }
  11250. /* A one-column table still has to fill its own width; the
  11251. * intrinsic fallback above otherwise leaves the cell at its
  11252. * text width (HN's outer table and nested story table). */
  11253. if (total > 0 && total < avail) {
  11254. int c;
  11255. for (c = 0; c < ncell; c++)
  11256. raw[c] = raw[c] * avail / total;
  11257. total = avail;
  11258. }
  11259. }
  11260. prefix[0] = row_left;
  11261. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  11262. prefix[n + 1] = prefix[n] + raw[n];
  11263. for (n = 0; n < (unsigned int)ncell; n++) {
  11264. struct br_style cs;
  11265. int start = colstart[n];
  11266. int end = start + colspan[n];
  11267. int w;
  11268. if (end > cols)
  11269. end = cols;
  11270. if (start >= cols)
  11271. continue;
  11272. w = prefix[end] - prefix[start];
  11273. br_style_for(&doc, cell[n], pst, &cs);
  11274. /* The column width already reflects the cell's width property. */
  11275. cs.width_kind = 0;
  11276. cs.max_width_kind = 0;
  11277. if (w < 24)
  11278. w = 24;
  11279. if (w < 8)
  11280. w = 8;
  11281. l->left = prefix[start];
  11282. l->right = l->left + w;
  11283. l->y = y;
  11284. l->line_left = l->line_x = l->left;
  11285. l->run_x = l->left;
  11286. l->line_y = l->y;
  11287. l->line_h = 0;
  11288. l->nruns = 0;
  11289. l->space_pending = 0;
  11290. l->align = cs.align;
  11291. layout_block(l, cell[n], &cs, depth + 1, link);
  11292. if (l->y > bottom)
  11293. bottom = l->y;
  11294. }
  11295. l->left = row_left;
  11296. l->right = row_right;
  11297. l->y = bottom;
  11298. l->line_left = l->line_x = l->left;
  11299. l->run_x = l->left;
  11300. l->line_y = l->y;
  11301. l->line_h = 0;
  11302. l->nruns = 0;
  11303. l->space_pending = 0;
  11304. }
  11305. #define TBL_MAX_ROWS 32
  11306. #define TBL_MAX_COLS 12
  11307. #define TBL_MAX_CELLS 128
  11308. struct tbl_cell {
  11309. unsigned int node;
  11310. unsigned char row, col, rowspan, colspan;
  11311. int height;
  11312. };
  11313. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  11314. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  11315. static int table_active;
  11316. static int table_has_rowspan(unsigned int table)
  11317. {
  11318. unsigned int r, c;
  11319. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  11320. struct br_node *rn = &doc.nodes[r];
  11321. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  11322. continue;
  11323. for (c = rn->first; c; c = doc.nodes[c].next) {
  11324. struct br_node *cn = &doc.nodes[c];
  11325. if (cn->type == BR_NODE_ELEM &&
  11326. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  11327. cn->rowspan > 1)
  11328. return 1;
  11329. }
  11330. }
  11331. return 0;
  11332. }
  11333. static void table_cell_style(unsigned int row, unsigned int cell,
  11334. const struct br_style *st, struct br_style *out)
  11335. {
  11336. struct br_style trs;
  11337. br_style_for(&doc, row, st, &trs);
  11338. br_style_for(&doc, cell, &trs, out);
  11339. }
  11340. /* Tables that use rowspan need row heights before anything is painted. This
  11341. * path builds a small occupancy grid, measures the natural cell heights, then
  11342. * lays every cell out at its row/column position. Tables without rowspan
  11343. * keep the lighter per-row path in layout_table_row(). */
  11344. static void layout_table(struct lay *l, unsigned int table,
  11345. const struct br_style *st, int depth,
  11346. unsigned short link)
  11347. {
  11348. unsigned int rows[TBL_MAX_ROWS];
  11349. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  11350. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  11351. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  11352. int free_raw = 0, free_cols = 0;
  11353. int table_left = l->left, table_right = l->right;
  11354. int top = l->y, avail = table_right - table_left;
  11355. unsigned int r, c;
  11356. int i, rr, cc;
  11357. if (depth > 48 || table_active) {
  11358. layout_children(l, table, st, depth, link);
  11359. return;
  11360. }
  11361. table_active = 1;
  11362. for (r = doc.nodes[table].first;
  11363. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  11364. struct br_node *rn = &doc.nodes[r];
  11365. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  11366. rows[nrows++] = r;
  11367. }
  11368. if (!nrows) {
  11369. table_active = 0;
  11370. layout_children(l, table, st, depth, link);
  11371. return;
  11372. }
  11373. for (rr = 0; rr < nrows; rr++)
  11374. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  11375. tbl_at[rr][cc] = 0;
  11376. for (rr = 0; rr < nrows; rr++) {
  11377. int col = 0;
  11378. for (c = doc.nodes[rows[rr]].first; c;
  11379. c = doc.nodes[c].next) {
  11380. struct br_node *cn = &doc.nodes[c];
  11381. struct br_style cs;
  11382. int rs, csn;
  11383. if (cn->type != BR_NODE_ELEM ||
  11384. (cn->tag != BR_TAG_TD &&
  11385. cn->tag != BR_TAG_TH))
  11386. continue;
  11387. table_cell_style(rows[rr], c, st, &cs);
  11388. if (cs.display == BR_DISPLAY_NONE)
  11389. continue;
  11390. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  11391. col++;
  11392. if (col >= TBL_MAX_COLS)
  11393. break;
  11394. rs = cn->rowspan ? cn->rowspan : 1;
  11395. csn = cn->colspan ? cn->colspan : 1;
  11396. if (rr + rs > nrows)
  11397. rs = nrows - rr;
  11398. if (col + csn > TBL_MAX_COLS)
  11399. csn = TBL_MAX_COLS - col;
  11400. if (rs < 1 || csn < 1)
  11401. continue;
  11402. if (ncells >= TBL_MAX_CELLS)
  11403. break;
  11404. tbl_cells[ncells].node = c;
  11405. tbl_cells[ncells].row = (unsigned char)rr;
  11406. tbl_cells[ncells].col = (unsigned char)col;
  11407. tbl_cells[ncells].rowspan = (unsigned char)rs;
  11408. tbl_cells[ncells].colspan = (unsigned char)csn;
  11409. tbl_cells[ncells].height = 0;
  11410. for (i = rr; i < rr + rs; i++)
  11411. for (int j = col; j < col + csn; j++)
  11412. tbl_at[i][j] =
  11413. (unsigned short)(ncells + 1);
  11414. ncells++;
  11415. col += csn;
  11416. if (col > cols)
  11417. cols = col;
  11418. }
  11419. }
  11420. if (!ncells || cols < 1) {
  11421. table_active = 0;
  11422. layout_children(l, table, st, depth, link);
  11423. return;
  11424. }
  11425. for (i = 0; i < cols; i++) {
  11426. raw[i] = 0;
  11427. fixed[i] = 0;
  11428. }
  11429. /* Intrinsic widths of single-column cells. */
  11430. for (i = 0; i < ncells; i++) {
  11431. struct br_style cs;
  11432. int w;
  11433. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  11434. st, &cs);
  11435. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  11436. mp_px(&cs, 7, avail) +
  11437. mp_px(&cs, 5, avail) +
  11438. mp_px(&cs, 3, avail) +
  11439. mp_px(&cs, 1, avail) +
  11440. cs.border_w[0] + cs.border_w[1] +
  11441. cs.border_w[2] + cs.border_w[3];
  11442. if (w < 24)
  11443. w = 24;
  11444. if (tbl_cells[i].colspan == 1) {
  11445. int col = tbl_cells[i].col;
  11446. if (w > raw[col])
  11447. raw[col] = w;
  11448. }
  11449. }
  11450. /* A spanning cell only needs the sum of its columns to be large
  11451. * enough; put the deficit in the last column. */
  11452. for (i = 0; i < ncells; i++) {
  11453. struct br_style cs;
  11454. int w, sum, col, span;
  11455. if (tbl_cells[i].colspan < 2)
  11456. continue;
  11457. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  11458. st, &cs);
  11459. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  11460. mp_px(&cs, 7, avail) +
  11461. mp_px(&cs, 5, avail) +
  11462. mp_px(&cs, 3, avail) +
  11463. mp_px(&cs, 1, avail) +
  11464. cs.border_w[0] + cs.border_w[1] +
  11465. cs.border_w[2] + cs.border_w[3];
  11466. col = tbl_cells[i].col;
  11467. span = tbl_cells[i].colspan;
  11468. sum = 0;
  11469. for (int j = 0; j < span; j++)
  11470. sum += raw[col + j];
  11471. if (w > sum)
  11472. raw[col + span - 1] += w - sum;
  11473. }
  11474. /* Explicit/percentage widths, as in table_columns(). */
  11475. for (i = 0; i < ncells; i++) {
  11476. struct br_style cs;
  11477. int col;
  11478. if (tbl_cells[i].colspan != 1)
  11479. continue;
  11480. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  11481. st, &cs);
  11482. col = tbl_cells[i].col;
  11483. if (cs.width_kind == 1) {
  11484. raw[col] = cs.width;
  11485. fixed[col] = 1;
  11486. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  11487. raw[col] = style_width_px(&cs, avail);
  11488. fixed[col] = 1;
  11489. }
  11490. }
  11491. for (i = 0; i < cols; i++) {
  11492. if (raw[i] < 8)
  11493. raw[i] = 8;
  11494. total += raw[i];
  11495. if (fixed[i])
  11496. fixed_sum += raw[i];
  11497. else {
  11498. free_raw += raw[i];
  11499. free_cols++;
  11500. }
  11501. }
  11502. if (fixed_sum > 0 && fixed_sum < avail) {
  11503. int free_avail = avail - fixed_sum;
  11504. if (free_raw > 0) {
  11505. for (i = 0; i < cols; i++)
  11506. if (!fixed[i])
  11507. raw[i] = free_avail * raw[i] /
  11508. free_raw;
  11509. } else if (free_cols > 0) {
  11510. for (i = 0; i < cols; i++)
  11511. if (!fixed[i])
  11512. raw[i] = free_avail / free_cols;
  11513. }
  11514. } else if (total < avail && total > 0) {
  11515. for (i = 0; i < cols; i++)
  11516. raw[i] = raw[i] * avail / total;
  11517. }
  11518. prefix[0] = table_left;
  11519. for (i = 0; i < cols; i++)
  11520. prefix[i + 1] = prefix[i] + raw[i];
  11521. /* Measure natural cell heights with the column widths. */
  11522. for (i = 0; i < ncells; i++) {
  11523. struct br_style cs;
  11524. int col = tbl_cells[i].col;
  11525. int span = tbl_cells[i].colspan;
  11526. int w = prefix[col + span] - prefix[col];
  11527. int sl = l->left, sr = l->right, sy = l->y;
  11528. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  11529. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  11530. int sal = l->align, sdraw = l->draw;
  11531. struct ngui *sui = l->ui;
  11532. if (w < 8)
  11533. w = 8;
  11534. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  11535. st, &cs);
  11536. cs.width_kind = 0;
  11537. cs.max_width_kind = 0;
  11538. l->draw = 0;
  11539. l->ui = 0;
  11540. l->left = prefix[col];
  11541. l->right = l->left + w;
  11542. l->y = 0;
  11543. l->line_left = l->line_x = l->left;
  11544. l->run_x = l->left;
  11545. l->line_y = 0;
  11546. l->line_h = 0;
  11547. l->nruns = 0;
  11548. l->space_pending = 0;
  11549. l->align = cs.align;
  11550. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  11551. tbl_cells[i].height = block_h[tbl_cells[i].node];
  11552. l->left = sl;
  11553. l->right = sr;
  11554. l->y = sy;
  11555. l->line_x = slx;
  11556. l->run_x = srx;
  11557. l->line_y = sly;
  11558. l->line_h = slh;
  11559. l->nruns = snr;
  11560. l->space_pending = ssp;
  11561. l->align = sal;
  11562. l->draw = sdraw;
  11563. l->ui = sui;
  11564. }
  11565. for (i = 0; i < nrows; i++)
  11566. rowh[i] = 0;
  11567. for (i = 0; i < ncells; i++) {
  11568. int row = tbl_cells[i].row;
  11569. if (tbl_cells[i].rowspan == 1) {
  11570. if (tbl_cells[i].height > rowh[row])
  11571. rowh[row] = tbl_cells[i].height;
  11572. }
  11573. }
  11574. for (i = 0; i < ncells; i++) {
  11575. int row = tbl_cells[i].row;
  11576. int span = tbl_cells[i].rowspan;
  11577. int sum = 0;
  11578. if (span < 2)
  11579. continue;
  11580. for (int j = 0; j < span; j++)
  11581. sum += rowh[row + j];
  11582. if (sum < tbl_cells[i].height)
  11583. rowh[row + span - 1] +=
  11584. tbl_cells[i].height - sum;
  11585. }
  11586. for (i = 0; i < nrows; i++)
  11587. if (rowh[i] < 8)
  11588. rowh[i] = 8;
  11589. rowy[0] = top;
  11590. for (i = 1; i < nrows; i++)
  11591. rowy[i] = rowy[i - 1] + rowh[i - 1];
  11592. if (!l->draw) {
  11593. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  11594. table_active = 0;
  11595. return;
  11596. }
  11597. for (i = 0; i < ncells; i++) {
  11598. struct br_style cs;
  11599. int col = tbl_cells[i].col;
  11600. int span = tbl_cells[i].colspan;
  11601. int row = tbl_cells[i].row;
  11602. int rspan = tbl_cells[i].rowspan;
  11603. int w = prefix[col + span] - prefix[col];
  11604. int h = 0;
  11605. int sl = l->left, sr = l->right, sy = l->y;
  11606. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  11607. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  11608. int sal = l->align;
  11609. int deco;
  11610. for (int j = 0; j < rspan; j++)
  11611. h += rowh[row + j];
  11612. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  11613. cs.width_kind = 0;
  11614. cs.max_width_kind = 0;
  11615. cs.box_sizing = 0;
  11616. deco = mp_px(&cs, 4, avail) +
  11617. mp_px(&cs, 6, avail) +
  11618. cs.border_w[0] + cs.border_w[2];
  11619. cs.height_kind = 1;
  11620. cs.height = h > deco ? h - deco : 0;
  11621. /* The block painter reads block_h[] from the measure pass; make
  11622. * the table cell fill its row/rowspan, not just its content. */
  11623. if (h > 0 && h < 65536)
  11624. block_h[tbl_cells[i].node] = (unsigned short)h;
  11625. l->left = prefix[col];
  11626. l->right = l->left + w;
  11627. l->y = rowy[row];
  11628. l->line_left = l->line_x = l->left;
  11629. l->run_x = l->left;
  11630. l->line_y = l->y;
  11631. l->line_h = 0;
  11632. l->nruns = 0;
  11633. l->space_pending = 0;
  11634. l->align = cs.align;
  11635. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  11636. l->left = sl;
  11637. l->right = sr;
  11638. l->y = sy;
  11639. l->line_x = slx;
  11640. l->run_x = srx;
  11641. l->line_y = sly;
  11642. l->line_h = slh;
  11643. l->nruns = snr;
  11644. l->space_pending = ssp;
  11645. l->align = sal;
  11646. }
  11647. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  11648. table_active = 0;
  11649. }
  11650. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  11651. * flow so they sit above it, like CSS painting order. Their flow origin is
  11652. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  11653. struct br_deferred {
  11654. unsigned int node;
  11655. int flow_y, flow_left, flow_right;
  11656. int parent_top; /* the parent box top, for sticky clamping */
  11657. unsigned short link;
  11658. signed short z_index;
  11659. unsigned char z_set;
  11660. unsigned int order;
  11661. };
  11662. /* Positioned boxes painted after the flow. News front pages have one or two
  11663. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  11664. * old 16 entries the rest fell back into the flow, so a hero image landed
  11665. * below its padding-top aspect box instead of on top of it. */
  11666. #define BR_MAX_DEFERRED 256
  11667. static struct br_deferred deferred[BR_MAX_DEFERRED];
  11668. static int ndeferred;
  11669. /* Outer width of an element's empty ::before (pe 1) / ::after (pe 2) icon
  11670. * box, 0 when it has none; *ps receives the pseudo-element's style. */
  11671. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  11672. struct br_style *ps, int base)
  11673. {
  11674. char buf[8];
  11675. int w, h;
  11676. if (!doc.npe_rules ||
  11677. br_pseudo(&doc, node, pe, st, ps, buf, sizeof(buf)) ||
  11678. ps->content != BR_CONTENT_EMPTY || ps->display == BR_DISPLAY_NONE)
  11679. return 0;
  11680. w = ps->width_kind ? style_width_px(ps, base) : 0;
  11681. h = ps->height_kind ? style_height_px(ps, base) : 0;
  11682. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  11683. w = (int)ps->min_width;
  11684. if (w <= 0)
  11685. w = h;
  11686. if (w <= 0 || w > 512)
  11687. return 0;
  11688. return w + (ps->ml_auto ? 0 : mp_px(ps, 3, base)) + mp_px(ps, 1, base);
  11689. }
  11690. /* An empty ::before/::after with a size and a background: one run the
  11691. * size of the box. Only data: background images are drawn (decoded at
  11692. * the background-size); `margin-left: auto` inside a flex parent pushes
  11693. * the box to the line's right edge like the flex row would. */
  11694. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  11695. const struct br_style *ps, unsigned short link)
  11696. {
  11697. struct lay_run *r;
  11698. int lw = l->line_right - l->line_left, w, h, ml, mr, tw, th;
  11699. const char *url = ps->bg_image ? br_bg_image_url(ps->bg_image - 1) : "";
  11700. if (lw < 8)
  11701. lw = 8;
  11702. w = ps->width_kind ? style_width_px(ps, lw) : 0;
  11703. h = ps->height_kind ? style_height_px(ps, lw) : 0;
  11704. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  11705. w = (int)ps->min_width;
  11706. if (w <= 0)
  11707. w = h;
  11708. if (h <= 0)
  11709. h = w;
  11710. if (w <= 0 || w > 512 || h > 512)
  11711. return;
  11712. ml = ps->ml_auto ? 0 : mp_px(ps, 3, lw);
  11713. mr = mp_px(ps, 1, lw);
  11714. if (ml < 0)
  11715. ml = 0;
  11716. if (mr < 0)
  11717. mr = 0;
  11718. if (l->line_x + ml + w > l->line_right &&
  11719. (l->nruns > 0 || l->line_x > l->line_left))
  11720. flush_line(l);
  11721. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  11722. flush_line(l);
  11723. if (l->nruns == 0) {
  11724. l->line_y = l->y;
  11725. l->line_h = 0;
  11726. start_line(l, ps);
  11727. }
  11728. if (ps->ml_auto && parent->display == BR_DISPLAY_FLEX &&
  11729. l->line_right - w - mr > l->line_x)
  11730. l->line_x = l->line_right - w - mr;
  11731. else
  11732. l->line_x += ml;
  11733. r = &l->runs[l->nruns++];
  11734. memset(r, 0, sizeof(*r));
  11735. r->box = l->box_owner;
  11736. r->gap = (unsigned short)(l->line_x > l->run_x ?
  11737. l->line_x - l->run_x : 0);
  11738. r->img = RUN_PBOX;
  11739. r->href = link;
  11740. r->iw = (unsigned short)w;
  11741. r->ih = (unsigned short)h;
  11742. r->w = (unsigned short)w;
  11743. r->font_px = ps->font_px;
  11744. r->pb_has_bg = ps->has_bg;
  11745. r->pb_bg = ps->bg;
  11746. r->pb_img = -1;
  11747. if (ps->transform_set) {
  11748. r->transform_scale = 1;
  11749. r->scale_x = ps->scale_x;
  11750. r->scale_y = ps->scale_y;
  11751. r->rotate_x100 = ps->rotate_x100;
  11752. }
  11753. /* Background size and position, as draw_bg_image() resolves them. */
  11754. tw = w;
  11755. th = h;
  11756. if (ps->bg_size_kind == 1 || ps->bg_size_kind == 2) {
  11757. int bw = ps->bg_size_w, bh = ps->bg_size_h;
  11758. if (ps->bg_size_kind == 2) {
  11759. bw = bw ? w * bw / 100 : 0;
  11760. bh = bh ? h * bh / 100 : 0;
  11761. }
  11762. tw = bw ? bw : (bh ? bh : w);
  11763. th = bh ? bh : tw;
  11764. }
  11765. if (tw > 0 && th > 0 && tw <= 512 && th <= 512 && url[0])
  11766. r->pb_img = (short)data_url_image(url, tw, th);
  11767. r->pb_w = (short)tw;
  11768. r->pb_h = (short)th;
  11769. r->pb_x = (short)(ps->bg_pos_x_kind == 1 ?
  11770. (w - tw) * ps->bg_pos_x / 100 : ps->bg_pos_x);
  11771. r->pb_y = (short)(ps->bg_pos_y_kind == 1 ?
  11772. (h - th) * ps->bg_pos_y / 100 : ps->bg_pos_y);
  11773. l->line_x += w + mr;
  11774. l->run_x = l->line_x;
  11775. if (l->line_h < h)
  11776. l->line_h = h;
  11777. }
  11778. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  11779. * element's line. A block-level pseudo-element gets its own line; its box
  11780. * (margins, padding, background) is not drawn. */
  11781. static void emit_pseudo(struct lay *l, unsigned int node,
  11782. const struct br_style *st, int pe, unsigned short link)
  11783. {
  11784. char buf[160];
  11785. struct br_style ps;
  11786. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  11787. unsigned int i = 0;
  11788. int block, space_w;
  11789. if (!n && ps.content == BR_CONTENT_EMPTY &&
  11790. ps.display != BR_DISPLAY_NONE) {
  11791. emit_pseudo_box(l, st, &ps, link);
  11792. return;
  11793. }
  11794. if (!n)
  11795. return;
  11796. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  11797. if (block)
  11798. flush_line(l);
  11799. if (ps.uppercase)
  11800. for (i = 0; i < n; i++)
  11801. if (buf[i] >= 'a' && buf[i] <= 'z')
  11802. buf[i] = (char)(buf[i] - 'a' + 'A');
  11803. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  11804. if (space_w <= 0)
  11805. space_w = 8;
  11806. i = 0;
  11807. while (i < n) {
  11808. char word[28];
  11809. unsigned int k = 0;
  11810. int w;
  11811. if (buf[i] == ' ') {
  11812. l->space_pending = 1;
  11813. i++;
  11814. continue;
  11815. }
  11816. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  11817. word[k++] = buf[i++];
  11818. word[k] = '\0';
  11819. if (l->space_pending &&
  11820. (l->nruns > 0 || l->line_x > l->line_left) &&
  11821. l->line_x + space_w <= l->line_right)
  11822. l->line_x += space_w;
  11823. l->space_pending = 0;
  11824. w = (int)face_text_width(l->ui, &ps, word, k);
  11825. if (l->line_x + w > l->line_right &&
  11826. (l->nruns > 0 || l->line_x > l->line_left))
  11827. flush_line(l);
  11828. add_run(l, 0, 0, &ps, link, word);
  11829. }
  11830. if (block)
  11831. flush_line(l);
  11832. }
  11833. /* An out-of-flow child (absolute/fixed, or a relative/sticky box with a
  11834. * z-index): measured in place, painted from the deferred stacked pass
  11835. * against its containing block. Shared by block and flex layout, so an
  11836. * absolute icon inside a flex row (a password field's reveal button) is
  11837. * not laid out as one of the row's items. Returns 1 when it handled n. */
  11838. static int layout_out_of_flow(struct lay *l, unsigned int n,
  11839. const struct br_style *cs, int depth,
  11840. unsigned short lk)
  11841. {
  11842. if (!(cs->pos == 1 || cs->pos == 2 ||
  11843. ((cs->pos == 3 || cs->pos == 4) && cs->z_set)))
  11844. return 0;
  11845. if ((cs->pos == 3 || cs->pos == 4) && l->draw &&
  11846. ndeferred < BR_MAX_DEFERRED) {
  11847. /* Relative or sticky z-index (a sticky site
  11848. * header): measure and advance the flow without
  11849. * painting, then paint it in the deferred
  11850. * (stacked) pass, above the content after it. */
  11851. int fy = l->y, fl = l->left, fr = l->right;
  11852. int save_draw = l->draw;
  11853. l->draw = 0;
  11854. layout_block(l, n, cs, depth + 1, lk);
  11855. l->draw = save_draw;
  11856. deferred[ndeferred].node = n;
  11857. deferred[ndeferred].parent_top = l->parent_top;
  11858. deferred[ndeferred].flow_y = fy;
  11859. deferred[ndeferred].flow_left = fl;
  11860. deferred[ndeferred].flow_right = fr;
  11861. deferred[ndeferred].link = lk;
  11862. deferred[ndeferred].z_index = cs->z_index;
  11863. deferred[ndeferred].z_set = cs->z_set;
  11864. deferred[ndeferred].order = (unsigned int)ndeferred;
  11865. ndeferred++;
  11866. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  11867. deferred[ndeferred].node = n;
  11868. deferred[ndeferred].parent_top = l->parent_top;
  11869. deferred[ndeferred].flow_y =
  11870. cs->pos == 1 ? l->cb_top : l->y;
  11871. deferred[ndeferred].flow_left =
  11872. cs->pos == 1 ? l->cb_left : l->left;
  11873. deferred[ndeferred].flow_right =
  11874. cs->pos == 1 ? l->cb_right : l->right;
  11875. deferred[ndeferred].link = lk;
  11876. deferred[ndeferred].z_index = cs->z_index;
  11877. deferred[ndeferred].z_set = cs->z_set;
  11878. deferred[ndeferred].order = (unsigned int)ndeferred;
  11879. ndeferred++;
  11880. } else if (l->draw && cs->pos == 1) {
  11881. /* Deferred list full: paint in place, but still
  11882. * against the containing block, not the flow. */
  11883. int fy = l->y, fl = l->left, fr = l->right;
  11884. l->y = l->cb_top;
  11885. l->left = l->cb_left;
  11886. l->right = l->cb_right;
  11887. layout_block(l, n, cs, depth + 1, lk);
  11888. l->y = fy;
  11889. l->left = fl;
  11890. l->right = fr;
  11891. } else {
  11892. layout_block(l, n, cs, depth + 1, lk);
  11893. }
  11894. if (cs->pos == 1 && block_h[n] &&
  11895. doc.nodes[n].class_off) {
  11896. const char *cl = doc.attrs +
  11897. doc.nodes[n].class_off;
  11898. if ((contains_ci(cl, "poster-wrapper") ||
  11899. contains_ci(cl, "ts-picture")) &&
  11900. !has_skeleton_sibling(n))
  11901. l->y += block_h[n];
  11902. }
  11903. return 1;
  11904. }
  11905. /* An element laid out in the text line (an inline span, or an inline-block
  11906. * that flows like one): its runs are tagged with it, so flush_line() can
  11907. * record its box for getBoundingClientRect() and click targeting. */
  11908. static void layout_inline_box(struct lay *l, unsigned int node,
  11909. const struct br_style *cs, int depth,
  11910. unsigned short link)
  11911. {
  11912. unsigned short saved = l->box_owner;
  11913. if (node < BR_MAX_NODES) {
  11914. inline_box_parent[node] = saved;
  11915. l->box_owner = (unsigned short)(node + 1);
  11916. }
  11917. layout_children(l, node, cs, depth + 1, link);
  11918. l->box_owner = saved;
  11919. }
  11920. static void layout_children(struct lay *l, unsigned int parent,
  11921. const struct br_style *pst, int depth,
  11922. unsigned short link)
  11923. {
  11924. unsigned int n;
  11925. if (depth > 48)
  11926. return;
  11927. emit_pseudo(l, parent, pst, 1, link);
  11928. n = doc.nodes[parent].first;
  11929. while (n) {
  11930. struct br_node *nd = &doc.nodes[n];
  11931. struct br_style cs;
  11932. unsigned short lk = link;
  11933. if (nd->type == BR_NODE_TEXT) {
  11934. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  11935. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  11936. n = nd->next;
  11937. continue;
  11938. }
  11939. br_style_for(&doc, n, pst, &cs);
  11940. if (cs.display == BR_DISPLAY_NONE) {
  11941. n = nd->next;
  11942. continue;
  11943. }
  11944. if (cs.clear && l->float_active) {
  11945. flush_line(l);
  11946. if (l->y < l->float_bottom)
  11947. l->y = l->float_bottom;
  11948. l->float_active = 0;
  11949. l->line_x = l->left;
  11950. l->run_x = l->left;
  11951. l->line_left = l->left;
  11952. l->line_right = l->right;
  11953. l->line_y = l->y;
  11954. l->line_h = 0;
  11955. l->nruns = 0;
  11956. l->space_pending = 0;
  11957. }
  11958. if (nd->tag == BR_TAG_A && nd->href_off)
  11959. lk = (unsigned short)n;
  11960. if (layout_out_of_flow(l, n, &cs, depth, lk)) {
  11961. n = nd->next;
  11962. continue;
  11963. }
  11964. if (nd->tag == BR_TAG_BR) {
  11965. flush_line(l);
  11966. n = nd->next;
  11967. continue;
  11968. }
  11969. if (nd->tag == BR_TAG_HR) {
  11970. flush_line(l);
  11971. if (l->draw)
  11972. ngui_fill_rect(l->ui,
  11973. (struct ngui_rect){l->left, l->y + 2,
  11974. l->right - l->left, 1}, BR_GRAY);
  11975. l->y += 8;
  11976. n = nd->next;
  11977. continue;
  11978. }
  11979. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  11980. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  11981. !button_has_elements(n)) {
  11982. if (!(nd->tag == BR_TAG_INPUT &&
  11983. s_eq(br_type(&doc, n), "hidden"))) {
  11984. form_fill_line = pst->display ==
  11985. BR_DISPLAY_FLEX &&
  11986. pst->flex_col;
  11987. add_form_run(l, n, &cs, lk);
  11988. form_fill_line = 0;
  11989. }
  11990. n = nd->next;
  11991. continue;
  11992. }
  11993. if (nd->tag == BR_TAG_IMG) {
  11994. add_image_run(l, n, &cs, lk);
  11995. n = nd->next;
  11996. continue;
  11997. }
  11998. if (nd->tag == BR_TAG_SVG &&
  11999. (cs.display == BR_DISPLAY_INLINE ||
  12000. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  12001. !cs.float_left) {
  12002. add_svg_run(l, n, &cs, lk);
  12003. n = nd->next;
  12004. continue;
  12005. }
  12006. if (nd->tag == BR_TAG_VIDEO) {
  12007. layout_block(l, n, &cs, depth + 1, lk);
  12008. n = nd->next;
  12009. continue;
  12010. }
  12011. if (cs.float_left) {
  12012. n = layout_float_group(l, n, pst, depth, lk);
  12013. continue;
  12014. }
  12015. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  12016. inline_block_flows(n, &cs, 0)) {
  12017. layout_inline_box(l, n, &cs, depth, lk);
  12018. n = nd->next;
  12019. continue;
  12020. }
  12021. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  12022. n = layout_inline_blocks(l, n, pst, depth, link);
  12023. continue;
  12024. }
  12025. /* A flex container is block-level like any block box even when
  12026. * the element is an inline tag such as <a> (a link card with
  12027. * display:flex is common on news sites). Without the block box
  12028. * its children were laid out in the parent flow with a 0x0 box
  12029. * of their own. */
  12030. /* inline-flex around inline content only ("| mehr" link
  12031. * tails, icon+label pills) stays in the text line. */
  12032. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  12033. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  12034. !flex_wants_row(n, &cs)) {
  12035. layout_children(l, n, &cs, depth + 1, lk);
  12036. } else if (cs.display == BR_DISPLAY_BLOCK ||
  12037. cs.display == BR_DISPLAY_FLEX ||
  12038. br_tag_is_block(nd->tag))
  12039. layout_block(l, n, &cs, depth + 1, lk);
  12040. else if (cs.display == BR_DISPLAY_INLINE &&
  12041. nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH)
  12042. layout_inline_box(l, n, &cs, depth, lk);
  12043. else {
  12044. layout_children(l, n, &cs, depth + 1, lk);
  12045. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  12046. l->space_pending = 1;
  12047. }
  12048. n = nd->next;
  12049. }
  12050. emit_pseudo(l, parent, pst, 2, link);
  12051. }
  12052. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  12053. * runs and a recursive page can otherwise overflow the stack. */
  12054. static struct lay layout_state;
  12055. static int measure_page(int left, int right)
  12056. {
  12057. struct lay *l = &layout_state;
  12058. struct br_style base = base_style();
  12059. unsigned int i;
  12060. for (i = 0; i < BR_MAX_NODES; i++) {
  12061. block_h[i] = 0;
  12062. flex_stretch_h[i] = 0;
  12063. img_top[i] = 0;
  12064. block_top[i] = 0;
  12065. img_h[i] = 0;
  12066. layout_boxes[i].valid = 0;
  12067. }
  12068. memset(li_marker, 0, sizeof(li_marker));
  12069. inline_box_pass_id++;
  12070. l->box_owner = 0;
  12071. l->draw = 0;
  12072. l->ui = &ui;
  12073. l->left = left;
  12074. l->right = right;
  12075. l->y = 0;
  12076. l->line_x = left;
  12077. l->run_x = left;
  12078. l->line_left = left;
  12079. l->line_right = right;
  12080. l->line_y = 0;
  12081. l->line_h = 0;
  12082. l->align = BR_ALIGN_LEFT;
  12083. l->cb_h = layout_view_h;
  12084. l->float_active = 0;
  12085. l->parent_top = 0;
  12086. l->cb_left = left;
  12087. l->cb_right = right;
  12088. l->cb_top = 0;
  12089. l->depth = 0;
  12090. l->nruns = 0;
  12091. l->space_pending = 0;
  12092. base = root_style();
  12093. layout_children(l, doc.root, &base, 0, 0);
  12094. return l->y + 8;
  12095. }
  12096. static int deferred_cmp(const struct br_deferred *a,
  12097. const struct br_deferred *b)
  12098. {
  12099. int az = a->z_set ? a->z_index : 0;
  12100. int bz = b->z_set ? b->z_index : 0;
  12101. if (az != bz)
  12102. return az < bz ? -1 : 1;
  12103. if (a->order != b->order)
  12104. return a->order < b->order ? -1 : 1;
  12105. return 0;
  12106. }
  12107. static void sort_deferred(void)
  12108. {
  12109. int i;
  12110. for (i = 1; i < ndeferred; i++) {
  12111. struct br_deferred key = deferred[i];
  12112. int j = i;
  12113. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  12114. deferred[j] = deferred[j - 1];
  12115. j--;
  12116. }
  12117. deferred[j] = key;
  12118. }
  12119. }
  12120. static void render_page(int left, int right, int y0)
  12121. {
  12122. struct lay *l = &layout_state;
  12123. struct br_style base = base_style();
  12124. inline_box_pass_id++;
  12125. l->box_owner = 0;
  12126. l->draw = 1;
  12127. l->ui = &ui;
  12128. l->left = left;
  12129. l->right = right;
  12130. l->y = y0;
  12131. l->line_x = left;
  12132. l->run_x = left;
  12133. l->line_left = left;
  12134. l->line_right = right;
  12135. l->line_y = y0;
  12136. l->line_h = 0;
  12137. l->align = BR_ALIGN_LEFT;
  12138. l->cb_h = layout_view_h;
  12139. l->float_active = 0;
  12140. l->parent_top = 0;
  12141. l->cb_left = left;
  12142. l->cb_right = right;
  12143. l->cb_top = y0;
  12144. l->depth = 0;
  12145. l->nruns = 0;
  12146. l->space_pending = 0;
  12147. nhits = 0;
  12148. ndeferred = 0;
  12149. base = root_style();
  12150. layout_children(l, doc.root, &base, 0, 0);
  12151. sort_deferred();
  12152. {
  12153. int i;
  12154. for (i = 0; i < ndeferred; i++) {
  12155. struct br_style st;
  12156. int hide;
  12157. br_style_for(&doc, deferred[i].node, &base, &st);
  12158. if (st.display == BR_DISPLAY_NONE)
  12159. continue;
  12160. /* A transparent or visibility:hidden positioned box
  12161. * still gets its boxes (scripts measure it) but no
  12162. * paint and no hit rectangles. */
  12163. hide = st.opacity_hidden || st.vis_hidden;
  12164. l->draw = !hide;
  12165. l->left = deferred[i].flow_left;
  12166. l->right = deferred[i].flow_right;
  12167. l->y = deferred[i].flow_y;
  12168. l->parent_top = deferred[i].parent_top;
  12169. l->line_left = l->line_x = l->left;
  12170. l->run_x = l->left;
  12171. l->line_y = l->y;
  12172. l->line_h = 0;
  12173. l->nruns = 0;
  12174. l->space_pending = 0;
  12175. l->align = st.align;
  12176. if (st.pos == 2 && block_h[deferred[i].node]) {
  12177. struct ngui_rect clip;
  12178. int ch = block_h[deferred[i].node] + 24;
  12179. int pr = page_rect.x + page_rect.w - 12;
  12180. int x0 = page_rect.x, x1 = pr;
  12181. int y0 = page_rect.y;
  12182. /* A box placed by `bottom` (a page footer) is
  12183. * clipped and filled where layout_block puts
  12184. * it, against the bottom edge. */
  12185. if (st.bottom_set && !st.top_set) {
  12186. ch = block_h[deferred[i].node] +
  12187. mp_px(&st, 0, pr - page_rect.x) +
  12188. mp_px(&st, 2, pr - page_rect.x);
  12189. y0 = page_rect.y + page_rect.h -
  12190. st.bottom - ch;
  12191. }
  12192. /* The background pre-fill spans the box's own
  12193. * columns, not the whole page: Docusaurus parks
  12194. * a white "Skip to main content" link at
  12195. * `left: 100%` with a z-index above the navbar,
  12196. * and a full-width fill painted over the bar. */
  12197. if (st.left_set)
  12198. x0 = page_rect.x + st.left;
  12199. else if (!st.right_set)
  12200. x0 = deferred[i].flow_left;
  12201. if (st.width_kind == 1) {
  12202. if (st.right_set && !st.left_set)
  12203. x0 = pr - st.right - st.width;
  12204. x1 = x0 + st.width;
  12205. } else if (st.right_set) {
  12206. x1 = pr - st.right;
  12207. }
  12208. if (x0 >= pr || x1 <= page_rect.x)
  12209. continue; /* entirely off-screen */
  12210. if (x0 < page_rect.x)
  12211. x0 = page_rect.x;
  12212. if (x1 > pr)
  12213. x1 = pr;
  12214. if (y0 < page_rect.y) {
  12215. ch -= page_rect.y - y0;
  12216. y0 = page_rect.y;
  12217. }
  12218. clip.x = x0;
  12219. clip.y = y0;
  12220. clip.w = x1 - x0;
  12221. if (ch > page_rect.h)
  12222. ch = page_rect.h;
  12223. if (ch <= 0)
  12224. continue;
  12225. clip.h = ch;
  12226. ngui_push_clip(&ui, clip);
  12227. if (st.has_bg && !hide)
  12228. ngui_fill_rect(&ui, clip, st.bg);
  12229. layout_block(l, deferred[i].node, &st, 0,
  12230. deferred[i].link);
  12231. ngui_pop_clip(&ui);
  12232. } else {
  12233. layout_block(l, deferred[i].node, &st, 0,
  12234. deferred[i].link);
  12235. }
  12236. }
  12237. }
  12238. }
  12239. /* ---- UI ---- */
  12240. static int find_hit(int x, int y)
  12241. {
  12242. int i;
  12243. for (i = nhits - 1; i >= 0; i--) {
  12244. struct hit *h = &hits[i];
  12245. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  12246. y < h->y + h->h)
  12247. return (int)h->node;
  12248. }
  12249. return 0;
  12250. }
  12251. /* ---- URL-bar autocomplete ----
  12252. *
  12253. * While the address bar has the focus a dropdown lists up to SUG_MAX
  12254. * history entries. An empty bar (a fresh focus, Ctrl+L) shows the most
  12255. * visited/recent sites; typing ranks prefix matches of the URL (with or
  12256. * without the scheme and "www.") above substring matches of the URL, then
  12257. * of the title, and adds visit count and recency. Typing at the end of the
  12258. * text also completes inline to the next '/' of the best prefix match
  12259. * ("clo" -> "cloudron.io/"), with the added part selected so the next
  12260. * keystroke replaces it; Enter on that text opens the history URL it came
  12261. * from (scheme included). Up/Down preview a row in the bar, Delete on a
  12262. * highlighted row forgets it, Esc closes the list (a second Esc leaves the
  12263. * bar), and a click on a row opens it. */
  12264. #define SUG_MAX 6
  12265. #define SUG_ROW_H 36
  12266. static int sug_idx[SUG_MAX];
  12267. static int sug_n, sug_sel = -1, sug_open;
  12268. static char sug_typed[NGUI_INPUT_MAX]; /* what the user typed */
  12269. static char sug_restore[NGUI_INPUT_MAX]; /* bar text before a preview */
  12270. static char ac_text[NGUI_INPUT_MAX]; /* bar text of the inline completion */
  12271. static char ac_url[HIST_URL_MAX]; /* the history URL it stands for */
  12272. static struct ngui_rect url_rect, sug_rect;
  12273. static int url_had_focus;
  12274. static char lc(char c)
  12275. {
  12276. return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
  12277. }
  12278. static int prefix_ci(const char *s, const char *p) /* p is lower case */
  12279. {
  12280. for (; *p; s++, p++)
  12281. if (lc(*s) != *p)
  12282. return 0;
  12283. return 1;
  12284. }
  12285. static unsigned int url_scheme_len(const char *url)
  12286. {
  12287. if (starts_with(url, "https://"))
  12288. return 8;
  12289. if (starts_with(url, "http://"))
  12290. return 7;
  12291. return 0;
  12292. }
  12293. /* Offset in `url` where the lower-case text `t` matches as a prefix: the
  12294. * whole URL, the URL without its scheme, or without scheme and "www.". */
  12295. static int hist_prefix_at(const char *url, const char *t)
  12296. {
  12297. unsigned int s = url_scheme_len(url);
  12298. if (prefix_ci(url, t))
  12299. return 0;
  12300. if (s && prefix_ci(url + s, t))
  12301. return (int)s;
  12302. if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
  12303. return (int)s + 4;
  12304. return -1;
  12305. }
  12306. static int hist_score(const struct hist_ent *e, const char *t,
  12307. unsigned int next)
  12308. {
  12309. unsigned int age = next - e->stamp;
  12310. int sc, at;
  12311. if (!t[0]) {
  12312. sc = 0;
  12313. } else if ((at = hist_prefix_at(e->url, t)) >= 0) {
  12314. /* Shorter rests first: "cloudron.io/" before its subpages. */
  12315. int rest = (int)s_len(e->url + at);
  12316. sc = 4000 - (rest > 400 ? 400 : rest);
  12317. } else if (contains_ci(e->url, t)) {
  12318. sc = 1000;
  12319. } else if (contains_ci(e->title, t)) {
  12320. sc = 600;
  12321. } else {
  12322. return -1;
  12323. }
  12324. sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
  12325. sc += age >= 500 ? 0 : (int)(500 - age);
  12326. return sc;
  12327. }
  12328. static void sug_lower(char *t, unsigned int cap)
  12329. {
  12330. unsigned int k;
  12331. for (k = 0; sug_typed[k] && k + 1 < cap; k++)
  12332. t[k] = lc(sug_typed[k]);
  12333. t[k] = '\0';
  12334. }
  12335. static void sug_refresh(void)
  12336. {
  12337. char t[NGUI_INPUT_MAX];
  12338. int sc[SUG_MAX], i, j;
  12339. unsigned int next = hist_next_stamp();
  12340. sug_lower(t, sizeof(t));
  12341. sug_n = 0;
  12342. for (i = 0; i < hist_n; i++) {
  12343. int s = hist_score(&hist_tab[i], t, next);
  12344. if (s < 0)
  12345. continue;
  12346. j = sug_n;
  12347. if (j == SUG_MAX) {
  12348. if (sc[SUG_MAX - 1] >= s)
  12349. continue;
  12350. j = SUG_MAX - 1;
  12351. }
  12352. while (j > 0 && sc[j - 1] < s) {
  12353. sc[j] = sc[j - 1];
  12354. sug_idx[j] = sug_idx[j - 1];
  12355. j--;
  12356. }
  12357. sc[j] = s;
  12358. sug_idx[j] = i;
  12359. if (sug_n < SUG_MAX)
  12360. sug_n++;
  12361. }
  12362. if (sug_sel >= sug_n)
  12363. sug_sel = -1;
  12364. }
  12365. /* Complete the typed text inline to the next '/' of the best prefix match. */
  12366. static void sug_inline(void)
  12367. {
  12368. char t[NGUI_INPUT_MAX];
  12369. const char *url, *rest;
  12370. unsigned int L, start, end, hs, tn, n = 0;
  12371. unsigned int next = hist_next_stamp();
  12372. int i, best = -1, best_sc = -1, at = 0;
  12373. sug_lower(t, sizeof(t));
  12374. L = s_len(t);
  12375. if (!L)
  12376. return;
  12377. for (i = 0; i < hist_n; i++) {
  12378. int a = hist_prefix_at(hist_tab[i].url, t), s;
  12379. if (a < 0)
  12380. continue;
  12381. s = hist_score(&hist_tab[i], t, next);
  12382. if (s > best_sc) {
  12383. best_sc = s;
  12384. best = i;
  12385. at = a;
  12386. }
  12387. }
  12388. if (best < 0)
  12389. return;
  12390. url = hist_tab[best].url;
  12391. rest = url + at;
  12392. /* Typing the scheme ("htt") completes past "https://", not to it. */
  12393. hs = at == 0 ? url_scheme_len(url) : 0;
  12394. start = L > hs ? L : hs;
  12395. end = start;
  12396. while (rest[end] && rest[end] != '/')
  12397. end++;
  12398. if (rest[end] == '/')
  12399. end++;
  12400. tn = s_len(sug_typed);
  12401. if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
  12402. return;
  12403. s_append(ac_text, &n, sug_typed, sizeof(ac_text));
  12404. for (; L < end && n + 1 < sizeof(ac_text); L++)
  12405. ac_text[n++] = rest[L];
  12406. ac_text[n] = '\0';
  12407. s_copy(ac_url, url, (unsigned int)at + end + 1);
  12408. ngui_input_set(&url_in, ac_text);
  12409. url_in.anchor = tn; /* select the completed part */
  12410. }
  12411. static void sug_close(void)
  12412. {
  12413. sug_open = 0;
  12414. sug_sel = -1;
  12415. ac_text[0] = '\0';
  12416. }
  12417. static int sug_visible(void)
  12418. {
  12419. return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
  12420. }
  12421. /* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
  12422. * start page) lists the top sites until something is typed. */
  12423. static int sug_focus_check(void)
  12424. {
  12425. int focused = ngui_focus(&ui) == ID_URL;
  12426. if (focused && !url_had_focus) {
  12427. sug_typed[0] = '\0';
  12428. sug_close();
  12429. sug_open = 1;
  12430. sug_refresh();
  12431. }
  12432. url_had_focus = focused;
  12433. return focused;
  12434. }
  12435. static void url_submit(unsigned int *action)
  12436. {
  12437. if (ac_text[0] && s_eq(url_in.text, ac_text))
  12438. s_copy(click_url, ac_url, sizeof(click_url));
  12439. *action |= ACT_NAV;
  12440. sug_close();
  12441. }
  12442. /* The bar text changed through typing or editing. */
  12443. static void sug_changed(void)
  12444. {
  12445. unsigned int pl = s_len(sug_typed);
  12446. int grew = url_in.len > pl && url_in.cursor == url_in.len &&
  12447. !memcmp(url_in.text, sug_typed, pl);
  12448. s_copy(sug_typed, url_in.text, sizeof(sug_typed));
  12449. ac_text[0] = '\0';
  12450. sug_sel = -1;
  12451. sug_open = 1;
  12452. sug_refresh();
  12453. if (grew)
  12454. sug_inline();
  12455. }
  12456. /* Keys for the list, taken off the queue before the text field sees them.
  12457. * Only a leading run is handled; the rest goes to the field. */
  12458. static void sug_keys(void)
  12459. {
  12460. int k;
  12461. while ((k = ngui_key_peek(&ui)) != 0) {
  12462. if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
  12463. ngui_key(&ui);
  12464. if (!sug_open) {
  12465. sug_open = 1;
  12466. continue;
  12467. }
  12468. if (sug_sel < 0)
  12469. s_copy(sug_restore, url_in.text,
  12470. sizeof(sug_restore));
  12471. if (k == NGUI_KEY_DOWN)
  12472. sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
  12473. else
  12474. sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
  12475. ngui_input_set(&url_in, sug_sel >= 0 ?
  12476. hist_tab[sug_idx[sug_sel]].url :
  12477. sug_restore);
  12478. } else if (k == NGUI_KEY_ESC && sug_visible()) {
  12479. ngui_key(&ui);
  12480. if (sug_sel >= 0)
  12481. ngui_input_set(&url_in, sug_restore);
  12482. else if (ac_text[0] && s_eq(url_in.text, ac_text))
  12483. ngui_input_set(&url_in, sug_typed);
  12484. sug_close();
  12485. } else if (k == NGUI_KEY_DELETE && sug_visible() &&
  12486. sug_sel >= 0) {
  12487. ngui_key(&ui);
  12488. hist_forget(sug_idx[sug_sel]);
  12489. ngui_input_set(&url_in, sug_restore);
  12490. sug_sel = -1;
  12491. sug_refresh();
  12492. } else {
  12493. break;
  12494. }
  12495. }
  12496. }
  12497. /* A press on a row of last frame's list opens it; any press on the list is
  12498. * swallowed so the page underneath does not see it. */
  12499. static void sug_click(unsigned int *action)
  12500. {
  12501. int row;
  12502. if (!(ui.pressed & 1) || !sug_rect.w ||
  12503. !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
  12504. return;
  12505. row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
  12506. if (row >= 0 && row < sug_n) {
  12507. s_copy(click_url, hist_tab[sug_idx[row]].url,
  12508. sizeof(click_url));
  12509. *action |= ACT_NAV;
  12510. sug_close();
  12511. }
  12512. ui.pressed = 0;
  12513. }
  12514. static void draw_suggest(struct ngui_rect page)
  12515. {
  12516. struct ngui_rect r;
  12517. int i, rows = sug_n, hover = -1;
  12518. r.x = url_rect.x;
  12519. r.y = url_rect.y + url_rect.h + 1;
  12520. r.w = url_rect.w < 320 ? 320 : url_rect.w;
  12521. if (r.x + r.w > ui.w - 2)
  12522. r.w = ui.w - 2 - r.x;
  12523. while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
  12524. rows--;
  12525. if (rows <= 0 || r.w < 60) {
  12526. sug_rect.w = 0;
  12527. return;
  12528. }
  12529. r.h = rows * SUG_ROW_H + 2;
  12530. sug_rect = r;
  12531. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  12532. hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
  12533. ngui_set_cursor(&ui, CURSOR_POINTER);
  12534. }
  12535. ngui_fill_rect(&ui, r, ui.theme.border);
  12536. for (i = 0; i < rows; i++) {
  12537. const struct hist_ent *e = &hist_tab[sug_idx[i]];
  12538. struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
  12539. r.w - 2, SUG_ROW_H};
  12540. struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
  12541. unsigned short bg = i == sug_sel ? ui.theme.selection :
  12542. i == hover ? ui.theme.panel_alt :
  12543. ui.theme.panel;
  12544. ngui_fill_rect(&ui, rr, bg);
  12545. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
  12546. e->title[0] ? e->title : e->url,
  12547. ui.theme.text);
  12548. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
  12549. i == sug_sel ? ui.theme.text :
  12550. ui.theme.text_dim);
  12551. }
  12552. }
  12553. static void ctx_close(void);
  12554. static void ctx_open_from_right(struct ngui_rect page);
  12555. static void ctx_press(struct ngui_rect page);
  12556. static void draw_context(void);
  12557. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  12558. {
  12559. int x = r.x + 4, y = r.y + 4, h = 22;
  12560. int compact = r.w < 560;
  12561. int go_w = r.w < 420 ? 32 : 42;
  12562. int in_x, in_w, res;
  12563. ngui_fill_rect(&ui, r, ui.theme.panel);
  12564. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  12565. ui.theme.border);
  12566. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  12567. NGUI_ICON_CHEVRON_LEFT))
  12568. *action |= ACT_BACK;
  12569. x += 32;
  12570. if (!compact) {
  12571. if (ngui_icon_button(&ui, ID_FORWARD,
  12572. (struct ngui_rect){x, y, 28, h},
  12573. NGUI_ICON_CHEVRON_RIGHT))
  12574. *action |= ACT_FORWARD;
  12575. x += 32;
  12576. }
  12577. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  12578. NGUI_ICON_REFRESH))
  12579. *action |= ACT_RELOAD;
  12580. x += 32;
  12581. if (!compact) {
  12582. if (ngui_icon_button(&ui, ID_HOME,
  12583. (struct ngui_rect){x, y, 28, h},
  12584. NGUI_ICON_HOME))
  12585. *action |= ACT_HOME;
  12586. x += 32;
  12587. }
  12588. dl_button_rect = (struct ngui_rect){x, y, 28, h};
  12589. if (ngui_icon_button(&ui, ID_DOWNLOADS, dl_button_rect,
  12590. NGUI_ICON_DOWNLOAD)) {
  12591. dl_panel_open = !dl_panel_open;
  12592. if (dl_panel_open) {
  12593. dl_unseen = 0;
  12594. ctx_close();
  12595. sug_close();
  12596. ngui_set_focus(&ui, 0);
  12597. }
  12598. ngui_invalidate(&ui);
  12599. }
  12600. if (dl_active >= 0) {
  12601. int p = dl_percent();
  12602. if (p < 0)
  12603. p = 0;
  12604. ngui_fill_rect(&ui, (struct ngui_rect){
  12605. dl_button_rect.x + 3,
  12606. dl_button_rect.y + dl_button_rect.h - 4,
  12607. dl_button_rect.w - 6, 2}, ui.theme.border);
  12608. if (p > 0)
  12609. ngui_fill_rect(&ui, (struct ngui_rect){
  12610. dl_button_rect.x + 3,
  12611. dl_button_rect.y + dl_button_rect.h - 4,
  12612. (dl_button_rect.w - 6) * p / 100, 2},
  12613. ui.theme.accent);
  12614. }
  12615. if (dl_unseen && !dl_panel_open)
  12616. ngui_fill_rect(&ui, (struct ngui_rect){
  12617. dl_button_rect.x + dl_button_rect.w - 6,
  12618. dl_button_rect.y + 2, 4, 4}, ui.theme.accent);
  12619. x += 32;
  12620. in_x = x + 2;
  12621. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  12622. if (in_w < 60)
  12623. in_w = 60;
  12624. url_rect = (struct ngui_rect){in_x, y, in_w, h};
  12625. if (sug_focus_check())
  12626. sug_keys();
  12627. res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
  12628. sug_focus_check(); /* a click into the bar focuses it here */
  12629. if (res & NGUI_INPUT_CHANGED)
  12630. sug_changed();
  12631. if (res & NGUI_INPUT_SUBMIT)
  12632. url_submit(action);
  12633. if (res & NGUI_INPUT_CANCEL)
  12634. ngui_set_focus(&ui, 0);
  12635. if (ngui_button(&ui, ID_GO,
  12636. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  12637. "Go"))
  12638. url_submit(action);
  12639. if (!sug_focus_check())
  12640. sug_close();
  12641. }
  12642. static int page_hover_node(void)
  12643. {
  12644. if (!ui.inside || ctx_open || dl_panel_open)
  12645. return 0;
  12646. if (ui.mouse_x < page_rect.x ||
  12647. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  12648. ui.mouse_y < page_rect.y ||
  12649. ui.mouse_y >= page_rect.y + page_rect.h)
  12650. return 0;
  12651. return find_hit(ui.mouse_x, ui.mouse_y);
  12652. }
  12653. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  12654. {
  12655. int x, y, w = page.w, h = page.h;
  12656. if (!src || w <= 0 || h <= 0)
  12657. return;
  12658. for (y = 0; y < h; y++) {
  12659. unsigned short *s = src + (page.y + y) * sw + page.x;
  12660. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  12661. for (x = 0; x + 1 < w; x += 2) {
  12662. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  12663. }
  12664. if (x < w)
  12665. d[x] = s[x];
  12666. }
  12667. }
  12668. static void draw_page(struct ngui_rect page)
  12669. {
  12670. int left, right, ch;
  12671. int old_panel, old_dim;
  12672. unsigned short *saved_px;
  12673. unsigned short page_bg = ui.theme.bg;
  12674. int saved_w, saved_h, use_buf;
  12675. unsigned int t0 = u_ticks_ms();
  12676. page_rect = page;
  12677. {
  12678. unsigned int root = doc.nnode > 1 ?
  12679. br_find_tag(&doc, BR_TAG_HTML) : 0;
  12680. unsigned int body = doc.nnode > 1 ?
  12681. br_find_tag(&doc, BR_TAG_BODY) : 0;
  12682. struct br_style bs;
  12683. int bg_found = 0;
  12684. if (root) {
  12685. style_for_node(root - 1, &bs);
  12686. if (bs.has_bg) {
  12687. page_bg = bs.bg;
  12688. bg_found = 1;
  12689. }
  12690. }
  12691. if (body) {
  12692. style_for_node(body - 1, &bs);
  12693. if (bs.has_bg) {
  12694. page_bg = bs.bg;
  12695. bg_found = 1;
  12696. }
  12697. }
  12698. /* No canvas colour, but the author made the text dark
  12699. * (Infima's light theme: `--ifm-background-color:
  12700. * transparent` on html, #1c1e21 text): the page expects the
  12701. * white canvas of a normal browser, and dark text on the
  12702. * dark default canvas is unreadable. */
  12703. if (!bg_found && (body || root) && bs.color != ui.theme.text) {
  12704. unsigned int c = bs.color;
  12705. unsigned int lum = ((c >> 11) & 31) * 8 * 299 +
  12706. ((c >> 5) & 63) * 4 * 587 +
  12707. (c & 31) * 8 * 114;
  12708. if (lum < 100 * 1000)
  12709. page_bg = 0xFFFF;
  12710. }
  12711. }
  12712. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  12713. page_cache_valid && layout_valid &&
  12714. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  12715. !(ui.scroll_y &&
  12716. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  12717. page_scroll.offset == page_cache_scroll &&
  12718. page_cache_nnode == doc.nnode &&
  12719. page_cache_x == page.x && page_cache_y == page.y &&
  12720. page_cache_w == page.w && page_cache_h == page.h) {
  12721. blit_page(page, page_backbuf, pagebuf_w);
  12722. if (img_stat_n)
  12723. img_stat_paint += u_ticks_ms() - t0;
  12724. return;
  12725. }
  12726. ngui_fill_rect(&ui, page, page_bg);
  12727. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  12728. const char *s = page_loading ? "Loading..." : "No page";
  12729. int w = (int)ngui_text_width_ui(&ui, s);
  12730. ngui_text(&ui, page.x + (page.w - w) / 2,
  12731. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  12732. page_scroll.content_h = 0;
  12733. page_scroll.view_h = page.h;
  12734. page_cache_valid = 0;
  12735. return;
  12736. }
  12737. if (page.w < 40 || page.h < 40) {
  12738. page_cache_valid = 0;
  12739. return;
  12740. }
  12741. saved_px = ui.px;
  12742. saved_w = ui.w;
  12743. saved_h = ui.h;
  12744. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  12745. if (use_buf) {
  12746. ui.px = page_backbuf;
  12747. ui.w = pagebuf_w;
  12748. ui.h = pagebuf_h;
  12749. ngui_fill_rect(&ui, page, page_bg);
  12750. }
  12751. /* No gutter of our own: the body's UA margin provides it. The
  12752. * right 12 px stay clear for the scrollbar, like every viewport
  12753. * width below (page_rect.w - 12). */
  12754. left = page.x;
  12755. right = page.x + page.w - 12;
  12756. if (!layout_valid || left != layout_left || right != layout_right ||
  12757. layout_nnode != doc.nnode) {
  12758. unsigned int tm = u_ticks_ms();
  12759. layout_view_h = page.h;
  12760. layout_content_h = measure_page(left, right);
  12761. if (img_stat_n)
  12762. img_stat_reflow += u_ticks_ms() - tm;
  12763. layout_valid = 1;
  12764. layout_left = left;
  12765. layout_right = right;
  12766. layout_nnode = doc.nnode;
  12767. /* Scripts that measured before any layout (offsetWidth on
  12768. * mount) get a resize event once real boxes exist, and again
  12769. * whenever the page width changes. */
  12770. if (js_browser_active() && right - left != resize_sent_w)
  12771. resize_pending = 1;
  12772. }
  12773. ch = layout_content_h;
  12774. page_scroll.content_h = ch;
  12775. page_scroll.view_h = page.h;
  12776. t0 = u_ticks_ms();
  12777. ngui_scroll_begin(&ui, page, &page_scroll);
  12778. ngui_scroll_wheel(&ui, page, &page_scroll);
  12779. render_page(left, right, page.y - page_scroll.offset);
  12780. old_panel = ui.theme.panel_alt;
  12781. old_dim = ui.theme.text_dim;
  12782. ui.theme.panel_alt = 0xC618;
  12783. ui.theme.text_dim = 0x8410;
  12784. ngui_scroll_end(&ui, page, &page_scroll);
  12785. ui.theme.panel_alt = old_panel;
  12786. ui.theme.text_dim = old_dim;
  12787. if (use_buf) {
  12788. ui.px = saved_px;
  12789. ui.w = saved_w;
  12790. ui.h = saved_h;
  12791. blit_page(page, page_backbuf, pagebuf_w);
  12792. page_cache_valid = 1;
  12793. page_cache_scroll = page_scroll.offset;
  12794. page_cache_nnode = doc.nnode;
  12795. page_cache_x = page.x;
  12796. page_cache_y = page.y;
  12797. page_cache_w = page.w;
  12798. page_cache_h = page.h;
  12799. } else {
  12800. page_cache_valid = 0;
  12801. }
  12802. if (img_stat_n)
  12803. img_stat_paint += u_ticks_ms() - t0;
  12804. }
  12805. /* Lay the page out now, into the page back buffer, so scripts read real
  12806. * boxes for nodes they just inserted. Absolute/fixed boxes only get their
  12807. * boxes in the painting pass, so this is a full render; the next frame
  12808. * repaints the screen as usual. Skipped while the page has never been
  12809. * drawn (no viewport yet) or without the back buffer. */
  12810. static void js_force_layout(void)
  12811. {
  12812. static int busy;
  12813. unsigned short *saved_px = ui.px;
  12814. int saved_w = ui.w, saved_h = ui.h;
  12815. struct ngui_rect page = page_rect;
  12816. static unsigned int window_t0, spent;
  12817. unsigned int t0 = u_ticks_ms();
  12818. if (busy || !page_backbuf || pagebuf_w != ui.w ||
  12819. pagebuf_h != ui.h || page.w < 40 || page.h < 40 ||
  12820. layout_right <= layout_left)
  12821. return;
  12822. /* Budget: a script that alternates writes and reads (an animation
  12823. * loop) would otherwise re-render the page on every read. Past
  12824. * 40 ms of forced layouts in a 100 ms window it reads the last
  12825. * layout, as before. */
  12826. if (t0 - window_t0 >= 100) {
  12827. window_t0 = t0;
  12828. spent = 0;
  12829. }
  12830. if (spent >= 40)
  12831. return;
  12832. busy = 1;
  12833. ui.px = page_backbuf;
  12834. layout_view_h = page.h;
  12835. layout_content_h = measure_page(layout_left, layout_right);
  12836. layout_valid = 1;
  12837. layout_nnode = doc.nnode;
  12838. ngui_push_clip(&ui, page);
  12839. render_page(layout_left, layout_right, page.y - page_scroll.offset);
  12840. ngui_pop_clip(&ui);
  12841. ui.px = saved_px;
  12842. ui.w = saved_w;
  12843. ui.h = saved_h;
  12844. page_cache_valid = 0;
  12845. ngui_invalidate(&ui);
  12846. spent += u_ticks_ms() - t0;
  12847. busy = 0;
  12848. }
  12849. static void draw_status(struct ngui_rect r)
  12850. {
  12851. static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
  12852. unsigned int n = 0;
  12853. int hover = page_hover_node();
  12854. unsigned short color;
  12855. const char *kind;
  12856. ngui_fill_rect(&ui, r, ui.theme.panel);
  12857. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  12858. ui.theme.border);
  12859. /* Only a real link target is shown: a form control, or an element
  12860. * that is merely clickable through a script listener (google.com's
  12861. * jsaction wrapper around its search field), is not a link. */
  12862. if (hover && !br_href(&doc, (unsigned int)hover))
  12863. hover = 0;
  12864. if (hover) {
  12865. const char *href = br_href(&doc, (unsigned int)hover);
  12866. char url[BR_URL_MAX];
  12867. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  12868. s_append(msg, &n, "Link: ", sizeof(msg));
  12869. s_append(msg, &n, url, sizeof(msg));
  12870. } else {
  12871. s_copy(msg, "Link", sizeof(msg));
  12872. }
  12873. color = ui.theme.accent;
  12874. } else if (status_text[0]) {
  12875. s_copy(msg, status_text, sizeof(msg));
  12876. color = status_error ? ui.theme.error : ui.theme.text;
  12877. } else if (page_title[0]) {
  12878. s_copy(msg, page_title, sizeof(msg));
  12879. color = ui.theme.text;
  12880. } else {
  12881. s_copy(msg, "Ready", sizeof(msg));
  12882. color = ui.theme.text_dim;
  12883. }
  12884. kind = s_eq(page_url, "about:home") ? "HOME" :
  12885. page_is_local ? "FILE" :
  12886. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  12887. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  12888. {
  12889. int kw = (int)ngui_text_width_ui(&ui, kind);
  12890. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  12891. ui.theme.text_dim);
  12892. }
  12893. }
  12894. /* ---- downloads panel -------------------------------------------------- */
  12895. static int dl_order[DL_MAX], dl_order_n;
  12896. static void dl_order_build(void)
  12897. {
  12898. int i, j;
  12899. dl_order_n = 0;
  12900. for (i = 0; i < DL_MAX; i++)
  12901. if (dl_tab[i].used)
  12902. dl_order[dl_order_n++] = i;
  12903. for (i = 1; i < dl_order_n; i++) {
  12904. int key = dl_order[i];
  12905. unsigned int stamp = dl_tab[key].stamp;
  12906. for (j = i - 1; j >= 0 &&
  12907. dl_tab[dl_order[j]].stamp < stamp; j--)
  12908. dl_order[j + 1] = dl_order[j];
  12909. dl_order[j + 1] = key;
  12910. }
  12911. }
  12912. static void dl_size_text(unsigned int size, char *out, unsigned int cap)
  12913. {
  12914. if (size >= 1024u * 1024u)
  12915. snprintf(out, cap, "%u.%u MB", size / (1024u * 1024u),
  12916. (size % (1024u * 1024u)) * 10 / (1024u * 1024u));
  12917. else if (size >= 1024u)
  12918. snprintf(out, cap, "%u KB", size / 1024u);
  12919. else
  12920. snprintf(out, cap, "%u bytes", size);
  12921. }
  12922. static void dl_ent_label(const struct dl_ent *e, char *out, unsigned int cap)
  12923. {
  12924. char base[16], ext[8];
  12925. if (e->name[0]) {
  12926. s_copy(out, e->name, cap);
  12927. return;
  12928. }
  12929. dl_url_name(e->url, "", base, sizeof(base), ext, sizeof(ext));
  12930. if (ext[0])
  12931. snprintf(out, cap, "%s.%s", base, ext);
  12932. else
  12933. s_copy(out, base, cap);
  12934. }
  12935. static void dl_ent_status(const struct dl_ent *e, char *out,
  12936. unsigned int cap)
  12937. {
  12938. char size[24];
  12939. switch (e->state) {
  12940. case DL_QUEUED:
  12941. s_copy(out, "Queued", cap);
  12942. break;
  12943. case DL_RUNNING: {
  12944. int p = dl_percent();
  12945. if (p >= 0) {
  12946. snprintf(out, cap, "Downloading %d%%", p);
  12947. } else {
  12948. dl_size_text(e->got, size, sizeof(size));
  12949. snprintf(out, cap, "Downloading %s", size);
  12950. }
  12951. break;
  12952. }
  12953. case DL_SAVING:
  12954. s_copy(out, "Saving...", cap);
  12955. break;
  12956. case DL_DONE:
  12957. dl_size_text(e->size, size, sizeof(size));
  12958. snprintf(out, cap, "Saved - %s", size);
  12959. break;
  12960. default:
  12961. if (e->err[0])
  12962. snprintf(out, cap, "Failed: %s", e->err);
  12963. else
  12964. s_copy(out, "Failed", cap);
  12965. break;
  12966. }
  12967. }
  12968. static void dl_panel_layout(struct ngui_rect page)
  12969. {
  12970. int w = DL_PANEL_W, rows, avail, h, x, y;
  12971. dl_order_build();
  12972. rows = dl_order_n;
  12973. if (rows > DL_PANEL_ROWS)
  12974. rows = DL_PANEL_ROWS;
  12975. avail = (page.h - 46) / DL_ROW_H;
  12976. if (avail < 0)
  12977. avail = 0;
  12978. if (rows > avail)
  12979. rows = avail;
  12980. dl_panel_rows = rows;
  12981. if (w > page.w - 16)
  12982. w = page.w - 16;
  12983. if (w < 120)
  12984. w = 120;
  12985. h = 36 + (rows ? rows * DL_ROW_H : 28) + 6;
  12986. if (h > page.h - 8)
  12987. h = page.h - 8;
  12988. x = dl_button_rect.x + dl_button_rect.w - w;
  12989. if (x + w > page.x + page.w - 4)
  12990. x = page.x + page.w - 4 - w;
  12991. if (x < page.x + 4)
  12992. x = page.x + 4;
  12993. y = page.y + 2;
  12994. dl_panel_rect = (struct ngui_rect){x, y, w, h};
  12995. dl_clear_rect = (struct ngui_rect){x + w - 54, y + 6, 46, 20};
  12996. }
  12997. static void dl_panel_press(struct ngui_rect page)
  12998. {
  12999. if (!dl_panel_open || !ui.pressed)
  13000. return;
  13001. dl_panel_layout(page);
  13002. if (ngui_rect_contains(&dl_panel_rect, ui.press_x, ui.press_y)) {
  13003. if (ngui_rect_contains(&dl_clear_rect, ui.press_x, ui.press_y))
  13004. dl_clear_history();
  13005. ui.pressed = ui.released = 0;
  13006. return;
  13007. }
  13008. if (!ngui_rect_contains(&dl_button_rect, ui.press_x, ui.press_y)) {
  13009. dl_panel_open = 0;
  13010. ngui_invalidate(&ui);
  13011. if (ngui_rect_contains(&page, ui.press_x, ui.press_y))
  13012. ui.pressed = ui.released = 0;
  13013. }
  13014. }
  13015. static void draw_downloads(struct ngui_rect page)
  13016. {
  13017. int i;
  13018. if (!dl_panel_open)
  13019. return;
  13020. dl_panel_layout(page);
  13021. if (ui.inside && ngui_rect_contains(&dl_panel_rect, ui.mouse_x,
  13022. ui.mouse_y))
  13023. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  13024. if (dl_history_count() > 0 && ui.inside &&
  13025. ngui_rect_contains(&dl_clear_rect, ui.mouse_x, ui.mouse_y))
  13026. ngui_set_cursor(&ui, CURSOR_POINTER);
  13027. ngui_fill_rect(&ui, dl_panel_rect, ui.theme.border);
  13028. ngui_fill_rect(&ui, (struct ngui_rect){dl_panel_rect.x + 1,
  13029. dl_panel_rect.y + 1, dl_panel_rect.w - 2,
  13030. dl_panel_rect.h - 2}, ui.theme.panel);
  13031. ngui_text_styled(&ui, dl_panel_rect.x + 10, dl_panel_rect.y + 8,
  13032. "Downloads", 9, ui.theme.text, 1, 1);
  13033. if (dl_history_count() > 0) {
  13034. int cw = (int)ngui_text_width_ui(&ui, "Clear");
  13035. int hot = ui.inside && ngui_rect_contains(&dl_clear_rect,
  13036. ui.mouse_x,
  13037. ui.mouse_y);
  13038. ngui_text(&ui, dl_clear_rect.x + (dl_clear_rect.w - cw) / 2,
  13039. dl_clear_rect.y + 1, "Clear",
  13040. hot ? ui.theme.accent : ui.theme.text_dim);
  13041. }
  13042. if (dl_order_n > dl_panel_rows && dl_panel_rows > 0 &&
  13043. dl_panel_rect.w > 260) {
  13044. char more[24];
  13045. int mw;
  13046. snprintf(more, sizeof(more), "%d more", dl_order_n - dl_panel_rows);
  13047. mw = (int)ngui_text_width_ui(&ui, more);
  13048. ngui_text(&ui, dl_clear_rect.x - mw - 8, dl_clear_rect.y + 1,
  13049. more, ui.theme.text_dim);
  13050. }
  13051. if (!dl_order_n) {
  13052. ngui_text(&ui, dl_panel_rect.x + 12,
  13053. dl_panel_rect.y + 40, "No downloads yet",
  13054. ui.theme.text_dim);
  13055. return;
  13056. }
  13057. for (i = 0; i < dl_panel_rows; i++) {
  13058. struct dl_ent *e = &dl_tab[dl_order[i]];
  13059. struct ngui_rect rr = {dl_panel_rect.x + 1,
  13060. dl_panel_rect.y + 30 + i * DL_ROW_H,
  13061. dl_panel_rect.w - 2, DL_ROW_H};
  13062. char name[DL_NAME_MAX], status[96];
  13063. int hot = ui.inside &&
  13064. ngui_rect_contains(&rr, ui.mouse_x, ui.mouse_y);
  13065. enum ngui_icon icon = NGUI_ICON_DOWNLOAD;
  13066. unsigned short icon_color = ui.theme.text_dim;
  13067. dl_ent_label(e, name, sizeof(name));
  13068. dl_ent_status(e, status, sizeof(status));
  13069. if (e->state == DL_DONE) {
  13070. icon = NGUI_ICON_FILE;
  13071. icon_color = ui.theme.text_dim;
  13072. } else if (e->state == DL_FAILED) {
  13073. icon = NGUI_ICON_CLOSE;
  13074. icon_color = ui.theme.error;
  13075. } else {
  13076. icon_color = ui.theme.accent;
  13077. }
  13078. ngui_fill_rect(&ui, rr, hot ? ui.theme.panel_alt : ui.theme.panel);
  13079. ngui_icon(&ui, (struct ngui_rect){rr.x + 7, rr.y + 8, 20, 20},
  13080. icon, icon_color);
  13081. ngui_text_ellipsis(&ui, rr, rr.x + 34, rr.y + 3, name,
  13082. ui.theme.text);
  13083. ngui_text_ellipsis(&ui, rr, rr.x + 34, rr.y + 19, status,
  13084. e->state == DL_FAILED ? ui.theme.error :
  13085. ui.theme.text_dim);
  13086. if (e->state == DL_RUNNING || e->state == DL_SAVING) {
  13087. int p = dl_percent();
  13088. int bw = rr.w - 42;
  13089. ngui_fill_rect(&ui, (struct ngui_rect){rr.x + 34,
  13090. rr.y + rr.h - 6, bw, 3},
  13091. ui.theme.border);
  13092. if (p > 0)
  13093. ngui_fill_rect(&ui, (struct ngui_rect){
  13094. rr.x + 34, rr.y + rr.h - 6,
  13095. bw * p / 100, 3}, ui.theme.accent);
  13096. }
  13097. }
  13098. }
  13099. /* Mouse cursor over the page: the hovered node's CSS `cursor` (inherited);
  13100. * for `auto`, a hand over links, the I-beam over text fields, and the
  13101. * progress arrow anywhere on the page while it is still loading. The
  13102. * toolbar's URL field sets its own I-beam through ngui. */
  13103. static void page_cursor(void)
  13104. {
  13105. int hover = page_hover_node();
  13106. struct br_style st;
  13107. if (!hover) {
  13108. if (page_loading && ui.inside &&
  13109. ngui_rect_contains(&page_rect, ui.mouse_x, ui.mouse_y))
  13110. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  13111. return;
  13112. }
  13113. style_for_node((unsigned int)hover, &st);
  13114. if (st.cursor != BR_CURSOR_AUTO) {
  13115. ngui_set_cursor(&ui, (int)st.cursor - 1);
  13116. return;
  13117. }
  13118. if (br_href(&doc, (unsigned int)hover)) {
  13119. ngui_set_cursor(&ui, CURSOR_POINTER);
  13120. return;
  13121. }
  13122. if (form_is_control((unsigned int)hover)) {
  13123. int k = form_kind_of((unsigned int)hover);
  13124. if (form_disabled((unsigned int)hover))
  13125. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  13126. else if (k == FORM_TEXT || k == FORM_PASSWORD ||
  13127. k == FORM_TEXTAREA)
  13128. ngui_set_cursor(&ui, CURSOR_TEXT);
  13129. return;
  13130. }
  13131. if (page_loading)
  13132. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  13133. }
  13134. static void draw(unsigned int *action)
  13135. {
  13136. struct ngui_rect r = {0, 0, ui.w, ui.h};
  13137. struct ngui_rect toolbar, status, page;
  13138. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  13139. status = ngui_cut_bottom(&r, BR_STATUS_H);
  13140. page = r;
  13141. if (sug_visible())
  13142. sug_click(action);
  13143. ctx_open_from_right(page);
  13144. ctx_press(page);
  13145. dl_panel_press(page);
  13146. draw_toolbar(toolbar, action);
  13147. draw_page(page);
  13148. draw_status(status);
  13149. page_cursor();
  13150. if (sug_visible())
  13151. draw_suggest(page);
  13152. else
  13153. sug_rect.w = 0;
  13154. draw_downloads(page);
  13155. draw_context();
  13156. }
  13157. static void redraw_now(void)
  13158. {
  13159. unsigned int action = 0;
  13160. ngui_begin(&ui);
  13161. draw(&action);
  13162. ngui_end(&ui);
  13163. }
  13164. static void handle_keys(unsigned int *action)
  13165. {
  13166. int k, scrolled = 0;
  13167. if (form_focus >= doc.nnode)
  13168. form_focus = 0;
  13169. if (form_focus && !ngui_focus(&ui)) {
  13170. while ((k = ngui_key(&ui)) != 0)
  13171. form_key(k);
  13172. return;
  13173. }
  13174. /* Batch queued page keys: a slow full-page render must not make a
  13175. * held Page Down advance only once every few frames. */
  13176. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  13177. scrolled++;
  13178. if (scrolled)
  13179. ngui_invalidate(&ui);
  13180. if (ngui_focus(&ui))
  13181. return;
  13182. while ((k = ngui_key(&ui)) != 0) {
  13183. switch (k) {
  13184. case NGUI_KEY_ESC:
  13185. if (ctx_open) {
  13186. ctx_close();
  13187. } else if (dl_panel_open) {
  13188. dl_panel_open = 0;
  13189. ngui_invalidate(&ui);
  13190. } else {
  13191. *action |= ACT_CLOSE;
  13192. }
  13193. break;
  13194. case NGUI_KEY_TAB:
  13195. case 0x0C: /* Ctrl+L */
  13196. ngui_set_focus(&ui, ID_URL);
  13197. break;
  13198. case 0x12: /* Ctrl+R */
  13199. *action |= ACT_RELOAD;
  13200. break;
  13201. case NGUI_KEY_BACKSPACE:
  13202. *action |= ACT_BACK;
  13203. break;
  13204. case NGUI_KEY_UP:
  13205. ngui_scroll_to(&page_scroll,
  13206. page_scroll.offset - 24);
  13207. ngui_invalidate(&ui);
  13208. break;
  13209. case NGUI_KEY_DOWN:
  13210. ngui_scroll_to(&page_scroll,
  13211. page_scroll.offset + 24);
  13212. ngui_invalidate(&ui);
  13213. break;
  13214. case NGUI_KEY_HOME:
  13215. ngui_scroll_to(&page_scroll, 0);
  13216. ngui_invalidate(&ui);
  13217. break;
  13218. case NGUI_KEY_END:
  13219. ngui_scroll_to(&page_scroll,
  13220. page_scroll.content_h -
  13221. page_scroll.view_h);
  13222. ngui_invalidate(&ui);
  13223. break;
  13224. default:
  13225. break;
  13226. }
  13227. }
  13228. }
  13229. static unsigned int form_ancestor(unsigned int node)
  13230. {
  13231. unsigned int p = node;
  13232. while (p && p < doc.nnode) {
  13233. if (doc.nodes[p].tag == BR_TAG_FORM &&
  13234. doc.nodes[p].type == BR_NODE_ELEM)
  13235. return p;
  13236. p = doc.nodes[p].parent;
  13237. }
  13238. return 0;
  13239. }
  13240. static int form_descendant(unsigned int node, unsigned int form)
  13241. {
  13242. unsigned int p = node;
  13243. while (p && p < doc.nnode) {
  13244. if (p == form)
  13245. return 1;
  13246. p = doc.nodes[p].parent;
  13247. }
  13248. return 0;
  13249. }
  13250. static void form_reset_form(unsigned int form)
  13251. {
  13252. unsigned int i;
  13253. for (i = 0; i < FORM_MAX; i++)
  13254. if (form_states[i].used &&
  13255. form_descendant(form_states[i].node, form))
  13256. form_states[i].used = 0;
  13257. form_focus = 0;
  13258. }
  13259. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  13260. const char *s)
  13261. {
  13262. static const char hex[] = "0123456789ABCDEF";
  13263. while (s && *s && *n + 1 < cap) {
  13264. unsigned char c = (unsigned char)*s++;
  13265. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  13266. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  13267. c == '.' || c == '~') {
  13268. dst[(*n)++] = (char)c;
  13269. } else if (c == ' ') {
  13270. dst[(*n)++] = '+';
  13271. } else if (*n + 3 < cap) {
  13272. dst[(*n)++] = '%';
  13273. dst[(*n)++] = hex[c >> 4];
  13274. dst[(*n)++] = hex[c & 15];
  13275. }
  13276. }
  13277. dst[*n] = '\0';
  13278. }
  13279. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  13280. const char *name, const char *value, int *first)
  13281. {
  13282. if (!name || !name[0])
  13283. return;
  13284. if (!*first && *n + 1 < cap)
  13285. dst[(*n)++] = '&';
  13286. *first = 0;
  13287. form_url_append(dst, n, cap, name);
  13288. if (*n + 1 < cap)
  13289. dst[(*n)++] = '=';
  13290. form_url_append(dst, n, cap, value ? value : "");
  13291. dst[*n] = '\0';
  13292. }
  13293. static int form_submit_form(unsigned int node, int fire_event)
  13294. {
  13295. unsigned int form = form_ancestor(node);
  13296. char action[BR_URL_MAX], query[2048];
  13297. unsigned int qn = 0, i;
  13298. int first = 1, is_post = 0;
  13299. const char *a, *method;
  13300. if (!form)
  13301. return 0;
  13302. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  13303. return 0;
  13304. method = br_find_attr(&doc, form, "method");
  13305. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  13306. is_post = 1;
  13307. a = br_find_attr(&doc, form, "action");
  13308. if (a && a[0]) {
  13309. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  13310. return 0;
  13311. } else {
  13312. s_copy(action, page_url, sizeof(action));
  13313. }
  13314. query[0] = '\0';
  13315. for (i = 0; i < doc.nnode; i++) {
  13316. struct br_node *nd = &doc.nodes[i];
  13317. struct form_state *fs;
  13318. const char *name;
  13319. const char *value = "";
  13320. if (nd->type != BR_NODE_ELEM || i == form ||
  13321. !form_descendant(i, form))
  13322. continue;
  13323. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  13324. nd->tag != BR_TAG_SELECT)
  13325. continue;
  13326. if (form_disabled(i))
  13327. continue;
  13328. name = br_find_attr(&doc, i, "name");
  13329. if (!name || !name[0])
  13330. continue;
  13331. fs = form_get(i, 1);
  13332. if (!fs)
  13333. continue;
  13334. if (nd->tag == BR_TAG_SELECT) {
  13335. char opt[64];
  13336. if (!form_option_text(i, fs->selected, opt,
  13337. sizeof(opt)))
  13338. s_copy(opt, "", sizeof(opt));
  13339. value = opt;
  13340. {
  13341. unsigned int c, oi = 0;
  13342. for (c = nd->first; c;
  13343. c = doc.nodes[c].next) {
  13344. if (doc.nodes[c].type != BR_NODE_ELEM ||
  13345. doc.nodes[c].tag != BR_TAG_OPTION)
  13346. continue;
  13347. if (oi == fs->selected) {
  13348. const char *v =
  13349. br_value(&doc, c);
  13350. if (v && v[0])
  13351. value = v;
  13352. break;
  13353. }
  13354. oi++;
  13355. }
  13356. }
  13357. } else if (nd->tag == BR_TAG_INPUT) {
  13358. int kind = form_kind_of(i);
  13359. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  13360. if (!fs->checked)
  13361. continue;
  13362. value = br_value(&doc, i);
  13363. if (!value || !value[0])
  13364. value = "on";
  13365. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  13366. kind == FORM_BUTTON) {
  13367. if (i != node)
  13368. continue;
  13369. value = fs->value;
  13370. } else {
  13371. value = fs->value;
  13372. }
  13373. } else {
  13374. value = fs->value;
  13375. }
  13376. form_add_param(query, &qn, sizeof(query), name, value, &first);
  13377. }
  13378. if (is_post) {
  13379. if (action[0] == '/') {
  13380. set_status("POST forms need an HTTP action URL", 1, 4000);
  13381. ngui_invalidate(&ui);
  13382. return 0;
  13383. }
  13384. if (qn >= sizeof(pending_post))
  13385. qn = sizeof(pending_post) - 1;
  13386. if (qn)
  13387. memcpy(pending_post, query, qn);
  13388. pending_post[qn] = '\0';
  13389. pending_post_len = qn;
  13390. pending_post_is = 1;
  13391. } else {
  13392. pending_post_len = 0;
  13393. pending_post_is = 0;
  13394. if (qn) {
  13395. unsigned int an = s_len(action);
  13396. if (an + qn + 2 < sizeof(action)) {
  13397. action[an++] = strchr(action, '?') ? '&' : '?';
  13398. action[an] = '\0';
  13399. s_copy(action + an, query,
  13400. sizeof(action) - an);
  13401. }
  13402. }
  13403. }
  13404. s_copy(pending_url, action, sizeof(pending_url));
  13405. pending_action |= ACT_NAV;
  13406. cancel_fetch = 1;
  13407. ngui_invalidate(&ui);
  13408. return 1;
  13409. }
  13410. static void form_reset_event(unsigned int form)
  13411. {
  13412. if (form && !js_browser_event(form, "reset", 1, 1))
  13413. return;
  13414. if (form)
  13415. form_reset_form(form);
  13416. else
  13417. form_reset_state();
  13418. form_dirty = 0;
  13419. layout_valid = 0;
  13420. ngui_invalidate(&ui);
  13421. }
  13422. static void form_blur(void)
  13423. {
  13424. unsigned int node = form_focus;
  13425. form_focus = 0;
  13426. if (node && form_dirty) {
  13427. form_dirty = 0;
  13428. js_browser_event(node, "change", 1, 0);
  13429. }
  13430. }
  13431. static void form_click(unsigned int node)
  13432. {
  13433. struct form_state *fs;
  13434. int kind, changed = 0;
  13435. if (!form_is_control(node) || form_disabled(node))
  13436. return;
  13437. if (form_focus != node)
  13438. form_blur();
  13439. fs = form_get(node, 1);
  13440. if (!fs)
  13441. return;
  13442. kind = form_kind_of(node);
  13443. /* Focus moves on the press, before `click` is dispatched: a page
  13444. * that cancels the click (a framework's root listener) suppresses
  13445. * the activation behaviour below, never the focus (as in other
  13446. * browsers, where focus follows mousedown). */
  13447. form_focus = node;
  13448. form_dirty = 0;
  13449. if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  13450. kind == FORM_TEXTAREA)
  13451. fs->caret = fs->len;
  13452. layout_valid = 0;
  13453. ngui_invalidate(&ui);
  13454. if (!js_browser_event(node, "click", 1, 1))
  13455. return;
  13456. fs = form_get(node, 0); /* the handler may have changed the DOM */
  13457. if (!fs)
  13458. return;
  13459. if (kind == FORM_CHECKBOX) {
  13460. fs->checked = !fs->checked;
  13461. changed = 1;
  13462. } else if (kind == FORM_RADIO) {
  13463. const char *name = br_find_attr(&doc, node, "name");
  13464. unsigned int i;
  13465. fs->checked = 1;
  13466. changed = 1;
  13467. if (name) {
  13468. for (i = 0; i < FORM_MAX; i++) {
  13469. struct form_state *o = &form_states[i];
  13470. if (!o->used || o->node == node)
  13471. continue;
  13472. if (form_kind_of(o->node) == FORM_RADIO) {
  13473. const char *on = br_find_attr(&doc,
  13474. o->node,
  13475. "name");
  13476. if (on && s_eq(on, name))
  13477. o->checked = 0;
  13478. }
  13479. }
  13480. }
  13481. } else if (kind == FORM_SELECT) {
  13482. unsigned int n = form_option_count(node);
  13483. if (n) {
  13484. fs->selected = (unsigned char)
  13485. ((fs->selected + 1) % n);
  13486. changed = 1;
  13487. }
  13488. } else if (kind == FORM_SUBMIT) {
  13489. form_submit_form(node, 1);
  13490. return;
  13491. } else if (kind == FORM_RESET) {
  13492. form_reset_event(form_ancestor(node));
  13493. return;
  13494. }
  13495. if (changed) {
  13496. js_browser_event(node, "input", 1, 0);
  13497. js_browser_event(node, "change", 1, 0);
  13498. }
  13499. layout_valid = 0;
  13500. ngui_invalidate(&ui);
  13501. }
  13502. static void form_focus_next(void)
  13503. {
  13504. unsigned int start = form_focus ? form_focus + 1 : 0;
  13505. unsigned int i;
  13506. form_blur();
  13507. for (i = start; i < doc.nnode; i++) {
  13508. if (form_is_control(i) && !form_disabled(i) &&
  13509. !s_eq(br_type(&doc, i), "hidden")) {
  13510. form_focus = i;
  13511. layout_valid = 0;
  13512. ngui_invalidate(&ui);
  13513. return;
  13514. }
  13515. }
  13516. form_focus = 0;
  13517. layout_valid = 0;
  13518. ngui_invalidate(&ui);
  13519. }
  13520. static void form_key(int k)
  13521. {
  13522. struct form_state *fs;
  13523. int kind;
  13524. if (!form_focus || form_focus >= doc.nnode) {
  13525. form_focus = 0;
  13526. return;
  13527. }
  13528. fs = form_get(form_focus, 1);
  13529. if (!fs || form_disabled(form_focus))
  13530. return;
  13531. kind = form_kind_of(form_focus);
  13532. if (kind == FORM_SELECT) {
  13533. unsigned int n = form_option_count(form_focus);
  13534. int changed = 0;
  13535. if (k == NGUI_KEY_UP && n) {
  13536. fs->selected = (unsigned char)
  13537. ((fs->selected + n - 1) % n);
  13538. changed = 1;
  13539. } else if (k == NGUI_KEY_DOWN && n) {
  13540. fs->selected = (unsigned char)
  13541. ((fs->selected + 1) % n);
  13542. changed = 1;
  13543. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  13544. form_blur();
  13545. layout_valid = 0;
  13546. ngui_invalidate(&ui);
  13547. return;
  13548. } else {
  13549. return;
  13550. }
  13551. if (changed) {
  13552. js_browser_event(form_focus, "input", 1, 0);
  13553. js_browser_event(form_focus, "change", 1, 0);
  13554. }
  13555. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  13556. if (k == ' ') {
  13557. form_click(form_focus);
  13558. return;
  13559. }
  13560. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  13561. form_blur();
  13562. layout_valid = 0;
  13563. ngui_invalidate(&ui);
  13564. }
  13565. return;
  13566. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  13567. kind == FORM_RESET) {
  13568. if (k == NGUI_KEY_ESC) {
  13569. form_blur();
  13570. layout_valid = 0;
  13571. ngui_invalidate(&ui);
  13572. } else if (k == '\r' || k == '\n' || k == ' ') {
  13573. form_click(form_focus);
  13574. }
  13575. return;
  13576. } else if (k == NGUI_KEY_TAB) {
  13577. form_focus_next();
  13578. return;
  13579. } else if (k == NGUI_KEY_ESC) {
  13580. form_blur();
  13581. layout_valid = 0;
  13582. ngui_invalidate(&ui);
  13583. return;
  13584. } else if (k == '\r' || k == '\n') {
  13585. unsigned int node = form_focus;
  13586. form_blur();
  13587. if (form_ancestor(node))
  13588. form_submit_form(node, 1);
  13589. layout_valid = 0;
  13590. ngui_invalidate(&ui);
  13591. return;
  13592. } else if (k == NGUI_KEY_BACKSPACE) {
  13593. if (fs->caret) {
  13594. unsigned int i = --fs->caret;
  13595. for (; i < fs->len; i++)
  13596. fs->value[i] = fs->value[i + 1];
  13597. if (fs->len)
  13598. fs->len--;
  13599. form_dirty = 1;
  13600. js_browser_event(form_focus, "input", 1, 0);
  13601. }
  13602. } else if (k == NGUI_KEY_DELETE) {
  13603. if (fs->caret < fs->len) {
  13604. unsigned int i;
  13605. for (i = fs->caret; i < fs->len; i++)
  13606. fs->value[i] = fs->value[i + 1];
  13607. fs->len--;
  13608. form_dirty = 1;
  13609. js_browser_event(form_focus, "input", 1, 0);
  13610. }
  13611. } else if (k == NGUI_KEY_LEFT) {
  13612. if (fs->caret)
  13613. fs->caret--;
  13614. } else if (k == NGUI_KEY_RIGHT) {
  13615. if (fs->caret < fs->len)
  13616. fs->caret++;
  13617. } else if (k == NGUI_KEY_HOME) {
  13618. fs->caret = 0;
  13619. } else if (k == NGUI_KEY_END) {
  13620. fs->caret = fs->len;
  13621. } else if (k >= 32 && k < 127) {
  13622. if (fs->len < FORM_VALUE_MAX) {
  13623. unsigned int i;
  13624. for (i = fs->len; i > fs->caret; i--)
  13625. fs->value[i] = fs->value[i - 1];
  13626. fs->value[fs->caret++] = (char)k;
  13627. fs->len++;
  13628. form_dirty = 1;
  13629. js_browser_event(form_focus, "input", 1, 0);
  13630. }
  13631. } else {
  13632. return;
  13633. }
  13634. fs->value[fs->len] = '\0';
  13635. layout_valid = 0;
  13636. ngui_invalidate(&ui);
  13637. }
  13638. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  13639. * a same-document navigation: update the URL and fire hashchange. Returns
  13640. * 1 when handled. */
  13641. static int link_fragment_nav(unsigned int node)
  13642. {
  13643. const char *href = br_href(&doc, node);
  13644. char url[BR_URL_MAX];
  13645. unsigned int n = 0;
  13646. if (!href || !href[0] || !js_browser_active())
  13647. return 0;
  13648. if (href[0] == '#') {
  13649. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  13650. url[n] = page_url[n];
  13651. n++;
  13652. }
  13653. url[n] = '\0';
  13654. s_append(url, &n, href, sizeof(url));
  13655. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  13656. return 0;
  13657. }
  13658. if (!same_doc_fragment(url))
  13659. return href[0] == '#';
  13660. page_set_fragment(url, 1);
  13661. js_browser_hashchange();
  13662. return 1;
  13663. }
  13664. /* A positioned box laid out while transparent or visibility:hidden (or
  13665. * inside one): it has a box for scripts but must not catch the pointer. */
  13666. static int node_invisible(unsigned int n)
  13667. {
  13668. unsigned int guard = 0;
  13669. while (n < doc.nnode && guard++ < 64) {
  13670. struct br_style st;
  13671. style_for_node(n, &st);
  13672. if (st.opacity_hidden || st.vis_hidden)
  13673. return 1;
  13674. if (n == 0)
  13675. break;
  13676. n = doc.nodes[n].parent;
  13677. }
  13678. return 0;
  13679. }
  13680. /* The innermost laid-out box under a screen point: the smallest valid box
  13681. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  13682. * Used to deliver clicks to elements that are neither links nor controls
  13683. * (a Vue <div role="button">, a card with a click listener). */
  13684. static unsigned int find_box_hit(int x, int y)
  13685. {
  13686. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  13687. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  13688. const struct br_layout_box *b = &layout_boxes[i];
  13689. unsigned int area;
  13690. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  13691. x < b->x || y < b->y || x >= b->x + b->w ||
  13692. y >= b->y + b->h)
  13693. continue;
  13694. area = (unsigned int)b->w * (unsigned int)b->h;
  13695. if (area <= best_area && !node_invisible(i)) {
  13696. best = i;
  13697. best_area = area;
  13698. }
  13699. }
  13700. return best;
  13701. }
  13702. /* ---- page context menu ------------------------------------------------ */
  13703. static void ctx_add(unsigned int action, const char *label, const char *url)
  13704. {
  13705. int i;
  13706. if (ctx_n >= CTX_MAX || !url || !url[0])
  13707. return;
  13708. for (i = 0; i < ctx_n; i++)
  13709. if (ctx_action[i] == action && s_eq(ctx_url[i], url))
  13710. return;
  13711. s_copy(ctx_label[ctx_n], label, sizeof(ctx_label[0]));
  13712. s_copy(ctx_url[ctx_n], url, sizeof(ctx_url[0]));
  13713. ctx_action[ctx_n] = action;
  13714. ctx_n++;
  13715. }
  13716. static unsigned int ctx_ancestor_tag(unsigned int node, unsigned char tag)
  13717. {
  13718. unsigned int guard = 0;
  13719. while (node && node < doc.nnode && guard++ < BR_MAX_NODES) {
  13720. if (doc.nodes[node].type == BR_NODE_ELEM &&
  13721. doc.nodes[node].tag == tag)
  13722. return node;
  13723. node = doc.nodes[node].parent;
  13724. }
  13725. return 0;
  13726. }
  13727. static void ctx_open_at(struct ngui_rect page, int x, int y)
  13728. {
  13729. unsigned int hit = (unsigned int)find_hit(x, y);
  13730. unsigned int box = find_box_hit(x, y);
  13731. unsigned int img = 0;
  13732. char resolved[BR_URL_MAX];
  13733. const char *href;
  13734. ctx_open = 0;
  13735. ctx_n = 0;
  13736. if (box && doc.nodes[box].tag == BR_TAG_IMG)
  13737. img = box;
  13738. else if (hit && doc.nodes[hit].tag == BR_TAG_IMG)
  13739. img = hit;
  13740. else if (hit)
  13741. img = ctx_ancestor_tag(hit, BR_TAG_IMG);
  13742. if (!img && box)
  13743. img = ctx_ancestor_tag(box, BR_TAG_IMG);
  13744. if (img && br_src(&doc, img) &&
  13745. resolve_link(page_url, br_src(&doc, img), resolved,
  13746. sizeof(resolved)) == 0)
  13747. ctx_add(CTX_SAVE_IMAGE, "Save image", resolved);
  13748. /* A CSS background image is an image too; check the element under
  13749. * the pointer and then its ancestors (a card's image behind text). */
  13750. if (!img) {
  13751. unsigned int n = box ? box : hit, guard = 0;
  13752. while (n && n < doc.nnode && guard++ < BR_MAX_NODES) {
  13753. struct br_style st;
  13754. style_for_node(n, &st);
  13755. if (st.bg_image > 0) {
  13756. const char *bg = br_bg_image_url(st.bg_image - 1);
  13757. if (bg && resolve_link(page_url, bg, resolved,
  13758. sizeof(resolved)) == 0)
  13759. ctx_add(CTX_SAVE_IMAGE, "Save image",
  13760. resolved);
  13761. break;
  13762. }
  13763. n = doc.nodes[n].parent;
  13764. }
  13765. }
  13766. href = hit ? br_href(&doc, hit) : 0;
  13767. if (!href && box)
  13768. href = br_href(&doc, box);
  13769. if (href && resolve_link(page_url, href, resolved,
  13770. sizeof(resolved)) == 0)
  13771. ctx_add(CTX_SAVE_LINK, "Save link", resolved);
  13772. if (page_url[0] && !starts_with(page_url, "about:"))
  13773. ctx_add(CTX_SAVE_PAGE, "Save page", page_url);
  13774. if (!ctx_n)
  13775. return;
  13776. ctx_w = 190;
  13777. ctx_h = ctx_n * CTX_ROW_H + 2;
  13778. ctx_x = x;
  13779. ctx_y = y;
  13780. if (ctx_x + ctx_w > page.x + page.w - 4)
  13781. ctx_x = page.x + page.w - 4 - ctx_w;
  13782. if (ctx_y + ctx_h > page.y + page.h - 4)
  13783. ctx_y = page.y + page.h - 4 - ctx_h;
  13784. if (ctx_x < page.x + 4)
  13785. ctx_x = page.x + 4;
  13786. if (ctx_y < page.y + 4)
  13787. ctx_y = page.y + 4;
  13788. ctx_open = 1;
  13789. ngui_invalidate(&ui);
  13790. }
  13791. static void ctx_close(void)
  13792. {
  13793. if (!ctx_open)
  13794. return;
  13795. ctx_open = 0;
  13796. ngui_invalidate(&ui);
  13797. }
  13798. static void ctx_open_from_right(struct ngui_rect page)
  13799. {
  13800. if (!ui.right_pressed)
  13801. return;
  13802. if (ngui_rect_contains(&page, ui.right_press_x, ui.right_press_y)) {
  13803. dl_panel_open = 0;
  13804. ngui_set_focus(&ui, 0);
  13805. sug_close();
  13806. ctx_open_at(page, ui.right_press_x, ui.right_press_y);
  13807. } else {
  13808. ctx_close();
  13809. }
  13810. }
  13811. static void ctx_press(struct ngui_rect page)
  13812. {
  13813. struct ngui_rect r;
  13814. int row;
  13815. if (!ctx_open || !ui.pressed)
  13816. return;
  13817. r = (struct ngui_rect){ctx_x, ctx_y, ctx_w, ctx_h};
  13818. if (ngui_rect_contains(&r, ui.press_x, ui.press_y)) {
  13819. row = -1;
  13820. if (ui.press_y > ctx_y &&
  13821. ui.press_y < ctx_y + 1 + ctx_n * CTX_ROW_H)
  13822. row = (ui.press_y - ctx_y - 1) / CTX_ROW_H;
  13823. if (row >= 0 && row < ctx_n)
  13824. dl_queue(ctx_url[row]);
  13825. ctx_close();
  13826. ui.pressed = ui.released = 0;
  13827. return;
  13828. }
  13829. if (ngui_rect_contains(&page, ui.press_x, ui.press_y)) {
  13830. ctx_close();
  13831. ui.pressed = ui.released = 0;
  13832. return;
  13833. }
  13834. ctx_close();
  13835. }
  13836. static void draw_context(void)
  13837. {
  13838. struct ngui_rect r;
  13839. int i, hover = -1;
  13840. if (!ctx_open)
  13841. return;
  13842. r = (struct ngui_rect){ctx_x, ctx_y, ctx_w, ctx_h};
  13843. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  13844. if (ui.mouse_y > ctx_y &&
  13845. ui.mouse_y < ctx_y + 1 + ctx_n * CTX_ROW_H)
  13846. hover = (ui.mouse_y - ctx_y - 1) / CTX_ROW_H;
  13847. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  13848. }
  13849. ngui_fill_rect(&ui, r, ui.theme.border);
  13850. for (i = 0; i < ctx_n; i++) {
  13851. struct ngui_rect rr = {ctx_x + 1,
  13852. ctx_y + 1 + i * CTX_ROW_H, ctx_w - 2, CTX_ROW_H};
  13853. ngui_fill_rect(&ui, rr, i == hover ? ui.theme.selection :
  13854. ui.theme.panel);
  13855. ngui_text(&ui, rr.x + 10,
  13856. rr.y + (rr.h - ngui_text_line_height(&ui,
  13857. ui.font_px, 0)) / 2,
  13858. ctx_label[i], ui.theme.text);
  13859. }
  13860. }
  13861. /* The element under the pointer for hover events: the innermost laid-out
  13862. * box, or the link/control hit inside it (an inline <a> has no box of its
  13863. * own but a hit rectangle). -1 when none. */
  13864. static int hover_node = -1;
  13865. static int node_contains(unsigned int a, unsigned int n)
  13866. {
  13867. unsigned int guard = 0;
  13868. while (n < doc.nnode && guard++ < BR_MAX_NODES) {
  13869. if (n == a)
  13870. return 1;
  13871. if (n == 0)
  13872. return 0;
  13873. n = doc.nodes[n].parent;
  13874. }
  13875. return 0;
  13876. }
  13877. static int hover_target(void)
  13878. {
  13879. int h, x = ui.mouse_x, y = ui.mouse_y;
  13880. unsigned int b;
  13881. if (!ui.inside || ui.buttons || sug_visible() || ctx_open ||
  13882. dl_panel_open ||
  13883. x < page_rect.x || x >= page_rect.x + page_rect.w - 12 ||
  13884. y < page_rect.y || y >= page_rect.y + page_rect.h)
  13885. return -1;
  13886. h = find_hit(x, y);
  13887. b = find_box_hit(x, y);
  13888. if (h && (!b || node_contains(b, (unsigned int)h)))
  13889. return h;
  13890. if (b)
  13891. return (int)b;
  13892. return h ? h : -1;
  13893. }
  13894. /* mouseover/mouseout (bubbling, with relatedTarget) at the old and new
  13895. * element, and mouseleave/mouseenter on every ancestor that was left or
  13896. * entered (outermost first for enter), like a browser's boundary events.
  13897. * jQuery 1.11 builds its mouseenter (Bootstrap tooltips) from mouseover
  13898. * and relatedTarget. */
  13899. static void page_hover_events(void)
  13900. {
  13901. int now, old, cx, cy, path[64], np = 0, i;
  13902. unsigned int n;
  13903. if (!js_browser_active()) {
  13904. hover_node = -1;
  13905. return;
  13906. }
  13907. now = hover_target();
  13908. if (now >= (int)doc.nnode)
  13909. now = -1;
  13910. if (now == hover_node)
  13911. return;
  13912. old = hover_node;
  13913. if (old >= (int)doc.nnode)
  13914. old = -1;
  13915. hover_node = now;
  13916. cx = ui.mouse_x - page_rect.x;
  13917. cy = ui.mouse_y - page_rect.y;
  13918. if (old >= 0) {
  13919. js_browser_mouse_event((unsigned int)old, "mouseout", 1, now,
  13920. cx, cy);
  13921. for (n = (unsigned int)old, i = 0;
  13922. n < doc.nnode && i < 64 &&
  13923. !(now >= 0 && node_contains(n, (unsigned int)now)); i++) {
  13924. js_browser_mouse_event(n, "mouseleave", 0, now, cx, cy);
  13925. if (n == 0)
  13926. break;
  13927. n = doc.nodes[n].parent;
  13928. }
  13929. }
  13930. if (now < 0 || now >= (int)doc.nnode)
  13931. return;
  13932. js_browser_mouse_event((unsigned int)now, "mouseover", 1, old, cx, cy);
  13933. for (n = (unsigned int)now;
  13934. n < doc.nnode && np < 64 &&
  13935. !(old >= 0 && node_contains(n, (unsigned int)old));) {
  13936. path[np++] = (int)n;
  13937. if (n == 0)
  13938. break;
  13939. n = doc.nodes[n].parent;
  13940. }
  13941. for (i = np - 1; i >= 0; i--)
  13942. js_browser_mouse_event((unsigned int)path[i], "mouseenter", 0,
  13943. old, cx, cy);
  13944. }
  13945. static void handle_page_click(unsigned int *action)
  13946. {
  13947. int node;
  13948. char url[BR_URL_MAX];
  13949. if (!ui.pressed)
  13950. return;
  13951. if (ui.press_x < page_rect.x ||
  13952. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  13953. ui.press_y < page_rect.y ||
  13954. ui.press_y >= page_rect.y + page_rect.h)
  13955. return;
  13956. node = find_hit(ui.press_x, ui.press_y);
  13957. if (!node) {
  13958. unsigned int box;
  13959. if (!js_browser_active())
  13960. return;
  13961. box = find_box_hit(ui.press_x, ui.press_y);
  13962. if (box) {
  13963. form_blur();
  13964. js_browser_event(box, "click", 1, 1);
  13965. }
  13966. return;
  13967. }
  13968. if (form_is_control((unsigned int)node)) {
  13969. form_click((unsigned int)node);
  13970. return;
  13971. }
  13972. form_blur();
  13973. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  13974. return;
  13975. if (link_fragment_nav((unsigned int)node))
  13976. return;
  13977. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  13978. sizeof(url)) != 0)
  13979. return;
  13980. s_copy(click_url, url, sizeof(click_url));
  13981. *action |= ACT_NAV;
  13982. }
  13983. void _start(const char *arg)
  13984. {
  13985. struct win_info wi;
  13986. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  13987. u_win_create(960, 640, "Browser", &wi) != 0 &&
  13988. u_win_create(780, 540, "Browser", &wi) != 0) {
  13989. u_puts("browser: no graphics window\n");
  13990. u_exit(1);
  13991. }
  13992. ufont_set_arena_bytes(BR_FONT_ARENA);
  13993. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  13994. url_in.placeholder = "http://...";
  13995. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  13996. ui.theme.accent);
  13997. br_set_viewport(wi.width);
  13998. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  13999. s_copy(cwd, "/", sizeof(cwd));
  14000. heap_clear();
  14001. origin_cache_load();
  14002. css_cache_init();
  14003. script_cache_init();
  14004. font_cache_init();
  14005. persist_restore();
  14006. hist_load();
  14007. dl_load();
  14008. page_scroll.offset = 0;
  14009. page_scroll.content_h = 0;
  14010. if (arg && arg[0]) {
  14011. navigate(arg, 1);
  14012. } else {
  14013. load_home(1);
  14014. /* Start ready to type: keep the home page, but leave the address
  14015. * bar empty instead of showing "about:home". */
  14016. ngui_input_set(&url_in, "");
  14017. ngui_set_focus(&ui, ID_URL);
  14018. }
  14019. for (;;) {
  14020. unsigned int action = 0;
  14021. unsigned int now;
  14022. click_url[0] = '\0';
  14023. if (pending_action) {
  14024. action |= pending_action & ACT_WAIT_NAV;
  14025. if (pending_url[0])
  14026. s_copy(click_url, pending_url, sizeof(click_url));
  14027. pending_action = 0;
  14028. pending_url[0] = '\0';
  14029. cancel_fetch = 0;
  14030. } else if (preload_active) {
  14031. if (preload_wait)
  14032. preload_wait = 0;
  14033. else
  14034. preload_step();
  14035. } else if ((preload_pending &&
  14036. page_scroll.offset != preload_scroll) ||
  14037. (preload_rescan && layout_valid)) {
  14038. preload_scroll = page_scroll.offset;
  14039. preload_rescan = 0;
  14040. preload_pending = 0;
  14041. preload_node = 0;
  14042. preload_active = 1;
  14043. }
  14044. js_browser_tick();
  14045. if (resize_pending && !pending_action) {
  14046. resize_pending = 0;
  14047. resize_sent_w = layout_right - layout_left;
  14048. js_browser_window_event("resize");
  14049. }
  14050. persist_tick();
  14051. dl_poll();
  14052. if (pending_action)
  14053. continue;
  14054. now = u_ticks_ms();
  14055. if (status_until && (int)(now - status_until) >= 0) {
  14056. status_text[0] = '\0';
  14057. status_until = 0;
  14058. status_error = 0;
  14059. ngui_invalidate(&ui);
  14060. }
  14061. if (!ngui_begin(&ui)) {
  14062. /* A queued navigation (e.g. Enter in the URL bar during
  14063. * a slow fetch) must be handled even when this frame
  14064. * needs no redraw. */
  14065. if (!action) {
  14066. fetch_workers_stop_if_unfocused();
  14067. u_sleep_ms(10);
  14068. continue;
  14069. }
  14070. } else {
  14071. draw(&action);
  14072. handle_keys(&action);
  14073. handle_page_click(&action);
  14074. page_hover_events();
  14075. ngui_end(&ui);
  14076. }
  14077. if (action & ACT_NAV) {
  14078. if (click_url[0]) {
  14079. navigate(click_url, 1);
  14080. click_url[0] = '\0';
  14081. } else {
  14082. navigate(url_in.text, 1);
  14083. }
  14084. }
  14085. if (action & ACT_BACK) {
  14086. if (hist_pos > 0) {
  14087. hist_pos--;
  14088. if (same_doc_fragment(history[hist_pos])) {
  14089. page_set_fragment(history[hist_pos], 0);
  14090. js_browser_hashchange();
  14091. } else {
  14092. navigate(history[hist_pos], 0);
  14093. }
  14094. }
  14095. }
  14096. if (action & ACT_FORWARD) {
  14097. if (hist_pos + 1 < hist_len) {
  14098. hist_pos++;
  14099. if (same_doc_fragment(history[hist_pos])) {
  14100. page_set_fragment(history[hist_pos], 0);
  14101. js_browser_hashchange();
  14102. } else {
  14103. navigate(history[hist_pos], 0);
  14104. }
  14105. }
  14106. }
  14107. if (action & ACT_RELOAD) {
  14108. if (s_eq(page_url, "about:home"))
  14109. load_home(0);
  14110. else
  14111. navigate(page_url, 0);
  14112. }
  14113. if (action & ACT_HOME)
  14114. load_home(1);
  14115. if (action & ACT_CLOSE)
  14116. quit = 1;
  14117. if (quit)
  14118. break;
  14119. if (pending_action)
  14120. continue;
  14121. fetch_workers_stop_if_unfocused();
  14122. u_sleep_ms(10);
  14123. }
  14124. fetch_workers_stop_all();
  14125. fetch_worker_stop(&dl_worker);
  14126. u_win_close();
  14127. u_exit(0);
  14128. }